alejandrocl86 commited on
Commit
6b977db
·
verified ·
1 Parent(s): b1bda51

Create app.py

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