Spaces:
Runtime error
Runtime error
mvy
commited on
Commit
•
10b2302
1
Parent(s):
58e3f16
refactor
Browse files
app.py
CHANGED
@@ -21,9 +21,15 @@ examples = [
|
|
21 |
],
|
22 |
]
|
23 |
|
|
|
|
|
24 |
gradio_app = gr.Interface(
|
25 |
-
|
26 |
-
inputs = [
|
|
|
|
|
|
|
|
|
27 |
outputs = [gr.HighlightedText()],
|
28 |
examples=examples,
|
29 |
theme="huggingface",
|
|
|
21 |
],
|
22 |
]
|
23 |
|
24 |
+
ner = NER('knowledgator/UTC-DeBERTa-small')
|
25 |
+
|
26 |
gradio_app = gr.Interface(
|
27 |
+
ner,
|
28 |
+
inputs = [
|
29 |
+
'text',
|
30 |
+
gr.Textbox(placeholder="Enter sentence here..."),
|
31 |
+
gr.Number(value=0.0, label="threshold")
|
32 |
+
],
|
33 |
outputs = [gr.HighlightedText()],
|
34 |
examples=examples,
|
35 |
theme="huggingface",
|
ner.py
CHANGED
@@ -1,78 +1,130 @@
|
|
|
|
|
|
|
|
1 |
from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
|
2 |
import spacy
|
3 |
import torch
|
4 |
|
5 |
-
nlp = spacy.load('en_core_web_sm', disable = ['lemmatizer', 'parser', 'tagger', 'ner'])
|
6 |
-
nlp.add_pipe('sentencizer')
|
7 |
-
|
8 |
-
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
9 |
-
|
10 |
-
|
11 |
class NER:
|
12 |
-
|
13 |
-
prompt="""
|
14 |
Identify entities in the text having the following classes:
|
15 |
{}
|
16 |
|
17 |
Text:
|
18 |
-
"""
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
def
|
32 |
-
|
|
|
|
|
|
|
|
|
33 |
chunks = []
|
34 |
starts = []
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
chunk_text = prompt_+text[start:end]
|
46 |
-
chunks.append(chunk_text)
|
47 |
-
proc = False
|
48 |
-
if proc:
|
49 |
-
chunk_text = prompt_+text[start:end]
|
50 |
-
chunks.append(chunk_text)
|
51 |
return chunks, starts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
|
54 |
@classmethod
|
55 |
-
def
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
outputs = []
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
for ent in output:
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
return {"text": text, "entities": outputs}
|
|
|
1 |
+
from typing import Tuple
|
2 |
+
import string
|
3 |
+
|
4 |
from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
|
5 |
import spacy
|
6 |
import torch
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
class NER:
|
9 |
+
prompt: str = """
|
|
|
10 |
Identify entities in the text having the following classes:
|
11 |
{}
|
12 |
|
13 |
Text:
|
14 |
+
"""
|
15 |
+
|
16 |
+
def __init__(self, model_name: str, sents_batch: int=10):
|
17 |
+
self.sents_batch = sents_batch
|
18 |
+
|
19 |
+
self.nlp: spacy.Language = spacy.load(
|
20 |
+
'en_core_web_sm',
|
21 |
+
disable = ['lemmatizer', 'parser', 'tagger', 'ner']
|
22 |
+
)
|
23 |
+
self.nlp.add_pipe('sentencizer')
|
24 |
+
|
25 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
27 |
+
model = AutoModelForTokenClassification.from_pretrained(model_name)
|
28 |
+
|
29 |
+
self.pipeline = pipeline(
|
30 |
+
"ner",
|
31 |
+
model=model,
|
32 |
+
tokenizer=tokenizer,
|
33 |
+
aggregation_strategy='first',
|
34 |
+
batch_size=12,
|
35 |
+
device=device
|
36 |
+
)
|
37 |
|
38 |
+
|
39 |
+
def get_last_sentence_id(self, i: int, sentences_len: int) -> int:
|
40 |
+
return min(i + self.sents_batch, sentences_len) - 1
|
41 |
+
|
42 |
+
|
43 |
+
def chunkanize(self, text: str) -> Tuple[list[str], list[int]]:
|
44 |
+
doc = self.nlp(text)
|
45 |
chunks = []
|
46 |
starts = []
|
47 |
+
sentences = list(doc.sents)
|
48 |
+
|
49 |
+
for i in range(0, len(sentences), self.sents_batch):
|
50 |
+
start = sentences[i].start_char
|
51 |
+
starts.append(start)
|
52 |
+
|
53 |
+
last_sentence = self.get_last_sentence_id(i, len(sentences))
|
54 |
+
end = sentences[last_sentence].end_char
|
55 |
+
|
56 |
+
chunks.append(text[start:end])
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
return chunks, starts
|
58 |
+
|
59 |
+
|
60 |
+
def get_inputs(
|
61 |
+
self, chunks: list[str], labels: list[str]
|
62 |
+
) -> Tuple[list[str], list[int]]:
|
63 |
+
inputs = []
|
64 |
+
prompts_lens = []
|
65 |
+
|
66 |
+
for label in labels:
|
67 |
+
prompt = self.prompt.format(label)
|
68 |
+
prompts_lens.append(len(prompt))
|
69 |
+
for chunk in chunks:
|
70 |
+
inputs.append(prompt + chunk)
|
71 |
+
|
72 |
+
return inputs, prompts_lens
|
73 |
|
74 |
|
75 |
@classmethod
|
76 |
+
def clean_span(
|
77 |
+
cls, start: int, end: int, span: str
|
78 |
+
) -> Tuple[int, int, str]:
|
79 |
+
if len(span) >= 1:
|
80 |
+
if span[0] in string.punctuation:
|
81 |
+
return cls.clean_span(start+1, end, span[1:])
|
82 |
+
if span[-1] in string.punctuation:
|
83 |
+
return cls.clean_span(start, end-1, span[:-1])
|
84 |
+
return start, end, span.strip()
|
85 |
+
|
86 |
+
|
87 |
+
def predict(
|
88 |
+
self,
|
89 |
+
text: str,
|
90 |
+
inputs: list[str],
|
91 |
+
labels: list[str],
|
92 |
+
chunks_starts: list[int],
|
93 |
+
prompts_lens: list[int],
|
94 |
+
threshold: float
|
95 |
+
) -> list[dict[str, any]]:
|
96 |
outputs = []
|
97 |
+
|
98 |
+
for id, output in enumerate(self.pipeline(inputs)):
|
99 |
+
label = labels[id//len(chunks_starts)]
|
100 |
+
shift = chunks_starts[id%len(chunks_starts)] - prompts_lens[id//len(chunks_starts)]
|
101 |
for ent in output:
|
102 |
+
start = ent['start'] + shift + 1
|
103 |
+
end = ent['end'] + shift
|
104 |
+
start, end, span = self.clean_span(start, end, text[start:end])
|
105 |
+
if not span:
|
106 |
+
continue
|
107 |
+
|
108 |
+
if ent['score'] >= threshold:
|
109 |
+
outputs.append({
|
110 |
+
'span': span,
|
111 |
+
'start': start,
|
112 |
+
'end': end,
|
113 |
+
'entity': label
|
114 |
+
})
|
115 |
+
return outputs
|
116 |
+
|
117 |
+
|
118 |
+
def __call__(
|
119 |
+
self, labels: str, text: str, threshold: float=0.
|
120 |
+
) -> dict[str, any]:
|
121 |
+
labels_list = [label.strip() for label in labels.split(',')]
|
122 |
+
|
123 |
+
chunks, chunks_starts = self.chunkanize(text)
|
124 |
+
inputs, prompts_lens = self.get_inputs(chunks, labels_list)
|
125 |
+
|
126 |
+
outputs = self.predict(
|
127 |
+
text, inputs, labels_list, chunks_starts, prompts_lens, threshold
|
128 |
+
)
|
129 |
+
print(outputs)
|
130 |
return {"text": text, "entities": outputs}
|