Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from prettytable import PrettyTable
|
| 5 |
+
|
| 6 |
+
from pytorch_ie.annotations import LabeledSpan, BinaryRelation
|
| 7 |
+
from pytorch_ie.auto import AutoPipeline
|
| 8 |
+
from pytorch_ie.core import AnnotationList, annotation_field
|
| 9 |
+
from pytorch_ie.documents import TextDocument
|
| 10 |
+
|
| 11 |
+
from typing import List
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
@dataclass
|
| 15 |
+
class ExampleDocument(TextDocument):
|
| 16 |
+
entities: AnnotationList[LabeledSpan] = annotation_field(target="text")
|
| 17 |
+
relations: AnnotationList[BinaryRelation] = annotation_field(target="entities")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
ner_model_name_or_path = "pie/example-ner-spanclf-conll03"
|
| 21 |
+
re_model_name_or_path = "DFKI-SLT/relation_classification_tacred_revisited"
|
| 22 |
+
|
| 23 |
+
ner_pipeline = AutoPipeline.from_pretrained(ner_model_name_or_path, device=-1, num_workers=0)
|
| 24 |
+
re_pipeline = AutoPipeline.from_pretrained(re_model_name_or_path, device=-1, num_workers=0)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def predict(text):
|
| 28 |
+
document = ExampleDocument(text)
|
| 29 |
+
|
| 30 |
+
ner_pipeline(document)
|
| 31 |
+
|
| 32 |
+
while len(document.entities.predictions) > 0:
|
| 33 |
+
document.entities.append(document.entities.predictions.pop(0))
|
| 34 |
+
|
| 35 |
+
re_pipeline(document)
|
| 36 |
+
|
| 37 |
+
t = PrettyTable()
|
| 38 |
+
t.field_names = ["head", "tail", "relation"]
|
| 39 |
+
t.align = "l"
|
| 40 |
+
for relation in document.relations.predictions:
|
| 41 |
+
t.add_row([str(relation.head), str(relation.tail), relation.label])
|
| 42 |
+
|
| 43 |
+
html = t.get_html_string(format=True)
|
| 44 |
+
html = (
|
| 45 |
+
"<div style='max-width:100%; max-height:360px; overflow:auto'>"
|
| 46 |
+
+ html
|
| 47 |
+
+ "</div>"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
return html
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
iface = gr.Interface(
|
| 54 |
+
fn=predict,
|
| 55 |
+
inputs=gr.inputs.Textbox(
|
| 56 |
+
lines=5,
|
| 57 |
+
default="There is still some uncertainty that Musk - also chief executive of electric car maker Tesla and rocket company SpaceX - will pull off his planned buyout.",
|
| 58 |
+
),
|
| 59 |
+
outputs="html",
|
| 60 |
+
)
|
| 61 |
+
iface.launch()
|