Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -60,9 +60,10 @@ def get_gemini_client():
|
|
| 60 |
return None
|
| 61 |
|
| 62 |
try:
|
|
|
|
| 63 |
return genai.Client(
|
| 64 |
api_key=api_key,
|
| 65 |
-
http_options=types.HttpOptions(timeout=
|
| 66 |
)
|
| 67 |
except Exception as e:
|
| 68 |
logger.warning(f"❌ Error instanciando cliente Gemini: {e}")
|
|
@@ -71,7 +72,9 @@ def get_gemini_client():
|
|
| 71 |
# --- CORTA-FUEGOS CON TIEMPO LÍMITE ESTRICTO DE 3.5 SEGUNDOS ---
|
| 72 |
def generate_content_with_fallback(gemini_client, prompt):
|
| 73 |
models_to_try = [
|
| 74 |
-
'gemini-3.5-flash-lite'
|
|
|
|
|
|
|
| 75 |
]
|
| 76 |
for model_name in models_to_try:
|
| 77 |
try:
|
|
@@ -90,18 +93,22 @@ def generate_content_with_fallback(gemini_client, prompt):
|
|
| 90 |
def generate_content_with_strict_timeout(gemini_client, prompt, timeout_seconds=3.5):
|
| 91 |
"""
|
| 92 |
Ejecuta la llamada a Gemini dentro de un hilo aislado.
|
| 93 |
-
Si Gemini tarda más de 3.5s, corta la ejecución
|
|
|
|
| 94 |
"""
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
# --- CARGA DE DATOS EN MEMORIA ---
|
| 107 |
@st.cache_resource
|
|
@@ -771,7 +778,7 @@ def generate_detailed_analysis(query, match, entities=None, food_compound_map=No
|
|
| 771 |
raw_text, used_model = generate_content_with_strict_timeout(gemini_client, prompt, timeout_seconds=3.5)
|
| 772 |
return f"🤖 **Análisis Redactado por IA Gemini ({used_model}):**\n\n" + raw_text + TEXTO_BANDERAS_ROJAS
|
| 773 |
except Exception as e:
|
| 774 |
-
logger.warning(f"
|
| 775 |
return generate_local_fallback_analysis(query, match, entities, food_compound_map, neuro_map)
|
| 776 |
|
| 777 |
def generate_neuro_report_text(entities, food_map, neuro_map):
|
|
@@ -901,6 +908,13 @@ with st.form(key="search_form", clear_on_submit=False):
|
|
| 901 |
|
| 902 |
if submitted:
|
| 903 |
if query_input and query_input.strip():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
current_query = query_input.strip()
|
| 905 |
st.session_state.user_query = current_query
|
| 906 |
st.session_state.has_searched = True
|
|
@@ -924,7 +938,6 @@ if submitted:
|
|
| 924 |
if st.session_state.search_results:
|
| 925 |
best_match = st.session_state.search_results[0]['entry']
|
| 926 |
|
| 927 |
-
# Pre-generación en segundo plano (imposible de bloquear la UI)
|
| 928 |
st.session_state.main_analysis = generate_detailed_analysis(
|
| 929 |
st.session_state.user_query, best_match,
|
| 930 |
st.session_state.entities, FOOD_TO_COMPOUND_MAP, INTEGRATED_NEURO_FOOD_MAP
|
|
|
|
| 60 |
return None
|
| 61 |
|
| 62 |
try:
|
| 63 |
+
# Timeout HTTP a nivel de socket ajustado a 4.0 segundos
|
| 64 |
return genai.Client(
|
| 65 |
api_key=api_key,
|
| 66 |
+
http_options=types.HttpOptions(timeout=4.0)
|
| 67 |
)
|
| 68 |
except Exception as e:
|
| 69 |
logger.warning(f"❌ Error instanciando cliente Gemini: {e}")
|
|
|
|
| 72 |
# --- CORTA-FUEGOS CON TIEMPO LÍMITE ESTRICTO DE 3.5 SEGUNDOS ---
|
| 73 |
def generate_content_with_fallback(gemini_client, prompt):
|
| 74 |
models_to_try = [
|
| 75 |
+
'gemini-3.5-flash-lite',
|
| 76 |
+
'gemini-2.5-flash',
|
| 77 |
+
'gemini-1.5-flash'
|
| 78 |
]
|
| 79 |
for model_name in models_to_try:
|
| 80 |
try:
|
|
|
|
| 93 |
def generate_content_with_strict_timeout(gemini_client, prompt, timeout_seconds=3.5):
|
| 94 |
"""
|
| 95 |
Ejecuta la llamada a Gemini dentro de un hilo aislado.
|
| 96 |
+
Si Gemini tarda más de 3.5s, corta la ejecución inmediatamente
|
| 97 |
+
y activa el motor local sin bloquear la interfaz.
|
| 98 |
"""
|
| 99 |
+
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
|
| 100 |
+
future = executor.submit(generate_content_with_fallback, gemini_client, prompt)
|
| 101 |
+
try:
|
| 102 |
+
result = future.result(timeout=timeout_seconds)
|
| 103 |
+
executor.shutdown(wait=False)
|
| 104 |
+
return result
|
| 105 |
+
except concurrent.futures.TimeoutError:
|
| 106 |
+
logger.warning(f"⏳ Gemini tardó más de {timeout_seconds}s. Se corta la espera y se activa el Motor Local.")
|
| 107 |
+
executor.shutdown(wait=False, cancel_futures=True)
|
| 108 |
+
raise TimeoutError("Tiempo límite de IA superado.")
|
| 109 |
+
except Exception as e:
|
| 110 |
+
executor.shutdown(wait=False)
|
| 111 |
+
raise e
|
| 112 |
|
| 113 |
# --- CARGA DE DATOS EN MEMORIA ---
|
| 114 |
@st.cache_resource
|
|
|
|
| 778 |
raw_text, used_model = generate_content_with_strict_timeout(gemini_client, prompt, timeout_seconds=3.5)
|
| 779 |
return f"🤖 **Análisis Redactado por IA Gemini ({used_model}):**\n\n" + raw_text + TEXTO_BANDERAS_ROJAS
|
| 780 |
except Exception as e:
|
| 781 |
+
logger.warning(f"Gemini no respondió en < 3.5s ({e}). Se activa la respuesta en modo local.")
|
| 782 |
return generate_local_fallback_analysis(query, match, entities, food_compound_map, neuro_map)
|
| 783 |
|
| 784 |
def generate_neuro_report_text(entities, food_map, neuro_map):
|
|
|
|
| 908 |
|
| 909 |
if submitted:
|
| 910 |
if query_input and query_input.strip():
|
| 911 |
+
# Limpieza explícita del estado para búsquedas consecutivas sin congelamiento
|
| 912 |
+
st.session_state.search_results = None
|
| 913 |
+
st.session_state.main_analysis = ""
|
| 914 |
+
st.session_state.neuro_text_cache = ""
|
| 915 |
+
st.session_state.mol_text_cache = ""
|
| 916 |
+
st.session_state.word_bytes_cache = None
|
| 917 |
+
|
| 918 |
current_query = query_input.strip()
|
| 919 |
st.session_state.user_query = current_query
|
| 920 |
st.session_state.has_searched = True
|
|
|
|
| 938 |
if st.session_state.search_results:
|
| 939 |
best_match = st.session_state.search_results[0]['entry']
|
| 940 |
|
|
|
|
| 941 |
st.session_state.main_analysis = generate_detailed_analysis(
|
| 942 |
st.session_state.user_query, best_match,
|
| 943 |
st.session_state.entities, FOOD_TO_COMPOUND_MAP, INTEGRATED_NEURO_FOOD_MAP
|