Spaces:
Runtime error
Runtime error
Create translator.py
Browse files- modules/translator.py +59 -0
modules/translator.py
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from .translation_model import TranslationModel
|
3 |
+
import time
|
4 |
+
|
5 |
+
def translator_component():
|
6 |
+
# Initialize the translation model
|
7 |
+
model = TranslationModel()
|
8 |
+
|
9 |
+
# Language mapping
|
10 |
+
LANGUAGES = {
|
11 |
+
"Afrikaans": "af",
|
12 |
+
"English": "en",
|
13 |
+
}
|
14 |
+
|
15 |
+
def translate_text(text, source_lang, target_lang):
|
16 |
+
if not text.strip():
|
17 |
+
return "Please enter text to translate."
|
18 |
+
|
19 |
+
start_time = time.time()
|
20 |
+
src_code = LANGUAGES[source_lang]
|
21 |
+
tgt_code = LANGUAGES[target_lang]
|
22 |
+
|
23 |
+
result = model.translate(text, src_code, tgt_code)
|
24 |
+
end_time = time.time()
|
25 |
+
|
26 |
+
return f"{result}\n\nTranslation time: {round(end_time - start_time, 2)} seconds"
|
27 |
+
|
28 |
+
with gr.Column() as translator:
|
29 |
+
gr.Markdown("### Neural Machine Translation")
|
30 |
+
gr.Markdown("Using M2M100 1.2B model for high-quality translations")
|
31 |
+
|
32 |
+
input_text = gr.Textbox(
|
33 |
+
label="Text to Translate",
|
34 |
+
placeholder="Enter text here...",
|
35 |
+
lines=3
|
36 |
+
)
|
37 |
+
|
38 |
+
with gr.Row():
|
39 |
+
source_lang = gr.Dropdown(
|
40 |
+
choices=list(LANGUAGES.keys()),
|
41 |
+
value="English",
|
42 |
+
label="From"
|
43 |
+
)
|
44 |
+
target_lang = gr.Dropdown(
|
45 |
+
choices=list(LANGUAGES.keys()),
|
46 |
+
value="Afrikaans",
|
47 |
+
label="To"
|
48 |
+
)
|
49 |
+
|
50 |
+
translate_btn = gr.Button("Translate")
|
51 |
+
output_text = gr.Textbox(label="Translation", lines=3)
|
52 |
+
|
53 |
+
translate_btn.click(
|
54 |
+
fn=translate_text,
|
55 |
+
inputs=[input_text, source_lang, target_lang],
|
56 |
+
outputs=output_text
|
57 |
+
)
|
58 |
+
|
59 |
+
return translator
|