import gradio as gr from groq import Groq import os # Initialize Groq client (reads GROQ_API_KEY from environment) client = Groq(api_key=os.environ.get("GROQ_API_KEY")) # Step 5: Translation function def translate_to_urdu(english_text): """ Translate English text to Urdu using Groq API """ if not english_text or english_text.strip() == "": return "Please enter some text to translate." try: chat_completion = client.chat.completions.create( messages=[ { "role": "system", "content": "You are a professional translator. Translate the given English text to Urdu. Only return the translation, no explanations or additional text. Ensure the translation is accurate and natural in Urdu." }, { "role": "user", "content": f"Translate this to Urdu: {english_text}" } ], model="llama-3.3-70b-versatile", # or "mixtral-8x7b-32768", "gemma2-9b-it" temperature=0.3, max_tokens=1024, stream=False ) urdu_translation = chat_completion.choices[0].message.content return urdu_translation except Exception as e: return f"Error: {str(e)}" # Step 6: Create Gradio Interface with gr.Blocks(title="English to Urdu Translator") as demo: gr.Markdown( """ # 🇬🇧 ➡️ 🇵🇰 English to Urdu Translator Powered by Groq AI (Llama 3.3 70B) """ ) with gr.Row(): with gr.Column(): input_text = gr.Textbox( label="English Text", placeholder="Enter text in English...", lines=5 ) translate_btn = gr.Button("Translate", variant="primary") with gr.Column(): output_text = gr.Textbox( label="Urdu Translation", placeholder="Translation will appear here...", lines=5, interactive=False ) # Examples gr.Examples( examples=[ ["Hello, how are you?"], ["I love learning new languages."], ["Pakistan is a beautiful country with rich culture."], ["Thank you very much for your help."], ["The weather is very nice today."] ], inputs=input_text, label="Try these examples" ) # Event handler translate_btn.click( fn=translate_to_urdu, inputs=input_text, outputs=output_text ) # Optional: Auto-translate on Enter key input_text.submit( fn=translate_to_urdu, inputs=input_text, outputs=output_text ) # Step 7: Launch the app demo.launch(share=True, debug=True)