Spaces:
Sleeping
Sleeping
| import os | |
| from openai import OpenAI | |
| import gradio as gr | |
| # π Load API key securely | |
| api_key = os.getenv("GROQ_API_KEY") | |
| # π§ Initialize Groq-compatible OpenAI client | |
| client = OpenAI( | |
| api_key=api_key, | |
| base_url="https://api.groq.com/openai/v1" | |
| ) | |
| # π Language options | |
| language_options = [ | |
| "Urdu", "Spanish", "French", "German", "Arabic", "Chinese", "Hindi", "Russian", "Japanese", "Turkish", | |
| "Korean", "Portuguese", "Italian", "Bengali", "Polish" | |
| ] | |
| # π§ Translation logic | |
| def translate_text(text, target_lang, history): | |
| if not text.strip() or not target_lang.strip(): | |
| return "β οΈ Please enter both English text and the target language.", history | |
| prompt = f"Translate the following English text to {target_lang}:\n\n{text}" | |
| try: | |
| response = client.chat.completions.create( | |
| model="llama3-8b-8192", | |
| messages=[{"role": "user", "content": prompt}], | |
| temperature=0.5 | |
| ) | |
| translated = response.choices[0].message.content.strip() | |
| history.append(f"π€ **English:** {text}\nπ **{target_lang}:** {translated}") | |
| return translated, history | |
| except Exception as e: | |
| return f"β Error: {str(e)}", history | |
| # π¨ Gradio UI | |
| with gr.Blocks(theme=gr.themes.Soft()) as app: | |
| gr.Markdown( | |
| """ | |
| # π English Language Translator | |
| **Features**: | |
| - Translate English text to 15+ languages | |
| - Clean modern interface | |
| - View translation history | |
| """ | |
| ) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| text_input = gr.Textbox( | |
| label="βοΈ English Text", | |
| placeholder="e.g., The building was damaged during the flood.", | |
| lines=4 | |
| ) | |
| with gr.Column(scale=1): | |
| lang_input = gr.Dropdown( | |
| label="π Select Target Language", | |
| choices=language_options, | |
| value="Urdu" | |
| ) | |
| with gr.Row(): | |
| translate_btn = gr.Button("π Translate") | |
| clear_btn = gr.Button("π§Ή Clear") | |
| output_box = gr.Textbox(label="π Translated Text", lines=6) | |
| history_display = gr.Markdown(label="π Translation History") | |
| state = gr.State([]) | |
| translate_btn.click(fn=translate_text, inputs=[text_input, lang_input, state], outputs=[output_box, state]) | |
| clear_btn.click(lambda: ("", "Urdu", "", []), outputs=[text_input, lang_input, output_box, state]) | |
| state.change(fn=lambda hist: "\n\n---\n\n".join(hist) if hist else "No translations yet.", inputs=state, outputs=history_display) | |
| # π Launch | |
| app.launch() | |