Mahrukhh commited on
Commit
6cffbdf
Β·
verified Β·
1 Parent(s): d9ffbb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -79
app.py CHANGED
@@ -2,100 +2,73 @@ 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(
10
- api_key=api_key,
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(
25
  model="llama3-8b-8192",
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, elem_id="output-box")
56
- copy_btn = gr.Button("πŸ“‹ Copy to Clipboard", elem_id="copy-btn")
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
- def download_text(translated_text):
75
- path = "/mnt/data/translation.txt"
76
- with open(path, "w", encoding="utf-8") as f:
77
- f.write(translated_text)
78
- return path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
80
- download_btn.click(download_text, inputs=[output_text], outputs=[download_btn])
 
 
81
 
82
- # πŸ”§ JavaScript for copy button
83
- gr.HTML("""
84
- <script>
85
- document.addEventListener("DOMContentLoaded", function() {
86
- const copyBtn = document.querySelector('#copy-btn button');
87
- copyBtn.addEventListener("click", function() {
88
- const outputBox = document.querySelector('textarea#output-box');
89
- if (outputBox) {
90
- navigator.clipboard.writeText(outputBox.value).then(() => {
91
- copyBtn.innerText = "βœ… Copied!";
92
- setTimeout(() => { copyBtn.innerText = "πŸ“‹ Copy to Clipboard"; }, 1500);
93
- });
94
- }
95
- });
96
- });
97
- </script>
98
- """)
99
 
100
- # πŸš€ Launch app
101
- app.launch()
 
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
+ client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
8
 
9
+ # Translation function
 
 
 
 
 
 
 
 
10
  def translate_text(text, target_lang):
11
  if not text.strip() or not target_lang.strip():
12
+ return "⚠️ Please enter both English text and target language."
13
 
14
  prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
 
15
  try:
16
  response = client.chat.completions.create(
17
  model="llama3-8b-8192",
18
  messages=[{"role": "user", "content": prompt}],
19
  temperature=0.5
20
  )
21
+ return response.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
22
  except Exception as e:
23
+ return f"❌ Error: {e}"
24
+
25
+ # Gradio UI
26
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo")) as demo:
27
+ gr.Markdown(
28
+ """
29
+ # 🌍 English Translator App
30
+ Translate any English text into your desired language using **Groq's LLaMA3 model**.
31
+
32
+ ✨ Features:
33
+ - Supports any language (e.g. Urdu, French, Spanish, Chinese)
34
+ - Clean and professional design
35
+ - Copy & download your translated text
36
+ """,
37
+ elem_id="title"
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  )
39
 
40
+ with gr.Group():
41
+ with gr.Row():
42
+ text_input = gr.Textbox(label="✏️ Enter English Text", placeholder="Type a sentence...", lines=4)
43
+ lang_input = gr.Dropdown(
44
+ label="🌐 Translate To",
45
+ choices=["Urdu", "French", "Spanish", "German", "Chinese", "Arabic", "Hindi", "Turkish", "Japanese", "Russian"],
46
+ allow_custom_value=True,
47
+ value="Urdu"
48
+ )
49
+
50
+ with gr.Row():
51
+ translate_btn = gr.Button("πŸš€ Translate", variant="primary")
52
+ copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
53
+ download_btn = gr.Button("⬇️ Download Translation")
54
+
55
+ result = gr.Textbox(label="πŸ“ Translated Text", lines=6, interactive=False)
56
+
57
+ # Button functionality
58
+ translate_btn.click(fn=translate_text, inputs=[text_input, lang_input], outputs=result)
59
+
60
+ # Copy to clipboard
61
+ copy_btn.click(
62
+ None,
63
+ inputs=[],
64
+ outputs=[],
65
+ js="() => navigator.clipboard.writeText(document.querySelector('textarea[aria-label=\"πŸ“ Translated Text\"]').value)"
66
+ )
67
 
68
+ # Download
69
+ def download_translation(text):
70
+ return gr.File.update(value=text.encode(), filename="translation.txt")
71
 
72
+ download_btn.click(download_translation, inputs=result, outputs=gr.File())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
+ demo.launch()