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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 DistilBertForTokenClassification
|
| 18 |
+
from collections import Counter
|
| 19 |
+
from unidecode import unidecode
|
| 20 |
+
import string
|
| 21 |
+
import re
|
| 22 |
+
|
| 23 |
+
auth_token = os.environ.get("NEXT_IT_TOKEN")
|
| 24 |
+
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained("osiria/blaze-it-ner", use_auth_token=auth_token)
|
| 26 |
+
model = DistilBertForTokenClassification.from_pretrained("osiria/blaze-it-ner", num_labels = 5, use_auth_token=auth_token)
|
| 27 |
+
device = torch.device("cpu")
|
| 28 |
+
model = model.to(device)
|
| 29 |
+
model.eval()
|
| 30 |
+
|
| 31 |
+
from transformers import pipeline
|
| 32 |
+
ner = pipeline('ner', model=model, tokenizer=tokenizer, device=-1)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
header = '''--------------------------------------------------------------------------------------------------
|
| 36 |
+
|
| 37 |
+
<style>
|
| 38 |
+
.vertical-text {
|
| 39 |
+
writing-mode: vertical-lr;
|
| 40 |
+
text-orientation: upright;
|
| 41 |
+
background-color:red;
|
| 42 |
+
}
|
| 43 |
+
</style>
|
| 44 |
+
<center>
|
| 45 |
+
<body>
|
| 46 |
+
<span class="vertical-text" style="background-color:lightgreen;border-radius: 3px;padding: 3px;"> </span>
|
| 47 |
+
<span class="vertical-text" style="background-color:orange;border-radius: 3px;padding: 3px;"> D</span>
|
| 48 |
+
<span class="vertical-text" style="background-color:lightblue;border-radius: 3px;padding: 3px;"> E</span>
|
| 49 |
+
<span class="vertical-text" style="background-color:tomato;border-radius: 3px;padding: 3px;"> M</span>
|
| 50 |
+
<span class="vertical-text" style="background-color:lightgrey;border-radius: 3px;padding: 3px;"> O</span>
|
| 51 |
+
<span class="vertical-text" style="background-color:#CF9FFF;border-radius: 3px;padding: 3px;"> </span>
|
| 52 |
+
</body>
|
| 53 |
+
</center>
|
| 54 |
+
<br>
|
| 55 |
+
<center>(BETA)</center>
|
| 56 |
+
|
| 57 |
+
--------------------------------------------------------------------------------------------------'''
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
paragraph = '''<b>What's BLAZE-IT?</b>
|
| 61 |
+
|
| 62 |
+
This app is a demo of [BLAZE-IT](https://huggingface.co/osiria/blaze-it), a <b>lightweight</b> and <b>uncased</b> italian language model (<b>55M parameters</b> and <b>220MB</b> size). The model is here fine-tuned for named entity recognition on WikiNER (cross-validated F1 score of 89.53%) plus a custom, hand-crafted dataset of 3.500 manually annotated Wikipedia paragraphs.
|
| 63 |
+
|
| 64 |
+
This system is a beta version, and will improve over time. It can recognize entities of the following types (in order to make the most of the color-coding, it is recommended to use the light theme for the interface):
|
| 65 |
+
|
| 66 |
+
- <span style="background-color:lightgreen;border-radius: 3px;padding: 3px;"><b>ᴘᴇʀ</b> person</span>: names of persons
|
| 67 |
+
- <span style="background-color:orange;border-radius: 3px;padding: 3px;"><b>ʟᴏᴄ</b> location</span>: names of places
|
| 68 |
+
- <span style="background-color:lightblue;border-radius: 3px;padding: 3px;"><b>ᴏʀɢ</b> organization</span>: names of organizations
|
| 69 |
+
- <span style="background-color:tomato;border-radius: 3px;padding: 3px;"><b>ᴍɪsᴄ</b> miscellanea</span>: mixed type entities
|
| 70 |
+
- <span style="background-color:lightgrey;border-radius: 3px;padding: 3px;"><b>ᴅᴀᴛᴇ</b> date</span>: regex-based dates
|
| 71 |
+
- <span style="background-color:#CF9FFF;border-radius: 3px;padding: 3px;"><b>ᴛᴀɢ</b> tag</span>: most relevant entities, of any type
|
| 72 |
+
|
| 73 |
+
The <b>ᴍɪsᴄ</b> class has mixed nature, and it mainly covers names of events or products. Occasionally, entities of other classes might be labeled as <b>ᴍɪsᴄ</b> if the model is not confident enough about their identification.
|
| 74 |
+
|
| 75 |
+
The execution time in this app depends on the availability of the underlying cloud instance, and is not a reflection of the model inference time.
|
| 76 |
+
If unknown tokens are present in the text, they will interfere with the prediction, and the model may behave erratically. In that case, a warning sign will be displayed.
|
| 77 |
+
'''
|
| 78 |
+
|
| 79 |
+
maps = {"O": "NONE", "PER": "PER", "LOC": "LOC", "ORG": "ORG", "MISC": "MISC", "DATE": "DATE"}
|
| 80 |
+
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)"
|
| 81 |
+
reg_date = "(?:\d{1,2}\°{0,1}|primo|\d{1,2}\º{0,1})" + " " + reg_month + " " + "\d{4}|"
|
| 82 |
+
reg_date = reg_date + reg_month + " " + "\d{4}|"
|
| 83 |
+
reg_date = reg_date + "\d{1,2}" + " " + reg_month
|
| 84 |
+
reg_date = reg_date + "\d{1,2}" + "(?:\/|\.)\d{1,2}(?:\/|\.)" + "\d{4}|"
|
| 85 |
+
reg_date = reg_date + "(?<=dal )\d{4}|(?<=al )\d{4}|(?<=nel )\d{4}|(?<=anno )\d{4}|(?<=del )\d{4}|"
|
| 86 |
+
reg_date = reg_date + "\d{1,5} a\.c\.|\d{1,5} d\.c\."
|
| 87 |
+
map_punct = {"’": "'", "«": '"', "»": '"', "”": '"', "“": '"', "–": "-", "$": ""}
|
| 88 |
+
unk_tok = 9005
|
| 89 |
+
|
| 90 |
+
merge_th_1 = 0.8
|
| 91 |
+
merge_th_2 = 0.4
|
| 92 |
+
min_th = 0.6
|
| 93 |
+
|
| 94 |
+
def extract(text):
|
| 95 |
+
|
| 96 |
+
text = text.strip()
|
| 97 |
+
for mp in map_punct:
|
| 98 |
+
text = text.replace(mp, map_punct[mp])
|
| 99 |
+
text = re.sub("\[\d+\]", "", text)
|
| 100 |
+
|
| 101 |
+
warn_flag = False
|
| 102 |
+
|
| 103 |
+
res_total = []
|
| 104 |
+
out_text = ""
|
| 105 |
+
|
| 106 |
+
for p_text in text.split("\n"):
|
| 107 |
+
|
| 108 |
+
if p_text:
|
| 109 |
+
|
| 110 |
+
toks = tokenizer.encode(p_text)
|
| 111 |
+
if unk_tok in toks:
|
| 112 |
+
warn_flag = True
|
| 113 |
+
|
| 114 |
+
res_orig = ner(p_text, aggregation_strategy = "first")
|
| 115 |
+
res_orig = [el for r, el in enumerate(res_orig) if len(el["word"].strip()) > 1]
|
| 116 |
+
res = []
|
| 117 |
+
|
| 118 |
+
for r, ent in enumerate(res_orig):
|
| 119 |
+
if r > 0 and ent["score"] < merge_th_1 and ent["start"] <= res[-1]["end"] + 1 and ent["score"] <= res[-1]["score"]:
|
| 120 |
+
res[-1]["word"] = res[-1]["word"] + " " + ent["word"]
|
| 121 |
+
res[-1]["score"] = merge_th_1*(res[-1]["score"] > merge_th_2)
|
| 122 |
+
res[-1]["end"] = ent["end"]
|
| 123 |
+
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"]:
|
| 124 |
+
res_orig[r+1]["word"] = ent["word"] + " " + res_orig[r+1]["word"]
|
| 125 |
+
res_orig[r+1]["score"] = merge_th_1*(res_orig[r+1]["score"] > merge_th_2)
|
| 126 |
+
res_orig[r+1]["start"] = ent["start"]
|
| 127 |
+
else:
|
| 128 |
+
res.append(ent)
|
| 129 |
+
|
| 130 |
+
res = [el for r, el in enumerate(res) if el["score"] >= min_th]
|
| 131 |
+
|
| 132 |
+
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)]
|
| 133 |
+
res.extend(dates)
|
| 134 |
+
res = sorted(res, key = lambda t: t["start"])
|
| 135 |
+
res_total.extend(res)
|
| 136 |
+
|
| 137 |
+
chunks = [("", "", 0, "NONE")]
|
| 138 |
+
|
| 139 |
+
for el in res:
|
| 140 |
+
if maps[el["entity_group"]] != "NONE":
|
| 141 |
+
tag = maps[el["entity_group"]]
|
| 142 |
+
chunks.append((p_text[el["start"]: el["end"]], p_text[chunks[-1][2]:el["end"]], el["end"], tag))
|
| 143 |
+
|
| 144 |
+
if chunks[-1][2] < len(p_text):
|
| 145 |
+
chunks.append(("END", p_text[chunks[-1][2]:], -1, "NONE"))
|
| 146 |
+
chunks = chunks[1:]
|
| 147 |
+
|
| 148 |
+
n_text = []
|
| 149 |
+
|
| 150 |
+
for i, chunk in enumerate(chunks):
|
| 151 |
+
|
| 152 |
+
rep = chunk[0]
|
| 153 |
+
|
| 154 |
+
if chunk[3] == "PER":
|
| 155 |
+
rep = '<span style="background-color:lightgreen;border-radius: 3px;padding: 3px;"><b>ᴘᴇʀ</b> ' + chunk[0] + '</span>'
|
| 156 |
+
elif chunk[3] == "LOC":
|
| 157 |
+
rep = '<span style="background-color:orange;border-radius: 3px;padding: 3px;"><b>ʟᴏᴄ</b> ' + chunk[0] + '</span>'
|
| 158 |
+
elif chunk[3] == "ORG":
|
| 159 |
+
rep = '<span style="background-color:lightblue;border-radius: 3px;padding: 3px;"><b>ᴏʀɢ</b> ' + chunk[0] + '</span>'
|
| 160 |
+
elif chunk[3] == "MISC":
|
| 161 |
+
rep = '<span style="background-color:tomato;border-radius: 3px;padding: 3px;"><b>ᴍɪsᴄ</b> ' + chunk[0] + '</span>'
|
| 162 |
+
elif chunk[3] == "DATE":
|
| 163 |
+
rep = '<span style="background-color:lightgrey;border-radius: 3px;padding: 3px;"><b>ᴅᴀᴛᴇ</b> ' + chunk[0] + '</span>'
|
| 164 |
+
|
| 165 |
+
n_text.append(chunk[1].replace(chunk[0], rep))
|
| 166 |
+
|
| 167 |
+
n_text = "".join(n_text)
|
| 168 |
+
if out_text:
|
| 169 |
+
out_text = out_text + "<br>" + n_text
|
| 170 |
+
else:
|
| 171 |
+
out_text = n_text
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
tags = [el["word"] for el in res_total if el["entity_group"] not in ['DATE', None]]
|
| 175 |
+
cnt = Counter(tags)
|
| 176 |
+
tags = sorted(list(set([el for el in tags if cnt[el] > 1])), key = lambda t: cnt[t]*np.exp(-tags.index(t)))[::-1]
|
| 177 |
+
tags = [" ".join(re.sub("[^A-Za-z0-9\s]", "", unidecode(tag)).split()) for tag in tags]
|
| 178 |
+
tags = ['<span style="background-color:#CF9FFF;border-radius: 3px;padding: 3px;"><b>ᴛᴀɢ </b> ' + el + '</span>' for el in tags]
|
| 179 |
+
tags = " ".join(tags)
|
| 180 |
+
|
| 181 |
+
if tags:
|
| 182 |
+
out_text = out_text + "<br><br><b>Tags:</b> " + tags
|
| 183 |
+
|
| 184 |
+
if warn_flag:
|
| 185 |
+
out_text = out_text + "<br><br><b>Warning ⚠️:</b> Unknown tokens detected in text. The model might behave erratically"
|
| 186 |
+
|
| 187 |
+
return out_text
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
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.
|
| 192 |
+
attualmente il direttore generale dell'agenzia è l'austriaco josef aschbacher, il quale ha sostituito il tedesco johann-dietrich wörner il primo marzo 2021.
|
| 193 |
+
|
| 194 |
+
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.
|
| 195 |
+
|
| 196 |
+
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 esa in orbita. [...]
|
| 197 |
+
|
| 198 |
+
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.'''
|
| 199 |
+
|
| 200 |
+
init_output = extract(init_text)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
with gr.Blocks() as interface:
|
| 206 |
+
|
| 207 |
+
with gr.Row():
|
| 208 |
+
gr.Markdown(header)
|
| 209 |
+
with gr.Row():
|
| 210 |
+
with gr.Column():
|
| 211 |
+
gr.Markdown(paragraph)
|
| 212 |
+
with gr.Column():
|
| 213 |
+
incipit = gr.Markdown("<b>Highlighted entities<b>")
|
| 214 |
+
entities = gr.Markdown(init_output)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
with gr.Row():
|
| 218 |
+
with gr.Column():
|
| 219 |
+
text = gr.Text(label="Extract entities", lines = 10, value = init_text)
|
| 220 |
+
with gr.Column():
|
| 221 |
+
gr.Examples([["aristotele nacque nel 384 a.c. o nel 383 a.c. a stagira, l'attuale stavro, colonia greca situata nella parte nord-orientale della penisola calcidica della tracia. si dice che il padre, nicomaco, sia vissuto presso aminta iii, re dei macedoni, prestandogli i servigi di medico e di amico. aristotele, come figlio del medico reale, doveva pertanto risiedere nella capitale del regno di macedonia"],
|
| 222 |
+
["mi chiamo edoardo, vivo a roma e lavoro per l'agenzia spaziale italiana, nella missione prisma"],
|
| 223 |
+
["wikipedia è un'enciclopedia online a contenuto libero, collaborativa, multilingue e gratuita, nata nel 2001, sostenuta e ospitata dalla wikimedia foundation, un'organizzazione non a scopo di lucro statunitense. lanciata da jimmy wales e larry sanger il 15 gennaio 2001, inizialmente nell'edizione in lingua inglese, nei mesi successivi ha aggiunto edizioni in numerose altre lingue"]],
|
| 224 |
+
inputs=[text])
|
| 225 |
+
with gr.Row():
|
| 226 |
+
button = gr.Button("Extract").style(full_width=False)
|
| 227 |
+
|
| 228 |
+
with gr.Row():
|
| 229 |
+
with gr.Column():
|
| 230 |
+
gr.Markdown("<center>The input examples in this demo are extracted from https://it.wikipedia.org</center>")
|
| 231 |
+
|
| 232 |
+
button.click(extract, inputs=[text], outputs = [entities])
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
interface.launch()
|