Josebert's picture
Update app.py
c0b19fe verified
import os
import json
import gradio as gr
from groq import Groq
import requests
from typing import Dict, Any
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class IbibioTranslationAgent:
def __init__(self):
self.groq_client = None
self.tavily_api_key = None
self.setup_apis()
# Local Ibibio dictionary (basic fallback)
self.local_dictionary = {
"hello": "ndimesiere",
"thank you": "sosongo",
"good morning": "emesiere ntak",
"good evening": "emesiere ekey",
"yes": "ayi",
"no": "mme",
"water": "mmong",
"food": "ndinyanga",
"house": "ufok",
"child": "akanamukoro"
}
def setup_apis(self):
"""Initialize API clients"""
try:
groq_api_key = os.getenv("GROQ_API_KEY")
self.tavily_api_key = os.getenv("TAVILY_API_KEY")
if groq_api_key:
self.groq_client = Groq(api_key=groq_api_key)
logger.info("Groq client initialized successfully")
else:
logger.warning("GROQ_API_KEY not found")
if not self.tavily_api_key:
logger.warning("TAVILY_API_KEY not found")
except Exception as e:
logger.error(f"Error setting up APIs: {e}")
def search_web(self, query: str) -> str:
"""Search web using Tavily API"""
if not self.tavily_api_key:
return "Web search unavailable - API key not configured"
try:
url = "https://api.tavily.com/search"
payload = {
"api_key": self.tavily_api_key,
"query": f"{query} Ibibio language translation",
"search_depth": "basic",
"include_answer": True,
"max_results": 3
}
response = requests.post(url, json=payload, timeout=10)
response.raise_for_status()
data = response.json()
if data.get("answer"):
return data["answer"]
elif data.get("results"):
# Combine top results
results = []
for result in data["results"][:2]:
results.append(f"β€’ {result.get('content', '')[:200]}")
return "\n".join(results)
else:
return "No web results found"
except Exception as e:
logger.error(f"Web search error: {e}")
return f"Web search failed: {str(e)}"
def check_local_dictionary(self, query: str) -> str:
"""Check local dictionary for basic translations"""
query_lower = query.lower().strip()
# Direct lookup
if query_lower in self.local_dictionary:
return f"Local dictionary: '{query_lower}' in Ibibio is '{self.local_dictionary[query_lower]}'"
# Partial matching
for eng, ibibio in self.local_dictionary.items():
if eng in query_lower or query_lower in eng:
return f"Local dictionary match: '{eng}' in Ibibio is '{ibibio}'"
return None
def groq_reasoning(self, query: str, web_results: str = None, local_result: str = None) -> str:
"""Use Groq for intelligent reasoning about translation"""
if not self.groq_client:
return "Groq API not available"
try:
# Build context
context_parts = []
if local_result:
context_parts.append(f"Local dictionary result: {local_result}")
if web_results and "unavailable" not in web_results.lower():
context_parts.append(f"Web search results: {web_results}")
context = "\n".join(context_parts) if context_parts else "No additional context available"
prompt = f"""You are an expert in Ibibio language translation. The user asked: "{query}"
Available information:
{context}
Your task:
1. If this is asking for Ibibio translation, provide the most accurate translation possible
2. If you have conflicting information, explain which source seems more reliable
3. If you don't have enough information, be honest about limitations
4. Always format your response clearly for the user
Provide a helpful, accurate response:"""
response = self.groq_client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=[
{"role": "system", "content": "You are a helpful Ibibio language translation assistant."},
{"role": "user", "content": prompt}
],
max_tokens=300,
temperature=0.3
)
return response.choices[0].message.content.strip()
except Exception as e:
logger.error(f"Groq reasoning error: {e}")
return f"AI reasoning failed: {str(e)}"
def translate_online(self, query: str) -> Dict[str, Any]:
"""Main translation function that combines all methods"""
try:
logger.info(f"Processing query: {query}")
# Step 1: Check local dictionary
local_result = self.check_local_dictionary(query)
# Step 2: Search web for additional context
web_results = self.search_web(query)
# Step 3: Use Groq for intelligent reasoning
ai_response = self.groq_reasoning(query, web_results, local_result)
# Compile response
response = {
"query": query,
"ai_response": ai_response,
"local_dictionary": local_result,
"web_search": web_results if "unavailable" not in web_results.lower() else None,
"status": "success"
}
return response
except Exception as e:
logger.error(f"Translation error: {e}")
return {
"query": query,
"error": str(e),
"status": "error"
}
# Initialize the agent
agent = IbibioTranslationAgent()
def translate_interface(query: str) -> str:
"""Gradio interface function"""
if not query.strip():
return "Please enter a translation query."
result = agent.translate_online(query)
if result["status"] == "error":
return f"❌ Error: {result['error']}"
# Format response for display
response_parts = []
if result.get("ai_response"):
response_parts.append(f"πŸ€– **AI Translation:**\n{result['ai_response']}")
if result.get("local_dictionary"):
response_parts.append(f"\nπŸ“š **Local Dictionary:**\n{result['local_dictionary']}")
if result.get("web_search"):
response_parts.append(f"\nπŸ” **Web Research:**\n{result['web_search'][:300]}...")
return "\n\n".join(response_parts) if response_parts else "No translation found."
def api_interface(query: str) -> str:
"""API-style interface that returns JSON"""
result = agent.translate_online(query)
return json.dumps(result, indent=2)
# Create Gradio interface
with gr.Blocks(title="Ibi-Voice Translation Backend", theme=gr.themes.Soft()) as app:
gr.Markdown("""
# 🎯 Ibi-Voice Translation Backend
**JR Digital Insights** - AI-powered Ibibio translation service
This backend combines:
- 🧠 **Groq LLaMA3** for intelligent reasoning
- πŸ” **Tavily Search** for real-time web lookup
- πŸ“š **Local Dictionary** for common phrases
""")
with gr.Tab("🎯 Translation Interface"):
with gr.Row():
with gr.Column():
query_input = gr.Textbox(
label="Enter your translation query",
placeholder="e.g., 'What is God is good in Ibibio?'",
lines=2
)
translate_btn = gr.Button("πŸš€ Translate", variant="primary")
with gr.Column():
translation_output = gr.Markdown(
label="Translation Result",
value="Enter a query to get started..."
)
# Examples
gr.Examples(
examples=[
["What is 'God is good' in Ibibio?"],
["How do you say 'thank you' in Ibibio?"],
["Translate 'good morning' to Ibibio"],
["What does 'sosongo' mean in English?"]
],
inputs=query_input
)
with gr.Tab("πŸ”§ API Format"):
gr.Markdown("### For developers: Raw JSON API response")
api_query = gr.Textbox(label="API Query", placeholder="Enter query for JSON response")
api_btn = gr.Button("Get JSON Response")
api_output = gr.Code(label="JSON Response", language="json")
api_btn.click(api_interface, inputs=api_query, outputs=api_output)
with gr.Tab("πŸ“‹ Setup Instructions"):
gr.Markdown("""
### πŸ”‘ Required Environment Variables
To use this backend, set these in your Hugging Face Space settings:
```bash
GROQ_API_KEY=your_groq_api_key_here
TAVILY_API_KEY=your_tavily_api_key_here
```
### 🌐 API Endpoint
Once deployed, your frontend can call:
```
POST https://your-username-ibi-voice-backend.hf.space/api/predict
```
### πŸ”— Integration with Your Frontend
```javascript
async function translateOnline(query) {
const response = await fetch('https://your-space-url.hf.space/api/predict', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
data: [query],
fn_index: 0
})
});
const result = await response.json();
return result.data[0];
}
```
""")
# Connect the interface
translate_btn.click(translate_interface, inputs=query_input, outputs=translation_output)
# Launch the app
if __name__ == "__main__":
app.launch(server_name="0.0.0.0", server_port=7860)