[INST]
You are an expert in South American indigenous languages.
Use strictly and only the information below to answer the user question in **English**.
- Do not infer or assume facts that are not explicitly stated.
- If the answer is unknown or insufficient, say \"I cannot answer with the available data.\"
- Limit your answer to 100 words.
### CONTEXT:
{chr(10).join(context)}
### RDF RELATIONS:
{chr(10).join(rdf_facts)}
### QUESTION:
{user_question}
Answer:
[/INST]"""
try:
res_es = requests.post(
ENDPOINT_URL,
headers={"Authorization": f"Bearer {HF_API_TOKEN}", "Content-Type": "application/json"},
json={"inputs": prompt_es}, timeout=60
)
res_en = requests.post(
ENDPOINT_URL,
headers={"Authorization": f"Bearer {HF_API_TOKEN}", "Content-Type": "application/json"},
json={"inputs": prompt_en}, timeout=60
)
out_es = res_es.json()
out_en = res_en.json()
if isinstance(out_es, dict) and "generated_text" in out_es:
response_es = out_es["generated_text"].strip()
elif isinstance(out_es, list) and "generated_text" in out_es[0]:
response_es = out_es[0]["generated_text"].replace(prompt_es.strip(), "").strip()
else:
response_es = "Error en respuesta en español."
if isinstance(out_en, dict) and "generated_text" in out_en:
response_en = out_en["generated_text"].strip()
elif isinstance(out_en, list) and "generated_text" in out_en[0]:
response_en = out_en[0]["generated_text"].replace(prompt_en.strip(), "").strip()
else:
response_en = "Error in English response."
combined = f"Respuesta en español:
{response_es}
Answer in English:
{response_en}"
return combined, ids, context, rdf_facts
except Exception as e:
return f"Error al consultar el modelo: {str(e)}", ids, context, rdf_facts
# === MAIN ===
def main():
methods, embedder = load_all_components()
st.markdown("""
""", unsafe_allow_html=True)
with st.expander("📌 **Resumen General**", expanded=True):
st.markdown("""
Esta aplicación ofrece **análisis impulsado por IA, Grafos y RAGs (GraphRAGs)** de lenguas indígenas de América del Sur,
integrando información de **Glottolog, Wikipedia y Wikidata**.
""")
with st.sidebar:
st.markdown("### 📚 Información de Contacto")
st.markdown("""
- Correo: jxvera@gmail.com
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown("### 🚀 Inicio Rápido")
st.markdown("""
1. **Escribe una pregunta** en el cuadro de entrada
2. **Haz clic en 'Analizar'** para obtener la respuesta
3. **Explora los resultados** con los detalles expandibles
""")
st.markdown("---")
st.markdown("### 🔍 Preguntas de Ejemplo")
questions = [
"¿Qué idiomas están en peligro en Brasil?",
"¿Qué idiomas se hablan en Perú?",
"¿Cuáles idiomas están relacionados con el Quechua?",
"¿Dónde se habla el Mapudungun?"
]
for q in questions:
if st.button(q, key=f"suggested_{q}", use_container_width=True):
st.session_state.query = q
st.markdown("---")
st.markdown("### ⚙️ Detalles Técnicos")
st.markdown("""
- Embeddings GraphSAGE
- Modelo de Lenguaje Mistral (Inference Endpoint)
- Grafo de Conocimiento Integración basada en RDF
""", unsafe_allow_html=True)
st.markdown("---")
st.markdown("### 📂 Fuentes de Datos")
st.markdown("""
- **Glottolog** (Clasificación de idiomas)
- **Wikipedia** (Resúmenes textuales)
- **Wikidata** (Hechos estructurados)
""")
st.markdown("---")
st.markdown("### 📊 Parámetros de Análisis")
k = st.slider("Número de idiomas a analizar", 1, 10, 3)
st.markdown("---")
st.markdown("### 🔧 Opciones Avanzadas")
show_ctx = st.checkbox("Mostrar información de contexto", False)
show_rdf = st.checkbox("Mostrar hechos estructurados", False)
st.markdown("### 📝 Haz una pregunta sobre lenguas indígenas")
st.markdown("*(Puedes preguntar en español o inglés, y el modelo responderá en **ambos idiomas**.)*")
query = st.text_input(
"Ingresa tu pregunta:",
value=st.session_state.get("query", ""),
label_visibility="collapsed",
placeholder="Ej. ¿Qué lenguas se hablan en Perú?"
)
if st.button("Analizar", type="primary", use_container_width=True):
if not query:
st.warning("Por favor, ingresa una pregunta")
return
label = "LinkGraph"
method = methods[label]
start = datetime.datetime.now()
response, lang_ids, context, rdf_data = generate_response(*method, query, k, embedder)
duration = (datetime.datetime.now() - start).total_seconds()
st.markdown(f"""
{response}
⏱️ {duration:.2f}s
🌐 {len(lang_ids)} idiomas
""", unsafe_allow_html=True)
if show_ctx:
with st.expander(f"📖 Contexto de {len(lang_ids)} idiomas"):
for lang_id, ctx in zip(lang_ids, context):
st.markdown(f"{ctx}
", unsafe_allow_html=True)
if show_rdf:
with st.expander("🔗 Hechos estructurados (RDF)"):
st.code("\n".join(rdf_data))
st.markdown("---")
st.markdown("""
📌 Nota: Esta herramienta está diseñada para investigadores, lingüistas y preservacionistas culturales.
Para mejores resultados, usa preguntas específicas sobre idiomas, familias o regiones.
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()