Spaces:
Sleeping
Sleeping
File size: 2,733 Bytes
ebee301 |
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 |
import gradio as gr
from language_directions import *
from transformers import pipeline
source_lang_dict = get_all_source_languages()
target_lang_dict = {}
source_languages = source_lang_dict.keys()
def source_dropdown_changed(source_dropdown, input_text=""):
global target_lang_dict
target_lang_dict = get_target_languages(source_lang_dict[source_dropdown], input_text)
target_languages = target_lang_dict.keys()
default_target_value = None
if "English" in target_languages or "english" in target_languages:
default_target_value = "English"
else:
default_target_value = target_languages[0]
target_dropdown = gr.Dropdown(choices=target_languages,
value=default_target_value,
label="Target Language")
return target_dropdown
def translate(input_text, source, target):
if source == "Auto Detect":
source, _ = auto_detect_language_code(input_text)
target_lang_dict = get_target_languages(source)
target = target_lang_dict[target]
model = f"Helsinki-NLP/opus-mt-{source}-{target}"
pipe = pipeline("translation", model=model)
translation = pipe(input_text)
return translation[0]['translation_text']
with gr.Blocks() as demo:
gr.HTML("""<html>
<head>
<style>
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Open Translate</h1>
</body>
</html>""")
with gr.Row():
with gr.Column():
source_language_dropdown = gr.Dropdown(choices=source_languages,
value="Auto Detect",
label="Source Language")
input_textbox = gr.Textbox(lines=5, placeholder="Enter text to translate", label="Input Text")
with gr.Column():
target_language_dropdown = gr.Dropdown(choices=["English", "French", "Spanish"],
value="English",
label="Target Language")
translated_textbox = gr.Textbox(lines=5, placeholder="", label="Translated Text")
btn = gr.Button("Translate")
source_language_dropdown.change(source_dropdown_changed, inputs=source_language_dropdown, outputs=target_language_dropdown)
btn.click(translate, inputs=[input_textbox,
source_language_dropdown,
target_language_dropdown],
outputs=translated_textbox)
gr.Examples(["Je te rencontre au café", "Répétez s'il vous plaît."],
inputs=[input_textbox])
if __name__ == "__main__":
demo.launch() |