File size: 5,538 Bytes
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
import gradio as gr
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

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/evaluation-portuguese-language-models\">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.)
""" }

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: "Additionally, the premise has also been detected as being 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: "(Além disso, a premissa também foi detectada como sendo 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)"
}

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 entailment(s1, s2):
    scores = {}
    for row in model_array:
        name = user_friendly_name[row["name"]]
        tokenizer = row["tokenizer"]
        model = row["model"]
        model_input = tokenizer(*([s1], [s2]), padding=True, return_tensors="pt")
        with torch.no_grad():
            output = model(**model_input)
            score = output[0][0].argmax().item()
            scores[name] = score
    assin2_scores = {k: v for k, v in scores.items() if "ASSIN 2" in k}
    average_score = most_frequent(assin2_scores.values())
    description = score_descriptions[average_score]
    description_pt = score_descriptions_pt[average_score]

    if 2 in scores.values():
        description = description + "\n" + score_descriptions[2]
        description_pt = description_pt + "\n" + score_descriptions_pt[2]
    final_description = description + "\n \n" + description_pt

    for key, value in scores.items():
      scores[key] = score_short_keys[value]

    return final_description, scores


inputs = [
    gr.inputs.Textbox(label="Premise"),
    gr.inputs.Textbox(label="Hypothesis")
]

outputs = [
 gr.Textbox(label="Evaluation", value=output_textbox_component_description),
 gr.JSON(label="Results by model", value=output_json_component_description)
]


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