code-alpha-task / app.py
saibafatima's picture
Update app.py
b31dd63 verified
Raw History Blame Contribute Delete
6.82 kB
"""
CodeAlpha Internship - Task 1: Language Translation Tool
Uses: Groq API (LLM inference) + langdetect + Gradio (UI)
"""
import gradio as gr
from groq import Groq
from langdetect import detect, DetectorFactory
import os
from dotenv import load_dotenv
load_dotenv() # Load .env file locally
DetectorFactory.seed = 0
# ─── CONFIGURATION ────────────────────────────────────────────────────────────
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", "")
MODEL = "llama-3.3-70b-versatile"
LANGUAGES = [
"Auto-Detect",
"English", "Urdu", "Arabic", "French", "Spanish", "German",
"Chinese (Simplified)", "Japanese", "Korean", "Hindi", "Portuguese",
"Italian", "Russian", "Turkish", "Dutch", "Polish", "Bengali",
"Vietnamese", "Thai", "Persian (Farsi)"
]
LANG_CODE_MAP = {
"en": "English", "ur": "Urdu", "ar": "Arabic", "fr": "French",
"es": "Spanish", "de": "German", "zh-cn": "Chinese (Simplified)",
"ja": "Japanese", "ko": "Korean", "hi": "Hindi", "pt": "Portuguese",
"it": "Italian", "ru": "Russian", "tr": "Turkish", "nl": "Dutch",
"pl": "Polish", "bn": "Bengali", "vi": "Vietnamese", "th": "Thai",
"fa": "Persian (Farsi)"
}
# ─── CORE TRANSLATION FUNCTION ────────────────────────────────────────────────
def translate_text(input_text, source_lang, target_lang):
if not input_text.strip():
return "⚠️ Please enter some text to translate.", ""
if target_lang == "Auto-Detect":
return "⚠️ Please select a target language.", ""
if not GROQ_API_KEY:
return "⚠️ GROQ_API_KEY is not set. Add it in .env file or HF Space Secrets.", ""
detected_info = ""
if source_lang == "Auto-Detect":
try:
detected_code = detect(input_text)
detected_name = LANG_CODE_MAP.get(detected_code, detected_code.upper())
detected_info = f"πŸ” Detected language: **{detected_name}**"
source_lang = detected_name
except Exception:
source_lang = "the source language"
detected_info = "πŸ” Could not detect language, letting AI handle it."
prompt = (
f"You are a professional translator. Translate the following text from {source_lang} "
f"to {target_lang}. Return ONLY the translated text β€” no explanations, no labels, "
f"no quotation marks, just the clean translation.\n\nText to translate:\n{input_text}"
)
try:
client = Groq(api_key=GROQ_API_KEY)
response = client.chat.completions.create(
model=MODEL,
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=1024
)
translated = response.choices[0].message.content.strip()
return translated, detected_info
except Exception as e:
return f"❌ Translation error: {str(e)}", ""
# ─── JS FUNCTIONS ──────────────────────────────────────────────────────────────
TTS_JS = """
function speakText() {
const outputBox = document.querySelector('#translated-output textarea');
if (!outputBox || !outputBox.value.trim()) {
alert("Nothing to speak yet!");
return;
}
const utterance = new SpeechSynthesisUtterance(outputBox.value);
window.speechSynthesis.speak(utterance);
}
"""
COPY_JS = """
function copyText() {
const outputBox = document.querySelector('#translated-output textarea');
if (!outputBox || !outputBox.value.trim()) {
alert("Nothing to copy yet!");
return;
}
navigator.clipboard.writeText(outputBox.value).then(() => {
alert("Copied to clipboard!");
});
}
"""
# ─── GRADIO UI ─────────────────────────────────────────────────────────────────
with gr.Blocks(
title="Language Translator β€” CodeAlpha",
theme=gr.themes.Soft(primary_hue="blue"),
css="""
.title-block { text-align: center; padding: 10px 0 20px; }
#translated-output textarea { font-size: 16px; }
.footer { text-align: center; font-size: 12px; color: #888; margin-top: 20px; }
"""
) as demo:
gr.HTML("""
<div class="title-block">
<h1>🌐 Language Translation Tool</h1>
<p style="color:#555;">Powered by Groq LLaMA3 + LangDetect | CodeAlpha Internship Task 1</p>
</div>
""")
with gr.Row():
source_lang = gr.Dropdown(
choices=LANGUAGES, value="Auto-Detect", label="Source Language", scale=1
)
target_lang = gr.Dropdown(
choices=[l for l in LANGUAGES if l != "Auto-Detect"],
value="Urdu", label="Target Language", scale=1
)
with gr.Row():
with gr.Column():
input_text = gr.Textbox(
label="Input Text",
placeholder="Enter text here to translate...",
lines=8, max_lines=15
)
with gr.Row():
translate_btn = gr.Button("πŸ” Translate", variant="primary", scale=3)
clear_btn = gr.Button("πŸ—‘οΈ Clear", scale=1)
with gr.Column():
output_text = gr.Textbox(
label="Translated Text",
lines=8, max_lines=15,
interactive=False,
elem_id="translated-output"
)
detection_info = gr.Markdown("")
with gr.Row():
copy_btn = gr.Button("πŸ“‹ Copy to Clipboard", scale=2)
speak_btn = gr.Button("πŸ”Š Speak Translation", scale=2)
def do_translate(text, src, tgt):
result, info = translate_text(text, src, tgt)
return result, info
def clear_all():
return "", "", ""
translate_btn.click(
fn=do_translate,
inputs=[input_text, source_lang, target_lang],
outputs=[output_text, detection_info]
)
input_text.submit(
fn=do_translate,
inputs=[input_text, source_lang, target_lang],
outputs=[output_text, detection_info]
)
clear_btn.click(fn=clear_all, outputs=[input_text, output_text, detection_info])
copy_btn.click(fn=None, js=COPY_JS)
speak_btn.click(fn=None, js=TTS_JS)
gr.HTML("""
<div class="footer">
Built with ❀️ for CodeAlpha AI Internship · Groq LLaMA3-8B · Gradio UI
</div>
""")
if __name__ == "__main__":
demo.launch()