tacitus-source-lab / inference.js
Giuliocc's picture
Add verified portable runner and participant scan status
8608670 verified
Raw History Blame Contribute Delete
14.7 kB
'use strict';
const tokenizer = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*|\p{N}+(?:[.,]\p{N}+)*|[^\s]/gu;
const number = /^\p{N}+(?:[.,]\p{N}+)*$/u;
const negation = ['no','not','never','neither','without','cannot','denied','deny'];
const modal = ['will','would','might','could','plans','planned','scheduled','proposed'];
const encoder = new TextEncoder();
const crcTable = Uint32Array.from({length:256}, (_, index) => {
for (let i = 0; i < 8; i++) index = (index >>> 1) ^ (index & 1 ? 0xedb88320 : 0);
return index >>> 0;
});
const modelCache = new Map();
const limit = {evidence:12000, actors:8000, events:5000};
function tokenize(text) {
let points = 0;
let units = 0;
return Array.from(text.matchAll(tokenizer), match => {
points += Array.from(text.slice(units,match.index)).length;
const start = points;
points += Array.from(match[0]).length;
units = match.index + match[0].length;
return [match[0],start,points];
});
}
function crc32(text) {
let crc = 0xffffffff;
for(const byte of encoder.encode(text)) crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 255];
return (crc ^ 0xffffffff) >>> 0;
}
function encode(features,width) {
const values = new Map();
for(const [name,value] of features) {
const hash = crc32(name);
const column = hash % width;
values.set(column,(values.get(column) || 0) + (hash & 0x80000000 ? -value : value));
}
return Array.from(values).sort(([a],[b])=>a-b);
}
function evidenceFeatures(text, claim, mode) {
const passage = tokenize(text).map(([word])=>word.toLowerCase());
const hypothesis = tokenize(claim).map(([word])=>word.toLowerCase());
const terms = new Set(passage), requested = new Set(hypothesis);
const words = Array.from(requested).sort((a,b)=>{
const left=Array.from(a,c=>c.codePointAt(0)), right=Array.from(b,c=>c.codePointAt(0));
const first=left.findIndex((value,index)=>value!==right[index]);
return first===-1 ? left.length-right.length : left[first]-(right[first]??-1);
});
const features = words.map(word=>['h:'+word,.25]);
if (mode === 'hypothesis') return features;
const recall = (reference, samples)=>samples.filter(term=>reference.has(term)).length/Math.max(1,samples.length);
const bigrams = sequence=>new Set(sequence.slice(1).map((word,index)=>JSON.stringify([sequence[index],word])));
const numerics = words.filter(word=>number.test(word));
const ratios = {
recall:recall(terms,words),
bigram:recall(bigrams(passage),Array.from(bigrams(hypothesis))),
numbers:recall(terms,numerics)
};
for(const [name,value] of Object.entries(ratios)) features.push(['val:'+name,value],['bin:'+name+':'+Math.floor(value*10),1]);
for(const [name, vocabulary] of [['neg',negation],['modal',modal]]) {
const left = +vocabulary.some(word=>terms.has(word));
const right = +vocabulary.some(word=>requested.has(word));
features.push([`${name}:${left}:${right}`,1]);
}
for(const word of words) features.push([(terms.has(word)?'match:':'missing:')+word,.5]);
features.push([`numbers-exact:${+(numerics.length>0)}:${+numerics.every(word=>terms.has(word))}`,1],
[`length:${Math.min(Math.floor(passage.length/25),12)}:${Math.min(Math.floor(hypothesis.length/5),10)}`,1]);
return features;
}
function tokenFeatures(tokens,index,mode,anchor=null,eventType=null) {
const word=tokens[index][0], lower=word.toLowerCase(), points=Array.from(lower);
const features=[['w:'+lower,1]];
if(mode==='lexical') return features;
const first=Array.from(word)[0];
const isUpper=value=>value.toUpperCase()===value&&value.toLowerCase()!==value;
const shape=isUpper(word)?'upper':isUpper(first)?'title':number.test(word)?'number':'other';
features.push(['shape:'+shape,1],['length:'+Math.min(Array.from(word).length,12),.5]);
for(const length of [2,3,4]) if(points.length>=length) {
features.push(['pre:'+points.slice(0,length).join(''),.5],['suf:'+points.slice(-length).join(''),.5]);
}
for(const offset of [-2,-1,1,2]) {
const pos=index+offset;
const other=pos<0?'<start>':pos>=tokens.length?'<end>':tokens[pos][0].toLowerCase();
features.push([`ctx:${offset}:${other}`,.65]);
if (Math.abs(offset)===1) features.push([`pair:${offset}:${lower}:${other}`,.5]);
}
if(anchor!==null) {
const dist=index-anchor, abs=Math.abs(dist);
const bucket=(abs<=12?abs:13+Math.min(Math.floor(abs/20),5))*Math.sign(dist);
features.push(['event:'+eventType,1],['dist:'+bucket,1],[`role:${eventType}:${bucket}`,1],
[`anchor:${tokens[anchor][0].toLowerCase()}:${bucket}`,.65],[`eventword:${eventType}:${lower}`,.8]);
}
return features;
}
function decode(model) {
const raw=Uint8Array.from(atob(model.weights),c=>c.charCodeAt(0));
if(raw.length!==model.width*model.labels.length*2) throw Error('The model weights are incomplete.');
return {...model,weights:new DataView(raw.buffer)};
}
function load(task) {
if(!modelCache.has(task)) {
modelCache.set(task,fetch(`models/${task}.json`).then(response=>{
if(!response.ok) throw Error('Model files are temporarily unavailable.');
return response.json();
}).then(decode).catch(error=>{modelCache.delete(task);throw error;}));
}
return modelCache.get(task);
}
function predict(model,features) {
const input=encode(features,model.width);
return model.labels.map((_,index)=>{
let value=model.bias[index], sum=0;
for(const [column,strength] of input)
sum+=model.weights.getInt16((index*model.width+column)*2,true)*strength;
return value+sum*model.scale[index];
});
}
function softmax(values) {
const max=Math.max(...values);
const exp=values.map(value=>Math.exp(value-max));
const sum=exp.reduce((left,right)=>left+right,0);
return exp.map(value=>value/sum);
}
function argmax(values) {
return values.reduce((best,value,index)=>value>values[best]?index:best,0);
}
function spans(model,tokens,points,anchor=null,kind=null) {
const result=[];
let previous=null;
const allowed=kind===null?null:new Set(model.allowed_roles[kind]??[]);
for(let i=0;i<tokens.length;i++) {
const [,start,end]=tokens[i];
const scores=predict(model,tokenFeatures(tokens,i,model.mode,anchor,kind));
scores[0]+=model.negative_margin;
if(allowed!==null) for(let j=1;j<scores.length;j++) if(!allowed.has(model.labels[j].slice(2))) scores[j]=-Infinity;
const index=argmax(scores);
if(index===0) {
previous=null;
continue;
}
const [marker,type]=model.labels[index].split(':');
if(marker==='I'&&previous?.type===type) {
previous.end=end;
} else {
previous={start,end,type};
result.push(previous);
}
}
for(const item of result) item.text=points.slice(item.start,item.end).join('');
return result;
}
const roleBoundary=new Set(['.',';','!','?',':','(',')','[',']']);
const roleEdges=new Set([',','"','“','”','—','–','-']);
const roleDeterminers=new Set(['the','a','an','some','these','those','his','her','their','its','our']);
const rolePronouns=new Set(['he','she','they','it','we','him','them','us','who','which','i','you']);
const rolePreps=new Set(['in','at','on','from','to','with','for','near','by','after','before','against','of','under','over']);
function roleFeatures(tokens,left,right,anchor,triggerEnd,kind) {
const words=tokens.slice(left,right).map(([word])=>word);
const low=words.map(word=>word.toLowerCase());
const word=i=>tokens[i]?.[0].toLowerCase()??'<boundary>';
const first=low[0],last=low.at(-1),before=word(left-1),after=word(right);
const distance=right<=anchor?right-anchor-1:left-triggerEnd+1;
const abs=Math.abs(distance);
const bin=abs<=6?abs:7+Math.min(Math.floor(abs/5),8);
const direction=distance<0?'L':'R';
const [gapStart,gapEnd]=right<=anchor?[right,anchor]:[triggerEnd,left];
const crossings=Math.min(3,tokens.slice(gapStart,gapEnd).filter(([part])=>roleBoundary.has(part)).length);
const upper=entry=>/^[\p{Lu}\p{Lt}]/u.test(entry);
const core=[
['len:'+words.length,1],['pos:'+direction+bin,1],['boundary-crossings:'+crossings,1],['side:'+direction,1],
['first:'+first,.6],['last:'+last,.8],['prev:'+before,1],['next:'+after,1],
['prev2:'+word(left-2)+':'+before,.6],['next2:'+after+':'+word(right+1),.6],['edges:'+before+':'+after,.7],
['start:'+first+':'+last,.6],['trigger:'+word(anchor),.8],['trigger-side:'+word(anchor)+':'+direction,.8],
['all-title:'+(+words.every(upper)),.8],['last-title:'+(+upper(words.at(-1))),.7],
['begins-det:'+(+roleDeterminers.has(first)),.8],['begins-prep:'+(+rolePreps.has(first)),.8],
['ends-prep:'+(+(rolePreps.has(last)||roleDeterminers.has(last))),.8],
['pronoun:'+(+(words.length===1&&rolePronouns.has(first))),.8],['len-side:'+words.length+':'+direction,.9],
['suffix:'+Array.from(last).slice(-3).join(''),.6],['prefix:'+Array.from(first).slice(0,3).join(''),.5],
['trigger-near:'+word(anchor)+':'+direction+bin,.7]
];
return core.concat(core.map(([key,value])=>[kind+'|'+key,value*.75]),[['type:'+kind,1]]);
}
function roleRanker(model,tokens,points,anchor,triggerEnd,kind) {
const offered=new Map((model.allowed_roles[kind]??[]).map(role=>[role,[]]));
if(!offered.size||anchor===undefined||triggerEnd===undefined) return [];
const min=Math.max(0,anchor-model.radius),max=Math.min(tokens.length,anchor+model.radius+1);
const allowed=model.labels.map((role,index)=>index===0||offered.has(role));
for(let left=min;left<max;left++) {
for(let right=left+1;right<=Math.min(max,left+model.max_words);right++) {
const first=tokens[left][0],last=tokens[right-1][0];
if(roleBoundary.has(last)) break;
if((left<triggerEnd&&anchor<right)||roleBoundary.has(first)||roleEdges.has(first)||roleEdges.has(last)) continue;
const values=predict(model,roleFeatures(tokens,left,right,anchor,triggerEnd,kind));
const probability=softmax(values.map((value,index)=>allowed[index]?value:-Infinity));
const start=tokens[left][1],end=tokens[right-1][2];
for(let index=1;index<probability.length;index++) {
const score=probability[index];
if(allowed[index]&&score>=model.threshold) offered.get(model.labels[index]).push({start,end,score});
}
}
}
const result=[];
for(const [role,choices] of offered) {
choices.sort((a,b)=>b.score-a.score||a.start-b.start||a.end-b.end);
const selected=[];
for(const candidate of choices) {
if(selected.length>=model.max_per_role) break;
if(selected.some(item=>candidate.start<item.end&&item.start<candidate.end)) continue;
selected.push(candidate);
}
for(const {start,end,score} of selected)
result.push({start,end,text:points.slice(start,end).join(''),role,score,status:'proposed'});
}
return result;
}
async function sha(text) {
const result=await crypto.subtle.digest('SHA-256',encoder.encode(text));
return Array.from(new Uint8Array(result),byte=>byte.toString(16).padStart(2,'0')).join('');
}
async function analyze(task,text,claim='',includeRoles=false,knownTrigger=null,loadModel=load) {
if(!Object.hasOwn(limit,task)||typeof text!=='string'||!text.trim())
throw Error('Enter a source passage.');
const points=Array.from(text);
if(points.length>limit[task]) throw Error(`Use at most ${limit[task].toLocaleString()} source characters.`);
if(task==='evidence'&&(typeof claim!=='string'||!claim.trim()||Array.from(claim).length>1500))
throw Error('Enter a claim of 1–1,500 characters.');
const model=await loadModel(task);
const textHash=await sha(text);
const envelope={task,schema_version:'0.3.0',preprocessing_revision:'0.2.0',document_id:textHash,text_sha256:textHash,
model_id:model.model_id,model_revision:model.model_revision,warnings:[]};
if(task==='evidence') {
const raw=predict(model,evidenceFeatures(text,claim,model.mode));
const probabilities=softmax(raw.map(value=>value/model.temperature));
const best=argmax(probabilities);
const review=probabilities[best]<model.threshold;
return {...envelope,claim_sha256:await sha(claim),verdict:model.labels[best],
scores:Object.fromEntries(model.labels.map((label,i)=>[label,probabilities[i]])),
review_required:review,review_reason:review?'Confidence fell below the validation threshold.':null,
calibration_revision:model.version,
warnings:['Experimental browser baseline. Calibration was measured on VitaminC. Verify the result against the passage.']};
}
const tokens=tokenize(text);
const byStart=new Map(tokens.map(([,start],i)=>[start,i]));
const byEnd=new Map(tokens.map(([, ,end],i)=>[end,i+1]));
let detected;
if(task==='events'&&knownTrigger!==null) {
const {start,end,event_type:type}=knownTrigger;
if(!Number.isInteger(start)||!Number.isInteger(end)||end<=start||
!byStart.has(start)||!byEnd.has(end)||!model.labels.includes('B:'+type))
throw Error('Select one trigger at token boundaries and choose its event type.');
detected=[{start,end,type,text:points.slice(start,end).join('')}];
} else {
detected=spans(model,tokens,points);
}
if(task==='actors') {
const mentions=await Promise.all(detected.map(async item=>({...item,canonical_actor_id:null,
mention_id:await sha(JSON.stringify([textHash,item.start,item.end,item.type,'0.2.0']))})));
return {...envelope,mentions,warnings:['Typed mentions can miss or mislabel actors.']};
}
const roles=includeRoles?await loadModel('roles'):null;
const events=[];
const roleMax=18;
for(const item of detected) {
const location=byStart.get(item.start);
let participants=[];
const participant_status=!roles?'disabled':events.length>=roleMax?'limit_reached':'scored';
if(participant_status==='scored') {
participants=roleRanker(roles,tokens,points,location,byEnd.get(item.end),item.type);
}
events.push({event_mention_id:await sha(JSON.stringify([textHash,item.start,item.end,item.type,'0.2.0'])),
trigger:item,event_type:item.type,assertion_status:'unknown',participant_status,participants});
}
return {...envelope,trigger_source:knownTrigger===null?'detected':'provided',roles_model_revision:roles?.model_revision??null,events,warnings:[
'Event triggers are proposals. Assertion status is unknown.',
...(roles?['Experimental participant spans can be wrong or incomplete. Review them against the source.']:[]),
...(roles&&detected.length>roleMax?[`Participant extraction was limited to the first ${roleMax} triggers.`]:[])]};
}
const tacitus = { analyze, tokenize, evidenceFeatures, tokenFeatures, encode, decode, predict, spans, roleRanker, roleFeatures };
if(typeof module!=='undefined') module.exports=tacitus;