lossLopes commited on
Commit
4508468
1 Parent(s): e3aeeca

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
+ import torch
4
+ from collections import Counter
5
+ from scipy.special import softmax
6
+
7
+ 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>."
8
+
9
+ app_title = "Offensive Language Detection (Detecção de Linguagem Ofensiva)"
10
+
11
+ app_description = """
12
+ This app detects offensive language on Portuguese text using multiple models. You can either introduce your own sentences by filling in "Text" or click on one of the examples provided below.
13
+ (Este aplicativo detecta linguagem ofensiva em texto em português usando vários modelos. Introduza suas próprias frases preenchendo o campo "Text", ou clique em um dos exemplos fornecidos abaixo.)
14
+ """
15
+
16
+ app_examples = [
17
+ ["Aquele cara é um babaca."],
18
+ ["Quem não deve não teme!!"],
19
+ ["Que nojo!🤮🤮🤮🤮🤮"],
20
+ ["Vagabunda,Ordinária"],
21
+ ["Vou mandar um óleo de peroba pra ela de presente! 😂😂😂😂"],
22
+ ["Porque é corrupta é conivente com o desgoverno anterior"],
23
+ ["A cada dia fico mais admirado com a cara de pau da elite dominante desse mundo até quando irão nos fazer de otários"]
24
+ ]
25
+
26
+ output_textbox_component_description = """
27
+ This box will display offensive language detection results based on the average score of multiple models.
28
+ (Esta caixa exibirá resultados da detecção de linguagem ofensiva com base na pontuação média de vários modelos.)
29
+ """
30
+
31
+ output_json_component_description = { "breakdown": """
32
+ This box presents a detailed breakdown of the evaluation for each model.
33
+ """,
34
+ "detalhamento": """
35
+ (Esta caixa apresenta um detalhamento da avaliação para cada modelo.)
36
+ """ }
37
+
38
+ short_score_descriptions = {
39
+ 0: "Not offensive",
40
+ 1: "Offensive"
41
+ }
42
+
43
+ score_descriptions = {
44
+ 0: "This text is not offensive.",
45
+ 1: "This text is offensive.",
46
+ }
47
+
48
+ score_descriptions_pt = {
49
+ 1: "(Este texto é ofensivo.)",
50
+ 0: "(Este texto não é ofensivo.)",
51
+ }
52
+
53
+ model_list = [
54
+ "ruanchaves/mdeberta-v3-base-hatebr",
55
+ "ruanchaves/bert-base-portuguese-cased-hatebr",
56
+ "ruanchaves/bert-large-portuguese-cased-hatebr",
57
+ ]
58
+
59
+ user_friendly_name = {
60
+ "ruanchaves/mdeberta-v3-base-hatebr": "mDeBERTa-v3 (HateBR)",
61
+ "ruanchaves/bert-base-portuguese-cased-hatebr": "BERTimbau base (HateBR)",
62
+ "ruanchaves/bert-large-portuguese-cased-hatebr": "BERTimbau large (HateBR)",
63
+ }
64
+
65
+ reverse_user_friendly_name = { v:k for k,v in user_friendly_name.items() }
66
+
67
+ user_friendly_name_list = list(user_friendly_name.values())
68
+
69
+ model_array = []
70
+
71
+ for model_name in model_list:
72
+ row = {}
73
+ row["name"] = model_name
74
+ row["tokenizer"] = AutoTokenizer.from_pretrained(model_name)
75
+ row["model"] = AutoModelForSequenceClassification.from_pretrained(model_name)
76
+ model_array.append(row)
77
+
78
+ def most_frequent(array):
79
+ occurence_count = Counter(array)
80
+ return occurence_count.most_common(1)[0][0]
81
+
82
+
83
+ def predict(s1, chosen_model):
84
+ if not chosen_model:
85
+ chosen_model = user_friendly_name_list[0]
86
+ scores = {}
87
+ full_chosen_model_name = reverse_user_friendly_name[chosen_model]
88
+ for row in model_array:
89
+ name = row["name"]
90
+ if name != full_chosen_model_name:
91
+ continue
92
+ else:
93
+ tokenizer = row["tokenizer"]
94
+ model = row["model"]
95
+ model_input = tokenizer(*([s1],), padding=True, return_tensors="pt")
96
+ with torch.no_grad():
97
+ output = model(**model_input)
98
+ logits = output[0][0].detach().numpy()
99
+ logits = softmax(logits).tolist()
100
+ break
101
+ def get_description(idx):
102
+ description = score_descriptions[idx]
103
+ description_pt = score_descriptions_pt[idx]
104
+ final_description = description + "\n \n" + description_pt
105
+ return final_description
106
+
107
+ max_pos = logits.index(max(logits))
108
+ markdown_description = get_description(max_pos)
109
+ scores = { short_score_descriptions[k]:v for k,v in enumerate(logits) }
110
+
111
+ return scores, markdown_description
112
+
113
+
114
+ inputs = [
115
+ gr.Textbox(label="Text", value=app_examples[0][0]),
116
+ gr.Dropdown(label="Model", choices=user_friendly_name_list, value=user_friendly_name_list[0])
117
+ ]
118
+
119
+ outputs = [
120
+ gr.Label(label="Result"),
121
+ gr.Markdown(),
122
+ ]
123
+
124
+
125
+ gr.Interface(fn=predict, inputs=inputs, outputs=outputs, title=app_title,
126
+ description=app_description,
127
+ examples=app_examples,
128
+ article = article_string).launch()