File size: 1,983 Bytes
7e52324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import openai
import gradio as gr

# Load Groq API key from Hugging Face Secret (name must be 'translate_API')
openai.api_key = os.environ.get("translate_API", "")
openai.api_base = "https://api.groq.com/openai/v1"

if not openai.api_key:
    raise ValueError("❌ Missing API key! Please add 'translate_API' in your HF Space > Settings > Secrets.")

# Language options
languages = [
    "Arabic", "Bengali", "Chinese", "Czech", "Dutch", "English", "French", "German", "Greek", "Gujarati",
    "Hebrew", "Hindi", "Hungarian", "Indonesian", "Italian", "Japanese", "Kannada", "Korean", "Malayalam",
    "Marathi", "Nepali", "Pashto", "Persian", "Polish", "Portuguese", "Punjabi", "Romanian", "Russian",
    "Sindhi", "Sinhala", "Spanish", "Swahili", "Swedish", "Tamil", "Telugu", "Thai", "Turkish", "Ukrainian",
    "Urdu", "Vietnamese"
]

# Translation function
def translate(text, target_lang):
    prompt = f"Translate the following to {target_lang}:\n\n{text}"
    try:
        response = openai.ChatCompletion.create(
            model="llama3-8b-8192",
            messages=[{"role": "user", "content": prompt}],
            temperature=0.3,
        )
        return text, response['choices'][0]['message']['content'].strip()
    except Exception as e:
        return text, f"⚠️ Error: {str(e)}"

# Gradio interface
with gr.Blocks() as app:
    gr.Markdown("## 🌐 Multilingual Translator using Groq + LLaMA3")
    gr.Markdown("Translate any sentence into your selected language (Urdu included).")

    with gr.Row():
        input_box = gr.Textbox(label="Enter Sentence", placeholder="e.g., How are you?", lines=2)
        output_box = gr.Textbox(label="Translated Output", interactive=False, lines=3)

    lang_dropdown = gr.Dropdown(choices=languages, value="Urdu", label="Target Language")
    translate_button = gr.Button("Translate")

    translate_button.click(fn=translate, inputs=[input_box, lang_dropdown], outputs=[input_box, output_box])

app.launch()