CVision-assitant commited on
Commit
abd2df4
·
verified ·
1 Parent(s): 290019d

Update modules/interface.py

Browse files
Files changed (1) hide show
  1. modules/interface.py +355 -371
modules/interface.py CHANGED
@@ -1,372 +1,356 @@
1
- import gradio as gr
2
- from modules.listen import transcribe_audio_file
3
- from modules.talker.talk import speak
4
- #APIS DE USUARIO
5
- from modules.utils.chat_utils import (
6
- productivity_chat,
7
- browser_chat,
8
- scientist_chat,
9
- regular_chat,
10
- document_chat,
11
- update_api_keys
12
- )
13
-
14
- BUTTON_TEXT = "Enviar"
15
- PLACEHOLDER = "Escribe lo que necesites..."
16
-
17
-
18
- # ---------------- ESTADO DE SESIÓN ----------------
19
- api_state = {
20
- "gemini": "",
21
- "nvidia": "",
22
- "notion": ""
23
- }
24
-
25
-
26
- # ---------------- GUARDAR API KEYS ----------------
27
- def save_api_keys(gemini_key, nvidia_key, notion_key):
28
- global api_state
29
-
30
- api_state = {
31
- "gemini": gemini_key.strip(),
32
- "nvidia": nvidia_key.strip(),
33
- "notion": notion_key.strip()
34
- }
35
-
36
- return "✅ API Keys guardadas correctamente."
37
-
38
-
39
- # ---------------- VOZ A TEXTO ----------------
40
- def speech_to_text(audio):
41
- if audio is None:
42
- return ""
43
-
44
- try:
45
- return transcribe_audio_file(audio)
46
- except Exception as e:
47
- print("Error STT:", e)
48
- return "No se pudo transcribir el audio."
49
-
50
-
51
- # ---------------- RESUMEN PARA VOZ ----------------
52
- def summarize_for_voice(text, max_chars=250):
53
- if not text:
54
- return ""
55
-
56
- text = str(text).strip()
57
-
58
- if len(text) <= max_chars:
59
- return text
60
-
61
- summary = text[:max_chars]
62
-
63
- if "." in summary:
64
- summary = summary.rsplit(".", 1)[0] + "."
65
- else:
66
- summary = summary.rsplit(" ", 1)[0]
67
-
68
- return summary + " ... resumen de respuesta."
69
-
70
-
71
- # ---------------- PROCESAR RESPUESTA ----------------
72
- def process_chat_result(result):
73
- final_response = result
74
-
75
- try:
76
- if hasattr(result, "__iter__") and not isinstance(result, list):
77
- for update in result:
78
- final_response = update
79
- except Exception as e:
80
- print("Error procesando generator:", e)
81
-
82
- return final_response
83
-
84
-
85
- # ---------------- MODO VOZ GENERAL ----------------
86
- def voice_chat(chat_history, audio, mode):
87
- if audio is None:
88
- return chat_history + [
89
- {"role": "assistant", "content": "⚠️ No se detectó audio."}
90
- ]
91
-
92
- try:
93
- user_text = transcribe_audio_file(audio)
94
- except Exception as e:
95
- print("Error audio:", e)
96
- return chat_history + [
97
- {"role": "assistant", "content": "❌ Error al transcribir audio"}
98
- ]
99
-
100
- if not user_text:
101
- return chat_history + [
102
- {"role": "assistant", "content": "⚠️ No se pudo entender el audio."}
103
- ]
104
-
105
- if mode == "productividad":
106
- result = productivity_chat(chat_history, user_text)
107
- elif mode == "web":
108
- result = browser_chat(chat_history, user_text)
109
- elif mode == "cientifico":
110
- result = scientist_chat(chat_history, user_text)
111
- else:
112
- result = regular_chat(chat_history, user_text)
113
-
114
- final_response = process_chat_result(result)
115
-
116
- try:
117
- if final_response and isinstance(final_response, list):
118
- last_msg = final_response[-1]["content"]
119
- voice_text = summarize_for_voice(last_msg)
120
- speak(voice_text)
121
- except Exception as e:
122
- print("Error TTS:", e)
123
-
124
- return final_response
125
-
126
-
127
- # ---------------- MODO VOZ PDF ----------------
128
- def voice_pdf(chat_history, audio, uploaded_document):
129
- if audio is None:
130
- return chat_history + [
131
- {"role": "assistant", "content": "⚠️ No se detectó audio."}
132
- ]
133
-
134
- if uploaded_document is None:
135
- return chat_history + [
136
- {"role": "assistant", "content": "⚠️ Debes subir un PDF primero."}
137
- ]
138
-
139
- try:
140
- user_text = transcribe_audio_file(audio)
141
- except Exception as e:
142
- print("Error PDF audio:", e)
143
- return chat_history + [
144
- {"role": "assistant", "content": "❌ Error al transcribir audio"}
145
- ]
146
-
147
- result = document_chat(chat_history, user_text, uploaded_document)
148
-
149
- final_response = process_chat_result(result)
150
-
151
- try:
152
- if final_response and isinstance(final_response, list):
153
- last_msg = final_response[-1]["content"]
154
- voice_text = summarize_for_voice(last_msg)
155
- speak(voice_text)
156
- except Exception as e:
157
- print("Error voz PDF:", e)
158
-
159
- return final_response
160
-
161
-
162
- # ---------------- CSS ----------------
163
- CUSTOM_CSS = """
164
- @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@500;700&family=Roboto+Mono:wght@400;500&display=swap');
165
-
166
- body {
167
- background: #0a0f1e;
168
- color: #d0d7e0;
169
- font-family: 'Roboto Mono', monospace;
170
- }
171
-
172
- #title {
173
- font-family: 'Orbitron', sans-serif;
174
- font-size: 48px;
175
- color: #4fc3f7;
176
- text-align: center;
177
- }
178
-
179
- #subtitle {
180
- text-align: center;
181
- color: #a0a8b0;
182
- margin-bottom: 30px;
183
- }
184
-
185
- .chatbot {
186
- height: 520px !important;
187
- background: #141b2f;
188
- }
189
-
190
- button {
191
- background: #4fc3f7 !important;
192
- color: #0a0f1e !important;
193
- }
194
-
195
- .voice-btn {
196
- background: #10b981 !important;
197
- }
198
- """
199
-
200
-
201
- # ---------------- INTERFAZ ----------------
202
- with gr.Blocks(css=CUSTOM_CSS) as assistant:
203
-
204
- gr.Image("assets/CVision logo.png", width=120)
205
- gr.Markdown('<div id="title">🤖 Asistente Virtual CV</div>')
206
- gr.Markdown('<div id="subtitle">Modo inteligente con voz</div>')
207
-
208
- # ---------------- CONFIGURACION API ----------------
209
- with gr.Tab("⚙️ Configuración API"):
210
-
211
- gr.Markdown("## 🔐 Configuración de API Keys")
212
-
213
- gemini_input = gr.Textbox(
214
- label="API Gemini",
215
- type="password"
216
- )
217
-
218
- nvidia_input = gr.Textbox(
219
- label="API NVIDIA",
220
- type="password"
221
- )
222
-
223
- notion_input = gr.Textbox(
224
- label="API Notion",
225
- type="password"
226
- )
227
-
228
- save_button = gr.Button("💾 Guardar configuración")
229
- save_status = gr.Markdown("⚠️ No hay claves cargadas.")
230
-
231
- save_button.click(
232
- save_api_keys,
233
- inputs=[gemini_input, nvidia_input, notion_input],
234
- outputs=save_status
235
- )
236
-
237
- # ---------------- PRODUCTIVIDAD ----------------
238
- with gr.Tab("📈 Productividad"):
239
- chatbot = gr.Chatbot(render_markdown=True)
240
- text_input = gr.Textbox(placeholder=PLACEHOLDER)
241
- mic = gr.Audio(sources=["microphone"], type="filepath")
242
-
243
- with gr.Row():
244
- text_button = gr.Button("Enviar")
245
- voice_button = gr.Button("🎤 Voz", elem_classes="voice-btn")
246
- clear_button = gr.Button("Limpiar")
247
-
248
- text_button.click(productivity_chat, [chatbot, text_input], chatbot)
249
-
250
- voice_button.click(
251
- lambda h, a: voice_chat(h, a, "productividad"),
252
- inputs=[chatbot, mic],
253
- outputs=chatbot
254
- )
255
-
256
- clear_button.click(lambda: [], None, chatbot)
257
- mic.change(speech_to_text, mic, text_input)
258
-
259
- # ---------------- WEB ----------------
260
- with gr.Tab("🌐 Web"):
261
- chatbot = gr.Chatbot(render_markdown=True)
262
- text_input = gr.Textbox(placeholder=PLACEHOLDER)
263
- mic = gr.Audio(sources=["microphone"], type="filepath")
264
-
265
- with gr.Row():
266
- text_button = gr.Button("Enviar")
267
- voice_button = gr.Button("🎤 Voz", elem_classes="voice-btn")
268
- clear_button = gr.Button("Limpiar")
269
-
270
- text_button.click(browser_chat, [chatbot, text_input], chatbot)
271
-
272
- voice_button.click(
273
- lambda h, a: voice_chat(h, a, "web"),
274
- inputs=[chatbot, mic],
275
- outputs=chatbot
276
- )
277
-
278
- clear_button.click(lambda: [], None, chatbot)
279
- mic.change(speech_to_text, mic, text_input)
280
-
281
- # ---------------- GENERAL ----------------
282
- with gr.Tab("💬 General"):
283
- chatbot = gr.Chatbot(render_markdown=True)
284
- text_input = gr.Textbox(placeholder=PLACEHOLDER)
285
- mic = gr.Audio(sources=["microphone"], type="filepath")
286
-
287
- with gr.Row():
288
- text_button = gr.Button("Enviar")
289
- voice_button = gr.Button("🎤 Voz", elem_classes="voice-btn")
290
- clear_button = gr.Button("Limpiar")
291
-
292
- text_button.click(regular_chat, [chatbot, text_input], chatbot)
293
-
294
- voice_button.click(
295
- lambda h, a: voice_chat(h, a, "general"),
296
- inputs=[chatbot, mic],
297
- outputs=chatbot
298
- )
299
-
300
- clear_button.click(lambda: [], None, chatbot)
301
- mic.change(speech_to_text, mic, text_input)
302
-
303
- # ---------------- CIENTIFICO ----------------
304
- with gr.Tab("🔬 Científico"):
305
- chatbot = gr.Chatbot(render_markdown=True)
306
- text_input = gr.Textbox(placeholder=PLACEHOLDER)
307
- mic = gr.Audio(sources=["microphone"], type="filepath")
308
-
309
- with gr.Row():
310
- text_button = gr.Button("Enviar")
311
- voice_button = gr.Button("🎤 Voz", elem_classes="voice-btn")
312
- clear_button = gr.Button("Limpiar")
313
-
314
- text_button.click(scientist_chat, [chatbot, text_input], chatbot)
315
-
316
- voice_button.click(
317
- lambda h, a: voice_chat(h, a, "cientifico"),
318
- inputs=[chatbot, mic],
319
- outputs=chatbot
320
- )
321
-
322
- clear_button.click(lambda: [], None, chatbot)
323
- mic.change(speech_to_text, mic, text_input)
324
-
325
- # ---------------- CHAT PDF ----------------
326
- with gr.Tab("📄 Chat PDF"):
327
- chatbot = gr.Chatbot(render_markdown=True)
328
-
329
- uploaded_document = gr.File(
330
- file_types=[".pdf"],
331
- label="Sube tu archivo PDF"
332
- )
333
-
334
- upload_status = gr.Markdown("⚠️ No hay archivo cargado.")
335
-
336
- text_input = gr.Textbox(placeholder=PLACEHOLDER)
337
- mic = gr.Audio(sources=["microphone"], type="filepath")
338
-
339
- with gr.Row():
340
- text_button = gr.Button("Enviar")
341
- voice_button = gr.Button("🎤 Voz", elem_classes="voice-btn")
342
- clear_button = gr.Button("Limpiar")
343
-
344
- def confirm_upload(file):
345
- if file is not None:
346
- return f"✅ Archivo cargado: **{file.name.split('/')[-1]}**"
347
- return "⚠️ No hay archivo cargado."
348
-
349
- uploaded_document.change(
350
- confirm_upload,
351
- inputs=uploaded_document,
352
- outputs=upload_status
353
- )
354
-
355
- text_button.click(
356
- document_chat,
357
- inputs=[chatbot, text_input, uploaded_document],
358
- outputs=chatbot
359
- )
360
-
361
- voice_button.click(
362
- voice_pdf,
363
- inputs=[chatbot, mic, uploaded_document],
364
- outputs=chatbot
365
- )
366
-
367
- clear_button.click(lambda: [], None, chatbot)
368
- mic.change(speech_to_text, mic, text_input)
369
-
370
-
371
- if __name__ == "__main__":
372
  assistant.launch()
 
1
+ import gradio as gr
2
+ from modules.listen import transcribe_audio_file
3
+ from modules.talker.talk import speak
4
+
5
+ from modules.utils.chat_utils import (
6
+ productivity_chat,
7
+ browser_chat,
8
+ scientist_chat,
9
+ regular_chat,
10
+ document_chat,
11
+ )
12
+
13
+ BUTTON_TEXT = "Enviar"
14
+ PLACEHOLDER = "Escribe lo que necesites..."
15
+
16
+
17
+ # ---------------- VOZ A TEXTO ----------------
18
+ def speech_to_text(audio):
19
+ if audio is None:
20
+ return ""
21
+
22
+ try:
23
+ return transcribe_audio_file(audio)
24
+ except Exception as e:
25
+ print("Error STT:", e)
26
+ return "No se pudo transcribir el audio."
27
+
28
+
29
+ # ---------------- RESUMEN PARA VOZ ----------------
30
+ def summarize_for_voice(text, max_chars=250):
31
+ if not text:
32
+ return ""
33
+
34
+ text = str(text).strip()
35
+
36
+ if len(text) <= max_chars:
37
+ return text
38
+
39
+ summary = text[:max_chars]
40
+
41
+ if "." in summary:
42
+ summary = summary.rsplit(".", 1)[0] + "."
43
+ else:
44
+ summary = summary.rsplit(" ", 1)[0]
45
+
46
+ return summary + " ... resumen de respuesta."
47
+
48
+
49
+ # ---------------- PROCESAR GENERATOR ----------------
50
+ def process_chat_result(result):
51
+ final_response = []
52
+
53
+ try:
54
+ for update in result:
55
+ final_response = update
56
+ except Exception as e:
57
+ print("Error generator:", e)
58
+
59
+ return final_response
60
+
61
+
62
+ # ---------------- EXTRAER ÚLTIMO MENSAJE ----------------
63
+ def get_last_assistant_message(chat_history):
64
+ if not chat_history:
65
+ return ""
66
+
67
+ last = chat_history[-1]
68
+
69
+ if isinstance(last, list) and len(last) == 2:
70
+ return last[1]
71
+
72
+ return ""
73
+
74
+
75
+ # ---------------- CHAT POR VOZ ----------------
76
+ def voice_chat(chat_history, audio, mode):
77
+ if chat_history is None:
78
+ chat_history = []
79
+
80
+ if audio is None:
81
+ return chat_history + [["", "⚠️ No se detectó audio."]]
82
+
83
+ try:
84
+ user_text = transcribe_audio_file(audio)
85
+ except Exception as e:
86
+ print("Error audio:", e)
87
+ return chat_history + [["", "❌ Error al transcribir audio."]]
88
+
89
+ if not user_text:
90
+ return chat_history + [["", "⚠️ No se pudo entender el audio."]]
91
+
92
+ if mode == "productividad":
93
+ result = productivity_chat(chat_history, user_text)
94
+
95
+ elif mode == "web":
96
+ result = browser_chat(chat_history, user_text)
97
+
98
+ elif mode == "cientifico":
99
+ result = scientist_chat(chat_history, user_text)
100
+
101
+ else:
102
+ result = regular_chat(chat_history, user_text)
103
+
104
+ final_response = process_chat_result(result)
105
+
106
+ try:
107
+ voice_text = summarize_for_voice(
108
+ get_last_assistant_message(final_response)
109
+ )
110
+
111
+ if voice_text:
112
+ speak(voice_text)
113
+
114
+ except Exception as e:
115
+ print("Error TTS:", e)
116
+
117
+ return final_response
118
+
119
+
120
+ # ---------------- CHAT PDF POR VOZ ----------------
121
+ def voice_pdf(chat_history, audio, uploaded_document):
122
+ if chat_history is None:
123
+ chat_history = []
124
+
125
+ if audio is None:
126
+ return chat_history + [["", "⚠️ No se detectó audio."]]
127
+
128
+ if uploaded_document is None:
129
+ return chat_history + [["", "⚠️ Debes subir un PDF primero."]]
130
+
131
+ try:
132
+ user_text = transcribe_audio_file(audio)
133
+ except Exception as e:
134
+ print("Error PDF audio:", e)
135
+ return chat_history + [["", "❌ Error al transcribir audio."]]
136
+
137
+ result = document_chat(
138
+ chat_history,
139
+ user_text,
140
+ uploaded_document
141
+ )
142
+
143
+ final_response = process_chat_result(result)
144
+
145
+ try:
146
+ voice_text = summarize_for_voice(
147
+ get_last_assistant_message(final_response)
148
+ )
149
+
150
+ if voice_text:
151
+ speak(voice_text)
152
+
153
+ except Exception as e:
154
+ print("Error voz PDF:", e)
155
+
156
+ return final_response
157
+
158
+
159
+ # ---------------- CSS ----------------
160
+ CUSTOM_CSS = """
161
+ body {
162
+ background: #0a0f1e;
163
+ color: white;
164
+ }
165
+
166
+ .chatbot {
167
+ height: 520px !important;
168
+ }
169
+
170
+ button {
171
+ background: #4fc3f7 !important;
172
+ color: black !important;
173
+ }
174
+ """
175
+
176
+
177
+ # ---------------- INTERFAZ ----------------
178
+ with gr.Blocks(css=CUSTOM_CSS) as assistant:
179
+
180
+ gr.Markdown("# 🤖 Asistente Virtual CV")
181
+ gr.Markdown("Modo inteligente con voz")
182
+
183
+ # ---------------- PRODUCTIVIDAD ----------------
184
+ with gr.Tab("📈 Productividad"):
185
+ chatbot_prod = gr.Chatbot(height=520)
186
+ text_prod = gr.Textbox(placeholder=PLACEHOLDER)
187
+ mic_prod = gr.Audio(
188
+ sources=["microphone"],
189
+ type="filepath"
190
+ )
191
+
192
+ with gr.Row():
193
+ btn_text = gr.Button("Enviar")
194
+ btn_voice = gr.Button("🎤 Voz")
195
+ btn_clear = gr.Button("Limpiar")
196
+
197
+ btn_text.click(
198
+ productivity_chat,
199
+ inputs=[chatbot_prod, text_prod],
200
+ outputs=chatbot_prod
201
+ )
202
+
203
+ btn_voice.click(
204
+ lambda h, a: voice_chat(h, a, "productividad"),
205
+ inputs=[chatbot_prod, mic_prod],
206
+ outputs=chatbot_prod
207
+ )
208
+
209
+ btn_clear.click(lambda: [], outputs=chatbot_prod)
210
+
211
+ mic_prod.change(
212
+ speech_to_text,
213
+ inputs=mic_prod,
214
+ outputs=text_prod
215
+ )
216
+
217
+ # ---------------- WEB ----------------
218
+ with gr.Tab("🌐 Web"):
219
+ chatbot_web = gr.Chatbot(height=520)
220
+ text_web = gr.Textbox(placeholder=PLACEHOLDER)
221
+ mic_web = gr.Audio(
222
+ sources=["microphone"],
223
+ type="filepath"
224
+ )
225
+
226
+ with gr.Row():
227
+ btn_text = gr.Button("Enviar")
228
+ btn_voice = gr.Button("🎤 Voz")
229
+ btn_clear = gr.Button("Limpiar")
230
+
231
+ btn_text.click(
232
+ browser_chat,
233
+ inputs=[chatbot_web, text_web],
234
+ outputs=chatbot_web
235
+ )
236
+
237
+ btn_voice.click(
238
+ lambda h, a: voice_chat(h, a, "web"),
239
+ inputs=[chatbot_web, mic_web],
240
+ outputs=chatbot_web
241
+ )
242
+
243
+ btn_clear.click(lambda: [], outputs=chatbot_web)
244
+
245
+ mic_web.change(
246
+ speech_to_text,
247
+ inputs=mic_web,
248
+ outputs=text_web
249
+ )
250
+
251
+ # ---------------- GENERAL ----------------
252
+ with gr.Tab("💬 General"):
253
+ chatbot_gen = gr.Chatbot(height=520)
254
+ text_gen = gr.Textbox(placeholder=PLACEHOLDER)
255
+ mic_gen = gr.Audio(
256
+ sources=["microphone"],
257
+ type="filepath"
258
+ )
259
+
260
+ with gr.Row():
261
+ btn_text = gr.Button("Enviar")
262
+ btn_voice = gr.Button("🎤 Voz")
263
+ btn_clear = gr.Button("Limpiar")
264
+
265
+ btn_text.click(
266
+ regular_chat,
267
+ inputs=[chatbot_gen, text_gen],
268
+ outputs=chatbot_gen
269
+ )
270
+
271
+ btn_voice.click(
272
+ lambda h, a: voice_chat(h, a, "general"),
273
+ inputs=[chatbot_gen, mic_gen],
274
+ outputs=chatbot_gen
275
+ )
276
+
277
+ btn_clear.click(lambda: [], outputs=chatbot_gen)
278
+
279
+ mic_gen.change(
280
+ speech_to_text,
281
+ inputs=mic_gen,
282
+ outputs=text_gen
283
+ )
284
+
285
+ # ---------------- CIENTÍFICO ----------------
286
+ with gr.Tab("🔬 Científico"):
287
+ chatbot_sci = gr.Chatbot(height=520)
288
+ text_sci = gr.Textbox(placeholder=PLACEHOLDER)
289
+ mic_sci = gr.Audio(
290
+ sources=["microphone"],
291
+ type="filepath"
292
+ )
293
+
294
+ with gr.Row():
295
+ btn_text = gr.Button("Enviar")
296
+ btn_voice = gr.Button("🎤 Voz")
297
+ btn_clear = gr.Button("Limpiar")
298
+
299
+ btn_text.click(
300
+ scientist_chat,
301
+ inputs=[chatbot_sci, text_sci],
302
+ outputs=chatbot_sci
303
+ )
304
+
305
+ btn_voice.click(
306
+ lambda h, a: voice_chat(h, a, "cientifico"),
307
+ inputs=[chatbot_sci, mic_sci],
308
+ outputs=chatbot_sci
309
+ )
310
+
311
+ btn_clear.click(lambda: [], outputs=chatbot_sci)
312
+
313
+ mic_sci.change(
314
+ speech_to_text,
315
+ inputs=mic_sci,
316
+ outputs=text_sci
317
+ )
318
+
319
+ # ---------------- PDF ----------------
320
+ with gr.Tab("📄 Chat PDF"):
321
+ chatbot_pdf = gr.Chatbot(height=520)
322
+ uploaded_document = gr.File(file_types=[".pdf"])
323
+ text_pdf = gr.Textbox(placeholder=PLACEHOLDER)
324
+ mic_pdf = gr.Audio(
325
+ sources=["microphone"],
326
+ type="filepath"
327
+ )
328
+
329
+ with gr.Row():
330
+ btn_text = gr.Button("Enviar")
331
+ btn_voice = gr.Button("🎤 Voz")
332
+ btn_clear = gr.Button("Limpiar")
333
+
334
+ btn_text.click(
335
+ document_chat,
336
+ inputs=[chatbot_pdf, text_pdf, uploaded_document],
337
+ outputs=chatbot_pdf
338
+ )
339
+
340
+ btn_voice.click(
341
+ voice_pdf,
342
+ inputs=[chatbot_pdf, mic_pdf, uploaded_document],
343
+ outputs=chatbot_pdf
344
+ )
345
+
346
+ btn_clear.click(lambda: [], outputs=chatbot_pdf)
347
+
348
+ mic_pdf.change(
349
+ speech_to_text,
350
+ inputs=mic_pdf,
351
+ outputs=text_pdf
352
+ )
353
+
354
+
355
+ if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
  assistant.launch()