tacitus-source-lab / workspace.js
Giuliocc's picture
Finalize Source Lab input, review, and export workflows
c95195c verified
Raw History Blame Contribute Delete
12.9 kB
'use strict';
const examples={
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.'],
actors:['The United Nations issued a statement in Geneva. Angela Merkel spoke to reporters, and Reuters covered the announcement.',''],
events:['The town council requested a review. Residents protested on Monday. Residents protested again on Wednesday after talks broke down.','']
};
const limits={evidence:12000,actors:8000,events:5000};
const claimLimit=1500;
const el=id=>document.getElementById(id);
const buttons=Array.from(document.querySelectorAll('[data-task]'));
let task='evidence',current=null,generation=0,knownTrigger=null;
let segments=[],spanButtons=[];
const label=value=>value.replaceAll('_',' ');
const points=value=>Array.from(value).length;
const countFormat=new Intl.NumberFormat('en');
function invalid(field,reason) {
field.setAttribute('aria-invalid',String(Boolean(reason)));
return reason;
}
function checkInputs(showRequired=false) {
const passage=el('passage'),claim=el('claim');
const inputs=[[passage,limits[task],'source passage','passage-count']];
if(task==='evidence')inputs.push([claim,claimLimit,'claim','claim-count']);
let firstError=null;
for(const [field,maximum,name,countId] of inputs){
const size=points(field.value);
const count=el(countId);
count.textContent=`${countFormat.format(size)} / ${countFormat.format(maximum)} characters`;
count.classList.toggle('over-limit',size>maximum);
const reason=size>maximum?`Use at most ${countFormat.format(maximum)} characters for the ${name}.`:
showRequired&&!field.value.trim()?`Enter a ${name}.`:'';
invalid(field,reason);
if(reason&&!firstError)firstError={field,reason};
}
return firstError;
}
function invalidate() {
generation++;
current=null;
el('result').hidden=true;
el('status').textContent='';
el('run').disabled=false;
checkInputs();
}
function resetReference() {
el('case-reference').hidden=true;
el('case-reference').open=false;
el('example-status').textContent='';
el('case-annotation').replaceChildren();
el('case-source').replaceChildren();
}
function updateCases() {
const options=civicBenchmark.cases[task].map((row,index)=>{
const option=document.createElement('option');
option.value=String(index);
option.textContent=row.title;
return option;
});
el('example-case').replaceChildren(...options);
}
function reference(row) {
const entries=task==='evidence'?[label(row.label)]:task==='actors'
?row.mentions.map(item=>`${item.text} · ${label(item.type)}`)
:row.events.map(event=>{
const participants=event.participants.map(item=>`${label(item.role)} = ${item.text}`).join(', ');
return `${event.trigger.text} · ${label(event.event_type)} · ${label(event.assertion_status)}${participants?' · '+participants:''}`;
});
const list=document.createElement('ul');
for(const entry of entries.length?entries:['No annotated mentions']){
const item=document.createElement('li');
item.textContent=entry;
list.append(item);
}
const link=document.createElement('a');
link.href=`https://huggingface.co/datasets/${civicBenchmark.dataset}/tree/${civicBenchmark.revision}`;
link.textContent='Pinned civic benchmark';
el('case-annotation').replaceChildren(list);
const source=el('case-source');
if(row.source_url) {
const sourceLink=document.createElement('a');
sourceLink.href=row.source_url;
sourceLink.textContent=row.source_title;
source.replaceChildren(sourceLink,' · '+row.attribution+' ',link);
} else source.replaceChildren('Original fictional passage. ',link);
el('case-reference').hidden=false;
}
function loadExample() {
clearTrigger();
resetReference();
const selected=civicBenchmark.cases[task][Number(el('example-case').value)];
el('passage').value=selected.text;
el('claim').value=selected.claim??'';
invalidate();
reference(selected);
el('example-status').textContent=`Loaded ${selected.title}. The reference has provisional labels.`;
}
function clearTrigger() {
knownTrigger=null;
el('known-trigger').textContent='';
el('clear-trigger').hidden=true;
}
el('save-trigger').addEventListener('click',()=>{
const source=el('passage');
if(source.selectionEnd===source.selectionStart) {
el('known-trigger').textContent='Select the trigger words in the source passage first.';
return;
}
knownTrigger={
start:points(source.value.slice(0,source.selectionStart)),
end:points(source.value.slice(0,source.selectionEnd)),
event_type:el('trigger-type').value
};
el('known-trigger').textContent='Selected trigger — '+source.value.slice(source.selectionStart,source.selectionEnd);
el('clear-trigger').hidden=false;
el('roles').checked=true;
invalidate();
});
el('clear-trigger').addEventListener('click',()=>{clearTrigger();invalidate();});
el('trigger-type').addEventListener('change',()=>{
if(knownTrigger) {
knownTrigger.event_type=el('trigger-type').value;
invalidate();
}
});
function highlight(text,spans) {
const source=el('source');
const characters=Array.from(text);
const edges=Array.from(new Set([0,characters.length,...spans.flatMap(item=>[item.start,item.end])])).sort((a,b)=>a-b);
const content=document.createDocumentFragment();
segments=[];
for(let i=1;i<edges.length;i++) {
const [left,right]=[edges[i-1],edges[i]];
const text=characters.slice(left,right).join('');
const matching=spans.filter(item=>item.start<=left&&item.end>=right);
if(matching.length) {
const mark=document.createElement('mark');
mark.textContent=text;
mark.title=matching.map(item=>item.role??item.type).join(', ');
mark.tabIndex=-1;
segments.push({left,right,mark});
content.append(mark);
} else content.append(text);
}
source.replaceChildren(content);
}
function locate(span,button) {
for(const item of spanButtons)item.setAttribute('aria-pressed',String(button===item));
let first=null;
for(const segment of segments){
const match=span.start<=segment.left&&segment.right<=span.end;
segment.mark.classList.toggle('selected-span',match);
if(match&&!first)first=segment.mark;
}
if(first){
first.scrollIntoView({block:'nearest'});
first.focus({preventScroll:true});
el('span-status').textContent=`Highlighted ${span.text} at characters ${span.start} to ${span.end} (end excluded).`;
}
}
function spanButton(span,description) {
const button=document.createElement('button');
button.type='button';
button.className='span-link';
button.textContent=`${span.text} · ${description}`;
button.setAttribute('aria-pressed','false');
button.addEventListener('click',()=>locate(span,button));
spanButtons.push(button);
return button;
}
function display(payload,text) {
current=payload;
const version=payload.model_revision?.slice(0,12);
el('version').textContent=`${payload.model_id} · ${version} · Schema ${payload.schema_version}`;
el('warning').textContent=payload.warnings.join(' ');
el('span-status').textContent='';
spanButtons=[];
let spans=[];
const list=document.createElement('ul');
const append=content=>{
const li=document.createElement('li');
li.append(content);
list.append(li);
return li;
};
if (payload.task==='evidence') {
el('summary').textContent=label(payload.verdict)+(payload.review_required?' · Review required':'');
for (const [name,score] of Object.entries(payload.scores)) append(`${label(name)} · ${(score*100).toFixed(1)}%`);
} else if(payload.task==='actors') {
const {mentions}=payload;
el('summary').textContent=`${mentions.length} actor mention${mentions.length===1?'':'s'}`;
spans=mentions;
for(const mention of mentions)append(spanButton(mention,label(mention.type)));
} else {
const {events}=payload;
el('summary').textContent=`${events.length} proposed event mention${events.length===1?'':'s'}`;
spans=events.flatMap(event=>[event.trigger,...event.participants]);
for(const event of events) {
const entry=append(spanButton(event.trigger,label(event.event_type)));
if(event.participants.length) {
const participants=document.createElement('ul');
for(const item of event.participants){
const row=document.createElement('li');
row.append(spanButton(item,label(item.role)));
participants.append(row);
}
entry.append(participants);
} else {
const note=document.createElement('span');
note.textContent=' · '+(event.participant_status==='limit_reached'?'Participant scan limit reached':
event.participant_status==='disabled'?'Participant scan off':'No participant candidate scored high enough');
entry.append(note);
}
}
}
highlight(text,spans);
el('span-help').hidden=spans.length===0;
el('details').replaceChildren(list);
el('json').textContent=JSON.stringify(payload,null,2);
el('result').hidden=false;
}
for(const button of buttons) button.addEventListener('click',()=>{
const next=button.dataset.task;
if(next===task) return;
task=next;
clearTrigger();
resetReference();
updateCases();
invalidate();
for(const item of buttons) item.setAttribute('aria-pressed',String(item===button));
el('claim-field').hidden=task!=='evidence';
el('claim').required=task==='evidence';
el('role-field').hidden=task!=='events';
el('run').textContent=task==='evidence'?'Check claim':'Extract mentions';
});
el('example').addEventListener('click',loadExample);
el('analysis').addEventListener('submit',async event=>{
event.preventDefault();
const error=checkInputs(true);
if(error){
el('status').textContent=error.reason;
error.field.focus();
return;
}
const turn=++generation;
const text=el('passage').value,claim=el('claim').value;
el('result').hidden=true;
el('run').disabled=true;
el('status').textContent='Analyzing passage…';
try{
const result=await tacitus.analyze(task,text,claim,el('roles').checked,knownTrigger);
if(turn===generation){display(result,text);el('status').textContent='Analysis complete.';}
}catch(error){
if(turn===generation)el('status').textContent=error.message;
}finally{
if(turn===generation)el('run').disabled=false;
}
});
el('passage').addEventListener('input',()=>{clearTrigger();resetReference();invalidate();});
el('claim').addEventListener('input',()=>{resetReference();invalidate();});
el('roles').addEventListener('change',invalidate);
function download(content, media, name) {
const url=URL.createObjectURL(new Blob([content],{type:media}));
const link=document.createElement('a');
link.href=url;
link.download=name;
link.click();
setTimeout(()=>URL.revokeObjectURL(url),1000);
}
function csvCell(value) {
let text=value??'';
if(typeof text==='string'&&/^[\s\uFEFF]*[=+@-]|^[\t\r\n]/u.test(text))text="'"+text;
return '"'+String(text).replaceAll('"','""')+'"';
}
function toCsv(result) {
const rows=[];
const metadata=[result.model_id,result.model_revision,result.schema_version];
const headings=['model_id','model_revision','schema_version'];
if(result.task==='evidence'){
rows.push(['label','score','verdict','review_required',...headings]);
for(const [key,score] of Object.entries(result.scores)) rows.push([key,score,result.verdict,result.review_required,...metadata]);
} else if(result.task==='actors'){
rows.push(['mention_id','text','type','start','end',...headings]);
for(const item of result.mentions) rows.push([item.mention_id,item.text,item.type,item.start,item.end,...metadata]);
} else {
rows.push(['event_mention_id','event_type','assertion_status','participant_status','span_kind','role','text','start','end','roles_model_revision',...headings]);
for(const event of result.events){
const eventFields=[event.event_mention_id,event.event_type,event.assertion_status,event.participant_status];
rows.push([...eventFields,'trigger','',event.trigger.text,event.trigger.start,event.trigger.end,result.roles_model_revision,...metadata]);
for(const item of event.participants) rows.push([...eventFields,'participant',item.role,item.text,item.start,item.end,result.roles_model_revision,...metadata]);
}
}
return rows.map(row=>row.map(csvCell).join(',')).join('\r\n')+'\r\n';
}
el('download').addEventListener('click',()=>{
if(current)download(JSON.stringify(current,null,2),'application/json',`tacitus-${current.task}.json`);
});
el('download-csv').addEventListener('click',()=>{
if(current)download(toCsv(current),'text/csv;charset=utf-8',`tacitus-${current.task}.csv`);
});
updateCases();
[el('passage').value,el('claim').value]=examples[task];
checkInputs();