fiel1986 commited on
Commit
fbc7eee
·
verified ·
1 Parent(s): ac9ff4e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -112
app.py CHANGED
@@ -303,129 +303,142 @@ def history_to_messages(norm_history):
303
 
304
 
305
  def run_chat(message, history, user_context, max_tokens, temperature, top_p, token, file_content, file_name, memoria):
306
- # --- Normalizar history ---
307
- norm_history = normalize_history(history)
 
 
 
 
 
 
308
 
309
- # --- SEGURIDAD ---
310
- for bloqueo in BLOQUEOS_JAILBREAK:
311
- if bloqueo in message.lower():
312
- reply = {"role": "assistant", "content": "Soy Aura, asistente especializado exclusivamente en programación."}
 
 
 
 
 
 
313
  chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
314
- yield chatbot_output, "", "", "⛔ Bloqueado por seguridad.", ""
315
  return
316
 
317
- if not HF_TOKEN:
318
- reply = {"role": "assistant", "content": "⚠️ Falta HF_TOKEN. Configura tu API Key en Settings → Secrets."}
319
- chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
320
- yield chatbot_output, "", "", "Configura HF_TOKEN.", ""
321
- return
322
-
323
- client = InferenceClient(token=token or HF_TOKEN, model=MODEL_ID)
324
-
325
- # --- Contexto del archivo ---
326
- contexto_archivo = ""
327
- errores_iniciales = []
328
- if file_content and file_name:
329
- errores_iniciales = analizar_todo(file_content, file_name)
330
- contexto_archivo = f"\n--- ARCHIVO ({file_name}) ---\n{file_content}\n"
331
- if errores_iniciales:
332
- contexto_archivo += "\n--- ERRORES ---\n" + "\n".join(errores_iniciales) + "\n"
333
-
334
- final_system = SYSTEM_PROMPT_BASE
335
- if user_context and user_context.strip():
336
- final_system += f"\n\n--- TU CONTEXTO ---\n{user_context}\n"
337
- if memoria and memoria.strip():
338
- final_system += f"\n--- MEMORIA ---\n{memoria}\n"
339
-
340
- # --- Construir messages para la API ---
341
- messages = [{"role": "system", "content": final_system}]
342
- messages.extend(history_to_messages(norm_history))
343
- user_content = message + (contexto_archivo if contexto_archivo else "")
344
- messages.append({"role": "user", "content": user_content})
345
-
346
- # --- Validar mensajes ---
347
- for i, msg in enumerate(messages):
348
- if not isinstance(msg, dict) or "role" not in msg or "content" not in msg:
349
- messages[i] = {"role": "system", "content": "[mensaje corrupto eliminado]"}
350
- msg["content"] = safe_str(msg["content"])
351
-
352
- # --- Streaming ---
353
- resp_text = ""
354
- try:
355
- for chunk in client.chat_completion(
356
- messages=messages,
357
- max_tokens=max_tokens,
358
- stream=True,
359
- temperature=temperature,
360
- top_p=top_p
361
- ):
362
- if chunk.choices and chunk.choices[0].delta.content:
363
- resp_text += chunk.choices[0].delta.content
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  chatbot_so_far = norm_history + [
365
  {"role": "user", "content": message},
366
- {"role": "assistant", "content": resp_text}
367
  ]
368
- yield chatbot_so_far, "", "", "Generando...", ""
369
- except Exception as e:
370
- error_msg = f"Error IA: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  chatbot_output = norm_history + [
372
  {"role": "user", "content": message},
373
- {"role": "assistant", "content": error_msg}
374
  ]
375
- yield chatbot_output, "", "", error_msg, ""
376
- return
377
-
378
- # --- Auto-corrección ---
379
- intentos = 0
380
- ultima_ejecucion = ""
381
- code_blocks = re.findall(r'```(?:python|javascript|js|html|sql)?\n(.*?)\n```', resp_text, re.DOTALL)
382
-
383
- if code_blocks:
384
- main_code = max(code_blocks, key=len)
385
- detected_ext = get_ext(file_name) if file_name else ("js" if ("function" in main_code or "const " in main_code) else "py")
386
- filename_for_exec = f"test.{detected_ext}"
387
-
388
- while intentos < MAX_AUTOFIX:
389
- exito, resultado_exec = ejecutar_codigo_sandbox(main_code, filename_for_exec)
390
- ultima_ejecucion = resultado_exec
391
- if exito:
392
- break
393
- intentos += 1
394
- chatbot_so_far = norm_history + [
395
- {"role": "user", "content": message},
396
- {"role": "assistant", "content": f"{resp_text}\n\n🔄 *Auto-corrigiendo ({intentos}/{MAX_AUTOFIX})...*"}
397
- ]
398
- yield chatbot_so_far, "", "", ultima_ejecucion, ""
399
- try:
400
- new_resp = ""
401
- for chunk in client.chat_completion(
402
- messages=[
403
- {"role": "system", "content": final_system},
404
- {"role": "user", "content": f"CORRIGE ESTE ERROR:\n{resultado_exec}\nDevuelve SOLO el código corregido en ```{detected_ext}."}
405
- ],
406
- max_tokens=max_tokens,
407
- stream=True,
408
- temperature=0.2
409
- ):
410
- if chunk.choices and chunk.choices[0].delta.content:
411
- new_resp += chunk.choices[0].delta.content
412
- new_blocks = re.findall(r'```(?:python|javascript|js|html|sql)?\n(.*?)\n```', new_resp, re.DOTALL)
413
- if new_blocks:
414
- main_code = max(new_blocks, key=len)
415
- resp_text += f"\n\n--- CORRECCIÓN {intentos} ---\n{new_resp}"
416
- else:
417
- break
418
- except Exception as e:
419
- print(f"\n[DEBUG] Error auto-corrección {intentos}: {e}")
420
- break
421
-
422
- # --- Output final ---
423
- chatbot_output = norm_history + [
424
- {"role": "user", "content": message},
425
- {"role": "assistant", "content": resp_text}
426
- ]
427
- yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
428
 
 
 
 
 
 
 
429
 
430
  # ============================================
431
  # INTERFAZ GRADIO
 
303
 
304
 
305
  def run_chat(message, history, user_context, max_tokens, temperature, top_p, token, file_content, file_name, memoria):
306
+ try:
307
+ # --- Normalizar history ---
308
+ norm_history = normalize_history(history)
309
+
310
+ # --- Validar mensaje vacío ---
311
+ if not message or not message.strip():
312
+ yield [], "", "", "⚠️ Mensaje vacío.", ""
313
+ return
314
 
315
+ # --- SEGURIDAD ---
316
+ for bloqueo in BLOQUEOS_JAILBREAK:
317
+ if bloqueo in message.lower():
318
+ reply = {"role": "assistant", "content": "Soy Aura, asistente especializado exclusivamente en programación."}
319
+ chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
320
+ yield chatbot_output, "", "", "⛔ Bloqueado por seguridad.", ""
321
+ return
322
+
323
+ if not HF_TOKEN:
324
+ reply = {"role": "assistant", "content": "⚠️ Falta HF_TOKEN. Configura tu API Key en Settings → Secrets."}
325
  chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
326
+ yield chatbot_output, "", "", "Configura HF_TOKEN.", ""
327
  return
328
 
329
+ client = InferenceClient(token=token or HF_TOKEN, model=MODEL_ID)
330
+
331
+ # --- Contexto del archivo ---
332
+ contexto_archivo = ""
333
+ errores_iniciales = []
334
+ if file_content and file_name:
335
+ errores_iniciales = analizar_todo(file_content, file_name)
336
+ contexto_archivo = f"\n--- ARCHIVO ({file_name}) ---\n{file_content}\n"
337
+ if errores_iniciales:
338
+ contexto_archivo += "\n--- ERRORES ---\n" + "\n".join(errores_iniciales) + "\n"
339
+
340
+ final_system = SYSTEM_PROMPT_BASE
341
+ if user_context and user_context.strip():
342
+ final_system += f"\n\n--- TU CONTEXTO ---\n{user_context}\n"
343
+ if memoria and memoria.strip():
344
+ final_system += f"\n--- MEMORIA ---\n{memoria}\n"
345
+
346
+ # --- Construir messages para la API ---
347
+ messages = [{"role": "system", "content": final_system}]
348
+ messages.extend(history_to_messages(norm_history))
349
+ user_content = message + (contexto_archivo if contexto_archivo else "")
350
+ messages.append({"role": "user", "content": user_content})
351
+
352
+ # --- Validar mensajes ---
353
+ for i, msg in enumerate(messages):
354
+ if not isinstance(msg, dict) or "role" not in msg or "content" not in msg:
355
+ messages[i] = {"role": "system", "content": "[mensaje corrupto eliminado]"}
356
+ msg["content"] = safe_str(msg["content"])
357
+
358
+ # --- Streaming ---
359
+ resp_text = ""
360
+ try:
361
+ for chunk in client.chat_completion(
362
+ messages=messages,
363
+ max_tokens=max_tokens,
364
+ stream=True,
365
+ temperature=temperature,
366
+ top_p=top_p
367
+ ):
368
+ if chunk.choices and chunk.choices[0].delta.content:
369
+ resp_text += chunk.choices[0].delta.content
370
+ chatbot_so_far = norm_history + [
371
+ {"role": "user", "content": message},
372
+ {"role": "assistant", "content": resp_text}
373
+ ]
374
+ yield chatbot_so_far, "", "", "Generando...", ""
375
+ except Exception as e:
376
+ error_msg = f"Error IA: {e}"
377
+ print(f"[DEBUG] Error streaming: {e}")
378
+ chatbot_output = norm_history + [
379
+ {"role": "user", "content": message},
380
+ {"role": "assistant", "content": error_msg}
381
+ ]
382
+ yield chatbot_output, "", "", error_msg, ""
383
+ return
384
+
385
+ # --- Auto-corrección ---
386
+ intentos = 0
387
+ ultima_ejecucion = ""
388
+ code_blocks = re.findall(r'```(?:python|javascript|js|html|sql)?\n(.*?)\n```', resp_text, re.DOTALL)
389
+
390
+ if code_blocks:
391
+ main_code = max(code_blocks, key=len)
392
+ detected_ext = get_ext(file_name) if file_name else ("js" if ("function" in main_code or "const " in main_code) else "py")
393
+ filename_for_exec = f"test.{detected_ext}"
394
+
395
+ while intentos < MAX_AUTOFIX:
396
+ exito, resultado_exec = ejecutar_codigo_sandbox(main_code, filename_for_exec)
397
+ ultima_ejecucion = resultado_exec
398
+ if exito:
399
+ break
400
+ intentos += 1
401
  chatbot_so_far = norm_history + [
402
  {"role": "user", "content": message},
403
+ {"role": "assistant", "content": f"{resp_text}\n\n🔄 *Auto-corrigiendo ({intentos}/{MAX_AUTOFIX})...*"}
404
  ]
405
+ yield chatbot_so_far, "", "", ultima_ejecucion, ""
406
+ try:
407
+ new_resp = ""
408
+ for chunk in client.chat_completion(
409
+ messages=[
410
+ {"role": "system", "content": final_system},
411
+ {"role": "user", "content": f"CORRIGE ESTE ERROR:\n{resultado_exec}\nDevuelve SOLO el código corregido en ```{detected_ext}."}
412
+ ],
413
+ max_tokens=max_tokens,
414
+ stream=True,
415
+ temperature=0.2
416
+ ):
417
+ if chunk.choices and chunk.choices[0].delta.content:
418
+ new_resp += chunk.choices[0].delta.content
419
+ new_blocks = re.findall(r'```(?:python|javascript|js|html|sql)?\n(.*?)\n```', new_resp, re.DOTALL)
420
+ if new_blocks:
421
+ main_code = max(new_blocks, key=len)
422
+ resp_text += f"\n\n--- CORRECCIÓN {intentos} ---\n{new_resp}"
423
+ else:
424
+ break
425
+ except Exception as e:
426
+ print(f"\n[DEBUG] Error auto-corrección {intentos}: {e}")
427
+ break
428
+
429
+ # --- Output final ---
430
  chatbot_output = norm_history + [
431
  {"role": "user", "content": message},
432
+ {"role": "assistant", "content": resp_text}
433
  ]
434
+ yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
 
436
+ except Exception as e:
437
+ # CATCH-ALL: Si algo explota antes del primer yield, esto lo salva
438
+ import traceback
439
+ error_trace = traceback.format_exc()
440
+ print(f"[DEBUG] CRASH EN RUN_CHAT: {error_trace}")
441
+ yield [], "", "", f"💥 Error interno: {str(e)}", ""
442
 
443
  # ============================================
444
  # INTERFAZ GRADIO