AjithBharadwaj commited on
Commit
56b3258
·
1 Parent(s): 82fe26b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -0
app.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import pipeline
2
+
3
+ get_completion = pipeline("ner", model="dslim/bert-base-NER")
4
+
5
+ def merge_tokens(tokens):
6
+ merged_tokens = []
7
+ for token in tokens:
8
+ if merged_tokens and token['entity'].startswith('I-') and merged_tokens[-1]['entity'].endswith(token['entity'][2:]):
9
+ # If current token continues the entity of the last one, merge them
10
+ last_token = merged_tokens[-1]
11
+ last_token['word'] += token['word'].replace('##', '')
12
+ last_token['end'] = token['end']
13
+ last_token['score'] = (last_token['score'] + token['score']) / 2
14
+ else:
15
+ # Otherwise, add the token to the list
16
+ merged_tokens.append(token)
17
+
18
+ return merged_tokens
19
+
20
+ def ner(input):
21
+ output = get_completion(input)
22
+ merged_tokens = merge_tokens(output)
23
+ return {"text": input, "entities": merged_tokens}
24
+
25
+ gr.close_all()
26
+ demo = gr.Interface(fn=ner,
27
+ inputs=[gr.Textbox(label="Text to find entities", lines=2)],
28
+ outputs=[gr.HighlightedText(label="Text with entities")],
29
+ title="NER with dslim/bert-base-NER",
30
+ description="Find entities using the `dslim/bert-base-NER` model under the hood!",
31
+ allow_flagging="never",
32
+ examples=["My name is Andrew, I'm building DeeplearningAI and I live in California", "My name is Poli, I live in Vienna and work at HuggingFace"])
33
+
34
+ demo.launch(share=True)