Spaces:
Running
Running
KarishmaShirsath
commited on
Commit
•
8850a9d
1
Parent(s):
b0ba6f1
Upload 5 files
Browse files- DejaVuSans.ttf +0 -0
- Final_file.py +699 -0
- app.py +128 -0
- conlleval.py +235 -0
- requirements.txt +0 -0
DejaVuSans.ttf
ADDED
Binary file (757 kB). View file
|
|
Final_file.py
ADDED
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
7 |
+
# get_ipython().system('pip3 install datasets')
|
8 |
+
# get_ipython().system('wget https://raw.githubusercontent.com/sighsmile/conlleval/master/conlleval.py')
|
9 |
+
|
10 |
+
import requests
|
11 |
+
|
12 |
+
url = "https://raw.githubusercontent.com/sighsmile/conlleval/master/conlleval.py"
|
13 |
+
response = requests.get(url)
|
14 |
+
|
15 |
+
with open("conlleval.py", "wb") as f:
|
16 |
+
f.write(response.content)
|
17 |
+
|
18 |
+
# In[36]:
|
19 |
+
|
20 |
+
|
21 |
+
# get_ipython().system('pip install presidio-analyzer')
|
22 |
+
|
23 |
+
|
24 |
+
# In[38]:
|
25 |
+
|
26 |
+
|
27 |
+
# get_ipython().system('pip install flair')
|
28 |
+
|
29 |
+
|
30 |
+
# In[19]:
|
31 |
+
|
32 |
+
|
33 |
+
import os
|
34 |
+
|
35 |
+
os.environ["KERAS_BACKEND"] = "tensorflow"
|
36 |
+
import streamlit as st
|
37 |
+
import os
|
38 |
+
import keras
|
39 |
+
import numpy as np
|
40 |
+
import tensorflow as tf
|
41 |
+
from keras import layers
|
42 |
+
from datasets import load_dataset
|
43 |
+
from collections import Counter
|
44 |
+
from conlleval import evaluate
|
45 |
+
|
46 |
+
import pandas as pd
|
47 |
+
# from google.colab import files
|
48 |
+
import matplotlib.pyplot as plt
|
49 |
+
|
50 |
+
from transformers import AutoModel, AutoTokenizer
|
51 |
+
|
52 |
+
import logging
|
53 |
+
from typing import Optional, List, Tuple, Set
|
54 |
+
from presidio_analyzer import (
|
55 |
+
RecognizerResult,
|
56 |
+
EntityRecognizer,
|
57 |
+
AnalysisExplanation,
|
58 |
+
)
|
59 |
+
from presidio_analyzer.nlp_engine import NlpArtifacts
|
60 |
+
|
61 |
+
from flair.data import Sentence
|
62 |
+
from flair.models import SequenceTagger
|
63 |
+
import tempfile
|
64 |
+
|
65 |
+
# In[4]:
|
66 |
+
|
67 |
+
|
68 |
+
class TransformerBlock(layers.Layer):
|
69 |
+
def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
|
70 |
+
super().__init__()
|
71 |
+
self.att = keras.layers.MultiHeadAttention(
|
72 |
+
num_heads=num_heads, key_dim=embed_dim
|
73 |
+
)
|
74 |
+
self.ffn = keras.Sequential(
|
75 |
+
[
|
76 |
+
keras.layers.Dense(ff_dim, activation="relu"),
|
77 |
+
keras.layers.Dense(embed_dim),
|
78 |
+
]
|
79 |
+
)
|
80 |
+
self.layernorm1 = keras.layers.LayerNormalization(epsilon=1e-6)
|
81 |
+
self.layernorm2 = keras.layers.LayerNormalization(epsilon=1e-6)
|
82 |
+
self.dropout1 = keras.layers.Dropout(rate)
|
83 |
+
self.dropout2 = keras.layers.Dropout(rate)
|
84 |
+
|
85 |
+
def call(self, inputs, training=False):
|
86 |
+
attn_output = self.att(inputs, inputs)
|
87 |
+
attn_output = self.dropout1(attn_output, training=training)
|
88 |
+
out1 = self.layernorm1(inputs + attn_output)
|
89 |
+
ffn_output = self.ffn(out1)
|
90 |
+
ffn_output = self.dropout2(ffn_output, training=training)
|
91 |
+
return self.layernorm2(out1 + ffn_output)
|
92 |
+
|
93 |
+
|
94 |
+
# In[5]:
|
95 |
+
|
96 |
+
|
97 |
+
class TokenAndPositionEmbedding(layers.Layer):
|
98 |
+
def __init__(self, maxlen, vocab_size, embed_dim):
|
99 |
+
super().__init__()
|
100 |
+
self.token_emb = keras.layers.Embedding(
|
101 |
+
input_dim=vocab_size, output_dim=embed_dim
|
102 |
+
)
|
103 |
+
self.pos_emb = keras.layers.Embedding(input_dim=maxlen, output_dim=embed_dim)
|
104 |
+
|
105 |
+
def call(self, inputs):
|
106 |
+
maxlen = tf.shape(inputs)[-1]
|
107 |
+
positions = tf.range(start=0, limit=maxlen, delta=1)
|
108 |
+
position_embeddings = self.pos_emb(positions)
|
109 |
+
token_embeddings = self.token_emb(inputs)
|
110 |
+
return token_embeddings + position_embeddings
|
111 |
+
|
112 |
+
|
113 |
+
# In[6]:
|
114 |
+
|
115 |
+
|
116 |
+
class NERModel(keras.Model):
|
117 |
+
def __init__(
|
118 |
+
self, num_tags, vocab_size, maxlen=128, embed_dim=32, num_heads=2, ff_dim=32
|
119 |
+
):
|
120 |
+
super().__init__()
|
121 |
+
self.embedding_layer = TokenAndPositionEmbedding(maxlen, vocab_size, embed_dim)
|
122 |
+
self.transformer_block = TransformerBlock(embed_dim, num_heads, ff_dim)
|
123 |
+
self.dropout1 = layers.Dropout(0.1)
|
124 |
+
self.ff = layers.Dense(ff_dim, activation="relu")
|
125 |
+
self.dropout2 = layers.Dropout(0.1)
|
126 |
+
self.ff_final = layers.Dense(num_tags, activation="softmax")
|
127 |
+
|
128 |
+
def call(self, inputs, training=False):
|
129 |
+
x = self.embedding_layer(inputs)
|
130 |
+
x = self.transformer_block(x)
|
131 |
+
x = self.dropout1(x, training=training)
|
132 |
+
x = self.ff(x)
|
133 |
+
x = self.dropout2(x, training=training)
|
134 |
+
x = self.ff_final(x)
|
135 |
+
return x
|
136 |
+
|
137 |
+
|
138 |
+
# In[7]:
|
139 |
+
|
140 |
+
@st.cache_data
|
141 |
+
def load_data(dataset):
|
142 |
+
return load_dataset("conll2003")
|
143 |
+
|
144 |
+
conll_data = load_data("conll2003")
|
145 |
+
|
146 |
+
|
147 |
+
# In[8]:
|
148 |
+
|
149 |
+
|
150 |
+
def dataset_to_dataframe(dataset):
|
151 |
+
data_dict = {key: dataset[key] for key in dataset.features}
|
152 |
+
return pd.DataFrame(data_dict)
|
153 |
+
|
154 |
+
# Combine all splits (train, validation, test) into a single DataFrame
|
155 |
+
conll_df = pd.concat([dataset_to_dataframe(conll_data[split]) for split in conll_data.keys()])
|
156 |
+
|
157 |
+
|
158 |
+
# In[7]:
|
159 |
+
|
160 |
+
|
161 |
+
csv_file_path = "conll_data.csv"
|
162 |
+
# conll_df.to_csv(csv_file_path, index=False)
|
163 |
+
|
164 |
+
# Download the CSV file to local machine
|
165 |
+
|
166 |
+
# files.download(csv_file_path)
|
167 |
+
|
168 |
+
|
169 |
+
#*****************************My code********************
|
170 |
+
|
171 |
+
# Create a temporary file to save the CSV data
|
172 |
+
|
173 |
+
|
174 |
+
# Function to download the CSV file
|
175 |
+
@st.cache_data(experimental_allow_widgets=True)
|
176 |
+
def download_csv(csv_file_path):
|
177 |
+
with open(csv_file_path, 'rb') as file:
|
178 |
+
data = file.read()
|
179 |
+
# Wrap the download button inside a div with style="display: none;"
|
180 |
+
st.markdown("<div style='display: None;'>", unsafe_allow_html=True)
|
181 |
+
st.download_button(label="Download CSV", data=data, file_name='data.csv', mime='text/csv')
|
182 |
+
st.markdown("</div>", unsafe_allow_html=True)
|
183 |
+
|
184 |
+
|
185 |
+
|
186 |
+
# Create a temporary file to save the CSV data
|
187 |
+
temp_file = tempfile.NamedTemporaryFile(prefix= csv_file_path,delete=False)
|
188 |
+
temp_file_path = temp_file.name
|
189 |
+
conll_df.to_csv(temp_file_path, index=False)
|
190 |
+
temp_file.close()
|
191 |
+
|
192 |
+
# Trigger the download automatically when the app starts
|
193 |
+
download_csv(temp_file_path)
|
194 |
+
st.markdown("<div style='display: none;'>Hidden download button</div>", unsafe_allow_html=True)
|
195 |
+
|
196 |
+
|
197 |
+
#**************************MY code *********************************
|
198 |
+
|
199 |
+
# In[8]:
|
200 |
+
|
201 |
+
|
202 |
+
# print(conll_df.head())
|
203 |
+
|
204 |
+
|
205 |
+
# In[10]:
|
206 |
+
|
207 |
+
|
208 |
+
# print(conll_df.describe())
|
209 |
+
|
210 |
+
|
211 |
+
# In[11]:
|
212 |
+
|
213 |
+
|
214 |
+
# print(conll_df.dtypes)
|
215 |
+
|
216 |
+
|
217 |
+
# In[12]:
|
218 |
+
|
219 |
+
|
220 |
+
# print(conll_df.isnull().sum())
|
221 |
+
|
222 |
+
|
223 |
+
# In[13]:
|
224 |
+
|
225 |
+
|
226 |
+
label_counts = conll_df['ner_tags'].value_counts()
|
227 |
+
print(label_counts)
|
228 |
+
|
229 |
+
|
230 |
+
# In[14]:
|
231 |
+
|
232 |
+
|
233 |
+
top_10_labels = label_counts.head(10)
|
234 |
+
|
235 |
+
# Plot the distribution of the top 10 NER tags
|
236 |
+
# plt.figure(figsize=(10, 6))
|
237 |
+
# top_10_labels.plot(kind='bar')
|
238 |
+
# plt.title('Top 10 Most Common NER Tags')
|
239 |
+
# plt.xlabel('NER Tag')
|
240 |
+
# plt.ylabel('Count')
|
241 |
+
# plt.show()
|
242 |
+
|
243 |
+
|
244 |
+
# In[9]:
|
245 |
+
|
246 |
+
@st.cache_resource
|
247 |
+
def export_to_file(export_file_path, _data):
|
248 |
+
with open(export_file_path, "w") as f:
|
249 |
+
for record in _data:
|
250 |
+
ner_tags = record["ner_tags"]
|
251 |
+
tokens = record["tokens"]
|
252 |
+
if len(tokens) > 0:
|
253 |
+
f.write(
|
254 |
+
str(len(tokens))
|
255 |
+
+ "\t"
|
256 |
+
+ "\t".join(tokens)
|
257 |
+
+ "\t"
|
258 |
+
+ "\t".join(map(str, ner_tags))
|
259 |
+
+ "\n"
|
260 |
+
)
|
261 |
+
|
262 |
+
|
263 |
+
os.makedirs("data", exist_ok=True)
|
264 |
+
export_to_file("./data/conll_train.txt", conll_data["train"])
|
265 |
+
export_to_file("./data/conll_val.txt", conll_data["validation"])
|
266 |
+
|
267 |
+
|
268 |
+
# In[10]:
|
269 |
+
|
270 |
+
|
271 |
+
def make_tag_lookup_table():
|
272 |
+
iob_labels = ["B", "I"]
|
273 |
+
ner_labels = ["PER", "ORG", "LOC", "MISC"]
|
274 |
+
all_labels = [(label1, label2) for label2 in ner_labels for label1 in iob_labels]
|
275 |
+
all_labels = ["-".join([a, b]) for a, b in all_labels]
|
276 |
+
all_labels = ["[PAD]", "O"] + all_labels
|
277 |
+
return dict(zip(range(0, len(all_labels) + 1), all_labels))
|
278 |
+
|
279 |
+
|
280 |
+
mapping = make_tag_lookup_table()
|
281 |
+
print(mapping)
|
282 |
+
|
283 |
+
|
284 |
+
# In[11]:
|
285 |
+
|
286 |
+
|
287 |
+
all_tokens = sum(conll_data["train"]["tokens"], [])
|
288 |
+
all_tokens_array = np.array(list(map(str.lower, all_tokens)))
|
289 |
+
|
290 |
+
counter = Counter(all_tokens_array)
|
291 |
+
# print(len(counter))
|
292 |
+
|
293 |
+
num_tags = len(mapping)
|
294 |
+
vocab_size = 20000
|
295 |
+
|
296 |
+
# We only take (vocab_size - 2) most commons words from the training data since
|
297 |
+
# the `StringLookup` class uses 2 additional tokens - one denoting an unknown
|
298 |
+
# token and another one denoting a masking token
|
299 |
+
vocabulary = [token for token, count in counter.most_common(vocab_size - 2)]
|
300 |
+
|
301 |
+
# The StringLook class will convert tokens to token IDs
|
302 |
+
lookup_layer = keras.layers.StringLookup(vocabulary=vocabulary)
|
303 |
+
|
304 |
+
|
305 |
+
# In[12]:
|
306 |
+
|
307 |
+
|
308 |
+
train_data = tf.data.TextLineDataset("./data/conll_train.txt")
|
309 |
+
val_data = tf.data.TextLineDataset("./data/conll_val.txt")
|
310 |
+
|
311 |
+
|
312 |
+
# In[13]:
|
313 |
+
|
314 |
+
|
315 |
+
print(list(train_data.take(1).as_numpy_iterator()))
|
316 |
+
|
317 |
+
|
318 |
+
# In[14]:
|
319 |
+
|
320 |
+
|
321 |
+
def map_record_to_training_data(record):
|
322 |
+
record = tf.strings.split(record, sep="\t")
|
323 |
+
length = tf.strings.to_number(record[0], out_type=tf.int32)
|
324 |
+
tokens = record[1 : length + 1]
|
325 |
+
tags = record[length + 1 :]
|
326 |
+
tags = tf.strings.to_number(tags, out_type=tf.int64)
|
327 |
+
tags += 1
|
328 |
+
return tokens, tags
|
329 |
+
|
330 |
+
|
331 |
+
def lowercase_and_convert_to_ids(tokens):
|
332 |
+
tokens = tf.strings.lower(tokens)
|
333 |
+
return lookup_layer(tokens)
|
334 |
+
|
335 |
+
|
336 |
+
# We use `padded_batch` here because each record in the dataset has a
|
337 |
+
# different length.
|
338 |
+
batch_size = 32
|
339 |
+
train_dataset = (
|
340 |
+
train_data.map(map_record_to_training_data)
|
341 |
+
.map(lambda x, y: (lowercase_and_convert_to_ids(x), y))
|
342 |
+
.padded_batch(batch_size)
|
343 |
+
)
|
344 |
+
val_dataset = (
|
345 |
+
val_data.map(map_record_to_training_data)
|
346 |
+
.map(lambda x, y: (lowercase_and_convert_to_ids(x), y))
|
347 |
+
.padded_batch(batch_size)
|
348 |
+
)
|
349 |
+
|
350 |
+
ner_model = NERModel(num_tags, vocab_size, embed_dim=32, num_heads=4, ff_dim=64)
|
351 |
+
|
352 |
+
|
353 |
+
# In[15]:
|
354 |
+
|
355 |
+
|
356 |
+
class CustomNonPaddingTokenLoss(keras.losses.Loss):
|
357 |
+
def __init__(self, name="custom_ner_loss"):
|
358 |
+
super().__init__(name=name)
|
359 |
+
|
360 |
+
def call(self, y_true, y_pred):
|
361 |
+
loss_fn = keras.losses.SparseCategoricalCrossentropy(
|
362 |
+
from_logits=False, reduction= 'none'
|
363 |
+
)
|
364 |
+
loss = loss_fn(y_true, y_pred)
|
365 |
+
mask = tf.cast((y_true > 0), dtype=tf.float32)
|
366 |
+
loss = loss * mask
|
367 |
+
return tf.reduce_sum(loss) / tf.reduce_sum(mask)
|
368 |
+
|
369 |
+
|
370 |
+
loss = CustomNonPaddingTokenLoss()
|
371 |
+
|
372 |
+
|
373 |
+
# In[16]:
|
374 |
+
|
375 |
+
|
376 |
+
ner_model.compile(optimizer="adam", loss=loss)
|
377 |
+
ner_model.fit(train_dataset, epochs=10)
|
378 |
+
|
379 |
+
|
380 |
+
def tokenize_and_convert_to_ids(text):
|
381 |
+
tokens = text.split()
|
382 |
+
return lowercase_and_convert_to_ids(tokens)
|
383 |
+
|
384 |
+
|
385 |
+
# Sample inference using the trained model
|
386 |
+
sample_input = tokenize_and_convert_to_ids(
|
387 |
+
"eu rejects german call to boycott british lamb"
|
388 |
+
)
|
389 |
+
sample_input = tf.reshape(sample_input, shape=[1, -1])
|
390 |
+
print(sample_input)
|
391 |
+
|
392 |
+
output = ner_model.predict(sample_input)
|
393 |
+
prediction = np.argmax(output, axis=-1)[0]
|
394 |
+
prediction = [mapping[i] for i in prediction]
|
395 |
+
|
396 |
+
# eu -> B-ORG, german -> B-MISC, british -> B-MISC
|
397 |
+
print(prediction)
|
398 |
+
|
399 |
+
|
400 |
+
# In[17]:
|
401 |
+
|
402 |
+
@st.cache_data
|
403 |
+
def calculate_metrics(_dataset):
|
404 |
+
all_true_tag_ids, all_predicted_tag_ids = [], []
|
405 |
+
|
406 |
+
for x, y in _dataset:
|
407 |
+
output = ner_model.predict(x, verbose=0)
|
408 |
+
predictions = np.argmax(output, axis=-1)
|
409 |
+
predictions = np.reshape(predictions, [-1])
|
410 |
+
|
411 |
+
true_tag_ids = np.reshape(y, [-1])
|
412 |
+
|
413 |
+
mask = (true_tag_ids > 0) & (predictions > 0)
|
414 |
+
true_tag_ids = true_tag_ids[mask]
|
415 |
+
predicted_tag_ids = predictions[mask]
|
416 |
+
|
417 |
+
all_true_tag_ids.append(true_tag_ids)
|
418 |
+
all_predicted_tag_ids.append(predicted_tag_ids)
|
419 |
+
|
420 |
+
all_true_tag_ids = np.concatenate(all_true_tag_ids)
|
421 |
+
all_predicted_tag_ids = np.concatenate(all_predicted_tag_ids)
|
422 |
+
|
423 |
+
predicted_tags = [mapping[tag] for tag in all_predicted_tag_ids]
|
424 |
+
real_tags = [mapping[tag] for tag in all_true_tag_ids]
|
425 |
+
|
426 |
+
evaluate(real_tags, predicted_tags)
|
427 |
+
|
428 |
+
|
429 |
+
calculate_metrics(val_dataset)
|
430 |
+
|
431 |
+
|
432 |
+
# In[18]:
|
433 |
+
|
434 |
+
@st.cache_resource
|
435 |
+
def test_model_with_input(_ner_model, mapping):
|
436 |
+
# Get input sentence from user
|
437 |
+
input_sentence = "My name is Karishma Shirsath. I live in Toronto Canada."
|
438 |
+
|
439 |
+
# Tokenize and convert input sentence to IDs
|
440 |
+
sample_input = tokenize_and_convert_to_ids(input_sentence)
|
441 |
+
sample_input = tf.reshape(sample_input, shape=[1, -1])
|
442 |
+
|
443 |
+
# Predict tags using the trained model
|
444 |
+
output = _ner_model.predict(sample_input)
|
445 |
+
predictions = np.argmax(output, axis=-1)[0]
|
446 |
+
predicted_tags = [mapping[i] for i in predictions]
|
447 |
+
|
448 |
+
# Print the predicted tags for each token in the input sentence
|
449 |
+
print("Input sentence:", input_sentence)
|
450 |
+
print("Predicted tags:", predicted_tags)
|
451 |
+
|
452 |
+
# Test the model with user input
|
453 |
+
test_model_with_input(ner_model, mapping)
|
454 |
+
|
455 |
+
|
456 |
+
# In[20]:
|
457 |
+
|
458 |
+
|
459 |
+
logger = logging.getLogger("presidio-analyzer")
|
460 |
+
|
461 |
+
|
462 |
+
class FlairRecognizer(EntityRecognizer):
|
463 |
+
"""
|
464 |
+
Wrapper for a flair model, if needed to be used within Presidio Analyzer.
|
465 |
+
:example:
|
466 |
+
>from presidio_analyzer import AnalyzerEngine, RecognizerRegistry
|
467 |
+
>flair_recognizer = FlairRecognizer()
|
468 |
+
>registry = RecognizerRegistry()
|
469 |
+
>registry.add_recognizer(flair_recognizer)
|
470 |
+
>analyzer = AnalyzerEngine(registry=registry)
|
471 |
+
>results = analyzer.analyze(
|
472 |
+
> "My name is Christopher and I live in Irbid.",
|
473 |
+
> language="en",
|
474 |
+
> return_decision_process=True,
|
475 |
+
>)
|
476 |
+
>for result in results:
|
477 |
+
> print(result)
|
478 |
+
> print(result.analysis_explanation)
|
479 |
+
"""
|
480 |
+
|
481 |
+
ENTITIES = [
|
482 |
+
"LOCATION",
|
483 |
+
"PERSON",
|
484 |
+
"ORGANIZATION",
|
485 |
+
# "MISCELLANEOUS" # - There are no direct correlation with Presidio entities.
|
486 |
+
]
|
487 |
+
|
488 |
+
DEFAULT_EXPLANATION = "Identified as {} by Flair's Named Entity Recognition"
|
489 |
+
|
490 |
+
CHECK_LABEL_GROUPS = [
|
491 |
+
({"LOCATION"}, {"LOC", "LOCATION"}),
|
492 |
+
({"PERSON"}, {"PER", "PERSON"}),
|
493 |
+
({"ORGANIZATION"}, {"ORG"}),
|
494 |
+
# ({"MISCELLANEOUS"}, {"MISC"}), # Probably not PII
|
495 |
+
]
|
496 |
+
|
497 |
+
MODEL_LANGUAGES = {"en": "flair/ner-english-large"}
|
498 |
+
|
499 |
+
PRESIDIO_EQUIVALENCES = {
|
500 |
+
"PER": "PERSON",
|
501 |
+
"LOC": "LOCATION",
|
502 |
+
"ORG": "ORGANIZATION",
|
503 |
+
# 'MISC': 'MISCELLANEOUS' # - Probably not PII
|
504 |
+
}
|
505 |
+
|
506 |
+
def __init__(
|
507 |
+
self,
|
508 |
+
supported_language: str = "en",
|
509 |
+
supported_entities: Optional[List[str]] = None,
|
510 |
+
check_label_groups: Optional[Tuple[Set, Set]] = None,
|
511 |
+
model: SequenceTagger = None,
|
512 |
+
model_path: Optional[str] = None,
|
513 |
+
):
|
514 |
+
self.check_label_groups = (
|
515 |
+
check_label_groups if check_label_groups else self.CHECK_LABEL_GROUPS
|
516 |
+
)
|
517 |
+
|
518 |
+
supported_entities = supported_entities if supported_entities else self.ENTITIES
|
519 |
+
|
520 |
+
if model and model_path:
|
521 |
+
raise ValueError("Only one of model or model_path should be provided.")
|
522 |
+
elif model and not model_path:
|
523 |
+
self.model = model
|
524 |
+
elif not model and model_path:
|
525 |
+
print(f"Loading model from {model_path}")
|
526 |
+
self.model = SequenceTagger.load(model_path)
|
527 |
+
else:
|
528 |
+
print(f"Loading model for language {supported_language}")
|
529 |
+
self.model = SequenceTagger.load(
|
530 |
+
self.MODEL_LANGUAGES.get(supported_language)
|
531 |
+
)
|
532 |
+
|
533 |
+
super().__init__(
|
534 |
+
supported_entities=supported_entities,
|
535 |
+
supported_language=supported_language,
|
536 |
+
name="Flair Analytics",
|
537 |
+
)
|
538 |
+
|
539 |
+
def load(self) -> None:
|
540 |
+
"""Load the model, not used. Model is loaded during initialization."""
|
541 |
+
pass
|
542 |
+
|
543 |
+
def get_supported_entities(self) -> List[str]:
|
544 |
+
"""
|
545 |
+
Return supported entities by this model.
|
546 |
+
:return: List of the supported entities.
|
547 |
+
"""
|
548 |
+
return self.supported_entities
|
549 |
+
|
550 |
+
# Class to use Flair with Presidio as an external recognizer.
|
551 |
+
def analyze(
|
552 |
+
self, text: str, entities: List[str], nlp_artifacts: NlpArtifacts = None
|
553 |
+
) -> List[RecognizerResult]:
|
554 |
+
"""
|
555 |
+
Analyze text using Text Analytics.
|
556 |
+
:param text: The text for analysis.
|
557 |
+
:param entities: Not working properly for this recognizer.
|
558 |
+
:param nlp_artifacts: Not used by this recognizer.
|
559 |
+
:param language: Text language. Supported languages in MODEL_LANGUAGES
|
560 |
+
:return: The list of Presidio RecognizerResult constructed from the recognized
|
561 |
+
Flair detections.
|
562 |
+
"""
|
563 |
+
|
564 |
+
results = []
|
565 |
+
|
566 |
+
sentences = Sentence(text)
|
567 |
+
self.model.predict(sentences)
|
568 |
+
|
569 |
+
# If there are no specific list of entities, we will look for all of it.
|
570 |
+
if not entities:
|
571 |
+
entities = self.supported_entities
|
572 |
+
|
573 |
+
for entity in entities:
|
574 |
+
if entity not in self.supported_entities:
|
575 |
+
continue
|
576 |
+
|
577 |
+
for ent in sentences.get_spans("ner"):
|
578 |
+
if not self.__check_label(
|
579 |
+
entity, ent.labels[0].value, self.check_label_groups
|
580 |
+
):
|
581 |
+
continue
|
582 |
+
textual_explanation = self.DEFAULT_EXPLANATION.format(
|
583 |
+
ent.labels[0].value
|
584 |
+
)
|
585 |
+
explanation = self.build_flair_explanation(
|
586 |
+
round(ent.score, 2), textual_explanation
|
587 |
+
)
|
588 |
+
flair_result = self._convert_to_recognizer_result(ent, explanation)
|
589 |
+
|
590 |
+
results.append(flair_result)
|
591 |
+
|
592 |
+
return results
|
593 |
+
|
594 |
+
def _convert_to_recognizer_result(self, entity, explanation) -> RecognizerResult:
|
595 |
+
entity_type = self.PRESIDIO_EQUIVALENCES.get(entity.tag, entity.tag)
|
596 |
+
flair_score = round(entity.score, 2)
|
597 |
+
|
598 |
+
flair_results = RecognizerResult(
|
599 |
+
entity_type=entity_type,
|
600 |
+
start=entity.start_position,
|
601 |
+
end=entity.end_position,
|
602 |
+
score=flair_score,
|
603 |
+
analysis_explanation=explanation,
|
604 |
+
)
|
605 |
+
|
606 |
+
return flair_results
|
607 |
+
|
608 |
+
def build_flair_explanation(
|
609 |
+
self, original_score: float, explanation: str
|
610 |
+
) -> AnalysisExplanation:
|
611 |
+
"""
|
612 |
+
Create explanation for why this result was detected.
|
613 |
+
:param original_score: Score given by this recognizer
|
614 |
+
:param explanation: Explanation string
|
615 |
+
:return:
|
616 |
+
"""
|
617 |
+
explanation = AnalysisExplanation(
|
618 |
+
recognizer=self.__class__.__name__,
|
619 |
+
original_score=original_score,
|
620 |
+
textual_explanation=explanation,
|
621 |
+
)
|
622 |
+
return explanation
|
623 |
+
|
624 |
+
@staticmethod
|
625 |
+
def __check_label(
|
626 |
+
entity: str, label: str, check_label_groups: Tuple[Set, Set]
|
627 |
+
) -> bool:
|
628 |
+
return any(
|
629 |
+
[entity in egrp and label in lgrp for egrp, lgrp in check_label_groups]
|
630 |
+
)
|
631 |
+
|
632 |
+
|
633 |
+
# In[21]:
|
634 |
+
|
635 |
+
|
636 |
+
|
637 |
+
|
638 |
+
# # Use Flair NER for identifying PII
|
639 |
+
# sentence = Sentence(input_text)
|
640 |
+
# tagger.predict(sentence)
|
641 |
+
# entities = sentence.to_dict(tag_type='ner')['entities']
|
642 |
+
|
643 |
+
# # Mask PII using Presidio analyzer
|
644 |
+
# masked_text = analyzer.analyze(input_text, entities=entities)
|
645 |
+
|
646 |
+
from flair.data import Sentence
|
647 |
+
from flair.models import SequenceTagger
|
648 |
+
|
649 |
+
def predict_ner_tags(input_text):
|
650 |
+
|
651 |
+
|
652 |
+
# load tagger
|
653 |
+
tagger = SequenceTagger.load("flair/ner-english-large")
|
654 |
+
|
655 |
+
# make example sentence
|
656 |
+
# sentence = Sentence("My name is Karishma Shirsath. I live in Toronto Canada.")
|
657 |
+
|
658 |
+
sentence = Sentence(input_text)
|
659 |
+
# predict NER tags
|
660 |
+
tagger.predict(sentence)
|
661 |
+
|
662 |
+
# print sentence
|
663 |
+
print(sentence)
|
664 |
+
|
665 |
+
# print predicted NER spans
|
666 |
+
print("The following NER tags are found:")
|
667 |
+
# iterate over entities and print
|
668 |
+
for entity in sentence.get_spans("ner"):
|
669 |
+
print(entity)
|
670 |
+
|
671 |
+
|
672 |
+
|
673 |
+
# In[33]:
|
674 |
+
|
675 |
+
|
676 |
+
def analyze_text(input_text):
|
677 |
+
# load tagger
|
678 |
+
tagger = SequenceTagger.load("flair/ner-english-large")
|
679 |
+
|
680 |
+
# make example sentence
|
681 |
+
sentence = Sentence(input_text)
|
682 |
+
|
683 |
+
# predict NER tags
|
684 |
+
tagger.predict(sentence)
|
685 |
+
|
686 |
+
# print sentence
|
687 |
+
print(sentence)
|
688 |
+
|
689 |
+
# Anonymize identified named entities
|
690 |
+
anonymized_sentence = str(sentence)
|
691 |
+
for entity in sentence.get_spans("ner"):
|
692 |
+
entity_text = entity.text
|
693 |
+
anonymized_text = "*" * len(entity_text)
|
694 |
+
anonymized_sentence = anonymized_sentence.replace(entity_text, anonymized_text)
|
695 |
+
|
696 |
+
# print anonymized sentence
|
697 |
+
print("Anonymized sentence:")
|
698 |
+
print(anonymized_sentence)
|
699 |
+
return anonymized_sentence
|
app.py
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from Final_file import FlairRecognizer
|
3 |
+
import os
|
4 |
+
import PyPDF2
|
5 |
+
import docx
|
6 |
+
# from io import BytesIO
|
7 |
+
from fpdf import FPDF
|
8 |
+
import io
|
9 |
+
from docx import Document
|
10 |
+
|
11 |
+
# Cache the model loading and prediction function
|
12 |
+
@st.cache_resource
|
13 |
+
def cached_predict_ner_tags(text):
|
14 |
+
return FlairRecognizer.predict_ner_tags(text)
|
15 |
+
|
16 |
+
# Cache the text analysis function
|
17 |
+
@st.cache_resource
|
18 |
+
def cached_analyze_text(text):
|
19 |
+
return FlairRecognizer.analyze_text(text)
|
20 |
+
|
21 |
+
def download_masked_file(masked_text, file_extension):
|
22 |
+
|
23 |
+
# Create a temporary file to store the masked text
|
24 |
+
temp_file_path = f"masked_output.{file_extension}"
|
25 |
+
with open(temp_file_path, "w") as temp_file:
|
26 |
+
temp_file.write(masked_text)
|
27 |
+
|
28 |
+
# Display a download button
|
29 |
+
st.download_button("Download Masked File", temp_file_path, file_name=f"masked_output.{file_extension}")
|
30 |
+
|
31 |
+
# Clean up the temporary file
|
32 |
+
os.remove(temp_file_path)
|
33 |
+
|
34 |
+
def extract_text_from_pdf(file_contents):
|
35 |
+
try:
|
36 |
+
# base64_pdf = base64.b64encode(file_contents.read()).decode('utf-8')
|
37 |
+
pdf_reader = PyPDF2.PdfReader(file_contents)
|
38 |
+
text = ''
|
39 |
+
for page_num in range(len(pdf_reader.pages)):
|
40 |
+
text += pdf_reader.pages[page_num].extract_text()
|
41 |
+
return text
|
42 |
+
except Exception as e:
|
43 |
+
return f"Error occurred: {str(e)}"
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
def create_pdf(text_content):
|
48 |
+
pdf = FPDF()
|
49 |
+
pdf.add_page()
|
50 |
+
pdf.add_font("DejaVuSans", "", "DejaVuSans.ttf",uni=True) # Add DejaVuSans font
|
51 |
+
pdf.set_font("DejaVuSans", size=12)
|
52 |
+
pdf.multi_cell(0, 10, txt=text_content)
|
53 |
+
return pdf
|
54 |
+
|
55 |
+
def create_word_file(text_content):
|
56 |
+
doc = Document()
|
57 |
+
doc.add_paragraph(text_content)
|
58 |
+
# Save the document to a BytesIO object
|
59 |
+
doc_io = io.BytesIO()
|
60 |
+
doc.save(doc_io)
|
61 |
+
doc_io.seek(0)
|
62 |
+
return doc_io
|
63 |
+
|
64 |
+
def main():
|
65 |
+
st.title('PII Masking App')
|
66 |
+
st.sidebar.header('Upload Options')
|
67 |
+
upload_option = st.sidebar.radio("Choose upload option:", ('Text Input', 'File Upload'))
|
68 |
+
|
69 |
+
# # Dropdown menu with four choices
|
70 |
+
# st.sidebar.header('Masking Options')
|
71 |
+
# choice = st.sidebar.selectbox('Choose your masking option:', ['Option 1', 'Option 2', 'Option 3', 'Option 4'])
|
72 |
+
masked_text_public = ''
|
73 |
+
if upload_option == 'Text Input':
|
74 |
+
input_text = st.text_area("Enter text here:")
|
75 |
+
if st.button('Analyze'):
|
76 |
+
with st.spinner('Wait for it... the model is loading'):
|
77 |
+
cached_predict_ner_tags(input_text)
|
78 |
+
masked_text = cached_analyze_text(input_text)
|
79 |
+
st.text_area("Masked text:", value=masked_text, height=200)
|
80 |
+
elif upload_option == 'File Upload':
|
81 |
+
uploaded_file = st.file_uploader("Upload a file", type=['txt', 'pdf', 'docx'])
|
82 |
+
if uploaded_file is not None:
|
83 |
+
file_contents = uploaded_file.read()
|
84 |
+
# Process PDF file
|
85 |
+
if uploaded_file.type == 'application/pdf':
|
86 |
+
extracted_text = extract_text_from_pdf(uploaded_file)
|
87 |
+
if st.button('Analyze'):
|
88 |
+
with st.spinner('Wait for it... the model is loading'):
|
89 |
+
cached_predict_ner_tags(extracted_text)
|
90 |
+
masked_text = cached_analyze_text(extracted_text)
|
91 |
+
st.text_area("Masked text:", value=masked_text, height=200) # Display the extracted text
|
92 |
+
if extracted_text:
|
93 |
+
pdf = create_pdf(masked_text)
|
94 |
+
# Save PDF to temporary location
|
95 |
+
pdf_file_path = "masked_output.pdf"
|
96 |
+
pdf.output(pdf_file_path)
|
97 |
+
|
98 |
+
# Download button
|
99 |
+
st.download_button(label="Download", data=open(pdf_file_path, "rb"), file_name="masked_output.pdf", mime="application/pdf")
|
100 |
+
else:
|
101 |
+
st.warning("Please enter some text to download as PDF.")
|
102 |
+
|
103 |
+
# Process Word document
|
104 |
+
elif uploaded_file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
|
105 |
+
doc = docx.Document(io.BytesIO(file_contents))
|
106 |
+
text = ''
|
107 |
+
for paragraph in doc.paragraphs:
|
108 |
+
text += paragraph.text
|
109 |
+
if st.button('Analyze'):
|
110 |
+
with st.spinner('Wait for it... the model is loading'):
|
111 |
+
cached_predict_ner_tags(text)
|
112 |
+
masked_text = cached_analyze_text(text)
|
113 |
+
st.text_area("Masked text:", value=masked_text, height=200)
|
114 |
+
#create word file
|
115 |
+
doc_io = create_word_file(masked_text)
|
116 |
+
#download it
|
117 |
+
st.download_button(label="Download", data=doc_io, file_name="masked_text.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
|
118 |
+
else:
|
119 |
+
if st.button('Analyze'):
|
120 |
+
with st.spinner('Wait for it... the model is loading'):
|
121 |
+
cached_predict_ner_tags(file_contents.decode())
|
122 |
+
masked_text = cached_analyze_text(file_contents.decode())
|
123 |
+
st.text_area("Masked text:", value=masked_text, height=200)
|
124 |
+
st.download_button(label="Download",data = masked_text,file_name="masked_text.txt")
|
125 |
+
|
126 |
+
|
127 |
+
if __name__ == "__main__":
|
128 |
+
main()
|
conlleval.py
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
8 |
+
- O = outside
|
9 |
+
|
10 |
+
e.g.
|
11 |
+
John lives in New York City .
|
12 |
+
B-PER O O B-LOC I-LOC I-LOC O
|
13 |
+
|
14 |
+
IOBES:
|
15 |
+
- B = begin,
|
16 |
+
- E = end,
|
17 |
+
- S = singleton,
|
18 |
+
- I = inside but not the first or the last,
|
19 |
+
- O = outside
|
20 |
+
|
21 |
+
e.g.
|
22 |
+
John lives in New York City .
|
23 |
+
S-PER O O B-LOC I-LOC E-LOC O
|
24 |
+
|
25 |
+
prefix: IOBES
|
26 |
+
chunk_type: PER, LOC, etc.
|
27 |
+
"""
|
28 |
+
from __future__ import division, print_function, unicode_literals
|
29 |
+
|
30 |
+
import sys
|
31 |
+
from collections import defaultdict
|
32 |
+
|
33 |
+
def split_tag(chunk_tag):
|
34 |
+
"""
|
35 |
+
split chunk tag into IOBES prefix and chunk_type
|
36 |
+
e.g.
|
37 |
+
B-PER -> (B, PER)
|
38 |
+
O -> (O, None)
|
39 |
+
"""
|
40 |
+
if chunk_tag == 'O':
|
41 |
+
return ('O', None)
|
42 |
+
return chunk_tag.split('-', maxsplit=1)
|
43 |
+
|
44 |
+
def is_chunk_end(prev_tag, tag):
|
45 |
+
"""
|
46 |
+
check if the previous chunk ended between the previous and current word
|
47 |
+
e.g.
|
48 |
+
(B-PER, I-PER) -> False
|
49 |
+
(B-LOC, O) -> True
|
50 |
+
|
51 |
+
Note: in case of contradicting tags, e.g. (B-PER, I-LOC)
|
52 |
+
this is considered as (B-PER, B-LOC)
|
53 |
+
"""
|
54 |
+
prefix1, chunk_type1 = split_tag(prev_tag)
|
55 |
+
prefix2, chunk_type2 = split_tag(tag)
|
56 |
+
|
57 |
+
if prefix1 == 'O':
|
58 |
+
return False
|
59 |
+
if prefix2 == 'O':
|
60 |
+
return prefix1 != 'O'
|
61 |
+
|
62 |
+
if chunk_type1 != chunk_type2:
|
63 |
+
return True
|
64 |
+
|
65 |
+
return prefix2 in ['B', 'S'] or prefix1 in ['E', 'S']
|
66 |
+
|
67 |
+
def is_chunk_start(prev_tag, tag):
|
68 |
+
"""
|
69 |
+
check if a new chunk started between the previous and current word
|
70 |
+
"""
|
71 |
+
prefix1, chunk_type1 = split_tag(prev_tag)
|
72 |
+
prefix2, chunk_type2 = split_tag(tag)
|
73 |
+
|
74 |
+
if prefix2 == 'O':
|
75 |
+
return False
|
76 |
+
if prefix1 == 'O':
|
77 |
+
return prefix2 != 'O'
|
78 |
+
|
79 |
+
if chunk_type1 != chunk_type2:
|
80 |
+
return True
|
81 |
+
|
82 |
+
return prefix2 in ['B', 'S'] or prefix1 in ['E', 'S']
|
83 |
+
|
84 |
+
|
85 |
+
def calc_metrics(tp, p, t, percent=True):
|
86 |
+
"""
|
87 |
+
compute overall precision, recall and FB1 (default values are 0.0)
|
88 |
+
if percent is True, return 100 * original decimal value
|
89 |
+
"""
|
90 |
+
precision = tp / p if p else 0
|
91 |
+
recall = tp / t if t else 0
|
92 |
+
fb1 = 2 * precision * recall / (precision + recall) if precision + recall else 0
|
93 |
+
if percent:
|
94 |
+
return 100 * precision, 100 * recall, 100 * fb1
|
95 |
+
else:
|
96 |
+
return precision, recall, fb1
|
97 |
+
|
98 |
+
|
99 |
+
def count_chunks(true_seqs, pred_seqs):
|
100 |
+
"""
|
101 |
+
true_seqs: a list of true tags
|
102 |
+
pred_seqs: a list of predicted tags
|
103 |
+
|
104 |
+
return:
|
105 |
+
correct_chunks: a dict (counter),
|
106 |
+
key = chunk types,
|
107 |
+
value = number of correctly identified chunks per type
|
108 |
+
true_chunks: a dict, number of true chunks per type
|
109 |
+
pred_chunks: a dict, number of identified chunks per type
|
110 |
+
|
111 |
+
correct_counts, true_counts, pred_counts: similar to above, but for tags
|
112 |
+
"""
|
113 |
+
correct_chunks = defaultdict(int)
|
114 |
+
true_chunks = defaultdict(int)
|
115 |
+
pred_chunks = defaultdict(int)
|
116 |
+
|
117 |
+
correct_counts = defaultdict(int)
|
118 |
+
true_counts = defaultdict(int)
|
119 |
+
pred_counts = defaultdict(int)
|
120 |
+
|
121 |
+
prev_true_tag, prev_pred_tag = 'O', 'O'
|
122 |
+
correct_chunk = None
|
123 |
+
|
124 |
+
for true_tag, pred_tag in zip(true_seqs, pred_seqs):
|
125 |
+
if true_tag == pred_tag:
|
126 |
+
correct_counts[true_tag] += 1
|
127 |
+
true_counts[true_tag] += 1
|
128 |
+
pred_counts[pred_tag] += 1
|
129 |
+
|
130 |
+
_, true_type = split_tag(true_tag)
|
131 |
+
_, pred_type = split_tag(pred_tag)
|
132 |
+
|
133 |
+
if correct_chunk is not None:
|
134 |
+
true_end = is_chunk_end(prev_true_tag, true_tag)
|
135 |
+
pred_end = is_chunk_end(prev_pred_tag, pred_tag)
|
136 |
+
|
137 |
+
if pred_end and true_end:
|
138 |
+
correct_chunks[correct_chunk] += 1
|
139 |
+
correct_chunk = None
|
140 |
+
elif pred_end != true_end or true_type != pred_type:
|
141 |
+
correct_chunk = None
|
142 |
+
|
143 |
+
true_start = is_chunk_start(prev_true_tag, true_tag)
|
144 |
+
pred_start = is_chunk_start(prev_pred_tag, pred_tag)
|
145 |
+
|
146 |
+
if true_start and pred_start and true_type == pred_type:
|
147 |
+
correct_chunk = true_type
|
148 |
+
if true_start:
|
149 |
+
true_chunks[true_type] += 1
|
150 |
+
if pred_start:
|
151 |
+
pred_chunks[pred_type] += 1
|
152 |
+
|
153 |
+
prev_true_tag, prev_pred_tag = true_tag, pred_tag
|
154 |
+
if correct_chunk is not None:
|
155 |
+
correct_chunks[correct_chunk] += 1
|
156 |
+
|
157 |
+
return (correct_chunks, true_chunks, pred_chunks,
|
158 |
+
correct_counts, true_counts, pred_counts)
|
159 |
+
|
160 |
+
def get_result(correct_chunks, true_chunks, pred_chunks,
|
161 |
+
correct_counts, true_counts, pred_counts, verbose=True):
|
162 |
+
"""
|
163 |
+
if verbose, print overall performance, as well as preformance per chunk type;
|
164 |
+
otherwise, simply return overall prec, rec, f1 scores
|
165 |
+
"""
|
166 |
+
# sum counts
|
167 |
+
sum_correct_chunks = sum(correct_chunks.values())
|
168 |
+
sum_true_chunks = sum(true_chunks.values())
|
169 |
+
sum_pred_chunks = sum(pred_chunks.values())
|
170 |
+
|
171 |
+
sum_correct_counts = sum(correct_counts.values())
|
172 |
+
sum_true_counts = sum(true_counts.values())
|
173 |
+
|
174 |
+
nonO_correct_counts = sum(v for k, v in correct_counts.items() if k != 'O')
|
175 |
+
nonO_true_counts = sum(v for k, v in true_counts.items() if k != 'O')
|
176 |
+
|
177 |
+
chunk_types = sorted(list(set(list(true_chunks) + list(pred_chunks))))
|
178 |
+
|
179 |
+
# compute overall precision, recall and FB1 (default values are 0.0)
|
180 |
+
prec, rec, f1 = calc_metrics(sum_correct_chunks, sum_pred_chunks, sum_true_chunks)
|
181 |
+
res = (prec, rec, f1)
|
182 |
+
if not verbose:
|
183 |
+
return res
|
184 |
+
|
185 |
+
# print overall performance, and performance per chunk type
|
186 |
+
|
187 |
+
print("processed %i tokens with %i phrases; " % (sum_true_counts, sum_true_chunks), end='')
|
188 |
+
print("found: %i phrases; correct: %i.\n" % (sum_pred_chunks, sum_correct_chunks), end='')
|
189 |
+
|
190 |
+
print("accuracy: %6.2f%%; (non-O)" % (100*nonO_correct_counts/nonO_true_counts))
|
191 |
+
print("accuracy: %6.2f%%; " % (100*sum_correct_counts/sum_true_counts), end='')
|
192 |
+
print("precision: %6.2f%%; recall: %6.2f%%; FB1: %6.2f" % (prec, rec, f1))
|
193 |
+
|
194 |
+
# for each chunk type, compute precision, recall and FB1 (default values are 0.0)
|
195 |
+
for t in chunk_types:
|
196 |
+
prec, rec, f1 = calc_metrics(correct_chunks[t], pred_chunks[t], true_chunks[t])
|
197 |
+
print("%17s: " %t , end='')
|
198 |
+
print("precision: %6.2f%%; recall: %6.2f%%; FB1: %6.2f" %
|
199 |
+
(prec, rec, f1), end='')
|
200 |
+
print(" %d" % pred_chunks[t])
|
201 |
+
|
202 |
+
return res
|
203 |
+
# you can generate LaTeX output for tables like in
|
204 |
+
# http://cnts.uia.ac.be/conll2003/ner/example.tex
|
205 |
+
# but I'm not implementing this
|
206 |
+
|
207 |
+
def evaluate(true_seqs, pred_seqs, verbose=True):
|
208 |
+
(correct_chunks, true_chunks, pred_chunks,
|
209 |
+
correct_counts, true_counts, pred_counts) = count_chunks(true_seqs, pred_seqs)
|
210 |
+
result = get_result(correct_chunks, true_chunks, pred_chunks,
|
211 |
+
correct_counts, true_counts, pred_counts, verbose=verbose)
|
212 |
+
return result
|
213 |
+
|
214 |
+
def evaluate_conll_file(fileIterator):
|
215 |
+
true_seqs, pred_seqs = [], []
|
216 |
+
|
217 |
+
for line in fileIterator:
|
218 |
+
cols = line.strip().split()
|
219 |
+
# each non-empty line must contain >= 3 columns
|
220 |
+
if not cols:
|
221 |
+
true_seqs.append('O')
|
222 |
+
pred_seqs.append('O')
|
223 |
+
elif len(cols) < 3:
|
224 |
+
raise IOError("conlleval: too few columns in line %s\n" % line)
|
225 |
+
else:
|
226 |
+
# extract tags from last 2 columns
|
227 |
+
true_seqs.append(cols[-2])
|
228 |
+
pred_seqs.append(cols[-1])
|
229 |
+
return evaluate(true_seqs, pred_seqs)
|
230 |
+
|
231 |
+
if __name__ == '__main__':
|
232 |
+
"""
|
233 |
+
usage: conlleval < file
|
234 |
+
"""
|
235 |
+
evaluate_conll_file(sys.stdin)
|
requirements.txt
ADDED
Binary file (5.85 kB). View file
|
|