Add-Vishnu commited on
Commit
19d65ea
·
1 Parent(s): 05c0b1b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -0
app.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spacy
3
+ import medspacy
4
+ from medspacy.visualization import visualize_dep, visualize_ent
5
+ from spacy import displacy
6
+
7
+ med_ner = medspacy.load(r"./ner_models//ner_model_v2//training//model-best")
8
+ def merge_tokens(tokens):
9
+ merged_tokens = []
10
+ for token in tokens:
11
+ if merged_tokens and token['entity'].startswith('I-') and merged_tokens[-1]['entity'].endswith(token['entity'][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(inp):
24
+ output = med_ner(inp)
25
+ formatted_ents = []
26
+ for i in output.ents:
27
+ ent = {}
28
+ ent['entity']= i.label_
29
+ ent['word']= i.text
30
+ ent['start']= int(i.start_char)
31
+ ent['end']= int(i.end_char)
32
+ print(i.label_,"->",i.text,"->",i.start_char,"->",i.end_char,"->",type(i.start_char))
33
+ formatted_ents.append(ent)
34
+ print(formatted_ents)
35
+
36
+ merged_tokens = merge_tokens(formatted_ents)
37
+ # return {"text": str(inp), "entities": formatted_ents}
38
+ return {"text": str(inp), "entities": merged_tokens}
39
+
40
+ demo = gr.Interface(fn=ner,
41
+ inputs=[gr.Textbox(label="Text to find entities", lines=2)],
42
+ outputs=[gr.HighlightedText(label="Text with entites")],
43
+ title="Custom-NER with Spacy3 and MedSpacy",
44
+ description="Find medical entities using the NER model under the hood!",
45
+ allow_flagging = True,
46
+ examples=["Patient has hx of stroke. Mother diagnosed with diabetes. No evidence of pna.", "I have fever and cough since 2 days."]
47
+ )
48
+
49
+ demo.launch()