[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 = requests.post(
f"https://api-inference.huggingface.co/models/{MODEL_ID}",
headers={"Authorization": f"Bearer {os.getenv('HF_API_TOKEN')}", "Content-Type": "application/json"},
json={"inputs": prompt}, timeout=30
)
out = res.json()
if isinstance(out, list) and "generated_text" in out[0]:
return out[0]["generated_text"].replace(prompt.strip(), "").strip(), ids, context, rdf_facts
return str(out), ids, context, rdf_facts
except Exception as e:
return str(e), ids, context, rdf_facts
# === MAIN FUNCTION ===
def main():
st.markdown("""
Linguistic Emergency: Over 40% of South America's indigenous languages face extinction.
This tool documents these cultural treasures before they disappear forever.
""", unsafe_allow_html=True)
with st.sidebar:
st.image("https://glottolog.org/static/img/glottolog_lod.png", width=180)
with st.container():
st.markdown('', unsafe_allow_html=True)
st.markdown("""
Standard Search
Semantic retrieval based on text-only embeddings. Identifies languages using purely linguistic similarity from Wikipedia summaries and labels.
Hybrid Search
Combines semantic embeddings with structured data from knowledge graphs. Enriches language representation with contextual facts.
GraphSAGE Search
Leverages deep graph neural networks to learn relational patterns across languages. Captures complex cultural and genealogical connections.
""", unsafe_allow_html=True)
with st.container():
st.markdown('', unsafe_allow_html=True)
k = st.slider("Languages to analyze per query", 1, 10, 3)
st.markdown("**Display Options:**")
show_ids = st.checkbox("Language IDs", value=True, key="show_ids")
show_ctx = st.checkbox("Cultural Context", value=True, key="show_ctx")
show_rdf = st.checkbox("RDF Relations", value=True, key="show_rdf")
with st.container():
st.markdown('', unsafe_allow_html=True)
st.markdown("""
- Glottolog
- Wikidata
- Wikipedia
- Ethnologue
""")
query = st.text_input("Ask about indigenous languages:", "Which Amazonian languages are most at risk?")
if st.button("Analyze with All Methods") and query:
col1, col2, col3 = st.columns(3)
results = {}
for col, (label, method) in zip([col1, col2, col3], methods.items()):
with col:
st.subheader(f"{label} Analysis")
start = datetime.datetime.now()
response, lang_ids, context, rdf_data = generate_response(*method, query, k)
duration = (datetime.datetime.now() - start).total_seconds()
st.markdown(response)
st.markdown(f"⏱️ {duration:.2f}s | 🌐 {len(lang_ids)} languages")
if show_ids:
st.markdown("**Language Identifiers:**")
st.code("\n".join(lang_ids))
if show_ctx:
st.markdown("**Cultural Context:**")
st.markdown("\n\n---\n\n".join(context))
if show_rdf:
st.markdown("**RDF Knowledge:**")
st.code("\n".join(rdf_data))
results[label] = response
log = f"""
[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]
QUERY: {query}
STANDARD:
{results.get('Standard', '')}
HYBRID:
{results.get('Hybrid', '')}
GRAPH-SAGE:
{results.get('GraphSAGE', '')}
{'='*60}
"""
try:
with open("language_analysis_logs.txt", "a", encoding="utf-8") as f:
f.write(log)
except Exception as e:
st.warning(f"Failed to log: {str(e)}")
if __name__ == "__main__":
main()