Download app.py from Ai1996/AwazHub21: direct link, hf CLI and curl.
- Browser
- Download file 2.69 kB
-
https://huggingface.co/spaces/Ai1996/AwazHub21/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ai1996/AwazHub21/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ai1996/AwazHub21/resolve/main/app.py
2.69 kB
| # app.py | |
| import gradio as gr | |
| import requests | |
| import os | |
| # Set your GROQ API key here | |
| groq_api_key = os.getenv("GROQ_API_KEY") or "your-groq-api-key" | |
| def translate_text(text, target_language): | |
| headers = { | |
| "Authorization": f"Bearer {groq_api_key}", | |
| "Content-Type": "application/json" | |
| } | |
| # More explicit system prompt for translation | |
| prompt = ( | |
| f"You are a professional translator. ONLY return the translated version of the following message into {target_language}. " | |
| f"Do not add any notes, comments, or explanations. Keep the meaning and tone the same." | |
| ) | |
| data = { | |
| "model": "llama3-8b-8192", | |
| "messages": [ | |
| {"role": "system", "content": prompt}, | |
| {"role": "user", "content": text} | |
| ] | |
| } | |
| try: | |
| response = requests.post( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| headers=headers, | |
| json=data, | |
| timeout=20 | |
| ) | |
| response.raise_for_status() | |
| content = response.json()['choices'][0]['message']['content'].strip() | |
| # Clean the result if there's extra explanation | |
| for unwanted in ["Translation:", "Translated text:", "Here is the"]: | |
| if content.lower().startswith(unwanted.lower()): | |
| content = content[len(unwanted):].strip(":").strip() | |
| return content | |
| except requests.exceptions.RequestException as e: | |
| return f"Error: {str(e)}" | |
| def handle_submission(post_text, category, language): | |
| translated = translate_text(post_text, language) | |
| return f"**Category:** {category}\\n\\n**Original:** {post_text}\\n\\n**Translated to {language}:** {translated}" | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(\"\"\"\n # AwaazHub\n **Your Local Community Bulletin**\n \n Share local news, job openings, lost items, and more — auto-translated into regional languages to make sure everyone stays informed.\n \"\"\") | |
| with gr.Row(): | |
| post_text = gr.Textbox(label="Your Message", lines=4, placeholder="Write your announcement here...") | |
| with gr.Row(): | |
| category = gr.Dropdown( | |
| choices=["Announcements", "Events", "Job Postings", "Lost & Found", "Community Initiatives"], | |
| label="Select Category" | |
| ) | |
| language = gr.Dropdown( | |
| choices=["Urdu", "Punjabi", "Sindhi", "Pashto", "Balochi", "Saraiki"], | |
| label="Translate To" | |
| ) | |
| submit_btn = gr.Button("Post") | |
| output = gr.Markdown() | |
| submit_btn.click(fn=handle_submission, inputs=[post_text, category, language], outputs=output) | |
| if __name__ == "__main__": | |
| demo.launch() |