File size: 2,126 Bytes
7aba1e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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())