reichenbach commited on
Commit
f1a14d9
1 Parent(s): 9ac47a7

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -0
app.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import numpy as np
3
+ import gradio as gr
4
+ import tensorflow as tf
5
+ from tensorflow import keras
6
+ from huggingface_hub.keras_mixin import from_pretrained_keras
7
+
8
+ class CustomNonPaddingTokenLoss(keras.losses.Loss):
9
+ def __init__(self, name="custom_ner_loss"):
10
+ super().__init__(name=name)
11
+
12
+ def call(self, y_true, y_pred):
13
+ loss_fn = keras.losses.SparseCategoricalCrossentropy(
14
+ from_logits=True, reduction=keras.losses.Reduction.NONE
15
+ )
16
+
17
+ loss = loss_fn(y_true, y_pred)
18
+ mask = tf.cast((y_true > 0), dtype=tf.float32)
19
+
20
+ loss = loss * mask
21
+ return tf.reduce_sum(loss) / tf.reduce_sum(mask)
22
+
23
+ def lowercase_and_convert_to_ids(tokens):
24
+ tokens = tf.strings.lower(tokens)
25
+
26
+ return lookup_layer(tokens)
27
+
28
+ def tokenize_and_convert_to_ids(text):
29
+ tokens = text.split()
30
+ return lowercase_and_convert_to_ids(tokens)
31
+
32
+
33
+ def ner_tagging(text_1):
34
+
35
+ with open("vocab.json",'r') as f:
36
+ vocab = json.load(f)
37
+
38
+ with open('mapping.json','r') as f:
39
+ mapping = json.load(f)
40
+
41
+ ner_model = from_pretrained_keras("keras-io/ner-with-transformers",
42
+ custom_objects={'CustomNonPaddingTokenLoss':CustomNonPaddingTokenLoss},
43
+ compile=False)
44
+
45
+ lookup_layer = keras.layers.StringLookup(vocabulary=vocab['tokens'])
46
+
47
+ sample_input = tokenize_and_convert_to_ids(text_1)
48
+ sample_input = tf.reshape(sample_input, shape=[1, -1])
49
+ output = ner_model.predict(sample_input)
50
+ prediction = np.argmax(output, axis=-1)[0]
51
+
52
+ prediction = [mapping[str(i)] for i in prediction]
53
+
54
+ return prediction
55
+
56
+ text_1 = gr.inputs.Textbox(lines=5)
57
+
58
+ ner_tag = gr.outputs.Textbox()
59
+
60
+ iface = gr.Interface(ner_tagging,
61
+ inputs=text_1,outputs=ner_tag, examples=[['EU rejects German call to boycott British lamb .'],
62
+ ["Wednesday's U.S. Open draw ceremony revealed that both title holders should run into their first serious opposition in the third round."]])
63
+
64
+ iface.launch()