Spaces:
Running
Running
Release browser inference, models, and data v0.2.0
Browse files- README.md +3 -1
- index.html +40 -30
- inference.js +220 -0
- models/actors.json +0 -0
- models/events.json +0 -0
- models/evidence.json +0 -0
- models/roles.json +0 -0
- review.html +16 -0
- saved-examples.html +48 -0
- source-lab.css +36 -0
- toolkit/README.md +86 -0
- toolkit/app.py +94 -0
- toolkit/baseline-results.json +153 -0
- toolkit/challenge-evaluation.json +298 -0
- toolkit/diagnostic-results.json +101 -0
- toolkit/diagnostics.py +45 -0
- toolkit/evidence-pilot-results.json +14 -0
- toolkit/evidence_pilot.py +57 -0
- toolkit/fixtures/evidence.jsonl +3 -0
- toolkit/release-versions.json +8 -0
- toolkit/requirements-research.txt +5 -0
- toolkit/requirements.txt +7 -0
- toolkit/research/REVIEW.md +31 -0
- toolkit/research/challenge_eval.py +66 -0
- toolkit/research/challenges.py +107 -0
- toolkit/research/event_pipeline.py +56 -0
- toolkit/research/features.py +79 -0
- toolkit/research/neural_evidence.py +110 -0
- toolkit/research/neural_infer.py +38 -0
- toolkit/research/package_release.py +164 -0
- toolkit/research/parity.py +22 -0
- toolkit/research/prepare.py +110 -0
- toolkit/research/publish_release.py +100 -0
- toolkit/research/train.py +321 -0
- toolkit/tacitus_nlp/__init__.py +205 -0
- toolkit/tacitus_nlp/data.py +145 -0
- toolkit/tacitus_nlp/sources.json +42 -0
- toolkit/tests/test_toolkit.py +85 -0
- workspace.js +120 -0
README.md
CHANGED
|
@@ -7,4 +7,6 @@ sdk: static
|
|
| 7 |
app_file: index.html
|
| 8 |
---
|
| 9 |
|
| 10 |
-
TACITUS Source Lab
|
|
|
|
|
|
|
|
|
| 7 |
app_file: index.html
|
| 8 |
---
|
| 9 |
|
| 10 |
+
TACITUS Source Lab analyzes new English passages with CPU-trained models that run in the browser. It supports source-relative claim verification, typed actor spans, and event triggers. Low-performing event participant proposals are opt-in. Input text stays in the browser.
|
| 11 |
+
|
| 12 |
+
The compact Evidence model is an experimental browser baseline. The Evidence model repository documents a separately evaluated CPU neural adapter when available. No Space GPU or inference API is required.
|
index.html
CHANGED
|
@@ -3,46 +3,56 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
|
|
| 6 |
<title>TACITUS Source Lab</title>
|
| 7 |
-
<
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
main { max-width: 62rem; margin: auto; padding: 3rem 1.25rem; }
|
| 11 |
-
header { border-bottom: 1px solid #adb8bb; margin-bottom: 1.4rem; padding-bottom: 1.4rem; }
|
| 12 |
-
h1 { font: 500 clamp(2rem,7vw,4rem)/1.1 Georgia,serif; margin: 0 0 .6rem; }
|
| 13 |
-
h2 { font: 500 1.5rem Georgia,serif; margin: 0 0 .7rem; }
|
| 14 |
-
p { margin: .4rem 0; }
|
| 15 |
-
nav { display: flex; flex-wrap: wrap; gap: .55rem; margin-bottom: 1rem; }
|
| 16 |
-
button { font: inherit; background: white; color: inherit; border: 1px solid #9aa9af; padding: .52rem .9rem; border-radius: .35rem; cursor: pointer; }
|
| 17 |
-
button[aria-pressed=true] { color: white; background: #223d54; border-color: #223d54; }
|
| 18 |
-
button:focus-visible { outline: 3px solid #b66a15; outline-offset: 3px; }
|
| 19 |
-
article { padding: clamp(1rem,4vw,2rem); border: 1px solid #cdd4d4; background: white; border-radius: .6rem; }
|
| 20 |
-
#source { white-space: pre-wrap; margin: 1rem 0; padding: 1rem; background: #f5f7fa; border-left: 3px solid #71869a; }
|
| 21 |
-
mark { background: #f6df9d; color: inherit; }
|
| 22 |
-
pre { max-height: 23rem; overflow: auto; padding: 1rem; background: #f5f7fa; font-size: .85rem; }
|
| 23 |
-
#revision { font-size: .85rem; color: #496176; overflow-wrap: anywhere; }
|
| 24 |
-
#download { margin-top: 1rem; }
|
| 25 |
-
</style>
|
| 26 |
-
<script src="examples.js" defer></script>
|
| 27 |
-
<script src="lab.js" defer></script>
|
| 28 |
</head>
|
| 29 |
<body>
|
| 30 |
<main>
|
| 31 |
-
<header>
|
| 32 |
-
<
|
| 33 |
-
<
|
| 34 |
-
<
|
| 35 |
-
<
|
|
|
|
|
|
|
|
|
|
| 36 |
</nav>
|
| 37 |
-
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
<h2 id="summary"></h2>
|
| 39 |
-
<p id="
|
| 40 |
-
<blockquote id="source"></blockquote>
|
| 41 |
-
<p id="claim"></p>
|
| 42 |
<p id="warning"></p>
|
|
|
|
|
|
|
| 43 |
<details><summary>Response JSON</summary><pre id="json"></pre></details>
|
| 44 |
<button type="button" id="download">Download JSON</button>
|
| 45 |
</article>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
</main>
|
| 47 |
</body>
|
| 48 |
</html>
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 6 |
+
<meta name="description" content="Check a claim or extract actor and event mentions with TACITUS browser models.">
|
| 7 |
<title>TACITUS Source Lab</title>
|
| 8 |
+
<link rel="stylesheet" href="source-lab.css">
|
| 9 |
+
<script src="inference.js" defer></script>
|
| 10 |
+
<script src="workspace.js" defer></script>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
</head>
|
| 12 |
<body>
|
| 13 |
<main>
|
| 14 |
+
<header>
|
| 15 |
+
<h1>TACITUS Source Lab</h1>
|
| 16 |
+
<p>Check a claim against a passage, or find actor and event mentions in English source text.</p>
|
| 17 |
+
</header>
|
| 18 |
+
<nav aria-label="Analysis mode">
|
| 19 |
+
<button type="button" data-task="evidence" aria-pressed="true">Evidence</button>
|
| 20 |
+
<button type="button" data-task="actors" aria-pressed="false">Actors</button>
|
| 21 |
+
<button type="button" data-task="events" aria-pressed="false">Events</button>
|
| 22 |
</nav>
|
| 23 |
+
<section class="workbench">
|
| 24 |
+
<form id="analysis">
|
| 25 |
+
<label for="passage">Source passage</label>
|
| 26 |
+
<textarea id="passage" rows="8" spellcheck="false" required></textarea>
|
| 27 |
+
<div id="claim-field">
|
| 28 |
+
<label for="claim">Claim</label>
|
| 29 |
+
<input id="claim" type="text" maxlength="1500" required>
|
| 30 |
+
</div>
|
| 31 |
+
<div id="role-field" hidden><label><input id="roles" type="checkbox"> Include experimental event participants</label></div>
|
| 32 |
+
<div class="actions">
|
| 33 |
+
<button type="submit" id="run" class="primary">Check claim</button>
|
| 34 |
+
<button type="button" id="example">Load example</button>
|
| 35 |
+
</div>
|
| 36 |
+
<p class="note">Analysis runs in this tab. Your text stays in your browser.</p>
|
| 37 |
+
<p id="status" role="status" aria-live="polite"></p>
|
| 38 |
+
</form>
|
| 39 |
+
<article id="result" aria-labelledby="summary" hidden>
|
| 40 |
<h2 id="summary"></h2>
|
| 41 |
+
<p id="version"></p>
|
|
|
|
|
|
|
| 42 |
<p id="warning"></p>
|
| 43 |
+
<blockquote id="source"></blockquote>
|
| 44 |
+
<div id="details"></div>
|
| 45 |
<details><summary>Response JSON</summary><pre id="json"></pre></details>
|
| 46 |
<button type="button" id="download">Download JSON</button>
|
| 47 |
</article>
|
| 48 |
+
</section>
|
| 49 |
+
<footer>
|
| 50 |
+
<a href="saved-examples.html">Earlier saved examples</a>
|
| 51 |
+
<a href="review.html">Evaluation and review</a>
|
| 52 |
+
<a href="https://huggingface.co/Giuliocc/tacitus-evidence-base">Evidence model</a>
|
| 53 |
+
<a href="https://huggingface.co/Giuliocc/tacitus-actors-base">Actors model</a>
|
| 54 |
+
<a href="https://huggingface.co/Giuliocc/tacitus-events-base">Events model</a>
|
| 55 |
+
</footer>
|
| 56 |
</main>
|
| 57 |
</body>
|
| 58 |
</html>
|
inference.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict';
|
| 2 |
+
|
| 3 |
+
const tokenizer = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*|\p{N}+(?:[.,]\p{N}+)*|[^\s]/gu;
|
| 4 |
+
const number = /^\p{N}+(?:[.,]\p{N}+)*$/u;
|
| 5 |
+
const negation = ['no','not','never','neither','without','cannot','denied','deny'];
|
| 6 |
+
const modal = ['will','would','might','could','plans','planned','scheduled','proposed'];
|
| 7 |
+
const encoder = new TextEncoder();
|
| 8 |
+
const crcTable = Uint32Array.from({length:256}, (_, index) => {
|
| 9 |
+
for (let i = 0; i < 8; i++) index = (index >>> 1) ^ (index & 1 ? 0xedb88320 : 0);
|
| 10 |
+
return index >>> 0;
|
| 11 |
+
});
|
| 12 |
+
const modelCache = new Map();
|
| 13 |
+
const limit = {evidence:12000, actors:8000, events:5000};
|
| 14 |
+
|
| 15 |
+
function tokenize(text) {
|
| 16 |
+
let points = 0;
|
| 17 |
+
let units = 0;
|
| 18 |
+
return Array.from(text.matchAll(tokenizer), match => {
|
| 19 |
+
points += Array.from(text.slice(units,match.index)).length;
|
| 20 |
+
const start = points;
|
| 21 |
+
points += Array.from(match[0]).length;
|
| 22 |
+
units = match.index + match[0].length;
|
| 23 |
+
return [match[0],start,points];
|
| 24 |
+
});
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
function crc32(text) {
|
| 28 |
+
let crc = 0xffffffff;
|
| 29 |
+
for(const byte of encoder.encode(text)) crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 255];
|
| 30 |
+
return (crc ^ 0xffffffff) >>> 0;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
function encode(features,width) {
|
| 34 |
+
const values = new Map();
|
| 35 |
+
for(const [name,value] of features) {
|
| 36 |
+
const hash = crc32(name);
|
| 37 |
+
const column = hash % width;
|
| 38 |
+
values.set(column,(values.get(column) || 0) + (hash & 0x80000000 ? -value : value));
|
| 39 |
+
}
|
| 40 |
+
return Array.from(values).sort(([a],[b])=>a-b);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
function evidenceFeatures(text, claim, mode) {
|
| 44 |
+
const passage = tokenize(text).map(([word])=>word.toLowerCase());
|
| 45 |
+
const hypothesis = tokenize(claim).map(([word])=>word.toLowerCase());
|
| 46 |
+
const terms = new Set(passage), requested = new Set(hypothesis);
|
| 47 |
+
const words = Array.from(requested).sort((a,b)=>{
|
| 48 |
+
const left=Array.from(a,c=>c.codePointAt(0)), right=Array.from(b,c=>c.codePointAt(0));
|
| 49 |
+
const first=left.findIndex((value,index)=>value!==right[index]);
|
| 50 |
+
return first===-1 ? left.length-right.length : left[first]-(right[first]??-1);
|
| 51 |
+
});
|
| 52 |
+
const features = words.map(word=>['h:'+word,.25]);
|
| 53 |
+
if (mode === 'hypothesis') return features;
|
| 54 |
+
const recall = (reference, samples)=>samples.filter(term=>reference.has(term)).length/Math.max(1,samples.length);
|
| 55 |
+
const bigrams = sequence=>new Set(sequence.slice(1).map((word,index)=>JSON.stringify([sequence[index],word])));
|
| 56 |
+
const numerics = words.filter(word=>number.test(word));
|
| 57 |
+
const ratios = {
|
| 58 |
+
recall:recall(terms,words),
|
| 59 |
+
bigram:recall(bigrams(passage),Array.from(bigrams(hypothesis))),
|
| 60 |
+
numbers:recall(terms,numerics)
|
| 61 |
+
};
|
| 62 |
+
for(const [name,value] of Object.entries(ratios)) features.push(['val:'+name,value],['bin:'+name+':'+Math.floor(value*10),1]);
|
| 63 |
+
for(const [name, vocabulary] of [['neg',negation],['modal',modal]]) {
|
| 64 |
+
const left = +vocabulary.some(word=>terms.has(word));
|
| 65 |
+
const right = +vocabulary.some(word=>requested.has(word));
|
| 66 |
+
features.push([`${name}:${left}:${right}`,1]);
|
| 67 |
+
}
|
| 68 |
+
for(const word of words) features.push([(terms.has(word)?'match:':'missing:')+word,.5]);
|
| 69 |
+
features.push([`numbers-exact:${+(numerics.length>0)}:${+numerics.every(word=>terms.has(word))}`,1],
|
| 70 |
+
[`length:${Math.min(Math.floor(passage.length/25),12)}:${Math.min(Math.floor(hypothesis.length/5),10)}`,1]);
|
| 71 |
+
return features;
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
function tokenFeatures(tokens,index,mode,anchor=null,eventType=null) {
|
| 75 |
+
const word=tokens[index][0], lower=word.toLowerCase(), points=Array.from(lower);
|
| 76 |
+
const features=[['w:'+lower,1]];
|
| 77 |
+
if(mode==='lexical') return features;
|
| 78 |
+
const first=Array.from(word)[0];
|
| 79 |
+
const isUpper=value=>value.toUpperCase()===value&&value.toLowerCase()!==value;
|
| 80 |
+
const shape=isUpper(word)?'upper':isUpper(first)?'title':number.test(word)?'number':'other';
|
| 81 |
+
features.push(['shape:'+shape,1],['length:'+Math.min(Array.from(word).length,12),.5]);
|
| 82 |
+
for(const length of [2,3,4]) if(points.length>=length) {
|
| 83 |
+
features.push(['pre:'+points.slice(0,length).join(''),.5],['suf:'+points.slice(-length).join(''),.5]);
|
| 84 |
+
}
|
| 85 |
+
for(const offset of [-2,-1,1,2]) {
|
| 86 |
+
const pos=index+offset;
|
| 87 |
+
const other=pos<0?'<start>':pos>=tokens.length?'<end>':tokens[pos][0].toLowerCase();
|
| 88 |
+
features.push([`ctx:${offset}:${other}`,.65]);
|
| 89 |
+
if (Math.abs(offset)===1) features.push([`pair:${offset}:${lower}:${other}`,.5]);
|
| 90 |
+
}
|
| 91 |
+
if(anchor!==null) {
|
| 92 |
+
const dist=index-anchor, abs=Math.abs(dist);
|
| 93 |
+
const bucket=(abs<=12?abs:13+Math.min(Math.floor(abs/20),5))*Math.sign(dist);
|
| 94 |
+
features.push(['event:'+eventType,1],['dist:'+bucket,1],[`role:${eventType}:${bucket}`,1],
|
| 95 |
+
[`anchor:${tokens[anchor][0].toLowerCase()}:${bucket}`,.65],[`eventword:${eventType}:${lower}`,.8]);
|
| 96 |
+
}
|
| 97 |
+
return features;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
function decode(model) {
|
| 101 |
+
const raw=Uint8Array.from(atob(model.weights),c=>c.charCodeAt(0));
|
| 102 |
+
if(raw.length!==model.width*model.labels.length*2) throw Error('The model weights are incomplete.');
|
| 103 |
+
return {...model,weights:new DataView(raw.buffer)};
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
function load(task) {
|
| 107 |
+
if(!modelCache.has(task)) {
|
| 108 |
+
modelCache.set(task,fetch(`models/${task}.json`).then(response=>{
|
| 109 |
+
if(!response.ok) throw Error('Model files are temporarily unavailable.');
|
| 110 |
+
return response.json();
|
| 111 |
+
}).then(decode).catch(error=>{modelCache.delete(task);throw error;}));
|
| 112 |
+
}
|
| 113 |
+
return modelCache.get(task);
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
function predict(model,features) {
|
| 117 |
+
const input=encode(features,model.width);
|
| 118 |
+
return model.labels.map((_,index)=>{
|
| 119 |
+
let value=model.bias[index], sum=0;
|
| 120 |
+
for(const [column,strength] of input)
|
| 121 |
+
sum+=model.weights.getInt16((index*model.width+column)*2,true)*strength;
|
| 122 |
+
return value+sum*model.scale[index];
|
| 123 |
+
});
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
function softmax(values) {
|
| 127 |
+
const max=Math.max(...values);
|
| 128 |
+
const exp=values.map(value=>Math.exp(value-max));
|
| 129 |
+
const sum=exp.reduce((left,right)=>left+right,0);
|
| 130 |
+
return exp.map(value=>value/sum);
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
function argmax(values) {
|
| 134 |
+
return values.reduce((best,value,index)=>value>values[best]?index:best,0);
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
function spans(model,tokens,points,anchor=null,kind=null) {
|
| 138 |
+
const result=[];
|
| 139 |
+
let previous=null;
|
| 140 |
+
const allowed=kind===null?null:new Set(model.allowed_roles[kind]??[]);
|
| 141 |
+
for(let i=0;i<tokens.length;i++) {
|
| 142 |
+
const [,start,end]=tokens[i];
|
| 143 |
+
const scores=predict(model,tokenFeatures(tokens,i,model.mode,anchor,kind));
|
| 144 |
+
scores[0]+=model.negative_margin;
|
| 145 |
+
if(allowed!==null) for(let j=1;j<scores.length;j++) if(!allowed.has(model.labels[j].slice(2))) scores[j]=-Infinity;
|
| 146 |
+
const index=argmax(scores);
|
| 147 |
+
if(index===0) {
|
| 148 |
+
previous=null;
|
| 149 |
+
continue;
|
| 150 |
+
}
|
| 151 |
+
const [marker,type]=model.labels[index].split(':');
|
| 152 |
+
if(marker==='I'&&previous?.type===type) {
|
| 153 |
+
previous.end=end;
|
| 154 |
+
} else {
|
| 155 |
+
previous={start,end,type};
|
| 156 |
+
result.push(previous);
|
| 157 |
+
}
|
| 158 |
+
}
|
| 159 |
+
for(const item of result) item.text=points.slice(item.start,item.end).join('');
|
| 160 |
+
return result;
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
async function sha(text) {
|
| 164 |
+
const result=await crypto.subtle.digest('SHA-256',encoder.encode(text));
|
| 165 |
+
return Array.from(new Uint8Array(result),byte=>byte.toString(16).padStart(2,'0')).join('');
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
async function analyze(task,text,claim='',includeRoles=false) {
|
| 169 |
+
if(!Object.hasOwn(limit,task)||typeof text!=='string'||!text.trim())
|
| 170 |
+
throw Error('Enter a source passage.');
|
| 171 |
+
const points=Array.from(text);
|
| 172 |
+
if(points.length>limit[task]) throw Error(`Use at most ${limit[task].toLocaleString()} source characters.`);
|
| 173 |
+
if(task==='evidence'&&(!claim.trim()||Array.from(claim).length>1500))
|
| 174 |
+
throw Error('Enter a claim of 1–1,500 characters.');
|
| 175 |
+
const model=await load(task);
|
| 176 |
+
const textHash=await sha(text);
|
| 177 |
+
const envelope={task,schema_version:'0.2.0',preprocessing_revision:'0.2.0',document_id:textHash,text_sha256:textHash,
|
| 178 |
+
model_id:model.model_id,model_revision:model.model_revision,warnings:[]};
|
| 179 |
+
if(task==='evidence') {
|
| 180 |
+
const raw=predict(model,evidenceFeatures(text,claim,model.mode));
|
| 181 |
+
const probabilities=softmax(raw.map(value=>value/model.temperature));
|
| 182 |
+
const best=argmax(probabilities);
|
| 183 |
+
const review=probabilities[best]<model.threshold;
|
| 184 |
+
return {...envelope,claim_sha256:await sha(claim),verdict:model.labels[best],
|
| 185 |
+
scores:Object.fromEntries(model.labels.map((label,i)=>[label,probabilities[i]])),
|
| 186 |
+
review_required:review,review_reason:review?'Confidence fell below the validation threshold.':null,
|
| 187 |
+
calibration_revision:model.version,
|
| 188 |
+
warnings:['Experimental browser baseline. Calibration was measured on VitaminC. Verify the result against the passage.']};
|
| 189 |
+
}
|
| 190 |
+
const tokens=tokenize(text);
|
| 191 |
+
const detected=spans(model,tokens,points);
|
| 192 |
+
if(task==='actors') {
|
| 193 |
+
const mentions=await Promise.all(detected.map(async item=>({...item,canonical_actor_id:null,
|
| 194 |
+
mention_id:await sha(JSON.stringify([textHash,item.start,item.end,item.type,envelope.schema_version]))})));
|
| 195 |
+
return {...envelope,mentions,warnings:['Typed mentions can miss or mislabel actors.']};
|
| 196 |
+
}
|
| 197 |
+
const roles=includeRoles?await load('roles'):null;
|
| 198 |
+
const byStart=new Map(tokens.map(([,start],i)=>[start,i]));
|
| 199 |
+
const events=[];
|
| 200 |
+
const roleMax=18;
|
| 201 |
+
for(const item of detected) {
|
| 202 |
+
const location=byStart.get(item.start);
|
| 203 |
+
let participants=[];
|
| 204 |
+
if(roles&&events.length<roleMax) {
|
| 205 |
+
const from=Math.max(0,location-roles.window_tokens);
|
| 206 |
+
const window=tokens.slice(from,location+roles.window_tokens+1);
|
| 207 |
+
participants=spans(roles,window,points,location-from,item.type)
|
| 208 |
+
.map(({type,...span})=>({...span,role:type,status:'proposed'}));
|
| 209 |
+
}
|
| 210 |
+
events.push({event_mention_id:await sha(JSON.stringify([textHash,item.start,item.end,item.type,envelope.schema_version])),
|
| 211 |
+
trigger:item,event_type:item.type,assertion_status:'unknown',participants});
|
| 212 |
+
}
|
| 213 |
+
return {...envelope,roles_model_revision:roles?.model_revision??null,events,warnings:[
|
| 214 |
+
'Event triggers are proposals. Assertion status is unknown.',
|
| 215 |
+
...(roles?['Experimental participant proposals had low exact-span scores in evaluation.']:[]),
|
| 216 |
+
...(roles&&detected.length>roleMax?[`Participant extraction was limited to the first ${roleMax} triggers.`]:[])]};
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
const tacitus = { analyze, tokenize, evidenceFeatures, tokenFeatures, encode, decode, predict, spans };
|
| 220 |
+
if(typeof module!=='undefined') module.exports=tacitus;
|
models/actors.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
models/events.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
models/evidence.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
models/roles.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
review.html
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
| 4 |
+
<title>TACITUS evaluation and review</title><link rel="stylesheet" href="source-lab.css"></head>
|
| 5 |
+
<body><main><header><h1>Evaluation and review</h1><p>Version 0.2.0</p></header>
|
| 6 |
+
<article>
|
| 7 |
+
<h2>What the tests show</h2>
|
| 8 |
+
<ul>
|
| 9 |
+
<li>Evidence browser macro-F1 was 0.479 on audited VitaminC pairs. The separate CPU neural adapter reached 0.581 on a 1,400-pair test sample, compared with 0.564 for unchanged DOXA on the same pairs.</li>
|
| 10 |
+
<li>Actors exact-span micro-F1 was 0.424 on the audited Few-NERD test split. Untouched GLiNER scored higher on the small civic diagnostic set.</li>
|
| 11 |
+
<li>Event trigger exact-span micro-F1 was 0.655 on an internal MAVEN-ARG holdout. Participant F1 was 0.095 with gold triggers and 0.072 end-to-end, so participants are opt-in.</li>
|
| 12 |
+
</ul>
|
| 13 |
+
<p>The civic examples are author-created diagnostics. Independent domain review is pending.</p>
|
| 14 |
+
<p><a href="https://huggingface.co/spaces/Giuliocc/tacitus-source-lab/blob/main/toolkit/research/REVIEW.md">Read the six review questions and responses</a></p>
|
| 15 |
+
<p><a href="./">Back to Source Lab</a></p>
|
| 16 |
+
</article></main></body></html>
|
saved-examples.html
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 6 |
+
<title>TACITUS Source Lab</title>
|
| 7 |
+
<style>
|
| 8 |
+
:root { color-scheme: light; font: 16px/1.55 system-ui,sans-serif; color: #18283a; background: #f4f3ee; }
|
| 9 |
+
body { margin: 0; }
|
| 10 |
+
main { max-width: 62rem; margin: auto; padding: 3rem 1.25rem; }
|
| 11 |
+
header { border-bottom: 1px solid #adb8bb; margin-bottom: 1.4rem; padding-bottom: 1.4rem; }
|
| 12 |
+
h1 { font: 500 clamp(2rem,7vw,4rem)/1.1 Georgia,serif; margin: 0 0 .6rem; }
|
| 13 |
+
h2 { font: 500 1.5rem Georgia,serif; margin: 0 0 .7rem; }
|
| 14 |
+
p { margin: .4rem 0; }
|
| 15 |
+
nav { display: flex; flex-wrap: wrap; gap: .55rem; margin-bottom: 1rem; }
|
| 16 |
+
button { font: inherit; background: white; color: inherit; border: 1px solid #9aa9af; padding: .52rem .9rem; border-radius: .35rem; cursor: pointer; }
|
| 17 |
+
button[aria-pressed=true] { color: white; background: #223d54; border-color: #223d54; }
|
| 18 |
+
button:focus-visible { outline: 3px solid #b66a15; outline-offset: 3px; }
|
| 19 |
+
article { padding: clamp(1rem,4vw,2rem); border: 1px solid #cdd4d4; background: white; border-radius: .6rem; }
|
| 20 |
+
#source { white-space: pre-wrap; margin: 1rem 0; padding: 1rem; background: #f5f7fa; border-left: 3px solid #71869a; }
|
| 21 |
+
mark { background: #f6df9d; color: inherit; }
|
| 22 |
+
pre { max-height: 23rem; overflow: auto; padding: 1rem; background: #f5f7fa; font-size: .85rem; }
|
| 23 |
+
#revision { font-size: .85rem; color: #496176; overflow-wrap: anywhere; }
|
| 24 |
+
#download { margin-top: 1rem; }
|
| 25 |
+
</style>
|
| 26 |
+
<script src="examples.js" defer></script>
|
| 27 |
+
<script src="lab.js" defer></script>
|
| 28 |
+
</head>
|
| 29 |
+
<body>
|
| 30 |
+
<main>
|
| 31 |
+
<header><h1>TACITUS Source Lab</h1><p>Explore saved baseline outputs for claim verification and source-span extraction.</p></header>
|
| 32 |
+
<nav aria-label="Analysis examples">
|
| 33 |
+
<button type="button" data-task="evidence">Evidence</button>
|
| 34 |
+
<button type="button" data-task="actors">Actors</button>
|
| 35 |
+
<button type="button" data-task="events">Events</button>
|
| 36 |
+
</nav>
|
| 37 |
+
<article aria-labelledby="summary">
|
| 38 |
+
<h2 id="summary"></h2>
|
| 39 |
+
<p id="revision"></p>
|
| 40 |
+
<blockquote id="source"></blockquote>
|
| 41 |
+
<p id="claim"></p>
|
| 42 |
+
<p id="warning"></p>
|
| 43 |
+
<details><summary>Response JSON</summary><pre id="json"></pre></details>
|
| 44 |
+
<button type="button" id="download">Download JSON</button>
|
| 45 |
+
</article>
|
| 46 |
+
</main>
|
| 47 |
+
</body>
|
| 48 |
+
</html>
|
source-lab.css
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root{color-scheme:light;font:16px/1.6 system-ui,sans-serif;color:#182638;background:#f4f2ed}
|
| 2 |
+
*{box-sizing:border-box}
|
| 3 |
+
body{margin:0}
|
| 4 |
+
main{max-width:80rem;margin:0 auto;padding:clamp(1rem,5vw,4rem)}
|
| 5 |
+
header{border-bottom:1px solid #afbac0;padding-bottom:1.2rem;margin-bottom:1.25rem}
|
| 6 |
+
h1,h2{font-family:Georgia,serif;font-weight:500;line-height:1.12}
|
| 7 |
+
h1{font-size:clamp(2.35rem,7vw,4.3rem);margin:0 0 .5rem}
|
| 8 |
+
h2{font-size:1.7rem;margin:0 0 .65rem}
|
| 9 |
+
p{margin:.45rem 0}
|
| 10 |
+
nav,.actions,footer{display:flex;gap:.65rem;flex-wrap:wrap}
|
| 11 |
+
nav{margin-bottom:1rem}
|
| 12 |
+
button{font:inherit;color:#1c3448;background:#fff;border:1px solid #869aa5;padding:.52rem .9rem;border-radius:.4rem;cursor:pointer}
|
| 13 |
+
button[aria-pressed=true],button.primary{color:#fff;background:#21425b;border-color:#21425b}
|
| 14 |
+
button:disabled{cursor:progress;opacity:.7}
|
| 15 |
+
button:focus-visible,textarea:focus-visible,input:focus-visible,a:focus-visible{outline:3px solid #ab610f;outline-offset:3px}
|
| 16 |
+
.workbench{display:grid;gap:1rem;grid-template-columns:repeat(2,minmax(0,1fr))}
|
| 17 |
+
form,article{min-width:0;border:1px solid #ccd2cf;border-radius:.65rem;background:#fff;padding:clamp(1rem,3vw,1.5rem)}
|
| 18 |
+
label{display:block;font-weight:650;margin-bottom:.3rem}
|
| 19 |
+
textarea,input{font:inherit;color:inherit;width:100%;border:1px solid #8c9ba2;border-radius:.4rem;padding:.65rem;background:#fdfeff}
|
| 20 |
+
textarea{resize:vertical}
|
| 21 |
+
#claim-field,.actions{margin-top:.85rem}
|
| 22 |
+
.note,#version{font-size:.86rem;color:#435b70}
|
| 23 |
+
#version{overflow-wrap:anywhere}
|
| 24 |
+
#status{color:#783816}
|
| 25 |
+
#source{margin:.9rem 0;padding:.8rem;background:#f4f6f9;border-left:3px solid #607e97;overflow-wrap:anywhere;white-space:pre-wrap}
|
| 26 |
+
mark{background:#f7dfa2;color:#182638}
|
| 27 |
+
ul{padding-inline-start:1.25rem}
|
| 28 |
+
li{padding:.2rem 0}
|
| 29 |
+
pre{max-height:21rem;overflow:auto;background:#f4f6f9;padding:1rem}
|
| 30 |
+
summary{cursor:pointer;margin:.35rem 0}
|
| 31 |
+
#download{margin-top:.85rem}
|
| 32 |
+
footer{border-top:1px solid #afbac0;margin-top:1.5rem;padding-top:1rem;font-size:.9rem}
|
| 33 |
+
footer a{color:#21425b;text-underline-offset:3px}
|
| 34 |
+
@media(max-width:740px){.workbench{grid-template-columns:1fr}}
|
| 35 |
+
|
| 36 |
+
#role-field{margin-top:.9rem} #roles{width:auto;margin-right:.3rem}
|
toolkit/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TACITUS Source Toolkit
|
| 2 |
+
|
| 3 |
+
A runnable CPU baseline for three English-language source analysis tasks. Evidence compares a claim with a supplied passage. Actors finds typed mentions. Events proposes trigger spans for Attack, Arrest, Protest, and Request. Events shares the upstream GLiNER checkpoint with Actors during this baseline phase. Its trigger proposals need review, and the default app leaves participant extraction disabled. Every event's assertion status is unknown.
|
| 4 |
+
|
| 5 |
+
## Run locally
|
| 6 |
+
|
| 7 |
+
Use Python 3.12. The first run downloads the pinned public checkpoints in `tacitus_nlp/sources.json`; allow approximately 2 GB of free model storage in addition to the Python environment.
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python -m venv .venv
|
| 11 |
+
source .venv/bin/activate
|
| 12 |
+
pip install torch==2.8.0 --index-url https://download.pytorch.org/whl/cpu
|
| 13 |
+
pip install -r requirements.txt
|
| 14 |
+
OMP_NUM_THREADS=4 python app.py
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
Open the local URL displayed by Gradio. The three tabs accept user text, display the model revision, and export response JSON in the browser. Actor and event views highlight source spans. The static sample explorer is available by opening `space/index.html` and displays the recorded examples offline.
|
| 18 |
+
|
| 19 |
+
```python
|
| 20 |
+
from tacitus_nlp import Actors, Evidence, Events
|
| 21 |
+
|
| 22 |
+
source = "Residents protested on Monday. Council members scheduled a vote for Wednesday."
|
| 23 |
+
result = Evidence.from_pretrained().check(passage=source, claim="The council has voted.")
|
| 24 |
+
actors = Actors.from_pretrained().extract(source)
|
| 25 |
+
events = Events.from_pretrained().extract(source)
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Offsets are Python Unicode code-point offsets with an exclusive end. Evidence shows uncalibrated class scores and requires review on every response. Actor mentions have no canonical identities. To experiment with target-conditioned event arguments, pass `role_schema={event_type: {role: definition}}` to `Events.from_pretrained()`. Supply roles verified against the upstream schema. The second pass marks the specific trigger occurrence and maps proposed role spans back to the original text.
|
| 29 |
+
|
| 30 |
+
## Verify and reproduce
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python -m unittest discover -s tests -v
|
| 34 |
+
OMP_NUM_THREADS=4 python diagnostics.py
|
| 35 |
+
OMP_NUM_THREADS=4 python evidence_pilot.py /path/to/new/scratch-checkpoint
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
`baseline-results.json` records actual predictions for the app examples. `diagnostic-results.json` compares pinned NLI and DOXA on three synthetic examples. For DOXA, obtain and review `verifier.py` and `adapter.json` from the pinned verifier revision in the source manifest, install ONNX Runtime, and pass their local directory as `--doxa-folder` to `diagnostics.py`. The comparison maps DOXA's `insufficient_context` to `insufficient_information` and leaves the source artifact intact. These cases are for diagnostics. A new independently reviewed benchmark and a SciFact rehydration check remain open.
|
| 39 |
+
|
| 40 |
+
`evidence-pilot-results.json` records one CPU training step on three original diagnostic examples with a frozen encoder. The classifier changed and the saved checkpoint preserved the label mapping and logits on reload. This pilot checks compatibility. Its checkpoint is excluded from the archive, and its training loss is unsuitable as an estimate of accuracy. No paid compute was used.
|
| 41 |
+
|
| 42 |
+
## Dataset conversion
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
python -m tacitus_nlp.data evidence evidence.jsonl train=vitaminc-train.jsonl dev=vitaminc-dev.jsonl
|
| 46 |
+
python -m tacitus_nlp.data actors actors.jsonl train=few-nerd-train.jsonl dev=few-nerd-dev.jsonl --labels few-nerd-fine-labels.json
|
| 47 |
+
python -m tacitus_nlp.data events events.jsonl train=maven-train.jsonl dev=maven-valid.jsonl
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
Inputs are original JSONL or JSONL exported from the pinned upstream dataset. For Few-NERD, export the supervised configuration and a JSON array of fine-label names in the same order as the dataset feature metadata. Its character offsets refer to a single-space reconstruction. Group audits compare normalized token sequences across splits. Article-level disjointness cannot be verified from the supervised token format.
|
| 51 |
+
|
| 52 |
+
The audit rejects records with bad labels or offsets and partitions sharing a recorded group. It preserves a prior successful output when a run fails. A failed audit reports the file and line for investigation. The converters have unit coverage. The smoke test converted 25 VitaminC development records and 25 Few-NERD supervised validation records, yielding 28 mapped actor spans. MAVEN-ARG was exercised with synthetic records. Full archive conversion, conflict resolution, dataset coverage counts, and independent data review remain pending.
|
| 53 |
+
|
| 54 |
+
- VitaminC supplies evidence labels and recovery identifiers under its listed CC BY-SA 3.0 terms. The canary is omitted. [VitaminC](https://huggingface.co/datasets/tals/vitaminc)
|
| 55 |
+
- Few-NERD supplies the supervised fine labels under its listed CC BY-SA 4.0 terms. [Few-NERD](https://huggingface.co/datasets/DFKI-SLT/few-nerd)
|
| 56 |
+
- MAVEN-ARG supplies linked trigger and participant spans. Obtain its archive and verify the official role definitions and redistribution terms. Official test argument labels are withheld. [MAVEN-ARG](https://github.com/THU-KEG/MAVEN-Argument)
|
| 57 |
+
|
| 58 |
+
## Hugging Face
|
| 59 |
+
|
| 60 |
+
The public static repository `Giuliocc/tacitus-source-lab` was created. Its files are still pending upload. The connector can create repositories but exposes no file commit, and the browser was unavailable. To publish the standalone sample explorer from a terminal already authenticated as Giuliocc with repository write access, run the following from the source directory.
|
| 61 |
+
|
| 62 |
+
```bash
|
| 63 |
+
hf auth whoami
|
| 64 |
+
hf upload Giuliocc/tacitus-source-lab ./space . --repo-type space
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
A separately configured Gradio hosting option is needed for live inference. Model and dataset repositories should receive actual reviewed deliverables. Full training, calibrated inference, official evaluation, and public model or dataset releases are pending.
|
| 68 |
+
|
| 69 |
+
## v0.2.0 research release
|
| 70 |
+
|
| 71 |
+
The static Space now runs compact, trained models on new text. The earlier saved examples and higher-capacity local Gradio baselines remain available. The published model cards link to held-out evaluation and dataset manifests. Use `research/REVIEW.md` for the review results and next experiments.
|
| 72 |
+
|
| 73 |
+
From this directory install `requirements-research.txt`. Arrange the pinned download files as listed in each dataset's provenance. Keep upstream files out of the Space. The following commands reproduce the main release.
|
| 74 |
+
|
| 75 |
+
```sh
|
| 76 |
+
python -m research.prepare /path/to/corpora /path/to/processed
|
| 77 |
+
python -m research.train evidence /path/to/processed /path/to/trained
|
| 78 |
+
python -m research.train actors /path/to/processed /path/to/trained
|
| 79 |
+
python -m research.train events /path/to/processed /path/to/trained
|
| 80 |
+
python -m research.train roles /path/to/processed /path/to/trained
|
| 81 |
+
python -m research.event_pipeline /path/to/processed/events /path/to/trained
|
| 82 |
+
python -m research.challenges /path/to/challenges
|
| 83 |
+
python -m research.challenge_eval /path/to/trained /path/to/challenges /path/to/challenge-evaluation.json
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
The optional neural Evidence branch uses `python -m research.neural_evidence /path/to/processed/evidence /path/to/doxa /path/to/trained/neural`. Use the local reviewed DOXA `verifier.py` and `adapter.json` at the pinned source revision. The results apply to their named evaluation partitions. No mature domain quality is assumed.
|
toolkit/app.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import html
|
| 2 |
+
from functools import lru_cache, partial
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
|
| 6 |
+
from tacitus_nlp import Actors, Evidence, Events
|
| 7 |
+
|
| 8 |
+
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."
|
| 9 |
+
EVENT_EXAMPLE = "The Civic Ledger requested the agenda. Residents protested on Monday and protested again on Wednesday."
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@lru_cache(maxsize=3)
|
| 13 |
+
def load(task):
|
| 14 |
+
return {"evidence": Evidence, "actors": Actors, "events": Events}[task].from_pretrained()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def highlight(text, spans):
|
| 18 |
+
boundaries = sorted({0, len(text), *(point for span in spans for point in (span["start"], span["end"]))})
|
| 19 |
+
parts = []
|
| 20 |
+
for left, right in zip(boundaries, boundaries[1:]):
|
| 21 |
+
segment = html.escape(text[left:right])
|
| 22 |
+
labels = sorted({span.get("role", span.get("type", "")) for span in spans
|
| 23 |
+
if span["start"] <= left and right <= span["end"]})
|
| 24 |
+
if labels:
|
| 25 |
+
title = html.escape(", ".join(labels), quote=True)
|
| 26 |
+
segment = f'<mark title="{title}">{segment}</mark>'
|
| 27 |
+
parts.append(segment)
|
| 28 |
+
return '<div class="source-text">' + "".join(parts) + "</div>"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def submit(task, text, claim=""):
|
| 32 |
+
try:
|
| 33 |
+
engine = load(task)
|
| 34 |
+
if task == "evidence":
|
| 35 |
+
result = engine.check(passage=text, claim=claim)
|
| 36 |
+
view = [(label.replace("_", " "), round(score, 4)) for label, score in result["scores"].items()]
|
| 37 |
+
note = f'**{result["verdict"].replace("_", " ").capitalize()}** · Review required'
|
| 38 |
+
spans = []
|
| 39 |
+
elif task == "actors":
|
| 40 |
+
result = engine.extract(text)
|
| 41 |
+
spans = result["mentions"]
|
| 42 |
+
view = [(span["text"], span["type"], span["start"], span["end"]) for span in spans]
|
| 43 |
+
note = f'**{len(view)} detected mentions**'
|
| 44 |
+
else:
|
| 45 |
+
result = engine.extract(text)
|
| 46 |
+
spans = [span for event in result["events"] for span in (event["trigger"], *event["participants"])]
|
| 47 |
+
view = [(event["trigger"]["text"], event["event_type"], event["trigger"]["start"],
|
| 48 |
+
event["trigger"]["end"], event["assertion_status"]) for event in result["events"]]
|
| 49 |
+
note = f'**{len(view)} proposed event mentions**'
|
| 50 |
+
except ValueError as error:
|
| 51 |
+
raise gr.Error(str(error)) from error
|
| 52 |
+
status = "<br>".join(html.escape(warning) for warning in result["warnings"])
|
| 53 |
+
version = f'`{result["model_id"]}@{result["model_revision"]}` · Schema {result["schema_version"]}'
|
| 54 |
+
return note + "\n\n" + version + "\n\n" + status, highlight(text, spans), view, result
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def interface():
|
| 58 |
+
with gr.Blocks(title="TACITUS Source Lab", analytics_enabled=False) as demo:
|
| 59 |
+
gr.Markdown("# TACITUS Source Lab\nCheck a claim against a passage or extract actor and event mentions from English text.")
|
| 60 |
+
for task, heading, columns, example in [
|
| 61 |
+
("evidence", "Evidence", ["Label", "Score"], EXAMPLE),
|
| 62 |
+
("actors", "Actors", ["Mention", "Type", "Start", "End"], EXAMPLE),
|
| 63 |
+
("events", "Events", ["Trigger", "Type", "Start", "End", "Assertion status"], EVENT_EXAMPLE),
|
| 64 |
+
]:
|
| 65 |
+
with gr.Tab(heading):
|
| 66 |
+
passage = gr.Textbox(label="Source passage", lines=5, value=example)
|
| 67 |
+
inputs = [passage]
|
| 68 |
+
if task == "evidence":
|
| 69 |
+
inputs.append(gr.Textbox(label="Claim", value="The council has already voted."))
|
| 70 |
+
button = gr.Button("Check claim" if task == "evidence" else "Extract mentions", variant="primary")
|
| 71 |
+
status = gr.Markdown()
|
| 72 |
+
source = gr.HTML()
|
| 73 |
+
table = gr.Dataframe(headers=columns, interactive=False)
|
| 74 |
+
result = gr.JSON(label="Response JSON")
|
| 75 |
+
download = gr.Button("Download JSON")
|
| 76 |
+
button.click(partial(submit, task), inputs, [status, source, table, result],
|
| 77 |
+
concurrency_limit=1, concurrency_id="inference")
|
| 78 |
+
download.click(None, result, None, js="""
|
| 79 |
+
(payload) => {
|
| 80 |
+
if (!payload) return;
|
| 81 |
+
const data = typeof payload === "string" ? payload : JSON.stringify(payload, null, 2);
|
| 82 |
+
const url = URL.createObjectURL(new Blob([data], {type: 'application/json'}));
|
| 83 |
+
const link = document.createElement('a');
|
| 84 |
+
link.href = url;
|
| 85 |
+
link.download = 'tacitus-response.json';
|
| 86 |
+
link.click();
|
| 87 |
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
| 88 |
+
}
|
| 89 |
+
""")
|
| 90 |
+
return demo
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
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}")
|
toolkit/baseline-results.json
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"evidence": {
|
| 3 |
+
"task": "evidence",
|
| 4 |
+
"schema_version": "0.1.0",
|
| 5 |
+
"preprocessing_revision": "0.1.0",
|
| 6 |
+
"document_id": "ebee7ded136124e6bbb3829bd0604cdd5c8fb667a0fa7891634ed24f2a807181",
|
| 7 |
+
"text_sha256": "ebee7ded136124e6bbb3829bd0604cdd5c8fb667a0fa7891634ed24f2a807181",
|
| 8 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
| 9 |
+
"model_revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 10 |
+
"warnings": [
|
| 11 |
+
"Uncalibrated upstream baseline."
|
| 12 |
+
],
|
| 13 |
+
"claim_sha256": "d80139c843f89b294a60132ea9ac0ab4c33bab814081280a56eee102a80b3704",
|
| 14 |
+
"verdict": "contradicted",
|
| 15 |
+
"scores": {
|
| 16 |
+
"supported": 0.00034367493935860693,
|
| 17 |
+
"insufficient_information": 0.0013294948730617762,
|
| 18 |
+
"contradicted": 0.99832683801651
|
| 19 |
+
},
|
| 20 |
+
"review_required": true,
|
| 21 |
+
"review_reason": "Baseline lacks domain calibration."
|
| 22 |
+
},
|
| 23 |
+
"actors": {
|
| 24 |
+
"task": "actors",
|
| 25 |
+
"schema_version": "0.1.0",
|
| 26 |
+
"preprocessing_revision": "0.1.0",
|
| 27 |
+
"document_id": "ebee7ded136124e6bbb3829bd0604cdd5c8fb667a0fa7891634ed24f2a807181",
|
| 28 |
+
"text_sha256": "ebee7ded136124e6bbb3829bd0604cdd5c8fb667a0fa7891634ed24f2a807181",
|
| 29 |
+
"model_id": "fastino/gliner2.5-base-v1",
|
| 30 |
+
"model_revision": "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c",
|
| 31 |
+
"warnings": [
|
| 32 |
+
"Zero-shot upstream baseline."
|
| 33 |
+
],
|
| 34 |
+
"mentions": [
|
| 35 |
+
{
|
| 36 |
+
"start": 0,
|
| 37 |
+
"end": 11,
|
| 38 |
+
"text": "Maya Torres",
|
| 39 |
+
"type": "politician",
|
| 40 |
+
"score": 0.9981634020805359,
|
| 41 |
+
"mention_id": "de9f3867d9f5496ced285067afe5e489bf5460fe9a492a6a7ba463c618a88b40",
|
| 42 |
+
"canonical_actor_id": null
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"start": 27,
|
| 46 |
+
"end": 38,
|
| 47 |
+
"text": "Northbridge",
|
| 48 |
+
"type": "geopolitical_location",
|
| 49 |
+
"score": 0.6417320370674133,
|
| 50 |
+
"mention_id": "beaaf4f102aece388bbfa6d57b6825179e7c8e5ee707a9f9647d913e7ce8897a",
|
| 51 |
+
"canonical_actor_id": null
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"start": 27,
|
| 55 |
+
"end": 51,
|
| 56 |
+
"text": "Northbridge City Council",
|
| 57 |
+
"type": "government_institution",
|
| 58 |
+
"score": 0.9966896772384644,
|
| 59 |
+
"mention_id": "da1d37384039bd5c19d2ba9837cf62909456d46e1ced01740fb6a7d404eebe63",
|
| 60 |
+
"canonical_actor_id": null
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"start": 81,
|
| 64 |
+
"end": 93,
|
| 65 |
+
"text": "Civic Ledger",
|
| 66 |
+
"type": "media_organization",
|
| 67 |
+
"score": 0.9732202887535095,
|
| 68 |
+
"mention_id": "43904d97874a58990419c8a0c1c984400bed7e581a5cdc264fe6561003b89125",
|
| 69 |
+
"canonical_actor_id": null
|
| 70 |
+
}
|
| 71 |
+
]
|
| 72 |
+
},
|
| 73 |
+
"events": {
|
| 74 |
+
"task": "events",
|
| 75 |
+
"schema_version": "0.1.0",
|
| 76 |
+
"preprocessing_revision": "0.1.0",
|
| 77 |
+
"document_id": "531c1440dbe55371f02228abe21460caf9d92ee7b7156ef7c6adb51a0515f7ba",
|
| 78 |
+
"text_sha256": "531c1440dbe55371f02228abe21460caf9d92ee7b7156ef7c6adb51a0515f7ba",
|
| 79 |
+
"model_id": "fastino/gliner2.5-base-v1",
|
| 80 |
+
"model_revision": "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c",
|
| 81 |
+
"warnings": [
|
| 82 |
+
"Zero-shot trigger proposals. Assertion status has not been assessed.",
|
| 83 |
+
"Participant extraction requires a per-event role schema."
|
| 84 |
+
],
|
| 85 |
+
"events": [
|
| 86 |
+
{
|
| 87 |
+
"event_mention_id": "d6cf0d97b309c32711b11ec25511d7ae1a338d411fda471f9d1f04513295f977",
|
| 88 |
+
"event_type": "Request",
|
| 89 |
+
"trigger": {
|
| 90 |
+
"start": 31,
|
| 91 |
+
"end": 37,
|
| 92 |
+
"text": "agenda",
|
| 93 |
+
"type": "Request",
|
| 94 |
+
"score": 0.982642650604248
|
| 95 |
+
},
|
| 96 |
+
"assertion_status": "unknown",
|
| 97 |
+
"participants": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"event_mention_id": "53eb04400403e59bd3e277fc1c5e0d620dd2777f47049c8e5d198c46859cc0f5",
|
| 101 |
+
"event_type": "Arrest",
|
| 102 |
+
"trigger": {
|
| 103 |
+
"start": 62,
|
| 104 |
+
"end": 68,
|
| 105 |
+
"text": "Monday",
|
| 106 |
+
"type": "Arrest",
|
| 107 |
+
"score": 0.9338197112083435
|
| 108 |
+
},
|
| 109 |
+
"assertion_status": "unknown",
|
| 110 |
+
"participants": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"event_mention_id": "bc9a7cc9091d04735004315b9e7051ee75c1b6a0fb5656679150167cb2bab597",
|
| 114 |
+
"event_type": "Protest",
|
| 115 |
+
"trigger": {
|
| 116 |
+
"start": 62,
|
| 117 |
+
"end": 68,
|
| 118 |
+
"text": "Monday",
|
| 119 |
+
"type": "Protest",
|
| 120 |
+
"score": 0.774868369102478
|
| 121 |
+
},
|
| 122 |
+
"assertion_status": "unknown",
|
| 123 |
+
"participants": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"event_mention_id": "9b7abc4058c93495bf71df3e73076d9236c16a40f3882282340c79ff0170d5de",
|
| 127 |
+
"event_type": "Arrest",
|
| 128 |
+
"trigger": {
|
| 129 |
+
"start": 92,
|
| 130 |
+
"end": 101,
|
| 131 |
+
"text": "Wednesday",
|
| 132 |
+
"type": "Arrest",
|
| 133 |
+
"score": 0.9109458327293396
|
| 134 |
+
},
|
| 135 |
+
"assertion_status": "unknown",
|
| 136 |
+
"participants": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"event_mention_id": "f022fe37cb7f3a05d9c8564f376966291244fc16636365ea6ae3fc13e8cac5d8",
|
| 140 |
+
"event_type": "Protest",
|
| 141 |
+
"trigger": {
|
| 142 |
+
"start": 92,
|
| 143 |
+
"end": 101,
|
| 144 |
+
"text": "Wednesday",
|
| 145 |
+
"type": "Protest",
|
| 146 |
+
"score": 0.9368264079093933
|
| 147 |
+
},
|
| 148 |
+
"assertion_status": "unknown",
|
| 149 |
+
"participants": []
|
| 150 |
+
}
|
| 151 |
+
]
|
| 152 |
+
}
|
| 153 |
+
}
|
toolkit/challenge-evaluation.json
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"evidence": {
|
| 3 |
+
"cases": 36,
|
| 4 |
+
"browser": {
|
| 5 |
+
"macro_f1": 0.31145431145431146,
|
| 6 |
+
"correct": 14
|
| 7 |
+
},
|
| 8 |
+
"unchanged_baseline": {
|
| 9 |
+
"macro_f1": 0.9721739130434782,
|
| 10 |
+
"correct": 35
|
| 11 |
+
}
|
| 12 |
+
},
|
| 13 |
+
"actors": {
|
| 14 |
+
"cases": 10,
|
| 15 |
+
"browser": {
|
| 16 |
+
"micro": {
|
| 17 |
+
"precision": 0.25,
|
| 18 |
+
"recall": 0.2222222222222222,
|
| 19 |
+
"f1": 0.23529411764705882,
|
| 20 |
+
"support": 18,
|
| 21 |
+
"predictions": 16
|
| 22 |
+
},
|
| 23 |
+
"per_type": {
|
| 24 |
+
"company": {
|
| 25 |
+
"precision": 0.0,
|
| 26 |
+
"recall": 0.0,
|
| 27 |
+
"f1": 0.0,
|
| 28 |
+
"support": 2,
|
| 29 |
+
"predictions": 2
|
| 30 |
+
},
|
| 31 |
+
"geopolitical_location": {
|
| 32 |
+
"precision": 0.5,
|
| 33 |
+
"recall": 0.6666666666666666,
|
| 34 |
+
"f1": 0.5714285714285714,
|
| 35 |
+
"support": 3,
|
| 36 |
+
"predictions": 4
|
| 37 |
+
},
|
| 38 |
+
"government_institution": {
|
| 39 |
+
"precision": 0.0,
|
| 40 |
+
"recall": 0.0,
|
| 41 |
+
"f1": 0.0,
|
| 42 |
+
"support": 3,
|
| 43 |
+
"predictions": 0
|
| 44 |
+
},
|
| 45 |
+
"media_organization": {
|
| 46 |
+
"precision": 0.0,
|
| 47 |
+
"recall": 0.0,
|
| 48 |
+
"f1": 0.0,
|
| 49 |
+
"support": 2,
|
| 50 |
+
"predictions": 0
|
| 51 |
+
},
|
| 52 |
+
"military_person": {
|
| 53 |
+
"precision": 0.0,
|
| 54 |
+
"recall": 0.0,
|
| 55 |
+
"f1": 0.0,
|
| 56 |
+
"support": 1,
|
| 57 |
+
"predictions": 0
|
| 58 |
+
},
|
| 59 |
+
"other_organization": {
|
| 60 |
+
"precision": 0.25,
|
| 61 |
+
"recall": 1.0,
|
| 62 |
+
"f1": 0.4,
|
| 63 |
+
"support": 2,
|
| 64 |
+
"predictions": 8
|
| 65 |
+
},
|
| 66 |
+
"political_party": {
|
| 67 |
+
"precision": 0.0,
|
| 68 |
+
"recall": 0.0,
|
| 69 |
+
"f1": 0.0,
|
| 70 |
+
"support": 2,
|
| 71 |
+
"predictions": 2
|
| 72 |
+
},
|
| 73 |
+
"politician": {
|
| 74 |
+
"precision": 0.0,
|
| 75 |
+
"recall": 0.0,
|
| 76 |
+
"f1": 0.0,
|
| 77 |
+
"support": 3,
|
| 78 |
+
"predictions": 0
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
},
|
| 82 |
+
"unchanged_baseline": {
|
| 83 |
+
"micro": {
|
| 84 |
+
"precision": 0.75,
|
| 85 |
+
"recall": 0.8333333333333334,
|
| 86 |
+
"f1": 0.7894736842105263,
|
| 87 |
+
"support": 18,
|
| 88 |
+
"predictions": 20
|
| 89 |
+
},
|
| 90 |
+
"per_type": {
|
| 91 |
+
"company": {
|
| 92 |
+
"precision": 1.0,
|
| 93 |
+
"recall": 1.0,
|
| 94 |
+
"f1": 1.0,
|
| 95 |
+
"support": 2,
|
| 96 |
+
"predictions": 2
|
| 97 |
+
},
|
| 98 |
+
"geopolitical_location": {
|
| 99 |
+
"precision": 0.75,
|
| 100 |
+
"recall": 1.0,
|
| 101 |
+
"f1": 0.8571428571428571,
|
| 102 |
+
"support": 3,
|
| 103 |
+
"predictions": 4
|
| 104 |
+
},
|
| 105 |
+
"government_institution": {
|
| 106 |
+
"precision": 0.6,
|
| 107 |
+
"recall": 1.0,
|
| 108 |
+
"f1": 0.75,
|
| 109 |
+
"support": 3,
|
| 110 |
+
"predictions": 5
|
| 111 |
+
},
|
| 112 |
+
"media_organization": {
|
| 113 |
+
"precision": 1.0,
|
| 114 |
+
"recall": 1.0,
|
| 115 |
+
"f1": 1.0,
|
| 116 |
+
"support": 2,
|
| 117 |
+
"predictions": 2
|
| 118 |
+
},
|
| 119 |
+
"military_person": {
|
| 120 |
+
"precision": 1.0,
|
| 121 |
+
"recall": 1.0,
|
| 122 |
+
"f1": 1.0,
|
| 123 |
+
"support": 1,
|
| 124 |
+
"predictions": 1
|
| 125 |
+
},
|
| 126 |
+
"other_organization": {
|
| 127 |
+
"precision": 0.0,
|
| 128 |
+
"recall": 0.0,
|
| 129 |
+
"f1": 0.0,
|
| 130 |
+
"support": 2,
|
| 131 |
+
"predictions": 0
|
| 132 |
+
},
|
| 133 |
+
"political_party": {
|
| 134 |
+
"precision": 0.5,
|
| 135 |
+
"recall": 0.5,
|
| 136 |
+
"f1": 0.5,
|
| 137 |
+
"support": 2,
|
| 138 |
+
"predictions": 2
|
| 139 |
+
},
|
| 140 |
+
"politician": {
|
| 141 |
+
"precision": 0.75,
|
| 142 |
+
"recall": 1.0,
|
| 143 |
+
"f1": 0.8571428571428571,
|
| 144 |
+
"support": 3,
|
| 145 |
+
"predictions": 4
|
| 146 |
+
}
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
},
|
| 150 |
+
"events": {
|
| 151 |
+
"cases": 10,
|
| 152 |
+
"browser_all_types": {
|
| 153 |
+
"micro": {
|
| 154 |
+
"precision": 0.75,
|
| 155 |
+
"recall": 0.6666666666666666,
|
| 156 |
+
"f1": 0.7058823529411765,
|
| 157 |
+
"support": 9,
|
| 158 |
+
"predictions": 8
|
| 159 |
+
},
|
| 160 |
+
"per_type": {
|
| 161 |
+
"Arrest": {
|
| 162 |
+
"precision": 1.0,
|
| 163 |
+
"recall": 1.0,
|
| 164 |
+
"f1": 1.0,
|
| 165 |
+
"support": 1,
|
| 166 |
+
"predictions": 1
|
| 167 |
+
},
|
| 168 |
+
"Attack": {
|
| 169 |
+
"precision": 1.0,
|
| 170 |
+
"recall": 1.0,
|
| 171 |
+
"f1": 1.0,
|
| 172 |
+
"support": 1,
|
| 173 |
+
"predictions": 1
|
| 174 |
+
},
|
| 175 |
+
"Military_operation": {
|
| 176 |
+
"precision": 0.0,
|
| 177 |
+
"recall": 0.0,
|
| 178 |
+
"f1": 0.0,
|
| 179 |
+
"support": 1,
|
| 180 |
+
"predictions": 1
|
| 181 |
+
},
|
| 182 |
+
"Protest": {
|
| 183 |
+
"precision": 0.0,
|
| 184 |
+
"recall": 0.0,
|
| 185 |
+
"f1": 0.0,
|
| 186 |
+
"support": 2,
|
| 187 |
+
"predictions": 0
|
| 188 |
+
},
|
| 189 |
+
"Request": {
|
| 190 |
+
"precision": 1.0,
|
| 191 |
+
"recall": 1.0,
|
| 192 |
+
"f1": 1.0,
|
| 193 |
+
"support": 1,
|
| 194 |
+
"predictions": 1
|
| 195 |
+
},
|
| 196 |
+
"Sign_agreement": {
|
| 197 |
+
"precision": 1.0,
|
| 198 |
+
"recall": 1.0,
|
| 199 |
+
"f1": 1.0,
|
| 200 |
+
"support": 1,
|
| 201 |
+
"predictions": 1
|
| 202 |
+
},
|
| 203 |
+
"Supporting": {
|
| 204 |
+
"precision": 0.5,
|
| 205 |
+
"recall": 1.0,
|
| 206 |
+
"f1": 0.6666666666666666,
|
| 207 |
+
"support": 1,
|
| 208 |
+
"predictions": 2
|
| 209 |
+
},
|
| 210 |
+
"Surrendering": {
|
| 211 |
+
"precision": 1.0,
|
| 212 |
+
"recall": 1.0,
|
| 213 |
+
"f1": 1.0,
|
| 214 |
+
"support": 1,
|
| 215 |
+
"predictions": 1
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
},
|
| 219 |
+
"browser_four_types": {
|
| 220 |
+
"micro": {
|
| 221 |
+
"precision": 1.0,
|
| 222 |
+
"recall": 0.6,
|
| 223 |
+
"f1": 0.75,
|
| 224 |
+
"support": 5,
|
| 225 |
+
"predictions": 3
|
| 226 |
+
},
|
| 227 |
+
"per_type": {
|
| 228 |
+
"Arrest": {
|
| 229 |
+
"precision": 1.0,
|
| 230 |
+
"recall": 1.0,
|
| 231 |
+
"f1": 1.0,
|
| 232 |
+
"support": 1,
|
| 233 |
+
"predictions": 1
|
| 234 |
+
},
|
| 235 |
+
"Attack": {
|
| 236 |
+
"precision": 1.0,
|
| 237 |
+
"recall": 1.0,
|
| 238 |
+
"f1": 1.0,
|
| 239 |
+
"support": 1,
|
| 240 |
+
"predictions": 1
|
| 241 |
+
},
|
| 242 |
+
"Protest": {
|
| 243 |
+
"precision": 0.0,
|
| 244 |
+
"recall": 0.0,
|
| 245 |
+
"f1": 0.0,
|
| 246 |
+
"support": 2,
|
| 247 |
+
"predictions": 0
|
| 248 |
+
},
|
| 249 |
+
"Request": {
|
| 250 |
+
"precision": 1.0,
|
| 251 |
+
"recall": 1.0,
|
| 252 |
+
"f1": 1.0,
|
| 253 |
+
"support": 1,
|
| 254 |
+
"predictions": 1
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
},
|
| 258 |
+
"unchanged_baseline_four_types": {
|
| 259 |
+
"micro": {
|
| 260 |
+
"precision": 0.0,
|
| 261 |
+
"recall": 0.0,
|
| 262 |
+
"f1": 0.0,
|
| 263 |
+
"support": 5,
|
| 264 |
+
"predictions": 8
|
| 265 |
+
},
|
| 266 |
+
"per_type": {
|
| 267 |
+
"Arrest": {
|
| 268 |
+
"precision": 0.0,
|
| 269 |
+
"recall": 0.0,
|
| 270 |
+
"f1": 0.0,
|
| 271 |
+
"support": 1,
|
| 272 |
+
"predictions": 4
|
| 273 |
+
},
|
| 274 |
+
"Attack": {
|
| 275 |
+
"precision": 0.0,
|
| 276 |
+
"recall": 0.0,
|
| 277 |
+
"f1": 0.0,
|
| 278 |
+
"support": 1,
|
| 279 |
+
"predictions": 2
|
| 280 |
+
},
|
| 281 |
+
"Protest": {
|
| 282 |
+
"precision": 0.0,
|
| 283 |
+
"recall": 0.0,
|
| 284 |
+
"f1": 0.0,
|
| 285 |
+
"support": 2,
|
| 286 |
+
"predictions": 1
|
| 287 |
+
},
|
| 288 |
+
"Request": {
|
| 289 |
+
"precision": 0.0,
|
| 290 |
+
"recall": 0.0,
|
| 291 |
+
"f1": 0.0,
|
| 292 |
+
"support": 1,
|
| 293 |
+
"predictions": 1
|
| 294 |
+
}
|
| 295 |
+
}
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
}
|
toolkit/diagnostic-results.json
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"document_id": "vote-announcement",
|
| 4 |
+
"expected": "contradicted",
|
| 5 |
+
"nli": {
|
| 6 |
+
"task": "evidence",
|
| 7 |
+
"schema_version": "0.1.0",
|
| 8 |
+
"preprocessing_revision": "0.1.0",
|
| 9 |
+
"document_id": "vote-announcement",
|
| 10 |
+
"text_sha256": "4d5e88aa241b935ae98e2b5c501076d0768951c7f9ac0bf14a7566f3604d94f1",
|
| 11 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
| 12 |
+
"model_revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 13 |
+
"warnings": [
|
| 14 |
+
"Uncalibrated upstream baseline."
|
| 15 |
+
],
|
| 16 |
+
"claim_sha256": "d1033ddac06f584907f6688bf3e1d1f95d0c46259cdffc77d68778f5f415e68c",
|
| 17 |
+
"verdict": "contradicted",
|
| 18 |
+
"scores": {
|
| 19 |
+
"supported": 0.00021193583961576223,
|
| 20 |
+
"insufficient_information": 0.0004051684809383005,
|
| 21 |
+
"contradicted": 0.9993828535079956
|
| 22 |
+
},
|
| 23 |
+
"review_required": true,
|
| 24 |
+
"review_reason": "Baseline lacks domain calibration."
|
| 25 |
+
},
|
| 26 |
+
"doxa": {
|
| 27 |
+
"verdict": "contradicted",
|
| 28 |
+
"scores": {
|
| 29 |
+
"contradicted": 0.6800815925039535,
|
| 30 |
+
"insufficient_information": 0.11557525612509136,
|
| 31 |
+
"supported": 0.20434315137095513
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"document_id": "library-closure",
|
| 37 |
+
"expected": "supported",
|
| 38 |
+
"nli": {
|
| 39 |
+
"task": "evidence",
|
| 40 |
+
"schema_version": "0.1.0",
|
| 41 |
+
"preprocessing_revision": "0.1.0",
|
| 42 |
+
"document_id": "library-closure",
|
| 43 |
+
"text_sha256": "20b38ec64c8d08e5df724a9f25656cb418f6cb62439c40cf3c618c412263d87d",
|
| 44 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
| 45 |
+
"model_revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 46 |
+
"warnings": [
|
| 47 |
+
"Uncalibrated upstream baseline."
|
| 48 |
+
],
|
| 49 |
+
"claim_sha256": "75e759ec52ec33829ff542d501c22be3436f42e74ce71498d8685bffcf07300e",
|
| 50 |
+
"verdict": "supported",
|
| 51 |
+
"scores": {
|
| 52 |
+
"supported": 0.994953453540802,
|
| 53 |
+
"insufficient_information": 0.003200602252036333,
|
| 54 |
+
"contradicted": 0.0018458812264725566
|
| 55 |
+
},
|
| 56 |
+
"review_required": true,
|
| 57 |
+
"review_reason": "Baseline lacks domain calibration."
|
| 58 |
+
},
|
| 59 |
+
"doxa": {
|
| 60 |
+
"verdict": "supported",
|
| 61 |
+
"scores": {
|
| 62 |
+
"contradicted": 0.17314476012147764,
|
| 63 |
+
"insufficient_information": 0.010610988587761183,
|
| 64 |
+
"supported": 0.8162442512907612
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"document_id": "meeting-attendance",
|
| 70 |
+
"expected": "insufficient_information",
|
| 71 |
+
"nli": {
|
| 72 |
+
"task": "evidence",
|
| 73 |
+
"schema_version": "0.1.0",
|
| 74 |
+
"preprocessing_revision": "0.1.0",
|
| 75 |
+
"document_id": "meeting-attendance",
|
| 76 |
+
"text_sha256": "4a9ba4ce76f9a6db26d328c03c611ba9f6ac6943b9fd538e858bd0a15ec24399",
|
| 77 |
+
"model_id": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
| 78 |
+
"model_revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 79 |
+
"warnings": [
|
| 80 |
+
"Uncalibrated upstream baseline."
|
| 81 |
+
],
|
| 82 |
+
"claim_sha256": "0ab6d925618b2348b6e0fda077f1ab79f9b2c584a76462089001d9ddcc67bdb1",
|
| 83 |
+
"verdict": "insufficient_information",
|
| 84 |
+
"scores": {
|
| 85 |
+
"supported": 0.00015759607776999474,
|
| 86 |
+
"insufficient_information": 0.9995259046554565,
|
| 87 |
+
"contradicted": 0.00031648206640966237
|
| 88 |
+
},
|
| 89 |
+
"review_required": true,
|
| 90 |
+
"review_reason": "Baseline lacks domain calibration."
|
| 91 |
+
},
|
| 92 |
+
"doxa": {
|
| 93 |
+
"verdict": "insufficient_information",
|
| 94 |
+
"scores": {
|
| 95 |
+
"contradicted": 0.11439679241031989,
|
| 96 |
+
"insufficient_information": 0.7171925268203496,
|
| 97 |
+
"supported": 0.16841068076933047
|
| 98 |
+
}
|
| 99 |
+
}
|
| 100 |
+
}
|
| 101 |
+
]
|
toolkit/diagnostics.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run synthetic Evidence diagnostics and optionally compare with a reviewed DOXA checkout."""
|
| 2 |
+
import argparse
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from tacitus_nlp import Evidence
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def doxa_predictor(folder):
|
| 11 |
+
spec = importlib.util.spec_from_file_location("doxa_verifier", folder / "verifier.py")
|
| 12 |
+
module = importlib.util.module_from_spec(spec)
|
| 13 |
+
spec.loader.exec_module(module)
|
| 14 |
+
adapter = module.load_adapter(folder / "adapter.json")
|
| 15 |
+
encoder = module.FrozenEncoder()
|
| 16 |
+
|
| 17 |
+
def predict(text, claim):
|
| 18 |
+
raw = module.infer(text, claim, adapter, encoder)
|
| 19 |
+
neutral = {"insufficient_context": "insufficient_information"}
|
| 20 |
+
return {"verdict": neutral.get(raw["decision"], raw["decision"]),
|
| 21 |
+
"scores": {neutral.get(key, key): value for key, value in raw["scores"].items()}}
|
| 22 |
+
|
| 23 |
+
return predict
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def main():
|
| 27 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 28 |
+
parser.add_argument("--doxa-folder", type=Path, help="Local, reviewed verifier.py and adapter.json")
|
| 29 |
+
args = parser.parse_args()
|
| 30 |
+
engine = Evidence.from_pretrained()
|
| 31 |
+
doxa = doxa_predictor(args.doxa_folder) if args.doxa_folder else None
|
| 32 |
+
fixtures = Path(__file__).parent / "fixtures/evidence.jsonl"
|
| 33 |
+
results = []
|
| 34 |
+
for line in fixtures.read_text().splitlines():
|
| 35 |
+
row = json.loads(line)
|
| 36 |
+
nli = engine.check(passage=row["text"], claim=row["claim"], document_id=row["document_id"])
|
| 37 |
+
result = {"document_id": row["document_id"], "expected": row["label"], "nli": nli}
|
| 38 |
+
if doxa:
|
| 39 |
+
result["doxa"] = doxa(row["text"], row["claim"])
|
| 40 |
+
results.append(result)
|
| 41 |
+
print(json.dumps(results, indent=2))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
main()
|
toolkit/evidence-pilot-results.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"mode": "CPU compatibility smoke test on three synthetic rows",
|
| 3 |
+
"model_revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 4 |
+
"seed": 17,
|
| 5 |
+
"optimizer_steps": 1,
|
| 6 |
+
"initial_loss": 0.0020502773113548756,
|
| 7 |
+
"max_classifier_weight_delta": 0.00010003894567489624,
|
| 8 |
+
"same_logits_after_reload": true,
|
| 9 |
+
"label_mapping": {
|
| 10 |
+
"0": "supported",
|
| 11 |
+
"1": "insufficient_information",
|
| 12 |
+
"2": "contradicted"
|
| 13 |
+
}
|
| 14 |
+
}
|
toolkit/evidence_pilot.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train and reload a small CPU compatibility checkpoint on synthetic fixtures."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 8 |
+
|
| 9 |
+
from tacitus_nlp import Evidence
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def main():
|
| 13 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 14 |
+
parser.add_argument("output", type=Path)
|
| 15 |
+
args = parser.parse_args()
|
| 16 |
+
args.output.mkdir(parents=True, exist_ok=False)
|
| 17 |
+
torch.manual_seed(17)
|
| 18 |
+
engine = Evidence.from_pretrained()
|
| 19 |
+
model = engine.model
|
| 20 |
+
rows = [json.loads(line) for line in
|
| 21 |
+
(Path(__file__).parent / "fixtures/evidence.jsonl").read_text().splitlines()]
|
| 22 |
+
indexes = {label: i for i, label in engine.labels.items()}
|
| 23 |
+
batch = engine.tokenizer([row["text"] for row in rows], [row["claim"] for row in rows],
|
| 24 |
+
padding=True, return_tensors="pt")
|
| 25 |
+
targets = torch.tensor([indexes[row["label"]] for row in rows])
|
| 26 |
+
model.requires_grad_(False)
|
| 27 |
+
model.classifier.requires_grad_(True)
|
| 28 |
+
before = model.classifier.weight.detach().clone()
|
| 29 |
+
optimizer = torch.optim.AdamW(model.classifier.parameters(), lr=1e-4)
|
| 30 |
+
loss = model(**batch, labels=targets).loss
|
| 31 |
+
loss.backward()
|
| 32 |
+
optimizer.step()
|
| 33 |
+
delta = torch.max(torch.abs(before - model.classifier.weight)).item()
|
| 34 |
+
if delta <= 0:
|
| 35 |
+
raise RuntimeError("The classifier did not update.")
|
| 36 |
+
model.config.id2label = engine.labels
|
| 37 |
+
model.config.label2id = indexes
|
| 38 |
+
model.save_pretrained(args.output)
|
| 39 |
+
engine.tokenizer.save_pretrained(args.output)
|
| 40 |
+
restored = AutoModelForSequenceClassification.from_pretrained(args.output).eval()
|
| 41 |
+
tokenizer = AutoTokenizer.from_pretrained(args.output)
|
| 42 |
+
with torch.inference_mode():
|
| 43 |
+
tokens = tokenizer([row["text"] for row in rows], [row["claim"] for row in rows],
|
| 44 |
+
padding=True, return_tensors="pt")
|
| 45 |
+
torch.testing.assert_close(model(**batch).logits, restored(**tokens).logits)
|
| 46 |
+
if restored.config.id2label != engine.labels or restored.config.label2id != indexes:
|
| 47 |
+
raise RuntimeError("Label order changed during save/reload.")
|
| 48 |
+
report = {"mode": "CPU compatibility smoke test on three synthetic rows",
|
| 49 |
+
"model_revision": engine.source["revision"], "seed": 17, "optimizer_steps": 1,
|
| 50 |
+
"initial_loss": loss.item(), "max_classifier_weight_delta": delta,
|
| 51 |
+
"same_logits_after_reload": True, "label_mapping": engine.labels}
|
| 52 |
+
(args.output / "pilot-report.json").write_text(json.dumps(report, indent=2))
|
| 53 |
+
print(json.dumps(report, indent=2))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if __name__ == "__main__":
|
| 57 |
+
main()
|
toolkit/fixtures/evidence.jsonl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"document_id":"vote-announcement","text":"Northbridge City Council scheduled its budget vote for next Tuesday. The motion has not yet been voted on.","claim":"The council has already voted on the budget.","label":"contradicted","annotation_status":"synthetic_diagnostic"}
|
| 2 |
+
{"document_id":"library-closure","text":"The Juniper Library will close at noon on Friday for routine maintenance.","claim":"The Juniper Library will close at noon on Friday.","label":"supported","annotation_status":"synthetic_diagnostic"}
|
| 3 |
+
{"document_id":"meeting-attendance","text":"The Rivergate Planning Board met on Thursday to discuss the proposed map.","claim":"Twelve board members attended the meeting.","label":"insufficient_information","annotation_status":"synthetic_diagnostic"}
|
toolkit/release-versions.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"Giuliocc/tacitus-evidence-base": "26cd1e3b0042f1addb98a4fd7d48bf6fc43c9db6",
|
| 3 |
+
"Giuliocc/tacitus-actors-base": "7ad1387521881d6370dca40a4256da29a56156e0",
|
| 4 |
+
"Giuliocc/tacitus-events-base": "322c6018d0091f33bcf747515a50bcfd36d2ea18",
|
| 5 |
+
"Giuliocc/tacitus-evidence-data": "3aae027b50e21c2d88583e2172e8c32cefd8d7a8",
|
| 6 |
+
"Giuliocc/tacitus-actors-data": "cf0fe540ffe40b696baec9e9274d677ff85f29c3",
|
| 7 |
+
"Giuliocc/tacitus-events-data": "ba96a8ae34cd5a676ed3998c1f4acbd67b122b0c"
|
| 8 |
+
}
|
toolkit/requirements-research.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-r requirements.txt
|
| 2 |
+
scikit-learn==1.9.1
|
| 3 |
+
pyarrow==26.0.1
|
| 4 |
+
regex==2026.11.25
|
| 5 |
+
onnxruntime==1.32.0
|
toolkit/requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.8.0
|
| 2 |
+
transformers==4.57.6
|
| 3 |
+
gliner2==2.2.0
|
| 4 |
+
gradio==6.10.0
|
| 5 |
+
huggingface-hub==0.36.2
|
| 6 |
+
sentencepiece==0.2.3
|
| 7 |
+
protobuf==7.36.2
|
toolkit/research/REVIEW.md
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TACITUS v0.2.0 review
|
| 2 |
+
|
| 3 |
+
The development split selected features, thresholds, and margins. The final upstream test was used to report the quantized release models. Original civic examples provide a separate diagnostic exercise. They have no independent human review and are too small to establish domain quality.
|
| 4 |
+
|
| 5 |
+
## 1. Could repeated material inflate test results?
|
| 6 |
+
|
| 7 |
+
Yes. The first converter stopped at the first cross-split conflict and produced no complete audit. The release now keeps official partition precedence, removes conflicting groups and duplicate inputs, and publishes row manifests and exclusion counts. VitaminC checks page, case, FEVER identifier, normalized claim, and exact passage–claim hash. Few-NERD checks exact and normalized token sequences. Its public token version lacks article IDs, so the remaining possibility of article overlap is disclosed.
|
| 8 |
+
|
| 9 |
+
## 2. Does Evidence actually read its source?
|
| 10 |
+
|
| 11 |
+
The development macro-F1 of the claim-only ablation was 0.280, compared with 0.473 for the source-aware compact model. The source-aware model scored 0.479 on 54,668 test pairs. Temperature scaling and a development-selected review threshold yielded 14.4% coverage and 84.4% accepted accuracy on that test. The Space shows the score and a review flag and warns that the baseline is experimental. Calibration on VitaminC does not establish calibration for TACITUS source material.
|
| 12 |
+
|
| 13 |
+
## 3. Is the Evidence browser model sufficient for harder cases?
|
| 14 |
+
|
| 15 |
+
No. Its civic diagnostic score is substantially lower than the untouched DeBERTa baseline. The CPU neural adapter instead uses frozen quantized NLI scores with a learned head. On a matched sample of 1,400 VitaminC test pairs, its macro-F1 was 0.581, compared with 0.564 for unchanged DOXA and 0.518 for the untouched small encoder. The head and CPU loader are released separately from the browser model. This test supports evaluating the neural adapter further. Independent and broader domain testing is still needed.
|
| 16 |
+
|
| 17 |
+
## 4. Are actor boundaries reliable?
|
| 18 |
+
|
| 19 |
+
Context and BIO tags increased exact-span development F1 from 0.229 for token identity to 0.423. The quantized browser model scored 0.424 on test. Few-NERD offsets refer to source reconstructed with single spaces. The runtime retains original offsets on user text and uses Unicode code points. Python and browser logits were compared from the same quantized weights on accented and astral-character input. The untouched GLiNER baseline remains a stronger local option on the small civic diagnostic set.
|
| 20 |
+
|
| 21 |
+
## 5. Can Events identify what happened and who participated?
|
| 22 |
+
|
| 23 |
+
These models predict text mentions. Assertion status remains unknown, including reported and denied events. Trigger micro-F1 rose from 0.600 for token identity to 0.631 with context on development and scored 0.655 on the internally held-out test subset. Participant F1 was 0.095 with gold triggers and 0.072 with predicted triggers. The browser therefore leaves participants off by default. Experimental participant proposals are constrained to observed type-specific roles and an exact ±90-token window around each trigger.
|
| 24 |
+
|
| 25 |
+
## 6. Can someone run or reproduce this release?
|
| 26 |
+
|
| 27 |
+
The Space now analyzes new passages entirely in the browser, with independently identified model revisions, exact source highlighting, and JSON download. It retains the earlier saved examples. Model and dataset repositories publish evaluation artifacts, named input revisions, source checksums, reconstruction instructions, and original diagnostic rows. No paid compute was used.
|
| 28 |
+
|
| 29 |
+
## Follow-on experiments
|
| 30 |
+
|
| 31 |
+
Collect independently reviewed English civic and conflict passages by document and scenario before claiming domain performance. Keep that test frozen. Compare a trainable Evidence encoder against the frozen neural head with paired uncertainty estimates. For Actors, fine-tune a contextual span encoder with target labels and compare against untouched GLiNER on the same grouped domain benchmark. For Events, prioritize trigger-conditioned structured candidate extraction and a confusion analysis by type before promoting participant roles. Benchmark one bounded GPU compatibility pilot only when GPU capacity and a spending cap are confirmed. Size subsequent runs from observed throughput and validate reload before release.
|
toolkit/research/challenge_eval.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Measure challenge cases for browser and unchanged upstream baselines."""
|
| 2 |
+
import collections
|
| 3 |
+
import json
|
| 4 |
+
import sys
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from scipy.special import softmax
|
| 8 |
+
from sklearn.metrics import f1_score
|
| 9 |
+
|
| 10 |
+
from research.event_pipeline import load, prediction
|
| 11 |
+
from research.features import tokenize, evidence_features
|
| 12 |
+
from research.train import features_matrix, logits, scores
|
| 13 |
+
from tacitus_nlp import Actors, Evidence, Events
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def evalu(task, model, weights, rows, baseline):
|
| 17 |
+
if task=="evidence":
|
| 18 |
+
labels=model["labels"]
|
| 19 |
+
gold,light,reference=[],[],[]
|
| 20 |
+
for row in rows:
|
| 21 |
+
gold.append(row["label"])
|
| 22 |
+
X,_=features_matrix([(evidence_features(row["text"],row["claim"],model["mode"]),labels[0])],labels)
|
| 23 |
+
index=softmax(logits(weights,X)[0]/model["temperature"]).argmax()
|
| 24 |
+
light.append(labels[index])
|
| 25 |
+
reference.append(baseline.check(passage=row["text"],claim=row["claim"])["verdict"])
|
| 26 |
+
return {name: {"macro_f1": f1_score(gold, pred, labels=labels, average="macro", zero_division=0),
|
| 27 |
+
"correct":sum(a==b for a,b in zip(gold,pred,strict=True))} for name,pred in
|
| 28 |
+
(("browser",light),("unchanged_baseline",reference))}
|
| 29 |
+
gold,light,reference = (collections.defaultdict(set) for _ in range(3))
|
| 30 |
+
for row in rows:
|
| 31 |
+
case=row["scenario_id"]
|
| 32 |
+
spans=(row["mentions"] if task=="actors" else
|
| 33 |
+
[{**event["trigger"],"type":event["event_type"]} for event in row["events"]])
|
| 34 |
+
for span in spans:
|
| 35 |
+
gold[span["type"]].add((case,span["start"],span["end"]))
|
| 36 |
+
for start,end,kind in prediction(tokenize(row["text"]),model,weights):
|
| 37 |
+
light[kind].add((case,start,end))
|
| 38 |
+
result=baseline.extract(row["text"])
|
| 39 |
+
spans=result["mentions"] if task=="actors" else [event["trigger"] for event in result["events"]]
|
| 40 |
+
for span in spans:
|
| 41 |
+
reference[span["type"]].add((case,span["start"],span["end"]))
|
| 42 |
+
if task=="events":
|
| 43 |
+
base_types={"Attack","Arrest","Protest","Request"}
|
| 44 |
+
selected={kind:items for kind,items in gold.items() if kind in base_types}
|
| 45 |
+
def common(data):
|
| 46 |
+
return collections.defaultdict(set,{kind:items for kind,items in data.items() if kind in base_types})
|
| 47 |
+
return {"browser_all_types":scores(light,gold),
|
| 48 |
+
"browser_four_types":scores(common(light),common(gold)),
|
| 49 |
+
"unchanged_baseline_four_types":scores(common(reference),common(selected))}
|
| 50 |
+
return {"browser":scores(light,gold),"unchanged_baseline":scores(reference,gold)}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
trained,challenges,out=map(Path,sys.argv[1:4])
|
| 55 |
+
report={}
|
| 56 |
+
for task,engine in (("evidence",Evidence),("actors",Actors),("events",Events)):
|
| 57 |
+
model,weights=load(trained/task/"model.json")
|
| 58 |
+
rows=[json.loads(line) for line in (challenges/f"{task}.jsonl").read_text().splitlines()]
|
| 59 |
+
report[task]={"cases":len(rows),**evalu(task,model,weights,rows,engine.from_pretrained())}
|
| 60 |
+
print(task,{key:value.get("micro",value) if isinstance(value,dict) else value
|
| 61 |
+
for key,value in report[task].items()},flush=True)
|
| 62 |
+
out.write_text(json.dumps(report,indent=2))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
if __name__=="__main__":
|
| 66 |
+
main()
|
toolkit/research/challenges.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Original civic-domain challenge examples with exact source spans."""
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
SCENARIOS = [
|
| 8 |
+
("northbridge-vote", "Northbridge City Council scheduled its budget vote for Tuesday. The motion has not yet been voted on.",
|
| 9 |
+
("The council scheduled a budget vote for Tuesday.", "The council has already voted on the budget.", "The proposal would increase library funding.")),
|
| 10 |
+
("riverside-count", "Riverside Clerk's Office confirmed that 42 ballots were accepted and another 11 were rejected.",
|
| 11 |
+
("The office accepted 42 ballots.", "The office accepted 11 ballots in total.", "The disputed ballots were mailed on Friday.")),
|
| 12 |
+
("oak-library", "The Oak Lane Library reopened at 9 a.m. on Monday and stayed open all day.",
|
| 13 |
+
("The Oak Lane Library reopened Monday morning.", "The Oak Lane Library remained closed on Monday.", "The reopening followed a six-week renovation.")),
|
| 14 |
+
("port-lease", "The Port Commission rejected a twelve-year lease. It approved a two-year extension to the existing agreement.",
|
| 15 |
+
("The commission approved a two-year extension.", "The commission approved the twelve-year lease.", "The extension includes a new cleanup provision.")),
|
| 16 |
+
("map-hearing", "The Planning Board postponed Friday's hearing. The minutes identify no replacement date.",
|
| 17 |
+
("Friday's hearing was postponed.", "Friday's hearing went ahead as scheduled.", "The next hearing will be on November 14.")),
|
| 18 |
+
("clinic-funding", "The committee authorized funding for the east clinic only. The west clinic's request was rejected.",
|
| 19 |
+
("The east clinic received authorization.", "The committee authorized the west clinic's request.", "The east clinic opens on April 6.")),
|
| 20 |
+
("meter-contract", "The Transit Authority said it might order new fare meters. Its board explicitly declined to approve a purchase.",
|
| 21 |
+
("The board declined to approve a purchase.", "The board approved the purchase of new fare meters.", "The preferred supplier is Alder Systems.")),
|
| 22 |
+
("festival", "The organizers cancelled the main concert but confirmed that three afternoon workshops would go ahead.",
|
| 23 |
+
("Three afternoon workshops were confirmed.", "The main concert will go ahead as planned.", "The workshops require advance registration.")),
|
| 24 |
+
("inspection", "The Landmark Office inspected all six buildings. It issued notices for two and found no issues in four.",
|
| 25 |
+
("The office issued two notices.", "The office issued six notices.", "The notices included a deadline of 30 days.")),
|
| 26 |
+
("council-report", "Chair Lena Ives said a consultant had recommended selling the building. The committee unanimously voted against selling it.",
|
| 27 |
+
("A consultant recommended selling the building.", "The committee voted to sell the building.", "The consultant charged 8,000 dollars.")),
|
| 28 |
+
("morning-route", "Route 24 no longer stops at Oak Square. The service still stops at Market Street on weekdays.",
|
| 29 |
+
("Route 24 serves Market Street on weekdays.", "Route 24 still stops at Oak Square.", "Route 24 serves Market Street on Saturday.")),
|
| 30 |
+
("union-statement", "The union said it would consider a revised proposal next week. Its statement explicitly denied announcing a strike.",
|
| 31 |
+
("The union denied announcing a strike.", "The union announced a strike.", "The revised proposal increases hourly pay.")),
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
ACTORS_CASES = [
|
| 35 |
+
("municipal", "🗳️ Mayor Elena Mora met officials from the Northbridge Planning Department.",
|
| 36 |
+
[("Elena Mora","politician"),("Northbridge Planning Department","government_institution")]),
|
| 37 |
+
("party-publisher", "The Cedar Reform Party told the Westbank Gazette that delegates would meet Sunday.",
|
| 38 |
+
[("Cedar Reform Party","political_party"),("Westbank Gazette","media_organization")]),
|
| 39 |
+
("civil-society", "The Riverside History Society and Alder Tools, Inc. opened a public exhibit.",
|
| 40 |
+
[("Riverside History Society","other_organization"),("Alder Tools, Inc.","company")]),
|
| 41 |
+
("military", "Colonel Omar Vidal of the Army met officials in San Telmo.",
|
| 42 |
+
[("Omar Vidal","military_person"),("San Telmo","geopolitical_location")]),
|
| 43 |
+
("accented", "Journalists at La Voz del Río spoke to Mayor Inés Álvarez in León.",
|
| 44 |
+
[("La Voz del Río","media_organization"),("Inés Álvarez","politician"),("León","geopolitical_location")]),
|
| 45 |
+
("long-agency", "The Office for Transit Safety and Public Infrastructure Oversight released the report.",
|
| 46 |
+
[("Office for Transit Safety and Public Infrastructure Oversight","government_institution")]),
|
| 47 |
+
("plain-negative", "A newspaper interviewed several elected officials in the capital.",
|
| 48 |
+
[]),
|
| 49 |
+
("company-agency", "The Department of Water Resources fined the firm Mossgate Glass Ltd.",
|
| 50 |
+
[("Department of Water Resources","government_institution"),("Mossgate Glass Ltd.","company")]),
|
| 51 |
+
("quoted-party", "“Our position is unchanged,” said River Alliance party leader Noah Ferra.",
|
| 52 |
+
[("River Alliance","political_party"),("Noah Ferra","politician")]),
|
| 53 |
+
("organization-location", "The Lirio Bird Club registered a chapter in Minas Gerais.",
|
| 54 |
+
[("Lirio Bird Club","other_organization"),("Minas Gerais","geopolitical_location")]),
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
EVENT_CASES = [
|
| 58 |
+
("repeated", "Residents protested on Monday and protested again on Wednesday.",
|
| 59 |
+
[("protested",0,"Protest",[("Residents","Agent")]),("protested",1,"Protest",[("Residents","Agent")])]),
|
| 60 |
+
("research-request", "The council requested that the clerk revise the report.",
|
| 61 |
+
[("requested",0,"Request",[("The council","Agent"),("the clerk","Patient"),("revise the report","Action")])]),
|
| 62 |
+
("denial", "The police denied that they arrested Riley.",
|
| 63 |
+
[("arrested",0,"Arrest",[("they","Agent"),("Riley","Patient")])]),
|
| 64 |
+
("signing", "The councils signed the River Charter in Brindle.",
|
| 65 |
+
[("signed",0,"Sign_agreement",[("The councils","Agent"),("the River Charter","Agreement"),("Brindle","Location")])]),
|
| 66 |
+
("support", "The committee supported the library's proposal.",
|
| 67 |
+
[("supported",0,"Supporting",[("The committee","Agent"),("the library","Patient")])]),
|
| 68 |
+
("surrender", "The garrison surrendered to the commander.",
|
| 69 |
+
[("surrendered",0,"Surrendering",[("The garrison","Agent"),("the commander","Patient")])]),
|
| 70 |
+
("attack-report", "Witnesses reported that the group attacked the outpost.",
|
| 71 |
+
[("attacked",0,"Attack",[("the group","Agent"),("the outpost","Patient")])]),
|
| 72 |
+
("military-mention", "The troops launched a military operation near the border.",
|
| 73 |
+
[("military operation",0,"Military_operation",[("The troops","Agent"),("the border","Location")])]),
|
| 74 |
+
("lookalikes", "The support beam was made of oak. The request form is stored in a drawer.",
|
| 75 |
+
[]),
|
| 76 |
+
("unrelated", "🔔 The library stayed open throughout the storm, though attendance was low.",
|
| 77 |
+
[]),
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def span(text, fragment, occurrence=0):
|
| 82 |
+
left=-1
|
| 83 |
+
for _ in range(occurrence+1):
|
| 84 |
+
left=text.index(fragment,left+1)
|
| 85 |
+
return {"text":fragment, "start":left, "end":left+len(fragment)}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def examples():
|
| 89 |
+
common={"annotation_status":"author_created_diagnostic", "split":"challenge"}
|
| 90 |
+
return {
|
| 91 |
+
"evidence": [{**common, "scenario_id": name, "text": text, "claim": claim, "label": label}
|
| 92 |
+
for name,text, claims in SCENARIOS
|
| 93 |
+
for claim,label in zip(claims,("supported","contradicted","insufficient_information"),strict=True)],
|
| 94 |
+
"actors": [{**common,"scenario_id":name,"text":text,"mentions":[{**span(text,fragment),"type":label}
|
| 95 |
+
for fragment,label in entities]} for name,text,entities in ACTORS_CASES],
|
| 96 |
+
"events": [{**common,"scenario_id":name,"text":text,"events":[
|
| 97 |
+
{"trigger":span(text,fragment,nth),"event_type":label,
|
| 98 |
+
"participants":[{**span(text,argument),"role":role} for argument,role in roles]}
|
| 99 |
+
for fragment,nth,label,roles in events]} for name,text,events in EVENT_CASES],
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
if __name__=="__main__":
|
| 104 |
+
directory=Path(sys.argv[1])
|
| 105 |
+
directory.mkdir(parents=True,exist_ok=True)
|
| 106 |
+
for task,cases in examples().items():
|
| 107 |
+
(directory/f"{task}.jsonl").write_text("".join(json.dumps(case,ensure_ascii=False)+"\n" for case in cases))
|
toolkit/research/event_pipeline.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Benchmark experimental role predictions conditioned on detected triggers."""
|
| 2 |
+
import base64
|
| 3 |
+
import collections
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from research.features import token_features, tokenize
|
| 11 |
+
from research.train import features_matrix, logits, choose_tags, unpack, scores, read_rows
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def load(path):
|
| 15 |
+
model = json.loads(path.read_text())
|
| 16 |
+
weights = np.frombuffer(base64.b64decode(model["weights"]), dtype="<i2").reshape(-1, model["width"])
|
| 17 |
+
return model, (weights.astype("float32") * np.asarray(model["scale"], dtype="float32")[:, None],
|
| 18 |
+
np.asarray(model["bias"], dtype="float32"))
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def prediction(tokens, model, weights, anchor=None, event_type=None):
|
| 22 |
+
labels = model["labels"]
|
| 23 |
+
X, _ = features_matrix(((token_features(tokens, i, model["mode"], anchor, event_type), "O")
|
| 24 |
+
for i in range(len(tokens))), labels)
|
| 25 |
+
allowed = None if event_type is None else model["allowed_roles"].get(event_type, [])
|
| 26 |
+
return unpack(tokens, choose_tags(logits(weights,X),labels,model["negative_margin"],allowed))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def main():
|
| 30 |
+
root, trained = map(Path,sys.argv[1:3])
|
| 31 |
+
events,event_weights=load(trained/"events/model.json")
|
| 32 |
+
roles,role_weights=load(trained/"roles/model.json")
|
| 33 |
+
gold,predicted=collections.defaultdict(set),collections.defaultdict(set)
|
| 34 |
+
for row in read_rows(root,"events","test"):
|
| 35 |
+
tokens=tokenize(row["text"])
|
| 36 |
+
starts={token[1]: i for i,token in enumerate(tokens)}
|
| 37 |
+
doc=row["source_index"]
|
| 38 |
+
for event in row["events"]:
|
| 39 |
+
trigger=event["trigger"]
|
| 40 |
+
anchor=(trigger["start"],trigger["end"],event["event_type"])
|
| 41 |
+
for participant in event["participants"]:
|
| 42 |
+
gold[participant["role"]].add((doc,anchor,participant["start"],participant["end"]))
|
| 43 |
+
for trigger in prediction(tokens,events,event_weights):
|
| 44 |
+
start,_,event_type=trigger
|
| 45 |
+
anchor=starts[start]
|
| 46 |
+
window=roles["window_tokens"]
|
| 47 |
+
left=max(0,anchor-window)
|
| 48 |
+
for start,end,role in prediction(tokens[left:anchor+window+1],roles,role_weights,anchor-left,event_type):
|
| 49 |
+
predicted[role].add((doc,trigger,start,end))
|
| 50 |
+
report={"evaluation":"Exact document, trigger span and type, and participant span and role",**scores(predicted,gold)}
|
| 51 |
+
(trained/"events/pipeline-evaluation.json").write_text(json.dumps(report,indent=2))
|
| 52 |
+
print(report["micro"])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
if __name__=="__main__":
|
| 56 |
+
main()
|
toolkit/research/features.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Features shared with the browser runtime through parity fixtures."""
|
| 2 |
+
import math
|
| 3 |
+
import zlib
|
| 4 |
+
|
| 5 |
+
import regex
|
| 6 |
+
|
| 7 |
+
WIDTH = 32768
|
| 8 |
+
PATTERN = regex.compile(r"[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*|\p{N}+(?:[.,]\p{N}+)*|[^\s]")
|
| 9 |
+
NUMBER = regex.compile(r"^\p{N}+(?:[.,]\p{N}+)*$")
|
| 10 |
+
NEGATION = frozenset(("no", "not", "never", "neither", "without", "cannot", "denied", "deny"))
|
| 11 |
+
MODAL = frozenset(("will", "would", "might", "could", "plans", "planned", "scheduled", "proposed"))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def tokenize(text):
|
| 15 |
+
return [(m.group(), m.start(), m.end()) for m in PATTERN.finditer(text)]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def evidence_features(text, claim, mode):
|
| 19 |
+
passage = [word.lower() for word, *_ in tokenize(text)]
|
| 20 |
+
hypothesis = [word.lower() for word, *_ in tokenize(claim)]
|
| 21 |
+
terms, requested = set(passage), set(hypothesis)
|
| 22 |
+
features = [(f"h:{word}", .25) for word in sorted(requested)]
|
| 23 |
+
if mode == "hypothesis":
|
| 24 |
+
return features
|
| 25 |
+
overlap = terms & requested
|
| 26 |
+
span = set(zip(passage, passage[1:]))
|
| 27 |
+
pair = set(zip(hypothesis, hypothesis[1:]))
|
| 28 |
+
numeric = {word for word in requested if NUMBER.fullmatch(word)}
|
| 29 |
+
numeric_source = {word for word in terms if NUMBER.fullmatch(word)}
|
| 30 |
+
ratios = {"recall": len(overlap) / max(1, len(requested)),
|
| 31 |
+
"bigram": len(span & pair) / max(1, len(pair)),
|
| 32 |
+
"numbers": len(numeric & numeric_source) / max(1, len(numeric))}
|
| 33 |
+
for name, value in ratios.items():
|
| 34 |
+
features += [(f"val:{name}", value), (f"bin:{name}:{math.floor(value * 10)}", 1.)]
|
| 35 |
+
for name, words in (("neg", NEGATION), ("modal", MODAL)):
|
| 36 |
+
features.append((f"{name}:{int(bool(words & terms))}:{int(bool(words & requested))}", 1.))
|
| 37 |
+
features += [(f"{'match' if word in terms else 'missing'}:{word}", .5) for word in sorted(requested)]
|
| 38 |
+
features += [(f"numbers-exact:{int(bool(numeric))}:{int(numeric <= numeric_source)}", 1.)]
|
| 39 |
+
features += [(f"length:{min(len(passage) // 25, 12)}:{min(len(hypothesis) // 5, 10)}", 1.)]
|
| 40 |
+
return features
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def token_features(tokens, i, mode, anchor=None, event_type=None):
|
| 44 |
+
word = tokens[i][0]
|
| 45 |
+
lower = word.lower()
|
| 46 |
+
values = [(f"w:{lower}", 1.)]
|
| 47 |
+
if mode == "lexical":
|
| 48 |
+
return values
|
| 49 |
+
shape = "upper" if word.upper() == word and word.lower() != word else (
|
| 50 |
+
"title" if word[0].upper() == word[0] and word[0].lower() != word[0] else
|
| 51 |
+
"number" if NUMBER.fullmatch(word) else "other")
|
| 52 |
+
values.extend(((f"shape:{shape}", 1.), (f"length:{min(len(word), 12)}", .5)))
|
| 53 |
+
for length in (2, 3, 4):
|
| 54 |
+
if len(lower) >= length:
|
| 55 |
+
values.extend(((f"pre:{lower[:length]}", .5), (f"suf:{lower[-length:]}", .5)))
|
| 56 |
+
for offset in (-2, -1, 1, 2):
|
| 57 |
+
index = i + offset
|
| 58 |
+
other = tokens[index][0].lower() if 0 <= index < len(tokens) else ("<start>" if index < 0 else "<end>")
|
| 59 |
+
values.append((f"ctx:{offset}:{other}", .65))
|
| 60 |
+
if abs(offset) == 1:
|
| 61 |
+
values.append((f"pair:{offset}:{lower}:{other}", .5))
|
| 62 |
+
if anchor is not None:
|
| 63 |
+
distance = i - anchor
|
| 64 |
+
bucket = min(abs(distance), 12) if abs(distance) <= 12 else 13 + min(abs(distance) // 20, 5)
|
| 65 |
+
direction = -1 if distance < 0 else 1
|
| 66 |
+
values += [(f"event:{event_type}", 1.), (f"dist:{bucket * direction}", 1.),
|
| 67 |
+
(f"role:{event_type}:{bucket * direction}", 1.),
|
| 68 |
+
(f"anchor:{tokens[anchor][0].lower()}:{bucket * direction}", .65),
|
| 69 |
+
(f"eventword:{event_type}:{lower}", .8)]
|
| 70 |
+
return values
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def encode(features):
|
| 74 |
+
values = {}
|
| 75 |
+
for name, value in features:
|
| 76 |
+
feature_hash = zlib.crc32(name.encode("utf-8"))
|
| 77 |
+
column = feature_hash % WIDTH
|
| 78 |
+
values[column] = values.get(column, 0.) + (-value if feature_hash & 0x80000000 else value)
|
| 79 |
+
return values
|
toolkit/research/neural_evidence.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fit a CPU neural-feature candidate against DOXA on the same held-out pairs."""
|
| 2 |
+
import argparse
|
| 3 |
+
import importlib.util
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
from scipy.optimize import minimize_scalar
|
| 9 |
+
from scipy.special import softmax
|
| 10 |
+
from sklearn.linear_model import LogisticRegression
|
| 11 |
+
from sklearn.metrics import f1_score, log_loss
|
| 12 |
+
from sklearn.pipeline import make_pipeline
|
| 13 |
+
from sklearn.preprocessing import StandardScaler
|
| 14 |
+
|
| 15 |
+
from research.train import evidence_metrics, keep, rows
|
| 16 |
+
|
| 17 |
+
LABELS = ("supported", "contradicted", "insufficient_information")
|
| 18 |
+
SIZES = {"train": 3800, "validation": 1000, "test": 1400}
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_verifier(folder):
|
| 22 |
+
spec = importlib.util.spec_from_file_location("doxa_verifier", folder / "verifier.py")
|
| 23 |
+
module = importlib.util.module_from_spec(spec)
|
| 24 |
+
spec.loader.exec_module(module)
|
| 25 |
+
return module
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def selection(root, split):
|
| 29 |
+
# Deterministic pseudo-random sampling restricted to the matching audited partition.
|
| 30 |
+
return sorted((row for row in rows(root, split) if keep(row["input_sha256"] + ":neural", .08)),
|
| 31 |
+
key=lambda row: row["input_sha256"])[:SIZES[split]]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def matrices(verifier, encoder, examples, cache, split):
|
| 35 |
+
if cache.exists():
|
| 36 |
+
cached = np.load(cache, allow_pickle=False)
|
| 37 |
+
if list(cached["identifiers"]) == [row["input_sha256"] for row in examples]:
|
| 38 |
+
return cached["features"], cached["labels"]
|
| 39 |
+
pairs = [(row["text"], row["claim"]) for row in examples]
|
| 40 |
+
columns = []
|
| 41 |
+
for start in range(0, len(pairs), 64):
|
| 42 |
+
batch = pairs[start:start+64]
|
| 43 |
+
logits, _ = encoder.logits(batch,batch_size=8)
|
| 44 |
+
columns.append(verifier.adapter_features(logits,batch))
|
| 45 |
+
if start % 512 == 0:
|
| 46 |
+
print(split, start, len(pairs), flush=True)
|
| 47 |
+
X = np.vstack(columns)
|
| 48 |
+
y = np.asarray([LABELS.index(row["label"]) for row in examples])
|
| 49 |
+
np.savez(cache, features=X, labels=y, identifiers=[row["input_sha256"] for row in examples])
|
| 50 |
+
return X, y
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def main():
|
| 54 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 55 |
+
parser.add_argument("processed",type=Path)
|
| 56 |
+
parser.add_argument("doxa",type=Path)
|
| 57 |
+
parser.add_argument("output",type=Path)
|
| 58 |
+
args=parser.parse_args()
|
| 59 |
+
args.output.mkdir(parents=True,exist_ok=True)
|
| 60 |
+
verifier=load_verifier(args.doxa)
|
| 61 |
+
encoder=verifier.FrozenEncoder(threads=3)
|
| 62 |
+
matrices_by_split={}
|
| 63 |
+
for split in SIZES:
|
| 64 |
+
examples=selection(args.processed,split)
|
| 65 |
+
cache=args.output / f"{split}-feature-cache.npz"
|
| 66 |
+
matrices_by_split[split]=matrices(verifier,encoder,examples,cache,split)
|
| 67 |
+
print(split, "features ready",flush=True)
|
| 68 |
+
model=make_pipeline(StandardScaler(),LogisticRegression(max_iter=300,random_state=1729))
|
| 69 |
+
model.fit(*matrices_by_split["train"])
|
| 70 |
+
dev_X,dev_y=matrices_by_split["validation"]
|
| 71 |
+
dev_logits=model.decision_function(dev_X)
|
| 72 |
+
tau=float(np.exp(minimize_scalar(lambda log_t:log_loss(dev_y,softmax(dev_logits/np.exp(log_t),axis=1)),
|
| 73 |
+
bounds=(-2.,3.),method="bounded").x))
|
| 74 |
+
confidence=softmax(dev_logits/tau,axis=1)
|
| 75 |
+
threshold=1.01
|
| 76 |
+
for value in np.arange(.45,.991,.01):
|
| 77 |
+
mask=confidence.max(axis=1)>=value
|
| 78 |
+
if mask.sum()>=60 and (confidence[mask].argmax(axis=1)==dev_y[mask]).mean()>=.8:
|
| 79 |
+
threshold=float(value)
|
| 80 |
+
break
|
| 81 |
+
test_X,test_y=matrices_by_split["test"]
|
| 82 |
+
old=verifier.load_adapter(args.doxa/"adapter.json")
|
| 83 |
+
raw_doxa=verifier.classify(old,test_X)
|
| 84 |
+
ordered=[old["classes"].index(label) for label in
|
| 85 |
+
("supported","contradicted","insufficient_context")]
|
| 86 |
+
doxa=np.log(np.clip(raw_doxa[:,ordered],1e-12,1))
|
| 87 |
+
nli=test_X[:,:3]
|
| 88 |
+
test_values=model.decision_function(test_X)
|
| 89 |
+
(args.output/"neural-evaluation.json").write_text(json.dumps({
|
| 90 |
+
"selection": "deterministic hash sample on separately audited VitaminC partitions",
|
| 91 |
+
"splits": SIZES, "development":evidence_metrics(dev_logits,dev_y,list(LABELS),tau,threshold),
|
| 92 |
+
"test":{"candidate":evidence_metrics(test_values,test_y,list(LABELS),tau,threshold),
|
| 93 |
+
"unchanged_doxa_macro_f1":f1_score(test_y,doxa.argmax(axis=1),average="macro"),
|
| 94 |
+
"untouched_backbone_macro_f1":f1_score(test_y,nli.argmax(axis=1),average="macro")},
|
| 95 |
+
"backbone_model":verifier.MODEL,"backbone_revision":verifier.REVISION,
|
| 96 |
+
},indent=2))
|
| 97 |
+
scaler,classifier=model.steps[0][1],model.steps[1][1]
|
| 98 |
+
adapter={"classes":list(LABELS),"features":list(verifier.FEATURES),"model_id":verifier.MODEL,
|
| 99 |
+
"backbone_revision":verifier.REVISION,"weights":verifier.WEIGHTS,
|
| 100 |
+
"mean":scaler.mean_.tolist(),"scale":scaler.scale_.tolist(),"coefficients":classifier.coef_.tolist(),
|
| 101 |
+
"intercept":classifier.intercept_.tolist(),"temperature":tau,"threshold":threshold}
|
| 102 |
+
expected=softmax(test_values/tau,axis=1)
|
| 103 |
+
actual=softmax(((test_X-scaler.mean_)/scaler.scale_ @ classifier.coef_.T+classifier.intercept_)/tau,axis=1)
|
| 104 |
+
np.testing.assert_allclose(actual,expected,rtol=1e-9,atol=1e-12)
|
| 105 |
+
(args.output/"neural-adapter.json").write_text(json.dumps(adapter,indent=2))
|
| 106 |
+
print("Neural adapter results ready",flush=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__=="__main__":
|
| 110 |
+
main()
|
toolkit/research/neural_infer.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the TACITUS neural adapter with a pinned frozen ONNX backbone."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
from verifier import FrozenEncoder, FEATURES, REVISION, adapter_features, softmax
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def predict(passage, claim, adapter, encoder):
|
| 12 |
+
if not passage.strip() or not claim.strip() or len(passage)>12000 or len(claim)>1500:
|
| 13 |
+
raise ValueError("Use a non-empty passage and claim within the documented character limits.")
|
| 14 |
+
if adapter["features"]!=list(FEATURES) or adapter["backbone_revision"]!=REVISION:
|
| 15 |
+
raise ValueError("Adapter and frozen encoder versions differ.")
|
| 16 |
+
pairs=[(passage,claim)]
|
| 17 |
+
values,windows=encoder.logits(pairs)
|
| 18 |
+
features=(adapter_features(values,pairs)-np.asarray(adapter["mean"]))/np.asarray(adapter["scale"])
|
| 19 |
+
logits=features@np.asarray(adapter["coefficients"]).T+np.asarray(adapter["intercept"])
|
| 20 |
+
probabilities=softmax(logits/adapter["temperature"])[0]
|
| 21 |
+
best=int(probabilities.argmax())
|
| 22 |
+
return {"verdict":adapter["classes"][best], "scores":dict(zip(adapter["classes"],probabilities.tolist(),strict=True)),
|
| 23 |
+
"review_required":bool(probabilities[best]<adapter["threshold"]),
|
| 24 |
+
"calibration_source":"audited VitaminC development sample","windows":windows[0]}
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 29 |
+
parser.add_argument("passage")
|
| 30 |
+
parser.add_argument("claim")
|
| 31 |
+
parser.add_argument("--adapter",type=Path,default=Path(__file__).with_name("neural-adapter.json"))
|
| 32 |
+
options=parser.parse_args()
|
| 33 |
+
adapter=json.loads(options.adapter.read_text())
|
| 34 |
+
print(json.dumps(predict(options.passage,options.claim,adapter,FrozenEncoder()),indent=2))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__=="__main__":
|
| 38 |
+
main()
|
toolkit/research/package_release.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Package model and dataset repositories without redistributing upstream text."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import shutil
|
| 5 |
+
import sys
|
| 6 |
+
from collections import Counter
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import pyarrow as pa
|
| 10 |
+
import pyarrow.parquet as pq
|
| 11 |
+
|
| 12 |
+
from research.train import choose_split, rows
|
| 13 |
+
|
| 14 |
+
TASKS = ("evidence","actors","events")
|
| 15 |
+
SOURCES = {
|
| 16 |
+
"evidence": ("VitaminC", "https://huggingface.co/datasets/tals/vitaminc",
|
| 17 |
+
"be6febb761b0b2807687e61e0b5282e459df2fa0", "CC BY-SA 3.0"),
|
| 18 |
+
"actors": ("Few-NERD supervised", "https://huggingface.co/datasets/DFKI-SLT/few-nerd",
|
| 19 |
+
"205f3e9c9f3577ea2561d43f2f62dc249ab92d5b", "CC BY-SA 4.0"),
|
| 20 |
+
"events": ("MAVEN-ARG v1.0", "https://github.com/THU-KEG/MAVEN-Argument",
|
| 21 |
+
"MAVEN-Arg.zip", "See upstream terms. Redistribution permission for source text was not established."),
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def read_json(path):
|
| 26 |
+
return json.loads(path.read_text())
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def checksum(path):
|
| 30 |
+
with path.open("rb") as stream:
|
| 31 |
+
return hashlib.file_digest(stream,"sha256").hexdigest()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def package_data(task, folder, processed, corpora, challenges):
|
| 35 |
+
data=folder/"data"
|
| 36 |
+
data.mkdir(parents=True,exist_ok=True)
|
| 37 |
+
source=processed/task
|
| 38 |
+
split_sizes=Counter()
|
| 39 |
+
upstream_source={"evidence":"vitamin","actors":"few","events":"maven"}[task]
|
| 40 |
+
in_files=sorted(path for path in (corpora/upstream_source).iterdir() if path.is_file() and path.suffix!=".md")
|
| 41 |
+
manifest_files={}
|
| 42 |
+
for split in ("train","validation","test"):
|
| 43 |
+
if task=="events" and split=="test":
|
| 44 |
+
continue
|
| 45 |
+
origin={row["source_index"]:choose_split(row) for row in rows(source,split)} if task=="events" and split=="validation" else None
|
| 46 |
+
manifest=source/f"{split}.manifest.jsonl"
|
| 47 |
+
with manifest.open() as stream:
|
| 48 |
+
for line in stream:
|
| 49 |
+
item=json.loads(line)
|
| 50 |
+
destination=origin[item["source_index"]] if origin is not None else split
|
| 51 |
+
item["source_split"] = (("valid" if task=="events" else "dev") if split=="validation" and task!="actors" else split)
|
| 52 |
+
item["split"]=destination
|
| 53 |
+
manifest_files.setdefault(destination,[]).append(item)
|
| 54 |
+
split_sizes[destination]+=1
|
| 55 |
+
for split,items in manifest_files.items():
|
| 56 |
+
pq.write_table(pa.Table.from_pylist(items),data/f"{split}.parquet",compression="zstd")
|
| 57 |
+
with (challenges/f"{task}.jsonl").open() as stream:
|
| 58 |
+
challenge=list(map(json.loads,stream))
|
| 59 |
+
pq.write_table(pa.Table.from_pylist(challenge),data/"challenge.parquet",compression="zstd")
|
| 60 |
+
name,url,revision,license_text=SOURCES[task]
|
| 61 |
+
provenance={"upstream":name,"url":url,"revision":revision,"terms":license_text,"input_sha256":
|
| 62 |
+
{path.name:checksum(path) for path in in_files},"published_manifest_rows":dict(split_sizes),
|
| 63 |
+
"challenge_rows":len(challenge),"source_index":"Zero-based input row order within source_split."}
|
| 64 |
+
(folder/"provenance.json").write_text(json.dumps(provenance,indent=2))
|
| 65 |
+
shutil.copy(source/"audit.json",folder/"audit.json")
|
| 66 |
+
shutil.copy(challenges/f"{task}.jsonl",folder/"challenge.jsonl")
|
| 67 |
+
counts=", ".join(f"{key} {value:,}" for key,value in sorted(split_sizes.items()))
|
| 68 |
+
notes={
|
| 69 |
+
"evidence":"Group checks cover wiki page, case, FEVER identifier, normalized claim and exact passage–claim hashes. The VitaminC canary is excluded. Released training sampled 72% deterministically from the audited train rows.",
|
| 70 |
+
"actors":"The supervised partition uses single-space token reconstruction. Group checks use normalized token sequences. Article identity is unavailable. Training retains all mentions and subsamples background sentences and tokens deterministically.",
|
| 71 |
+
"events":"All supported annotated train and validation documents passed span conversion. The official annotated validation file is divided by normalized title hash into development and test subsets. The official test file has withheld argument labels. Manifest rows include zero-target documents. Training role allowlists use observed nonempty roles per type, and preserve source event and entity mention identities during reconstruction.",
|
| 72 |
+
}[task]
|
| 73 |
+
(folder/"README.md").write_text(f"""---
|
| 74 |
+
language:
|
| 75 |
+
- en
|
| 76 |
+
license: other
|
| 77 |
+
pretty_name: TACITUS {task.title()} data
|
| 78 |
+
configs:
|
| 79 |
+
- config_name: reconstruction
|
| 80 |
+
default: true
|
| 81 |
+
data_files:
|
| 82 |
+
- split: train
|
| 83 |
+
path: data/train.parquet
|
| 84 |
+
- split: validation
|
| 85 |
+
path: data/validation.parquet
|
| 86 |
+
- split: test
|
| 87 |
+
path: data/test.parquet
|
| 88 |
+
- config_name: original_diagnostics
|
| 89 |
+
data_files:
|
| 90 |
+
- split: challenge
|
| 91 |
+
path: data/challenge.parquet
|
| 92 |
+
---
|
| 93 |
+
|
| 94 |
+
# TACITUS {task.title()} data
|
| 95 |
+
|
| 96 |
+
Release v0.2.0. Reconstruction manifests cover **{counts}** source records from [{name}]({url}). The original challenge configuration contains **{len(challenge)}** author-created civic-domain diagnostics with expected labels or exact source spans. These diagnostics have no independent human review and were kept separate from upstream training.
|
| 97 |
+
|
| 98 |
+
## Reconstruct and audit
|
| 99 |
+
|
| 100 |
+
Download the source files at the revision recorded in `provenance.json`, verify their SHA-256 hashes, and run `research/prepare.py` from the [Source Lab repository](https://huggingface.co/spaces/Giuliocc/tacitus-source-lab/tree/main/toolkit). Or use `source_split` and zero-based `source_index` to select rows from upstream. `input_sha256` hashes JSON with the reconstructed source and optional claim. Manifest rows include annotation counts and hashed provenance. They exclude upstream passages and individual annotations.
|
| 101 |
+
|
| 102 |
+
{notes}
|
| 103 |
+
|
| 104 |
+
Upstream terms are listed in `provenance.json`. See `audit.json` for exclusions and label counts. Do not use the challenge split as a validated domain benchmark.
|
| 105 |
+
""")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def package_model(task,folder,trained):
|
| 109 |
+
folder.mkdir(parents=True,exist_ok=True)
|
| 110 |
+
model=trained/task
|
| 111 |
+
for path in model.iterdir():
|
| 112 |
+
if path.is_file():
|
| 113 |
+
shutil.copy(path,folder/path.name)
|
| 114 |
+
report=read_json(model/"evaluation.json")
|
| 115 |
+
test=report["test"]
|
| 116 |
+
sources = {"evidence":"pipeline_tag: text-classification","actors":"pipeline_tag: token-classification",
|
| 117 |
+
"events":"pipeline_tag: token-classification"}
|
| 118 |
+
measure = f"Test macro-F1 {test['macro_f1']:.3f} on {test['rows']:,} audited VitaminC pairs. At the development-selected threshold, test coverage was {test['coverage']:.1%} and accepted accuracy was {test['accepted_accuracy']:.1%}." if task=="evidence" else (
|
| 119 |
+
f"Test exact span micro-F1 {test['micro']['f1']:.3f} over {test['micro']['support']:,} {('actor mentions' if task=='actors' else 'event triggers')}.")
|
| 120 |
+
extra=""
|
| 121 |
+
if task=="events":
|
| 122 |
+
shutil.copy(trained/"roles/model.json",folder/"roles.json")
|
| 123 |
+
shutil.copy(trained/"roles/evaluation.json",folder/"roles-evaluation.json")
|
| 124 |
+
role_report=read_json(trained/"roles/evaluation.json")["test"]["micro"]
|
| 125 |
+
pipeline=read_json(model/"pipeline-evaluation.json")["micro"]
|
| 126 |
+
extra=f"""
|
| 127 |
+
The role component uses a ±90-token trigger window and restricts output to observed per-type roles. Its exact-span micro-F1 is {role_report['f1']:.3f} with gold triggers and {pipeline['f1']:.3f} end-to-end. Participants are opt-in in the demo. Event assertion status is unknown. MAVEN-ARG's official labeled test remains unavailable. Our test partition is carved from its annotated development file before training.
|
| 128 |
+
"""
|
| 129 |
+
if task=="evidence" and (trained/"neural/neural-adapter.json").exists():
|
| 130 |
+
for name in ("neural-adapter.json","neural-evaluation.json"):
|
| 131 |
+
shutil.copy(trained/"neural"/name,folder/name)
|
| 132 |
+
neural=read_json(trained/"neural/neural-evaluation.json")["test"]
|
| 133 |
+
extra=f"""
|
| 134 |
+
The separately trained neural adapter reuses an unchanged quantized NLI encoder and fits only an adapter on 3,800 audited VitaminC pairs. Over a 1,400-pair matched test sample, macro-F1 was {neural['candidate']['macro_f1']:.3f} for the candidate, {neural['unchanged_doxa_macro_f1']:.3f} for unchanged DOXA, and {neural['untouched_backbone_macro_f1']:.3f} for the unchanged encoder. See `neural-evaluation.json` for calibration results. The browser Space uses the compact model. The neural adapter can run with the released CPU loader and its pinned upstream encoder.
|
| 135 |
+
"""
|
| 136 |
+
(folder/"README.md").write_text(f"""---
|
| 137 |
+
language:
|
| 138 |
+
- en
|
| 139 |
+
{sources[task]}
|
| 140 |
+
tags:
|
| 141 |
+
- tacitus
|
| 142 |
+
- browser-inference
|
| 143 |
+
- cpu
|
| 144 |
+
datasets:
|
| 145 |
+
- Giuliocc/tacitus-{task}-data
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
# TACITUS {task.title()} Baseline v0.2.0
|
| 149 |
+
|
| 150 |
+
{measure} The compact candidate uses a trained feature-hashed linear model with 16-bit weights and a CPU/browser runtime. The training used {report['training_instances']:,} examples or token instances per optimization pass. See `evaluation.json` for development candidate comparisons, test metrics, and per-class support.
|
| 151 |
+
{extra}
|
| 152 |
+
## Use
|
| 153 |
+
|
| 154 |
+
[TACITUS Source Lab](https://huggingface.co/spaces/Giuliocc/tacitus-source-lab) loads the model in your browser and analyzes new English passages locally. Download `model.json` for standalone use with `inference.js` in the Space source. The weight format is row-major signed little-endian int16 with per-row scales and bias. This format uses the provided runtime.
|
| 155 |
+
|
| 156 |
+
[source data and split audit](https://huggingface.co/datasets/Giuliocc/tacitus-{task}-data) · [training and evaluation code](https://huggingface.co/spaces/Giuliocc/tacitus-source-lab/tree/main/toolkit)
|
| 157 |
+
""")
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
if __name__=="__main__":
|
| 161 |
+
processed,corpora,challenges,trained,out=map(Path,sys.argv[1:6])
|
| 162 |
+
for task in TASKS:
|
| 163 |
+
package_data(task,out/f"{task}-data",processed,corpora,challenges)
|
| 164 |
+
package_model(task,out/f"{task}-base",trained)
|
toolkit/research/parity.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Generate numeric parity fixtures from the released weights."""
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from research.event_pipeline import load
|
| 7 |
+
from research.features import tokenize, evidence_features, token_features
|
| 8 |
+
from research.train import features_matrix, logits
|
| 9 |
+
|
| 10 |
+
root=Path(sys.argv[1])
|
| 11 |
+
text="🗳️ Inés Álvarez did not attend. She would appear later at Río’s office in León."
|
| 12 |
+
claim="Inés Álvarez attended."
|
| 13 |
+
tokens=tokenize(text)
|
| 14 |
+
checks=[]
|
| 15 |
+
for task in ("evidence","actors","events","roles"):
|
| 16 |
+
model,weights=load(root/task/"model.json")
|
| 17 |
+
args=[4,9,"Request"] if task=="roles" else [4,None,None]
|
| 18 |
+
features=evidence_features(text,claim,model["mode"]) if task=="evidence" else token_features(tokens,*args[:1],model["mode"],*args[1:])
|
| 19 |
+
X,_=features_matrix([(features,model["labels"][0])],model["labels"])
|
| 20 |
+
checks.append({"task":task,"text":text,"claim":claim,"tokenization":tokens,"args":args,
|
| 21 |
+
"logits":logits(weights,X)[0].tolist()})
|
| 22 |
+
print(json.dumps(checks,ensure_ascii=False))
|
toolkit/research/prepare.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build audited source manifests and private reconstruction rows."""
|
| 2 |
+
import collections
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
import zipfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import pyarrow.parquet as pq
|
| 11 |
+
|
| 12 |
+
from tacitus_nlp.data import few_nerd, maven, vitamin
|
| 13 |
+
|
| 14 |
+
ROOT = Path(sys.argv[1])
|
| 15 |
+
OUT = Path(sys.argv[2])
|
| 16 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 17 |
+
EVENT_TYPES = {
|
| 18 |
+
"Attack", "Arrest", "Protest", "Request", "Military_operation", "Sign_agreement", "Surrendering", "Supporting"
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def source_rows(task, split):
|
| 23 |
+
if task == "evidence":
|
| 24 |
+
name = ("dev" if split == "validation" else split) + ".jsonl"
|
| 25 |
+
with (ROOT / "vitamin" / name).open() as stream:
|
| 26 |
+
for line in stream:
|
| 27 |
+
yield json.loads(line), None
|
| 28 |
+
elif task == "actors":
|
| 29 |
+
file = pq.ParquetFile(ROOT / "few" / f"{split}.parquet")
|
| 30 |
+
descriptor = json.loads(file.schema_arrow.metadata[b"huggingface"])
|
| 31 |
+
names = descriptor["info"]["features"]["fine_ner_tags"]["feature"]["names"]
|
| 32 |
+
for batch in file.iter_batches(batch_size=4096):
|
| 33 |
+
for row in batch.to_pylist():
|
| 34 |
+
yield row, names
|
| 35 |
+
else:
|
| 36 |
+
name = ("valid" if split == "validation" else split) + ".jsonl"
|
| 37 |
+
with zipfile.ZipFile(ROOT / "maven" / "MAVEN-Arg.zip") as archive, archive.open(name) as stream:
|
| 38 |
+
for line in stream:
|
| 39 |
+
yield json.loads(line), None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def digest(text):
|
| 43 |
+
return hashlib.sha256(text.encode()).hexdigest()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def entities(row, task):
|
| 47 |
+
if task == "actors":
|
| 48 |
+
return collections.Counter(mention["type"] for mention in row["mentions"])
|
| 49 |
+
if task == "events":
|
| 50 |
+
return collections.Counter(event["event_type"] for event in row["events"])
|
| 51 |
+
return collections.Counter({row["label"]: 1})
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def build(task):
|
| 55 |
+
splits = ["validation", "train"] if task == "events" else ["test", "validation", "train"]
|
| 56 |
+
converter = {"evidence": vitamin, "actors": few_nerd, "events": maven}[task]
|
| 57 |
+
root = OUT / task
|
| 58 |
+
root.mkdir(exist_ok=True)
|
| 59 |
+
group_split = {}
|
| 60 |
+
seen = {}
|
| 61 |
+
audit = {}
|
| 62 |
+
roles = collections.defaultdict(collections.Counter)
|
| 63 |
+
for split in splits:
|
| 64 |
+
stats = collections.Counter()
|
| 65 |
+
labels = collections.Counter()
|
| 66 |
+
with (root / f"{split}.jsonl").open("w") as private, (root / f"{split}.manifest.jsonl").open("w") as public:
|
| 67 |
+
for source_index, (raw, names) in enumerate(source_rows(task, split)):
|
| 68 |
+
stats["read"] += 1
|
| 69 |
+
try:
|
| 70 |
+
row = converter(raw, names) if task == "actors" else converter(raw)
|
| 71 |
+
except (ValueError, KeyError, TypeError, IndexError):
|
| 72 |
+
stats["invalid_annotation"] += 1
|
| 73 |
+
continue
|
| 74 |
+
check = digest(json.dumps([row["text"], row.get("claim", "")], ensure_ascii=False))
|
| 75 |
+
if any(group in group_split and group_split[group] != split for group in row["groups"]):
|
| 76 |
+
stats["overlapping_group"] += 1
|
| 77 |
+
continue
|
| 78 |
+
if check in seen:
|
| 79 |
+
stats["duplicate_input"] += 1
|
| 80 |
+
continue
|
| 81 |
+
for group in row["groups"]:
|
| 82 |
+
group_split[group] = split
|
| 83 |
+
seen[check] = split
|
| 84 |
+
counts = entities(row, task)
|
| 85 |
+
labels.update(counts)
|
| 86 |
+
row.update(source_index=source_index, split=split, input_sha256=check)
|
| 87 |
+
if task == "actors":
|
| 88 |
+
row["tokens"] = raw["tokens"]
|
| 89 |
+
elif task == "events" and split == "train":
|
| 90 |
+
for record in raw["events"]:
|
| 91 |
+
if record["type"] in EVENT_TYPES:
|
| 92 |
+
roles[record["type"]].update(role for role, args in record["argument"].items() if args)
|
| 93 |
+
manifest = {"source_index": source_index, "split": split, "input_sha256": check,
|
| 94 |
+
"annotation_count": sum(counts.values()),
|
| 95 |
+
"label_counts_json": json.dumps(counts, sort_keys=True)}
|
| 96 |
+
# Hash provenance payloads rather than republish source text, official annotations, or wiki titles.
|
| 97 |
+
manifest["provenance_sha256"] = digest(json.dumps(row["provenance"], sort_keys=True))
|
| 98 |
+
public.write(json.dumps(manifest) + "\n")
|
| 99 |
+
private.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 100 |
+
stats["accepted"] += 1
|
| 101 |
+
audit[split] = {"counts": dict(stats), "label_counts": dict(labels)}
|
| 102 |
+
print(task, split, audit[split], flush=True)
|
| 103 |
+
if roles:
|
| 104 |
+
audit["train_role_counts"] = roles
|
| 105 |
+
(root / "audit.json").write_text(json.dumps(audit, indent=2, sort_keys=True))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if __name__ == "__main__":
|
| 109 |
+
for selected_task in sys.argv[3:] or ["evidence", "actors", "events"]:
|
| 110 |
+
build(selected_task)
|
toolkit/research/publish_release.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish audited TACITUS artifacts and atomically update the source Space."""
|
| 2 |
+
import argparse
|
| 3 |
+
import concurrent.futures
|
| 4 |
+
import json
|
| 5 |
+
import shutil
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 9 |
+
|
| 10 |
+
OWNER="Giuliocc"
|
| 11 |
+
TASKS=("evidence","actors","events")
|
| 12 |
+
SPACE=f"{OWNER}/tacitus-source-lab"
|
| 13 |
+
PREVIOUS_SPACE="9ae128a13ee60fba1161f70730f21015eb6278db"
|
| 14 |
+
CODE=Path(__file__).resolve().parents[1]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def model_id(task):
|
| 18 |
+
return f"{OWNER}/tacitus-{'events' if task=='roles' else task}-base"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def stage_space(local, release, versions):
|
| 22 |
+
local.mkdir(parents=True,exist_ok=True)
|
| 23 |
+
shutil.copytree(CODE/"space",local,dirs_exist_ok=True)
|
| 24 |
+
models=local/"models"
|
| 25 |
+
models.mkdir(exist_ok=True)
|
| 26 |
+
for task in (*TASKS,"roles"):
|
| 27 |
+
folder=release/f"{'events' if task=='roles' else task}-base"
|
| 28 |
+
raw=json.loads((folder/("roles.json" if task=="roles" else "model.json")).read_text())
|
| 29 |
+
raw.update(model_id=model_id(task),model_revision=versions.get(model_id(task),"development"))
|
| 30 |
+
(models/f"{task}.json").write_text(json.dumps(raw,separators=(",",":")))
|
| 31 |
+
toolkit=local/"toolkit"
|
| 32 |
+
toolkit.mkdir(exist_ok=True)
|
| 33 |
+
for folder in ("research","tacitus_nlp","tests","fixtures"):
|
| 34 |
+
shutil.copytree(CODE/folder,toolkit/folder,dirs_exist_ok=True,ignore=shutil.ignore_patterns("__pycache__","*.pyc"))
|
| 35 |
+
for name in ("README.md","requirements.txt","requirements-research.txt","app.py","baseline-results.json",
|
| 36 |
+
"diagnostics.py","evidence_pilot.py","evidence-pilot-results.json","diagnostic-results.json"):
|
| 37 |
+
shutil.copy(CODE/name,toolkit/name)
|
| 38 |
+
shutil.copy(CODE.parent/"challenge-evaluation.json",toolkit/"challenge-evaluation.json")
|
| 39 |
+
(toolkit/"release-versions.json").write_text(json.dumps(versions,indent=2))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def publish_repo(api, task, kind, release):
|
| 43 |
+
name=f"{task}-{'data' if kind=='dataset' else 'base'}"
|
| 44 |
+
identifier=f"{OWNER}/tacitus-{name}"
|
| 45 |
+
api.create_repo(identifier,repo_type=kind,private=False,exist_ok=True)
|
| 46 |
+
head=api.repo_info(identifier,repo_type=kind).sha
|
| 47 |
+
files=set(api.list_repo_files(identifier,repo_type=kind,revision=head))
|
| 48 |
+
if files-{".gitattributes","README.md"}:
|
| 49 |
+
published=hf_hub_download(identifier,"README.md",repo_type=kind,revision=head)
|
| 50 |
+
if f"TACITUS {task.title()}" not in Path(published).read_text():
|
| 51 |
+
raise RuntimeError(f"{identifier} contains unrelated files. Review before replacing anything.")
|
| 52 |
+
commit=api.upload_folder(repo_id=identifier,repo_type=kind,folder_path=release/name,parent_commit=head,
|
| 53 |
+
commit_message=f"Publish TACITUS {task.title()} v0.2.0")
|
| 54 |
+
actual=set(api.list_repo_files(identifier,repo_type=kind,revision=commit.oid))
|
| 55 |
+
expected={str(path.relative_to(release/name)) for path in (release/name).rglob("*") if path.is_file()}
|
| 56 |
+
if missing:=expected-actual:
|
| 57 |
+
raise RuntimeError(f"{identifier} is missing {missing}")
|
| 58 |
+
print(kind,identifier,commit.oid,flush=True)
|
| 59 |
+
return identifier,commit.oid
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def main():
|
| 63 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 64 |
+
parser.add_argument("release",type=Path)
|
| 65 |
+
parser.add_argument("stage",type=Path)
|
| 66 |
+
parser.add_argument("--local",action="store_true")
|
| 67 |
+
args=parser.parse_args()
|
| 68 |
+
if args.local:
|
| 69 |
+
stage_space(args.stage,args.release,{})
|
| 70 |
+
return
|
| 71 |
+
api=HfApi()
|
| 72 |
+
if api.whoami()["name"].casefold()!=OWNER.casefold():
|
| 73 |
+
raise SystemExit("Authenticate as Giuliocc before uploading.")
|
| 74 |
+
if api.space_info(SPACE).sha!=PREVIOUS_SPACE:
|
| 75 |
+
raise SystemExit("The published Space changed since inspection. Review its current revision first.")
|
| 76 |
+
jobs=[(task,kind) for task in TASKS for kind in ("model","dataset")]
|
| 77 |
+
versions={}
|
| 78 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
| 79 |
+
results={pool.submit(publish_repo,api,task,kind,args.release):(task,kind) for task,kind in jobs}
|
| 80 |
+
for result in concurrent.futures.as_completed(results):
|
| 81 |
+
name,revision=result.result()
|
| 82 |
+
versions[name]=revision
|
| 83 |
+
stage_space(args.stage,args.release,versions)
|
| 84 |
+
commit=api.upload_folder(repo_id=SPACE,repo_type="space",folder_path=args.stage,parent_commit=PREVIOUS_SPACE,
|
| 85 |
+
commit_message="Release browser inference, models, and data v0.2.0")
|
| 86 |
+
print("space",SPACE,commit.oid,flush=True)
|
| 87 |
+
collection=api.create_collection("TACITUS Source Toolkit",namespace=OWNER,
|
| 88 |
+
description="Source-relative Evidence, Actors, and Events models, reconstruction datasets, and browser demo.",
|
| 89 |
+
private=False,exists_ok=True)
|
| 90 |
+
for item_id,item_type in [(SPACE,"space")]+[(f"{OWNER}/tacitus-{task}-{'base' if kind=='model' else 'data'}",kind)
|
| 91 |
+
for task,kind in jobs]:
|
| 92 |
+
api.add_collection_item(collection.slug,item_id,item_type,exists_ok=True)
|
| 93 |
+
found=api.get_collection(collection.slug)
|
| 94 |
+
if len(found.items)<7:
|
| 95 |
+
raise RuntimeError("The collection is missing release items.")
|
| 96 |
+
print("collection",found.url,flush=True)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
if __name__=="__main__":
|
| 100 |
+
main()
|
toolkit/research/train.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Train CPU models and export quantized browser weights."""
|
| 2 |
+
import argparse
|
| 3 |
+
import base64
|
| 4 |
+
import collections
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from scipy.optimize import minimize_scalar
|
| 12 |
+
from scipy.sparse import csr_matrix
|
| 13 |
+
from scipy.special import softmax
|
| 14 |
+
from sklearn.linear_model import SGDClassifier
|
| 15 |
+
from sklearn.metrics import classification_report, f1_score, log_loss
|
| 16 |
+
|
| 17 |
+
from research.features import WIDTH, encode, evidence_features, token_features, tokenize
|
| 18 |
+
|
| 19 |
+
SEED = 1729
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def rows(root, split):
|
| 23 |
+
with (root / f"{split}.jsonl").open() as stream:
|
| 24 |
+
for line in stream:
|
| 25 |
+
yield json.loads(line)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def keep(key, ratio):
|
| 29 |
+
number = int.from_bytes(hashlib.blake2s(str(key).encode(), digest_size=4).digest(), "big")
|
| 30 |
+
return number / 2**32 < ratio
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def choose_split(document):
|
| 34 |
+
return "test" if keep(document["groups"][-1], .5) else "validation"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def read_rows(root, task, split):
|
| 38 |
+
actual = "validation" if task in ("events", "roles") and split == "test" else split
|
| 39 |
+
for row in rows(root, actual):
|
| 40 |
+
if task in ("events", "roles") and split != "train" and choose_split(row) != split:
|
| 41 |
+
continue
|
| 42 |
+
yield row
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def features_matrix(records, labels):
|
| 46 |
+
columns, values, pointers = [], [], [0]
|
| 47 |
+
targets = []
|
| 48 |
+
for features, label in records:
|
| 49 |
+
for slot, value in sorted(encode(features).items()):
|
| 50 |
+
columns.append(slot)
|
| 51 |
+
values.append(value)
|
| 52 |
+
pointers.append(len(columns))
|
| 53 |
+
targets.append(labels.index(label))
|
| 54 |
+
return csr_matrix((np.array(values, dtype="float32"), columns, pointers),
|
| 55 |
+
shape=(len(targets), WIDTH)), np.array(targets)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def batched(iterable, size):
|
| 59 |
+
batch = []
|
| 60 |
+
for item in iterable:
|
| 61 |
+
batch.append(item)
|
| 62 |
+
if len(batch) == size:
|
| 63 |
+
yield batch
|
| 64 |
+
batch = []
|
| 65 |
+
if batch:
|
| 66 |
+
yield batch
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def dataset(root, task, split, mode, labels):
|
| 70 |
+
for document in read_rows(root, task, split):
|
| 71 |
+
if task == "evidence":
|
| 72 |
+
# Keep all held-out pairs. Use a stable majority of the audited training pairs.
|
| 73 |
+
if split == "train" and not keep(document["input_sha256"], .72):
|
| 74 |
+
continue
|
| 75 |
+
yield evidence_features(document["text"], document["claim"], mode), document["label"]
|
| 76 |
+
continue
|
| 77 |
+
if task == "actors" and split == "train" and not document["mentions"] and not keep(document["source_index"], .45):
|
| 78 |
+
continue
|
| 79 |
+
for tokens, gold, anchor, event_type, _ in instances(document, task):
|
| 80 |
+
for index, label in enumerate(gold):
|
| 81 |
+
if label not in labels:
|
| 82 |
+
continue
|
| 83 |
+
if split == "train" and label == "O":
|
| 84 |
+
ratio = {"actors": .30, "events": .12, "roles": .22}[task]
|
| 85 |
+
if not keep((document["source_index"], anchor, index), ratio):
|
| 86 |
+
continue
|
| 87 |
+
yield token_features(tokens, index, mode, anchor, event_type), label
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def aligned_tags(tokens, spans):
|
| 91 |
+
by_start = {token[1]: index for index, token in enumerate(tokens)}
|
| 92 |
+
by_end = {token[2]: index for index, token in enumerate(tokens)}
|
| 93 |
+
tags = ["O"] * len(tokens)
|
| 94 |
+
for left, right, kind in sorted(spans, key=lambda span: (span[0], -(span[1]-span[0]), span[2])):
|
| 95 |
+
start, end = by_start.get(left), by_end.get(right)
|
| 96 |
+
if start is None or end is None or start > end or any(tag != "O" for tag in tags[start:end+1]):
|
| 97 |
+
continue
|
| 98 |
+
tags[start] = "B:" + kind
|
| 99 |
+
tags[start+1:end+1] = ["I:" + kind] * (end-start)
|
| 100 |
+
return tags
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def instances(document, task):
|
| 104 |
+
tokens = tokenize(document["text"])
|
| 105 |
+
if task == "actors":
|
| 106 |
+
spans = {(item["start"], item["end"], item["type"]) for item in document["mentions"]}
|
| 107 |
+
elif task == "events":
|
| 108 |
+
spans = {(item["trigger"]["start"], item["trigger"]["end"], item["event_type"]) for item in document["events"]}
|
| 109 |
+
else:
|
| 110 |
+
starts = {token[1]: index for index, token in enumerate(tokens)}
|
| 111 |
+
for event in document["events"]:
|
| 112 |
+
trigger = event["trigger"]
|
| 113 |
+
position = starts.get(trigger["start"])
|
| 114 |
+
if position is None:
|
| 115 |
+
continue
|
| 116 |
+
start, end = max(0, position-90), min(len(tokens), position+91)
|
| 117 |
+
window = tokens[start:end]
|
| 118 |
+
spans = {(item["start"], item["end"], item["role"]) for item in event["participants"]}
|
| 119 |
+
yield window, aligned_tags(window, spans), position-start, event["event_type"], spans
|
| 120 |
+
return
|
| 121 |
+
yield tokens, aligned_tags(tokens, spans), None, None, spans
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def unpack(tokens, tags):
|
| 125 |
+
result = set()
|
| 126 |
+
previous = None
|
| 127 |
+
for (_, start, end), tag in zip(tokens, tags, strict=True):
|
| 128 |
+
if tag == "O":
|
| 129 |
+
previous = None
|
| 130 |
+
continue
|
| 131 |
+
marker, kind = tag.split(":", 1)
|
| 132 |
+
if marker == "I" and previous is not None and previous[2] == kind:
|
| 133 |
+
result.remove(previous)
|
| 134 |
+
previous = (previous[0], end, kind)
|
| 135 |
+
else:
|
| 136 |
+
previous = (start, end, kind)
|
| 137 |
+
result.add(previous)
|
| 138 |
+
return result
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def scores(predicted, gold):
|
| 142 |
+
keys = sorted(predicted.keys() | gold.keys())
|
| 143 |
+
totals = np.zeros(3, dtype=int)
|
| 144 |
+
per_type = {}
|
| 145 |
+
for key in keys:
|
| 146 |
+
a, b = predicted[key], gold[key]
|
| 147 |
+
tp = len(a & b)
|
| 148 |
+
counts = np.array([tp, len(a)-tp, len(b)-tp])
|
| 149 |
+
totals += counts
|
| 150 |
+
per_type[key] = stat(*map(int, counts))
|
| 151 |
+
return {"micro": stat(*map(int, totals)), "per_type": per_type}
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def stat(tp, fp, fn):
|
| 155 |
+
return {"precision": tp / max(1, tp+fp), "recall": tp / max(1, tp+fn),
|
| 156 |
+
"f1": 2*tp / max(1, 2*tp+fp+fn), "support": tp+fn, "predictions": tp+fp}
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def model_arrays(model):
|
| 160 |
+
if isinstance(model, tuple):
|
| 161 |
+
return model
|
| 162 |
+
return model.coef_.astype("float32"), model.intercept_.astype("float32")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def logits(model, X):
|
| 166 |
+
weight, bias = model_arrays(model)
|
| 167 |
+
return np.asarray(X @ weight.T + bias)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def choose_tags(values, labels, margin, allowed=None):
|
| 171 |
+
values[:, 0] += margin
|
| 172 |
+
if allowed is not None:
|
| 173 |
+
for column, label in enumerate(labels):
|
| 174 |
+
if column and label[2:] not in allowed:
|
| 175 |
+
values[:, column] = -np.inf
|
| 176 |
+
return [labels[i] for i in values.argmax(axis=1)]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def span_evaluate(model, root, task, split, mode, labels, margins, allowed_roles):
|
| 180 |
+
gold = collections.defaultdict(set)
|
| 181 |
+
predictions = {margin: collections.defaultdict(set) for margin in margins}
|
| 182 |
+
document_count = 0
|
| 183 |
+
for document in read_rows(root, task, split):
|
| 184 |
+
document_count += 1
|
| 185 |
+
for instance_index, (tokens, _, anchor, kind, spans) in enumerate(instances(document, task)):
|
| 186 |
+
for start, end, label in spans:
|
| 187 |
+
gold[label].add((document_count, instance_index, start, end))
|
| 188 |
+
allowed = allowed_roles.get(kind) if task == "roles" else None
|
| 189 |
+
X, _ = features_matrix(((token_features(tokens,i,mode,anchor,kind),"O")
|
| 190 |
+
for i in range(len(tokens))), labels)
|
| 191 |
+
matrix = logits(model, X)
|
| 192 |
+
for margin in margins:
|
| 193 |
+
tags = choose_tags(matrix.copy(), labels, margin, allowed)
|
| 194 |
+
for start, end, label in unpack(tokens, tags):
|
| 195 |
+
predictions[margin][label].add((document_count, instance_index, start, end))
|
| 196 |
+
return {margin: {"rows": document_count, **scores(pred, gold)} for margin, pred in predictions.items()}
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def evidence_matrix(root, split, mode, labels):
|
| 200 |
+
matrices, targets = [], []
|
| 201 |
+
for batch in batched(dataset(root,"evidence",split,mode,labels), 8192):
|
| 202 |
+
X, y = features_matrix(batch,labels)
|
| 203 |
+
matrices.append(X)
|
| 204 |
+
targets.append(y)
|
| 205 |
+
from scipy.sparse import vstack
|
| 206 |
+
return vstack(matrices), np.concatenate(targets)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def fit(root, task, mode, labels, epochs):
|
| 210 |
+
model = SGDClassifier(loss="log_loss", penalty="l2", alpha=.000025, random_state=SEED,
|
| 211 |
+
average=True, learning_rate="optimal")
|
| 212 |
+
used = 0
|
| 213 |
+
# Cache the sparse matrices for additional passes without repeating tokenization.
|
| 214 |
+
prepared = []
|
| 215 |
+
for batch in batched(dataset(root,task,"train",mode,labels), 8192):
|
| 216 |
+
X, y = features_matrix(batch,labels)
|
| 217 |
+
weight = np.where(y == 0, 1., 1.15) if task != "evidence" else np.ones(len(y))
|
| 218 |
+
prepared.append((X,y,weight))
|
| 219 |
+
used += len(y)
|
| 220 |
+
rng = np.random.default_rng(SEED)
|
| 221 |
+
for epoch in range(epochs):
|
| 222 |
+
for index in rng.permutation(len(prepared)):
|
| 223 |
+
X, y, weight = prepared[index]
|
| 224 |
+
model.partial_fit(X, y, classes=np.arange(len(labels)), sample_weight=weight)
|
| 225 |
+
print(task, mode, "epoch", epoch+1, "training instances", used, flush=True)
|
| 226 |
+
return model, used
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def evidence_metrics(values, y, labels, temperature, threshold):
|
| 230 |
+
probabilities = softmax(values / temperature, axis=1)
|
| 231 |
+
prediction = probabilities.argmax(axis=1)
|
| 232 |
+
accept = probabilities.max(axis=1) >= threshold
|
| 233 |
+
return {"rows":len(y), "macro_f1":f1_score(y,prediction,average="macro"),
|
| 234 |
+
"nll":log_loss(y,probabilities,labels=np.arange(len(labels))),
|
| 235 |
+
"ece_10_bins":sum(
|
| 236 |
+
float(mask.mean()) * abs(float(probabilities.max(axis=1)[mask].mean()) -
|
| 237 |
+
float((prediction[mask]==y[mask]).mean()))
|
| 238 |
+
for low in np.arange(0., 1., .1)
|
| 239 |
+
if (mask := ((probabilities.max(axis=1) >= low) &
|
| 240 |
+
(probabilities.max(axis=1) < low+.1000001))).any()),
|
| 241 |
+
"coverage":float(accept.mean()),"accepted_accuracy":float((prediction[accept]==y[accept]).mean()) if accept.any() else None,
|
| 242 |
+
"per_label":classification_report(y,prediction,target_names=labels,output_dict=True,zero_division=0)}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def export(model, folder, metadata):
|
| 246 |
+
weight,bias = model_arrays(model)
|
| 247 |
+
scales = np.maximum(np.abs(weight).max(axis=1), 1e-8) / 32767
|
| 248 |
+
quantized = np.rint(weight/scales[:,None]).astype("<i2")
|
| 249 |
+
restored = (quantized.astype(np.float32)*scales[:,None], bias)
|
| 250 |
+
metadata.update(width=WIDTH, scale=scales.tolist(), bias=bias.tolist(),
|
| 251 |
+
encoding="row-major-signed-int16-little-endian-base64",
|
| 252 |
+
max_weight_rounding_error=float(np.max(np.abs(weight-restored[0]))))
|
| 253 |
+
(folder/"model.json").write_text(json.dumps({**metadata, "weights":base64.b64encode(quantized.tobytes()).decode()},
|
| 254 |
+
separators=(",", ":")))
|
| 255 |
+
return restored
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def main():
|
| 259 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 260 |
+
parser.add_argument("task",choices=("evidence","actors","events","roles"))
|
| 261 |
+
parser.add_argument("processed",type=Path)
|
| 262 |
+
parser.add_argument("output",type=Path)
|
| 263 |
+
args = parser.parse_args()
|
| 264 |
+
task = args.task
|
| 265 |
+
root = args.processed/("events" if task=="roles" else task)
|
| 266 |
+
folder = args.output/task
|
| 267 |
+
folder.mkdir(parents=True,exist_ok=True)
|
| 268 |
+
audit=json.loads((root/"audit.json").read_text())
|
| 269 |
+
allowed={key:sorted(value) for key,value in audit.get("train_role_counts",{}).items()}
|
| 270 |
+
if task=="evidence":
|
| 271 |
+
labels=["supported","contradicted","insufficient_information"]
|
| 272 |
+
else:
|
| 273 |
+
kinds=sorted({label for group in allowed.values() for label in group}) if task=="roles" else sorted(audit["train"]["label_counts"])
|
| 274 |
+
labels=["O"]+[f"{prefix}:{kind}" for kind in kinds for prefix in ("B","I")]
|
| 275 |
+
modes = ("hypothesis", "pair") if task=="evidence" else (("context",) if task=="roles" else ("lexical","context"))
|
| 276 |
+
candidates={}
|
| 277 |
+
for mode in modes:
|
| 278 |
+
model, used=fit(root,task,mode,labels,3 if task!="roles" else 4)
|
| 279 |
+
if task=="evidence":
|
| 280 |
+
X,y=evidence_matrix(root,"validation",mode,labels)
|
| 281 |
+
values=logits(model,X)
|
| 282 |
+
tau=math.exp(minimize_scalar(lambda log_t:log_loss(y,softmax(values/math.exp(log_t),axis=1)),
|
| 283 |
+
bounds=(-2,3),method="bounded").x)
|
| 284 |
+
probabilities=softmax(values/tau,axis=1)
|
| 285 |
+
choices=[]
|
| 286 |
+
for threshold in np.arange(.45,.991,.01):
|
| 287 |
+
accepted=probabilities.max(axis=1)>=threshold
|
| 288 |
+
if accepted.sum()>=100 and (probabilities[accepted].argmax(axis=1)==y[accepted]).mean()>=.8:
|
| 289 |
+
choices.append(float(threshold))
|
| 290 |
+
threshold=min(choices) if choices else 1.01
|
| 291 |
+
report=evidence_metrics(values,y,labels,tau,threshold)
|
| 292 |
+
tuning={"temperature":tau,"threshold":threshold}
|
| 293 |
+
ranking=report["macro_f1"]
|
| 294 |
+
else:
|
| 295 |
+
results=span_evaluate(model,root,task,"validation",mode,labels,(0.,.5,1.,1.5,2.,2.5),allowed)
|
| 296 |
+
margin=max(results,key=lambda key:results[key]["micro"]["f1"])
|
| 297 |
+
report=results[margin]
|
| 298 |
+
tuning={"negative_margin":margin}
|
| 299 |
+
ranking=report["micro"]["f1"]
|
| 300 |
+
candidates[mode]=(ranking,model,used,report,tuning)
|
| 301 |
+
print(task, mode, "development F1", ranking, flush=True)
|
| 302 |
+
# The Evidence release always evaluates the source-aware model as the product candidate.
|
| 303 |
+
# A hypothesis-only run is an ablation and never answers passage/claim requests.
|
| 304 |
+
mode="pair" if task=="evidence" else max(candidates,key=lambda key:candidates[key][0])
|
| 305 |
+
rank,model,used,valid,tuning=candidates[mode]
|
| 306 |
+
restored=export(model,folder,{"task":task,"version":"0.2.0","labels":labels,"mode":mode,
|
| 307 |
+
**tuning,**({"allowed_roles":allowed,"window_tokens":90} if task=="roles" else {})})
|
| 308 |
+
if task=="evidence":
|
| 309 |
+
X,y=evidence_matrix(root,"test",mode,labels)
|
| 310 |
+
test=evidence_metrics(logits(restored,X),y,labels,tuning["temperature"],tuning["threshold"])
|
| 311 |
+
else:
|
| 312 |
+
test=span_evaluate(restored,root,task,"test",mode,labels,(tuning["negative_margin"],),allowed)[tuning["negative_margin"]]
|
| 313 |
+
report={"mode":mode,"training_instances":used,"seed":SEED,"development":valid,"test":test,
|
| 314 |
+
"selection":{key:{"f1":value[0],"training_instances":value[2],"tuning":value[4]}
|
| 315 |
+
for key,value in candidates.items()},**tuning}
|
| 316 |
+
(folder/"evaluation.json").write_text(json.dumps(report,indent=2))
|
| 317 |
+
print(task,"test",test.get("micro",test.get("macro_f1")),flush=True)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__=="__main__":
|
| 321 |
+
main()
|
toolkit/tacitus_nlp/__init__.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source-relative inference using pinned upstream checkpoints."""
|
| 2 |
+
import hashlib
|
| 3 |
+
import json
|
| 4 |
+
import re
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
SOURCES = json.loads(Path(__file__).with_name("sources.json").read_text())
|
| 8 |
+
LABELS = {"entailment": "supported", "neutral": "insufficient_information", "contradiction": "contradicted"}
|
| 9 |
+
ACTORS = {
|
| 10 |
+
"politician": "named politician or elected official",
|
| 11 |
+
"military_person": "named military service member",
|
| 12 |
+
"government_institution": "named government agency or institution",
|
| 13 |
+
"political_party": "named political party",
|
| 14 |
+
"company": "named commercial company",
|
| 15 |
+
"media_organization": "named news outlet or publisher",
|
| 16 |
+
"other_organization": "named organization outside the other categories",
|
| 17 |
+
"geopolitical_location": "named city, country, or other geopolitical jurisdiction",
|
| 18 |
+
}
|
| 19 |
+
EVENTS = {
|
| 20 |
+
"Attack": "the trigger word or phrase explicitly mentioning an attack",
|
| 21 |
+
"Arrest": "the trigger word or phrase explicitly mentioning an arrest",
|
| 22 |
+
"Protest": "the trigger word or phrase explicitly mentioning a public protest",
|
| 23 |
+
"Request": "the trigger word or phrase explicitly mentioning a request",
|
| 24 |
+
"Military_operation": "the trigger for a military operation",
|
| 25 |
+
"Sign_agreement": "the trigger for signing an agreement",
|
| 26 |
+
"Surrendering": "the trigger for surrendering",
|
| 27 |
+
"Supporting": "the trigger for providing support",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def sha(text):
|
| 32 |
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def validate(text, document_id, max_chars=12000):
|
| 36 |
+
if not isinstance(text, str) or not text.strip():
|
| 37 |
+
raise ValueError("Enter non-empty source text.")
|
| 38 |
+
if len(text) > max_chars:
|
| 39 |
+
raise ValueError(f"Source exceeds {max_chars:,} characters. Use a shorter excerpt.")
|
| 40 |
+
if document_id is not None and (not isinstance(document_id, str) or not document_id.strip()):
|
| 41 |
+
raise ValueError("Document ID must be a non-empty string.")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def source_span(text, start, end, expected):
|
| 45 |
+
if not (0 <= start < end <= len(text)) or text[start:end] != expected:
|
| 46 |
+
raise ValueError("Span does not match the original source.")
|
| 47 |
+
return {"start": start, "end": end, "text": expected}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class _Model:
|
| 51 |
+
def __init__(self, model, source):
|
| 52 |
+
self.model = model
|
| 53 |
+
self.source = source
|
| 54 |
+
|
| 55 |
+
def envelope(self, task, text, document_id, warnings):
|
| 56 |
+
digest = sha(text)
|
| 57 |
+
return {
|
| 58 |
+
"task": task, "schema_version": "0.1.0", "preprocessing_revision": "0.1.0",
|
| 59 |
+
"document_id": document_id or digest, "text_sha256": digest,
|
| 60 |
+
"model_id": self.source["repo"], "model_revision": self.source["revision"],
|
| 61 |
+
"warnings": warnings,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Evidence(_Model):
|
| 66 |
+
@classmethod
|
| 67 |
+
def from_pretrained(cls, model_id=None, *, revision=None):
|
| 68 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 69 |
+
source = _source("evidence", model_id, revision)
|
| 70 |
+
params = {"revision": source["revision"], "trust_remote_code": False}
|
| 71 |
+
instance = cls(AutoModelForSequenceClassification.from_pretrained(
|
| 72 |
+
source["repo"], use_safetensors=True, **params).eval(), source)
|
| 73 |
+
instance.tokenizer = AutoTokenizer.from_pretrained(source["repo"], **params)
|
| 74 |
+
names = {i: LABELS.get(label.lower(), label.lower()) for i, label in
|
| 75 |
+
instance.model.config.id2label.items()}
|
| 76 |
+
if set(names.values()) != set(LABELS.values()) or set(names) != {0, 1, 2}:
|
| 77 |
+
raise ValueError(f"Unexpected NLI label mapping: {names}")
|
| 78 |
+
instance.labels = names
|
| 79 |
+
return instance
|
| 80 |
+
|
| 81 |
+
def check(self, *, passage, claim, document_id=None):
|
| 82 |
+
import torch
|
| 83 |
+
validate(passage, document_id)
|
| 84 |
+
if not isinstance(claim, str) or not claim.strip() or len(claim) > 1500:
|
| 85 |
+
raise ValueError("Enter a claim of 1–1,500 characters.")
|
| 86 |
+
batch = self.tokenizer(passage, claim, return_tensors="pt", truncation=False)
|
| 87 |
+
limit = min(self.model.config.max_position_embeddings, 512)
|
| 88 |
+
if batch.input_ids.shape[-1] > limit:
|
| 89 |
+
raise ValueError(f"Source and claim exceed {limit} tokens. Use a shorter excerpt.")
|
| 90 |
+
with torch.inference_mode():
|
| 91 |
+
probabilities = self.model(**batch).logits[0].softmax(dim=-1).tolist()
|
| 92 |
+
scores = {self.labels[i]: value for i, value in enumerate(probabilities)}
|
| 93 |
+
return {
|
| 94 |
+
**self.envelope("evidence", passage, document_id, ["Uncalibrated upstream baseline."]),
|
| 95 |
+
"claim_sha256": sha(claim), "verdict": max(scores, key=scores.__getitem__),
|
| 96 |
+
"scores": scores, "review_required": True, "review_reason": "Baseline lacks domain calibration.",
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _source(key, model_id, revision):
|
| 101 |
+
from huggingface_hub import model_info
|
| 102 |
+
source = SOURCES[key]
|
| 103 |
+
if model_id in (None, source["repo"]) and revision in (None, source["revision"]):
|
| 104 |
+
return source
|
| 105 |
+
model_id = model_id or source["repo"]
|
| 106 |
+
commit = model_info(model_id, revision=revision).sha
|
| 107 |
+
return {"repo": model_id, "revision": commit}
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class _Extractor(_Model):
|
| 111 |
+
@classmethod
|
| 112 |
+
def from_pretrained(cls, model_id=None, *, revision=None, **options):
|
| 113 |
+
from gliner2 import AutoExtractor
|
| 114 |
+
from huggingface_hub import snapshot_download
|
| 115 |
+
source = _source("extractor", model_id, revision)
|
| 116 |
+
path = snapshot_download(source["repo"], revision=source["revision"],
|
| 117 |
+
allow_patterns=["*.json", "*.safetensors", "*.model"])
|
| 118 |
+
model = AutoExtractor.from_pretrained(path, map_location="cpu")
|
| 119 |
+
model.eval()
|
| 120 |
+
instance = cls(model, source)
|
| 121 |
+
for name, value in options.items():
|
| 122 |
+
if name != "role_schema" or not isinstance(instance, Events):
|
| 123 |
+
raise TypeError(f"Unexpected option: {name}")
|
| 124 |
+
instance.role_schema = value
|
| 125 |
+
return instance
|
| 126 |
+
|
| 127 |
+
def _extract(self, text, schema):
|
| 128 |
+
import torch
|
| 129 |
+
with torch.inference_mode():
|
| 130 |
+
groups = self.model.extract_entities(text, schema, include_confidence=True, include_spans=True)["entities"]
|
| 131 |
+
spans = []
|
| 132 |
+
for label, values in groups.items():
|
| 133 |
+
for item in values:
|
| 134 |
+
span = source_span(text, item["start"], item["end"], item["text"])
|
| 135 |
+
spans.append({**span, "type": label, "score": float(item["confidence"])})
|
| 136 |
+
return sorted(spans, key=lambda span: (span["start"], span["end"], span["type"]))
|
| 137 |
+
|
| 138 |
+
def _windows(self, text, schema):
|
| 139 |
+
words = list(re.finditer(r"\S+", text))
|
| 140 |
+
unique = {}
|
| 141 |
+
for i in range(0, len(words), 160):
|
| 142 |
+
start, end = words[i].start(), words[min(i + 191, len(words) - 1)].end()
|
| 143 |
+
for span in self._extract(text[start:end], schema):
|
| 144 |
+
span["start"] += start
|
| 145 |
+
span["end"] += start
|
| 146 |
+
key = (span["start"], span["end"], span["type"])
|
| 147 |
+
if key not in unique or unique[key]["score"] < span["score"]:
|
| 148 |
+
unique[key] = span
|
| 149 |
+
if i + 192 >= len(words):
|
| 150 |
+
break
|
| 151 |
+
return [unique[key] for key in sorted(unique)]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _identity(result, span):
|
| 155 |
+
identity = [result["document_id"], result["text_sha256"], span["start"], span["end"],
|
| 156 |
+
span["type"], result["schema_version"]]
|
| 157 |
+
return sha(json.dumps(identity, ensure_ascii=False))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class Actors(_Extractor):
|
| 161 |
+
def extract(self, text, document_id=None):
|
| 162 |
+
validate(text, document_id)
|
| 163 |
+
result = self.envelope("actors", text, document_id, ["Zero-shot upstream baseline."])
|
| 164 |
+
result["mentions"] = [
|
| 165 |
+
{**span, "mention_id": _identity(result, span), "canonical_actor_id": None}
|
| 166 |
+
for span in self._windows(text, ACTORS)
|
| 167 |
+
]
|
| 168 |
+
return result
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class Events(_Extractor):
|
| 172 |
+
role_schema = None
|
| 173 |
+
|
| 174 |
+
def extract(self, text, document_id=None):
|
| 175 |
+
validate(text, document_id, max_chars=4000)
|
| 176 |
+
result = self.envelope("events", text, document_id, [
|
| 177 |
+
"Zero-shot trigger proposals. Assertion status has not been assessed."
|
| 178 |
+
])
|
| 179 |
+
if not self.role_schema:
|
| 180 |
+
result["warnings"].append("Participant extraction requires a per-event role schema.")
|
| 181 |
+
result["events"] = [
|
| 182 |
+
{"event_mention_id": _identity(result, trigger), "event_type": trigger["type"],
|
| 183 |
+
"trigger": trigger, "assertion_status": "unknown",
|
| 184 |
+
"participants": self._roles(text, trigger)}
|
| 185 |
+
for trigger in self._windows(text, dict(list(EVENTS.items())[:4]))
|
| 186 |
+
]
|
| 187 |
+
return result
|
| 188 |
+
|
| 189 |
+
def _roles(self, text, trigger):
|
| 190 |
+
schema = (self.role_schema or {}).get(trigger["type"])
|
| 191 |
+
if not schema:
|
| 192 |
+
return []
|
| 193 |
+
start, end = trigger["start"], trigger["end"]
|
| 194 |
+
opening, closing = " [TARGET] ", " [/TARGET] "
|
| 195 |
+
marked = text[:start] + opening + text[start:end] + closing + text[end:]
|
| 196 |
+
regions = [(0, start, 0), (start + len(opening), end + len(opening), len(opening)),
|
| 197 |
+
(end + len(opening) + len(closing), len(marked), len(opening) + len(closing))]
|
| 198 |
+
roles = []
|
| 199 |
+
for span in self._windows(marked, schema):
|
| 200 |
+
for left, right, shift in regions:
|
| 201 |
+
if left <= span["start"] < span["end"] <= right:
|
| 202 |
+
clean = source_span(text, span["start"] - shift, span["end"] - shift, span["text"])
|
| 203 |
+
roles.append({**clean, "role": span["type"], "score": span["score"], "status": "proposed"})
|
| 204 |
+
break
|
| 205 |
+
return roles
|
toolkit/tacitus_nlp/data.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert upstream records without distributing upstream text."""
|
| 2 |
+
import argparse
|
| 3 |
+
import json
|
| 4 |
+
import unicodedata
|
| 5 |
+
from collections import Counter
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from tempfile import NamedTemporaryFile
|
| 8 |
+
|
| 9 |
+
from . import EVENTS, sha, source_span
|
| 10 |
+
|
| 11 |
+
EVIDENCE_MAP = {"SUPPORTS": "supported", "REFUTES": "contradicted", "NOT ENOUGH INFO": "insufficient_information"}
|
| 12 |
+
ACTOR_MAP = {
|
| 13 |
+
"person-politician": "politician", "person-soldier": "military_person",
|
| 14 |
+
"organization-government/governmentagency": "government_institution",
|
| 15 |
+
"organization-politicalparty": "political_party", "organization-company": "company",
|
| 16 |
+
"organization-media/newspaper": "media_organization", "location-GPE": "geopolitical_location",
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def vitamin(row):
|
| 21 |
+
text, claim = row["evidence"], row["claim"]
|
| 22 |
+
if not text.strip() or not claim.strip():
|
| 23 |
+
raise ValueError("Evidence and claim are required.")
|
| 24 |
+
provenance = {key: row[key] for key in
|
| 25 |
+
("case_id", "unique_id", "page", "wiki_revision_id", "revision_type", "FEVER_id")
|
| 26 |
+
if row.get(key) not in (None, "")}
|
| 27 |
+
if not any(key in provenance for key in ("case_id", "unique_id")):
|
| 28 |
+
raise ValueError("Missing upstream identity.")
|
| 29 |
+
return {"text": text, "claim": claim, "label": EVIDENCE_MAP[row["label"]], "provenance": provenance,
|
| 30 |
+
"groups": [f"{key}:{_group_value(provenance[key])}" for key in ("page", "case_id", "FEVER_id")
|
| 31 |
+
if key in provenance] + ["claim:" + sha(_group_value(claim))]}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _group_value(value):
|
| 35 |
+
return " ".join(unicodedata.normalize("NFKC", str(value)).casefold().split())
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def few_nerd(row, names=None):
|
| 39 |
+
tokens = row["tokens"]
|
| 40 |
+
labels = [names[i] if isinstance(i, int) else i for i in row["fine_ner_tags"]]
|
| 41 |
+
if len(tokens) != len(labels) or not tokens or any(not token for token in tokens):
|
| 42 |
+
raise ValueError("Expected aligned non-empty tokens and fine labels.")
|
| 43 |
+
text = " ".join(tokens)
|
| 44 |
+
offsets = [0]
|
| 45 |
+
for token in tokens:
|
| 46 |
+
offsets.append(offsets[-1] + len(token) + 1)
|
| 47 |
+
mentions = []
|
| 48 |
+
start = 0
|
| 49 |
+
while start < len(labels):
|
| 50 |
+
label = labels[start]
|
| 51 |
+
end = start + 1
|
| 52 |
+
while end < len(labels) and labels[end] == label:
|
| 53 |
+
end += 1
|
| 54 |
+
target = ACTOR_MAP.get(label)
|
| 55 |
+
if target is None and label.startswith("organization-"):
|
| 56 |
+
target = "other_organization"
|
| 57 |
+
if target is not None:
|
| 58 |
+
span = source_span(text, offsets[start], offsets[end] - 1, " ".join(tokens[start:end]))
|
| 59 |
+
mentions.append({**span, "type": target, "source_label": label})
|
| 60 |
+
start = end
|
| 61 |
+
return {"text": text, "mentions": mentions,
|
| 62 |
+
"provenance": {"spacing": "single-space token reconstruction"},
|
| 63 |
+
"groups": ["tokens:" + sha(_group_value(text))]}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def maven(row):
|
| 67 |
+
text = row["document"]
|
| 68 |
+
if "events" not in row:
|
| 69 |
+
raise ValueError("This split has no gold event or argument annotations.")
|
| 70 |
+
entities = {entity["id"]: entity["mention"] for entity in row["entities"]}
|
| 71 |
+
events = []
|
| 72 |
+
for event in row["events"]:
|
| 73 |
+
if event["type"] not in EVENTS:
|
| 74 |
+
continue
|
| 75 |
+
participants = []
|
| 76 |
+
for role, arguments in event["argument"].items():
|
| 77 |
+
for arg in arguments:
|
| 78 |
+
entity_id = arg.get("entity_id")
|
| 79 |
+
if entity_id:
|
| 80 |
+
for mention in entities[entity_id]:
|
| 81 |
+
span = source_span(text, *mention["offset"], mention["mention"])
|
| 82 |
+
participants.append({**span, "role": role, "entity_id": entity_id,
|
| 83 |
+
"source_mention_id": mention["id"]})
|
| 84 |
+
else:
|
| 85 |
+
span = source_span(text, *arg["offset"], arg["content"])
|
| 86 |
+
participants.append({**span, "role": role})
|
| 87 |
+
for mention in event["mention"]:
|
| 88 |
+
trigger = source_span(text, *mention["offset"], mention["trigger_word"])
|
| 89 |
+
events.append({"event_type": event["type"], "source_event_id": event["id"],
|
| 90 |
+
"source_trigger_id": mention["id"], "trigger": trigger, "participants": participants})
|
| 91 |
+
negatives = [
|
| 92 |
+
{**source_span(text, *mention["offset"], mention["trigger_word"]), "source_trigger_id": mention["id"]}
|
| 93 |
+
for mention in row.get("negative_triggers", [])
|
| 94 |
+
]
|
| 95 |
+
return {"text": text, "events": events, "negative_triggers": negatives,
|
| 96 |
+
"provenance": {"source_document_id": row["id"], "title": row["title"]},
|
| 97 |
+
"groups": ["document:" + str(row["id"]), "title:" + _group_value(row["title"])]}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def convert(task, inputs, output, names=None):
|
| 101 |
+
converter = {"evidence": vitamin, "actors": few_nerd, "events": maven}[task]
|
| 102 |
+
split_by_group = {}
|
| 103 |
+
counts = Counter()
|
| 104 |
+
temporary = None
|
| 105 |
+
try:
|
| 106 |
+
with NamedTemporaryFile(mode="w", dir=output.parent, encoding="utf-8", delete=False) as stream:
|
| 107 |
+
temporary = Path(stream.name)
|
| 108 |
+
for split, file in inputs:
|
| 109 |
+
with Path(file).open(encoding="utf-8") as rows:
|
| 110 |
+
for line_number, line in enumerate(rows, 1):
|
| 111 |
+
try:
|
| 112 |
+
raw = json.loads(line)
|
| 113 |
+
row = converter(raw, names=names) if task == "actors" else converter(raw)
|
| 114 |
+
for group in row["groups"]:
|
| 115 |
+
previous = split_by_group.setdefault(group, split)
|
| 116 |
+
if previous != split:
|
| 117 |
+
raise ValueError(f"Group crosses partitions {previous!r} and {split!r}.")
|
| 118 |
+
except (KeyError, TypeError, ValueError, IndexError) as error:
|
| 119 |
+
raise ValueError(f"{file}:{line_number}: {error}") from error
|
| 120 |
+
row.update(split=split, text_sha256=sha(row["text"]))
|
| 121 |
+
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 122 |
+
counts[split] += 1
|
| 123 |
+
temporary.replace(output)
|
| 124 |
+
finally:
|
| 125 |
+
if temporary:
|
| 126 |
+
temporary.unlink(missing_ok=True)
|
| 127 |
+
return counts
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main():
|
| 131 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 132 |
+
parser.add_argument("task", choices=["evidence", "actors", "events"])
|
| 133 |
+
parser.add_argument("output", type=Path)
|
| 134 |
+
parser.add_argument("inputs", nargs="+", metavar="SPLIT=JSONL")
|
| 135 |
+
parser.add_argument("--labels", type=Path, help="Few-NERD fine-label names in feature metadata order")
|
| 136 |
+
args = parser.parse_args()
|
| 137 |
+
inputs = [item.split("=", 1) for item in args.inputs]
|
| 138 |
+
if any(len(item) != 2 or not all(item) for item in inputs):
|
| 139 |
+
parser.error("Each input must be SPLIT=JSONL.")
|
| 140 |
+
names = json.loads(args.labels.read_text()) if args.labels else None
|
| 141 |
+
print(json.dumps(convert(args.task, inputs, args.output, names)))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
if __name__ == "__main__":
|
| 145 |
+
main()
|
toolkit/tacitus_nlp/sources.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"evidence": {
|
| 3 |
+
"repo": "MoritzLaurer/DeBERTa-v3-base-mnli-fever-anli",
|
| 4 |
+
"revision": "6f5cf0a2b59cabb106aca4c287eed12e357e90eb",
|
| 5 |
+
"license": "mit",
|
| 6 |
+
"kind": "models"
|
| 7 |
+
},
|
| 8 |
+
"extractor": {
|
| 9 |
+
"repo": "fastino/gliner2.5-base-v1",
|
| 10 |
+
"revision": "07d99c0ba5d15cb3b24e0a236fa99bdd4ef87a5c",
|
| 11 |
+
"license": "apache-2.0",
|
| 12 |
+
"kind": "models"
|
| 13 |
+
},
|
| 14 |
+
"actors_source": {
|
| 15 |
+
"repo": "DFKI-SLT/few-nerd",
|
| 16 |
+
"revision": "205f3e9c9f3577ea2561d43f2f62dc249ab92d5b",
|
| 17 |
+
"license": [
|
| 18 |
+
"cc-by-sa-4.0"
|
| 19 |
+
],
|
| 20 |
+
"kind": "datasets"
|
| 21 |
+
},
|
| 22 |
+
"evidence_source": {
|
| 23 |
+
"repo": "tals/vitaminc",
|
| 24 |
+
"revision": "be6febb761b0b2807687e61e0b5282e459df2fa0",
|
| 25 |
+
"license": [
|
| 26 |
+
"cc-by-sa-3.0"
|
| 27 |
+
],
|
| 28 |
+
"kind": "datasets"
|
| 29 |
+
},
|
| 30 |
+
"doxa": {
|
| 31 |
+
"repo": "Giuliocc/doxa-evidence-verifier",
|
| 32 |
+
"revision": "4aff63cbf95574c310329ec3e28ef19ca591feb5",
|
| 33 |
+
"license": "apache-2.0",
|
| 34 |
+
"kind": "models"
|
| 35 |
+
},
|
| 36 |
+
"doxa_benchmark": {
|
| 37 |
+
"repo": "Giuliocc/doxa-evidence-benchmark",
|
| 38 |
+
"revision": "056301683cd8a3266e1b8c507e33a003c08ad3e7",
|
| 39 |
+
"license": "other",
|
| 40 |
+
"kind": "datasets"
|
| 41 |
+
}
|
| 42 |
+
}
|
toolkit/tests/test_toolkit.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import tempfile
|
| 3 |
+
import unittest
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from app import highlight, interface
|
| 7 |
+
from tacitus_nlp import Events, source_span
|
| 8 |
+
from tacitus_nlp.data import convert, few_nerd, maven, vitamin
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ContractTests(unittest.TestCase):
|
| 12 |
+
def test_unicode_offsets_and_escaped_preview(self):
|
| 13 |
+
text = "🗳️ <b>Río</b>"
|
| 14 |
+
start = text.index("Río")
|
| 15 |
+
span = source_span(text, start, start + 3, "Río")
|
| 16 |
+
self.assertIn("<b><mark", highlight(text, [span]))
|
| 17 |
+
with self.assertRaises(ValueError):
|
| 18 |
+
source_span(text, start + 1, start + 4, "Río")
|
| 19 |
+
|
| 20 |
+
def test_same_type_event_mentions_have_distinct_ids_and_invert_role_offsets(self):
|
| 21 |
+
text = "🔔 Ada protested and Bea protested."
|
| 22 |
+
actor_schema = {"Participant": "Name of the person protesting"}
|
| 23 |
+
event = Events(None, {"repo": "test", "revision": "fixture"})
|
| 24 |
+
event.role_schema = {"Protest": actor_schema}
|
| 25 |
+
|
| 26 |
+
def fake_windows(source, schema):
|
| 27 |
+
if schema is actor_schema:
|
| 28 |
+
name = "Ada" if source.index("[TARGET]") < source.index("Bea") else "Bea"
|
| 29 |
+
start = source.index(name)
|
| 30 |
+
return [{"start": start, "end": start + len(name), "text": name,
|
| 31 |
+
"score": 1.0, "type": "Participant"}]
|
| 32 |
+
first, second = source.index("protested"), source.rindex("protested")
|
| 33 |
+
return [{"start": start, "end": start + 9, "text": "protested", "type": "Protest"}
|
| 34 |
+
for start in (first, second)]
|
| 35 |
+
|
| 36 |
+
event._windows = fake_windows
|
| 37 |
+
rows = event.extract(text)["events"]
|
| 38 |
+
self.assertNotEqual(rows[0]["event_mention_id"], rows[1]["event_mention_id"])
|
| 39 |
+
for row, name in zip(rows, ("Ada", "Bea"), strict=True):
|
| 40 |
+
span = row["participants"][0]
|
| 41 |
+
self.assertEqual(text[span["start"]:span["end"]], name)
|
| 42 |
+
|
| 43 |
+
def test_ui_has_three_prediction_and_three_download_actions(self):
|
| 44 |
+
self.assertEqual(len(interface().config["dependencies"]), 6)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ConverterTests(unittest.TestCase):
|
| 48 |
+
def test_vitaminc_discards_canary_and_retains_case(self):
|
| 49 |
+
row = vitamin({"evidence": "Text", "claim": "Claim", "label": "REFUTES",
|
| 50 |
+
"case_id": "c1", "big_bench_canary": "never retain"})
|
| 51 |
+
self.assertEqual(row["label"], "contradicted")
|
| 52 |
+
self.assertIn("case_id:c1", row["groups"])
|
| 53 |
+
self.assertNotIn("never retain", json.dumps(row))
|
| 54 |
+
|
| 55 |
+
def test_few_nerd_preserves_exact_reconstructed_spans(self):
|
| 56 |
+
row = few_nerd({"tokens": ["🗳", "Juniper", "Town", "Council", "met"],
|
| 57 |
+
"fine_ner_tags": [0, 1, 1, 1, 0]},
|
| 58 |
+
names=["O", "organization-government/governmentagency"])
|
| 59 |
+
span = row["mentions"][0]
|
| 60 |
+
self.assertEqual(row["text"][span["start"]:span["end"]], "Juniper Town Council")
|
| 61 |
+
self.assertEqual(span["type"], "government_institution")
|
| 62 |
+
|
| 63 |
+
def test_maven_resolves_entity_references_to_source_spans(self):
|
| 64 |
+
row = maven({"id": "d", "title": "Test", "document": "Ada protested.",
|
| 65 |
+
"events": [{"id": "e", "type": "Protest",
|
| 66 |
+
"mention": [{"id": "t", "trigger_word": "protested", "offset": [4, 13]}],
|
| 67 |
+
"argument": {"Participant": [{"entity_id": "p"}]}}],
|
| 68 |
+
"entities": [{"id": "p", "mention": [{"id": "m", "mention": "Ada", "offset": [0, 3]}]}]})
|
| 69 |
+
span = row["events"][0]["participants"][0]
|
| 70 |
+
self.assertEqual(row["text"][span["start"]:span["end"]], "Ada")
|
| 71 |
+
self.assertEqual(span["source_mention_id"], "m")
|
| 72 |
+
|
| 73 |
+
def test_split_audit_rejects_duplicate_and_keeps_previous_output(self):
|
| 74 |
+
row = {"evidence": "Evidence", "claim": "a claim", "label": "SUPPORTS", "case_id": "c"}
|
| 75 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 76 |
+
source, output = (Path(folder) / name for name in ("source", "out"))
|
| 77 |
+
source.write_text(json.dumps(row) + "\n")
|
| 78 |
+
output.write_text("previous")
|
| 79 |
+
with self.assertRaisesRegex(ValueError, "crosses partitions"):
|
| 80 |
+
convert("evidence", [("train", source), ("test", source)], output)
|
| 81 |
+
self.assertEqual(output.read_text(), "previous")
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
unittest.main()
|
workspace.js
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use strict';
|
| 2 |
+
const examples={
|
| 3 |
+
evidence:['Northbridge City Council scheduled its budget vote for next Tuesday. The motion has not yet been voted on.','The council has already voted on the budget.'],
|
| 4 |
+
actors:['The United Nations issued a statement in Geneva. Angela Merkel spoke to reporters, and Reuters covered the announcement.',''],
|
| 5 |
+
events:['The town council requested a review. Residents protested on Monday. Residents protested again on Wednesday after talks broke down.','']
|
| 6 |
+
};
|
| 7 |
+
const el=id=>document.getElementById(id);
|
| 8 |
+
const buttons=Array.from(document.querySelectorAll('[data-task]'));
|
| 9 |
+
let task='evidence',current=null,generation=0;
|
| 10 |
+
|
| 11 |
+
function invalidate() {
|
| 12 |
+
generation++;
|
| 13 |
+
current=null;
|
| 14 |
+
el('result').hidden=true;
|
| 15 |
+
el('status').textContent='';
|
| 16 |
+
el('run').disabled=false;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
function loadExample() {
|
| 20 |
+
invalidate();
|
| 21 |
+
[el('passage').value,el('claim').value]=examples[task];
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
function highlight(text,spans) {
|
| 25 |
+
const source=el('source');
|
| 26 |
+
const characters=Array.from(text);
|
| 27 |
+
const edges=Array.from(new Set([0,characters.length,...spans.flatMap(item=>[item.start,item.end])])).sort((a,b)=>a-b);
|
| 28 |
+
source.replaceChildren();
|
| 29 |
+
for(let i=1;i<edges.length;i++) {
|
| 30 |
+
const [left,right]=[edges[i-1],edges[i]];
|
| 31 |
+
const segment=characters.slice(left,right).join('');
|
| 32 |
+
const matching=spans.filter(item=>item.start<=left&&item.end>=right);
|
| 33 |
+
if(matching.length) {
|
| 34 |
+
const mark=document.createElement('mark');
|
| 35 |
+
mark.textContent=segment;
|
| 36 |
+
mark.title=matching.map(item=>item.role??item.type).join(', ');
|
| 37 |
+
source.append(mark);
|
| 38 |
+
} else source.append(segment);
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
const label=value=>value.replaceAll('_',' ');
|
| 43 |
+
function display(payload,text) {
|
| 44 |
+
current=payload;
|
| 45 |
+
const version=payload.model_revision?.slice(0,12);
|
| 46 |
+
el('version').textContent=`${payload.model_id} · ${version} · Schema ${payload.schema_version}`;
|
| 47 |
+
el('warning').textContent=payload.warnings.join(' ');
|
| 48 |
+
const labels=[];
|
| 49 |
+
let spans=[];
|
| 50 |
+
if (payload.task==='evidence') {
|
| 51 |
+
el('summary').textContent=label(payload.verdict)+(payload.review_required?' · Review required':'');
|
| 52 |
+
for (const [name,score] of Object.entries(payload.scores)) labels.push(`${label(name)} · ${(score*100).toFixed(1)}%`);
|
| 53 |
+
} else if(payload.task==='actors') {
|
| 54 |
+
const {mentions}=payload;
|
| 55 |
+
el('summary').textContent=`${mentions.length} actor mention${mentions.length===1?'':'s'}`;
|
| 56 |
+
spans=mentions;
|
| 57 |
+
for(const mention of mentions) labels.push(`${mention.text} · ${label(mention.type)}`);
|
| 58 |
+
} else {
|
| 59 |
+
const {events}=payload;
|
| 60 |
+
el('summary').textContent=`${events.length} proposed event mention${events.length===1?'':'s'}`;
|
| 61 |
+
spans=events.flatMap(event=>[event.trigger,...event.participants]);
|
| 62 |
+
for(const event of events) {
|
| 63 |
+
const parts=event.participants.map(item=>`${label(item.role)} = ${item.text}`).join(', ');
|
| 64 |
+
labels.push(`${event.trigger.text} · ${label(event.event_type)}${parts?' · '+parts:''}`);
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
highlight(text,spans);
|
| 68 |
+
const list=document.createElement('ul');
|
| 69 |
+
for(const item of labels) {
|
| 70 |
+
const li=document.createElement('li');
|
| 71 |
+
li.textContent=item;
|
| 72 |
+
list.append(li);
|
| 73 |
+
}
|
| 74 |
+
el('details').replaceChildren(list);
|
| 75 |
+
el('json').textContent=JSON.stringify(payload,null,2);
|
| 76 |
+
el('result').hidden=false;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
for(const button of buttons) button.addEventListener('click',()=>{
|
| 80 |
+
const next=button.dataset.task;
|
| 81 |
+
if(next===task) return;
|
| 82 |
+
task=next;
|
| 83 |
+
invalidate();
|
| 84 |
+
for(const item of buttons) item.setAttribute('aria-pressed',String(item===button));
|
| 85 |
+
el('claim-field').hidden=task!=='evidence';
|
| 86 |
+
el('claim').required=task==='evidence';
|
| 87 |
+
el('role-field').hidden=task!=='events';
|
| 88 |
+
el('run').textContent=task==='evidence'?'Check claim':'Extract mentions';
|
| 89 |
+
});
|
| 90 |
+
|
| 91 |
+
el('example').addEventListener('click',loadExample);
|
| 92 |
+
el('analysis').addEventListener('submit',async event=>{
|
| 93 |
+
event.preventDefault();
|
| 94 |
+
const turn=++generation;
|
| 95 |
+
const text=el('passage').value,claim=el('claim').value;
|
| 96 |
+
el('result').hidden=true;
|
| 97 |
+
el('run').disabled=true;
|
| 98 |
+
el('status').textContent='Analyzing passage…';
|
| 99 |
+
try{
|
| 100 |
+
const result=await tacitus.analyze(task,text,claim,el('roles').checked);
|
| 101 |
+
if(turn===generation){display(result,text);el('status').textContent='';}
|
| 102 |
+
}catch(error){
|
| 103 |
+
if(turn===generation)el('status').textContent=error.message;
|
| 104 |
+
}finally{
|
| 105 |
+
if(turn===generation)el('run').disabled=false;
|
| 106 |
+
}
|
| 107 |
+
});
|
| 108 |
+
el('passage').addEventListener('input',invalidate);
|
| 109 |
+
el('claim').addEventListener('input',invalidate);
|
| 110 |
+
el('roles').addEventListener('change',invalidate);
|
| 111 |
+
el('download').addEventListener('click',()=>{
|
| 112 |
+
if(!current) return;
|
| 113 |
+
const url=URL.createObjectURL(new Blob([JSON.stringify(current,null,2)],{type:'application/json'}));
|
| 114 |
+
const link=document.createElement('a');
|
| 115 |
+
link.href=url;
|
| 116 |
+
link.download=`tacitus-${current.task}.json`;
|
| 117 |
+
link.click();
|
| 118 |
+
setTimeout(()=>URL.revokeObjectURL(url),1000);
|
| 119 |
+
});
|
| 120 |
+
loadExample();
|