Salt40404 commited on
Commit
16b505f
·
verified ·
1 Parent(s): 9c44597

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -37
app.py CHANGED
@@ -2,23 +2,26 @@ 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 = """
@@ -45,34 +48,40 @@ If someone asks what you are, clarify politely that you are BitAI, an AI chatbot
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;
@@ -80,7 +89,6 @@ body, .gr-blocks {
80
  height: 100vh;
81
  overflow-y: auto;
82
  }
83
-
84
  .sidebar button {
85
  display: block;
86
  width: 100%;
@@ -97,13 +105,10 @@ body, .gr-blocks {
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;
@@ -116,36 +121,39 @@ textarea {
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
 
 
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
 
11
+ def load_saved_chats(user_id):
12
+ path = get_user_file(user_id)
13
+ if os.path.exists(path):
14
+ with open(path, "r", encoding="utf-8") as f:
15
  return json.load(f)
16
  return []
17
 
18
+ def save_chats(user_id, chats):
19
+ path = get_user_file(user_id)
20
+ with open(path, "w", encoding="utf-8") as f:
21
  json.dump(chats, f, ensure_ascii=False, indent=2)
22
 
23
  # Função principal do chat
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
  system_message = """
 
48
  response += token
49
  yield response
50
 
51
+ # salva automático
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:
75
+ chats = [[]]
76
+ save_chats(user_id, chats)
77
+ return user_id, chats, len(chats) - 1
78
+
79
  with gr.Blocks(css="""
80
+ /* Sidebar e chat estilo escuro */
81
  body, .gr-blocks {
82
  background-color: #1a1a1a !important;
83
  color: white;
84
  }
 
 
85
  .sidebar {
86
  background-color: #111;
87
  padding: 10px;
 
89
  height: 100vh;
90
  overflow-y: auto;
91
  }
 
92
  .sidebar button {
93
  display: block;
94
  width: 100%;
 
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;
 
121
  }
122
  """) as demo:
123
 
124
+ user_id = gr.State("")
125
+ saved_chats = gr.State([])
126
  current_index = gr.State(0)
127
 
128
  with gr.Row():
129
+ with gr.Column(scale=0.3, elem_classes="sidebar") as sidebar:
130
  gr.HTML("<h3>💬 Histórico</h3>")
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; color:white'>BitAI</h2>")
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
+ update_chat_list, saved_chats, chat_list
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
  update_chat_list, saved_chats, chat_list
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