Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -957,22 +957,44 @@ if st.session_state.search_results is not None:
|
|
| 957 |
score_col2.metric("Puntos por Síntomas", f"{best_match_data['score']['symptoms']}")
|
| 958 |
score_col3.metric("PUNTUACIÓN TOTAL", f"{best_match_data['score']['total']}", delta="Máxima coincidencia")
|
| 959 |
|
| 960 |
-
|
| 961 |
st.write("")
|
| 962 |
if foodb_index:
|
| 963 |
with st.popover("🔬 Componentes Moleculares del Diagnóstico"):
|
|
|
|
| 964 |
st.info("Análisis de los compuestos en los alimentos mencionados que están directamente implicados en el diagnóstico principal.")
|
|
|
|
| 965 |
user_foods_mentioned = st.session_state.entities.get("alimentos", [])
|
| 966 |
|
| 967 |
if not user_foods_mentioned:
|
| 968 |
st.warning("No se identificó un alimento específico para buscar.")
|
| 969 |
else:
|
| 970 |
-
|
| 971 |
target_compounds = set()
|
| 972 |
-
for compound, triggered_symptoms in KNOWN_TRIGGERS_MAP.items():
|
| 973 |
-
if any(symptom in main_diagnosis_symptoms for symptom in triggered_symptoms):
|
| 974 |
-
target_compounds.add(compound.lower())
|
| 975 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 976 |
if not target_compounds:
|
| 977 |
st.warning(f"No se pudieron determinar los compuestos moleculares clave para '{best_match.get('condicion_asociada')}'.")
|
| 978 |
else:
|
|
@@ -986,8 +1008,10 @@ if st.session_state.search_results is not None:
|
|
| 986 |
relevant_compounds = []
|
| 987 |
for item in compounds_data:
|
| 988 |
compound_name_lower = item['compound'].lower()
|
|
|
|
| 989 |
if any(target in compound_name_lower for target in target_compounds):
|
| 990 |
relevant_compounds.append(item)
|
|
|
|
| 991 |
if relevant_compounds:
|
| 992 |
found_any_data = True
|
| 993 |
with st.container(border=True):
|
|
@@ -996,6 +1020,7 @@ if st.session_state.search_results is not None:
|
|
| 996 |
for item in relevant_compounds[:5]:
|
| 997 |
st.write(f"**Compuesto:** {item['compound']}")
|
| 998 |
st.caption(f"Este compuesto está directamente relacionado con '{best_match.get('condicion_asociada')}'.")
|
|
|
|
| 999 |
if not found_any_data:
|
| 1000 |
st.warning(f"No se encontraron los compuestos específicos de '{best_match.get('condicion_asociada')}' en los alimentos analizados en la base de datos FoodB.")
|
| 1001 |
|
|
|
|
| 957 |
score_col2.metric("Puntos por Síntomas", f"{best_match_data['score']['symptoms']}")
|
| 958 |
score_col3.metric("PUNTUACIÓN TOTAL", f"{best_match_data['score']['total']}", delta="Máxima coincidencia")
|
| 959 |
|
| 960 |
+
with col2_expander:
|
| 961 |
st.write("")
|
| 962 |
if foodb_index:
|
| 963 |
with st.popover("🔬 Componentes Moleculares del Diagnóstico"):
|
| 964 |
+
|
| 965 |
st.info("Análisis de los compuestos en los alimentos mencionados que están directamente implicados en el diagnóstico principal.")
|
| 966 |
+
|
| 967 |
user_foods_mentioned = st.session_state.entities.get("alimentos", [])
|
| 968 |
|
| 969 |
if not user_foods_mentioned:
|
| 970 |
st.warning("No se identificó un alimento específico para buscar.")
|
| 971 |
else:
|
| 972 |
+
# --- LÓGICA HÍBRIDA MEJORADA ---
|
| 973 |
target_compounds = set()
|
|
|
|
|
|
|
|
|
|
| 974 |
|
| 975 |
+
# 1. PRIORIDAD 1: Intentar extraer el compuesto directamente del diagnóstico.
|
| 976 |
+
target_compounds_text = best_match.get("compuesto_alimento", "").lower()
|
| 977 |
+
cleaned_text = re.sub(r'\(.*?\)', '', target_compounds_text) # Limpiar texto en paréntesis
|
| 978 |
+
direct_keywords = set(re.findall(r'\b[a-zA-Z-]+\b', cleaned_text)) # Extraer palabras
|
| 979 |
+
|
| 980 |
+
# Filtrar palabras genéricas para forzar el fallback si es necesario
|
| 981 |
+
generic_words = {'y', 'o', 'en', 'con', 'lácteos', 'carnes', 'pescados'}
|
| 982 |
+
direct_keywords -= generic_words
|
| 983 |
+
|
| 984 |
+
if direct_keywords:
|
| 985 |
+
target_compounds.update(direct_keywords)
|
| 986 |
+
logger.info(f"Método Directo: Compuestos objetivo encontrados: {target_compounds}")
|
| 987 |
+
|
| 988 |
+
# 2. PRIORIDAD 2: Si el método directo falla o es muy genérico, usar el método indirecto.
|
| 989 |
+
if not target_compounds:
|
| 990 |
+
logger.info("Método Directo falló, usando Fallback (método indirecto)...")
|
| 991 |
+
main_diagnosis_symptoms = set(s.lower() for s in best_match.get("sintomas_clave", []))
|
| 992 |
+
for compound, triggered_symptoms in KNOWN_TRIGGERS_MAP.items():
|
| 993 |
+
# Usar intersection para encontrar síntomas compartidos
|
| 994 |
+
if main_diagnosis_symptoms.intersection(triggered_symptoms):
|
| 995 |
+
target_compounds.add(compound.lower())
|
| 996 |
+
logger.info(f"Método Indirecto: Compuestos objetivo encontrados: {target_compounds}")
|
| 997 |
+
|
| 998 |
if not target_compounds:
|
| 999 |
st.warning(f"No se pudieron determinar los compuestos moleculares clave para '{best_match.get('condicion_asociada')}'.")
|
| 1000 |
else:
|
|
|
|
| 1008 |
relevant_compounds = []
|
| 1009 |
for item in compounds_data:
|
| 1010 |
compound_name_lower = item['compound'].lower()
|
| 1011 |
+
# Comprobar si el nombre del compuesto contiene ALGUNA de las palabras clave objetivo
|
| 1012 |
if any(target in compound_name_lower for target in target_compounds):
|
| 1013 |
relevant_compounds.append(item)
|
| 1014 |
+
|
| 1015 |
if relevant_compounds:
|
| 1016 |
found_any_data = True
|
| 1017 |
with st.container(border=True):
|
|
|
|
| 1020 |
for item in relevant_compounds[:5]:
|
| 1021 |
st.write(f"**Compuesto:** {item['compound']}")
|
| 1022 |
st.caption(f"Este compuesto está directamente relacionado con '{best_match.get('condicion_asociada')}'.")
|
| 1023 |
+
|
| 1024 |
if not found_any_data:
|
| 1025 |
st.warning(f"No se encontraron los compuestos específicos de '{best_match.get('condicion_asociada')}' en los alimentos analizados en la base de datos FoodB.")
|
| 1026 |
|