import gradio as gr from groq import Groq import os from datetime import datetime # Load API key from environment variable (set this on Hugging Face) GROQ_API_KEY = os.getenv("GROQ_API_KEY") client = Groq(api_key=GROQ_API_KEY) def translate_text(text, direction): if not text.strip(): return "Please enter some text.", "" if direction == "English → Urdu": system_prompt = "You are a professional English to Urdu translator." user_prompt = f"Translate this English text to Urdu:\n{text}" else: system_prompt = "You are a professional Urdu to English translator." user_prompt = f"Translate this Urdu text to English:\n{text}" try: completion = client.chat.completions.create( model="llama3-8b-8192", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt} ], temperature=0.2, max_tokens=500 ) result = completion.choices[0].message.content timestamp = datetime.now().strftime("%H:%M:%S") history_entry = f"[{timestamp}] {direction}\nInput: {text}\nOutput: {result}\n" return result, history_entry except Exception as e: return f"❌ Error: {str(e)}", "" # Gradio UI with gr.Blocks() as app: gr.Markdown("# 🌍 English ↔ Urdu Translator") gr.Markdown("Translate between English and Urdu instantly. Mobile-friendly and fast!") with gr.Row(): direction = gr.Radio( ["English → Urdu", "Urdu → English"], value="English → Urdu", label="Translation Direction" ) input_text = gr.Textbox(label="Enter Text", lines=5, placeholder="Type here...") output_text = gr.Textbox(label="Translated Text", lines=5) translate_btn = gr.Button("Translate 🚀") history = gr.Textbox(label="Translation History", lines=10) translate_btn.click( fn=translate_text, inputs=[input_text, direction], outputs=[output_text, history] ) app.launch(theme=gr.themes.Soft())