Spaces:
Running
Running
File size: 4,941 Bytes
2e39601 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | import html
from functools import lru_cache, partial
import gradio as gr
from tacitus_nlp import Actors, Evidence, Events
EXAMPLE = "Maya Torres announced that Northbridge City Council would vote next Tuesday. The Civic Ledger requested the agenda. Residents protested on Monday and protested again on Wednesday."
EVENT_EXAMPLE = "The Civic Ledger requested the agenda. Residents protested on Monday and protested again on Wednesday."
@lru_cache(maxsize=3)
def load(task):
return {"evidence": Evidence, "actors": Actors, "events": Events}[task].from_pretrained()
def highlight(text, spans):
boundaries = sorted({0, len(text), *(point for span in spans for point in (span["start"], span["end"]))})
parts = []
for left, right in zip(boundaries, boundaries[1:]):
segment = html.escape(text[left:right])
labels = sorted({span.get("role", span.get("type", "")) for span in spans
if span["start"] <= left and right <= span["end"]})
if labels:
title = html.escape(", ".join(labels), quote=True)
segment = f'<mark title="{title}">{segment}</mark>'
parts.append(segment)
return '<div class="source-text">' + "".join(parts) + "</div>"
def submit(task, text, claim=""):
try:
engine = load(task)
if task == "evidence":
result = engine.check(passage=text, claim=claim)
view = [(label.replace("_", " "), round(score, 4)) for label, score in result["scores"].items()]
note = f'**{result["verdict"].replace("_", " ").capitalize()}** · Review required'
spans = []
elif task == "actors":
result = engine.extract(text)
spans = result["mentions"]
view = [(span["text"], span["type"], span["start"], span["end"]) for span in spans]
note = f'**{len(view)} detected mentions**'
else:
result = engine.extract(text)
spans = [span for event in result["events"] for span in (event["trigger"], *event["participants"])]
view = [(event["trigger"]["text"], event["event_type"], event["trigger"]["start"],
event["trigger"]["end"], event["assertion_status"]) for event in result["events"]]
note = f'**{len(view)} proposed event mentions**'
except ValueError as error:
raise gr.Error(str(error)) from error
status = "<br>".join(html.escape(warning) for warning in result["warnings"])
version = f'`{result["model_id"]}@{result["model_revision"]}` · Schema {result["schema_version"]}'
return note + "\n\n" + version + "\n\n" + status, highlight(text, spans), view, result
def interface():
with gr.Blocks(title="TACITUS Source Lab", analytics_enabled=False) as demo:
gr.Markdown("# TACITUS Source Lab\nCheck a claim against a passage or extract actor and event mentions from English text.")
for task, heading, columns, example in [
("evidence", "Evidence", ["Label", "Score"], EXAMPLE),
("actors", "Actors", ["Mention", "Type", "Start", "End"], EXAMPLE),
("events", "Events", ["Trigger", "Type", "Start", "End", "Assertion status"], EVENT_EXAMPLE),
]:
with gr.Tab(heading):
passage = gr.Textbox(label="Source passage", lines=5, value=example)
inputs = [passage]
if task == "evidence":
inputs.append(gr.Textbox(label="Claim", value="The council has already voted."))
button = gr.Button("Check claim" if task == "evidence" else "Extract mentions", variant="primary")
status = gr.Markdown()
source = gr.HTML()
table = gr.Dataframe(headers=columns, interactive=False)
result = gr.JSON(label="Response JSON")
download = gr.Button("Download JSON")
button.click(partial(submit, task), inputs, [status, source, table, result],
concurrency_limit=1, concurrency_id="inference")
download.click(None, result, None, js="""
(payload) => {
if (!payload) return;
const data = typeof payload === "string" ? payload : JSON.stringify(payload, null, 2);
const url = URL.createObjectURL(new Blob([data], {type: 'application/json'}));
const link = document.createElement('a');
link.href = url;
link.download = 'tacitus-response.json';
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
""")
return demo
if __name__ == "__main__":
interface().queue(max_size=8).launch(css=".source-text {white-space:pre-wrap; font-size:1.05rem} mark {background:#f7dc8e;color:#172034;border-radius:3px}")
|