Mahrukhh commited on
Commit
5a14ea9
Β·
verified Β·
1 Parent(s): 339b895

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -39
app.py CHANGED
@@ -1,12 +1,9 @@
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(
@@ -14,16 +11,14 @@ client = OpenAI(
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(
@@ -31,50 +26,60 @@ def translate_text(text, target_lang):
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()
 
1
  import os
2
  from openai import OpenAI
3
  import gradio as gr
 
4
 
5
+ # πŸ” Load Groq API key
6
  api_key = os.getenv("GROQ_API_KEY")
 
 
7
 
8
  # βœ… Groq-compatible OpenAI client
9
  client = OpenAI(
 
11
  base_url="https://api.groq.com/openai/v1"
12
  )
13
 
14
+ # 🧠 Translation function with history
15
  translation_history = []
16
 
 
17
  def translate_text(text, target_lang):
18
  if not text.strip() or not target_lang.strip():
19
+ return "⚠️ Please enter both English text and a target language.", gr.update(visible=False)
20
 
21
+ prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
 
22
 
23
  try:
24
  response = client.chat.completions.create(
 
26
  messages=[{"role": "user", "content": prompt}],
27
  temperature=0.5
28
  )
29
+ translation = response.choices[0].message.content.strip()
30
 
31
+ # Add to history (limit 5)
32
+ translation_history.append(f"**{target_lang}**: {translation}")
33
+ if len(translation_history) > 5:
34
+ translation_history.pop(0)
35
 
36
+ return translation, gr.update(visible=True)
37
 
38
  except Exception as e:
39
+ return f"❌ Error: {e}", gr.update(visible=False)
40
 
41
+ # πŸ“‹ Languages list
42
+ language_choices = ["Urdu", "French", "Spanish", "German", "Chinese", "Arabic", "Hindi", "Turkish", "Japanese", "Russian"]
43
+
44
+ # πŸŽ› Gradio UI
45
  with gr.Blocks(theme=gr.themes.Monochrome()) as app:
46
+ gr.Markdown("# 🌍 English Translator App")
47
+ gr.Markdown("Translate any English sentence into your desired language using Groq's **LLaMA3** model.")
 
 
48
 
49
  with gr.Row():
50
  with gr.Column():
51
+ text_input = gr.Textbox(label="Enter English Text", placeholder="Type your sentence here...", lines=4)
52
+ language_dropdown = gr.Dropdown(choices=language_choices, label="Translate to", value="Urdu")
53
+ translate_btn = gr.Button("🌐 Translate")
 
 
 
 
54
  with gr.Column():
55
+ output_text = gr.Textbox(label="Translated Text", lines=4)
56
  copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
57
+ download_btn = gr.Button("⬇️ Download Translation", visible=False)
58
+
59
+ with gr.Accordion("πŸ•“ Translation History", open=False):
60
+ history_box = gr.Markdown("")
61
+
62
+ # πŸ” Bind functions
63
+ translate_btn.click(
64
+ translate_text,
65
+ inputs=[text_input, language_dropdown],
66
+ outputs=[output_text, download_btn]
67
+ )
68
+
69
+ def update_history():
70
+ return "\n\n".join(translation_history)
71
+
72
+ translate_btn.click(fn=update_history, outputs=[history_box])
73
 
74
+ copy_btn.click(fn=None, inputs=[], outputs=[], _js="() => navigator.clipboard.writeText(document.querySelector('textarea[aria-label=\"Translated Text\"]').value)")
 
75
 
76
+ def download_text(translated_text):
77
+ path = "/mnt/data/translation.txt"
78
+ with open(path, "w", encoding="utf-8") as f:
79
+ f.write(translated_text)
80
+ return path
81
 
82
+ download_btn.click(download_text, inputs=[output_text], outputs=[download_btn])
 
 
83
 
84
  # πŸš€ Launch app
85
  app.launch()