makenmtviz / app.py
Gabriela Nicole Gonzalez Saez
fix error
9221f9f
raw
history blame
6.05 kB
import gradio as gr
import inseq
import captum
import torch
import os
# import nltk
import argparse
import random
import numpy as np
from argparse import Namespace
from tqdm.notebook import tqdm
from torch.utils.data import DataLoader
from functools import partial
from transformers import AutoTokenizer, MarianTokenizer, AutoModel, AutoModelForSeq2SeqLM, MarianMTModel
from bertviz import model_view, head_view
from bertviz_gradio import head_view_mod
model_es = "Helsinki-NLP/opus-mt-en-es"
model_fr = "Helsinki-NLP/opus-mt-en-fr"
model_zh = "Helsinki-NLP/opus-mt-en-zh"
tokenizer_es = AutoTokenizer.from_pretrained(model_es)
tokenizer_fr = AutoTokenizer.from_pretrained(model_fr)
tokenizer_zh = AutoTokenizer.from_pretrained(model_zh)
model_tr_es = MarianMTModel.from_pretrained(model_es)
model_tr_fr = MarianMTModel.from_pretrained(model_fr)
model_tr_zh = MarianMTModel.from_pretrained(model_zh)
model_es = inseq.load_model("Helsinki-NLP/opus-mt-en-es", "input_x_gradient")
model_fr = inseq.load_model("Helsinki-NLP/opus-mt-en-fr", "input_x_gradient")
model_zh = inseq.load_model("Helsinki-NLP/opus-mt-en-zh", "input_x_gradient")
dict_models = {
'en-es': model_es,
'en-fr': model_fr,
'en-zh': model_zh,
}
dict_models_tr = {
'en-es': model_tr_es,
'en-fr': model_tr_fr,
'en-zh': model_tr_zh,
}
dict_tokenizer_tr = {
'en-es': tokenizer_es,
'en-fr': tokenizer_fr,
'en-zh': tokenizer_zh,
}
saliency_examples = [
"Peace of Mind: Protection for consumers.",
"The sustainable development goals report: towards a rescue plan for people and planet",
"We will leave no stone unturned to hold those responsible to account.",
"The clock is now ticking on our work to finalise the remaining key legislative proposals presented by this Commission to ensure that citizens and businesses can reap the benefits of our policy actions.",
"Pumpkins, squash and gourds, fresh or chilled, excluding courgettes",
"The labour market participation of mothers with infants has even deteriorated over the past two decades, often impacting their career and incomes for years.",
]
contrastive_examples = [
["Peace of Mind: Protection for consumers.",
"Paz mental: protección de los consumidores",
"Paz de la mente: protección de los consumidores"],
["the slaughterer has finished his work.",
"l'abatteur a terminé son travail.",
"l'abatteuse a terminé son travail."],
['A fundamental shift is needed - in commitment, solidarity, financing and action - to put the world on a better path.',
'需要在承诺、团结、筹资和行动方面进行根本转变,使世界走上更美好的道路。',
'我们需要从根本上转变承诺、团结、资助和行动,使世界走上更美好的道路。',]
]
def get_bertvis_data(input_text, lg_model):
tokenizer_tr = dict_tokenizer_tr[lg_model]
model_tr = dict_models_tr[lg_model]
input_ids = tokenizer_tr(input_text, return_tensors="pt", padding=True)
result_att = model_tr.generate(**input_ids,
return_dict_in_generate=True,
output_attentions =True,
output_scores=True,
)
# tokenizer_tr.convert_ids_to_tokens(result_att.sequences[0])
# tokenizer_tr.convert_ids_to_tokens(input_ids.input_ids[0])
tgt_text = tokenizer_tr.decode(result_att.sequences[0], skip_special_tokens=True)
print(tgt_text)
outputs = model_tr(input_ids=input_ids.input_ids,
decoder_input_ids=result_att.sequences,
output_attentions =True,
)
print(tokenizer_tr.convert_ids_to_tokens(result_att.sequences[0]))
# print(tokenizer_tr.convert_ids_to_tokens(input_ids.input_ids[0]), tokenizer_tr.convert_ids_to_tokens(result_att.sequences[0]))
html_attentions = head_view_mod(
encoder_attention = outputs.encoder_attentions,
cross_attention = outputs.cross_attentions,
decoder_attention = outputs.decoder_attentions,
encoder_tokens = tokenizer_tr.convert_ids_to_tokens(input_ids.input_ids[0]),
decoder_tokens = tokenizer_tr.convert_ids_to_tokens(result_att.sequences[0]),
html_action='gradio'
)
return html_attentions, tgt_text
## First create html and divs
html = """
<html>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min"></script>
<script async data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<body>
<div id="bertviz"></div>
<div id="d3_beam_search"></div>
</body>
</html>
"""
def sentence_maker(w1, model, var2={}):
#translate and get internal values
params,tgt = get_bertvis_data(w1, model)
### get translation
return [tgt, params['params'],params['html2'].data]
def sentence_maker2(w1,j2):
# json_value = {'one':1}
# return f"{w1['two']} in sentence22..."
print(w1,j2)
return "in sentence22..."
with gr.Blocks(js="plotsjs_bertviz.js") as demo:
gr.Markdown("""
# MAKE NMT Workshop \t `BertViz` \n
https://github.com/jessevig/bertviz
""")
with gr.Row():
with gr.Column(scale=1):
in_text = gr.Textbox(label="Source Text")
out_text = gr.Textbox(label="Target Text")
out_text2 = gr.Textbox(visible=False)
var2 = gr.JSON(visible=False)
btn = gr.Button("Create sentence.")
radio_c = gr.Radio(choices=['en-zh', 'en-es', 'en-fr'], value="en-zh", label= '', container=False)
with gr.Column(scale=4):
gr.Markdown("Attentions: ")
input_mic = gr.HTML(html)
out_html = gr.HTML()
btn.click(sentence_maker, [in_text,radio_c], [out_text,var2,out_html], js="(in_text,radio_c) => testFn_out(in_text,radio_c)") #should return an output comp.
out_text.change(sentence_maker2, [out_text, var2], out_text2, js="(out_text,var2) => testFn_out_json(var2)") #
# out_text.change(sentence_maker2, [out_text, var2], out_text2, js="(out_text,var2) => testFn_out_json(var2)") #
# run script function on load,
# demo.load(None,None,None,js="plotsjs.js")
if __name__ == "__main__":
demo.launch()