lalaru commited on
Commit
fd505dd
·
verified ·
1 Parent(s): 89d19e1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +143 -43
app.py CHANGED
@@ -1,57 +1,157 @@
1
  # app.py
2
  import os
 
 
3
  import gradio as gr
4
- from groq import Groq
5
-
6
- # Load your Groq API key (set it in Hugging Face "Secrets")
7
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
8
-
9
- client = Groq(api_key=GROQ_API_KEY)
10
-
11
- # Define the translation prompt
12
- def translate_text(user_text, target_lang):
13
- if not user_text.strip():
14
- return "⚠️ Please enter some text."
15
-
16
- # System prompt keeps the model focused
17
- system_prompt = f"""
18
- You are a multilingual translation assistant.
19
- Supported languages: English, Spanish, French.
20
-
21
- Task:
22
- 1. Detect the input language automatically.
23
- 2. Translate the input into the target language requested: {target_lang}.
24
- 3. Preserve meaning, tone, and formatting of the input.
25
- 4. Keep numbers, symbols, names, and special characters unchanged.
26
- 5. If the input is already in the target language, return it unchanged.
27
- 6. Respond with ONLY the translated text, no explanations or extra commentary.
28
- """
29
-
30
- # Call Groq API (Mistral or LLaMA etc.)
31
- response = client.chat.completions.create(
32
- model="mixtral-8x7b-32768", # you can swap with mistral model available
33
- messages=[
34
- {"role": "system", "content": system_prompt},
35
- {"role": "user", "content": user_text},
36
- ],
37
- temperature=0, # translation should be deterministic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
- return response.choices[0].message.content.strip()
 
 
41
 
42
- # Gradio UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  with gr.Blocks() as demo:
44
  gr.Markdown("## 🌐 Hackathon Translator (EN/ES/FR)")
45
 
46
  with gr.Row():
47
- user_text = gr.Textbox(label="Enter your text", lines=4, placeholder="Type something...")
48
- target_lang = gr.Dropdown(["English", "Spanish", "French"], value="English", label="Target Language")
49
-
50
- output_text = gr.Textbox(label="Translated Output", lines=4)
51
-
52
- translate_btn = gr.Button("Translate")
53
 
54
- translate_btn.click(fn=translate_text, inputs=[user_text, target_lang], outputs=output_text)
 
 
55
 
56
  if __name__ == "__main__":
57
  demo.launch()
 
1
  # app.py
2
  import os
3
+ import json
4
+ import requests
5
  import gradio as gr
6
+ from langdetect import detect, LangDetectException
7
+
8
+ # Groq SDK (install in requirements.txt)
9
+ try:
10
+ from groq import Groq
11
+ except Exception:
12
+ Groq = None
13
+
14
+ # Config (set these in your Space secrets)
15
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY") # your Groq key
16
+ GROQ_MODEL = os.getenv("GROQ_MODEL", "mixtral-8x7b-32768")
17
+ HUGGINGFACE_TOKEN = os.getenv("HUGGINGFACE_TOKEN") # hf_... token (optional but recommended)
18
+
19
+ # Init clients (if keys provided)
20
+ groq_client = None
21
+ if GROQ_API_KEY and Groq is not None:
22
+ try:
23
+ groq_client = Groq(api_key=GROQ_API_KEY)
24
+ except Exception as e:
25
+ print("Groq client init failed:", repr(e))
26
+
27
+ # Simple mapping for UI -> code
28
+ LANG_UI_TO_CODE = {"English": "en", "Spanish": "es", "French": "fr"}
29
+
30
+ SYSTEM_PROMPT = """
31
+ You are a multilingual translation assistant.
32
+ Supported languages: English, Spanish, French.
33
+
34
+ Task:
35
+ 1. Detect the input language automatically.
36
+ 2. Translate the input into the exact target language requested by the user.
37
+ 3. Preserve meaning, tone, and formatting.
38
+ 4. Keep numbers, symbols, names and special characters unchanged.
39
+ 5. If the input is already in the target language, return it unchanged.
40
+ 6. Output ONLY the translated text, no commentary.
41
+ """
42
+
43
+ def call_groq(user_text, target_lang_ui):
44
+ if not groq_client:
45
+ raise RuntimeError("Groq client not configured")
46
+ # Put the target explicitly for determinism
47
+ messages = [
48
+ {"role": "system", "content": SYSTEM_PROMPT},
49
+ {"role": "user", "content": f"Target language: {target_lang_ui}\n\n{user_text}"},
50
+ ]
51
+ # Best-effort: extract content from different response shapes
52
+ chat = groq_client.chat.completions.create(
53
+ model=GROQ_MODEL,
54
+ messages=messages,
55
+ temperature=0,
56
+ max_tokens=2048,
57
  )
58
+ # SDK usually returns .choices[0].message.content
59
+ try:
60
+ return chat.choices[0].message.content.strip()
61
+ except Exception:
62
+ # fallback for dict-like response
63
+ try:
64
+ return chat["choices"][0]["message"]["content"].strip()
65
+ except Exception as e:
66
+ print("Unexpected Groq response shape:", repr(e))
67
+ raise
68
+
69
+ def call_hf_opus(user_text, src_code, tgt_code):
70
+ # map most common pairs to explicit model ids
71
+ model_map = {
72
+ ("en","es"): "Helsinki-NLP/opus-mt-en-es",
73
+ ("es","en"): "Helsinki-NLP/opus-mt-es-en",
74
+ ("en","fr"): "Helsinki-NLP/opus-mt-en-fr",
75
+ ("fr","en"): "Helsinki-NLP/opus-mt-fr-en",
76
+ ("es","fr"): "Helsinki-NLP/opus-mt-es-fr",
77
+ ("fr","es"): "Helsinki-NLP/opus-mt-fr-es",
78
+ }
79
+ model_id = model_map.get((src_code, tgt_code)) or f"Helsinki-NLP/opus-mt-{src_code}-{tgt_code}"
80
 
81
+ url = f"https://api-inference.huggingface.co/models/{model_id}"
82
+ headers = {"Authorization": f"Bearer {HUGGINGFACE_TOKEN}"} if HUGGINGFACE_TOKEN else {}
83
+ payload = {"inputs": user_text}
84
 
85
+ resp = requests.post(url, headers=headers, json=payload, timeout=30)
86
+ if resp.status_code != 200:
87
+ raise RuntimeError(f"Hugging Face fallback failed: {resp.status_code} {resp.text}")
88
+
89
+ data = resp.json()
90
+ # handle common response shapes:
91
+ if isinstance(data, list) and len(data) > 0:
92
+ first = data[0]
93
+ if isinstance(first, dict):
94
+ # prefer common keys
95
+ for k in ("translation_text", "generated_text", "text"):
96
+ if k in first:
97
+ return first[k]
98
+ # otherwise return first value
99
+ return next(iter(first.values()))
100
+ else:
101
+ return str(first)
102
+ if isinstance(data, dict):
103
+ for k in ("translation_text", "generated_text", "text"):
104
+ if k in data:
105
+ return data[k]
106
+ return json.dumps(data)
107
+ return str(data)
108
+
109
+ def detect_lang_code(text):
110
+ try:
111
+ code = detect(text)
112
+ # keep only en/es/fr; if another, default to 'en' for fallback routing
113
+ return code if code in ("en","es","fr") else "en"
114
+ except LangDetectException:
115
+ return "en"
116
+
117
+ def translate_text(user_text, target_lang_ui):
118
+ user_text = (user_text or "").strip()
119
+ if not user_text:
120
+ return "⚠️ Please enter some text to translate."
121
+ target_code = LANG_UI_TO_CODE.get(target_lang_ui, "en")
122
+
123
+ # First: try Groq (preferred)
124
+ try:
125
+ if groq_client:
126
+ out = call_groq(user_text, target_lang_ui)
127
+ if out:
128
+ return out
129
+ except Exception as e:
130
+ print("Groq call failed:", repr(e))
131
+
132
+ # Fallback: detect source and call HF OPUS-MT models
133
+ try:
134
+ src_code = detect_lang_code(user_text)
135
+ if src_code == target_code:
136
+ # already same language
137
+ return user_text
138
+ out = call_hf_opus(user_text, src_code, target_code)
139
+ return out.strip()
140
+ except Exception as e:
141
+ print("Hugging Face fallback failed:", repr(e))
142
+ return f"Error: translation failed. Check Space logs for details."
143
+
144
+ # ----------------- Gradio UI -----------------
145
  with gr.Blocks() as demo:
146
  gr.Markdown("## 🌐 Hackathon Translator (EN/ES/FR)")
147
 
148
  with gr.Row():
149
+ txt = gr.Textbox(label="Enter your text", lines=6, placeholder="Type or paste text here...")
150
+ tgt = gr.Dropdown(choices=["English","Spanish","French"], value="English", label="Target Language")
 
 
 
 
151
 
152
+ out = gr.Textbox(label="Translated Output", lines=6)
153
+ btn = gr.Button("Translate")
154
+ btn.click(fn=translate_text, inputs=[txt, tgt], outputs=[out])
155
 
156
  if __name__ == "__main__":
157
  demo.launch()