Spaces:
Paused
Paused
File size: 8,155 Bytes
b620462 4c18b68 e1b65d6 b620462 e1b65d6 aed1d52 e1b65d6 91126af e1b65d6 fb8fc36 e1b65d6 4c18b68 e1b65d6 b620462 4c18b68 b620462 e1b65d6 4c18b68 b620462 e1b65d6 4c18b68 e1b65d6 4c18b68 e1b65d6 4c18b68 e1b65d6 4c18b68 b620462 e1b65d6 4c18b68 b620462 e1b65d6 b620462 e1b65d6 b620462 e1b65d6 91126af e1b65d6 aed1d52 91126af aed1d52 e1b65d6 91126af e1b65d6 af8c6cf e1b65d6 91126af e1b65d6 91126af e1b65d6 91126af e1b65d6 91126af e1b65d6 b620462 e1b65d6 |
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 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 |
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
import itertools
DEVICE = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
MODEL_IDS = [
"70M",
"160M",
"410M",
"610M",
]
MODEL_MAPPING = {
model_id: f"LinguaCustodia/multilingual-multidomain-fin-mt-{model_id}"
for model_id in MODEL_IDS
}
MODEL_INDEX = {m: i for i, m in enumerate(MODEL_IDS)}
TOKENIZER = AutoTokenizer.from_pretrained(
MODEL_MAPPING["70M"],
pad_token="<pad>",
mask_token="<mask>",
eos_token="<eos>",
padding_side="left",
max_position_embeddings=512,
model_max_length=512,
)
MODELS = {
model_name: AutoModelForCausalLM.from_pretrained(
model_id,
max_position_embeddings=512,
device_map=DEVICE,
torch_dtype=torch.bfloat16,
)
for model_name, model_id in MODEL_MAPPING.items()
}
DOMAINS = [
"Auto",
"Asset management",
"Annual report",
"Corporate action",
"Equity research",
"Fund fact sheet",
"Kiid",
"Life insurance",
"Regulatory",
"General",
]
DOMAIN_MAPPING = {
"Auto": None,
"Asset management": "am",
"Annual report": "ar",
"Corporate action": "corporateAction",
"Equity research": "equi",
"Fund fact sheet": "ffs",
"Kiid": "kiid",
"Life insurance": "lifeInsurance",
"Regulatory": "regulatory",
"General": "general",
}
DOMAIN_MAPPING_REVERSED = {v: k for k, v in DOMAIN_MAPPING.items()}
LANG2CODE = {
"English": "en",
"German": "de",
"Spanish": "es",
"French": "fr",
"Italian": "it",
"Dutch": "nl",
"Swedish": "sv",
"Portuguese": "pt",
}
CODE2LANG = {v: k for k, v in LANG2CODE.items()}
LANGUAGES = sorted(LANG2CODE.keys())
def language_token(lang):
return f"<lang_{lang}>"
def domain_token(dom):
return f"<dom_{dom}>"
def language_token_to_str(token):
return token[6:-1]
def domain_token_to_str(token):
return token[5:-1]
def format_input(src, tgt_lang, src_lang, domain):
tgt_lang_token = language_token(tgt_lang)
prefix = TOKENIZER.eos_token
base_input = f"{prefix}{src}</src>{tgt_lang_token}"
if src_lang is None:
return base_input
else:
src_lang_token = language_token(src_lang)
base_input = f"{base_input}{src_lang_token}"
if domain is None:
return base_input
else:
dom_token = domain_token(domain)
base_input = f"{base_input}{dom_token}"
return base_input
def translate_with_model(model_name, text, tgt_lang, src_lang, domain):
model = MODELS[model_name]
formatted_text = format_input(text, tgt_lang, src_lang, domain)
inputs = TOKENIZER(formatted_text, return_tensors="pt", return_token_type_ids=False)
for k, v in inputs.items():
inputs[k] = v.to(DEVICE)
if src_lang is None:
domain_token_pos = inputs["input_ids"].size(1) + 1
elif domain is None:
domain_token_pos = inputs["input_ids"].size(1)
else:
domain_token_pos = inputs["input_ids"].size(1) - 1
src_lang_token_pos = domain_token_pos - 1
_tgt_lang_token_pos = src_lang_token_pos - 1
outputs = model.generate(
**inputs,
num_beams=5,
length_penalty=0.65,
max_new_tokens=500,
pad_token_id=TOKENIZER.pad_token_id,
eos_token_id=TOKENIZER.eos_token_id,
)
generated_translation = TOKENIZER.decode(
outputs[0, domain_token_pos + 1 :], skip_special_tokens=True
)
source_language_token = TOKENIZER.convert_ids_to_tokens(
outputs[0, src_lang_token_pos].item()
)
domain_token = TOKENIZER.convert_ids_to_tokens(outputs[0, domain_token_pos].item())
return {
"model": model_name,
"source_lang": CODE2LANG[language_token_to_str(source_language_token)],
"domain": DOMAIN_MAPPING_REVERSED[domain_token_to_str(domain_token)],
"translation": generated_translation,
}
def translate_with_all_models(selected_models, text, tgt_lang, src_lang, domain):
tgt_lang = LANG2CODE[tgt_lang]
src_lang = None if src_lang == "Auto" else LANG2CODE.get(src_lang)
domain = DOMAIN_MAPPING[domain]
outputs = [None] * (3 * len(MODEL_IDS))
outputs = list(
itertools.chain.from_iterable(
(
["Processing..."] * 3
if model_id in selected_models
else ["This model is disabled"] * 3
)
for model_id in MODEL_IDS
)
)
for model_id in selected_models:
i = MODEL_INDEX[model_id]
model_output = translate_with_model(model_id, text, tgt_lang, src_lang, domain)
outputs[i * 3] = model_output["translation"]
outputs[i * 3 + 1] = model_output["source_lang"]
outputs[i * 3 + 2] = model_output["domain"]
yield outputs
with gr.Blocks() as demo:
with gr.Row(variant="default"):
title = "🌐 Multilingual Multidomain Financial Translator"
description = """<p>Specialized Translation for Financial Documents across 8 Languages and 9 Domains</p>"""
gr.HTML(f"<h1>{title}</h1>\n<p>{description}</p>")
with gr.Row(variant="panel"):
with gr.Column(variant="default"):
selected_models = gr.CheckboxGroup(
choices=MODEL_IDS,
value=MODEL_IDS,
type="value",
label="Models",
container=True,
)
source_text = gr.Textbox(lines=3, label="Source sentence")
with gr.Column(variant="default"):
source_language = gr.Dropdown(
LANGUAGES + ["Auto"], value="Auto", label="Source language"
)
target_language = gr.Dropdown(
LANGUAGES, value="French", label="Target language"
)
with gr.Column(variant="default"):
domain = gr.Radio(DOMAINS, value="Auto", label="Domain")
with gr.Row():
translate_btn = gr.Button("Translate", variant="primary")
with gr.Row(variant="panel"):
outputs = {}
for model_id in MODEL_IDS:
with gr.Tab(model_id):
outputs[model_id] = {
"translation": gr.Textbox(
lines=2, label="Translation", container=True
),
"source_lang": gr.Textbox(
label="Predicted source language",
info='This is the predicted source language, if "Auto" is selected.',
container=True,
),
"domain": gr.Textbox(
label="Predicted domain",
info='This is the predicted domain, if "Auto" is checked.',
container=True,
),
}
gr.HTML(
f"<p>Model: <a href='https://huggingface.co/LinguaCustodia/multilingual-multidomain-fin-mt-{model_id}' target='_blank'>LinguaCustodia/multilingual-multidomain-fin-mt-{model_id}</a></p>"
)
with gr.Row(variant="panel"):
gr.HTML(
"""<p><strong>Please cite this work as:</strong>\n\n<pre>@inproceedings{DBLP:conf/wmt/CaillautNQLB24,
author = {Ga{\"{e}}tan Caillaut and
Mariam Nakhl{\'{e}} and
Raheel Qader and
Jingshu Liu and
Jean{-}Gabriel Barthelemy},
title = {Scaling Laws of Decoder-Only Models on the Multilingual Machine Translation Task},
booktitle = {{WMT}},
pages = {1318--1331},
publisher = {Association for Computational Linguistics},
year = {2024}
}</pre></p>"""
)
translate_btn.click(
fn=translate_with_all_models,
inputs=[selected_models, source_text, target_language, source_language, domain],
outputs=list(
itertools.chain.from_iterable(
[outputs[model_id][k] for k in ("translation", "source_lang", "domain")]
for model_id in MODEL_IDS
)
),
)
demo.launch()
|