CVision-assitant commited on
Commit
ab0cb15
路
verified 路
1 Parent(s): 5c49c18

Update modules/interface.py

Browse files
Files changed (1) hide show
  1. modules/interface.py +146 -98
modules/interface.py CHANGED
@@ -15,47 +15,49 @@ from modules.utils.chat_utils import (
15
  )
16
 
17
  # ---------------- CONFIGURACIONES DE INTERFAZ ----------------
18
- PLACEHOLDER = "Escribe o usa el micr贸fono para tu mensaje..."
19
 
20
  CUSTOM_CSS = """
21
  body { background: #0a0f1e; color: white; font-family: 'Segoe UI', sans-serif; }
22
- .chatbot-container { border-radius: 15px; border: 1px solid rgba(0, 210, 255, 0.2); background: #0d1117 !important; }
23
- .chatbot { height: 500px !important; }
24
 
25
  /* Burbujas Estilo WhatsApp Independientes */
26
  .chatbot .message.user {
27
- background-color: #004d40 !important;
28
- border-radius: 15px 15px 2px 15px !important;
29
- padding: 10px !important;
30
- margin-left: 10% !important;
 
31
  }
32
  .chatbot .message.bot {
33
- background-color: #161b22 !important;
34
- border-radius: 15px 15px 15px 2px !important;
35
- padding: 10px !important;
36
- margin-right: 10% !important;
37
- border: 1px solid rgba(0, 210, 255, 0.1);
38
  }
39
 
40
- /* N茅bula Optimizada */
41
- .nebula-container-outer { display: flex; justify-content: center; width: 100%; margin: 15px 0; }
42
  .nebula-wrapper {
43
- background: radial-gradient(circle, rgba(0,210,255,0.05) 0%, rgba(0,0,0,0.8) 100%);
44
- border-radius: 50%; border: 2px solid rgba(0, 210, 255, 0.4);
45
- width: 280px; height: 280px; overflow: hidden; position: relative;
 
46
  }
47
  #nebulaCanvas { width: 100%; height: 100%; display: block; }
48
  """
49
 
50
- # ---------------- JAVASCRIPT: N脡BULA LIGERA ----------------
51
  NEBULA_JS = """
52
  function createCircularNebula() {
53
  const canvas = document.getElementById('nebulaCanvas');
54
  if (!canvas) return;
55
  const ctx = canvas.getContext('2d');
56
  let particles = [];
57
- const NUM_PARTICLES = 65;
58
- const CONNECTION_DISTANCE = 90;
59
 
60
  function resize() {
61
  if(!canvas) return;
@@ -68,7 +70,7 @@ function createCircularNebula() {
68
  constructor(angle, radius) {
69
  this.angle = angle;
70
  this.baseRadius = radius;
71
- this.speed = (Math.random() - 0.5) * 0.004;
72
  this.update();
73
  }
74
  update() {
@@ -77,8 +79,10 @@ function createCircularNebula() {
77
  this.angle += this.speed;
78
  }
79
  draw() {
80
- ctx.fillStyle = 'rgba(0, 210, 255, 0.8)';
81
- ctx.beginPath(); ctx.arc(this.x, this.y, 1.2, 0, Math.PI * 2); ctx.fill();
 
 
82
  }
83
  }
84
 
@@ -87,7 +91,7 @@ function createCircularNebula() {
87
  const minDim = Math.min(canvas.width, canvas.height) / 2;
88
  for (let i = 0; i < NUM_PARTICLES; i++) {
89
  const angle = Math.random() * Math.PI * 2;
90
- const r = minDim * (0.6 + Math.random() * 0.3);
91
  particles.push(new Particle(angle, r));
92
  }
93
  }
@@ -95,25 +99,27 @@ function createCircularNebula() {
95
  function drawCenterLogo() {
96
  const centerX = canvas.width / 2;
97
  const centerY = canvas.height / 2;
98
- ctx.font = "bold 32px Arial";
99
  ctx.textAlign = "center";
100
  ctx.textBaseline = "middle";
101
- ctx.fillStyle = "#00d2ff";
102
- ctx.shadowBlur = 15;
103
- ctx.shadowColor = '#00d2ff';
104
  ctx.fillText("CVision", centerX, centerY);
105
- ctx.shadowBlur = 0;
106
  }
107
 
108
  function animate() {
109
  ctx.clearRect(0, 0, canvas.width, canvas.height);
110
- ctx.strokeStyle = 'rgba(0, 180, 255, 0.1)';
111
  for (let i = 0; i < particles.length; i++) {
112
- const p = particles[i]; p.update(); p.draw();
 
 
113
  for (let j = i + 1; j < particles.length; j++) {
114
  const d = Math.hypot(p.x - particles[j].x, p.y - particles[j].y);
115
  if (d < CONNECTION_DISTANCE) {
116
- ctx.beginPath(); ctx.moveTo(p.x, p.y); ctx.lineTo(particles[j].x, particles[j].y); ctx.stroke();
 
 
 
117
  }
118
  }
119
  }
@@ -121,99 +127,141 @@ function createCircularNebula() {
121
  requestAnimationFrame(animate);
122
  }
123
  window.addEventListener('resize', resize);
124
- resize(); animate();
 
125
  }
126
  setTimeout(createCircularNebula, 500);
127
  """
128
 
129
- # ---------------- L脫GICA DE LIMPIEZA Y SOPORTE ----------------
130
- def clean_final_response(text):
131
- """Limpieza profunda de residuos de listas y saltos de l铆nea."""
132
- if not text: return ""
133
- res = str(text).strip()
134
- # Elimina patrones como: ], ' o ], " o solo ] al final
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  res = re.sub(r"\]?,?\s?['\"]?\s?$", "", res)
136
- return res.rstrip('\n').strip("[]'\" ")
137
-
138
- def toggle_voice(current):
139
- """Funci贸n global para el bot贸n de voz."""
140
- new_state = not current
141
- label = "Voz: ON" if new_state else "Voz: OFF"
142
- color = "primary" if new_state else "secondary"
143
- return new_state, gr.update(value=label, variant=color)
144
-
145
- def transcribe_only(audio_file):
146
- """Convierte audio a texto para el Textbox."""
147
- if not audio_file: return ""
148
- return transcribe_audio_file(audio_file)
149
 
150
- def chat_engine(chat_history, user_text, mode_key, voice_active, pdf_doc=None):
151
- if not user_text: return chat_history, "", None
 
 
 
 
 
 
 
 
 
152
 
153
- funcs = {"general": regular_chat, "web": browser_chat, "productividad": productivity_chat, "cientifico": scientist_chat, "pdf": document_chat}
154
  target_func = funcs.get(mode_key, regular_chat)
155
 
156
  try:
157
- raw_out = target_func(chat_history, user_text, pdf_doc) if mode_key == "pdf" else target_func(chat_history, user_text)
158
-
159
- bot_msg = ""
 
 
 
160
  if hasattr(raw_out, "__iter__") and not isinstance(raw_out, (list, tuple)):
161
- for part in raw_out: bot_msg = part[-1][1] if isinstance(part, list) else str(part)
162
- else: bot_msg = raw_out
 
 
163
 
164
- clean_reply = clean_final_response(bot_msg)
165
  chat_history.append((user_text, clean_reply))
166
 
167
- audio_path = speak(clean_reply.replace("*", "")[:400]) if voice_active else None
168
- return chat_history, "", audio_path
169
- except Exception:
170
- return chat_history + [(user_text, "Error en CVision.")], "", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  # ---------------- INTERFAZ GRADIO ----------------
173
  with gr.Blocks(css=CUSTOM_CSS, head=f"<script>{NEBULA_JS}</script>") as assistant:
174
- voice_enabled = gr.State(False)
175
-
176
  with gr.Row():
177
- with gr.Column(scale=1): gr.Image("assets/CVision logo.png", width=90, show_label=False)
178
  with gr.Column(scale=4):
179
- gr.Markdown("# **CVision AI System**")
180
- gr.Markdown("### Desarrollo: Cristian Velasco")
181
 
182
  gr.HTML('<div class="nebula-container-outer"><div class="nebula-wrapper"><canvas id="nebulaCanvas"></canvas></div></div>')
183
 
184
- def create_mode_tab(mode_id):
185
- chatbot = gr.Chatbot(height=480, bubble_full_width=False, elem_classes="chatbot-container")
186
- v_player = gr.Audio(visible=False, autoplay=True)
 
187
  with gr.Row():
188
- txt_msg = gr.Textbox(placeholder=PLACEHOLDER, scale=7, show_label=False)
189
- btn_voice_toggle = gr.Button("Voz: OFF", scale=1, variant="secondary")
190
  btn_send = gr.Button("Enviar", variant="primary", scale=1)
 
191
  with gr.Row():
192
- mic_input = gr.Audio(sources=["microphone"], type="filepath", label="Dictar pregunta", scale=5)
193
- btn_clear = gr.Button("Limpiar Chat", scale=2)
194
-
195
- btn_voice_toggle.click(toggle_voice, [voice_enabled], [voice_enabled, btn_voice_toggle])
196
- btn_send.click(chat_engine, [chatbot, txt_msg, gr.State(mode_id), voice_enabled], [chatbot, txt_msg, v_player])
197
- txt_msg.submit(chat_engine, [chatbot, txt_msg, gr.State(mode_id), voice_enabled], [chatbot, txt_msg, v_player])
198
- mic_input.change(transcribe_only, [mic_input], [txt_msg])
199
- btn_clear.click(lambda: ([], "", None), None, [chatbot, txt_msg, v_player])
200
-
201
- with gr.Tab("馃挰 General"): create_mode_tab("general")
202
- with gr.Tab("馃寪 Web Search"): create_mode_tab("web")
203
- with gr.Tab("馃搱 Productividad"): create_mode_tab("productividad")
204
- with gr.Tab("馃敩 Cient铆fico"): create_mode_tab("cientifico")
 
 
 
205
  with gr.Tab("馃搫 Analista PDF"):
206
- c_pdf = gr.Chatbot(height=480, bubble_full_width=False)
207
- v_pdf = gr.Audio(visible=False, autoplay=True)
208
- f_pdf = gr.File(label="Subir PDF")
209
- t_pdf = gr.Textbox(placeholder="Pregunta sobre el PDF...")
210
- v_toggle_pdf = gr.Button("Voz: OFF", variant="secondary")
211
  with gr.Row():
212
- b_pdf = gr.Button("Analizar", variant="primary"); b_c = gr.Button("Limpiar")
213
 
214
- v_toggle_pdf.click(toggle_voice, [voice_enabled], [voice_enabled, v_toggle_pdf])
215
- b_pdf.click(chat_engine, [c_pdf, t_pdf, gr.State("pdf"), voice_enabled, f_pdf], [c_pdf, t_pdf, v_pdf])
216
- b_c.click(lambda: ([], "", None), None, [c_pdf, t_pdf, v_pdf])
217
 
218
  if __name__ == "__main__":
219
- assistant.launch()
 
15
  )
16
 
17
  # ---------------- CONFIGURACIONES DE INTERFAZ ----------------
18
+ PLACEHOLDER = "Escribe tu mensaje para CVision..."
19
 
20
  CUSTOM_CSS = """
21
  body { background: #0a0f1e; color: white; font-family: 'Segoe UI', sans-serif; }
22
+ .chatbot-container { border-radius: 20px; border: 1px solid rgba(0, 210, 255, 0.3); background: #0d1117 !important; }
23
+ .chatbot { height: 550px !important; }
24
 
25
  /* Burbujas Estilo WhatsApp Independientes */
26
  .chatbot .message.user {
27
+ background-color: #005a53 !important;
28
+ border-radius: 18px 18px 2px 18px !important;
29
+ padding: 12px !important;
30
+ margin-left: 15% !important;
31
+ box-shadow: 2px 2px 8px rgba(0,0,0,0.4);
32
  }
33
  .chatbot .message.bot {
34
+ background-color: #1c222d !important;
35
+ border-radius: 18px 18px 18px 2px !important;
36
+ padding: 12px !important;
37
+ margin-right: 15% !important;
38
+ border: 1px solid rgba(0, 210, 255, 0.15);
39
  }
40
 
41
+ /* N茅bula Reactor Optimizada */
42
+ .nebula-container-outer { display: flex; justify-content: center; width: 100%; margin: 25px 0; }
43
  .nebula-wrapper {
44
+ background: radial-gradient(circle, rgba(0,210,255,0.08) 0%, rgba(0,0,0,0.8) 100%);
45
+ border-radius: 50%; border: 3px solid rgba(0, 210, 255, 0.6);
46
+ width: 320px; height: 320px; overflow: hidden; position: relative;
47
+ box-shadow: 0 0 50px rgba(0, 210, 255, 0.2);
48
  }
49
  #nebulaCanvas { width: 100%; height: 100%; display: block; }
50
  """
51
 
52
+ # ---------------- JAVASCRIPT: N脡BULA OPTIMIZADA ----------------
53
  NEBULA_JS = """
54
  function createCircularNebula() {
55
  const canvas = document.getElementById('nebulaCanvas');
56
  if (!canvas) return;
57
  const ctx = canvas.getContext('2d');
58
  let particles = [];
59
+ const NUM_PARTICLES = 60; // REDUCIDO PARA FLUIDEZ
60
+ const CONNECTION_DISTANCE = 100;
61
 
62
  function resize() {
63
  if(!canvas) return;
 
70
  constructor(angle, radius) {
71
  this.angle = angle;
72
  this.baseRadius = radius;
73
+ this.speed = (Math.random() - 0.5) * 0.005;
74
  this.update();
75
  }
76
  update() {
 
79
  this.angle += this.speed;
80
  }
81
  draw() {
82
+ ctx.fillStyle = 'rgba(0, 210, 255, 0.9)';
83
+ ctx.beginPath();
84
+ ctx.arc(this.x, this.y, 1.2, 0, Math.PI * 2);
85
+ ctx.fill();
86
  }
87
  }
88
 
 
91
  const minDim = Math.min(canvas.width, canvas.height) / 2;
92
  for (let i = 0; i < NUM_PARTICLES; i++) {
93
  const angle = Math.random() * Math.PI * 2;
94
+ const r = minDim * (0.5 + Math.random() * 0.4);
95
  particles.push(new Particle(angle, r));
96
  }
97
  }
 
99
  function drawCenterLogo() {
100
  const centerX = canvas.width / 2;
101
  const centerY = canvas.height / 2;
102
+ ctx.font = "bold 36px Arial";
103
  ctx.textAlign = "center";
104
  ctx.textBaseline = "middle";
105
+ ctx.fillStyle = '#00d2ff';
 
 
106
  ctx.fillText("CVision", centerX, centerY);
 
107
  }
108
 
109
  function animate() {
110
  ctx.clearRect(0, 0, canvas.width, canvas.height);
111
+ ctx.strokeStyle = 'rgba(0, 180, 255, 0.15)';
112
  for (let i = 0; i < particles.length; i++) {
113
+ const p = particles[i];
114
+ p.update();
115
+ p.draw();
116
  for (let j = i + 1; j < particles.length; j++) {
117
  const d = Math.hypot(p.x - particles[j].x, p.y - particles[j].y);
118
  if (d < CONNECTION_DISTANCE) {
119
+ ctx.beginPath();
120
+ ctx.moveTo(p.x, p.y);
121
+ ctx.lineTo(particles[j].x, particles[j].y);
122
+ ctx.stroke();
123
  }
124
  }
125
  }
 
127
  requestAnimationFrame(animate);
128
  }
129
  window.addEventListener('resize', resize);
130
+ resize();
131
+ animate();
132
  }
133
  setTimeout(createCircularNebula, 500);
134
  """
135
 
136
+ # ---------------- L脫GICA DE LIMPIEZA DE MENSAJES ----------------
137
+ def clean_message_logic(text_input):
138
+ """Limpia el texto evitando la repetici贸n del historial y caracteres residuales."""
139
+ if not text_input: return ""
140
+
141
+ if isinstance(text_input, (list, tuple)):
142
+ if len(text_input) > 0:
143
+ last_item = text_input[-1]
144
+ text_input = last_item[1] if isinstance(last_item, (list, tuple)) else str(last_item)
145
+
146
+ res = str(text_input)
147
+
148
+ # 1. Quitar basura t茅cnica y generadores
149
+ res = re.sub(r"<generator object.*?>", "", res)
150
+
151
+ # 2. SEPARACI脫N DE MENSAJES: Si el historial se filtr贸
152
+ if "]," in res or "', '" in res:
153
+ fragments = re.split(r"'],|',|\[", res)
154
+ res = fragments[-1]
155
+
156
+ # 3. Limpieza de caracteres residuales solicitados ( ], ' )
157
+ # Eliminamos espec铆ficamente el patr贸n final que mencionas
158
  res = re.sub(r"\]?,?\s?['\"]?\s?$", "", res)
159
+ res = res.replace("(['", "").replace("'])", "").replace("['", "").replace("']", "")
160
+
161
+ # 4. Quitar saltos de l铆nea dobles al final
162
+ res = res.strip().rstrip('\\n')
163
+
164
+ return res.strip("[]()', \"")
 
 
 
 
 
 
 
165
 
166
+ # ---------------- MANEJADORES DE CHAT ----------------
167
+ def unified_chat_handler(chat_history, user_text, mode_key, pdf_doc=None):
168
+ if not user_text: return chat_history, ""
169
+
170
+ funcs = {
171
+ "general": regular_chat,
172
+ "web": browser_chat,
173
+ "productividad": productivity_chat,
174
+ "cientifico": scientist_chat,
175
+ "pdf": document_chat
176
+ }
177
 
 
178
  target_func = funcs.get(mode_key, regular_chat)
179
 
180
  try:
181
+ if mode_key == "pdf" and pdf_doc:
182
+ raw_out = target_func(chat_history, user_text, pdf_doc)
183
+ else:
184
+ raw_out = target_func(chat_history, user_text)
185
+
186
+ final_msg = ""
187
  if hasattr(raw_out, "__iter__") and not isinstance(raw_out, (list, tuple)):
188
+ for part in raw_out:
189
+ final_msg = part[-1][1] if isinstance(part, list) else str(part)
190
+ else:
191
+ final_msg = raw_out
192
 
193
+ clean_reply = clean_message_logic(final_msg)
194
  chat_history.append((user_text, clean_reply))
195
 
196
+ except Exception as e:
197
+ print(f"Error CVision: {e}")
198
+ chat_history.append((user_text, "Error en el procesamiento."))
199
+
200
+ return chat_history, ""
201
+
202
+ def voice_auto_handler(chat_history, audio_file, mode_key, pdf_doc=None):
203
+ """Solo transcribe y responde si el usuario grab贸 audio."""
204
+ if not audio_file: return chat_history, None, ""
205
+
206
+ user_msg = transcribe_audio_file(audio_file)
207
+ if not user_msg: return chat_history, None, ""
208
+
209
+ # Procesamos el chat con la l贸gica unificada
210
+ new_history, _ = unified_chat_handler(chat_history, user_msg, mode_key, pdf_doc)
211
+
212
+ # Voz de la respuesta
213
+ bot_reply = new_history[-1][1]
214
+ voice_clean = bot_reply.replace("*", "").replace("#", "").replace("`", "")
215
+ audio_reply = speak(voice_clean[:350])
216
+
217
+ return new_history, audio_reply, user_msg
218
 
219
  # ---------------- INTERFAZ GRADIO ----------------
220
  with gr.Blocks(css=CUSTOM_CSS, head=f"<script>{NEBULA_JS}</script>") as assistant:
221
+
 
222
  with gr.Row():
223
+ with gr.Column(scale=1): gr.Image("assets/CVision logo.png", width=110, show_label=False)
224
  with gr.Column(scale=4):
225
+ gr.Markdown("# **CVision Assistant**")
226
+ gr.Markdown("### Cristian Velasco | Soporte Multimodal")
227
 
228
  gr.HTML('<div class="nebula-container-outer"><div class="nebula-wrapper"><canvas id="nebulaCanvas"></canvas></div></div>')
229
 
230
+ def build_interface_tab(label, mode_id):
231
+ chatbot = gr.Chatbot(height=520, bubble_full_width=False, elem_classes="chatbot-container")
232
+ v_output = gr.Audio(visible=False, autoplay=True)
233
+
234
  with gr.Row():
235
+ txt_input = gr.Textbox(placeholder=PLACEHOLDER, scale=8, show_label=False)
 
236
  btn_send = gr.Button("Enviar", variant="primary", scale=1)
237
+
238
  with gr.Row():
239
+ audio_input = gr.Audio(sources=["microphone"], type="filepath", label="Transcripci贸n de Voz", scale=5)
240
+ btn_clear = gr.Button("Limpiar", scale=2)
241
+
242
+ # Eventos
243
+ btn_send.click(unified_chat_handler, [chatbot, txt_input, gr.State(mode_id)], [chatbot, txt_input])
244
+ txt_input.submit(unified_chat_handler, [chatbot, txt_input, gr.State(mode_id)], [chatbot, txt_input])
245
+
246
+ # Transcripci贸n y respuesta de voz autom谩tica
247
+ audio_input.change(voice_auto_handler, [chatbot, audio_input, gr.State(mode_id)], [chatbot, v_output, txt_input])
248
+
249
+ btn_clear.click(lambda: ([], None, ""), None, [chatbot, v_output, txt_input])
250
+
251
+ with gr.Tab("馃挰 General"): build_interface_tab("General", "general")
252
+ with gr.Tab("馃寪 Web"): build_interface_tab("Web", "web")
253
+ with gr.Tab("馃搱 Productividad"): build_interface_tab("Productividad", "productividad")
254
+ with gr.Tab("馃敩 Cient铆fico"): build_interface_tab("Cient铆fico", "cientifico")
255
  with gr.Tab("馃搫 Analista PDF"):
256
+ chat_pdf = gr.Chatbot(height=520, bubble_full_width=False)
257
+ voice_pdf = gr.Audio(visible=False, autoplay=True)
258
+ file_pdf = gr.File(label="PDF", file_types=[".pdf"])
259
+ txt_pdf = gr.Textbox(placeholder="Consulta sobre el PDF...")
 
260
  with gr.Row():
261
+ b_pdf = gr.Button("Enviar", variant="primary"); b_clr = gr.Button("Limpiar")
262
 
263
+ b_pdf.click(unified_chat_handler, [chat_pdf, txt_pdf, gr.State("pdf"), file_pdf], [chat_pdf, txt_pdf])
264
+ b_clr.click(lambda: ([], None, ""), None, [chat_pdf, voice_pdf, txt_pdf])
 
265
 
266
  if __name__ == "__main__":
267
+ assistant.launch(show_error=True)