christophalt commited on
Commit
3ddbd57
·
1 Parent(s): 3279fb3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from dataclasses import dataclass
3
+
4
+ from pytorch_ie import AnnotationList, LabeledSpan, Pipeline, TextDocument, annotation_field
5
+ from pytorch_ie.models import TransformerSpanClassificationModel
6
+ from pytorch_ie.taskmodules import TransformerSpanClassificationTaskModule
7
+ from spacy import displacy
8
+
9
+
10
+ @dataclass
11
+ class ExampleDocument(TextDocument):
12
+ entities: AnnotationList[LabeledSpan] = annotation_field(target="text")
13
+
14
+
15
+ model_name_or_path = "pie/example-ner-spanclf-conll03"
16
+ ner_taskmodule = TransformerSpanClassificationTaskModule.from_pretrained(model_name_or_path)
17
+ ner_model = TransformerSpanClassificationModel.from_pretrained(model_name_or_path)
18
+
19
+ ner_pipeline = Pipeline(model=ner_model, taskmodule=ner_taskmodule, device=-1, num_workers=0)
20
+
21
+
22
+ def predict(text):
23
+ document = ExampleDocument(text)
24
+
25
+ ner_pipeline(document, predict_field="entities")
26
+
27
+ doc = {
28
+ "text": document.text,
29
+ "ents": [{
30
+ "start": entity.start,
31
+ "end": entity.end,
32
+ "label": entity.label
33
+ } for entity in sorted(document.entities.predictions, key=lambda e: e.start)],
34
+ "title": None
35
+ }
36
+
37
+ html = displacy.render(doc, style="ent", page=True, manual=True, minify=True)
38
+ html = (
39
+ "<div style='max-width:100%; max-height:360px; overflow:auto'>"
40
+ + html
41
+ + "</div>"
42
+ )
43
+
44
+ return html
45
+
46
+
47
+ iface = gr.Interface(fn=predict, inputs="textbox", outputs="html")
48
+ iface.launch()