Files changed (1) hide show
  1. app.py +20 -153
app.py CHANGED
@@ -1,154 +1,21 @@
1
- import spaces
2
  import gradio as gr
3
- from sacremoses import MosesPunctNormalizer
4
- from stopes.pipelines.monolingual.utils.sentence_split import get_split_algo
5
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
6
- from flores import code_mapping
7
- import platform
8
- import torch
9
- import nltk
10
- from functools import lru_cache
11
-
12
- nltk.download("punkt_tab")
13
-
14
- REMOVED_TARGET_LANGUAGES = {"Ligurian", "Lombard", "Sicilian"}
15
-
16
-
17
- device = "cpu" if platform.system() == "Darwin" else "cuda"
18
- MODEL_NAME = "facebook/nllb-200-3.3B"
19
-
20
- code_mapping = dict(sorted(code_mapping.items(), key=lambda item: item[0]))
21
- flores_codes = list(code_mapping.keys())
22
- target_languages = [language for language in flores_codes if not language in REMOVED_TARGET_LANGUAGES]
23
-
24
- def load_model():
25
- model = AutoModelForSeq2SeqLM.from_pretrained(MODEL_NAME).to(device)
26
- print(f"Model loaded in {device}")
27
- return model
28
-
29
-
30
- model = load_model()
31
-
32
-
33
- # Loading the tokenizer once, because re-loading it takes about 1.5 seconds each time
34
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
35
-
36
-
37
- punct_normalizer = MosesPunctNormalizer(lang="en")
38
-
39
-
40
- @lru_cache(maxsize=202)
41
- def get_language_specific_sentence_splitter(language_code):
42
- short_code = language_code[:3]
43
- splitter = get_split_algo(short_code, "default")
44
- return splitter
45
-
46
-
47
- # cache function
48
- @lru_cache(maxsize=100)
49
- def translate(text: str, src_lang: str, tgt_lang: str):
50
- if not src_lang:
51
- raise gr.Error("The source language is empty! Please choose it in the dropdown list.")
52
- if not tgt_lang:
53
- raise gr.Error("The target language is empty! Please choose it in the dropdown list.")
54
- return _translate(text, src_lang, tgt_lang)
55
-
56
-
57
- # Only assign GPU if cache not used
58
- @spaces.GPU
59
- def _translate(text: str, src_lang: str, tgt_lang: str):
60
- src_code = code_mapping[src_lang]
61
- tgt_code = code_mapping[tgt_lang]
62
- tokenizer.src_lang = src_code
63
- tokenizer.tgt_lang = tgt_code
64
-
65
- # normalizing the punctuation first
66
- text = punct_normalizer.normalize(text)
67
-
68
- paragraphs = text.split("\n")
69
- translated_paragraphs = []
70
-
71
- for paragraph in paragraphs:
72
- splitter = get_language_specific_sentence_splitter(src_code)
73
- sentences = list(splitter(paragraph))
74
- translated_sentences = []
75
-
76
- for sentence in sentences:
77
- input_tokens = (
78
- tokenizer(sentence, return_tensors="pt")
79
- .input_ids[0]
80
- .cpu()
81
- .numpy()
82
- .tolist()
83
- )
84
- translated_chunk = model.generate(
85
- input_ids=torch.tensor([input_tokens]).to(device),
86
- forced_bos_token_id=tokenizer.convert_tokens_to_ids(tgt_code),
87
- max_length=len(input_tokens) + 50,
88
- num_return_sequences=1,
89
- num_beams=5,
90
- no_repeat_ngram_size=4, # repetition blocking works better if this number is below num_beams
91
- renormalize_logits=True, # recompute token probabilities after banning the repetitions
92
- )
93
- translated_chunk = tokenizer.decode(
94
- translated_chunk[0], skip_special_tokens=True
95
- )
96
- translated_sentences.append(translated_chunk)
97
-
98
- translated_paragraph = " ".join(translated_sentences)
99
- translated_paragraphs.append(translated_paragraph)
100
-
101
- return "\n".join(translated_paragraphs)
102
-
103
-
104
-
105
- description = """
106
- <div style="text-align: center;">
107
- <img src="https://huggingface.co/spaces/UNESCO/nllb/resolve/main/UNESCO_META_HF_BANNER.png" alt="UNESCO Meta Hugging Face Banner" style="max-width: 800px; width: 100%; margin: 0 auto;">
108
- <h1 style="color: #0077be;">UNESCO Language Translator, powered by Meta and Hugging Face</h1>
109
- </div>
110
-
111
- UNESCO, Meta, and Hugging Face have come together to create an accessible, high-quality translation experience in 200 languages.
112
-
113
- This is made possible through an open approach to AI innovation using Meta's open-sourced No Language Left Behind (NLLB) AI model, hosted on Hugging Face Spaces.
114
- """
115
- disclaimer = """
116
- ## Disclaimer
117
-
118
- This translation interface, developed as part of UNESCO's work on Multilingualism and supported by Meta's No Language Left Behind AI model and Hugging Face, is designed to assist with language translation using open-source AI technologies. However, translations generated by the tool may not be accurate or perfect. While we strive to provide accurate translations, the tool may produce inaccuracies due to the complexity and nuances of different languages.
119
-
120
- - The tool may not fully capture the context, cultural nuances, idiomatic expressions, or specific terminologies.
121
- - Manual review and adjustment are recommended for important translations.
122
- - The translations are provided "as is" without any warranties of any kind, either expressed or implied.
123
- - Users should not rely solely on the tool for critical or sensitive translations and are responsible for verifying the accuracy and appropriateness of the translations for their specific needs.
124
- - We recommend consulting with professional translators for official, legal, medical, or other critical translations.
125
- - We shall not be liable for any direct, indirect, incidental, special, or consequential damages arising out of or in connection with the use or inability to use the translation tool, including but not limited to errors or omissions in translations.
126
-
127
- By using this translation tool, you agree to these terms and acknowledge that the use of the tool is at your own risk.
128
-
129
- For any feedback or support, please contact UNESCO World Atlas of Languages Team: WAL.Data@unesco.org.
130
- """
131
-
132
-
133
- examples_inputs = [["The United Nations Educational, Scientific and Cultural Organization is a specialized agency of the United Nations with the aim of promoting world peace and security through international cooperation in education, arts, sciences and culture. ","English","Ayacucho Quechua"],]
134
-
135
- with gr.Blocks() as demo:
136
- gr.Markdown(description)
137
- with gr.Row():
138
- src_lang = gr.Dropdown(label="Source Language", choices=flores_codes)
139
- target_lang = gr.Dropdown(label="Target Language", choices=target_languages)
140
- with gr.Row():
141
- input_text = gr.Textbox(label="Input Text", lines=6)
142
- with gr.Row():
143
- btn = gr.Button("Translate text")
144
- with gr.Row():
145
- output = gr.Textbox(label="Output Text", lines=6)
146
- btn.click(
147
- translate,
148
- inputs=[input_text, src_lang, target_lang],
149
- outputs=output,
150
- )
151
- examples = gr.Examples(examples=examples_inputs,inputs=[input_text, src_lang,target_lang], fn=translate, outputs=output, cache_examples=True)
152
- with gr.Row():
153
- gr.Markdown(disclaimer)
154
- demo.launch()
 
 
1
  import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Load translation model
5
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ur")
6
+
7
+ # Define translation function
8
+ def translate_text(text):
9
+ result = translator(text)
10
+ return result[0]['translation_text']
11
+
12
+ # Gradio interface
13
+ app = gr.Interface(
14
+ fn=translate_text,
15
+ inputs=gr.Textbox(label="Enter English text"),
16
+ outputs=gr.Textbox(label="Urdu translation"),
17
+ title="English to Urdu Translator",
18
+ description="Simple AI translator using Hugging Face model"
19
+ )
20
+
21
+ app.launch()