Spaces:
Sleeping
Sleeping
File size: 10,626 Bytes
3e81500 c0b19fe 3e81500 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 |
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) |