Salt40404 commited on
Commit
e69bdf3
·
verified ·
1 Parent(s): 299222a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -59
app.py CHANGED
@@ -1,9 +1,24 @@
1
  import os
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  def respond(message, history: list[dict[str, str]], saved_chats):
6
- # Puxa o token do secret do Hugging Face
7
  client = InferenceClient(token=os.environ["HF_TOKEN"], model="openai/gpt-oss-20b")
8
 
9
  system_message = """
@@ -26,62 +41,70 @@ If someone asks what you are, clarify politely that you are BitAI, an AI chatbot
26
  temperature=0.7,
27
  top_p=0.95,
28
  ):
29
- choices = msg.choices
30
- token = ""
31
- if len(choices) and choices[0].delta.content:
32
- token = choices[0].delta.content
33
  response += token
34
  yield response
35
 
36
- def save_chat(history, saved_chats):
37
- # Salva o histórico atual
38
- if history:
39
- saved_chats.append(history.copy())
40
- return saved_chats, "Chat salvo! ✅"
41
 
42
- def load_chat(index, saved_chats):
43
- # Carrega um chat salvo
 
 
 
 
 
 
 
 
 
 
44
  if 0 <= index < len(saved_chats):
45
- return saved_chats[index], f"Chat {index+1} carregado! 📂"
46
  return [], "Índice inválido."
47
 
48
  with gr.Blocks(css="""
49
- /* Mesmo CSS que você fez */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  .gr-chat-interface {
51
  border-radius: 20px !important;
52
- overflow: hidden !important;
53
  border: 2px solid #333 !important;
54
  background-color: #1a1a1a !important;
55
  color: white;
56
  }
57
- .gr-button, .gr-chat-send-button {
58
- border-radius: 50px;
59
- padding: 12px 20px;
60
- background-color: #111;
61
- color: white;
62
- font-weight: bold;
63
- cursor: pointer;
64
- height: 50px;
65
- transition: background-color 0.5s;
66
- }
67
- .gr-button:active, .gr-chat-send-button:active {
68
- background-color: white !important;
69
- color: #111 !important;
70
- transition: background-color 0.5s;
71
- }
72
- button:not(.gr-chat-send-button) {
73
- border-radius: 30px;
74
- padding: 6px 12px;
75
- background-color: #222;
76
- color: white;
77
- height: 40px;
78
- transition: background-color 0.5s;
79
- }
80
- button:not(.gr-chat-send-button):active {
81
- background-color: white !important;
82
- color: #111 !important;
83
- transition: background-color 0.5s;
84
- }
85
  textarea {
86
  height: 40px !important;
87
  border-radius: 20px !important;
@@ -93,22 +116,38 @@ textarea {
93
  }
94
  """) as demo:
95
 
96
- saved_chats = gr.State([]) # Lista com todos os chats salvos
97
-
98
- with gr.Column():
99
- gr.HTML("<h2 style='text-align:center; color:white'>BitAI</h2>")
100
- chatbot = gr.ChatInterface(fn=respond, type="messages", additional_inputs=[saved_chats])
101
-
102
- with gr.Row():
103
- save_btn = gr.Button("💾 Salvar Chat")
104
- load_index = gr.Number(label="Número do chat pra carregar", precision=0)
105
- load_btn = gr.Button("📂 Carregar Chat")
106
-
107
- status = gr.Textbox(label="Status", interactive=False)
108
-
109
- # Liga os botões
110
- save_btn.click(save_chat, [chatbot.chatbot, saved_chats], [saved_chats, status])
111
- load_btn.click(load_chat, [load_index, saved_chats], [chatbot.chatbot, status])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
  if __name__ == "__main__":
114
  demo.launch()
 
1
  import os
2
  import gradio as gr
3
  from huggingface_hub import InferenceClient
4
+ import json
5
 
6
+ SAVE_FILE = "bitai_history.json"
7
+
8
+ # Função pra carregar histórico salvo no arquivo
9
+ def load_saved_chats():
10
+ if os.path.exists(SAVE_FILE):
11
+ with open(SAVE_FILE, "r", encoding="utf-8") as f:
12
+ return json.load(f)
13
+ return []
14
+
15
+ # Função pra salvar o histórico atual no arquivo
16
+ def save_chats(chats):
17
+ with open(SAVE_FILE, "w", encoding="utf-8") as f:
18
+ json.dump(chats, f, ensure_ascii=False, indent=2)
19
+
20
+ # Função principal do chat
21
  def respond(message, history: list[dict[str, str]], saved_chats):
 
22
  client = InferenceClient(token=os.environ["HF_TOKEN"], model="openai/gpt-oss-20b")
23
 
24
  system_message = """
 
41
  temperature=0.7,
42
  top_p=0.95,
43
  ):
44
+ token = msg.choices[0].delta.content if msg.choices and msg.choices[0].delta else ""
 
 
 
45
  response += token
46
  yield response
47
 
48
+ # Após a resposta completa, salva automaticamente
49
+ history.append({"role": "user", "content": message})
50
+ history.append({"role": "assistant", "content": response})
 
 
51
 
52
+ # Atualiza o histórico e salva no arquivo
53
+ saved_chats[-1] = history
54
+ save_chats(saved_chats)
55
+
56
+ def new_chat(saved_chats):
57
+ # Cria novo chat vazio
58
+ saved_chats.append([])
59
+ save_chats(saved_chats)
60
+ return saved_chats, len(saved_chats) - 1, []
61
+
62
+ def select_chat(index, saved_chats):
63
+ # Seleciona um chat pelo índice
64
  if 0 <= index < len(saved_chats):
65
+ return saved_chats[index], f"Chat {index+1} carregado!"
66
  return [], "Índice inválido."
67
 
68
  with gr.Blocks(css="""
69
+ /* Fundo geral */
70
+ body, .gr-blocks {
71
+ background-color: #1a1a1a !important;
72
+ color: white;
73
+ }
74
+
75
+ /* Sidebar */
76
+ .sidebar {
77
+ background-color: #111;
78
+ padding: 10px;
79
+ border-right: 2px solid #333;
80
+ height: 100vh;
81
+ overflow-y: auto;
82
+ }
83
+
84
+ .sidebar button {
85
+ display: block;
86
+ width: 100%;
87
+ margin-bottom: 10px;
88
+ background-color: #222;
89
+ color: white;
90
+ border-radius: 10px;
91
+ padding: 10px;
92
+ text-align: left;
93
+ border: none;
94
+ cursor: pointer;
95
+ transition: background-color 0.3s;
96
+ }
97
+ .sidebar button:hover {
98
+ background-color: #444;
99
+ }
100
+
101
+ /* Chat */
102
  .gr-chat-interface {
103
  border-radius: 20px !important;
 
104
  border: 2px solid #333 !important;
105
  background-color: #1a1a1a !important;
106
  color: white;
107
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  textarea {
109
  height: 40px !important;
110
  border-radius: 20px !important;
 
116
  }
117
  """) as demo:
118
 
119
+ saved_chats = gr.State(load_saved_chats())
120
+ current_index = gr.State(0)
121
+
122
+ with gr.Row():
123
+ with gr.Column(scale=0.3, elem_classes="sidebar"):
124
+ gr.HTML("<h3>���� Histórico</h3>")
125
+ chat_list = gr.Column()
126
+ new_chat_btn = gr.Button(" Novo Chat")
127
+
128
+ with gr.Column(scale=1):
129
+ gr.HTML("<h2 style='text-align:center; color:white'>BitAI</h2>")
130
+ chatbot = gr.ChatInterface(fn=respond, type="messages", additional_inputs=[saved_chats])
131
+ status = gr.Textbox(label="Status", interactive=False)
132
+
133
+ def update_chat_list(saved_chats):
134
+ # Mostra botões para cada chat
135
+ return [
136
+ gr.Button.update(value=f"Chat {i+1}") for i in range(len(saved_chats))
137
+ ]
138
+
139
+ # Atualiza lista de chats
140
+ demo.load(update_chat_list, saved_chats, chat_list)
141
+
142
+ # Cria novo chat
143
+ new_chat_btn.click(new_chat, [saved_chats], [saved_chats, current_index, chatbot.chatbot]).then(
144
+ update_chat_list, saved_chats, chat_list
145
+ )
146
+
147
+ # Clica num chat da lista
148
+ for i in range(20): # Limite de 20 chats visíveis
149
+ btn = gr.Button(f"Chat {i+1}", visible=False)
150
+ btn.click(select_chat, [gr.State(i), saved_chats], [chatbot.chatbot, status])
151
 
152
  if __name__ == "__main__":
153
  demo.launch()