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'{segment}' parts.append(segment) return '
' + "".join(parts) + "
" 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 = "
".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}")