JairoCesar commited on
Commit
a5ab17e
·
verified ·
1 Parent(s): ddcb31e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -15
app.py CHANGED
@@ -14,7 +14,6 @@ import re
14
  import pandas as pd
15
  import altair as alt
16
  from datetime import datetime
17
- from tenacity import retry, stop_after_attempt, wait_fixed
18
  from io import BytesIO
19
  import docx
20
  import difflib
@@ -39,9 +38,9 @@ Este análisis es una herramienta informativa de IA y **NO es un diagnóstico m
39
  **Si tus síntomas son severos, busca ayuda médica urgente.**
40
  """
41
 
42
- # --- CONFIGURACIÓN DE LA API GEMINI (google-genai V3.0) ---
43
- @st.cache_resource
44
  def get_gemini_client():
 
45
  try:
46
  if 'APIkeydetective' in st.secrets:
47
  APIkeydetective = st.secrets['APIkeydetective']
@@ -49,19 +48,16 @@ def get_gemini_client():
49
  APIkeydetective = os.getenv("APIkeydetective")
50
 
51
  if not APIkeydetective:
52
- logger.warning("No se encontró APIkeydetective. Activando modo local permanente.")
53
  return None
54
 
55
  return genai.Client(
56
  api_key=APIkeydetective,
57
- http_options=types.HttpOptions(timeout=10000) # 10 segundos de timeout
58
  )
59
  except Exception as e:
60
- logger.warning(f"Error al configurar Gemini API: {e}. Se usará modo local.")
61
  return None
62
 
63
- client = get_gemini_client()
64
-
65
  # --- CARGA ULTRA-RÁPIDA DE DATOS Y FOODB (CERO COPIA EN MEMORIA) ---
66
  @st.cache_resource
67
  def load_data():
@@ -91,10 +87,9 @@ def get_foodb_lower_map(_foodb_index):
91
 
92
  foodb_lower_map = get_foodb_lower_map(foodb_index)
93
 
94
- # --- OPCIÓN 1: CACHÉ GLOBAL DE APRENDIZAJE EN RAM ---
95
  @st.cache_resource
96
  def get_global_learned_cache():
97
- """Almacena en RAM las respuestas generadas por Gemini para reutilizarlas instantáneamente entre usuarios."""
98
  return {}
99
 
100
  global_learned_cache = get_global_learned_cache()
@@ -236,7 +231,6 @@ FOOD_NAME_TO_FOODB_KEY = {
236
  "lentejas": ["lentil"], "almendras": ["almond"], "nueces": ["walnut"]
237
  }
238
 
239
- # --- SEGURO LÓGICO Y MATRIZ DE RIESGOS MÉDICOS ---
240
  STRICT_COMPOUND_TRIGGERS = {
241
  "cafeína": ["cafeína", "caffeine", "café", "coffee", "espresso", "energizante", "guaraná"],
242
  "teobromina": ["teobromina", "theobromine", "cacao", "chocolate"],
@@ -491,7 +485,6 @@ def validar_seguro_logico(entry, user_foods, user_query, food_compound_map):
491
 
492
  return True
493
 
494
- @retry(wait=wait_fixed(2), stop=stop_after_attempt(2))
495
  def extract_entities_with_gemini(query):
496
  gemini_client = get_gemini_client()
497
  if not gemini_client: return {"alimentos": [], "sintomas": []}
@@ -515,7 +508,7 @@ def extract_entities_with_gemini(query):
515
  elif "```" in text: text = text.split("```")[1].split("```")[0]
516
  return json.loads(text)
517
  except Exception as e:
518
- logger.warning(f"Extracción por IA no disponible ({e}). Se usará extracción directa.")
519
  return {"alimentos": [], "sintomas": []}
520
 
521
  def reinforce_entities_with_keywords(entities, query, food_map, master_symptom_map):
@@ -730,7 +723,6 @@ def generate_detailed_analysis(query, match, entities=None, food_compound_map=No
730
 
731
  gemini_client = get_gemini_client()
732
 
733
- # Si la API no está configurada, generar informe local
734
  if not gemini_client:
735
  local_report = generate_local_fallback_analysis(query, match, entities, food_compound_map, neuro_map)
736
  global_learned_cache[cache_lookup_key] = local_report
@@ -770,7 +762,6 @@ def generate_detailed_analysis(query, match, entities=None, food_compound_map=No
770
  contents=prompt
771
  )
772
  ai_report = response.text + TEXTO_BANDERAS_ROJAS
773
- # Guardar en la caché global de aprendizaje
774
  global_learned_cache[cache_lookup_key] = ai_report
775
  return ai_report
776
  except Exception as e:
 
14
  import pandas as pd
15
  import altair as alt
16
  from datetime import datetime
 
17
  from io import BytesIO
18
  import docx
19
  import difflib
 
38
  **Si tus síntomas son severos, busca ayuda médica urgente.**
39
  """
40
 
41
+ # --- CONFIGURACIÓN DE CLIENTE GEMINI SIN CACHÉ PARA EVITAR DEAD SOCKETS ---
 
42
  def get_gemini_client():
43
+ """Crea una instancia fresca del cliente para evitar congelamientos por sockets cerrados."""
44
  try:
45
  if 'APIkeydetective' in st.secrets:
46
  APIkeydetective = st.secrets['APIkeydetective']
 
48
  APIkeydetective = os.getenv("APIkeydetective")
49
 
50
  if not APIkeydetective:
 
51
  return None
52
 
53
  return genai.Client(
54
  api_key=APIkeydetective,
55
+ http_options=types.HttpOptions(timeout=5000) # Timeout agresivo de 5 segundos
56
  )
57
  except Exception as e:
58
+ logger.warning(f"No se pudo instanciar Gemini Client: {e}")
59
  return None
60
 
 
 
61
  # --- CARGA ULTRA-RÁPIDA DE DATOS Y FOODB (CERO COPIA EN MEMORIA) ---
62
  @st.cache_resource
63
  def load_data():
 
87
 
88
  foodb_lower_map = get_foodb_lower_map(foodb_index)
89
 
90
+ # --- CACHÉ GLOBAL DE APRENDIZAJE EN RAM ---
91
  @st.cache_resource
92
  def get_global_learned_cache():
 
93
  return {}
94
 
95
  global_learned_cache = get_global_learned_cache()
 
231
  "lentejas": ["lentil"], "almendras": ["almond"], "nueces": ["walnut"]
232
  }
233
 
 
234
  STRICT_COMPOUND_TRIGGERS = {
235
  "cafeína": ["cafeína", "caffeine", "café", "coffee", "espresso", "energizante", "guaraná"],
236
  "teobromina": ["teobromina", "theobromine", "cacao", "chocolate"],
 
485
 
486
  return True
487
 
 
488
  def extract_entities_with_gemini(query):
489
  gemini_client = get_gemini_client()
490
  if not gemini_client: return {"alimentos": [], "sintomas": []}
 
508
  elif "```" in text: text = text.split("```")[1].split("```")[0]
509
  return json.loads(text)
510
  except Exception as e:
511
+ logger.warning(f"Extracción por IA no disponible ({e}). Se usará extracción directa por palabras clave.")
512
  return {"alimentos": [], "sintomas": []}
513
 
514
  def reinforce_entities_with_keywords(entities, query, food_map, master_symptom_map):
 
723
 
724
  gemini_client = get_gemini_client()
725
 
 
726
  if not gemini_client:
727
  local_report = generate_local_fallback_analysis(query, match, entities, food_compound_map, neuro_map)
728
  global_learned_cache[cache_lookup_key] = local_report
 
762
  contents=prompt
763
  )
764
  ai_report = response.text + TEXTO_BANDERAS_ROJAS
 
765
  global_learned_cache[cache_lookup_key] = ai_report
766
  return ai_report
767
  except Exception as e: