Spaces:
Running
Running
Initial commit: bilingual models, multilingual mode, Google Translate
Browse files- app.py +220 -58
- model_spacy.py +24 -0
- model_translation.py +69 -0
app.py
CHANGED
@@ -8,58 +8,185 @@ Date: 2024-09-07
|
|
8 |
"""
|
9 |
import spaces
|
10 |
import torch
|
11 |
-
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
12 |
-
from transformers import BitsAndBytesConfig
|
13 |
import gradio as gr
|
|
|
14 |
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
quantization_config = BitsAndBytesConfig(
|
27 |
-
load_in_8bit=True,
|
28 |
-
llm_int8_threshold=200.0 # https://discuss.huggingface.co/t/correct-usage-of-bitsandbytesconfig/33809/5
|
29 |
-
)
|
30 |
-
|
31 |
-
tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True)
|
32 |
-
model = AutoModelForSeq2SeqLM.from_pretrained(
|
33 |
-
model_name,
|
34 |
-
device_map="auto",
|
35 |
-
torch_dtype=torch.float16,
|
36 |
-
quantization_config=quantization_config)
|
37 |
-
model = torch.compile(model)
|
38 |
|
39 |
#
|
40 |
-
# Translate given input text
|
41 |
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
@spaces.GPU
|
43 |
-
def
|
44 |
text: str,
|
45 |
tgt_lang: str,
|
46 |
-
|
47 |
-
|
|
|
48 |
"""
|
49 |
-
Translate text
|
50 |
-
Input text will be split into chunk that will be translated sequentially.
|
51 |
-
We will have up to sents_per_chunk sentences in a given chunk.
|
52 |
"""
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
input_text
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
#
|
65 |
# User interface
|
@@ -67,32 +194,66 @@ def translate_text(
|
|
67 |
with gr.Blocks() as demo:
|
68 |
|
69 |
gr.Markdown("""
|
70 |
-
## Text translation (basic, small paragraph, multilingual)
|
71 |
""")
|
72 |
input_text = gr.Textbox(
|
73 |
-
lines=
|
74 |
placeholder="Enter text to translate",
|
75 |
label="Text to translate",
|
76 |
render=False
|
77 |
)
|
78 |
-
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
81 |
|
82 |
# Examples
|
83 |
examples = [
|
84 |
-
["ریچارد مور، رئیس سازمان مخفی اطلاعاتی بریتانیا (امآی۶) در دیدار ویلیام برنز، رئیس سازمان اطلاعات مرکزی آمریکا (سیا) گفت همچنان احتمال اقدام ایران علیه اسرائیل در واکنش به ترور اسماعیل هنیه، رهبر حماس وجود دارد. آقای برنز نیز در این دیدار فاش کرد که در سال اول جنگ اوکراین، «خطر واقعی» وجود داشت که روسیه به استفاده از «تسلیحات هستهای تاکتیکی» متوسل شود. این دو مقام امنیتی هشدار دادند که «نظم جهانی» از زمان جنگ سرد تا کنون تا این حد «در معرض تهدید» نبوده است.", "
|
85 |
-
["Clément Delangue est, avec Julien Chaumond et Thomas Wolf, l’un des trois Français cofondateurs de Hugging Face, une start-up d’intelligence artificielle (IA) de premier plan. Valorisée à 4,2 milliards d’euros après avoir levé près de 450 millions d’euros depuis sa création en 2016, cette société de droit américain est connue comme la plate-forme de référence où développeurs et entreprises publient des outils et des modèles pour faire de l’IA en open source, c’est-à-dire accessible gratuitement et modifiable.", "
|
86 |
-
["يُعد تفشي مرض جدري القردة قضية صحية عالمية خطيرة، ومن المهم محاولة منع انتشاره للحفاظ على سلامة الناس وتجنب العدوى. د. صموئيل بولاند، مدير الحوادث الخاصة بمرض الجدري في المكتب الإقليمي لمنظمة الصحة العالمية في أفريقيا، يتحدث من كينشاسا في جمهورية الكونغو الديمقراطية، ولديه بعض النصائح البسيطة التي يمكن للناس اتباعها لتقليل خطر انتشار المرض.", "
|
87 |
-
["【ワシントン=冨山優介】米ボーイングの新型宇宙船「スターライナー」は7日午前0時(日本時間7日午後1時)過ぎ、米ニューメキシコ州のホワイトサンズ宇宙港に着地し、地球に帰還した。スターライナーは米宇宙飛行士2人を乗せて6月に打ち上げられ、国際宇宙ステーション(ISS)に接続したが、機体のトラブルが解決できず、無人でISSから離脱した。", "
|
88 |
-
["張先生稱,奇瑞已經凖備在西班牙生產汽車,並決心採取「本地化」的方式進入歐洲市場。此外,他也否認該公司的出口受益於不公平補貼。奇瑞成立於1997年,是中國最大的汽車公司之一。它已經是中國最大的汽車出口商,並且制定了進一步擴張的野心勃勃的計劃。", "
|
89 |
-
["ברוכה הבאה, קיטי: בית הקפה החדש בלוס אנג'לס החתולה האהובה והחברים שלה מקבלים בית קפה משלהם בשדרות יוניברסל סיטי, שם תוכלו למצוא מגוון של פינוקים מתוקים – החל ממשקאות ועד עוגות", "
|
90 |
]
|
|
|
|
|
|
|
|
|
91 |
|
92 |
gr.Interface(
|
93 |
fn=translate_text,
|
94 |
-
inputs=[input_text,
|
95 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
allow_flagging="never",
|
97 |
examples=examples,
|
98 |
cache_examples=True
|
@@ -100,9 +261,10 @@ with gr.Blocks() as demo:
|
|
100 |
|
101 |
with gr.Accordion("Documentation", open=False):
|
102 |
gr.Markdown("""
|
103 |
-
-
|
104 |
-
- Basic:
|
105 |
- Most examples are copy/pasted from BBC news international web sites.
|
106 |
""")
|
107 |
|
108 |
-
|
|
|
|
8 |
"""
|
9 |
import spaces
|
10 |
import torch
|
|
|
|
|
11 |
import gradio as gr
|
12 |
+
import langdetect
|
13 |
|
14 |
+
import logging
|
15 |
+
logger = logging.getLogger(__name__)
|
16 |
+
logging.basicConfig(level=logging.INFO)
|
17 |
+
|
18 |
+
import model_translation as translation
|
19 |
+
from model_translation import tokenizer_multilingual
|
20 |
+
from model_translation import model_multilingual
|
21 |
+
|
22 |
+
from deep_translator import GoogleTranslator
|
23 |
+
|
24 |
+
from model_spacy import nlp_xx
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
#
|
27 |
+
# Translate given input text
|
28 |
#
|
29 |
+
def build_text_chunks(text, src_lang, sents_per_chunk):
|
30 |
+
"""
|
31 |
+
Given a text:
|
32 |
+
- Split the text into sentences.
|
33 |
+
- Build text chunks:
|
34 |
+
- Consider up to sents_per_chunk
|
35 |
+
- Ensure that we do not exceed translation.max_words_per_chunk
|
36 |
+
"""
|
37 |
+
# Split text into sentences...
|
38 |
+
sentences = [
|
39 |
+
sent.text.strip() for sent in nlp_xx(text).sents if sent.text.strip()]
|
40 |
+
logger.info(f"LANG: {src_lang}, TEXT: {text[:20]}, NB_SENTS: {len(sentences)}")
|
41 |
+
|
42 |
+
# Create text chunks of N sentences
|
43 |
+
chunks = []
|
44 |
+
chunk = ''
|
45 |
+
chunk_nb_sentences = 0
|
46 |
+
chunk_nb_words = 0
|
47 |
+
|
48 |
+
for i in range(0, len(sentences)):
|
49 |
+
# Get sentence
|
50 |
+
sent = sentences[i]
|
51 |
+
sent_nb_words = len(sent.split())
|
52 |
+
|
53 |
+
# If chunk already 'full', save chunk, start new chunk
|
54 |
+
if (
|
55 |
+
(chunk_nb_words + sent_nb_words > translation.max_words_per_chunk) or
|
56 |
+
(chunk_nb_sentences + 1 > sents_per_chunk)
|
57 |
+
):
|
58 |
+
chunks.append(chunk)
|
59 |
+
chunk = ''
|
60 |
+
chunk_nb_sentences = 0
|
61 |
+
chunk_nb_words = 0
|
62 |
+
|
63 |
+
# Append sentence to current chunk. One sentence per line.
|
64 |
+
chunk = (chunk + '\n' + sent) if chunk else sent
|
65 |
+
chunk_nb_sentences += 1
|
66 |
+
chunk_nb_words += sent_nb_words
|
67 |
+
|
68 |
+
# Append last chunk
|
69 |
+
if chunk:
|
70 |
+
chunks.append(chunk)
|
71 |
+
|
72 |
+
# !!! SKIP splitting of text into chunks for now !!!
|
73 |
+
# Might not be reliable for non-European languages.
|
74 |
+
#chunks = [text, ]
|
75 |
+
|
76 |
+
# NOTE: The 'fa' (Persian) model has multiple target languages to choose from.
|
77 |
+
# We need to specifiy the desired languages among: fra ita por ron spa
|
78 |
+
# https://huggingface.co/Helsinki-NLP/opus-mt-tc-big-fa-itc
|
79 |
+
# Prepend text with >>fra<< in order to translate in French.
|
80 |
+
if src_lang == 'fa':
|
81 |
+
chunks = [">>fra<< " + chunk for chunk in chunks]
|
82 |
+
|
83 |
+
return chunks
|
84 |
+
|
85 |
+
def translate_with_model(
|
86 |
+
text, tokenizer, model, src_lang, sents_per_chunk,
|
87 |
+
input_max_length=512, output_max_length=512):
|
88 |
+
|
89 |
+
# Build text chunks (using sents_per_chunk and translation.max_words_per_chunk)
|
90 |
+
chunks = build_text_chunks(text, src_lang, sents_per_chunk)
|
91 |
+
logger.info(f"LANG: {src_lang}, TEXT: {text[:20]}, NB_CHUNKS: {len(chunks)}")
|
92 |
+
|
93 |
+
# Translate chunks
|
94 |
+
translated_chunks = []
|
95 |
+
for chunk in chunks:
|
96 |
+
inputs = tokenizer(
|
97 |
+
chunk, return_tensors="pt",
|
98 |
+
max_length=input_max_length,
|
99 |
+
truncation=True, padding="longest").to(model.device)
|
100 |
+
|
101 |
+
outputs = model.generate(
|
102 |
+
**inputs,
|
103 |
+
max_length=output_max_length)
|
104 |
+
|
105 |
+
translated_chunk = tokenizer.batch_decode(
|
106 |
+
outputs, skip_special_tokens=True)[0]
|
107 |
+
|
108 |
+
#logger.info(f"Text: {chunk}")
|
109 |
+
#logger.info(f"Translation: {translated_chunk}")
|
110 |
+
|
111 |
+
translated_chunks.append(translated_chunk)
|
112 |
+
|
113 |
+
return '\n'.join(translated_chunks)
|
114 |
+
|
115 |
+
def detect_language(text):
|
116 |
+
lang = langdetect.detect(text)
|
117 |
+
return lang
|
118 |
+
|
119 |
@spaces.GPU
|
120 |
+
def translate_with_multilingual_model(
|
121 |
text: str,
|
122 |
tgt_lang: str,
|
123 |
+
sents_per_chunk: int=5,
|
124 |
+
input_max_length: int=512,
|
125 |
+
output_max_length: int=512):
|
126 |
"""
|
127 |
+
Translate the givent text into English (default "easy" language)
|
|
|
|
|
128 |
"""
|
129 |
+
chunks = build_text_chunks(text, None, sents_per_chunk)
|
130 |
+
translated_chunks = []
|
131 |
+
|
132 |
+
for chunk in chunks:
|
133 |
+
input_text = f"<2{tgt_lang}> {text}"
|
134 |
+
logger.info(f" Translating: {input_text[:30]}")
|
135 |
+
input_ids = tokenizer_multilingual(
|
136 |
+
input_text, return_tensors="pt",
|
137 |
+
max_length=input_max_length,
|
138 |
+
truncation=True, padding="longest").input_ids.to(
|
139 |
+
model_multilingual.device)
|
140 |
+
outputs = model_multilingual.generate(
|
141 |
+
input_ids=input_ids, max_length=output_max_length)
|
142 |
+
translated_chunk = tokenizer_multilingual.decode(outputs[0], skip_special_tokens=True)
|
143 |
+
translated_chunks.append(translated_chunk)
|
144 |
+
|
145 |
+
return '\n'.join(translated_chunks)
|
146 |
+
|
147 |
+
def translate_text(
|
148 |
+
text: str,
|
149 |
+
src_lang: str=None,
|
150 |
+
sents_per_chunk: int=5,
|
151 |
+
input_max_length: int=512,
|
152 |
+
output_max_length: int=512):
|
153 |
+
"""
|
154 |
+
Translate the given text into English (default "easy" language)
|
155 |
+
"""
|
156 |
+
#
|
157 |
+
# Bilingual (Helsinki model)
|
158 |
+
#
|
159 |
+
src_lang = src_lang if (src_lang and src_lang != "auto") else detect_language(text)
|
160 |
+
if src_lang not in translation.src_langs:
|
161 |
+
return (
|
162 |
+
f"ISSUE: currently no model for language '{src_lang}'. "
|
163 |
+
"If wrong language, please specify language."
|
164 |
+
)
|
165 |
+
logger.info(f"LANG: {src_lang}, TEXT: {text[:50]}...")
|
166 |
+
tokenizer, model = translation.get_tokenizer_model_for_src_lang(src_lang)
|
167 |
+
|
168 |
+
translated_text_bilingual_model = translate_with_model(
|
169 |
+
text, tokenizer, model, src_lang, sents_per_chunk)
|
170 |
+
|
171 |
+
#
|
172 |
+
# Multilingual model (Google MADLAD)
|
173 |
+
#
|
174 |
+
tgt_lang = 'en' # Default "easy" language
|
175 |
+
translated_text_multilingual_model = translate_with_multilingual_model(
|
176 |
+
text, tgt_lang, sents_per_chunk, input_max_length, output_max_length)
|
177 |
+
|
178 |
+
#
|
179 |
+
# Google Translate
|
180 |
+
#
|
181 |
+
translated_text_google_translate = GoogleTranslator(
|
182 |
+
source='auto', target='en').translate(text=text)
|
183 |
+
|
184 |
+
return (
|
185 |
+
translated_text_bilingual_model,
|
186 |
+
translated_text_multilingual_model,
|
187 |
+
translated_text_google_translate
|
188 |
+
)
|
189 |
+
|
190 |
|
191 |
#
|
192 |
# User interface
|
|
|
194 |
with gr.Blocks() as demo:
|
195 |
|
196 |
gr.Markdown("""
|
197 |
+
## Text translation v0.0.2 (basic, small paragraph, multilingual)
|
198 |
""")
|
199 |
input_text = gr.Textbox(
|
200 |
+
lines=15,
|
201 |
placeholder="Enter text to translate",
|
202 |
label="Text to translate",
|
203 |
render=False
|
204 |
)
|
205 |
+
output_text_bilingual_model = gr.Textbox(
|
206 |
+
lines=6,
|
207 |
+
label="Bilingual translation model (Helsinki NLP)",
|
208 |
+
render=False
|
209 |
+
)
|
210 |
+
output_text_multilingual_model = gr.Textbox(
|
211 |
+
lines=6,
|
212 |
+
label="Multilingual translation model (**small** Google MADLAD)",
|
213 |
+
render=False
|
214 |
+
)
|
215 |
+
output_text_google_translate = gr.Textbox(
|
216 |
+
lines=6,
|
217 |
+
label="Google Translate",
|
218 |
+
render=False
|
219 |
+
)
|
220 |
+
|
221 |
+
# Extra (additional) input parameters
|
222 |
+
sentences_per_chunk = gr.Slider(
|
223 |
+
minimum=1, maximum=10, value=5, step=1,
|
224 |
+
label="nb sentences per context",
|
225 |
+
render=False
|
226 |
+
)
|
227 |
+
src_lang = gr.Radio(
|
228 |
+
choices=["auto", "ar", "en", "fa", "fr", "he", "ja", "zh"], value="auto",
|
229 |
+
label="Source language",
|
230 |
+
render=False
|
231 |
+
)
|
232 |
|
233 |
# Examples
|
234 |
examples = [
|
235 |
+
["ریچارد مور، رئیس سازمان مخفی اطلاعاتی بریتانیا (امآی۶) در دیدار ویلیام برنز، رئیس سازمان اطلاعات مرکزی آمریکا (سیا) گفت همچنان احتمال اقدام ایران علیه اسرائیل در واکنش به ترور اسماعیل هنیه، رهبر حماس وجود دارد. آقای برنز نیز در این دیدار فاش کرد که در سال اول جنگ اوکراین، «خطر واقعی» وجود داشت که روسیه به استفاده از «تسلیحات هستهای تاکتیکی» متوسل شود. این دو مقام امنیتی هشدار دادند که «نظم جهانی» از زمان جنگ سرد تا کنون تا این حد «در معرض تهدید» نبوده است.", "fa"],
|
236 |
+
["Clément Delangue est, avec Julien Chaumond et Thomas Wolf, l’un des trois Français cofondateurs de Hugging Face, une start-up d’intelligence artificielle (IA) de premier plan. Valorisée à 4,2 milliards d’euros après avoir levé près de 450 millions d’euros depuis sa création en 2016, cette société de droit américain est connue comme la plate-forme de référence où développeurs et entreprises publient des outils et des modèles pour faire de l’IA en open source, c’est-à-dire accessible gratuitement et modifiable.", "fr"],
|
237 |
+
["يُعد تفشي مرض جدري القردة قضية صحية عالمية خطيرة، ومن المهم محاولة منع انتشاره للحفاظ على سلامة الناس وتجنب العدوى. د. صموئيل بولاند، مدير الحوادث الخاصة بمرض الجدري في المكتب الإقليمي لمنظمة الصحة العالمية في أفريقيا، يتحدث من كينشاسا في جمهورية الكونغو الديمقراطية، ولديه بعض النصائح البسيطة التي يمكن للناس اتباعها لتقليل خطر انتشار المرض.", "ar"],
|
238 |
+
["【ワシントン=冨山優介】米ボーイングの新型宇宙船「スターライナー」は7日午前0時(日本時間7日午後1時)過ぎ、米ニューメキシコ州のホワイトサンズ宇宙港に着地し、地球に帰還した。スターライナーは米宇宙飛行士2人を乗せて6月に打ち上げられ、国際宇宙ステーション(ISS)に接続したが、機体のトラブルが解決できず、無人でISSから離脱した。", "ja"],
|
239 |
+
["張先生稱,奇瑞已經凖備在西班牙生產汽車,並決心採取「本地化」的方式進入歐洲市場。此外,他也否認該公司的出口受益於不公平補貼。奇瑞成立於1997年,是中國最大的汽車公司之一。它已經是中國最大的汽車出口商,並且制定了進一步擴張的野心勃勃的計劃。", "zh"],
|
240 |
+
["ברוכה הבאה, קיטי: בית הקפה החדש בלוס אנג'לס החתולה האהובה והחברים שלה מקבלים בית קפה משלהם בשדרות יוניברסל סיטי, שם תוכלו למצוא מגוון של פינוקים מתוקים – החל ממשקאות ועד עוגות", "he"],
|
241 |
]
|
242 |
+
|
243 |
+
outputs = gr.Row(
|
244 |
+
|
245 |
+
)
|
246 |
|
247 |
gr.Interface(
|
248 |
fn=translate_text,
|
249 |
+
inputs=[input_text,],
|
250 |
+
outputs=[
|
251 |
+
output_text_bilingual_model,
|
252 |
+
output_text_multilingual_model,
|
253 |
+
output_text_google_translate,
|
254 |
+
],
|
255 |
+
additional_inputs=[src_lang, sentences_per_chunk],
|
256 |
+
clear_btn=None, # Unfortunately, clear_btn also reset the additional inputs. Hence disabling for now.
|
257 |
allow_flagging="never",
|
258 |
examples=examples,
|
259 |
cache_examples=True
|
|
|
261 |
|
262 |
with gr.Accordion("Documentation", open=False):
|
263 |
gr.Markdown("""
|
264 |
+
- Models: serving bilingual models from Helsinki NLP and multilingual model from Google MADLAD.
|
265 |
+
- Basic: processing of long paragraph / document to be enhanced.
|
266 |
- Most examples are copy/pasted from BBC news international web sites.
|
267 |
""")
|
268 |
|
269 |
+
if __name__ == "__main__":
|
270 |
+
demo.launch()
|
model_spacy.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
File: model_spacy.py
|
3 |
+
|
4 |
+
Description:
|
5 |
+
Load a spaCy model (will be used to split a text into sentences)
|
6 |
+
|
7 |
+
Author: Didier Guillevic
|
8 |
+
Date: 2024-03-30
|
9 |
+
"""
|
10 |
+
|
11 |
+
import spacy
|
12 |
+
|
13 |
+
model_xx_name = 'xx_sent_ud_sm'
|
14 |
+
|
15 |
+
nlp_xx = spacy.load(model_xx_name)
|
16 |
+
|
17 |
+
if __name__ == "__main__":
|
18 |
+
text = """
|
19 |
+
This is a very long text. Actually, not that long but still made of a few sentences.
|
20 |
+
"""
|
21 |
+
sentences = [sent.text.strip() for sent in nlp(text).sents if sent.text.strip()]
|
22 |
+
print(f"Nb of sentences: {len(sentences)}")
|
23 |
+
for i, sent in enumerate(sentences):
|
24 |
+
print(f"{i:2}: {sent}")
|
model_translation.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
File: model_translation.py
|
3 |
+
|
4 |
+
Description:
|
5 |
+
Loading models for text translations (EN->FR, FR->EN)
|
6 |
+
|
7 |
+
Author: Didier Guillevic
|
8 |
+
Date: 2024-03-16
|
9 |
+
"""
|
10 |
+
|
11 |
+
import torch
|
12 |
+
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
|
13 |
+
|
14 |
+
src_langs = set(["ar", "en", "fa", "fr", "he", "ja", "zh"])
|
15 |
+
model_names = {
|
16 |
+
"ar": "Helsinki-NLP/opus-mt-ar-en",
|
17 |
+
"en": "Helsinki-NLP/opus-mt-en-fr",
|
18 |
+
"fa": "Helsinki-NLP/opus-mt-tc-big-fa-itc",
|
19 |
+
"fr": "Helsinki-NLP/opus-mt-fr-en",
|
20 |
+
"he": "Helsinki-NLP/opus-mt-tc-big-he-en",
|
21 |
+
"ja": "Helsinki-NLP/opus-mt-jap-en",
|
22 |
+
"zh": "Helsinki-NLP/opus-mt-zh-en",
|
23 |
+
}
|
24 |
+
|
25 |
+
# Registry for all loaded bilingual models
|
26 |
+
tokenizer_model_registry = {}
|
27 |
+
|
28 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
29 |
+
|
30 |
+
def get_tokenizer_model_for_src_lang(src_lang: str) -> (AutoTokenizer, AutoModelForSeq2SeqLM):
|
31 |
+
"""
|
32 |
+
Return the (tokenizer, model) for a given source language.
|
33 |
+
"""
|
34 |
+
src_lang = src_lang.lower()
|
35 |
+
|
36 |
+
# Already loaded?
|
37 |
+
if src_lang in tokenizer_model_registry:
|
38 |
+
return tokenizer_model_registry.get(src_lang)
|
39 |
+
|
40 |
+
# Load tokenizer and model
|
41 |
+
model_name = model_names.get(src_lang)
|
42 |
+
if not model_name:
|
43 |
+
raise Exception(f"No model defined for language: {src_lang}")
|
44 |
+
|
45 |
+
# We will leave the models on the CPU (for now)
|
46 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
47 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
48 |
+
if model.config.torch_dtype != torch.float16:
|
49 |
+
model = model.half()
|
50 |
+
model = model.to(device)
|
51 |
+
tokenizer_model_registry[src_lang] = (tokenizer, model)
|
52 |
+
|
53 |
+
return (tokenizer, model)
|
54 |
+
|
55 |
+
# Max number of words for given input text
|
56 |
+
# - Usually 512 tokens (max position encodings, as well as max length)
|
57 |
+
# - Let's set to some number of words somewhat lower than that threshold
|
58 |
+
# - e.g. 200 words
|
59 |
+
max_words_per_chunk = 200
|
60 |
+
|
61 |
+
#
|
62 |
+
# Multilingual translation model
|
63 |
+
#
|
64 |
+
model_MADLAD_name = "google/madlad400-3b-mt"
|
65 |
+
#model_MADLAD_name = "google/madlad400-7b-mt-bt"
|
66 |
+
tokenizer_multilingual = AutoTokenizer.from_pretrained(model_MADLAD_name, use_fast=True)
|
67 |
+
model_multilingual = AutoModelForSeq2SeqLM.from_pretrained(
|
68 |
+
model_MADLAD_name, device_map="auto", torch_dtype=torch.float16)
|
69 |
+
|