Mahrukhh commited on
Commit
c746a50
Β·
verified Β·
1 Parent(s): 5779ddf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -51
app.py CHANGED
@@ -1,31 +1,26 @@
1
  import os
2
- import pandas as pd
3
- from openai import OpenAI
4
  import gradio as gr
 
 
5
 
6
- # Load API key securely
7
  api_key = os.getenv("GROQ_API_KEY")
 
8
 
9
- # Initialize Groq-compatible OpenAI client
10
- client = OpenAI(
11
- api_key=api_key,
12
- base_url="https://api.groq.com/openai/v1"
13
- )
14
-
15
- # In-memory translation history
16
  translation_history = []
17
 
18
- # Full language list
19
- language_list = [
20
- "Urdu", "Hindi", "Arabic", "Spanish", "French", "German", "Chinese", "Japanese",
21
- "Korean", "Turkish", "Russian", "Portuguese", "Italian", "Bengali", "Tamil",
22
- "Punjabi", "Greek", "Dutch", "Polish", "Swedish", "Norwegian", "Hebrew"
23
  ]
24
 
25
- # Translation function with history tracking
26
- def translate_and_save(text, target_lang):
27
  if not text.strip() or not target_lang.strip():
28
- return "⚠️ Please enter both English text and target language.", pd.DataFrame(translation_history)
29
 
30
  prompt = f"Translate the following English text to {target_lang}:\n\n{text}"
31
 
@@ -37,57 +32,72 @@ def translate_and_save(text, target_lang):
37
  )
38
  translated = response.choices[0].message.content.strip()
39
 
40
- # Save to history as a dict
41
  translation_history.append({
42
- "English Text": text,
43
- "Language": target_lang,
44
- "Translation": translated
 
45
  })
 
 
 
46
 
47
- # Convert to DataFrame for display
48
- history_df = pd.DataFrame(translation_history)
 
49
 
50
- return translated, history_df
51
- except Exception as e:
52
- return f"❌ Error: {str(e)}", pd.DataFrame(translation_history)
 
 
53
 
54
- # Build the Gradio UI
55
  with gr.Blocks(theme=gr.themes.Soft()) as app:
56
- gr.Markdown("# 🌍 English Language Translator")
57
- gr.Markdown("Translate any English sentence into your desired language using **Groq's LLaMA3 model**.")
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  with gr.Row():
60
  with gr.Column(scale=1):
61
- text_input = gr.Textbox(label="✏️ English Text", placeholder="Enter your English sentence here...", lines=4)
 
 
 
 
 
62
  with gr.Column(scale=1):
63
- lang_dropdown = gr.Dropdown(
64
- choices=language_list,
65
- label="🌐 Target Language",
66
- info="Select a language",
67
- allow_custom_value=True,
68
- interactive=True
69
  )
70
 
71
  with gr.Row():
72
  translate_btn = gr.Button("🌐 Translate")
73
  clear_btn = gr.Button("🧹 Clear")
74
 
75
- output_box = gr.Textbox(label="πŸ“ Translated Text", lines=6)
76
- history_table = gr.Dataframe(label="πŸ“œ Translation History", interactive=False)
77
 
78
- translate_btn.click(
79
- fn=translate_and_save,
80
- inputs=[text_input, lang_dropdown],
81
- outputs=[output_box, history_table]
82
- )
83
 
84
- clear_btn.click(
85
- lambda: ("", "", "", pd.DataFrame(translation_history)),
86
- outputs=[text_input, lang_dropdown, output_box, history_table]
87
- )
88
 
89
- gr.Markdown("---")
90
- gr.Markdown("⚑ Powered by [Groq](https://groq.com) | Built with ❀️ using [Gradio](https://gradio.app)")
91
 
92
- # Launch the app
93
  app.launch()
 
1
  import os
 
 
2
  import gradio as gr
3
+ from openai import OpenAI
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 translation history
 
 
 
 
 
 
11
  translation_history = []
12
 
13
+ # Supported languages
14
+ LANGUAGES = [
15
+ "Urdu", "Arabic", "Chinese", "French", "German", "Hindi", "Italian",
16
+ "Japanese", "Korean", "Persian", "Portuguese", "Punjabi", "Russian",
17
+ "Spanish", "Turkish"
18
  ]
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}:\n\n{text}"
26
 
 
32
  )
33
  translated = response.choices[0].message.content.strip()
34
 
35
+ # Append to history
36
  translation_history.append({
37
+ "Time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
38
+ "From": text,
39
+ "To": target_lang,
40
+ "Result": translated
41
  })
42
+ return translated
43
+ except Exception as e:
44
+ return f"❌ Error: {str(e)}"
45
 
46
+ # Clear input/output
47
+ def clear_all():
48
+ return "", LANGUAGES[0], "", []
49
 
50
+ # Load history
51
+ def get_history():
52
+ if not translation_history:
53
+ return []
54
+ return [[row["Time"], row["From"], row["To"], row["Result"]] for row in translation_history[::-1]]
55
 
56
+ # Gradio UI
57
  with gr.Blocks(theme=gr.themes.Soft()) as app:
58
+ gr.Markdown(
59
+ """
60
+ # 🌍 English Language Translator
61
+
62
+ ### βœ… Features:
63
+ - Translate English text to 15+ languages using **Groq’s LLaMA3 model**
64
+ - Clean, responsive, and dark-themed UI
65
+ - Easy language selection from dropdown menu
66
+ - Instant translation with a single click
67
+ - Translation history displayed in a table
68
+ - "Clear" button to reset inputs and output
69
+ """
70
+ )
71
 
72
  with gr.Row():
73
  with gr.Column(scale=1):
74
+ text_input = gr.Textbox(
75
+ label="πŸ“ English Text",
76
+ placeholder="e.g., The construction site was damaged after the storm.",
77
+ lines=4
78
+ )
79
+
80
  with gr.Column(scale=1):
81
+ lang_input = gr.Dropdown(
82
+ choices=LANGUAGES,
83
+ value=LANGUAGES[0],
84
+ label="🌐 Target Language"
 
 
85
  )
86
 
87
  with gr.Row():
88
  translate_btn = gr.Button("🌐 Translate")
89
  clear_btn = gr.Button("🧹 Clear")
90
 
91
+ output_box = gr.Textbox(label="πŸ“„ Translated Text", lines=4)
 
92
 
93
+ with gr.Accordion("πŸ“œ Translation History", open=False):
94
+ history_table = gr.Dataframe(headers=["Time", "English Text", "Target Language", "Translation"])
 
 
 
95
 
96
+ # Bind actions
97
+ translate_btn.click(fn=translate_text, inputs=[text_input, lang_input], outputs=output_box)\
98
+ .then(fn=get_history, outputs=history_table)
 
99
 
100
+ clear_btn.click(fn=clear_all, outputs=[text_input, lang_input, output_box, history_table])
 
101
 
102
+ # Launch app
103
  app.launch()