Mahrukhh commited on
Commit
a14c8e3
Β·
verified Β·
1 Parent(s): 2581003

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -51
app.py CHANGED
@@ -1,21 +1,22 @@
1
  import os
2
  from openai import OpenAI
3
  import gradio as gr
4
- from datetime import datetime
5
 
6
- # Load Groq API Key
7
  api_key = os.getenv("GROQ_API_KEY")
8
  client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
9
 
10
- # Store history
11
- history = []
12
 
13
- # Translation function
14
  def translate_text(text, target_lang):
15
  if not text.strip() or not target_lang.strip():
16
- return "⚠️ Please enter both English text and target language.", gr.update(visible=False), history
17
 
18
  prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
 
19
  try:
20
  response = client.chat.completions.create(
21
  model="llama3-8b-8192",
@@ -23,62 +24,40 @@ def translate_text(text, target_lang):
23
  temperature=0.5
24
  )
25
  translated = response.choices[0].message.content.strip()
26
- history.insert(0, f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | {target_lang}: {translated}")
27
- return translated, gr.update(visible=True), history[:5]
 
 
 
 
 
28
  except Exception as e:
29
- return f"❌ Error: {e}", gr.update(visible=False), history
30
-
31
- # Download function
32
- def download_translation(text):
33
- filename = "/mnt/data/translation.txt"
34
- with open(filename, "w", encoding="utf-8") as f:
35
- f.write(text)
36
- return filename
37
 
38
- # Gradio UI
39
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="indigo")) as demo:
40
- gr.Markdown("""
41
- # 🌍 English Translator App
42
- Translate English text into any language using **Groq's LLaMA3 model**.
43
- """)
44
 
45
  with gr.Row():
46
- text_input = gr.Textbox(label="✏️ English Text", placeholder="Type a sentence...", lines=4)
47
- lang_input = gr.Dropdown(
48
- label="🌐 Translate To",
49
- choices=["Urdu", "French", "Spanish", "German", "Chinese", "Arabic", "Hindi", "Turkish", "Japanese", "Russian"],
50
- allow_custom_value=True,
51
- value="Urdu"
52
- )
53
-
54
- translate_btn = gr.Button("πŸš€ Translate", variant="primary")
55
- result = gr.Textbox(label="πŸ“ Translated Text", lines=4, interactive=False)
56
 
57
  with gr.Row():
58
- copy_btn = gr.Button("πŸ“‹ Copy to Clipboard")
59
- download_btn = gr.Button("⬇️ Download Translation")
60
 
61
- file_output = gr.File(visible=False)
62
- history_output = gr.Textbox(label="πŸ“œ Recent History", lines=5, interactive=False)
 
63
 
 
64
  translate_btn.click(
65
  translate_text,
66
  inputs=[text_input, lang_input],
67
- outputs=[result, file_output, history_output]
68
- )
69
-
70
- copy_btn.click(
71
- None,
72
- inputs=[],
73
- outputs=[],
74
- js="""
75
- () => {
76
- const output = document.querySelector('textarea[aria-label="πŸ“ Translated Text"]');
77
- if (output) navigator.clipboard.writeText(output.value);
78
- }
79
- """
80
  )
81
 
82
- download_btn.click(download_translation, inputs=result, outputs=file_output)
83
 
84
- demo.launch()
 
1
  import os
2
  from openai import OpenAI
3
  import gradio as gr
4
+ import datetime
5
 
6
+ # πŸ” API Setup
7
  api_key = os.getenv("GROQ_API_KEY")
8
  client = OpenAI(api_key=api_key, base_url="https://api.groq.com/openai/v1")
9
 
10
+ # 🧠 Chat history
11
+ chat_history = []
12
 
13
+ # πŸ“˜ Translate function
14
  def translate_text(text, target_lang):
15
  if not text.strip() or not target_lang.strip():
16
+ return "⚠️ Please enter both text and target language.", None, chat_history
17
 
18
  prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
19
+
20
  try:
21
  response = client.chat.completions.create(
22
  model="llama3-8b-8192",
 
24
  temperature=0.5
25
  )
26
  translated = response.choices[0].message.content.strip()
27
+ chat_history.append(f"πŸ—£οΈ **You**: {text}\n🌐 **{target_lang}**: {translated}")
28
+
29
+ # Save translated text to file
30
+ filename = f"translation_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
31
+ with open(filename, "w", encoding="utf-8") as f:
32
+ f.write(translated)
33
+ return translated, filename, chat_history
34
  except Exception as e:
35
+ return f"❌ Error: {e}", None, chat_history
 
 
 
 
 
 
 
36
 
37
+ # 🎨 Gradio App Layout
38
+ with gr.Blocks(theme=gr.themes.Soft(), css=".gr-button {font-size: 16px !important;}") as app:
39
+ gr.Markdown("## 🌍 **English Translator App**")
40
+ gr.Markdown("Easily translate English text into any language using **Groq's LLaMA3 model**.")
 
 
41
 
42
  with gr.Row():
43
+ text_input = gr.Textbox(label="Enter English Text", placeholder="Type something to translate...", lines=3)
44
+ lang_input = gr.Textbox(label="Translate to (e.g. Urdu, French, Spanish)", placeholder="e.g. Urdu")
 
 
 
 
 
 
 
 
45
 
46
  with gr.Row():
47
+ translate_btn = gr.Button("🌐 Translate")
48
+ clear_btn = gr.Button("🧹 Clear")
49
 
50
+ result_output = gr.Textbox(label="Translated Text", lines=4)
51
+ file_output = gr.File(label="πŸ“„ Download Translated Text")
52
+ history_display = gr.Markdown("")
53
 
54
+ # ✨ Button handlers
55
  translate_btn.click(
56
  translate_text,
57
  inputs=[text_input, lang_input],
58
+ outputs=[result_output, file_output, history_display]
 
 
 
 
 
 
 
 
 
 
 
 
59
  )
60
 
61
+ clear_btn.click(lambda: ("", "", [], ""), None, [text_input, lang_input, result_output, history_display])
62
 
63
+ app.launch()