alejandrocl86 commited on
Commit
6be75e7
·
verified ·
1 Parent(s): 5f5d913

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -0
app.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline
3
+
4
+ # Load the model locally
5
+ model_name = "dslim/bert-base-NER"
6
+ ner_pipeline = pipeline("ner", model=model_name, tokenizer=model_name, aggregation_strategy="simple")
7
+
8
+ def merge_tokens(tokens):
9
+ merged_tokens = []
10
+ for token in tokens:
11
+ if merged_tokens and token['entity_group'].startswith('I-') and merged_tokens[-1]['entity_group'].endswith(token['entity_group'][2:]):
12
+ # If current token continues the entity of the last one, merge them
13
+ last_token = merged_tokens[-1]
14
+ last_token['word'] += token['word'].replace('##', '')
15
+ last_token['end'] = token['end']
16
+ last_token['score'] = (last_token['score'] + token['score']) / 2
17
+ else:
18
+ # Otherwise, add the token to the list
19
+ merged_tokens.append(token)
20
+
21
+ return merged_tokens
22
+
23
+ def ner(input_text):
24
+ # Use the pipeline to get entities
25
+ output = ner_pipeline(input_text)
26
+ merged_tokens = merge_tokens(output)
27
+ return {"text": input_text, "entities": merged_tokens}
28
+
29
+ # Gradio interface
30
+ demo = gr.Interface(fn=ner,
31
+ inputs=[gr.Textbox(label="Text to find entities", lines=2)],
32
+ outputs=[gr.HighlightedText(label="Text with entities")],
33
+ title="NER with dslim/bert-base-NER",
34
+ description="Find entities using the `dslim/bert-base-NER` model under the hood!",
35
+ allow_flagging="never",
36
+ 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"])
37
+
38
+ demo.launch()