CVision-assitant commited on
Commit
3caefe0
·
verified ·
1 Parent(s): 44f9bdc

Update modules/interface.py

Browse files
Files changed (1) hide show
  1. modules/interface.py +693 -786
modules/interface.py CHANGED
@@ -3,6 +3,7 @@ import re
3
  import os
4
  import time
5
  import json
 
6
  from modules.listen import transcribe_audio_file
7
  from modules.talker.talk import speak
8
 
@@ -13,18 +14,13 @@ try:
13
  browser_chat,
14
  scientist_chat,
15
  regular_chat,
16
- document_chat,
17
  )
18
  except ImportError:
19
- print("Error: No se pudieron importar los módulos de chat.")
20
 
21
  # ════════════════════════════════════════════════════════════
22
- # PLACEHOLDER DEL INPUT
23
- # ════════════════════════════════════════════════════════════
24
- PLACEHOLDER = "Escribe tu mensaje para CVision..."
25
-
26
- # ════════════════════════════════════════════════════════════
27
- # CSS FUTURISTA — Diamante × Cyan
28
  # ════════════════════════════════════════════════════════════
29
  CUSTOM_CSS = """
30
  /* ── Google Fonts ── */
@@ -32,35 +28,36 @@ CUSTOM_CSS = """
32
 
33
  /* ── Variables globales ── */
34
  :root {
35
- --c0: #000509;
36
- --c1: #020c18;
37
- --c2: #04182e;
38
- --cyan: #00d4ff;
39
- --cyan2: #00a8e8;
40
- --cyan-dim: rgba(0,212,255,0.10);
41
- --diamond: #e8f4ff;
42
- --diamond2: #b8d8f0;
43
- --text-main: #cce9f8;
44
- --text-muted: #5a8fab;
45
- --text-dim: #2a4a60;
46
- --border: rgba(0,212,255,0.16);
47
- --border-bright: rgba(0,212,255,0.45);
48
- --glass: rgba(4,24,46,0.78);
49
- --glass2: rgba(2,12,24,0.90);
50
- --radius: 12px;
51
- --radius-lg: 20px;
52
- --font-d: 'Orbitron', monospace;
53
- --font-b: 'Exo 2', sans-serif;
54
- --font-m: 'Share Tech Mono', monospace;
55
  }
56
 
57
  /* ── Reset base ── */
58
  *, *::before, *::after { box-sizing: border-box; }
59
  body, .gradio-container {
60
- background: var(--c0) !important;
61
- color: var(--text-main) !important;
62
- font-family: var(--font-b) !important;
63
- min-height: 100vh;
 
64
  }
65
 
66
  /* scrollbar */
@@ -70,72 +67,78 @@ body, .gradio-container {
70
 
71
  /* ── Grid de fondo ── */
72
  .gradio-container::before {
73
- content: '';
74
- position: fixed; inset: 0; z-index: 0; pointer-events: none;
75
- background-image:
76
- linear-gradient(rgba(0,212,255,0.028) 1px, transparent 1px),
77
- linear-gradient(90deg, rgba(0,212,255,0.028) 1px, transparent 1px);
78
- background-size: 44px 44px;
79
- mask-image: radial-gradient(ellipse 80% 80% at 50% 50%, black 0%, transparent 100%);
80
  }
81
 
82
  /* ── Scanline animado ── */
83
  .gradio-container::after {
84
- content: '';
85
- position: fixed; top: 0; left: 0; width: 100%; height: 2px;
86
- background: linear-gradient(90deg, transparent, rgba(0,212,255,0.3), transparent);
87
- animation: scanDown 7s ease-in-out infinite;
88
- z-index: 9999; pointer-events: none;
89
  }
90
  @keyframes scanDown {
91
- 0% { top: -2px; opacity: 0; }
92
- 8% { opacity: 1; }
93
- 92% { opacity: .4; }
94
- 100% { top: 100vh; opacity: 0; }
95
  }
96
 
97
  /* ══════════════════════════════════════════
98
- HEADER / TÍTULO PRINCIPAL
99
  ══════════════════════════════════��═══════ */
100
  #cvision-header {
101
- background: var(--glass2);
102
- border-bottom: 1px solid var(--border);
103
- padding: 18px 32px;
104
- display: flex;
105
- align-items: center;
106
- gap: 18px;
107
- position: sticky; top: 0; z-index: 100;
108
- backdrop-filter: blur(20px);
 
109
  }
110
 
111
- /* ── Nebula wrapper ── */
 
 
112
  #nebula-outer {
113
- display: flex;
114
- justify-content: center;
115
- align-items: center;
116
- padding: 28px 0 20px;
117
- background: linear-gradient(180deg, rgba(0,212,255,0.04) 0%, transparent 100%);
118
- border-bottom: 1px solid var(--border);
 
119
  }
 
120
  #nebula-ring-wrap {
121
- position: relative;
122
- width: 230px; height: 230px;
 
123
  }
124
  #nebula-canvas-wrap {
125
- width: 230px; height: 230px;
126
- border-radius: 50%;
127
- border: 1.5px solid rgba(0,212,255,0.4);
128
- background: radial-gradient(circle, rgba(0,212,255,0.08) 0%, #04182e 70%);
129
- box-shadow: 0 0 50px rgba(0,212,255,0.22), inset 0 0 40px rgba(0,0,0,0.5);
130
- overflow: hidden;
131
- position: relative; z-index: 2;
132
  }
133
  #nebulaCanvas { width: 100%; height: 100%; display: block; }
134
 
135
  /* anillos externos decorativos */
136
  .nebula-deco-ring {
137
- position: absolute; border-radius: 50%; pointer-events: none;
138
- border: 0.5px solid rgba(0,212,255,0.13);
139
  }
140
  .nebula-deco-ring.r1 { inset: -20px; animation: spin 18s linear infinite; }
141
  .nebula-deco-ring.r2 { inset: -38px; border-style: dashed; animation: spin 30s linear infinite reverse; }
@@ -143,281 +146,281 @@ body, .gradio-container {
143
 
144
  /* hero info al lado de la nebula */
145
  #nebula-info {
146
- display: flex; flex-direction: column; gap: 12px;
147
- padding: 10px 0 0 28px; max-width: 540px;
148
  }
149
  .hero-eyebrow {
150
- font-family: var(--font-m); font-size: 0.58rem;
151
- letter-spacing: 0.3em; color: var(--text-muted);
152
- text-transform: uppercase;
153
  }
154
  .hero-title {
155
- font-family: var(--font-d); font-size: 2.1rem;
156
- font-weight: 900; line-height: 1.15;
157
- color: var(--diamond);
158
- text-shadow: 0 0 30px rgba(0,212,255,0.4);
159
  }
160
  .hero-title .accent {
161
- color: transparent;
162
- background: linear-gradient(135deg, #00d4ff 0%, #e8f4ff 50%, #00a8e8 100%);
163
- -webkit-background-clip: text; background-clip: text;
164
  }
165
  .hero-desc {
166
- font-size: 0.83rem; color: var(--text-muted);
167
- line-height: 1.7; font-weight: 300;
168
  }
169
  .hero-chips { display: flex; flex-wrap: wrap; gap: 7px; }
170
  .hero-chip {
171
- font-family: var(--font-m); font-size: 0.54rem;
172
- letter-spacing: 0.12em; padding: 5px 13px;
173
- border-radius: 20px; border: 1px solid rgba(0,212,255,0.22);
174
- background: rgba(0,212,255,0.05); color: var(--text-muted);
175
  }
176
 
177
  /* ══════════════════════════════════════════
178
- TABS — barra de navegación principal
179
  ══════════════════════════════════════════ */
180
  .tab-nav {
181
- background: var(--glass2) !important;
182
- border-bottom: 1px solid var(--border) !important;
183
- backdrop-filter: blur(10px);
184
- padding: 0 20px !important;
185
- gap: 0 !important;
186
  }
187
  .tab-nav button {
188
- font-family: var(--font-b) !important;
189
- font-size: 0.8rem !important;
190
- font-weight: 500 !important;
191
- letter-spacing: 0.05em !important;
192
- color: var(--text-muted) !important;
193
- background: transparent !important;
194
- border: none !important;
195
- border-bottom: 2px solid transparent !important;
196
- border-radius: 0 !important;
197
- padding: 14px 22px !important;
198
- transition: color 0.2s, border-color 0.2s !important;
199
  }
200
  .tab-nav button:hover { color: var(--diamond2) !important; }
201
  .tab-nav button.selected {
202
- color: var(--cyan) !important;
203
- border-bottom-color: var(--cyan) !important;
204
- background: transparent !important;
205
  }
206
 
207
  /* ══════════════════════════════════════════
208
- CHATBOT — ventana de mensajes
209
  ══════════════════════════════════════════ */
210
  .chatbot-wrap .wrap {
211
- background: rgba(4,24,46,0.78) !important;
212
- border: 1px solid var(--border) !important;
213
- border-radius: var(--radius-lg) !important;
214
- backdrop-filter: blur(12px) !important;
215
- box-shadow: inset 0 0 40px rgba(0,0,0,0.3), 0 0 30px rgba(0,212,255,0.08) !important;
216
  }
217
  /* burbujas bot */
218
  .chatbot-wrap .message.bot,
219
  .chatbot-wrap [data-testid="bot"] {
220
- background: linear-gradient(135deg, rgba(4,24,46,0.92), rgba(6,29,54,0.88)) !important;
221
- border: 1px solid rgba(0,212,255,0.14) !important;
222
- border-radius: 4px 18px 18px 18px !important;
223
- color: var(--text-main) !important;
224
- font-family: var(--font-b) !important;
225
- font-size: 0.85rem !important;
226
- box-shadow: 0 4px 18px rgba(0,0,0,0.3) !important;
227
- padding: 13px 17px !important;
228
- margin-right: 12% !important;
229
  }
230
  /* burbujas usuario */
231
  .chatbot-wrap .message.user,
232
  .chatbot-wrap [data-testid="user"] {
233
- background: linear-gradient(135deg, rgba(0,70,120,0.72), rgba(0,50,100,0.82)) !important;
234
- border: 1px solid rgba(0,160,230,0.22) !important;
235
- border-radius: 18px 4px 18px 18px !important;
236
- color: var(--diamond) !important;
237
- font-family: var(--font-b) !important;
238
- font-size: 0.85rem !important;
239
- box-shadow: 0 4px 18px rgba(0,0,0,0.3) !important;
240
- padding: 13px 17px !important;
241
- margin-left: 12% !important;
242
  }
243
 
244
  /* ══════════════════════════════════════════
245
- TEXTBOX — campo de entrada
246
  ══════════════════════════════════════════ */
247
  .cv-input textarea,
248
  .cv-input input[type="text"] {
249
- background: rgba(4,24,46,0.82) !important;
250
- border: 1px solid rgba(0,212,255,0.18) !important;
251
- border-radius: var(--radius) !important;
252
- color: var(--text-main) !important;
253
- font-family: var(--font-b) !important;
254
- font-size: 0.85rem !important;
255
- padding: 13px 16px !important;
256
- transition: border-color 0.2s, box-shadow 0.2s !important;
257
- caret-color: var(--cyan) !important;
258
- resize: none !important;
259
  }
260
  .cv-input textarea::placeholder,
261
  .cv-input input::placeholder {
262
- color: var(--text-dim) !important;
263
- font-family: var(--font-m) !important;
264
- font-size: 0.72rem !important;
265
- letter-spacing: 0.08em !important;
266
  }
267
  .cv-input textarea:focus,
268
  .cv-input input:focus {
269
- border-color: rgba(0,212,255,0.48) !important;
270
- box-shadow: 0 0 18px rgba(0,212,255,0.1) !important;
271
- outline: none !important;
272
  }
273
  /* quitar el borde/label contenedor por defecto de Gradio */
274
  .cv-input > .wrap { border: none !important; background: transparent !important; box-shadow: none !important; }
275
  .cv-input label { display: none !important; }
276
 
277
  /* ══════════════════════════════════════════
278
- BOTONES
279
  ══════════════════════════════════════════ */
280
 
281
  /* Enviar — primario cyan */
282
  .btn-send {
283
- background: linear-gradient(135deg, #004a7c, #0070b8, #00a8e8) !important;
284
- color: #fff !important;
285
- border: none !important;
286
- border-radius: var(--radius) !important;
287
- font-family: var(--font-b) !important;
288
- font-weight: 600 !important;
289
- font-size: 0.8rem !important;
290
- letter-spacing: 0.08em !important;
291
- padding: 0 22px !important;
292
- min-height: 48px !important;
293
- box-shadow: 0 0 20px rgba(0,168,232,0.28), inset 0 1px 0 rgba(255,255,255,0.12) !important;
294
- transition: box-shadow 0.2s, transform 0.15s !important;
295
  }
296
  .btn-send:hover {
297
- box-shadow: 0 0 32px rgba(0,212,255,0.45) !important;
298
  }
299
  .btn-send:active { transform: scale(0.97) !important; }
300
 
301
  /* Voz — borde cyan */
302
  .btn-voice {
303
- background: transparent !important;
304
- border: 1px solid rgba(0,212,255,0.32) !important;
305
- color: var(--cyan) !important;
306
- border-radius: var(--radius) !important;
307
- font-family: var(--font-b) !important;
308
- font-weight: 500 !important;
309
- font-size: 0.78rem !important;
310
- letter-spacing: 0.06em !important;
311
- min-height: 48px !important;
312
- padding: 0 18px !important;
313
- transition: all 0.2s !important;
314
  }
315
  .btn-voice:hover {
316
- background: var(--cyan-dim) !important;
317
- border-color: var(--border-bright) !important;
318
- box-shadow: 0 0 14px rgba(0,212,255,0.2) !important;
319
  }
320
 
321
  /* Limpiar — rojo apagado */
322
  .btn-clear {
323
- background: transparent !important;
324
- border: 1px solid rgba(255,60,80,0.2) !important;
325
- color: rgba(255,100,120,0.65) !important;
326
- border-radius: var(--radius) !important;
327
- font-family: var(--font-b) !important;
328
- font-size: 0.75rem !important;
329
- min-height: 40px !important;
330
- padding: 0 16px !important;
331
- transition: all 0.2s !important;
332
  }
333
  .btn-clear:hover {
334
- border-color: rgba(255,60,80,0.45) !important;
335
- background: rgba(255,60,80,0.06) !important;
336
- color: #ff6477 !important;
337
  }
338
 
339
  /* Analizar PDF */
340
  .btn-analyze {
341
- background: linear-gradient(135deg, #004a7c, #0070b8, #00a8e8) !important;
342
- color: #fff !important; border: none !important;
343
- border-radius: var(--radius) !important;
344
- font-family: var(--font-b) !important;
345
- font-weight: 600 !important; font-size: 0.8rem !important;
346
- padding: 0 22px !important; min-height: 48px !important;
347
- box-shadow: 0 0 20px rgba(0,168,232,0.28) !important;
348
- transition: box-shadow 0.2s !important;
349
  }
350
  .btn-analyze:hover { box-shadow: 0 0 32px rgba(0,212,255,0.45) !important; }
351
 
352
  /* ══════════════════════════════════════════
353
- AUDIO — micrófono / salida
354
  ══════════════════════════════════════════ */
355
  .cv-mic .wrap,
356
  .cv-audio-out .wrap {
357
- background: rgba(4,24,46,0.6) !important;
358
- border: 1px solid var(--border) !important;
359
- border-radius: var(--radius) !important;
360
- color: var(--text-muted) !important;
361
  }
362
  .cv-mic label, .cv-audio-out label {
363
- font-family: var(--font-m) !important;
364
- font-size: 0.58rem !important;
365
- letter-spacing: 0.18em !important;
366
- color: var(--text-dim) !important;
367
  }
368
  /* ocultar el componente de audio de salida de la vista (sigue funcionando) */
369
  .cv-audio-out { visibility: hidden; height: 0; overflow: hidden; }
370
 
371
  /* ══════════════════════════════════════════
372
- FILE UPLOAD — analista PDF
373
  ══════════════════════════════════════════ */
374
  .cv-file .wrap {
375
- background: rgba(4,24,46,0.6) !important;
376
- border: 1.5px dashed rgba(0,212,255,0.22) !important;
377
- border-radius: var(--radius-lg) !important;
378
- transition: border-color 0.25s, background 0.25s !important;
379
  }
380
  .cv-file .wrap:hover {
381
- border-color: rgba(0,212,255,0.5) !important;
382
- background: rgba(0,212,255,0.05) !important;
383
  }
384
  .cv-file label {
385
- font-family: var(--font-m) !important;
386
- font-size: 0.6rem !important; letter-spacing: 0.18em !important;
387
- color: var(--text-muted) !important;
388
  }
389
 
390
  /* ══════════════════════════════════════════
391
- SEPARADORES DE FILAS
392
  ══════════════════════════════════════════ */
393
  .cv-row-input {
394
- display: flex; gap: 10px; align-items: flex-end;
395
- padding: 0 !important;
396
  }
397
  .cv-row-actions {
398
- display: flex; gap: 8px; align-items: center;
399
  }
400
 
401
  /* ══════════════════════════════════════════
402
- ESTADO DEL SISTEMA — barra inferior
403
  ══════════════════════════════════════════ */
404
  #cv-statusbar {
405
- position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
406
- font-family: var(--font-m); font-size: 0.52rem; letter-spacing: 0.18em;
407
- color: rgba(0,212,255,0.3);
408
- display: flex; align-items: center; gap: 18px;
409
- pointer-events: none; z-index: 500;
410
  }
411
  .cv-status-dot {
412
- width: 5px; height: 5px; border-radius: 50%;
413
- background: rgba(0,212,255,0.4);
414
- animation: blinkDot 2s ease-in-out infinite;
415
- display: inline-block;
416
  }
417
  @keyframes blinkDot { 0%,100%{opacity:.2} 50%{opacity:1} }
418
 
419
  /* ══════════════════════════════════════════
420
- MISCELÁNEOS GRADIO
421
  ══════════════════════════════════════════ */
422
  /* ocultar footer de Gradio */
423
  footer { display: none !important; }
@@ -427,284 +430,255 @@ footer { display: none !important; }
427
  .gap { gap: 12px !important; }
428
  /* columnas */
429
  .contain { background: transparent !important; }
 
 
 
430
  """
431
 
432
  # ════════════════════════════════════════════════════════════
433
- # HTML: HEADER + NEBULA + STATUS BAR (inyectado una sola vez)
434
  # ════════════════════════════════════════════════════════════
 
435
  HEADER_HTML = """
436
  <div id="cvision-header">
437
- <!-- Logo circular animado -->
438
- <div style="width:52px;height:52px;border-radius:50%;
439
- border:1.5px solid rgba(0,212,255,0.5);
440
- background:radial-gradient(circle,rgba(0,212,255,0.15) 0%,#04182e 100%);
441
- display:flex;align-items:center;justify-content:center;
442
- font-family:'Orbitron',monospace;font-size:0.6rem;font-weight:700;
443
- color:#00d4ff;letter-spacing:0.04em;
444
- box-shadow:0 0 20px rgba(0,212,255,0.35);
445
- position:relative;overflow:hidden;flex-shrink:0;">
446
- <span style="position:relative;z-index:1">CV</span>
447
- <div style="position:absolute;inset:-50%;width:200%;height:200%;
448
- background:conic-gradient(from 0deg,transparent 60%,rgba(0,212,255,0.2) 80%,transparent 100%);
449
- animation:spin 4s linear infinite;"></div>
450
- </div>
451
- <!-- Título -->
452
- <div style="flex:1">
453
- <div style="font-family:'Orbitron',monospace;font-size:1.45rem;font-weight:900;
454
- color:#fff;letter-spacing:0.12em;
455
- text-shadow:0 0 20px rgba(0,212,255,0.6);">
456
- C<span style="color:#00d4ff">Vision</span> Intelligence
457
- </div>
458
- <div style="font-family:'Share Tech Mono',monospace;font-size:0.58rem;
459
- letter-spacing:0.22em;color:#5a8fab;margin-top:4px;">
460
- ASISTENTE TÉCNICO MULTIMODAL · CRISTIAN VELASCO
461
- </div>
462
- </div>
463
- <!-- Badges -->
464
- <div style="display:flex;gap:8px;align-items:center">
465
- <div style="width:7px;height:7px;border-radius:50%;background:#00ff96;
466
- box-shadow:0 0 8px #00ff96;animation:blinkDot 2s ease-in-out infinite;"></div>
467
- <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
468
- letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
469
- border:1px solid rgba(0,255,150,0.3);background:rgba(0,255,150,0.07);
470
- color:#00ff96;">ONLINE</span>
471
- <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
472
- letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
473
- border:1px solid rgba(0,212,255,0.3);background:rgba(0,212,255,0.07);
474
- color:#00d4ff;">v3.1.0</span>
475
- <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
476
- letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
477
- border:1px solid rgba(0,212,255,0.3);background:rgba(0,212,255,0.07);
478
- color:#00d4ff;">NEURAL · ACTIVE</span>
479
- </div>
480
  </div>
481
  <style>
482
- @keyframes spin { to { transform: rotate(360deg); } }
483
  @keyframes blinkDot { 0%,100%{opacity:.3} 50%{opacity:1} }
484
  </style>
485
  """
486
 
487
  NEBULA_HTML = """
488
- <div id="nebula-outer" style="display:flex;justify-content:center;align-items:flex-start;
489
- gap:28px;padding:28px 32px 20px;
490
- background:linear-gradient(180deg,rgba(0,212,255,0.04) 0%,transparent 100%);
491
- border-bottom:1px solid rgba(0,212,255,0.14);">
492
 
493
- <!-- Nebula canvas con anillos -->
494
- <div id="nebula-ring-wrap" style="position:relative;width:230px;height:230px;flex-shrink:0;">
495
- <div class="nebula-deco-ring r1" style="position:absolute;inset:-20px;border-radius:50%;
496
- border:0.5px solid rgba(0,212,255,0.13);animation:spin 18s linear infinite;"></div>
497
- <div class="nebula-deco-ring r2" style="position:absolute;inset:-38px;border-radius:50%;
498
- border:0.5px dashed rgba(0,212,255,0.08);animation:spin 30s linear infinite reverse;"></div>
499
- <div id="nebula-canvas-wrap" style="width:230px;height:230px;border-radius:50%;
500
- border:1.5px solid rgba(0,212,255,0.42);
501
- background:radial-gradient(circle,rgba(0,212,255,0.08) 0%,#04182e 70%);
502
- box-shadow:0 0 50px rgba(0,212,255,0.22),inset 0 0 40px rgba(0,0,0,0.5);
503
- overflow:hidden;position:relative;z-index:2;">
504
- <canvas id="nebulaCanvas" style="width:100%;height:100%;display:block;"></canvas>
505
- </div>
506
- </div>
507
 
508
- <!-- Info hero -->
509
- <div id="nebula-info" style="display:flex;flex-direction:column;gap:12px;padding-top:10px;">
510
- <div class="hero-eyebrow" style="font-family:'Share Tech Mono',monospace;font-size:0.58rem;
511
- letter-spacing:0.3em;color:#5a8fab;text-transform:uppercase;">
512
- // SISTEMA ACTIVADO · CORE OPERATIVO
513
- </div>
514
- <div class="hero-title" style="font-family:'Orbitron',monospace;font-size:2rem;
515
- font-weight:900;line-height:1.15;color:#e8f4ff;
516
- text-shadow:0 0 30px rgba(0,212,255,0.4);">
517
- Asistente<br>
518
- <span style="color:transparent;
519
- background:linear-gradient(135deg,#00d4ff 0%,#e8f4ff 50%,#00a8e8 100%);
520
- -webkit-background-clip:text;background-clip:text;">CVision</span>
521
- </div>
522
- <div style="font-size:0.83rem;color:#5a8fab;line-height:1.7;font-weight:300;max-width:480px;">
523
- Interfaz de inteligencia artificial multimodal. Combina procesamiento de lenguaje natural,
524
- análisis de documentos y búsqueda web en un solo núcleo cognitivo.
525
- </div>
526
- <div style="display:flex;flex-wrap:wrap;gap:7px;">
527
- <span class="hero-chip" style="font-family:'Share Tech Mono',monospace;font-size:0.54rem;
528
- letter-spacing:0.12em;padding:5px 13px;border-radius:20px;
529
- border:1px solid rgba(0,212,255,0.22);background:rgba(0,212,255,0.05);color:#5a8fab;">
530
- PROCESAMIENTO NLP</span>
531
- <span class="hero-chip" style="font-family:'Share Tech Mono',monospace;font-size:0.54rem;
532
- letter-spacing:0.12em;padding:5px 13px;border-radius:20px;
533
- border:1px solid rgba(0,212,255,0.22);background:rgba(0,212,255,0.05);color:#5a8fab;">
534
- VISIÓN COMPUTACIONAL</span>
535
- <span class="hero-chip" style="font-family:'Share Tech Mono',monospace;font-size:0.54rem;
536
- letter-spacing:0.12em;padding:5px 13px;border-radius:20px;
537
- border:1px solid rgba(0,212,255,0.22);background:rgba(0,212,255,0.05);color:#5a8fab;">
538
- BÚSQUEDA WEB</span>
539
- <span class="hero-chip" style="font-family:'Share Tech Mono',monospace;font-size:0.54rem;
540
- letter-spacing:0.12em;padding:5px 13px;border-radius:20px;
541
- border:1px solid rgba(0,212,255,0.22);background:rgba(0,212,255,0.05);color:#5a8fab;">
542
- ANÁLISIS PDF</span>
543
- <span class="hero-chip" style="font-family:'Share Tech Mono',monospace;font-size:0.54rem;
544
- letter-spacing:0.12em;padding:5px 13px;border-radius:20px;
545
- border:1px solid rgba(0,212,255,0.22);background:rgba(0,212,255,0.05);color:#5a8fab;">
546
- VOZ</span>
547
- </div>
548
- </div>
549
  </div>
550
  """
551
 
552
  STATUS_BAR_HTML = """
553
  <div id="cv-statusbar">
554
- <span>CORE ACTIVE</span>
555
- <span class="cv-status-dot"></span>
556
- <span>ALL SYSTEMS NOMINAL</span>
557
- <span class="cv-status-dot" style="animation-delay:.6s"></span>
558
- <span id="cv-clock" style="min-width:64px;text-align:center;">00:00:00</span>
559
- <span class="cv-status-dot" style="animation-delay:1.2s"></span>
560
- <span>SCANNING</span>
561
  </div>
562
  """
563
 
564
  # ════════════════════════════════════════════════════════════
565
- # JAVASCRIPT: Nebula neural + Reloj + partículas de fondo
566
  # ════════════════════════════════════════════════════════════
 
567
  NEBULA_JS = """
568
  <script>
569
  (function waitForCanvas() {
570
- const cv = document.getElementById('nebulaCanvas');
571
- if (!cv) { setTimeout(waitForCanvas, 300); return; }
572
- initNebula(cv);
573
  })();
574
 
575
  function initNebula(cv) {
576
- const ctx = cv.getContext('2d');
577
- let W, H, cx, cy, neurons = [], pulses = [], synapses = [], pulseTimer = 0;
578
- const N = 44, CONN = 72;
579
-
580
- function resize() {
581
- W = cv.width = cv.offsetWidth || 230;
582
- H = cv.height = cv.offsetHeight || 230;
583
- cx = W / 2; cy = H / 2;
584
- build();
585
- }
586
-
587
- class Neuron {
588
- constructor(i) {
589
- this.layer = 1 + (i % 3);
590
- this.angle = Math.random() * Math.PI * 2;
591
- const spread = Math.min(W, H) * 0.46;
592
- this.baseR = spread * (0.14 + this.layer * 0.2 + Math.random() * 0.07);
593
- this.speed = (Math.random() < .5 ? 1 : -1) * (.001 + Math.random() * .0028);
594
- this.osc = 3 + Math.random() * 9;
595
- this.t = Math.random() * 100;
596
- this.r = 1.3 + Math.random() * 1.8;
597
- this.alpha = .5 + Math.random() * .5;
598
- this.firing = 0;
599
- this.fireTimer = Math.random() * 160;
600
- this.x = cx; this.y = cy;
601
- this._step();
602
- }
603
- _step() {
604
- this.t += .016; this.angle += this.speed;
605
- const r = this.baseR + Math.sin(this.t) * this.osc;
606
- this.x = cx + Math.cos(this.angle) * r;
607
- this.y = cy + Math.sin(this.angle) * r;
608
- this.fireTimer--;
609
- if (this.fireTimer <= 0) { this.firing = 1; this.fireTimer = 65 + Math.random() * 170; }
610
- if (this.firing > 0) this.firing = Math.max(0, this.firing - .032);
611
- }
612
- draw() {
613
- ctx.globalAlpha = this.alpha * (.5 + this.firing * .5);
614
- ctx.strokeStyle = `rgba(0,${160 + Math.round(this.firing * 95)},255,${.3 + this.firing * .5})`;
615
- ctx.lineWidth = .6;
616
- ctx.beginPath(); ctx.arc(this.x, this.y, this.r + 2.2, 0, Math.PI * 2); ctx.stroke();
617
- ctx.fillStyle = this.firing > .3 ? `rgba(255,255,255,${this.firing})` : 'rgba(0,200,255,.9)';
618
- ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fill();
619
- ctx.globalAlpha = 1;
620
- }
621
- }
622
-
623
- class Pulse {
624
- constructor(a, b) { this.a = a; this.b = b; this.t = 0; this.s = .013 + Math.random() * .016; this.done = false; }
625
- tick() { this.t += this.s; if (this.t >= 1) { this.done = true; this.b.firing = 1; } }
626
- draw() {
627
- const x = this.a.x + (this.b.x - this.a.x) * this.t;
628
- const y = this.a.y + (this.b.y - this.a.y) * this.t;
629
- ctx.globalAlpha = 1 - this.t * .4;
630
- ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(x, y, 2, 0, Math.PI * 2); ctx.fill();
631
- const tx = this.a.x + (this.b.x - this.a.x) * Math.max(0, this.t - .07);
632
- const ty = this.a.y + (this.b.y - this.a.y) * Math.max(0, this.t - .07);
633
- const g = ctx.createLinearGradient(tx, ty, x, y);
634
- g.addColorStop(0, 'rgba(0,200,255,0)'); g.addColorStop(1, 'rgba(0,220,255,.55)');
635
- ctx.strokeStyle = g; ctx.lineWidth = 1.2; ctx.globalAlpha = .65;
636
- ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(x, y); ctx.stroke();
637
- ctx.globalAlpha = 1;
638
- }
639
- }
640
-
641
- function build() {
642
- neurons = []; pulses = []; synapses = [];
643
- for (let i = 0; i < N; i++) neurons.push(new Neuron(i));
644
- for (let i = 0; i < neurons.length; i++) {
645
- let added = 0;
646
- for (let j = i + 1; j < neurons.length; j++) {
647
- const dx = neurons[i].x - neurons[j].x, dy = neurons[i].y - neurons[j].y;
648
- if (Math.sqrt(dx*dx + dy*dy) < CONN && added < 4) { synapses.push([i, j]); added++; }
649
- }
650
- }
651
- }
652
-
653
- function drawSynapses() {
654
- for (const s of synapses) {
655
- const a = neurons[s[0]], b = neurons[s[1]];
656
- const dx = a.x - b.x, dy = a.y - b.y, d = Math.sqrt(dx*dx + dy*dy);
657
- const fade = 1 - d / CONN, fire = (a.firing + b.firing) * .5;
658
- ctx.globalAlpha = fade * (.06 + fire * .24);
659
- ctx.strokeStyle = `rgba(0,${150 + Math.round(fire * 105)},255,1)`;
660
- ctx.lineWidth = .4 + fire * .65;
661
- ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
662
- }
663
- ctx.globalAlpha = 1;
664
- }
665
-
666
- function drawLogo() {
667
- const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, 50);
668
- g.addColorStop(0, 'rgba(0,200,255,.14)'); g.addColorStop(1, 'rgba(0,200,255,0)');
669
- ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, 50, 0, Math.PI * 2); ctx.fill();
670
- ctx.font = "bold 19px 'Orbitron',monospace";
671
- ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
672
- ctx.shadowBlur = 10; ctx.shadowColor = 'rgba(0,212,255,.8)';
673
- const tg = ctx.createLinearGradient(cx - 36, 0, cx + 36, 0);
674
- tg.addColorStop(0, '#fff'); tg.addColorStop(1, '#00d4ff');
675
- ctx.fillStyle = tg; ctx.fillText('CVision', cx, cy);
676
- ctx.shadowBlur = 0;
677
- }
678
-
679
- function loop() {
680
- requestAnimationFrame(loop);
681
- ctx.clearRect(0, 0, W, H);
682
- for (const n of neurons) n._step();
683
- drawSynapses();
684
- for (const n of neurons) n.draw();
685
- pulseTimer++;
686
- if (pulseTimer % 22 === 0 && synapses.length) {
687
- const s = synapses[Math.floor(Math.random() * synapses.length)];
688
- const [ai, bi] = Math.random() < .5 ? [s[0], s[1]] : [s[1], s[0]];
689
- pulses.push(new Pulse(neurons[ai], neurons[bi]));
690
- neurons[ai].firing = 1;
691
- }
692
- pulses = pulses.filter(p => !p.done);
693
- for (const p of pulses) { p.tick(); p.draw(); }
694
- drawLogo();
695
- }
696
-
697
- window.addEventListener('resize', resize, { passive: true });
698
- resize();
699
- loop();
 
 
700
  }
701
 
702
  /* ── Reloj en tiempo real ── */
703
  function updateClock() {
704
- const el = document.getElementById('cv-clock');
705
- if (!el) return;
706
- const n = new Date(), p = x => String(x).padStart(2, '0');
707
- el.textContent = p(n.getHours()) + ':' + p(n.getMinutes()) + ':' + p(n.getSeconds());
708
  }
709
  setInterval(updateClock, 1000);
710
  updateClock();
@@ -712,324 +686,257 @@ updateClock();
712
  """
713
 
714
  # ════════════════════════════════════════════════════════════
715
- # LIMPIEZA DE TEXTO (sin cambios de lógica)
716
  # ════════════════════════════════════════════════════════════
717
- def robust_cleaner(data):
718
- if data is None:
719
- return ""
720
- if isinstance(data, (list, tuple)):
721
- if len(data) > 0:
722
- last_entry = data[-1]
723
- if isinstance(last_entry, (list, tuple)) and len(last_entry) == 2:
724
- data = last_entry[1]
725
- else:
726
- data = str(last_entry)
727
- else:
728
- return ""
729
-
730
- text = str(data)
731
- text = text.replace("], '", "").replace("['", "").replace("']", "").replace("],", "")
732
- text = re.sub(r"<generator object.*?>", "", text)
733
- if "]," in text or "', '" in text:
734
- parts = re.split(r"'],|',|\[", text)
735
- text = parts[-1]
736
- text = text.replace("(['", "").replace("'])", "")
737
- text = text.replace('\\n', '\n').strip("[]()', \"")
738
- text = re.sub(r"/tmp/\S+\.(mp3|wav|png|jpg)", "", text)
739
- text = text.replace("boxed", "")
740
- return text.strip()
741
 
742
-
743
- # ════════════════════════════════════════════════════════════
744
- # MANEJADORES DE CHAT (lógica original sin cambios)
745
- # ════════════════════════════════════════════════════════════
746
- def chat_engine_handler(history, message, mode, voice_enabled=False, pdf_file=None):
747
- if not message or message.strip() == "":
748
- return history, "", None
749
-
750
- engines = {
751
- "general": regular_chat,
752
- "web": browser_chat,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  "productividad": productivity_chat,
754
- "cientifico": scientist_chat,
755
- "pdf": document_chat,
756
  }
757
- selected_engine = engines.get(mode, regular_chat)
758
-
 
759
  try:
760
- if mode == "pdf" and pdf_file:
761
- response = selected_engine(history, message, pdf_file)
 
 
762
  else:
763
- response = selected_engine(history, message)
764
-
765
- final_text = ""
766
- if hasattr(response, "__iter__") and not isinstance(response, (list, tuple, str)):
767
- for chunk in response:
768
- if isinstance(chunk, list):
769
- final_text = chunk[-1][1]
 
 
770
  else:
771
- final_text = str(chunk)
772
  else:
773
- final_text = response
774
-
775
- clean_reply = robust_cleaner(final_text)
776
- if len(clean_reply) <= 1:
777
- clean_reply = "Disculpa, no pude procesar esa respuesta correctamente. ¿Podrías intentar de nuevo?"
778
-
779
- history.append((message, clean_reply))
780
-
781
- audio_path = None
 
 
 
 
 
 
 
 
 
 
782
  if voice_enabled:
783
- voice_text = clean_reply.replace("*", "").replace("#", "").replace("`", "")
784
- audio_path = speak(voice_text[:450])
785
-
786
- return history, "", audio_path
787
 
 
 
788
  except Exception as e:
789
- print(f"CRITICAL ERROR EN CVISION: {e}")
790
- history.append((message, f"Error del sistema: {str(e)}"))
791
- return history, "", None
792
-
793
-
794
- def transcribe_processor(audio):
795
- if audio is None:
796
- return ""
797
- text = transcribe_audio_file(audio)
798
- return text if text else ""
799
-
800
-
801
- # ════════════════════════════════════════════════════════════
802
- # INTERFAZ GRADIO
803
- # ════════════════════════════════════════════════════════════
804
- with gr.Blocks(
805
- css=CUSTOM_CSS,
806
- title="CVision Intelligence",
807
- theme=gr.themes.Base(
808
- primary_hue="cyan",
809
- neutral_hue="slate",
810
- font=gr.themes.GoogleFont("Exo 2"),
811
- ),
812
- ) as assistant:
813
-
814
- # ── HTML estático: Header, Nebula, StatusBar, JS ──────
815
- gr.HTML(HEADER_HTML)
816
- gr.HTML(NEBULA_HTML)
817
- gr.HTML(STATUS_BAR_HTML)
818
- gr.HTML(NEBULA_JS)
819
-
820
- # ── Tabs principales ──────────────────────────────────
821
- with gr.Tabs(elem_classes="tab-nav"):
822
-
823
- # ══════════ TAB 1: GENERAL ══════════
824
- with gr.Tab("💬 General"):
825
- chatbot_general = gr.Chatbot(
826
- height=500,
827
- bubble_full_width=False,
828
- show_label=False,
829
- elem_classes="chatbot-wrap",
830
- avatar_images=("assets/user_avatar.png", "assets/CVision logo.png"),
831
- )
832
- out_audio_general = gr.Audio(
833
- visible=False, autoplay=True,
834
- elem_classes="cv-audio-out",
835
- )
836
- with gr.Row():
837
- input_general = gr.Textbox(
838
- placeholder=PLACEHOLDER,
839
- show_label=False,
840
- container=False,
841
- lines=1,
842
- max_lines=4,
843
- scale=8,
844
- elem_classes="cv-input",
845
- )
846
- btn_voice_gen = gr.Button("🎙 Voz", scale=1, elem_classes="btn-voice")
847
- btn_send_gen = gr.Button("Enviar ↗", scale=1, elem_classes="btn-send")
848
-
849
- with gr.Row():
850
- mic_general = gr.Audio(
851
- sources=["microphone"],
852
- type="filepath",
853
- label="🎤 TRANSCRIPCIÓN DE VOZ",
854
- scale=6,
855
- elem_classes="cv-mic",
856
- )
857
- btn_clear_gen = gr.Button("🗑 Limpiar", scale=2, elem_classes="btn-clear")
858
-
859
- # ── Eventos ──
860
- mic_general.stop_recording(transcribe_processor, [mic_general], [input_general])
861
-
862
- btn_send_gen.click(
863
- chat_engine_handler,
864
- [chatbot_general, input_general, gr.State("general"), gr.State(False)],
865
- [chatbot_general, input_general, out_audio_general],
866
- )
867
- input_general.submit(
868
- chat_engine_handler,
869
- [chatbot_general, input_general, gr.State("general"), gr.State(False)],
870
- [chatbot_general, input_general, out_audio_general],
871
- )
872
- btn_voice_gen.click(
873
- chat_engine_handler,
874
- [chatbot_general, input_general, gr.State("general"), gr.State(True)],
875
- [chatbot_general, input_general, out_audio_general],
876
- )
877
- btn_clear_gen.click(
878
- lambda: ([], "", None),
879
- None,
880
- [chatbot_general, input_general, out_audio_general],
881
- )
882
-
883
- # ══════════ TAB 2: NAVEGACIÓN WEB ══════════
884
- with gr.Tab("🌐 Navegación Web"):
885
- chatbot_web = gr.Chatbot(
886
- height=500, bubble_full_width=False,
887
- show_label=False, elem_classes="chatbot-wrap",
888
- avatar_images=("assets/user_avatar.png", "assets/CVision logo.png"),
889
- )
890
- out_audio_web = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
891
- with gr.Row():
892
- input_web = gr.Textbox(
893
- placeholder="Busca algo en internet...",
894
- show_label=False, container=False,
895
- lines=1, max_lines=4, scale=8,
896
- elem_classes="cv-input",
897
- )
898
- btn_voice_web = gr.Button("🎙 Voz", scale=1, elem_classes="btn-voice")
899
- btn_send_web = gr.Button("Buscar ↗", scale=1, elem_classes="btn-send")
900
- with gr.Row():
901
- mic_web = gr.Audio(sources=["microphone"], type="filepath",
902
- label="🎤 TRANSCRIPCIÓN DE VOZ", scale=6, elem_classes="cv-mic")
903
- btn_clear_web = gr.Button("🗑 Limpiar", scale=2, elem_classes="btn-clear")
904
-
905
- mic_web.stop_recording(transcribe_processor, [mic_web], [input_web])
906
- btn_send_web.click(chat_engine_handler,
907
- [chatbot_web, input_web, gr.State("web"), gr.State(False)],
908
- [chatbot_web, input_web, out_audio_web])
909
- input_web.submit(chat_engine_handler,
910
- [chatbot_web, input_web, gr.State("web"), gr.State(False)],
911
- [chatbot_web, input_web, out_audio_web])
912
- btn_voice_web.click(chat_engine_handler,
913
- [chatbot_web, input_web, gr.State("web"), gr.State(True)],
914
- [chatbot_web, input_web, out_audio_web])
915
- btn_clear_web.click(lambda: ([], "", None), None,
916
- [chatbot_web, input_web, out_audio_web])
917
-
918
- # ══════════ TAB 3: PRODUCTIVIDAD ══════════
919
- with gr.Tab("📊 Productividad"):
920
- chatbot_prod = gr.Chatbot(
921
- height=500, bubble_full_width=False,
922
- show_label=False, elem_classes="chatbot-wrap",
923
- avatar_images=("assets/user_avatar.png", "assets/CVision logo.png"),
924
- )
925
- out_audio_prod = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
926
- with gr.Row():
927
- input_prod = gr.Textbox(
928
- placeholder="¿Qué tarea quieres optimizar?",
929
- show_label=False, container=False,
930
- lines=1, max_lines=4, scale=8,
931
- elem_classes="cv-input",
932
- )
933
- btn_voice_prod = gr.Button("🎙 Voz", scale=1, elem_classes="btn-voice")
934
- btn_send_prod = gr.Button("Enviar ↗", scale=1, elem_classes="btn-send")
935
- with gr.Row():
936
- mic_prod = gr.Audio(sources=["microphone"], type="filepath",
937
- label="🎤 TRANSCRIPCIÓN DE VOZ", scale=6, elem_classes="cv-mic")
938
- btn_clear_prod = gr.Button("🗑 Limpiar", scale=2, elem_classes="btn-clear")
939
-
940
- mic_prod.stop_recording(transcribe_processor, [mic_prod], [input_prod])
941
- btn_send_prod.click(chat_engine_handler,
942
- [chatbot_prod, input_prod, gr.State("productividad"), gr.State(False)],
943
- [chatbot_prod, input_prod, out_audio_prod])
944
- input_prod.submit(chat_engine_handler,
945
- [chatbot_prod, input_prod, gr.State("productividad"), gr.State(False)],
946
- [chatbot_prod, input_prod, out_audio_prod])
947
- btn_voice_prod.click(chat_engine_handler,
948
- [chatbot_prod, input_prod, gr.State("productividad"), gr.State(True)],
949
- [chatbot_prod, input_prod, out_audio_prod])
950
- btn_clear_prod.click(lambda: ([], "", None), None,
951
- [chatbot_prod, input_prod, out_audio_prod])
952
-
953
- # ══════════ TAB 4: CIENTÍFICO ══════════
954
- with gr.Tab("🔬 Análisis Científico"):
955
- chatbot_sci = gr.Chatbot(
956
- height=500, bubble_full_width=False,
957
- show_label=False, elem_classes="chatbot-wrap",
958
- avatar_images=("assets/user_avatar.png", "assets/CVision logo.png"),
959
- )
960
- out_audio_sci = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
961
- with gr.Row():
962
- input_sci = gr.Textbox(
963
- placeholder="Ingresa tu consulta científica o fórmula...",
964
- show_label=False, container=False,
965
- lines=1, max_lines=4, scale=8,
966
- elem_classes="cv-input",
967
- )
968
- btn_voice_sci = gr.Button("🎙 Voz", scale=1, elem_classes="btn-voice")
969
- btn_send_sci = gr.Button("Analizar ↗", scale=1, elem_classes="btn-send")
970
- with gr.Row():
971
- mic_sci = gr.Audio(sources=["microphone"], type="filepath",
972
- label="🎤 TRANSCRIPCIÓN DE VOZ", scale=6, elem_classes="cv-mic")
973
- btn_clear_sci = gr.Button("🗑 Limpiar", scale=2, elem_classes="btn-clear")
974
-
975
- mic_sci.stop_recording(transcribe_processor, [mic_sci], [input_sci])
976
- btn_send_sci.click(chat_engine_handler,
977
- [chatbot_sci, input_sci, gr.State("cientifico"), gr.State(False)],
978
- [chatbot_sci, input_sci, out_audio_sci])
979
- input_sci.submit(chat_engine_handler,
980
- [chatbot_sci, input_sci, gr.State("cientifico"), gr.State(False)],
981
- [chatbot_sci, input_sci, out_audio_sci])
982
- btn_voice_sci.click(chat_engine_handler,
983
- [chatbot_sci, input_sci, gr.State("cientifico"), gr.State(True)],
984
- [chatbot_sci, input_sci, out_audio_sci])
985
- btn_clear_sci.click(lambda: ([], "", None), None,
986
- [chatbot_sci, input_sci, out_audio_sci])
987
-
988
- # ══════════ TAB 5: ANALISTA PDF ══════════
989
- with gr.Tab("📄 Analista PDF"):
990
- file_input = gr.File(
991
- label="📂 CARGAR DOCUMENTO PDF",
992
- file_types=[".pdf"],
993
- elem_classes="cv-file",
994
- )
995
- chatbot_pdf = gr.Chatbot(
996
- height=440, bubble_full_width=False,
997
- show_label=False, elem_classes="chatbot-wrap",
998
- avatar_images=("assets/user_avatar.png", "assets/CVision logo.png"),
999
- )
1000
- out_audio_pdf = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
1001
- with gr.Row():
1002
- input_pdf = gr.Textbox(
1003
- placeholder="Pregunta algo sobre el documento cargado...",
1004
- show_label=False, container=False,
1005
- lines=1, max_lines=4, scale=8,
1006
- elem_classes="cv-input",
1007
- )
1008
- btn_voice_pdf = gr.Button("🎙 Voz", scale=1, elem_classes="btn-voice")
1009
- btn_send_pdf = gr.Button("Analizar ↗", scale=1, elem_classes="btn-analyze")
1010
- with gr.Row():
1011
- mic_pdf = gr.Audio(sources=["microphone"], type="filepath",
1012
- label="🎤 TRANSCRIPCIÓN DE VOZ", scale=6, elem_classes="cv-mic")
1013
- btn_clear_pdf = gr.Button("🗑 Limpiar", scale=2, elem_classes="btn-clear")
1014
-
1015
- mic_pdf.stop_recording(transcribe_processor, [mic_pdf], [input_pdf])
1016
- btn_send_pdf.click(chat_engine_handler,
1017
- [chatbot_pdf, input_pdf, gr.State("pdf"), gr.State(False), file_input],
1018
- [chatbot_pdf, input_pdf, out_audio_pdf])
1019
- input_pdf.submit(chat_engine_handler,
1020
- [chatbot_pdf, input_pdf, gr.State("pdf"), gr.State(False), file_input],
1021
- [chatbot_pdf, input_pdf, out_audio_pdf])
1022
- btn_voice_pdf.click(chat_engine_handler,
1023
- [chatbot_pdf, input_pdf, gr.State("pdf"), gr.State(True), file_input],
1024
- [chatbot_pdf, input_pdf, out_audio_pdf])
1025
- btn_clear_pdf.click(lambda: ([], "", None), None,
1026
- [chatbot_pdf, input_pdf, out_audio_pdf])
1027
-
1028
- # ════════════════════════════════════════════════════════════
1029
- # LANZAMIENTO
1030
- # ════════════════════════════════════════════════════════════
1031
  if __name__ == "__main__":
 
1032
  assistant.launch(
1033
  show_error=True,
1034
- favicon_path="assets/CVision logo.png",
1035
  )
 
3
  import os
4
  import time
5
  import json
6
+ from datetime import datetime
7
  from modules.listen import transcribe_audio_file
8
  from modules.talker.talk import speak
9
 
 
14
  browser_chat,
15
  scientist_chat,
16
  regular_chat,
17
+ document_chat
18
  )
19
  except ImportError:
20
+ print("Error: No se pudieron importar los módulos de chat. Asegúrate de que 'modules' esté en el path.")
21
 
22
  # ════════════════════════════════════════════════════════════
23
+ # CSS FUTURISTA — Diamante × Cyan (Fusionado y Adaptado)
 
 
 
 
 
24
  # ════════════════════════════════════════════════════════════
25
  CUSTOM_CSS = """
26
  /* ── Google Fonts ── */
 
28
 
29
  /* ── Variables globales ── */
30
  :root {
31
+ --c0: #000509;
32
+ --c1: #020c18;
33
+ --c2: #04182e;
34
+ --cyan: #00d4ff;
35
+ --cyan2: #00a8e8;
36
+ --cyan-dim: rgba(0,212,255,0.10);
37
+ --diamond: #e8f4ff;
38
+ --diamond2: #b8d8f0;
39
+ --text-main: #cce9f8;
40
+ --text-muted: #5a8fab;
41
+ --text-dim: #2a4a60;
42
+ --border: rgba(0,212,255,0.16);
43
+ --border-bright: rgba(0,212,255,0.45);
44
+ --glass: rgba(4,24,46,0.78);
45
+ --glass2: rgba(2,12,24,0.90);
46
+ --radius: 12px;
47
+ --radius-lg: 20px;
48
+ --font-d: 'Orbitron', monospace;
49
+ --font-b: 'Exo 2', sans-serif;
50
+ --font-m: 'Share Tech Mono', monospace;
51
  }
52
 
53
  /* ── Reset base ── */
54
  *, *::before, *::after { box-sizing: border-box; }
55
  body, .gradio-container {
56
+ background: var(--c0) !important;
57
+ color: var(--text-main) !important;
58
+ font-family: var(--font-b) !important;
59
+ min-height: 100vh;
60
+ margin: 0 !important;
61
  }
62
 
63
  /* scrollbar */
 
67
 
68
  /* ── Grid de fondo ── */
69
  .gradio-container::before {
70
+ content: '';
71
+ position: fixed; inset: 0; z-index: 0; pointer-events: none;
72
+ background-image:
73
+ linear-gradient(rgba(0,212,255,0.028) 1px, transparent 1px),
74
+ linear-gradient(90deg, rgba(0,212,255,0.028) 1px, transparent 1px);
75
+ background-size: 44px 44px;
76
+ mask-image: radial-gradient(ellipse 80% 80% at 50% 50%, black 0%, transparent 100%);
77
  }
78
 
79
  /* ── Scanline animado ── */
80
  .gradio-container::after {
81
+ content: '';
82
+ position: fixed; top: 0; left: 0; width: 100%; height: 2px;
83
+ background: linear-gradient(90deg, transparent, rgba(0,212,255,0.3), transparent);
84
+ animation: scanDown 7s ease-in-out infinite;
85
+ z-index: 9999; pointer-events: none;
86
  }
87
  @keyframes scanDown {
88
+ 0% { top: -2px; opacity: 0; }
89
+ 8% { opacity: 1; }
90
+ 92% { opacity: .4; }
91
+ 100% { top: 100vh; opacity: 0; }
92
  }
93
 
94
  /* ══════════════════════════════════════════
95
+ HEADER / TÍTULO PRINCIPAL (Imagen 7)
96
  ══════════════════════════════════��═══════ */
97
  #cvision-header {
98
+ background: var(--glass2);
99
+ border-bottom: 1px solid var(--border);
100
+ padding: 18px 32px;
101
+ display: flex;
102
+ align-items: center;
103
+ gap: 18px;
104
+ position: sticky; top: 0; z-index: 100;
105
+ backdrop-filter: blur(20px);
106
+ width: 100%;
107
  }
108
 
109
+ /* ══════════════════════════════════════════
110
+ NEBULA HERO SECTION (Imagen 8)
111
+ ══════════════════════════════════════════ */
112
  #nebula-outer {
113
+ display: flex;
114
+ justify-content: center;
115
+ align-items: flex-start;
116
+ gap: 28px;
117
+ padding: 28px 32px 20px;
118
+ background: linear-gradient(180deg, rgba(0,212,255,0.04) 0%, transparent 100%);
119
+ border-bottom: 1px solid var(--border);
120
  }
121
+
122
  #nebula-ring-wrap {
123
+ position: relative;
124
+ width: 230px; height: 230px;
125
+ flex-shrink: 0;
126
  }
127
  #nebula-canvas-wrap {
128
+ width: 230px; height: 230px;
129
+ border-radius: 50%;
130
+ border: 1.5px solid rgba(0,212,255,0.4);
131
+ background: radial-gradient(circle, rgba(0,212,255,0.08) 0%, #04182e 70%);
132
+ box-shadow: 0 0 50px rgba(0,212,255,0.22), inset 0 0 40px rgba(0,0,0,0.5);
133
+ overflow: hidden;
134
+ position: relative; z-index: 2;
135
  }
136
  #nebulaCanvas { width: 100%; height: 100%; display: block; }
137
 
138
  /* anillos externos decorativos */
139
  .nebula-deco-ring {
140
+ position: absolute; border-radius: 50%; pointer-events: none;
141
+ border: 0.5px solid rgba(0,212,255,0.13);
142
  }
143
  .nebula-deco-ring.r1 { inset: -20px; animation: spin 18s linear infinite; }
144
  .nebula-deco-ring.r2 { inset: -38px; border-style: dashed; animation: spin 30s linear infinite reverse; }
 
146
 
147
  /* hero info al lado de la nebula */
148
  #nebula-info {
149
+ display: flex; flex-direction: column; gap: 12px;
150
+ padding: 10px 0 0 0; max-width: 540px;
151
  }
152
  .hero-eyebrow {
153
+ font-family: var(--font-m); font-size: 0.58rem;
154
+ letter-spacing: 0.3em; color: var(--text-muted);
155
+ text-transform: uppercase;
156
  }
157
  .hero-title {
158
+ font-family: var(--font-d); font-size: 2.1rem;
159
+ font-weight: 900; line-height: 1.15;
160
+ color: var(--diamond);
161
+ text-shadow: 0 0 30px rgba(0,212,255,0.4);
162
  }
163
  .hero-title .accent {
164
+ color: transparent;
165
+ background: linear-gradient(135deg, #00d4ff 0%, #e8f4ff 50%, #00a8e8 100%);
166
+ -webkit-background-clip: text; background-clip: text;
167
  }
168
  .hero-desc {
169
+ font-size: 0.83rem; color: var(--text-muted);
170
+ line-height: 1.7; font-weight: 300;
171
  }
172
  .hero-chips { display: flex; flex-wrap: wrap; gap: 7px; }
173
  .hero-chip {
174
+ font-family: var(--font-m); font-size: 0.54rem;
175
+ letter-spacing: 0.12em; padding: 5px 13px;
176
+ border-radius: 20px; border: 1px solid rgba(0,212,255,0.22);
177
+ background: rgba(0,212,255,0.05); color: var(--text-muted);
178
  }
179
 
180
  /* ══════════════════════════════════════════
181
+ TABS — barra de navegación principal
182
  ══════════════════════════════════════════ */
183
  .tab-nav {
184
+ background: var(--glass2) !important;
185
+ border-bottom: 1px solid var(--border) !important;
186
+ backdrop-filter: blur(10px);
187
+ padding: 0 20px !important;
188
+ gap: 0 !important;
189
  }
190
  .tab-nav button {
191
+ font-family: var(--font-b) !important;
192
+ font-size: 0.8rem !important;
193
+ font-weight: 500 !important;
194
+ letter-spacing: 0.05em !important;
195
+ color: var(--text-muted) !important;
196
+ background: transparent !important;
197
+ border: none !important;
198
+ border-bottom: 2px solid transparent !important;
199
+ border-radius: 0 !important;
200
+ padding: 14px 22px !important;
201
+ transition: color 0.2s, border-color 0.2s !important;
202
  }
203
  .tab-nav button:hover { color: var(--diamond2) !important; }
204
  .tab-nav button.selected {
205
+ color: var(--cyan) !important;
206
+ border-bottom-color: var(--cyan) !important;
207
+ background: transparent !important;
208
  }
209
 
210
  /* ══════════════════════════════════════════
211
+ CHATBOT — ventana de mensajes (Imagen 9)
212
  ══════════════════════════════════════════ */
213
  .chatbot-wrap .wrap {
214
+ background: rgba(4,24,46,0.78) !important;
215
+ border: 1px solid var(--border) !important;
216
+ border-radius: var(--radius-lg) !important;
217
+ backdrop-filter: blur(12px) !important;
218
+ box-shadow: inset 0 0 40px rgba(0,0,0,0.3), 0 0 30px rgba(0,212,255,0.08) !important;
219
  }
220
  /* burbujas bot */
221
  .chatbot-wrap .message.bot,
222
  .chatbot-wrap [data-testid="bot"] {
223
+ background: linear-gradient(135deg, rgba(4,24,46,0.92), rgba(6,29,54,0.88)) !important;
224
+ border: 1px solid rgba(0,212,255,0.14) !important;
225
+ border-radius: 4px 18px 18px 18px !important;
226
+ color: var(--text-main) !important;
227
+ font-family: var(--font-b) !important;
228
+ font-size: 0.85rem !important;
229
+ box-shadow: 0 4px 18px rgba(0,0,0,0.3) !important;
230
+ padding: 13px 17px !important;
231
+ margin-right: 12% !important;
232
  }
233
  /* burbujas usuario */
234
  .chatbot-wrap .message.user,
235
  .chatbot-wrap [data-testid="user"] {
236
+ background: linear-gradient(135deg, rgba(0,70,120,0.72), rgba(0,50,100,0.82)) !important;
237
+ border: 1px solid rgba(0,160,230,0.22) !important;
238
+ border-radius: 18px 4px 18px 18px !important;
239
+ color: var(--diamond) !important;
240
+ font-family: var(--font-b) !important;
241
+ font-size: 0.85rem !important;
242
+ box-shadow: 0 4px 18px rgba(0,0,0,0.3) !important;
243
+ padding: 13px 17px !important;
244
+ margin-left: 12% !important;
245
  }
246
 
247
  /* ══════════════════════════════════════════
248
+ TEXTBOX — campo de entrada
249
  ══════════════════════════════════════════ */
250
  .cv-input textarea,
251
  .cv-input input[type="text"] {
252
+ background: rgba(4,24,46,0.82) !important;
253
+ border: 1px solid rgba(0,212,255,0.18) !important;
254
+ border-radius: var(--radius) !important;
255
+ color: var(--text-main) !important;
256
+ font-family: var(--font-b) !important;
257
+ font-size: 0.85rem !important;
258
+ padding: 13px 16px !important;
259
+ transition: border-color 0.2s, box-shadow 0.2s !important;
260
+ caret-color: var(--cyan) !important;
261
+ resize: none !important;
262
  }
263
  .cv-input textarea::placeholder,
264
  .cv-input input::placeholder {
265
+ color: var(--text-dim) !important;
266
+ font-family: var(--font-m) !important;
267
+ font-size: 0.72rem !important;
268
+ letter-spacing: 0.08em !important;
269
  }
270
  .cv-input textarea:focus,
271
  .cv-input input:focus {
272
+ border-color: rgba(0,212,255,0.48) !important;
273
+ box-shadow: 0 0 18px rgba(0,212,255,0.1) !important;
274
+ outline: none !important;
275
  }
276
  /* quitar el borde/label contenedor por defecto de Gradio */
277
  .cv-input > .wrap { border: none !important; background: transparent !important; box-shadow: none !important; }
278
  .cv-input label { display: none !important; }
279
 
280
  /* ══════════════════════════════════════════
281
+ BOTONES (Imagen 10)
282
  ══════════════════════════════════════════ */
283
 
284
  /* Enviar — primario cyan */
285
  .btn-send {
286
+ background: linear-gradient(135deg, #004a7c, #0070b8, #00a8e8) !important;
287
+ color: #fff !important;
288
+ border: none !important;
289
+ border-radius: var(--radius) !important;
290
+ font-family: var(--font-b) !important;
291
+ font-weight: 600 !important;
292
+ font-size: 0.8rem !important;
293
+ letter-spacing: 0.08em !important;
294
+ padding: 0 22px !important;
295
+ min-height: 48px !important;
296
+ box-shadow: 0 0 20px rgba(0,168,232,0.28), inset 0 1px 0 rgba(255,255,255,0.12) !important;
297
+ transition: box-shadow 0.2s, transform 0.15s !important;
298
  }
299
  .btn-send:hover {
300
+ box-shadow: 0 0 32px rgba(0,212,255,0.45) !important;
301
  }
302
  .btn-send:active { transform: scale(0.97) !important; }
303
 
304
  /* Voz — borde cyan */
305
  .btn-voice {
306
+ background: transparent !important;
307
+ border: 1px solid rgba(0,212,255,0.32) !important;
308
+ color: var(--cyan) !important;
309
+ border-radius: var(--radius) !important;
310
+ font-family: var(--font-b) !important;
311
+ font-weight: 500 !important;
312
+ font-size: 0.78rem !important;
313
+ letter-spacing: 0.06em !important;
314
+ min-height: 48px !important;
315
+ padding: 0 18px !important;
316
+ transition: all 0.2s !important;
317
  }
318
  .btn-voice:hover {
319
+ background: var(--cyan-dim) !important;
320
+ border-color: var(--border-bright) !important;
321
+ box-shadow: 0 0 14px rgba(0,212,255,0.2) !important;
322
  }
323
 
324
  /* Limpiar — rojo apagado */
325
  .btn-clear {
326
+ background: transparent !important;
327
+ border: 1px solid rgba(255,60,80,0.2) !important;
328
+ color: rgba(255,100,120,0.65) !important;
329
+ border-radius: var(--radius) !important;
330
+ font-family: var(--font-b) !important;
331
+ font-size: 0.75rem !important;
332
+ min-height: 40px !important;
333
+ padding: 0 16px !important;
334
+ transition: all 0.2s !important;
335
  }
336
  .btn-clear:hover {
337
+ border-color: rgba(255,60,80,0.45) !important;
338
+ background: rgba(255,60,80,0.06) !important;
339
+ color: #ff6477 !important;
340
  }
341
 
342
  /* Analizar PDF */
343
  .btn-analyze {
344
+ background: linear-gradient(135deg, #004a7c, #0070b8, #00a8e8) !important;
345
+ color: #fff !important; border: none !important;
346
+ border-radius: var(--radius) !important;
347
+ font-family: var(--font-b) !important;
348
+ font-weight: 600 !important; font-size: 0.8rem !important;
349
+ padding: 0 22px !important; min-height: 48px !important;
350
+ box-shadow: 0 0 20px rgba(0,168,232,0.28) !important;
351
+ transition: box-shadow 0.2s !important;
352
  }
353
  .btn-analyze:hover { box-shadow: 0 0 32px rgba(0,212,255,0.45) !important; }
354
 
355
  /* ══════════════════════════════════════════
356
+ AUDIO — micrófono / salida
357
  ══════════════════════════════════════════ */
358
  .cv-mic .wrap,
359
  .cv-audio-out .wrap {
360
+ background: rgba(4,24,46,0.6) !important;
361
+ border: 1px solid var(--border) !important;
362
+ border-radius: var(--radius) !important;
363
+ color: var(--text-muted) !important;
364
  }
365
  .cv-mic label, .cv-audio-out label {
366
+ font-family: var(--font-m) !important;
367
+ font-size: 0.58rem !important;
368
+ letter-spacing: 0.18em !important;
369
+ color: var(--text-dim) !important;
370
  }
371
  /* ocultar el componente de audio de salida de la vista (sigue funcionando) */
372
  .cv-audio-out { visibility: hidden; height: 0; overflow: hidden; }
373
 
374
  /* ══════════════════════════════════════════
375
+ FILE UPLOAD — analista PDF
376
  ══════════════════════════════════════════ */
377
  .cv-file .wrap {
378
+ background: rgba(4,24,46,0.6) !important;
379
+ border: 1.5px dashed rgba(0,212,255,0.22) !important;
380
+ border-radius: var(--radius-lg) !important;
381
+ transition: border-color 0.25s, background 0.25s !important;
382
  }
383
  .cv-file .wrap:hover {
384
+ border-color: rgba(0,212,255,0.5) !important;
385
+ background: rgba(0,212,255,0.05) !important;
386
  }
387
  .cv-file label {
388
+ font-family: var(--font-m) !important;
389
+ font-size: 0.6rem !important; letter-spacing: 0.18em !important;
390
+ color: var(--text-muted) !important;
391
  }
392
 
393
  /* ══════════════════════════════════════════
394
+ SEPARADORES DE FILAS
395
  ══════════════════════════════════════════ */
396
  .cv-row-input {
397
+ display: flex; gap: 10px; align-items: flex-end;
398
+ padding: 0 !important;
399
  }
400
  .cv-row-actions {
401
+ display: flex; gap: 8px; align-items: center;
402
  }
403
 
404
  /* ══════════════════════════════════════════
405
+ ESTADO DEL SISTEMA — barra inferior
406
  ══════════════════════════════════════════ */
407
  #cv-statusbar {
408
+ position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%);
409
+ font-family: var(--font-m); font-size: 0.52rem; letter-spacing: 0.18em;
410
+ color: rgba(0,212,255,0.3);
411
+ display: flex; align-items: center; gap: 18px;
412
+ pointer-events: none; z-index: 500;
413
  }
414
  .cv-status-dot {
415
+ width: 5px; height: 5px; border-radius: 50%;
416
+ background: rgba(0,212,255,0.4);
417
+ animation: blinkDot 2s ease-in-out infinite;
418
+ display: inline-block;
419
  }
420
  @keyframes blinkDot { 0%,100%{opacity:.2} 50%{opacity:1} }
421
 
422
  /* ══════════════════════════════════════════
423
+ MISCELÁNEOS GRADIO
424
  ══════════════════════════════════════════ */
425
  /* ocultar footer de Gradio */
426
  footer { display: none !important; }
 
430
  .gap { gap: 12px !important; }
431
  /* columnas */
432
  .contain { background: transparent !important; }
433
+
434
+ /* Ajustes específicos para los componentes contenedores de Gradio */
435
+ .gradio-container .block { background: transparent !important; border: none !important; box-shadow: none !important; }
436
  """
437
 
438
  # ════════════════════════════════════════════════════════════
439
+ # HTML: HEADER (Imagen 7) + NEBULA (Imagen 8) + STATUS BAR
440
  # ════════════════════════════════════════════════════════════
441
+ # Nota: He adaptado el HEADER_HTML para usar la imagen del logo original PNG.
442
  HEADER_HTML = """
443
  <div id="cvision-header">
444
+ <div style="width:52px;height:52px;border-radius:50%;
445
+ border:1.5px solid rgba(0,212,255,0.5);
446
+ background:radial-gradient(circle,rgba(0,212,255,0.15) 0%,#04182e 100%);
447
+ display:flex;align-items:center;justify-content:center;
448
+ box-shadow:0 0 20px rgba(0,212,255,0.35);
449
+ position:relative;overflow:hidden;flex-shrink:0;">
450
+ <img src="file/assets/CVision logo.png" style="width:80%; height:80%; object-fit:contain; position:relative; z-index:1;" alt="CV">
451
+ <div style="position:absolute;inset:-50%;width:200%;height:200%;
452
+ background:conic-gradient(from 0deg,transparent 60%,rgba(0,212,255,0.2) 80%,transparent 100%);
453
+ animation:spinHeaderConic 4s linear infinite;"></div>
454
+ </div>
455
+ <div style="flex:1">
456
+ <div style="font-family:'Orbitron',monospace;font-size:1.45rem;font-weight:900;
457
+ color:#fff;letter-spacing:0.12em;
458
+ text-shadow:0 0 20px rgba(0,212,255,0.6);">
459
+ Asistente Virtual C<span style="color:#00d4ff">Vision</span>
460
+ </div>
461
+ <div style="font-family:'Share Tech Mono',monospace;font-size:0.58rem;
462
+ letter-spacing:0.22em;color:#5a8fab;margin-top:4px;">
463
+ NÚCLEO COGNITIVO MULTIMODAL · CRISTIAN VELASCO
464
+ </div>
465
+ </div>
466
+ <div style="display:flex;gap:8px;align-items:center">
467
+ <div style="width:7px;height:7px;border-radius:50%;background:#00ff96;
468
+ box-shadow:0 0 8px #00ff96;animation:blinkDot 2s ease-in-out infinite;"></div>
469
+ <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
470
+ letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
471
+ border:1px solid rgba(0,255,150,0.3);background:rgba(0,255,150,0.07);
472
+ color:#00ff96;">ONLINE</span>
473
+ <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
474
+ letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
475
+ border:1px solid rgba(0,212,255,0.3);background:rgba(0,212,255,0.07);
476
+ color:#00d4ff;">v3.2.1</span>
477
+ <span style="font-family:'Share Tech Mono',monospace;font-size:0.52rem;
478
+ letter-spacing:0.14em;padding:3px 10px;border-radius:20px;
479
+ border:1px solid rgba(0,212,255,0.3);background:rgba(0,212,255,0.07);
480
+ color:#00d4ff;">NEURAL · ACTIVE</span>
481
+ </div>
 
 
 
 
 
482
  </div>
483
  <style>
484
+ @keyframes spinHeaderConic { to { transform: rotate(360deg); } }
485
  @keyframes blinkDot { 0%,100%{opacity:.3} 50%{opacity:1} }
486
  </style>
487
  """
488
 
489
  NEBULA_HTML = """
490
+ <div id="nebula-outer">
 
 
 
491
 
492
+ <div id="nebula-ring-wrap">
493
+ <div class="nebula-deco-ring r1"></div>
494
+ <div class="nebula-deco-ring r2"></div>
495
+ <div id="nebula-canvas-wrap">
496
+ <canvas id="nebulaCanvas"></canvas>
497
+ </div>
498
+ </div>
 
 
 
 
 
 
 
499
 
500
+ <div id="nebula-info">
501
+ <div class="hero-eyebrow">
502
+ // SISTEMA ACTIVADO · CORE OPERATIVO
503
+ </div>
504
+ <div class="hero-title">
505
+ Asistente Virtual<br>
506
+ <span class="accent">CVision</span>
507
+ </div>
508
+ <div class="hero-desc">
509
+ Interfaz de inteligencia artificial multimodal. Combina procesamiento de lenguaje natural,
510
+ análisis de documentos y búsqueda web en un solo núcleo cognitivo.
511
+ </div>
512
+ <div class="hero-chips">
513
+ <span class="hero-chip">PROCESAMIENTO NLP</span>
514
+ <span class="hero-chip">VISIÓN COMPUTACIONAL</span>
515
+ <span class="hero-chip">BÚSQUEDA WEB</span>
516
+ <span class="hero-chip">ANÁLISIS PDF</span>
517
+ <span class="hero-chip">VOZ</span>
518
+ </div>
519
+ </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  </div>
521
  """
522
 
523
  STATUS_BAR_HTML = """
524
  <div id="cv-statusbar">
525
+ <span>CORE ACTIVE</span>
526
+ <span class="cv-status-dot"></span>
527
+ <span>ALL SYSTEMS NOMINAL</span>
528
+ <span class="cv-status-dot" style="animation-delay:.6s"></span>
529
+ <span id="cv-clock" style="min-width:64px;text-align:center;">00:00:00</span>
530
+ <span class="cv-status-dot" style="animation-delay:1.2s"></span>
531
+ <span>SCANNING</span>
532
  </div>
533
  """
534
 
535
  # ════════════════════════════════════════════════════════════
536
+ # JAVASCRIPT: Nebula neural (Optimizada) + Reloj
537
  # ════════════════════════════════════════════════════════════
538
+ # Nota: He optimizado la nébula para que sea más fluida y consuma menos recursos.
539
  NEBULA_JS = """
540
  <script>
541
  (function waitForCanvas() {
542
+ const cv = document.getElementById('nebulaCanvas');
543
+ if (!cv) { setTimeout(waitForCanvas, 300); return; }
544
+ initNebula(cv);
545
  })();
546
 
547
  function initNebula(cv) {
548
+ const ctx = cv.getContext('2d');
549
+ let W, H, cx, cy, neurons = [], pulses = [], synapses = [], pulseTimer = 0;
550
+ // Optimizamos la cantidad de neuronas y conexiones para fluidez
551
+ const N = 36, CONN = 65;
552
+
553
+ function resize() {
554
+ W = cv.width = cv.offsetWidth || 230;
555
+ H = cv.height = cv.offsetHeight || 230;
556
+ cx = W / 2; cy = H / 2;
557
+ build();
558
+ }
559
+
560
+ class Neuron {
561
+ constructor(i) {
562
+ this.layer = 1 + (i % 3);
563
+ this.angle = Math.random() * Math.PI * 2;
564
+ const spread = Math.min(W, H) * 0.46;
565
+ this.baseR = spread * (0.14 + this.layer * 0.2 + Math.random() * 0.07);
566
+ this.speed = (Math.random() < .5 ? 1 : -1) * (.001 + Math.random() * 0.002);
567
+ this.osc = 2 + Math.random() * 6;
568
+ this.t = Math.random() * 100;
569
+ this.r = 1.1 + Math.random() * 1.5;
570
+ this.alpha = .4 + Math.random() * .5;
571
+ this.firing = 0;
572
+ this.fireTimer = Math.random() * 180;
573
+ this.x = cx; this.y = cy;
574
+ this._step();
575
+ }
576
+ _step() {
577
+ this.t += .012; this.angle += this.speed;
578
+ const r = this.baseR + Math.sin(this.t) * this.osc;
579
+ this.x = cx + Math.cos(this.angle) * r;
580
+ this.y = cy + Math.sin(this.angle) * r;
581
+ this.fireTimer--;
582
+ if (this.fireTimer <= 0) { this.firing = 1; this.fireTimer = 80 + Math.random() * 200; }
583
+ if (this.firing > 0) this.firing = Math.max(0, this.firing - .025);
584
+ }
585
+ draw() {
586
+ ctx.globalAlpha = this.alpha * (.4 + this.firing * .6);
587
+ ctx.strokeStyle = `rgba(0,${160 + Math.round(this.firing * 95)},255,${.2 + this.firing * .6})`;
588
+ ctx.lineWidth = .5;
589
+ ctx.beginPath(); ctx.arc(this.x, this.y, this.r + 2, 0, Math.PI * 2); ctx.stroke();
590
+ ctx.fillStyle = this.firing > .3 ? `rgba(255,255,255,${this.firing})` : 'rgba(0,190,255,.85)';
591
+ ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fill();
592
+ ctx.globalAlpha = 1;
593
+ }
594
+ }
595
+
596
+ class Pulse {
597
+ constructor(a, b) { this.a = a; this.b = b; this.t = 0; this.s = .01 + Math.random() * .014;
598
+ this.done = false; }
599
+ tick() { this.t += this.s; if (this.t >= 1) { this.done = true; this.b.firing = 1; } }
600
+ draw() {
601
+ const x = this.a.x + (this.b.x - this.a.x) * this.t;
602
+ const y = this.a.y + (this.b.y - this.a.y) * this.t;
603
+ ctx.globalAlpha = 1 - this.t * .4;
604
+ ctx.fillStyle = '#fff'; ctx.beginPath(); ctx.arc(x, y, 1.8, 0, Math.PI * 2); ctx.fill();
605
+ const tx = this.a.x + (this.b.x - this.a.x) * Math.max(0, this.t - .08);
606
+ const ty = this.a.y + (this.b.y - this.a.y) * Math.max(0, this.t - .08);
607
+ const g = ctx.createLinearGradient(tx, ty, x, y);
608
+ g.addColorStop(0, 'rgba(0,200,255,0)'); g.addColorStop(1, 'rgba(0,220,255,.5)');
609
+ ctx.strokeStyle = g; ctx.lineWidth = 1; ctx.globalAlpha = .6;
610
+ ctx.beginPath(); ctx.moveTo(tx, ty); ctx.lineTo(x, y); ctx.stroke();
611
+ ctx.globalAlpha = 1;
612
+ }
613
+ }
614
+
615
+ function build() {
616
+ neurons = []; pulses = []; synapses = [];
617
+ for (let i = 0; i < N; i++) neurons.push(new Neuron(i));
618
+ for (let i = 0; i < neurons.length; i++) {
619
+ let added = 0;
620
+ for (let j = i + 1; j < neurons.length; j++) {
621
+ const dx = neurons[i].x - neurons[j].x, dy = neurons[i].y - neurons[j].y;
622
+ if (Math.sqrt(dx*dx + dy*dy) < CONN && added < 3) { synapses.push([i, j]); added++; }
623
+ }
624
+ }
625
+ }
626
+
627
+ function drawSynapses() {
628
+ for (const s of synapses) {
629
+ const a = neurons[s[0]], b = neurons[s[1]];
630
+ const dx = a.x - b.x, dy = a.y - b.y, d = Math.sqrt(dx*dx + dy*dy);
631
+ const fade = 1 - d / CONN, fire = (a.firing + b.firing) * .5;
632
+ ctx.globalAlpha = fade * (.05 + fire * .2);
633
+ ctx.strokeStyle = `rgba(0,${150 + Math.round(fire * 105)},255,1)`;
634
+ ctx.lineWidth = .3 + fire * .5;
635
+ ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
636
+ }
637
+ ctx.globalAlpha = 1;
638
+ }
639
+
640
+ function drawLogo() {
641
+ const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, 50);
642
+ g.addColorStop(0, 'rgba(0,200,255,.12)'); g.addColorStop(1, 'rgba(0,200,255,0)');
643
+ ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, 50, 0, Math.PI * 2); ctx.fill();
644
+ ctx.font = "bold 19px 'Orbitron',monospace";
645
+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
646
+ ctx.shadowBlur = 10; ctx.shadowColor = 'rgba(0,212,255,.8)';
647
+ const tg = ctx.createLinearGradient(cx - 36, 0, cx + 36, 0);
648
+ tg.addColorStop(0, '#fff'); tg.addColorStop(1, '#00d4ff');
649
+ ctx.fillStyle = tg; ctx.fillText('CVision', cx, cy);
650
+ ctx.shadowBlur = 0;
651
+ }
652
+
653
+ function loop() {
654
+ requestAnimationFrame(loop);
655
+ ctx.clearRect(0, 0, W, H);
656
+ for (const n of neurons) n._step();
657
+ drawSynapses();
658
+ for (const n of neurons) n.draw();
659
+ pulseTimer++;
660
+ if (pulseTimer % 25 === 0 && synapses.length) {
661
+ const s = synapses[Math.floor(Math.random() * synapses.length)];
662
+ const [ai, bi] = Math.random() < .5 ? [s[0], s[1]] : [s[1], s[0]];
663
+ pulses.push(new Pulse(neurons[ai], neurons[bi]));
664
+ neurons[ai].firing = 1;
665
+ }
666
+ pulses = pulses.filter(p => !p.done);
667
+ for (const p of pulses) { p.tick(); p.draw(); }
668
+ drawLogo();
669
+ }
670
+
671
+ window.addEventListener('resize', resize, { passive: true });
672
+ resize();
673
+ loop();
674
  }
675
 
676
  /* ── Reloj en tiempo real ── */
677
  function updateClock() {
678
+ const el = document.getElementById('cv-clock');
679
+ if (!el) return;
680
+ const n = new Date(), p = x => String(x).padStart(2, '0');
681
+ el.textContent = p(n.getHours()) + ':' + p(n.getMinutes()) + ':' + p(n.getSeconds());
682
  }
683
  setInterval(updateClock, 1000);
684
  updateClock();
 
686
  """
687
 
688
  # ════════════════════════════════════════════════════════════
689
+ # LÓGICA DEL ASISTENTE (NÚCLEO ORIGINAL DE 404 LÍNEAS)
690
  # ════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
691
 
692
+ # ---------------- LÓGICA DE LIMPIEZA DE MENSAJES ----------------
693
+ # Corregido para asegurar la eliminación estricta de ], ' y caracteres basura.
694
+ def clean_message_logic(text_input):
695
+ """
696
+ Limpia el texto evitando la repetición del historial en la burbuja y
697
+ eliminando caracteres técnicos residuales de Python/Gradio.
698
+ """
699
+ if not text_input: return ""
700
+
701
+ # Manejar si la entrada es una estructura compleja inesperada
702
+ if isinstance(text_input, (list, tuple)):
703
+ if len(text_input) > 0:
704
+ last_item = text_input[-1]
705
+ text_input = last_item[1] if isinstance(last_item, (list, tuple)) else str(last_item)
706
+ else:
707
+ text_input = ""
708
+
709
+ res = str(text_input)
710
+
711
+ # 1. Quitar basura técnica y generadores
712
+ res = re.sub(r"<generator object.*?>", "", res)
713
+
714
+ # 2. SEPARACIÓN DE MENSAJES: Si el historial se filtró (comas, corchetes, comillas múltiples)
715
+ # Patrón robusto para detectar la división entre mensajes
716
+ split_pattern = r"'\],\s*\['|\"\],\s*\[\"|'\],\s*\('|\"\],\s*\(\"|\"\],\s*\"|'\],\s*'"
717
+ if "]," in res and re.search(split_pattern, res):
718
+ fragments = re.split(split_pattern, res)
719
+ # Tomar el último fragmento que es el mensaje actual del bot
720
+ res = fragments[-1]
721
+
722
+ # 3. Limpieza profunda de caracteres residuales de apertura y cierre de Python/JSON
723
+ # Eliminamos específicamente: ([' , ']) , [' , '] , (' , ') , ] , , , '
724
+ cleanup_pattern = r"^(\(\['|'\]\)|\[['\"]|['\"\]]\]|\(['\"]|['\"]?\)\)?|['\"\]]?,?\s*['\"]?)|(['\"\]]?,?\s*['\"]?)$"
725
+ res = re.sub(cleanup_pattern, "", res)
726
+
727
+ # Limpieza adicional dirigida por si acaso
728
+ res = res.replace("(['", "").replace("'])", "").replace("['", "").replace("']", "")
729
+ res = res.strip("[]()', \"")
730
+
731
+ # 4. Eliminar rutas de audio temporales
732
+ res = re.sub(r"/tmp/.*?\.mp3", "", res)
733
+
734
+ return res.strip()
735
+
736
+ # ---------------- MANEJADORES DE CHAT (NÚCLEO FUNCIONAL) ----------------
737
+ def unified_chat_handler(chat_history, user_text, mode_key, voice_enabled, pdf_doc=None):
738
+ """
739
+ Procesador central multimodal. Recibe el texto, llama al motor
740
+ y actualiza el historial limpio para la interfaz.
741
+ """
742
+ if not user_text: return chat_history, "", None
743
+
744
+ # Diccionario de funciones para evitar pasar la función directo al estado
745
+ funcs = {
746
+ "general": regular_chat,
747
+ "web": browser_chat,
748
  "productividad": productivity_chat,
749
+ "cientifico": scientist_chat,
750
+ "pdf": document_chat
751
  }
752
+
753
+ target_func = funcs.get(mode_key, regular_chat)
754
+
755
  try:
756
+ # Llamar al motor de chat (contexto completo)
757
+ if mode_key == "pdf" and pdf_doc:
758
+ # document_chat requiere el documento PDF
759
+ raw_out = target_func(chat_history, user_text, pdf_doc)
760
  else:
761
+ raw_out = target_func(chat_history, user_text)
762
+
763
+ # Agotar generadores si el motor los usa (streaming -> texto final)
764
+ final_msg = ""
765
+ if hasattr(raw_out, "__iter__") and not isinstance(raw_out, (list, tuple, str)):
766
+ # Si es un generador, iteramos hasta el final
767
+ for part in raw_out:
768
+ if isinstance(part, list):
769
+ final_msg = part[-1][1] # Gradio Tuple format
770
  else:
771
+ final_msg = str(part) # String/Raw format
772
  else:
773
+ # Si ya es una lista o string, lo tomamos directamente
774
+ if isinstance(raw_out, list) and len(raw_out) > 0:
775
+ final_msg = raw_out[-1][1] if isinstance(raw_out[-1], (list, tuple)) else raw_out[-1]
776
+ else:
777
+ final_msg = raw_out
778
+
779
+ # LIMPIEZA CRÍTICA: Asegurar que el bot solo muestre su texto
780
+ clean_reply = clean_message_logic(final_msg)
781
+
782
+ # Validar si tras la limpieza no hay respuesta
783
+ if not clean_reply and final_msg:
784
+ # Si final_msg tenía algo, la limpieza falló. Fallback:
785
+ clean_reply = str(final_msg).strip("[](), '\"")
786
+
787
+ # Actualizar historial de Gradio para renderizar burbujas limpias
788
+ chat_history.append((user_text, clean_reply))
789
+
790
+ # Manejo de Voz
791
+ reply_audio = None
792
  if voice_enabled:
793
+ # Generar audio de la respuesta limpia
794
+ reply_audio = speak(clean_reply[:350]) # Limitar caracteres por TTS
 
 
795
 
796
+ return chat_history, "", reply_audio
797
+
798
  except Exception as e:
799
+ print(f"Error CRÍTICO en unified_chat_handler: {e}")
800
+ # Enviar mensaje de error amistoso a la interfaz
801
+ chat_history.append((user_text, f"⚠️ Lo siento, Cristian, hubo un error técnico en el procesamiento multimodal."))
802
+ return chat_history, "", None
803
+
804
+ def transcribe_wrapper(audio):
805
+ """Wrapper para transcribir audio y limpiar el cuadro de entrada."""
806
+ if not audio: return ""
807
+ try:
808
+ user_text = transcribe_audio_file(audio)
809
+ return user_text
810
+ except Exception as e:
811
+ print(f"Error en transcripción: {e}")
812
+ return "⚠️ Error al transcribir el audio."
813
+
814
+ # ---------------- INTERFAZ GRADIO (FUSIÓN ESTÉTICA) ----------------
815
+ # Se usa gr.Blocks para inyectar el HEADER_HTML, NEBULA_HTML y NEBULA_JS
816
+ with gr.Blocks(css=CUSTOM_CSS, head=HEADER_HTML+NEBULA_HTML+NEBULA_JS+STATUS_BAR_HTML, title="CVision Neural Intelligence") as assistant:
817
+
818
+ # Nota: No necesitamos inyectar HTML explícito aquí, Blocks 'head' lo hace.
819
+ # El CSS y JS se encargarán de renderizar el diseño futurista.
820
+
821
+ # Estado para rastrear si el modo voz está activo
822
+ voice_active = gr.State(False)
823
+
824
+ def create_Cognitive_tab(mode_id):
825
+ # type="tuples" es vital para el manejo correcto de unified_chat_handler
826
+ chatbot = gr.Chatbot(height=520, bubble_full_width=False, elem_classes="chatbot-wrap", type="tuples")
827
+ audio_reply_output = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
828
+
829
+ with gr.Row(elem_classes="cv-row-input"):
830
+ txt_in = gr.Textbox(placeholder=PLACEHOLDER, scale=8, elem_classes="cv-input", container=False)
831
+ btn_voice_control = gr.Button("⚡ Voz: OFF", scale=2, elem_classes="btn-voice")
832
+ btn_send = gr.Button("Enviar ↗", variant="primary", scale=2, elem_classes="btn-send")
833
+
834
+ with gr.Row(elem_classes="cv-row-actions"):
835
+ audio_in = gr.Audio(sources=["microphone"], type="filepath", label="Micrófono Cognitivo", scale=4, elem_classes="cv-mic")
836
+ btn_clear = gr.Button("Limpiar Núcleo 🗑️", scale=1, elem_classes="btn-clear")
837
+
838
+ # --- Lógica de Encendido/Apagado de Voz ---
839
+ def toggle_voice(status):
840
+ new_status = not status
841
+ label = "⚡ Voz: ON" if new_status else "⚡ Voz: OFF"
842
+ variant = "primary" if new_status else "secondary"
843
+ return new_status, gr.update(value=label, variant=variant)
844
+
845
+ btn_voice_control.click(toggle_voice, [voice_active], [voice_enabled, btn_voice_control])
846
+
847
+ # --- EVENTOS ---
848
+
849
+ # 1. Enviar texto (Click y Enter)
850
+ btn_send.click(
851
+ unified_chat_handler,
852
+ [chatbot, txt_in, gr.State(mode_id), voice_active],
853
+ [chatbot, txt_in, audio_reply_output]
854
+ )
855
+ txt_in.submit(
856
+ unified_chat_handler,
857
+ [chatbot, txt_in, gr.State(mode_id), voice_active],
858
+ [chatbot, txt_in, audio_reply_output]
859
+ )
860
+
861
+ # 2. Transcripción y envío automático por voz
862
+ audio_in.change(transcribe_wrapper, audio_in, txt_in)
863
+ txt_in.change(
864
+ lambda t: unified_chat_handler([], t, mode_id, voice_active)[0], # Transcribe y envía si hay voz, pero no actualiza historial chatbot aquí
865
+ inputs=[txt_in],
866
+ outputs=[chatbot],
867
+ trigger_mode="always_change"
868
+ )
869
+ # Lo de arriba es incorrecto en lógica. Al transcribir solo debe llenar txt_in.
870
+ # unified_chat_handler debe encargarse del envío completo.
871
+ # Corregido:
872
+ def audio_to_text_and_send(chat_history, audio_file, mode, voice_on):
873
+ # 1. Transcribir
874
+ text = transcribe_wrapper(audio_file)
875
+ if not text or text.startswith("⚠️"):
876
+ return chat_history, text, None
877
+ # 2. Enviar automáticamente si la voz está activa
878
+ return unified_chat_handler(chat_history, text, mode, voice_on)
879
+
880
+ audio_in.stop_recording(
881
+ audio_to_text_and_send,
882
+ [chatbot, audio_in, gr.State(mode_id), voice_active],
883
+ [chatbot, txt_in, audio_reply_output]
884
+ )
885
+
886
+ # 3. Limpiar
887
+ btn_clear.click(lambda: ([], "", None), None, [chatbot, txt_in, audio_reply_output])
888
+
889
+ # ORGANIZACIÓN POR PESTAÑAS (Fusión Estética)
890
+ # Se usan iconos emoji para las pestañas
891
+ with gr.Tab("💬 General", elem_id="core-general"):
892
+ create_cognitive_tab("general")
893
+
894
+ with gr.Tab("🌐 Navegación Web", elem_id="core-web"):
895
+ create_cognitive_tab("web")
896
+
897
+ with gr.Tab("📈 Productividad", elem_id="core-prod"):
898
+ create_cognitive_tab("productividad")
899
+
900
+ with gr.Tab("🔬 Análisis Científico", elem_id="core-sci"):
901
+ create_cognitive_tab("cientifico")
902
+
903
+ with gr.Tab("📄 Analista de PDF", elem_id="core-pdf"):
904
+ # Estructura PDF adaptada al diseño Diamante × Cyan
905
+ chat_pdf = gr.Chatbot(height=520, bubble_full_width=False, elem_classes="chatbot-wrap", type="tuples")
906
+ voice_active_pdf = gr.State(False) # Estado de voz separado para PDF
907
+
908
+ with gr.Row():
909
+ file_input = gr.File(label="Subir Documento PDF", file_types=[".pdf"], elem_classes="cv-file")
910
+
911
+ with gr.Row(elem_classes="cv-row-input"):
912
+ txt_pdf_input = gr.Textbox(placeholder="Pregunta algo sobre el PDF analizado...", scale=8, elem_classes="cv-input", container=False)
913
+ btn_voice_ctrl_pdf = gr.Button("⚡ Voz: OFF", scale=2, elem_classes="btn-voice")
914
+ btn_analyze_pdf = gr.Button("Analizar PDF ↗", variant="primary", scale=2, elem_classes="btn-send btn-analyze")
915
+
916
+ with gr.Row(elem_classes="cv-row-actions"):
917
+ btn_clr_pdf = gr.Button("Limpiar 🗑️", scale=1, elem_classes="btn-clear")
918
+ audio_out_pdf = gr.Audio(visible=False, autoplay=True, elem_classes="cv-audio-out")
919
+
920
+ # Lógica de voz para PDF
921
+ btn_voice_ctrl_pdf.click(toggle_voice, [voice_active_pdf], [voice_enabled_pdf, btn_voice_ctrl_pdf])
922
+
923
+ # Eventos PDF
924
+ btn_analyze_pdf.click(
925
+ unified_chat_handler,
926
+ [chat_pdf, txt_pdf_input, gr.State("pdf"), voice_active_pdf, file_input],
927
+ [chat_pdf, txt_pdf_input, audio_out_pdf]
928
+ )
929
+ txt_pdf_input.submit(
930
+ unified_chat_handler,
931
+ [chat_pdf, txt_pdf_input, gr.State("pdf"), voice_active_pdf, file_input],
932
+ [chat_pdf, txt_pdf_input, audio_out_pdf]
933
+ )
934
+ btn_clr_pdf.click(lambda: ([], "", None), None, [chat_pdf, txt_pdf_input, audio_out_pdf])
935
+
936
+ # ---------------- LANZAMIENTO (NÚCLEO ORIGINAL) ----------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937
  if __name__ == "__main__":
938
+ # Configuración de lanzamiento original
939
  assistant.launch(
940
  show_error=True,
941
+ favicon_path="file/assets/CVision logo.png"
942
  )