osiria commited on
Commit
b918ec7
1 Parent(s): 45b6e26

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +199 -0
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import subprocess
4
+ import sys
5
+
6
+ def install(package):
7
+ subprocess.check_call([sys.executable, "-m", "pip", "install", package])
8
+
9
+ install("numpy")
10
+ install("torch")
11
+ install("transformers")
12
+ install("unidecode")
13
+
14
+ import numpy as np
15
+ import torch
16
+ from transformers import AutoTokenizer
17
+ from transformers import AutoModelForTokenClassification
18
+ from collections import Counter
19
+ from unidecode import unidecode
20
+ import string
21
+ import re
22
+
23
+ tokenizer = AutoTokenizer.from_pretrained("osiria/deberta-base-italian-uncased-ner")
24
+ model = AutoModelForTokenClassification.from_pretrained("osiria/deberta-base-italian-uncased-ner", num_labels = 5)
25
+ device = torch.device("cpu")
26
+ model = model.to(device)
27
+ model.eval()
28
+
29
+ from transformers import pipeline
30
+ ner = pipeline('ner', model=model, tokenizer=tokenizer, device=-1)
31
+
32
+
33
+ header = '''--------------------------------------------------------------------------------------------------
34
+ <style>
35
+ .vertical-text {
36
+ writing-mode: vertical-lr;
37
+ text-orientation: upright;
38
+ background-color:red;
39
+ }
40
+ </style>
41
+ <center>
42
+ <body>
43
+ <span class="vertical-text" style="background-color:lightgreen;border-radius: 3px;padding: 3px;"> </span>
44
+ <span class="vertical-text" style="background-color:orange;border-radius: 3px;padding: 3px;"> D</span>
45
+ <span class="vertical-text" style="background-color:lightblue;border-radius: 3px;padding: 3px;">    E</span>
46
+ <span class="vertical-text" style="background-color:tomato;border-radius: 3px;padding: 3px;">    M</span>
47
+ <span class="vertical-text" style="background-color:lightgrey;border-radius: 3px;padding: 3px;"> O</span>
48
+ <span class="vertical-text" style="background-color:#CF9FFF;border-radius: 3px;padding: 3px;"> </span>
49
+ </body>
50
+ </center>
51
+ <br>
52
+ <center>(BETA)</center>
53
+ '''
54
+
55
+ maps = {"O": "NONE", "PER": "PER", "LOC": "LOC", "ORG": "ORG", "MISC": "MISC", "DATE": "DATE"}
56
+ reg_month = "(?:gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre|january|february|march|april|may|june|july|august|september|october|november|december)"
57
+ reg_date = "(?:\d{1,2}\°{0,1}|primo|\d{1,2}\º{0,1})" + " " + reg_month + " " + "\d{4}|"
58
+ reg_date = reg_date + reg_month + " " + "\d{4}|"
59
+ reg_date = reg_date + "\d{1,2}" + " " + reg_month
60
+ reg_date = reg_date + "\d{1,2}" + "(?:\/|\.)\d{1,2}(?:\/|\.)" + "\d{4}|"
61
+ reg_date = reg_date + "(?<=dal )\d{4}|(?<=al )\d{4}|(?<=nel )\d{4}|(?<=anno )\d{4}|(?<=del )\d{4}|"
62
+ reg_date = reg_date + "\d{1,5} a\.c\.|\d{1,5} d\.c\."
63
+ map_punct = {"’": "'", "«": '"', "»": '"', "”": '"', "“": '"', "–": "-", "$": ""}
64
+ unk_tok = 9005
65
+
66
+ merge_th_1 = 0.8
67
+ merge_th_2 = 0.4
68
+ min_th = 0.55
69
+
70
+ def extract(text):
71
+
72
+ text = text.strip().lower()
73
+ text = re.sub("\[\d+\]", "", text)
74
+ for mp in map_punct:
75
+ text = text.replace(mp, map_punct[mp])
76
+ for p in string.punctuation:
77
+ text = text.replace(p, " " + p + " ")
78
+
79
+ warn_flag = False
80
+
81
+ res_total = []
82
+ out_text = ""
83
+
84
+ for p_text in text.split("\n"):
85
+
86
+ if p_text:
87
+
88
+ toks = tokenizer.encode(p_text)
89
+ if unk_tok in toks:
90
+ warn_flag = True
91
+
92
+ res_orig = ner(p_text, aggregation_strategy = "first")
93
+ res_orig = [el for r, el in enumerate(res_orig) if len(el["word"].strip()) > 1]
94
+ res = []
95
+
96
+ for r, ent in enumerate(res_orig):
97
+ if (r > 0 and ent["score"] < merge_th_1 and ent["start"] <= res[-1]["end"] + 1 and ent["score"] <= res[-1]["score"]) or (r > 0 and ent["entity_group"] == "LOC" and (re.findall(" di$| del$| dello$| della$| degli$| dei$", p_text[res[-1]["start"]:res[-1]["end"]].strip()) or re.findall("^di |^del |^dello |^della |^degli |^dei ", p_text[ent["start"]:ent["end"]].strip()))):
98
+ res[-1]["word"] = res[-1]["word"] + " " + ent["word"]
99
+ res[-1]["score"] = merge_th_1*(res[-1]["score"] > merge_th_2)
100
+ res[-1]["end"] = ent["end"]
101
+ elif r < len(res_orig) - 1 and ent["score"] < merge_th_1 and res_orig[r+1]["start"] <= ent["end"] + 1 and res_orig[r+1]["score"] > ent["score"]:
102
+ res_orig[r+1]["word"] = ent["word"] + " " + res_orig[r+1]["word"]
103
+ res_orig[r+1]["score"] = merge_th_1*(res_orig[r+1]["score"] > merge_th_2)
104
+ res_orig[r+1]["start"] = ent["start"]
105
+ else:
106
+ res.append(ent)
107
+
108
+ res = [el for r, el in enumerate(res) if el["score"] >= min_th]
109
+
110
+ dates = [{"entity_group": "DATE", "score": 1.0, "word": p_text[el.span()[0]:el.span()[1]], "start": el.span()[0], "end": el.span()[1]} for el in re.finditer(reg_date, p_text, flags = re.IGNORECASE)]
111
+ res.extend(dates)
112
+ res = sorted(res, key = lambda t: t["start"])
113
+ res_total.extend([p_text[el["start"]: el["end"]] for el in res if el["entity_group"] not in ['DATE', None]])
114
+
115
+ chunks = [("", "", 0, "NONE")]
116
+
117
+ for el in res:
118
+ if maps[el["entity_group"]] != "NONE":
119
+ tag = maps[el["entity_group"]]
120
+ chunks.append((p_text[el["start"]: el["end"]], p_text[chunks[-1][2]:el["end"]], el["end"], tag))
121
+
122
+ if chunks[-1][2] < len(p_text):
123
+ chunks.append(("END", p_text[chunks[-1][2]:], -1, "NONE"))
124
+ chunks = chunks[1:]
125
+
126
+ n_text = []
127
+
128
+ for i, chunk in enumerate(chunks):
129
+
130
+ rep = chunk[0]
131
+
132
+ if chunk[3] == "PER":
133
+ rep = ' <span style="background-color:lightgreen;border-radius: 3px;padding: 3px;"><b>ᴘᴇʀ</b> ' + chunk[0] + '</span>'
134
+ elif chunk[3] == "LOC":
135
+ rep = ' <span style="background-color:orange;border-radius: 3px;padding: 3px;"><b>ʟᴏᴄ</b> ' + chunk[0] + '</span>'
136
+ elif chunk[3] == "ORG":
137
+ rep = ' <span style="background-color:lightblue;border-radius: 3px;padding: 3px;"><b>ᴏʀɢ</b> ' + chunk[0] + '</span>'
138
+ elif chunk[3] == "MISC":
139
+ rep = ' <span style="background-color:tomato;border-radius: 3px;padding: 3px;"><b>ᴍɪsᴄ</b> ' + chunk[0] + '</span>'
140
+ elif chunk[3] == "DATE":
141
+ rep = ' <span style="background-color:lightgrey;border-radius: 3px;padding: 3px;"><b>ᴅᴀᴛᴇ</b> ' + chunk[0] + '</span>'
142
+
143
+ n_text.append(chunk[1].replace(chunk[0], rep))
144
+
145
+ n_text = "".join(n_text)
146
+ if out_text:
147
+ out_text = out_text + "<br>" + n_text
148
+ else:
149
+ out_text = n_text
150
+
151
+
152
+ out_text = out_text.replace(" ,", ",").replace(" .", ".").replace(" :", ":").replace(" ;", ";").replace(" ' ", "'").replace("( ", "(").replace(" )", ")").replace(" !", "!").replace(" ?", "?")
153
+ cnt = Counter(res_total)
154
+ tags = sorted(list(set([el for el in res_total if cnt[el] > 1])), key = lambda t: cnt[t]*np.exp(-res_total.index(t)))[::-1]
155
+ tags = [" ".join(re.sub("[^A-Za-z0-9\s]", "", unidecode(tag.replace("▁", " "))).split()) for tag in tags]
156
+ tags = ['<span style="background-color:#CF9FFF;border-radius: 3px;padding: 3px;"><b>ᴛᴀɢ </b> ' + el + '</span>' for el in tags]
157
+ tags = " ".join(tags)
158
+
159
+ if tags:
160
+ out_text = out_text + "<br><br><b>Tags:</b> " + tags
161
+
162
+ if warn_flag:
163
+ out_text = out_text + "<br><br><b>Warning ⚠️:</b> Unknown tokens detected in text. The model might behave erratically"
164
+
165
+ return out_text
166
+
167
+
168
+
169
+ init_text = '''L'Agenzia spaziale europea, nota internazionalmente con l'acronimo ESA dalla denominazione inglese European Space Agency, è un'agenzia internazionale fondata nel 1975 incaricata di coordinare i progetti spaziali di 22 Paesi europei. Il suo quartier generale si trova a Parigi in Francia, con uffici a Mosca, Bruxelles, Washington e Houston. Il personale dell'ESA del 2016 ammontava a 2 200 persone (esclusi sub-appaltatori e le agenzie nazionali) e il budget del 2022 è di 7,15 miliardi di euro. Attualmente il direttore generale dell'agenzia è l'austriaco Josef Aschbacher, il quale ha sostituito il tedesco Johann-Dietrich Wörner il primo marzo 2021.
170
+ Lo spazioporto dell'ESA è il Centre Spatial Guyanais a Kourou, nella Guyana francese, un sito scelto, come tutte le basi di lancio, per via della sua vicinanza con l'equatore. Durante gli ultimi anni il lanciatore Ariane 5 ha consentito all'ESA di raggiungere una posizione di primo piano nei lanci commerciali e l'ESA è il principale concorrente della NASA nell'esplorazione spaziale.
171
+ Le missioni scientifiche dell'ESA hanno le loro basi al Centro europeo per la ricerca e la tecnologia spaziale (ESTEC) di Noordwijk, nei Paesi Bassi. Il Centro europeo per le operazioni spaziali (ESOC), di Darmstadt in Germania, è responsabile del controllo dei satelliti dell'ESA in orbita. Le responsabilità del Centro europeo per l'osservazione della Terra (ESRIN) a Frascati, in Italia, includono la raccolta, l'archiviazione e la distribuzione di dati satellitari ai partner dell'ESA; oltre a ciò, la struttura agisce come centro di informazione tecnologica per l'intera agenzia. [...]
172
+ L'Agenzia Spaziale Italiana (ASI) venne fondata nel 1988 per promuovere, coordinare e condurre le attività spaziali in Italia. Opera in collaborazione con il Ministero dell'università e della ricerca scientifica e coopera in numerosi progetti con entità attive nella ricerca scientifica e nelle attività commerciali legate allo spazio. Internazionalmente l'ASI fornisce la delegazione italiana per l'Agenzia Spaziale Europea e le sue sussidiarie.'''
173
+
174
+ init_output = extract(init_text)
175
+
176
+
177
+
178
+
179
+ with gr.Blocks(css="footer {visibility: hidden}", theme=gr.themes.Default(text_size="lg", spacing_size="lg")) as interface:
180
+
181
+ with gr.Row():
182
+ gr.Markdown(header)
183
+ with gr.Row():
184
+ text = gr.Text(label="Extract entities", lines = 10, value = init_text)
185
+ with gr.Row():
186
+ with gr.Column():
187
+ button = gr.Button("Extract").style(full_width=False)
188
+ with gr.Row():
189
+ with gr.Column():
190
+ entities = gr.Markdown(init_output)
191
+
192
+ with gr.Row():
193
+ with gr.Column():
194
+ gr.Markdown("<center>The input examples in this demo are extracted from https://it.wikipedia.org</center>")
195
+
196
+ button.click(extract, inputs=[text], outputs = [entities])
197
+
198
+
199
+ interface.launch()