lalaru commited on
Commit
c65f390
Β·
verified Β·
1 Parent(s): ccba5bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +40 -86
app.py CHANGED
@@ -1,103 +1,57 @@
1
- import gradio as gr
2
  import os
3
- import re
4
  from groq import Groq
5
- from faster_whisper import WhisperModel
6
- from transformers import pipeline
7
 
8
- # =========================
9
- # CONFIG
10
- # =========================
11
- GROQ_API_KEY = os.getenv("GROQ_API_KEY") # set in HuggingFace secrets
12
- groq_client = Groq(api_key=GROQ_API_KEY)
13
 
14
- # Whisper ASR model
15
- whisper_model = WhisperModel("medium")
16
 
17
- # Hugging Face fallback translation models
18
- translator_en2es = pipeline("translation", model="Helsinki-NLP/opus-mt-en-es")
19
- translator_es2en = pipeline("translation", model="Helsinki-NLP/opus-mt-es-en")
 
20
 
21
- # =========================
22
- # TEXT CLEANING FUNCTION
23
- # =========================
24
- def clean_text(text):
25
- # Remove filler words
26
- text = re.sub(r"\b(um+|uh+|erm+|hmm+)\b", "", text, flags=re.IGNORECASE)
27
- # Normalize spacing
28
- text = re.sub(r"\s+", " ", text).strip()
29
- # Capitalize first letter
30
- if text and not text[0].isupper():
31
- text = text[0].upper() + text[1:]
32
- return text
33
-
34
- # =========================
35
- # TRANSLATION FUNCTION
36
- # =========================
37
- def mistral_translate(text, source_lang, target_lang):
38
- system_prompt = """
39
- You are an expert bilingual translator (English ↔ Spanish).
40
- Translate text accurately while preserving meaning, idioms, and emotional tags (<happy>, <angry>, <calm>).
41
- Output only the translated text.
42
- """
43
 
44
- user_prompt = f"""
45
- Translate the following text:
46
- Source Language: {source_lang}
47
- Target Language: {target_lang}
48
- Text: "{text}"
 
 
49
  """
50
 
51
- try:
52
- response = groq_client.chat.completions.create(
53
- model="mistral-7b-instruct",
54
- messages=[
55
- {"role": "system", "content": system_prompt},
56
- {"role": "user", "content": user_prompt},
57
- ],
58
- temperature=0.3,
59
- )
60
- return response.choices[0].message["content"].strip()
61
- except Exception as e:
62
- print("Groq API failed, switching to OPUS-MT:", e)
63
- if source_lang.lower().startswith("english"):
64
- return translator_en2es(text)[0]["translation_text"]
65
- else:
66
- return translator_es2en(text)[0]["translation_text"]
67
 
68
- # =========================
69
- # MAIN PIPELINE
70
- # =========================
71
- def translate_speech(audio, source_lang="English", target_lang="Spanish"):
72
- # Step 1: Speech β†’ Text
73
- segments, _ = whisper_model.transcribe(audio, beam_size=5)
74
- asr_text = " ".join([seg.text for seg in segments])
75
- asr_text = clean_text(asr_text)
76
 
77
- # Step 2: Translate Text
78
- translated_text = mistral_translate(asr_text, source_lang, target_lang)
79
-
80
- return {
81
- "original_text": asr_text,
82
- "translated_text": translated_text
83
- }
84
-
85
- # =========================
86
- # GRADIO UI
87
- # =========================
88
  with gr.Blocks() as demo:
89
- gr.Markdown("# πŸŽ™οΈ AI Universal Translator (EN ↔ ES)")
90
- gr.Markdown("Speak in English or Spanish, and get real-time translated speech + text.")
91
 
92
  with gr.Row():
93
- source_lang = gr.Dropdown(["English", "Spanish"], value="English", label="Source Language")
94
- target_lang = gr.Dropdown(["Spanish", "English"], value="Spanish", label="Target Language")
95
 
96
- with gr.Row():
97
- audio_in = gr.Audio(sources=["microphone"], type="filepath", label="🎀 Speak Here")
98
- output_text = gr.JSON(label="Translation Result")
99
 
100
- btn = gr.Button("Translate")
101
- btn.click(translate_speech, inputs=[audio_in, source_lang, target_lang], outputs=[output_text])
102
 
103
- demo.launch()
 
 
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()