File size: 6,823 Bytes
00ac257
 
2e514a1
00ac257
 
 
 
 
2e514a1
 
00ac257
2e514a1
 
00ac257
 
2e514a1
b31dd63
00ac257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e514a1
 
00ac257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e514a1
00ac257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e514a1
00ac257
 
 
 
 
 
 
 
 
 
 
 
2e514a1
 
 
 
 
 
 
 
 
 
 
 
 
00ac257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e514a1
00ac257
 
 
2e514a1
00ac257
 
 
 
 
 
 
2e514a1
00ac257
 
 
 
 
 
 
 
2e514a1
00ac257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e514a1
 
00ac257
 
 
 
 
 
 
 
2e514a1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""
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()