Spaces:
Runtime error
Runtime error
| # app.py | |
| import requests | |
| import json | |
| import gradio as gr | |
| import os | |
| # Step 1: Get your Groq API Key from environment variable | |
| GROQ_API_KEY = os.getenv("GROQ_API_KEY") # Hugging Face will set this secretly | |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| # Step 2: Function to call Groq API | |
| def translate_text(text, target_language, model="llama3-8b-8192"): | |
| if not GROQ_API_KEY: | |
| return "β οΈ Error: GROQ_API_KEY not found. Please set it in the environment variables." | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json", | |
| } | |
| prompt = ( | |
| f"Translate the following text into {target_language}. " | |
| "Only provide the translated text without any extra explanation.\n\n" | |
| f"Text: {text}" | |
| ) | |
| payload = { | |
| "model": model, | |
| "messages": [{"role": "user", "content": prompt}], | |
| "temperature": 0.3, | |
| "stream": False | |
| } | |
| try: | |
| response = requests.post(GROQ_API_URL, headers=headers, data=json.dumps(payload), timeout=20) | |
| response.raise_for_status() | |
| response_json = response.json() | |
| translation = response_json['choices'][0]['message']['content'] | |
| return translation.strip() | |
| except requests.exceptions.RequestException as e: | |
| print("π΄ Connection Error:", e) | |
| return "β οΈ Error connecting to Groq API." | |
| # Step 3: Gradio Interface | |
| def gradio_translate(text, target_language): | |
| return translate_text(text, target_language) | |
| with gr.Blocks() as app: | |
| gr.Markdown("# π Language Translator App (powered by Groq LLaMA3)") | |
| gr.Markdown("Type anything, select your target language, and get translation instantly!") | |
| with gr.Row(): | |
| input_text = gr.Textbox(label="Enter Text", placeholder="Type something...") | |
| target_lang = gr.Dropdown( | |
| ["French", "Spanish", "German", "Chinese", "Arabic", "Hindi", "Urdu", "Japanese", "Italian", "Russian"], | |
| label="Translate to", | |
| value="French" | |
| ) | |
| output_text = gr.Textbox(label="Translated Text") | |
| translate_button = gr.Button("Translate π") | |
| translate_button.click(fn=gradio_translate, inputs=[input_text, target_lang], outputs=output_text) | |
| # Step 4: Launch App | |
| app.launch() |