FaizaRiaz commited on
Commit
03b46a5
Β·
verified Β·
1 Parent(s): 15fb427

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+
5
+ # Get GROQ API key from Hugging Face secret
6
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
+
8
+ API_URL = "https://api.groq.com/openai/v1/chat/completions"
9
+
10
+ LANGUAGES = [
11
+ "Urdu", "Hindi", "Arabic", "Spanish", "French", "German",
12
+ "Chinese", "Japanese", "Korean", "Turkish", "Italian", "Russian"
13
+ ]
14
+
15
+ def translate_text(text, target_language):
16
+ headers = {
17
+ "Authorization": f"Bearer {GROQ_API_KEY}",
18
+ "Content-Type": "application/json"
19
+ }
20
+
21
+ prompt = f"""Translate the following English text into {target_language}:
22
+
23
+ English: "{text}"
24
+
25
+ {target_language}:"""
26
+
27
+ payload = {
28
+ "model": "llama3-70b-8192",
29
+ "messages": [
30
+ {"role": "system", "content": "You are a helpful assistant that translates English into other languages."},
31
+ {"role": "user", "content": prompt}
32
+ ],
33
+ "temperature": 0.3
34
+ }
35
+
36
+ try:
37
+ response = requests.post(API_URL, headers=headers, json=payload)
38
+
39
+ if response.status_code != 200:
40
+ return f"❌ API Error {response.status_code}: {response.text}"
41
+
42
+ result = response.json()
43
+
44
+ if "choices" in result:
45
+ return result["choices"][0]["message"]["content"].strip()
46
+ else:
47
+ return f"❌ Unexpected response format: {result}"
48
+
49
+ except Exception as e:
50
+ return f"❌ Exception occurred: {str(e)}"
51
+
52
+ # Gradio UI
53
+ with gr.Blocks() as demo:
54
+ gr.Markdown("## 🌍 English Text Translator using GROQ API")
55
+ gr.Markdown("Translate English into your chosen language.")
56
+
57
+ with gr.Row():
58
+ input_text = gr.Textbox(label="✍️ Enter English text", lines=4, placeholder="Type something...")
59
+ output_text = gr.Textbox(label="πŸ”€ Translated Text", lines=4)
60
+
61
+ language_dropdown = gr.Dropdown(choices=LANGUAGES, label="🌐 Choose Target Language")
62
+ translate_btn = gr.Button("πŸ” Translate")
63
+
64
+ translate_btn.click(translate_text, inputs=[input_text, language_dropdown], outputs=output_text)
65
+
66
+ demo.launch()