Salt40404 commited on
Commit
23af0ed
·
verified ·
1 Parent(s): d6b4525

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -107
app.py CHANGED
@@ -1,128 +1,100 @@
1
- import os, json, uuid
2
- import gradio as gr
3
  from huggingface_hub import InferenceClient
4
 
5
- def get_user_file(user_id):
6
- return f"bitai_user_{user_id}.json"
7
 
8
- def load_saved_chats(user_id):
9
- path = get_user_file(user_id)
10
- if os.path.exists(path):
11
- with open(path, "r", encoding="utf-8") as f:
 
 
 
 
 
 
 
12
  return json.load(f)
13
  return []
14
 
15
- def save_chats(user_id, chats):
16
- path = get_user_file(user_id)
17
- with open(path, "w", encoding="utf-8") as f:
18
- json.dump(chats, f, ensure_ascii=False, indent=2)
19
 
20
- def respond(message, history, saved_chats, user_id):
21
- client = InferenceClient(token=os.environ["HF_TOKEN"], model="openai/gpt-oss-20b")
 
 
 
 
 
22
 
23
- system = {
24
- "role": "system",
25
- "content": "You are BitAI (V1), a friendly chatbot created by Sal."
26
- }
 
 
 
 
27
 
28
- messages = [system] + history + [{"role": "user", "content": message}]
29
  response = ""
30
- for msg in client.chat_completion(messages, max_tokens=2048, stream=True):
31
- token = msg.choices[0].delta.content if msg.choices and msg.choices[0].delta else ""
 
 
 
32
  response += token
33
- yield response
34
 
35
- # Salva automático
36
- history.append({"role": "user", "content": message})
37
  history.append({"role": "assistant", "content": response})
38
- saved_chats[-1] = history
39
- save_chats(user_id, saved_chats)
40
-
41
- def new_chat(saved_chats, user_id):
42
- saved_chats.append([])
43
- save_chats(user_id, saved_chats)
44
- return saved_chats, len(saved_chats) - 1, []
45
-
46
- def select_chat(index, saved_chats):
47
- if 0 <= index < len(saved_chats):
48
- return saved_chats[index], f"Chat {index+1} carregado!"
49
- return [], "Índice inválido."
50
-
51
- def start_session(username):
52
- user_id = username.strip().replace(" ", "_") if username else str(uuid.uuid4())[:8]
53
- chats = load_saved_chats(user_id)
54
- if not chats:
55
- chats = [[]]
56
- save_chats(user_id, chats)
57
- return user_id, chats, len(chats) - 1
58
-
59
- def render_sidebar(saved_chats):
60
- html = "<div class='chatlist'>"
61
- for i, chat in enumerate(saved_chats):
62
- preview = ""
63
- for m in chat:
64
- if m["role"] == "user":
65
- preview = m["content"][:35] + ("..." if len(m["content"]) > 35 else "")
66
- break
67
- html += f"""
68
- <div class='chat-item' onclick="selectChat({i})">
69
- <div class='chat-title'>💬 Chat {i+1}</div>
70
- <div class='chat-preview'>{preview or 'Conversa vazia'}</div>
71
- </div>
72
- """
73
- html += "</div>"
74
- return html
75
-
76
- with gr.Blocks(css="""
77
- /* Sidebar com vibes modernas */
78
- body, .gr-blocks {
79
- background-color: #1a1a1a !important;
80
- color: white;
81
- }
82
  .sidebar {
83
- background-color: #111;
84
- padding: 10px;
85
- border-right: 2px solid #333;
86
- height: 100vh;
87
- overflow-y: auto;
 
 
88
  }
89
- .chatlist { display: flex; flex-direction: column; gap: 8px; }
90
- .chat-item {
91
- background: #222;
92
- border-radius: 10px;
93
- padding: 10px;
94
- cursor: pointer;
95
- transition: all 0.2s ease;
 
 
 
 
 
96
  }
97
- .chat-item:hover { background: #333; transform: scale(1.02); }
98
- .chat-title { font-weight: bold; color: #fff; }
99
- .chat-preview { font-size: 13px; color: #bbb; margin-top: 2px; }
100
- """) as demo:
101
-
102
- user_id = gr.State("")
103
- saved_chats = gr.State([])
104
- current_index = gr.State(0)
105
 
106
  with gr.Row():
107
- with gr.Column(scale=0.3, elem_classes="sidebar"):
108
- sidebar_html = gr.HTML("<div class='chatlist'></div>")
 
109
  new_chat_btn = gr.Button("➕ Novo Chat")
 
 
 
 
 
110
 
111
- with gr.Column(scale=1):
112
- gr.HTML("<h2 style='text-align:center;'>BitAI</h2>")
113
- chatbot = gr.ChatInterface(fn=respond, type="messages", additional_inputs=[saved_chats, user_id])
114
- status = gr.Textbox(label="Status", interactive=False)
115
-
116
- username_input = gr.Textbox(label="Seu nome (opcional):")
117
- start_btn = gr.Button("Iniciar Chat")
118
-
119
- start_btn.click(start_session, username_input, [user_id, saved_chats, current_index]).then(
120
- render_sidebar, saved_chats, sidebar_html
121
- )
122
-
123
- new_chat_btn.click(new_chat, [saved_chats, user_id], [saved_chats, current_index, chatbot.chatbot]).then(
124
- render_sidebar, saved_chats, sidebar_html
125
- )
126
 
127
- if __name__ == "__main__":
128
- demo.launch()
 
1
+ import os, json, uuid, gradio as gr
 
2
  from huggingface_hub import InferenceClient
3
 
4
+ # Usa o modelo certo
5
+ client = InferenceClient("openai/gpt-oss-20b", token=os.getenv("HF_TOKEN"))
6
 
7
+ os.makedirs("bitai_data", exist_ok=True)
8
+
9
+ def get_user_file(username):
10
+ if not username:
11
+ username = str(uuid.uuid4())[:8]
12
+ return f"bitai_data/{username}.json"
13
+
14
+ def load_history(username):
15
+ file = get_user_file(username)
16
+ if os.path.exists(file):
17
+ with open(file, "r") as f:
18
  return json.load(f)
19
  return []
20
 
21
+ def save_history(username, history):
22
+ with open(get_user_file(username), "w") as f:
23
+ json.dump(history, f)
 
24
 
25
+ def list_chats():
26
+ files = os.listdir("bitai_data")
27
+ return [f.replace(".json", "") for f in files]
28
+
29
+ def respond(message, history, username):
30
+ history.append({"role": "user", "content": message})
31
+ save_history(username, history)
32
 
33
+ system_message = """
34
+ You are BitAI (V1), a friendly, curious, and talkative chatbot created by the user 'Sal'.
35
+ You can share opinions, answer casual questions, and chat about personal-style topics in a safe and friendly way.
36
+ Politely refuse only things that are truly harmful, illegal, or unsafe.
37
+ """
38
+
39
+ messages = [{"role": "system", "content": system_message}]
40
+ messages.extend(history)
41
 
 
42
  response = ""
43
+ for msg in client.chat_completion(messages, max_tokens=1024, stream=True):
44
+ choices = msg.choices
45
+ token = ""
46
+ if len(choices) and choices[0].delta.content:
47
+ token = choices[0].delta.content
48
  response += token
 
49
 
 
 
50
  history.append({"role": "assistant", "content": response})
51
+ save_history(username, history)
52
+ return history, history
53
+
54
+ def select_chat(username):
55
+ return load_history(username), username
56
+
57
+ with gr.Blocks(theme="soft", css="""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  .sidebar {
59
+ width: 220px;
60
+ background-color: #1f1f1f;
61
+ color: white;
62
+ height: 100%;
63
+ padding: 10px;
64
+ border-right: 2px solid #333;
65
+ overflow-y: auto;
66
  }
67
+ .chat-btn {
68
+ display: block;
69
+ width: 100%;
70
+ margin-bottom: 6px;
71
+ padding: 8px;
72
+ text-align: left;
73
+ background: #2c2c2c;
74
+ color: white;
75
+ border-radius: 6px;
76
+ border: none;
77
+ cursor: pointer;
78
+ transition: 0.2s;
79
  }
80
+ .chat-btn:hover {
81
+ background: #444;
82
+ }
83
+ """) as app:
 
 
 
 
84
 
85
  with gr.Row():
86
+ with gr.Column(elem_classes="sidebar"):
87
+ gr.Markdown("### 💬 Chats")
88
+ chat_list = gr.Dropdown(choices=list_chats(), label="Selecionar Chat", interactive=True)
89
  new_chat_btn = gr.Button("➕ Novo Chat")
90
+ with gr.Column(scale=3):
91
+ username = gr.Textbox(label="Usuário", placeholder="Digite seu nome (ou deixe vazio)")
92
+ chatbot = gr.Chatbot(label="GPT OSS 20B", height=500)
93
+ msg = gr.Textbox(placeholder="Mensagem...")
94
+ send = gr.Button("Enviar")
95
 
96
+ send.click(respond, [msg, chatbot, username], [chatbot, chatbot])
97
+ new_chat_btn.click(lambda: ([], ""), None, [chatbot, username])
98
+ chat_list.change(select_chat, [chat_list], [chatbot, username])
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ app.launch()