Spaces:
Running
Running
Download app.js from Hugdrigo/evalflow-ci-lab: direct link, hf CLI and curl.
- Browser
- Download file 22.9 kB
-
https://huggingface.co/spaces/Hugdrigo/evalflow-ci-lab/resolve/main/app.js
- Command line
-
hf download hf://spaces/Hugdrigo/evalflow-ci-lab/app.js
-
curl -L -o app.js https://huggingface.co/spaces/Hugdrigo/evalflow-ci-lab/resolve/main/app.js
22.9 kB
| /* EvalFlow CI Lab — Static browser interface. Source and fixed evaluation remain local. */ | |
| (function(){'use strict'; | |
| const E=window.EvalFlowEngine;const state={rows:[],meta:null,view:'overview',result:null,policy:{...E.DEFAULT_POLICY},history:[],error:null,filter:'all',search:'',sliceKey:'language',caseLimit:10,dataSource:'bundled synthetic snapshot',imported:false}; | |
| const $=id=>document.getElementById(id);const fmt=n=>n==null?'n/a':Number(n).toLocaleString('en-US',{maximumFractionDigits:2});const pct=n=>n==null?'n/a':(n*100).toFixed(1)+'%';const delta=n=>n==null?'n/a':(n>=0?'+':'')+(n*100).toFixed(1)+' pp';const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));const c=(name,body,side='')=>`<article class="panel"><div class="panel-title"><h3>${name}</h3><span class="micro">${side}</span></div>${body}</article>`;const stat=(label,val,sub='')=>`<div class="stat"><small>${label}</small><strong>${val}</strong><span class="sub">${sub}</span></div>`; | |
| function badge(ok,text){return `<span class="badge ${ok?'ok':'fail'}">${text??(ok?'PASS':'BLOCK')}</span>`;} | |
| function meter(label,val,color=''){return `<div class="meter-row"><span>${esc(label)}</span><div class="meter ${color}"><div style="width:${Math.max(0,Math.min(100,(val??0)*100)).toFixed(2)}%"></div></div><strong>${pct(val)}</strong></div>`;} | |
| function rowsTable(headers,content){return `<div class="table-wrap"><table><thead><tr>${headers.map(h=>`<th>${esc(h)}</th>`).join('')}</tr></thead><tbody>${content}</tbody></table></div>`;} | |
| function overview(){const r=state.result,b=r.baselineMetrics,a=r.candidateMetrics,tests=r.gates.filter(g=>g.pass).length;return ` | |
| <div class="grid cols4">${stat('Candidate Accuracy',pct(a.accuracy),'Held-out '+a.n+' examples')}${stat('Candidate macro-F1',pct(a.macroF1),'Six academic labels')}${stat('Paired Accuracy delta',delta(r.pair.delta),'vs '+E.NAME[r.baseline])}${stat('Research release gate',badge(r.passed,r.status),`${tests} of ${r.gates.length} checks pass`)}</div><div class="spacer"></div> | |
| <div class="grid cols2"> | |
| ${c('Method comparison',`<div class="smalltext">Both methods are tested against identical synthetic examples; these are different classifiers, not sequential versions.</div>${meter('Baseline · '+E.NAME[r.baseline],b.accuracy,'blue')}${meter('Candidate · '+E.NAME[r.candidate],a.accuracy)}${meter('Baseline macro-F1',b.macroF1,'blue')}${meter('Candidate macro-F1',a.macroF1)}<div class="summary">Paired estimate: <strong>${delta(r.pair.delta)}</strong> · Fixed-prediction bootstrap 95% interval: <strong>${delta(r.interval.low)} to ${delta(r.interval.high)}</strong></div>`,'EVIDENCE-BASED')} | |
| ${c('Release decision',`<div class="row">${badge(r.passed,r.passed?'ALL GATES PASS':'RESEARCH GATES BLOCK')}<span class="smalltext">${tests}/${r.gates.length} gate rules satisfied</span></div><div class="spacer"></div>${r.gates.map(g=>`<div class="rule"><span class="status">${badge(g.pass)}</span><div><strong>${esc(g.label)}</strong><div class="explain">Observed ${g.unit==='count'?fmt(g.actual):pct(g.actual)} · Rule ${g.comparator} ${g.unit==='count'?fmt(g.limit):pct(g.limit)}</div></div></div>`).join('')}<p class="smalltext">Gate results are advisory; no automatic code deployment, model update, or real CI task is performed by this browser.</p>`,'POLICY CONTRACT')} | |
| </div><div class="spacer"></div> | |
| ${c('Research provenance',`<div class="grid cols3">${stat('Dataset','1,026','842 train / 130 IID / 54 challenge')}${stat('Fixed records',fmt(state.rows.length),'Six stress conditions')}${stat('Source',esc(state.imported?'USER-IMPORTED':'BUNDLED'),'Snapshot, not a live model')}</div><div class="spacer"></div><div class="banner warn">Synthetic-curated academic language only. The numbers cannot validate real-world performance, model safety, fairness or automatic production readiness. “Candidate” is a <strong>method comparison</strong>, not a time-stamped model revision.</div>`,'AUDIT TRAIL')}`;} | |
| function pipeline(){const r=state.result;const phases=[['01','Load evidence',state.rows.length+' fixed prediction records','pass'],['02','Validate schema', 'Unique model / split / attack / example keys','pass'],['03','Match examples',r.pair.n+' paired examples, '+r.pair.onlyBase.length+' missing from candidate',r.pair.complete?'pass':'fail'],['04','Compute metrics','Accuracy, macro-F1 and paired differences','pass'],['05','Stress and slices','Language strata, typo and context flip rates','pass'],['06','Evaluate policy',r.gates.filter(x=>!x.pass).length+' rule violations',r.passed?'pass':'fail'],['07','Emit audit artifacts','CLI JSON, Markdown and CSV available','pass']];return `<div class="banner">This browser <strong>replays</strong> a reproducible gate pipeline from fixed evidence. To execute checks automatically on future commits, publish the source to a GitHub repository and enable the included workflow.</div><div class="spacer"></div>${c('Pipeline stages',`<div class="steps">${phases.map(([id,label,desc,status])=>`<div class="step ${status}"><div class="row"><span class="step-index">STAGE ${id}</span>${badge(status==='pass')}</div><strong>${label}</strong><p>${esc(desc)}</p></div>`).join('')}</div>`,'LOCAL REPLAY')}<div class="spacer"></div>${c('Reproducible command',`<div class="codeblock">node ci_evalflow.js --baseline=${r.baseline} --candidate=${r.candidate} --split=${r.split} --policy=release_policy.json --output=artifacts</div><p class="smalltext">Node 20+ · no npm dependencies · exit code 0 when all gates pass, 2 when gates block, 1 for invalid input. The included GitHub Actions example uses these commands.</p>`,'CLI')}`;} | |
| function regressions(){const r=state.result;const pairs=r.pair.rows;let filtered=pairs;if(state.filter==='improved')filtered=filtered.filter(x=>x.candidateCorrect&&!x.baseCorrect);if(state.filter==='regressed')filtered=filtered.filter(x=>!x.candidateCorrect&&x.baseCorrect);if(state.filter==='changed')filtered=filtered.filter(x=>x.candidatePred!==x.basePred);if(state.search)filtered=filtered.filter(x=>(x.id+' '+x.baseText+' '+x.language+' '+x.truth).toLowerCase().includes(state.search.toLowerCase()));return `<div class="grid cols4">${stat('Paired examples',fmt(r.pair.n),'Identical gold labels')}${stat('Candidate repairs',r.pair.improved,'Wrong → correct')}${stat('New mistakes',r.pair.regressed,'Correct → wrong')}${stat('Paired change',delta(r.pair.delta),'Candidate − baseline')}</div><div class="spacer"></div> | |
| ${c('Example-level audit',`<div class="filter-row"><label class="smalltext">Status<select id="caseFilter"><option value="all" ${state.filter==='all'?'selected':''}>All matched examples</option><option value="improved" ${state.filter==='improved'?'selected':''}>Newly correct</option><option value="regressed" ${state.filter==='regressed'?'selected':''}>Newly incorrect</option><option value="changed" ${state.filter==='changed'?'selected':''}>Different predictions</option></select></label><label class="smalltext">Search example ID, text or language<input type="search" id="caseSearch" value="${esc(state.search)}" placeholder="Search evidence…"></label></div><p class="smalltext">Showing ${Math.min(filtered.length,10)} of ${filtered.length} matching pairs. Values are original fixed classifier predictions.</p>${filtered.slice(0,10).map(x=>`<div class="case"><div><span class="title">${esc(x.id)} · ${esc(E.LANG[x.language])}</span>${badge(x.candidateCorrect&&!x.baseCorrect,'REPAIRED')}${!x.candidateCorrect&&x.baseCorrect?badge(false,'NEW ERROR'):''}</div><p>${esc(x.baseText)}</p><div class="tiny">Gold: <strong>${esc(x.truth)}</strong> · Baseline: ${esc(x.basePred)} ${x.baseCorrect?'✓':'✗'} · Candidate: ${esc(x.candidatePred)} ${x.candidateCorrect?'✓':'✗'}</div></div>`).join('')||'<div class="empty">No examples match the current filter.</div>'}`,'TRACEABLE PAIRS')}`;} | |
| function gates(){const r=state.result,p=state.policy;const forms=[['minN','Minimum examples','count',1,1000,1],['minAccuracy','Minimum Accuracy','fraction',0,1,.01],['minMacroF1','Minimum macro-F1','fraction',0,1,.01],['maxRegression','Maximum regression tolerated','fraction',0,1,.01],['maxTypoFlip','Maximum typo flip rate','fraction',0,1,.01],['maxContextFlip','Maximum context flip rate','fraction',0,1,.01],['minLanguageN','Minimum language sample','count',1,1000,1],['minLanguageAccuracy','Minimum language Accuracy','fraction',0,1,.01]];const fields=forms.map(([id,title,unit,min,max,step])=>`<label>${esc(title)} ${unit==='fraction'?'(0–1)':''}<input type="number" id="policy_${id}" min="${min}" max="${max}" step="${step}" value="${p[id]}"></label>`).join('');return `${c('Editable research quality contract',`<div class="banner warn">Changing thresholds changes the <strong>gate decision</strong>, not the model, labels or measurements. Research gates are not an authorization to deploy.</div><div class="spacer"></div><div class="config-row">${fields}</div><div class="config-footer"><button id="applyPolicy" class="primary">Apply research policy</button><button id="resetPolicy" class="secondary">Restore documented defaults</button></div>`,'POLICY AS CODE')}<div class="spacer"></div>${c('Gate audit · '+r.status,rowsTable(['Gate','Observed','Threshold','Result'],r.gates.map(g=>`<tr><td>${esc(g.label)}</td><td>${g.unit==='count'?fmt(g.actual):pct(g.actual)}</td><td>${g.comparator} ${g.unit==='count'?fmt(g.limit):pct(g.limit)}</td><td>${badge(g.pass)}</td></tr>`).join('')),`${r.gates.length} CHECKS`)}<div class="spacer"></div>${c('What the gate cannot measure',`<p class="smalltext">Documentation completeness, ethics certification, external validity, subgroup fairness and live-model stability are not measured. Fixed predictions can identify mathematical regressions, but not drift in a production service.</p><p class="smalltext">A blocking gate identifies a breached <em>research policy</em>. A passing gate does not certify safety or justify deployment.</p>`,'SCOPE')}`;} | |
| function slices(){const r=state.result,key=state.sliceKey,base=E.byGroup(E.get(state.rows,r.baseline,r.split),key),cand=E.byGroup(E.get(state.rows,r.candidate,r.split),key),match=new Map(base.map(x=>[x.label,x]));return `${c('Compare groups',`<label class="smalltext">Group by<select id="sliceKey"><option value="language" ${key==='language'?'selected':''}>Language</option><option value="domain" ${key==='domain'?'selected':''}>Research domain</option><option value="truth" ${key==='truth'?'selected':''}>Rhetorical label</option></select></label><div class="spacer"></div>${cand.map(v=>`${meter(v.label,v.accuracy)}<div class="mini muted" style="margin:-10px 0 15px">${v.n} examples · Baseline ${pct(match.get(v.label)?.accuracy)} · Candidate ${pct(v.accuracy)} · Difference ${delta(v.accuracy-(match.get(v.label)?.accuracy??v.accuracy))}</div>`).join('')}`,'STRATIFIED EVALUATION')}<div class="spacer"></div>${key==='domain'&&cand.length<2?'<div class="banner warn">The challenge split is labeled as a single mixed domain, so meaningful domain-to-domain comparisons are unavailable. Switch to the controlled IID split to inspect multiple research domains.</div><div class="spacer"></div>':''}${c('Full slice registry',rowsTable(['Group','Examples','Baseline','Candidate','Change'],cand.map(v=>`<tr><td>${esc(v.label)}</td><td>${v.n}</td><td>${pct(match.get(v.label)?.accuracy)}</td><td>${pct(v.accuracy)}</td><td>${delta(v.accuracy-(match.get(v.label)?.accuracy??v.accuracy))}</td></tr>`).join('')),'DESCRIPTIVE')}<div class="spacer"></div><div class="banner warn">These are synthetic, small research groups. Scores by language or topic are not population fairness assessments. Always inspect the group denominator and dataset construction.</div>`;} | |
| function stress(){const m=state.result.candidateMetrics;return `<div class="grid cols3">${stat('Original examples',m.n,'Fixed held-out split')}${stat('Test conditions',m.attacks.length,'One is destructive')}${stat('Method',esc(E.NAME[m.method]),'Predictions fixed')}</div><div class="spacer"></div>${c('Robustness coverage and flips',rowsTable(['Condition','Evaluated','Actually changed','Flip rate','Matched accuracy'],m.attacks.map(a=>`<tr><td>${esc(a.id)} ${a.destructive?'<span class="badge fail">NO ACCURACY CLAIM</span>':''}</td><td>${a.n}</td><td>${a.matched} (${pct(a.changedShare)})</td><td>${pct(a.flipRate)}</td><td>${a.destructive?'Not scored':pct(a.matchedAccuracy)}</td></tr>`).join('')),'SIX CONDITIONS')}<div class="spacer"></div>${c('What the stress measurements mean',`<div class="banner warn">Typos, substitutions and context sentences are deterministic test transformations, not independent human-validated adversarial examples. The “information removal” condition is destructive and is never scored against the unmodified gold label.</div><div class="spacer"></div>${m.attacks.filter(x=>x.id!=='original').map(x=>meter(x.id,x.flipRate,x.flipRate>.15?'red':'' )).join('')}`,'NO FABRICATED ROBUSTNESS')}`;} | |
| function registry(){const rows=state.history;return `${c('Local session run registry',`<div class="summary">${rows.length} run replay(s) in this browser session. Nothing is saved to your Hugging Face account automatically. Export the JSON before closing the page if you want to retain these runs.</div><div class="spacer"></div>${rowsTable(['Run','Comparison','Split','Candidate Accuracy','Policy result'],rows.map((x,i)=>`<tr><td class="mono">${esc(x.id)}<br><small>${esc(x.created)}</small></td><td>${esc(E.NAME[x.baseline])} → ${esc(E.NAME[x.candidate])}</td><td>${esc(x.split)}</td><td>${pct(x.candidateAccuracy)}</td><td>${badge(x.passed,x.passed?'PASS':'BLOCK')}</td></tr>`).join(''))}<div class="actions"><button class="secondary" data-export="registry">↓ Export run registry JSON</button></div>`,'LOCAL ONLY')}<div class="spacer"></div>${c('Repeatability contract',`<p class="smalltext">Baseline and candidate predictions, sample IDs, gold labels, source hash manifest, release thresholds and random bootstrap seed are versionable artifacts. A reproducible CI run requires pushing these files to a separate code repository with the included workflow.</p>`,'DATA LINEAGE')}`;} | |
| function automation(){return `${c('GitHub Actions integration, opt-in',`<div class="banner">This ZIP contains the real GitHub Actions workflow template <code>GITHUB_ACTIONS_WORKFLOW.yml</code>. Copy it to <code>.github/workflows/evalflow-ci.yml</code> in a GitHub repository. It is <strong>not enabled by uploading to Hugging Face</strong>. To automate evaluation, copy the repository to GitHub and commit it with Actions enabled.</div><div class="spacer"></div><div class="steps"><div class="step"><span class="step-index">01</span><strong>Version source</strong><p>Commit benchmark data and all engine source files to GitHub.</p></div><div class="step"><span class="step-index">02</span><strong>Automated tests</strong><p>On pushes and pull requests, GitHub runs deterministic engine unit tests.</p></div><div class="step"><span class="step-index">03</span><strong>Release gates</strong><p>The Node CLI evaluates the pinned comparisons and exits nonzero when blocked.</p></div></div><div class="spacer"></div><div class="codeblock">node test_engine.js\nnode ci_evalflow.js --baseline=nb --candidate=hybrid --split=challenge --policy=release_policy.json --output=artifacts</div><p class="smalltext">The command above reuses 54 fixed challenge examples. The generated report and JSON artifacts are available for GitHub Actions uploads. No hosted model is retrained or deployed by this workflow.</p>`,'NO PAID COMPUTE')}<div class="spacer"></div>${c('Practical release discipline',`<p class="smalltext">Use a pinned data SHA-256 manifest, fixed test splits, sample-level evidence, a declared policy and a CI status check before tagging a release. Do not merge a failing quality report without documenting the exception and its risk.</p>`,'REPRODUCIBILITY')}`;} | |
| function exportsView(){const r=state.result;return `${c('Download reproducible artifacts',`<p class="smalltext">All outputs are generated in your browser from the selected models and current quality policy. Model predictions are fixed snapshots from the synthetic benchmark.</p><div class="actions"><button class="secondary" data-export="report">↓ Audit report .md</button><button class="secondary" data-export="result">↓ Release decision .json</button><button class="secondary" data-export="paired">↓ Paired examples .csv</button><button class="secondary" data-export="gates">↓ Gate checks .csv</button><button class="secondary" data-export="registry">↓ Session registry .json</button></div><div class="spacer"></div><p class="smalltext">Import a different record snapshot in the same JSON schema to run local exploratory checks. Files remain in your browser and are never uploaded to a service.</p><label class="smalltext">Import local prediction JSON (.json only, 10 MB maximum)<input id="importJson" type="file" accept=".json,application/json"></label><div class="actions"><button class="secondary" id="restore">↻ Restore original benchmark</button></div>`,'EXPORT / IMPORT')}<div class="spacer"></div>${c('Active provenance',`<div class="chips2"><span>Source: ${esc(state.dataSource)}</span><span>${state.rows.length} rows</span><span>Bootstrap seed ${r.interval.seed}</span><span>${r.interval.iterations} resamples</span></div><div class="spacer"></div><p class="smalltext">An official SHA-256 registry of the original source artifacts is included as <code>DATA_PROVENANCE.md</code>. View <code>METHODS.md</code>, <code>REPRODUCE.md</code> and <code>SECURITY.md</code> before using results outside the synthetic research demonstration.</p>`,'HASHES / LICENSE')}`;} | |
| const VIEWS={overview:['Command center',overview],pipeline:['Pipeline replay',pipeline],regressions:['Paired regressions',regressions],gates:['Release gates',gates],slices:['Slice diagnostics',slices],stress:['Robustness checks',stress],registry:['Run registry',registry],automation:['CI integration',automation],export:['Export & provenance',exportsView]}; | |
| function showError(e){state.error=e instanceof Error?e.message:String(e);$('error').hidden=false;$('error').textContent=state.error;} | |
| function clearError(){state.error=null;$('error').hidden=true;$('error').textContent='';} | |
| function render(){if(!state.result)return;const [label,fn]=VIEWS[state.view];$('viewTitle').textContent=label;document.querySelectorAll('.nav-btn').forEach(b=>{const active=b.dataset.view===state.view;b.classList.toggle('active',active);b.setAttribute('aria-current',active?'page':'false');});$('content').innerHTML=fn();} | |
| function run(addHistory=true){try{clearError();const base=$('baseline').value,cand=$('candidate').value,split=$('split').value;const result=E.evaluate(state.rows,base,cand,split,state.policy);state.result=result;if(addHistory){state.history.unshift({id:'REPLAY-'+String(state.history.length+1).padStart(3,'0'),created:new Date().toISOString(),baseline:base,candidate:cand,split,candidateAccuracy:result.candidateMetrics.accuracy,passed:result.passed,policy:{...state.policy}});}render();}catch(e){showError(e);}} | |
| function changeView(name){if(!VIEWS[name])return;state.view=name;render();} | |
| function download(name,text,type='text/plain'){const blob=new Blob([text],{type});const link=document.createElement('a');link.href=URL.createObjectURL(blob);link.download=name;document.body.append(link);link.click();link.remove();setTimeout(()=>URL.revokeObjectURL(link.href),1000);} | |
| function compactResult(r){return {project:'EvalFlow CI Lab',kind:'research-release-replay',source:state.dataSource,methodComparisonOnly:true,baseline:r.baseline,candidate:r.candidate,split:r.split,policy:r.policy,status:r.status,passed:r.passed,baselineMetrics:r.baselineMetrics,candidateMetrics:r.candidateMetrics,paired:{n:r.pair.n,delta:r.pair.delta,improved:r.pair.improved,regressed:r.pair.regressed,complete:r.pair.complete},interval:r.interval,gates:r.gates,note:r.note};} | |
| function handleExport(kind){const r=state.result;if(!r)return;switch(kind){case'report':download('evalflow_audit.md',E.report(r),'text/markdown');break;case'result':download('evalflow_release_replay.json',JSON.stringify(compactResult(r),null,2),'application/json');break;case'paired':download('evalflow_paired_examples.csv',E.csv(r.pair.rows,['id','language','domain','truth','basePred','candidatePred','baseCorrect','candidateCorrect','baseText']),'text/csv');break;case'gates':download('evalflow_gate_decisions.csv',E.csv(r.gates,['id','label','actual','limit','comparator','pass','unit']),'text/csv');break;case'registry':download('evalflow_session_runs.json',JSON.stringify({kind:'local-replay-registry',source:state.dataSource,runs:state.history},null,2),'application/json');break;default:showError('Unknown export type');}} | |
| async function importJson(file){try{clearError();if(!file||file.size>10*1024*1024)throw Error('Choose a JSON file smaller than 10 MB');const parsed=JSON.parse(await file.text());const rows=Array.isArray(parsed)?parsed:(parsed?.rows??null);E.verify(rows);state.rows=rows;state.imported=true;state.dataSource='user-imported local JSON';$('heroRecords').textContent=fmt(rows.length);$('dataStatus').textContent='LOCAL IMPORT · UNVERIFIED SOURCE';state.history=[];run();}catch(e){showError(e);}} | |
| async function restore(){try{clearError();const res=await fetch('robustness_snapshots.json');if(!res.ok)throw Error('Cannot load bundled evidence (HTTP '+res.status+')');const blob=await res.json();E.verify(blob.rows);state.rows=blob.rows;state.meta=blob.metadata;state.imported=false;state.dataSource='bundled synthetic snapshot';state.history=[];$('heroRecords').textContent=fmt(state.rows.length);$('dataStatus').textContent='SNAPSHOT LOADED';run();}catch(e){showError(e);$('dataStatus').textContent='ERROR · EVIDENCE UNAVAILABLE';}} | |
| document.addEventListener('click',ev=>{const t=ev.target.closest('button');if(!t)return;if(t.classList.contains('nav-btn'))changeView(t.dataset.view);else if(t.id==='run')run();else if(t.id==='downloadTop')handleExport('report');else if(t.dataset.export)handleExport(t.dataset.export);else if(t.id==='resetPolicy'){state.policy={...E.DEFAULT_POLICY};run();}else if(t.id==='applyPolicy'){try{const p={};for(const k of Object.keys(E.DEFAULT_POLICY)){p[k]=k==='requireComplete'?true:Number($('policy_'+k).value);}state.policy=E.policyCheck(p);run();}catch(e){showError(e);}}else if(t.id==='restore')restore();}); | |
| document.addEventListener('change',ev=>{const t=ev.target;if(t.id==='sliceKey'){state.sliceKey=t.value;render();}else if(t.id==='caseFilter'){state.filter=t.value;render();}else if(t.id==='importJson')importJson(t.files[0]);}); | |
| document.addEventListener('input',ev=>{if(ev.target.id==='caseSearch'){state.search=ev.target.value;render();const input=$('caseSearch');input.focus();input.setSelectionRange(input.value.length,input.value.length);}}); | |
| restore(); | |
| })(); | |