Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,7 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
from huggingface_hub import InferenceClient
|
| 4 |
-
import json
|
| 5 |
-
import uuid # gera IDs únicos
|
| 6 |
|
| 7 |
-
# Funções pra salvar/carregar o histórico do usuário
|
| 8 |
def get_user_file(user_id):
|
| 9 |
return f"bitai_user_{user_id}.json"
|
| 10 |
|
|
@@ -20,55 +17,38 @@ def save_chats(user_id, chats):
|
|
| 20 |
with open(path, "w", encoding="utf-8") as f:
|
| 21 |
json.dump(chats, f, ensure_ascii=False, indent=2)
|
| 22 |
|
| 23 |
-
|
| 24 |
-
def respond(message, history: list[dict[str, str]], saved_chats, user_id):
|
| 25 |
client = InferenceClient(token=os.environ["HF_TOKEN"], model="openai/gpt-oss-20b")
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
You
|
| 30 |
-
|
| 31 |
-
Politely refuse only things that are truly harmful, illegal, or unsafe.
|
| 32 |
-
If someone asks what you are, clarify politely that you are BitAI, an AI chatbot.
|
| 33 |
-
"""
|
| 34 |
-
|
| 35 |
-
messages = [{"role": "system", "content": system_message}]
|
| 36 |
-
messages.extend(history)
|
| 37 |
-
messages.append({"role": "user", "content": message})
|
| 38 |
|
|
|
|
| 39 |
response = ""
|
| 40 |
-
for msg in client.chat_completion(
|
| 41 |
-
messages,
|
| 42 |
-
max_tokens=2048,
|
| 43 |
-
stream=True,
|
| 44 |
-
temperature=0.7,
|
| 45 |
-
top_p=0.95,
|
| 46 |
-
):
|
| 47 |
token = msg.choices[0].delta.content if msg.choices and msg.choices[0].delta else ""
|
| 48 |
response += token
|
| 49 |
yield response
|
| 50 |
|
| 51 |
-
#
|
| 52 |
history.append({"role": "user", "content": message})
|
| 53 |
history.append({"role": "assistant", "content": response})
|
| 54 |
saved_chats[-1] = history
|
| 55 |
save_chats(user_id, saved_chats)
|
| 56 |
|
| 57 |
-
# Criar novo chat
|
| 58 |
def new_chat(saved_chats, user_id):
|
| 59 |
saved_chats.append([])
|
| 60 |
save_chats(user_id, saved_chats)
|
| 61 |
return saved_chats, len(saved_chats) - 1, []
|
| 62 |
|
| 63 |
-
# Selecionar chat existente
|
| 64 |
def select_chat(index, saved_chats):
|
| 65 |
if 0 <= index < len(saved_chats):
|
| 66 |
return saved_chats[index], f"Chat {index+1} carregado!"
|
| 67 |
return [], "Índice inválido."
|
| 68 |
|
| 69 |
-
# Inicialização do usuário
|
| 70 |
def start_session(username):
|
| 71 |
-
# gera ID fixo pro nome, ou aleatório se em branco
|
| 72 |
user_id = username.strip().replace(" ", "_") if username else str(uuid.uuid4())[:8]
|
| 73 |
chats = load_saved_chats(user_id)
|
| 74 |
if not chats:
|
|
@@ -76,8 +56,25 @@ def start_session(username):
|
|
| 76 |
save_chats(user_id, chats)
|
| 77 |
return user_id, chats, len(chats) - 1
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
with gr.Blocks(css="""
|
| 80 |
-
/* Sidebar
|
| 81 |
body, .gr-blocks {
|
| 82 |
background-color: #1a1a1a !important;
|
| 83 |
color: white;
|
|
@@ -89,36 +86,17 @@ body, .gr-blocks {
|
|
| 89 |
height: 100vh;
|
| 90 |
overflow-y: auto;
|
| 91 |
}
|
| 92 |
-
.
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
margin-bottom: 10px;
|
| 96 |
-
background-color: #222;
|
| 97 |
-
color: white;
|
| 98 |
border-radius: 10px;
|
| 99 |
padding: 10px;
|
| 100 |
-
text-align: left;
|
| 101 |
-
border: none;
|
| 102 |
cursor: pointer;
|
| 103 |
-
transition:
|
| 104 |
-
}
|
| 105 |
-
.sidebar button:hover {
|
| 106 |
-
background-color: #444;
|
| 107 |
-
}
|
| 108 |
-
.gr-chat-interface {
|
| 109 |
-
border-radius: 20px !important;
|
| 110 |
-
border: 2px solid #333 !important;
|
| 111 |
-
background-color: #1a1a1a !important;
|
| 112 |
-
}
|
| 113 |
-
textarea {
|
| 114 |
-
height: 40px !important;
|
| 115 |
-
border-radius: 20px !important;
|
| 116 |
-
border: 1px solid #444 !important;
|
| 117 |
-
padding: 8px !important;
|
| 118 |
-
background-color: #111;
|
| 119 |
-
color: white;
|
| 120 |
-
resize: none !important;
|
| 121 |
}
|
|
|
|
|
|
|
|
|
|
| 122 |
""") as demo:
|
| 123 |
|
| 124 |
user_id = gr.State("")
|
|
@@ -126,36 +104,25 @@ textarea {
|
|
| 126 |
current_index = gr.State(0)
|
| 127 |
|
| 128 |
with gr.Row():
|
| 129 |
-
with gr.Column(scale=0.3, elem_classes="sidebar")
|
| 130 |
-
gr.HTML("<
|
| 131 |
-
chat_list = gr.Column()
|
| 132 |
new_chat_btn = gr.Button("➕ Novo Chat")
|
| 133 |
|
| 134 |
with gr.Column(scale=1):
|
| 135 |
-
gr.HTML("<h2 style='text-align:center;
|
| 136 |
chatbot = gr.ChatInterface(fn=respond, type="messages", additional_inputs=[saved_chats, user_id])
|
| 137 |
status = gr.Textbox(label="Status", interactive=False)
|
| 138 |
|
| 139 |
username_input = gr.Textbox(label="Seu nome (opcional):")
|
| 140 |
start_btn = gr.Button("Iniciar Chat")
|
| 141 |
|
| 142 |
-
def update_chat_list(saved_chats):
|
| 143 |
-
return [gr.Button.update(value=f"Chat {i+1}") for i in range(len(saved_chats))]
|
| 144 |
-
|
| 145 |
-
# Inicia sessão
|
| 146 |
start_btn.click(start_session, username_input, [user_id, saved_chats, current_index]).then(
|
| 147 |
-
|
| 148 |
)
|
| 149 |
|
| 150 |
-
# Criar novo chat
|
| 151 |
new_chat_btn.click(new_chat, [saved_chats, user_id], [saved_chats, current_index, chatbot.chatbot]).then(
|
| 152 |
-
|
| 153 |
)
|
| 154 |
|
| 155 |
-
# Simula botões pros chats (20 máx)
|
| 156 |
-
for i in range(20):
|
| 157 |
-
btn = gr.Button(f"Chat {i+1}", visible=False)
|
| 158 |
-
btn.click(select_chat, [gr.State(i), saved_chats], [chatbot.chatbot, status])
|
| 159 |
-
|
| 160 |
if __name__ == "__main__":
|
| 161 |
demo.launch()
|
|
|
|
| 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 |
|
|
|
|
| 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:
|
|
|
|
| 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;
|
|
|
|
| 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("")
|
|
|
|
| 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()
|