muhammadrazapathan commited on
Commit
40bb168
Β·
verified Β·
1 Parent(s): 2eaf803

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -0
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from groq import Groq
3
+ import os
4
+ from datetime import datetime
5
+
6
+ # Load API key from environment variable
7
+ GROQ_API_KEY = os.getenv("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")
8
+
9
+ client = Groq(api_key=GROQ_API_KEY)
10
+
11
+ def translate_text(text, direction):
12
+ if not text.strip():
13
+ return "Please enter some text.", ""
14
+
15
+ if direction == "English β†’ Urdu":
16
+ system_prompt = "You are a professional English to Urdu translator."
17
+ user_prompt = f"Translate this English text to Urdu:\n{text}"
18
+ else:
19
+ system_prompt = "You are a professional Urdu to English translator."
20
+ user_prompt = f"Translate this Urdu text to English:\n{text}"
21
+
22
+ try:
23
+ completion = client.chat.completions.create(
24
+ model="llama3-8b-8192",
25
+ messages=[
26
+ {"role": "system", "content": system_prompt},
27
+ {"role": "user", "content": user_prompt}
28
+ ],
29
+ temperature=0.2,
30
+ max_tokens=500
31
+ )
32
+ result = completion.choices[0].message.content
33
+
34
+ # Add to history
35
+ timestamp = datetime.now().strftime("%H:%M:%S")
36
+ history_entry = f"[{timestamp}] {direction}\nInput: {text}\nOutput: {result}\n"
37
+
38
+ return result, history_entry
39
+
40
+ except Exception as e:
41
+ return f"❌ Error: {str(e)}", ""
42
+
43
+ # Gradio UI
44
+ with gr.Blocks(theme=gr.themes.Soft()) as app:
45
+ gr.Markdown("# 🌍 English ↔ Urdu Translator")
46
+ gr.Markdown("Translate between English and Urdu instantly. Mobile-friendly and fast!")
47
+
48
+ with gr.Row():
49
+ direction = gr.Radio(
50
+ ["English β†’ Urdu", "Urdu β†’ English"],
51
+ value="English β†’ Urdu",
52
+ label="Translation Direction"
53
+ )
54
+
55
+ input_text = gr.Textbox(
56
+ label="Enter Text",
57
+ placeholder="Type your text here...",
58
+ lines=5
59
+ )
60
+
61
+ translate_button = gr.Button("πŸ” Translate", variant="primary")
62
+
63
+ output_text = gr.Textbox(
64
+ label="Translated Text",
65
+ lines=5,
66
+ show_copy_button=True
67
+ )
68
+
69
+ history_box = gr.Textbox(
70
+ label="Translation History",
71
+ lines=8,
72
+ interactive=False
73
+ )
74
+
75
+ translate_button.click(
76
+ fn=translate_text,
77
+ inputs=[input_text, direction],
78
+ outputs=[output_text, history_box],
79
+ append_to_history=True
80
+ )
81
+
82
+ app.launch()