Mahrukhh commited on
Commit
a364322
Β·
verified Β·
1 Parent(s): 0634ef2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -40
app.py CHANGED
@@ -1,70 +1,80 @@
1
  import os
2
  from openai import OpenAI
3
  import gradio as gr
 
4
 
5
- # πŸ” Load API key securely (from HF Spaces Secrets or local environment)
6
- api_key = os.getenv("GROQ_API_KEY") # Set this in your environment
 
 
7
 
8
- # 🧠 Initialize Groq-compatible OpenAI client
9
  client = OpenAI(
10
  api_key=api_key,
11
  base_url="https://api.groq.com/openai/v1"
12
  )
13
 
 
 
 
14
  # 🌐 Translation function
15
  def translate_text(text, target_lang):
16
  if not text.strip() or not target_lang.strip():
17
- return "⚠️ Please enter both English text and the target language."
 
 
 
18
 
19
- prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
20
-
21
  try:
22
  response = client.chat.completions.create(
23
  model="llama3-8b-8192",
24
  messages=[{"role": "user", "content": prompt}],
25
  temperature=0.5
26
  )
27
- return response.choices[0].message.content.strip()
28
- except Exception as e:
29
- return f"❌ Error: {str(e)}"
30
 
31
- # 🎨 Gradio UI
32
- with gr.Blocks(theme=gr.themes.Soft()) as app:
33
- gr.Markdown(
34
- """
35
- # 🌍 English Language Translator
36
- Translate any English text into your desired language using **Groq's LLaMA3 model**.
37
- """
38
- )
39
 
40
- with gr.Row():
41
- with gr.Column(scale=1):
42
- gr.Markdown("### ✏️ Enter English Text")
43
- text_input = gr.Textbox(
44
- placeholder="e.g., The construction site was damaged after the storm.",
45
- lines=4,
46
- label="English Text"
47
- )
48
 
49
- with gr.Column(scale=1):
50
- gr.Markdown("### 🌐 Target Language")
51
- lang_input = gr.Textbox(
52
- placeholder="e.g., Urdu, Spanish, French",
53
- label="Target Language"
54
- )
 
 
 
55
 
56
  with gr.Row():
57
- translate_btn = gr.Button("🌐 Translate")
58
- clear_btn = gr.Button("🧹 Clear")
 
 
 
 
 
 
 
 
 
 
59
 
60
- output_box = gr.Textbox(label="πŸ“ Translated Text", lines=6)
 
61
 
62
- # Bind button actions
63
- translate_btn.click(fn=translate_text, inputs=[text_input, lang_input], outputs=[output_box])
64
- clear_btn.click(lambda: ("", "", ""), outputs=[text_input, lang_input, output_box])
 
 
65
 
66
- gr.Markdown("---")
67
- gr.Markdown("⚑ Powered by [Groq](https://groq.com) | Built with ❀️ and [Gradio](https://gradio.app)")
 
68
 
69
- # πŸš€ Launch
70
  app.launch()
 
1
  import os
2
  from openai import OpenAI
3
  import gradio as gr
4
+ from datetime import datetime
5
 
6
+ # πŸ” Load Groq API key (set this in Hugging Face Secrets)
7
+ api_key = os.getenv("GROQ_API_KEY")
8
+ if not api_key:
9
+ raise RuntimeError("❌ GROQ_API_KEY is missing. Set it in your environment.")
10
 
11
+ # βœ… Groq-compatible OpenAI client
12
  client = OpenAI(
13
  api_key=api_key,
14
  base_url="https://api.groq.com/openai/v1"
15
  )
16
 
17
+ # 🧠 Session-based translation history
18
+ translation_history = []
19
+
20
  # 🌐 Translation function
21
  def translate_text(text, target_lang):
22
  if not text.strip() or not target_lang.strip():
23
+ return "⚠️ Please enter both English text and select a target language.", ""
24
+
25
+ prompt = f"Translate the following English text to {target_lang}:
26
+ \n{text}"
27
 
 
 
28
  try:
29
  response = client.chat.completions.create(
30
  model="llama3-8b-8192",
31
  messages=[{"role": "user", "content": prompt}],
32
  temperature=0.5
33
  )
34
+ translated = response.choices[0].message.content.strip()
 
 
35
 
36
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
37
+ history_entry = f"[{timestamp}] ➀ {target_lang}\nπŸ“€ {text}\nπŸ“₯ {translated}\n"
38
+ translation_history.append(history_entry)
 
 
 
 
 
39
 
40
+ return translated, "\n---\n".join(translation_history[-5:])
 
 
 
 
 
 
 
41
 
42
+ except Exception as e:
43
+ return f"❌ Error: {e}", ""
44
+
45
+ # πŸŽ› Gradio UI with enhanced design and features
46
+ with gr.Blocks(theme=gr.themes.Monochrome()) as app:
47
+ gr.Markdown("""
48
+ # 🌍 **Ultimate English Translator App**
49
+ Translate English into any major language using Groq's blazing-fast LLaMA 3 model.
50
+ """)
51
 
52
  with gr.Row():
53
+ with gr.Column():
54
+ input_text = gr.Textbox(label="✏️ Enter English Text", lines=3, placeholder="Type something in English...")
55
+ lang_dropdown = gr.Dropdown(
56
+ label="🌐 Target Language",
57
+ choices=["Urdu", "French", "Spanish", "German", "Arabic", "Hindi", "Chinese", "Russian", "Turkish", "Japanese"],
58
+ value="Urdu"
59
+ )
60
+ translate_button = gr.Button("πŸš€ Translate")
61
+ with gr.Column():
62
+ output_text = gr.Textbox(label="πŸ“ Translated Text", lines=3)
63
+ copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
64
+ download_btn = gr.Button("πŸ’Ύ Download as .txt")
65
 
66
+ with gr.Accordion("πŸ“œ Translation History (Last 5)", open=False):
67
+ history_box = gr.Textbox(label="History", lines=8, interactive=False)
68
 
69
+ def download_translation(txt):
70
+ filename = "translation.txt"
71
+ with open(filename, "w", encoding="utf-8") as f:
72
+ f.write(txt)
73
+ return filename
74
 
75
+ translate_button.click(translate_text, inputs=[input_text, lang_dropdown], outputs=[output_text, history_box])
76
+ copy_btn.click(lambda x: x, inputs=output_text, outputs=output_text, show_progress=False)
77
+ download_btn.click(download_translation, inputs=output_text, outputs=gr.File(label="Download Translation"))
78
 
79
+ # πŸš€ Launch app
80
  app.launch()