File size: 5,836 Bytes
3eb176d
 
 
69f0559
3eb176d
 
 
 
 
 
c69e84b
3eb176d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa5ff01
 
 
 
 
 
3eb176d
 
 
69f0559
3eb176d
 
 
 
 
 
69f0559
3eb176d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f0559
 
 
 
 
3eb176d
 
 
 
 
 
 
 
 
 
69f0559
 
 
3eb176d
69f0559
3eb176d
69f0559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa5ff01
 
 
69f0559
fa5ff01
3eb176d
 
 
fa5ff01
 
 
3eb176d
 
 
fa5ff01
 
3eb176d
 
 
69f0559
3eb176d
 
 
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
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from scipy.special import softmax
from collections import Counter
 
def most_frequent(array):
    occurence_count = Counter(array)
    return occurence_count.most_common(1)[0][0]

article_string = "Author: <a href=\"https://huggingface.co/ruanchaves\">Ruan Chaves Rodrigues</a>. Read more about our <a href=\"https://github.com/ruanchaves/eplm\">research on the evaluation of Portuguese language models</a>."

app_title = "Textual entailment (Implicação)"

app_description = """
This app detects textual entailment and paraphrase between two pieces of Portuguese text using multiple models. You can either introduce your own sentences by filling in "Premise" and "Hypothesis" or click on one of the example pairs provided below.

(Este aplicativo detecta implicação e paráfrase entre dois trechos de texto em português usando vários modelos. Introduza suas próprias frases preenchendo "Premise" e "Hypothesis", ou clique em um dos pares de exemplo fornecidos abaixo.)
"""

app_examples = [
    ["Uma pessoa tem cabelo loiro e esvoaçante e está tocando violão.", "Um guitarrista tem cabelo loiro e esvoaçante."],
    ["A batata está sendo descascada por uma mulher", "Uma mulher está descascando a batata"],
    ["Uma mulher está temperando um pedaço de carne", "Não tem nenhum homem carregando um rifle com balas"]
]

output_textbox_component_description = """
This box will display the relationship between premise and hypothesis based on the average score of multiple models.

(Esta caixa exibirá a relação entre premissa e hipótese com base na pontuação média de vários modelos.)
"""

output_json_component_description = { "breakdown": """
This box presents a detailed breakdown of the evaluation for each model, 
displaying the relationship between the text pairs.
""",
"detalhamento": """
(Esta caixa apresenta um detalhamento da avaliação para cada modelo,
exibindo a relação entre os pares textuais.)
""" }

short_score_descriptions = {
  1: "Entailment (Implicação)",
  0: "No relationship (Nenhuma relação)",
  2: "Paraphrase (Paráfrase)"
}

score_descriptions = {
  1: "There is an entailment relation between premise and hypothesis. If the premise is true, then the hypothesis must also be true.",
  0: "There is no logical relation between the premise and the hypothesis.",
  2: "The premise is a paraphrase of the hypothesis."
}


score_descriptions_pt = {
   1: "(Existe uma relação de implicação entre premissa e hipótese. Se a premissa é verdadeira, então a hipótese também deve ser verdadeira.)",
   0: "(Não há relação lógica entre a premissa e a hipótese.)",
   2: "(A premissa é uma paráfrase da hipótese.)"
}

score_short_keys = {
    0: "No relationship (Nenhuma relação)",
    1: "Entailment (Implicação)",
    2: "Paraphrase (Paráfrase)"
}


model_list = [
    "ruanchaves/mdeberta-v3-base-assin2-entailment",
    "ruanchaves/bert-base-portuguese-cased-assin2-entailment",
    "ruanchaves/bert-large-portuguese-cased-assin2-entailment",
    "ruanchaves/mdeberta-v3-base-assin-entailment",
    "ruanchaves/bert-base-portuguese-cased-assin-entailment",
    "ruanchaves/bert-large-portuguese-cased-assin-entailment",
]

user_friendly_name = {
    "ruanchaves/mdeberta-v3-base-assin2-entailment": "mDeBERTa-v3 (ASSIN 2)",
    "ruanchaves/bert-base-portuguese-cased-assin2-entailment": "BERTimbau base (ASSIN 2)",
    "ruanchaves/bert-large-portuguese-cased-assin2-entailment": "BERTimbau large (ASSIN 2)",
    "ruanchaves/mdeberta-v3-base-assin-entailment": "mDeBERTa-v3 (ASSIN)",
    "ruanchaves/bert-base-portuguese-cased-assin-entailment": "BERTimbau base (ASSIN)",
    "ruanchaves/bert-large-portuguese-cased-assin-entailment": "BERTimbau large (ASSIN)"
}

reverse_user_friendly_name = { v:k for k,v in user_friendly_name.items() }

user_friendly_name_list = list(user_friendly_name.values())


model_array = []

for model_name in model_list:
    row = {}
    row["name"] = model_name
    row["tokenizer"] = AutoTokenizer.from_pretrained(model_name)
    row["model"] = AutoModelForSequenceClassification.from_pretrained(model_name)
    model_array.append(row)


def predict(s1, s2, chosen_model):
    if not chosen_model:
      chosen_model = user_friendly_name_list[0]
    scores = {}
    full_chosen_model_name = reverse_user_friendly_name[chosen_model]
    for row in model_array:
        name = row["name"]
        if name != full_chosen_model_name:
          continue
        else:
          tokenizer = row["tokenizer"]
          model = row["model"]
          model_input = tokenizer(*([s1], [s2]), padding=True, return_tensors="pt")
          with torch.no_grad():
              output = model(**model_input)
              logits = output[0][0].detach().numpy()
              logits = softmax(logits).tolist()
              break
    def get_description(idx):
      description = score_descriptions[idx]
      description_pt = score_descriptions_pt[idx]
      final_description = description + "\n \n" + description_pt
      return final_description
    
    max_pos = logits.index(max(logits))
    description = get_description(max_pos)
    scores = { short_score_descriptions[k]:v for k,v in enumerate(logits) }

    return scores, description


inputs = [
    gr.Textbox(label="Premise", value=app_examples[0][0]),
    gr.Textbox(label="Hypothesis", value=app_examples[0][1]),
    gr.Dropdown(label="Model", choices=user_friendly_name_list, value=user_friendly_name_list[0])
]

outputs = [
 gr.Label(label="Result"),
 gr.Markdown()
]


gr.Interface(fn=predict, inputs=inputs, outputs=outputs, title=app_title, 
             description=app_description,
             examples=app_examples,
             article = article_string).launch()