muhammadrazapathan commited on
Commit
7aba1e1
Β·
verified Β·
1 Parent(s): b0a4b96

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (set this on Hugging Face)
7
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
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
+ timestamp = datetime.now().strftime("%H:%M:%S")
35
+ history_entry = f"[{timestamp}] {direction}\nInput: {text}\nOutput: {result}\n"
36
+
37
+ return result, history_entry
38
+
39
+ except Exception as e:
40
+ return f"❌ Error: {str(e)}", ""
41
+
42
+ # Gradio UI
43
+ with gr.Blocks() as app:
44
+ gr.Markdown("# 🌍 English ↔ Urdu Translator")
45
+ gr.Markdown("Translate between English and Urdu instantly. Mobile-friendly and fast!")
46
+
47
+ with gr.Row():
48
+ direction = gr.Radio(
49
+ ["English β†’ Urdu", "Urdu β†’ English"],
50
+ value="English β†’ Urdu",
51
+ label="Translation Direction"
52
+ )
53
+
54
+ input_text = gr.Textbox(label="Enter Text", lines=5, placeholder="Type here...")
55
+ output_text = gr.Textbox(label="Translated Text", lines=5)
56
+
57
+ translate_btn = gr.Button("Translate πŸš€")
58
+
59
+ history = gr.Textbox(label="Translation History", lines=10)
60
+
61
+ translate_btn.click(
62
+ fn=translate_text,
63
+ inputs=[input_text, direction],
64
+ outputs=[output_text, history]
65
+ )
66
+
67
+ app.launch(theme=gr.themes.Soft())