ruanchaves commited on
Commit
3245b7e
1 Parent(s): 5121405

feat: semantic similarity app

Browse files
Files changed (1) hide show
  1. app.py +75 -9
app.py CHANGED
@@ -2,6 +2,52 @@ import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import torch
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
  model_list = [
7
  "ruanchaves/mdeberta-v3-base-assin2-similarity",
@@ -12,26 +58,45 @@ model_list = [
12
  "ruanchaves/bert-large-portuguese-cased-assin-similarity",
13
  ]
14
 
 
 
 
 
 
 
 
 
 
15
  model_array = []
16
 
17
  for model_name in model_list:
18
  row = {}
 
19
  row["tokenizer"] = AutoTokenizer.from_pretrained(model_name)
20
  row["model"] = AutoModelForSequenceClassification.from_pretrained(model_name)
21
  model_array.append(row)
22
 
23
 
24
  def similarity(s1, s2):
25
- scores = []
26
  for row in model_array:
 
27
  tokenizer = row["tokenizer"]
28
  model = row["model"]
29
  model_input = tokenizer(*([s1, s1], [s2, s1]), padding=True, return_tensors="pt")
30
  with torch.no_grad():
31
  output = model(**model_input)
32
  score = output[0][0].item()
33
- scores.append(score)
34
- return sum(scores) / len(scores)
 
 
 
 
 
 
 
 
35
 
36
 
37
  inputs = [
@@ -39,11 +104,12 @@ inputs = [
39
  gr.inputs.Textbox(label="Text 2")
40
  ]
41
 
42
- outputs = gr.outputs.Textbox(label="Similarity Score")
 
 
 
43
 
44
 
45
- gr.Interface(fn=similarity, inputs=inputs, outputs=outputs, title="Semantic Similarity",
46
- description="Calculates semantic similarity between two pieces of text using multiple pre-trained models.",
47
- examples=[["A quem é atribuida a invenção do ábaco?", "A primeira ferramenta conhecida para a computação foi o ábaco, cuja invenção é atribuída a habitantes da Mesopotâmia, em torno de 2700–2300 a.C.."],
48
- ["I love pizza", "Pizza is my favorite food"],
49
- ["I hate cats", "I love dogs"]]).launch()
 
2
  from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
  import torch
4
 
5
+ app_title = "Semantic Similarity (Similaridade Semântica)"
6
+
7
+ app_description = """
8
+ This app calculates the semantic similarity between two pieces of Portuguese text using multiple models. You can either introduce your own sentences by filling in "Text 1" and "Text 2" or click on one of the example pairs provided below.
9
+
10
+ Este aplicativo calcula a similaridade semântica entre dois trechos de texto em português usando vários modelos. Introduza suas próprias frases preenchendo "Text 1" e "Text 2", ou clique em um dos pares de exemplo fornecidos abaixo.
11
+ """
12
+
13
+ app_examples = [
14
+ ["Uma pessoa tem cabelo loiro e esvoaçante e está tocando violão.", "Um guitarrista tem cabelo loiro e esvoaçante."],
15
+ ["A batata está sendo descascada por uma mulher", "Uma mulher está descascando a batata"],
16
+ ["Uma mulher está temperando um pedaço de carne", "Não tem nenhum homem carregando um rifle com balas"]
17
+ ]
18
+
19
+ output_textbox_component_description = """
20
+ This box will display the semantic similarity evaluation based on the average score of multiple models.
21
+
22
+ Esta caixa exibirá a avaliação de similaridade semântica com base na pontuação média de vários modelos.
23
+ """
24
+
25
+ output_json_component_description = { "breakdown": """
26
+ This box presents a detailed breakdown of the evaluation for each model,
27
+ displaying the percentage of similarity between the text pairs.
28
+ """,
29
+ "detalhamento": """
30
+ Esta caixa apresenta um detalhamento da avaliação para cada modelo,
31
+ exibindo a porcentagem de similaridade entre os pares textuais.
32
+ """ }
33
+
34
+ score_descriptions = {
35
+ 0: "The sentences are completely different from each other and do not have any common topic or similarity.",
36
+ 1: "The sentences are completely different from each other and do not have any common topic or similarity.",
37
+ 2: "The sentences are not directly related, but they share some topic or theme.",
38
+ 3: "The sentences are somewhat related: they may have different content but have some common details or aspects.",
39
+ 4: "The sentences are strongly related, but still have some differences in details or wording.",
40
+ 5: "The sentences convey essentially the same message or information."
41
+ }
42
+
43
+ score_descriptions_pt = {
44
+ 0: "As frases são completamente diferentes uma da outra e não têm nenhum tópico ou semelhança em comum.",
45
+ 1: "As frases são completamente diferentes uma da outra e não têm nenhum tópico ou semelhança em comum.",
46
+ 2: "As frases não estão diretamente relacionadas, mas compartilham algum tópico ou tema.",
47
+ 3: "As frases são um pouco relacionadas: podem ter conteúdo diferente, mas têm alguns detalhes ou aspectos comuns.",
48
+ 4: "As frases estão fortemente relacionadas, mas ainda têm algumas diferenças em detalhes ou palavras.",
49
+ 5: "As frases transmitem essencialmente a mesma mensagem ou informação."
50
+ }
51
 
52
  model_list = [
53
  "ruanchaves/mdeberta-v3-base-assin2-similarity",
 
58
  "ruanchaves/bert-large-portuguese-cased-assin-similarity",
59
  ]
60
 
61
+ user_friendly_name = {
62
+ "ruanchaves/mdeberta-v3-base-assin2-similarity": "mDeBERTa-v3 (ASSIN 2)",
63
+ "ruanchaves/bert-base-portuguese-cased-assin2-similarity": "BERTimbau base (ASSIN 2)",
64
+ "ruanchaves/bert-large-portuguese-cased-assin2-similarity": "BERTimbau large (ASSIN 2)",
65
+ "ruanchaves/mdeberta-v3-base-assin-similarity": "mDeBERTa-v3 (ASSIN)",
66
+ "ruanchaves/bert-base-portuguese-cased-assin-similarity": "BERTimbau base (ASSIN)",
67
+ "ruanchaves/bert-large-portuguese-cased-assin-similarity": "BERTimbau large (ASSIN)"
68
+ }
69
+
70
  model_array = []
71
 
72
  for model_name in model_list:
73
  row = {}
74
+ row["name"] = model_name
75
  row["tokenizer"] = AutoTokenizer.from_pretrained(model_name)
76
  row["model"] = AutoModelForSequenceClassification.from_pretrained(model_name)
77
  model_array.append(row)
78
 
79
 
80
  def similarity(s1, s2):
81
+ scores = {}
82
  for row in model_array:
83
+ name = user_friendly_name[row["name"]]
84
  tokenizer = row["tokenizer"]
85
  model = row["model"]
86
  model_input = tokenizer(*([s1, s1], [s2, s1]), padding=True, return_tensors="pt")
87
  with torch.no_grad():
88
  output = model(**model_input)
89
  score = output[0][0].item()
90
+ scores[name] = score
91
+ average_score = sum(scores.values()) / len(scores)
92
+ description = score_descriptions[round(average_score)]
93
+ description_pt = score_descriptions_pt[round(average_score)]
94
+ final_description = description + "\n \n" + description_pt
95
+
96
+ for key, value in scores.items():
97
+ scores[key] = '{:,.2%}'.format(min(value, 5) / 5)
98
+
99
+ return final_description, scores
100
 
101
 
102
  inputs = [
 
104
  gr.inputs.Textbox(label="Text 2")
105
  ]
106
 
107
+ outputs = [
108
+ gr.Textbox(label="Evaluation", value=output_textbox_component_description),
109
+ gr.JSON(label="Breakdown", value=output_json_component_description)
110
+ ]
111
 
112
 
113
+ gr.Interface(fn=similarity, inputs=inputs, outputs=outputs, title=app_title,
114
+ description=app_description,
115
+ examples=app_examples).launch(share=True, debug=True)