Spaces:
Running
Running
Add compressed billing imports, bulk CPU analysis and provider swap scenarios
Browse filesAdd bounded ZIP/PDF/CSV/JSON billing imports, temporary private result jobs, constrained 3/12/36-month provider scenarios, live Grokked/SARIMA bulk inference and public benchmark audit downloads. Preserve the React app, CPU Basic hardware and existing MCP endpoint. Validated with 54 tests, production frontend build and REST/MCP smoke checks. No customer documents or normalized customer records are committed.
Files changed (18)
- AnalysisPanel.jsxAdded+31
- App.jsx+11-9
- Dockerfile+1-1
- README.md+66-5
- app.py+90-7
- archive_import.pyAdded+342
- bulk.pyAdded+262
- core.py+7
- datasets.pyAdded+83
- file_inputs.pyAdded+76
- models.py+2
- package-lock.json+2-2
- package.json+1-1
- requirements.txt+3
- resources.zip+2-2
- resources_manifest.json+16-13
- scenarios.pyAdded+236
- styles.css+1
12345678910111213141516171819202122232425262728293031import React, {useState, useEffect} from 'react';import {Upload, Download, RefreshCw, Play, Info, ArrowRight, CheckCircle2} from 'lucide-react';import Papa from 'papaparse';
async function api(path,payload){const r=await fetch(path,{method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});const d=await r.json();if(!r.ok)throw Error(d.detail||'Request failed');return d;}function save(value,name){const url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}function SmallTable({rows,fields}){return <div className="table-wrap"><table><thead><tr>{fields.map(([key,label])=><th key={key}>{label}</th>)}</tr></thead><tbody>{rows.map((row,i)=><tr key={i}>{fields.map(([key])=><td key={key}>{typeof row[key]==='number'?row[key].toLocaleString(undefined,{maximumFractionDigits:3}):String(row[key]??'—')}</td>)}</tr>)}</tbody></table></div>}function Note({children}){return <div className="notice"><Info size={17}/><div>{children}</div></div>}
export function AuditDatasets(){ const [catalog,setCatalog]=useState(null),[error,setError]=useState(''); useEffect(()=>{api('/api/datasets/manifest').then(setCatalog).catch(e=>setError(e.message));},[]); return <section className="panel"><div className="section-title"><div><h2>Inspect the benchmark data</h2><p>Source snapshots, recorded predictions, truth values, protocol and checksums.</p></div><a className="secondary" href="/api/datasets/audit.zip" download><Download size={15}/>Public audit ZIP</a></div>{error&&<p role="alert">{error}</p>}<div className="dataset-list">{catalog?.datasets.map(d=><div className="dataset-row" key={d.dataset_id}><div><b>{d.title}</b><small>{d.rows.toLocaleString()} rows · {d.unit}</small><code>{d.sha256}</code></div><a className="text-button" href={d.download_path} download>CSV <Download size={13}/></a></div>)}</div><Note>These downloads contain official grid snapshots and recorded benchmark evidence. Uploaded customer bills and private analysis results are separate. Transformer/LLM evidence remains retrospective.</Note></section>;}
export default function AnalysisPanel({country,quotes,onProfile,onError}){ const [busy,setBusy]=useState(false),[importJob,setImportJob]=useState(null),[imported,setImported]=useState(null),[job,setJob]=useState(null),[result,setResult]=useState(null),[reviewed,setReviewed]=useState(false),[future,setFuture]=useState(false),[growth,setGrowth]=useState(5),[history,setHistory]=useState(null),[mode,setMode]=useState('switching'),[bulkInput,setBulkInput]=useState(''),[selected,setSelected]=useState(''); const run=async(fn)=>{setBusy(true);onError('');try{await fn()}catch(e){onError(e.message)}finally{setBusy(false)}}; const poll=async(jid,type)=>{const r=await api('/api/analysis_result',{job_id:jid,limit:20});if(r.state==='failed')throw Error(r.error);if(type==='import'){setImportJob(r);if(r.state==='completed'){setImported(r.result);setReviewed(false);}}else{setJob(r);if(r.state==='completed')setResult(r.result);}return r;}; useEffect(()=>{let jid=importJob?.job_id;if(!jid||!['queued','running'].includes(importJob.state||'queued'))return;let id=setInterval(()=>poll(jid,'import').catch(e=>{onError(e.message);clearInterval(id);}),2500);return()=>clearInterval(id)},[importJob?.job_id,importJob?.state]); useEffect(()=>{let jid=job?.job_id;if(!jid||!['queued','running'].includes(job.state||'queued'))return;let id=setInterval(()=>poll(jid,'analysis').catch(e=>{onError(e.message);clearInterval(id);}),2500);return()=>clearInterval(id)},[job?.job_id,job?.state]); const upload=async(files)=>{if(!files.length)return;if([...files].reduce((s,f)=>s+f.size,0)>25*1024*1024)throw Error('Combined compressed files must be at most 25 MiB.');let form=new FormData();for(const f of files)form.append('files',f);const r=await fetch('/api/billing_import',{method:'POST',body:form});const data=await r.json();if(!r.ok)throw Error(data.detail||'Import failed');setImported(null);setImportJob({...data,state:'queued'});setSelected('');}; const profiles=imported?.profiles||[]; const submit=async()=>{let payload;if(mode==='switching'){const prices={};for(const q of quotes||[])prices[q.provider]=Number(growth);payload={kind:'switching',import_job_id:importJob?.job_id,profiles:selected?profiles.filter(p=>p.profile_id===selected):profiles,offers:quotes||[],horizons:[3,12,36],accept_profile_estimates:reviewed,assume_future_enrolment:future,price_scenarios:[{name:'constant-price',annual_price_change_pct:{}},{name:'declared-price-change',annual_price_change_pct:prices}]};}else{payload=JSON.parse(bulkInput);payload.kind=mode;}const data=await api('/api/analysis_submit',payload);setResult(null);setJob({...data,state:'queued'});}; const plans=result?.profiles?.flatMap(p=>p.plans.map(x=>({profile_id:p.profile_id,...x})))||[]; return <><div className="two-column"><section className="panel"><div className="section-title"><div><h2>Import compressed bills</h2><p>Keep multiple meters apart. Inspect what was extracted.</p></div><span className="source-pill">ZIP · PDF · CSV · JSON</span></div><label className="upload"><Upload size={22}/><b>Select billing archives or files</b><span>Up to 10 files · 25 MiB combined · 250 archive members</span><input aria-label="Upload compressed billing files" type="file" multiple accept=".zip,.pdf,.csv,.json" disabled={busy} onChange={e=>{const files=[...e.target.files];e.target.value='';run(()=>upload(files))}}/></label><Note>Text-based EDP Portugal PDFs are supported. Germany/Australia and other PDF layouts need normalized CSV/JSON. Water and unrelated files are excluded; scanned PDFs need OCR elsewhere. Raw files are used for this temporary computation and are not published.</Note>{importJob&&<div className="job-status"><span className="status-dot"/>Import: {importJob.state}<button className="text-button" onClick={()=>run(()=>poll(importJob.job_id,'import'))}><RefreshCw size={14}/>Refresh</button></div>}{imported&&<><SmallTable rows={Object.entries(imported.document_counts||{}).map(([status,count])=>({status,count}))} fields={[["status","Document outcome"],["count","Count"]]}/><div className="button-row"><a className="secondary" href={importJob.export_path} download><Download size={15}/>Private import audit</a><button className="secondary" onClick={()=>save(imported,'electrocheap-normalized-profile.json')}>Normalized JSON</button></div><label className="check-row"><input type="checkbox" checked={reviewed} onChange={e=>setReviewed(e.target.checked)}/><span>I reviewed the extracted consumption and electricity charges<small>PDF months are daily allocations; annual totals are estimates over covered days. Services, payment adjustments and water are excluded.</small></span></label></>}</section><section className="panel"><h2>Short, middle and long horizons</h2><p>Compare staying with constrained swap schedules over 3, 12 and 36 months, under explicit future-price assumptions.</p><div className="form-grid"><label className="field"><span>Analysis</span><select value={mode} onChange={e=>setMode(e.target.value)}><option value="switching">Provider swap scenarios</option><option value="forecast">Bulk live CPU forecasts</option><option value="benchmark">Bulk chronological benchmarks</option></select></label>{mode==='switching'&&<label className="field"><span>Profile</span><select value={selected} onChange={e=>setSelected(e.target.value)}><option value="">All imported profiles</option>{profiles.map(p=><option key={p.profile_id} value={p.profile_id}>{p.profile_id} · {p.contracted_power_kva??'?'} kVA</option>)}</select></label>}</div>{mode==='switching'?<><label className="field"><span>Declared annual price change · %</span><input type="number" value={growth} min="-90" max="300" onChange={e=>setGrowth(e.target.value)}/></label><label className="check-row"><input type="checkbox" checked={future} onChange={e=>setFuture(e.target.checked)}/><span>Assume supplied offers remain open for future swaps<small>This is a scenario, not a verified future offer. Default: enrol now; later entries need dated availability.</small></span></label><Note>{quotes?.length||0} supplied quotes loaded from Quote explorer. A comparison requires complete, fresh, tax-inclusive quotes matching each meter’s power and contract terms. Without quotes the scenario keeps the historical bill baseline.</Note></>:<><label className="field"><span>Normalized bulk request JSON</span><textarea rows={12} value={bulkInput} placeholder='{"series":[{"series_id":"anonymous-series","records":[...]}],"models":["seasonal_naive","grokked_sarima"],"horizon_months":12}' onChange={e=>setBulkInput(e.target.value)}/></label><Note>Forecasts: 1–10 series, 12 complete months for seasonal naive and 36 for Grokked/SARIMA. Benchmarks: 1–3 grid/wholesale series with 72 complete months. Units, coverage and monthly dates are mandatory. Archived transformer/Astra scores do not run customer inference.</Note><label className="upload"><Upload size={18}/><b>Load bulk JSON or a monthly CSV</b><input type="file" accept=".json,.csv" onChange={e=>{const f=e.target.files[0];if(!f)return;if(f.size>2000000){onError('Normalized JSON/CSV limit is 2 MB.');return;}run(async()=>{if(f.name.endsWith('.json'))setBulkInput(await f.text());else{let parsed=Papa.parse(await f.text(),{header:true,skipEmptyLines:true});if(parsed.errors.length)throw Error(parsed.errors[0].message);setBulkInput(JSON.stringify({series:[{series_id:'uploaded-series',kind:'demand',records:parsed.data}],models:['seasonal_naive','grokked_sarima'],horizon_months:12},null,2));}});e.target.value='';}}/></label></>}<button className="primary full" disabled={busy||(mode==='switching'&&(!profiles.length||!reviewed))} onClick={()=>run(submit)}><Play size={16}/>Queue analysis<ArrowRight size={15}/></button>{job&&<div className="job-status"><span className="status-dot"/>Analysis: {job.state}<button className="text-button" onClick={()=>run(()=>poll(job.job_id,'analysis'))}><RefreshCw size={14}/>Refresh</button></div>}<Note>Results use a private unguessable link and expire after one hour or a Space restart. Download the audit ZIP to retain them. One CPU worker; no paid model calls or automatic supplier switching.</Note></section></div> {profiles.length>0&&<section className="panel"><div className="section-title"><div><h2>Imported electricity profiles</h2><p>Annualized historical scenarios; no missing latest-year bills are invented.</p></div><button className="secondary" onClick={()=>run(async()=>setHistory(await api('/api/provider_history',{import_job_id:importJob.job_id})))}>Inspect observed tariff evolution</button></div><SmallTable rows={profiles} fields={[["profile_id","Anonymous meter"],["provider","Provider"],["contracted_power_kva","Power · kVA"],["period_start","Start"],["period_end","End"],["observed_kwh","Observed · kWh"],["observed_electricity_charges","Electricity charges"],["annual_kwh","Annualized · kWh"],["current_annual_bill","Annualized cost"]]}/><div className="button-row">{profiles.map(p=><button className="text-button" key={p.profile_id} disabled={!reviewed||p.annual_kwh==null} onClick={()=>onProfile(p)}>Use {p.profile_id.slice(-6)} in Quote explorer <ArrowRight size={13}/></button>)}</div><details><summary>Allocated months and source checksums</summary><pre className="json">{JSON.stringify(profiles,null,2)}</pre></details></section>} {history&&<section className="panel"><h2>Observed provider price evolution</h2>{history.groups.map(g=><div key={g.tariff_id} className="history-group"><h3>{g.provider} · {g.tariff_id.slice(-8)}</h3><p>{g.tax_included?'VAT included':'Before VAT'} · {g.unit} · historical observations</p><SmallTable rows={g.observations} fields={[["effective_from","Effective from"],["observed_at","Bill period end"],["rate_per_kwh","Unit price"],["date_basis","Date precision"]]}/></div>)}<Note>{history.limits}</Note></section>} {result&&<section className="panel"><div className="section-title"><div><h2>Completed analysis</h2><p>{result.status}</p></div><a className="secondary" href={job.export_path} download><Download size={15}/>Private result audit ZIP</a></div>{plans.length>0&&<><SmallTable rows={plans} fields={[["profile_id","Profile"],["scenario","Price scenario"],["horizon_months","Months"],["planned_cost","Planned cost"],["stay_cost","Stay cost"],["saving_vs_stay_scenario","Scenario saving"],["currency","Currency"],["switch_count","Swaps"]]}/><Note>Exact minima within supplied monthly assumptions. Future prices and availability are uncertain; the full schedule shows fees, credits, guarantees and assumptions. This does not execute a switch.</Note></>}<details open={!plans.length}><summary>Full results, schedules and model diagnostics</summary><pre className="json">{JSON.stringify(result,null,2)}</pre></details></section>} <AuditDatasets/></>;}123456785 unmodified lines14151617181920212223242526272829303132333435363738394041import React,{useState,useEffect} from 'react';import {Zap,Activity,BarChart3,ReceiptText,Network,FileJson,ArrowUpRight,Upload,ArrowRight,Play,CheckCircle2,AlertCircle,Download,RefreshCw,ChevronRight,Info} from 'lucide-react';import Papa from 'papaparse';const markets={PT:{name:'Portugal',scope:'Mainland grid',currency:'EUR',region:'PT-mainland',flag:'🇵🇹'},DE:{name:'Germany',scope:'National grid load',currency:'EUR',region:'DE-local-grid',flag:'🇩🇪'},AU:{name:'Australia',scope:'NEM · five regions',currency:'AUD',region:'NSW1',flag:'🇦🇺'}};const nav=[['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['benchmark','Forecast lab',Activity],['models','Model evidence',BarChart3],['sources','Official feeds',Network],['api','API & methods',FileJson]];async function request(path,payload){let r=await fetch(path,{method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});let data=await r.json();if(!r.ok)throw Error(data.detail||'Request failed');return data;}const num=(n,d=0)=>Number(n).toLocaleString(undefined,{maximumFractionDigits:d});function Json({value}){return <pre className="json">{JSON.stringify(value,null,2)}</pre>}5 unmodified linesfunction download(value,name){let url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));let a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}export default function App(){const [boot,setBoot]=useState(null),[country,setCountry]=useState('PT'),[tab,setTab]=useState('quotes'),[error,setError]=useState(''),[busy,setBusy]=useState(false);const [usage,setUsage]=useState(3500),[bill,setBill]=useState(1200),[region,setRegion]=useState('PT-mainland'),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(.5),[demo,setDemo]=useState(false),[quotes,setQuotes]=useState(null),[bills,setBills]=useState(null),[accepted,setAccepted]=useState(''),[comparison,setComparison]=useState(null);const [kind,setKind]=useState('demand'),[monthly,setMonthly]=useState(null),[provider,setProvider]=useState(''),[bench,setBench]=useState(null),[evidence,setEvidence]=useState(null);const [month,setMonth]=useState('2026-09'),[nemRegion,setNemRegion]=useState('NSW1'),[live,setLive]=useState(null),[brand,setBrand]=useState('agl'),[postcode,setPostcode]=useState(''),[plans,setPlans]=useState(null),[planId,setPlanId]=useState(''),[plan,setPlan]=useState(null);const [jsonInput,setJsonInput]=useState(''),[apiType,setApiType]=useState('consumer_compare'),[apiOutput,setApiOutput]=useState(null);useEffect(()=>{request('/api/bootstrap').then(d=>{setBoot(d);setMonth(d.latest_month)}).catch(e=>setError(e.message));},[]);useEffect(()=>{let cancel=false;request('/api/model_evidence',{country}).then(d=>{if(!cancel)setEvidence(d)}).catch(e=>setError(e.message));return()=>{cancel=true}},[country]);const market=markets[country];const history=boot?.histories[country]||[];const payload=()=>{let p={country,region,meter_type:meter,peak_share:Number(peak),allow_illustrative:demo,offers:quotes||(demo?boot.example_quotes.filter(q=>q.country===country):[]),accepted_conditions:accepted.split(',').map(x=>x.trim()).filter(Boolean)};if(bills){p.billing_months=bills;if(bills.every(x=>'peak_kwh'in x))delete p.peak_share;}else{p.annual_kwh=Number(usage);p.current_annual_bill=Number(bill)}return p};const run=async(fn)=>{setError('');setBusy(true);try{await fn()}catch(e){setError(e.message)}finally{setBusy(false)}};const changeMarket=c=>{setCountry(c);setRegion(markets[c].region);setComparison(null);setBench(null);setBills(null);setQuotes(null);setLive(null);setError('')};const best=comparison?.ranked_offers?.[0];let billingUsage=bills?bills.reduce((s,r)=>s+Number(r.kwh||0),0):Number(usage);let billingTotal=bills?bills.reduce((s,r)=>s+Number(r.billed_total||0),0):Number(bill);if(!boot)return <div className="loading"><Zap size={30}/><b>Electrocheap</b><p>{error||'Loading the evidence…'}</p>{error&&<button onClick={()=>location.reload()}>Retry</button>}</div>;return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('quotes')}}><div className="brand-symbol"><Zap size={23} fill="currentColor"/></div><div><strong>XenoWAttz</strong><small>WITH BHOR BOHR</small></div></a><div className="side-divider"/><div className="side-label">ELECTROCHEAP BENCHMARK</div><nav>{nav.map(([id,label,Icon])=><button key={id} onClick={()=>{setTab(id);setError('')}} className={tab===id?'nav-item active':'nav-item'}><Icon size={19}/>{label}{id===tab&&<ChevronRight size={15} className="nav-arrow"/>}</button>)}</nav><div className="side-character"><video autoPlay loop muted playsInline poster="/brand/xenowattz-poster.png" src="/brand/xenowattz_480.mp4"/><div><span className="tiny-dot"/>Bhor Bohr is in the grid.</div></div><div className="side-foot"><span className="status-dot"/>CPU research space<small>Source first. Estimate second.</small></div></aside><main><header className="topbar"><div className="crumb">XenoWAttz <ChevronRight size={13}/><b>Electrocheap</b></div><div className="top-links"><span className="research-badge">RESEARCH PREVIEW</span><a href="/docs" target="_blank" rel="noreferrer">API docs <ArrowUpRight size={14}/></a></div></header><div className="page"><div className="page-heading"><div><div className="eyebrow">ELECTRICITY, WITH THE EVIDENCE ATTACHED</div><h1>{tab==='quotes'?'More clarity. Less bill shock.':tab==='bills'?'Your year, in kilowatt-hours.':tab==='benchmark'?'Challenge the forecast.':tab==='models'?'Every model earns its place.':tab==='sources'?'Go straight to the source.':'The engine behind XenoWAttz.'}</h1><p>{tab==='quotes'?'Compare the offers you can actually use, with every supplied cost included.':tab==='bills'?'A complete bill profile makes a better starting point than a national average.':tab==='benchmark'?'Chronological calibration, validation and test. Complexity gets no free pass.':tab==='models'?'TSF, transformers and Astra — inspect the versions and the measured evidence.':tab==='sources'?'Published demand, wholesale prices and Australian retailer plan data.':'React on the surface. Reproducible Python underneath.'}</p></div><div className="market-switch">{Object.entries(markets).map(([c,m])=><button key={c} className={c===country?'selected':''} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>{error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}<div className="stats-row"><div><span>SELECTED MARKET</span><strong>{market.name}<small>{market.flag}</small></strong><p>{market.scope}</p></div><div><span>YOUR CONSUMPTION SCENARIO</span><strong>{num(billingUsage)}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':'From your annual input'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{num(billingTotal,2)}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:'Full electricity cost, tax included'}</p></div></div>{tab==='quotes'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><Zap size={18}/></span><div><h2>Build your comparison</h2><p>Complete quotes. One consistent usage scenario.</p></div><span className="step">01</span></div><div className="form-grid"><Field label="Annual usage · kWh"><input type="number" min="1" value={bills?billingUsage:usage} disabled={!!bills} onChange={e=>setUsage(e.target.value)}/></Field><Field label={`Current annual cost · ${market.currency}`}><input type="number" min="0" value={bills?billingTotal:bill} disabled={!!bills} onChange={e=>setBill(e.target.value)}/></Field><Field label="Eligibility region / grid"><input value={region} onChange={e=>setRegion(e.target.value)}/></Field><Field label="Meter type"><select value={meter} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label={`Peak usage share · ${Math.round(peak*100)}%`}><input type="range" min="0" max="1" step=".01" value={peak} onChange={e=>setPeak(e.target.value)}/></Field>}<CsvUpload label={quotes?`${quotes.length} supplied quotes loaded`:'Add your provider quotes'} onData={d=>{setQuotes(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/quote_template.csv" download>Get the empty template <Download size={13}/></a><button onClick={()=>setTab('bills')}>{bills?'Edit bill profile':'Use monthly bills'} <ArrowRight size={13}/></button></div><Field label="Acknowledged offer condition IDs · optional"><input value={accepted} placeholder="Comma-separated IDs" onChange={e=>setAccepted(e.target.value)}/></Field><label className="check-row"><input type="checkbox" checked={demo} onChange={e=>{setDemo(e.target.checked);setComparison(null)}}/><span>Try fictional example quotes<small>Illustrative sandbox · explicitly enabled</small></span></label><button className="primary full" disabled={busy} onClick={()=>run(async()=>setComparison(await request('/api/consumer_compare',payload())))}>{busy?<RefreshCw size={16}/>:<Zap size={16}/>}Compare eligible quotes<ArrowRight size={16}/></button></section><div className="right-stack"><section className="panel grid-card"><div className="section-title"><div><div className="eyebrow">THE MARKET IN CONTEXT</div><h2>{market.name} · grid demand</h2></div><span className="source-pill">{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'}</span></div><Chart series={[{name:'Published monthly grid energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/><div className="chart-caption">{history.length} monthly records · Jan 2015–Sep 2026<span>GWh</span></div><p className="subtle">Grid demand provides context. It does not describe an individual retailer or predict your bill.</p></section><section className="how-card"><span className="icon-box"><CheckCircle2 size={19}/></span><h3>The whole quoted cost.</h3><p>Energy + supply charges + annual fees + switching costs − guaranteed credits.</p><div className="how-tags"><span>Tax included</span><span>Eligibility checked</span><span>Dated evidence</span></div></section></div></div>{comparison&&<section className="panel result-panel"><div className="section-title"><div><div className="eyebrow">{demo?'ILLUSTRATIVE SCENARIO':'SUPPLIED QUOTE SCENARIO'}</div><h2>{best?`${best.provider} · lowest supplied first-year cost`:'No eligible quotes'}</h2></div>{best&&<strong className="result-cost">{num(best.first_year_cost,2)} <small>{market.currency}</small></strong>}</div>{best&&<p>Estimated difference from your supplied annual bill: <b>{num(best.estimated_saving,2)} {market.currency}</b>. {best.price_basis}.</p>}<Table rows={comparison.ranked_offers} columns={[["provider","Provider"],["first_year_cost","First-year cost"],["recurring_annual_cost","Recurring cost"],["estimated_saving","Estimated saving"],["evidence","Evidence"]]}/>{comparison.excluded_offers.length>0&&<details><summary>Excluded quotes and reasons ({comparison.excluded_offers.length})</summary><Table rows={comparison.excluded_offers} columns={[["offer_id","Offer"],["reason","Reason"]]}/></details>}<details><summary>Calculation evidence</summary><Json value={comparison}/></details></section>}<Notice>Quotes must be complete and tax inclusive. The comparison covers eligible supplied offers; it is not a whole-market promise. Complex indexed, tiered, demand-charge or export tariffs need a complete scoped quote.</Notice></>}{tab==='bills'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><ReceiptText size={18}/></span><div><h2>A complete latest-year profile</h2><p>Twelve complete months before the current month.</p></div></div><CsvUpload label="Upload anonymous monthly bills" help="month, kwh, billed_total, currency · optional peak_kwh" onData={d=>{setBills(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/example_billing_months.csv" download>Download fictional EUR sample <Download size={13}/></a>{country==='PT'&&<button onClick={()=>{setBills(boot.example_bills);setComparison(null)}}>Load fictional sample</button>}</div><Notice>Use actual tax-inclusive electricity charges, not bank-payment instalments. Remove names, addresses and account numbers. Each month must appear once, in the selected market currency.</Notice><button className="primary full" onClick={()=>setTab('quotes')}>Compare using this profile <ArrowRight size={16}/></button>{bills&&<button className="text-button" onClick={()=>{setBills(null);setComparison(null)}}>Clear monthly profile</button>}</section><section className="panel"><h2>What your data can tell us</h2><div className="explain-row"><span>01</span><div><b>Consumption and current cost</b><p>Your latest-year totals replace the manual annual fields.</p></div></div><div className="explain-row"><span>02</span><div><b>Peak and off-peak allocation</b><p>Supply peak_kwh for every month, or supply your measured peak share separately.</p></div></div><div className="explain-row"><span>03</span><div><b>A starting scenario, not a model winner</b><p>Twelve monthly bills cover only one annual cycle. The grid-model leaderboard cannot select a reliable household forecaster.</p></div></div></section></div>{bills&&<section className="panel"><h2>Supplied monthly profile</h2><Chart series={[{name:'Monthly consumption',values:bills.map(x=>Number(x.kwh))}]} labels={bills.map(x=>x.month)} unit="kWh"/><Table rows={bills} columns={[["month","Month"],["kwh","Consumption · kWh"],["billed_total","Billed electricity cost"],["currency","Currency"]]}/></section>}</>}{tab==='benchmark'&&<><section className="panel"><div className="section-title"><div><h2>The forecast laboratory</h2><p>Same series. Same origins. Validation chooses; test measures.</p></div><span className="source-pill">PROTOCOL V2</span></div><div className="form-grid three"><Field label="Forecast target"><select value={kind} onChange={e=>{setKind(e.target.value);setBench(null)}}><option value="demand">Monthly grid energy · GWh</option><option value="price">Monthly wholesale price · {market.currency}/MWh</option></select></Field><Field label="Provider label · uploaded data only"><input value={provider} placeholder="Exact provider column value" onChange={e=>setProvider(e.target.value)}/></Field><div className="worker-note"><span className="status-dot"/>Single CPU benchmark worker<br/><small>No paid model calls</small></div></div><CsvUpload label={monthly?`${monthly.length} monthly records loaded`:'Use an optional monthly series'} help="timestamp,value,unit,coverage · ≥72 complete months" onData={d=>{setMonthly(d);setBench(null)}} onError={setError}/>{monthly&&<button className="text-button" onClick={()=>{setMonthly(null);setBench(null)}}>Use bundled grid snapshot instead</button>}<div className="protocol-strip"><span><b>1.</b> Training prefix</span><ArrowRight size={14}/><span><b>2.</b> Calibration</span><ArrowRight size={14}/><span><b>3.</b> Validation</span><ArrowRight size={14}/><span><b>4.</b> Test</span></div><div className="button-row"><button className="primary" disabled={busy} onClick={()=>run(async()=>setBench(await request('/api/benchmark',{country,kind,records:monthly,provider})))}>{busy?<RefreshCw size={16}/>:<Play size={16}/>}Run CPU benchmark</button><span className="subtle">Seasonal baselines · SARIMA · Grokked · SARIMAX · GARCH</span></div></section>{!bench&&<section className="panel"><div className="section-title"><h2>Published historical context</h2><span className="source-pill">{market.scope}</span></div>{kind==='demand'?<Chart series={[{name:'Monthly energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/>:<div className="empty">Wholesale history is not bundled. Upload a complete monthly price series to run a pricing benchmark.</div>}</section>}{bench&&<section className="panel"><div className="section-title"><div><div className="eyebrow">VALIDATION-SELECTED</div><h2>{bench.selected_model}</h2><p>{bench.series_scope} · held-out test starts {bench.test_start}</p></div><button className="secondary" onClick={()=>download(bench,'electrocheap-benchmark.json')}><Download size={15}/>Evidence JSON</button></div><Chart unit={bench.unit} labels={bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.timestamp)} series={[{name:'Actual',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.actual),color:'#243344'},{name:bench.selected_model,values:bench.predictions.filter(p=>p.split==='test'&&p.model===bench.selected_model).map(p=>p.forecast),color:'#18a184'},{name:'Seasonal naive',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.forecast),color:'#e59b39',dashed:true}]}/><Table rows={bench.scores.filter(s=>s.split==='test')} columns={[["model","Model"],["MAE","MAE"],["RMSE","RMSE"],["MASE","MASE"],["selected_on_validation","Selected"]]}/><details><summary>Residual GARCH volatility and protocol</summary><Json value={{volatility:bench.residual_volatility,claim:bench.claim,input_sha256:bench.input_sha256,implementation_sha256:bench.implementation_sha256}}/></details></section>}<Notice>At least 72 consecutive complete months. No interpolation. Bias is frozen after calibration; a candidate needs 5% better validation MAE to replace the baseline. GARCH estimates residual volatility and keeps the SARIMAX mean unchanged. Tests are retrospective and descriptive.</Notice></>}{tab==='models'&&<><section className="panel"><div className="section-title"><div><h2>The full recorded model family</h2><p>Archived grid-demand evidence · 24 test targets · six-month forecasts</p></div><span className="source-pill">2026-10-09 ARCHIVE</span></div><Table rows={evidence?.scores} columns={[["model","Model / variant"],["mae_gwh","MAE · GWh"],["mase","MASE"],["skill_vs_seasonal_naive_pct","Skill vs baseline · %"],["selected_on_validation","Selected"]]}/></section><div className="model-cards"><section className="panel"><div className="eyebrow">LIVE CPU CANDIDATES</div><h2>Statistical & Grokked</h2><p>Seasonal baselines, SARIMA, the explicit 80/20 Grokked blend, calendar SARIMAX and residual GARCH.</p><span className="availability live"><CheckCircle2 size={14}/>Runnable in Forecast lab</span></section><section className="panel"><div className="eyebrow">PINNED TRANSFORMERS</div><h2>TimesFM 2.5 · Chronos-2</h2><p>Exact checkpoint revisions and Python package versions preserved from the measured archived runs.</p><span className="availability"><BarChart3 size={14}/>Cached measured evidence</span></section><section className="panel"><div className="eyebrow">HOSTED MODEL DIAGNOSTICS</div><h2>Astra · Sol</h2><p>Archived delegated test diagnostics. No separately authenticated customer inference API is configured.</p><span className="availability"><BarChart3 size={14}/>Diagnostic only</span></section></div><Notice>A separate Super Grokked implementation and the original KMLAIOps SARIMAX-GARCHX source are unavailable. Newly written adapters are not presented under those identities. Grid scores do not establish household accuracy or bill savings.</Notice><section className="panel"><details><summary>Inspect exact versions, source commits and availability</summary><Json value={evidence}/></details></section></>}{tab==='sources'&&<><div className="two-column"><section className="panel"><h2>Official grid & wholesale feed</h2><p className="subtle">Fetch only on request. Freshness and completeness travel with the response.</p><div className="form-grid"><Field label="Complete month · YYYY-MM"><input value={month} onChange={e=>setMonth(e.target.value)}/></Field><Field label="Australian NEM region"><select value={nemRegion} onChange={e=>setNemRegion(e.target.value)}>{boot.au_regions.map(r=><option key={r}>{r}</option>)}</select></Field></div><button className="primary" disabled={busy} onClick={()=>run(async()=>setLive(await request('/api/live_market',{country,region:nemRegion,month})))}><RefreshCw size={15}/>Fetch official data</button></section><section className="panel"><h2>Australian retailer plans</h2><p className="subtle">AER Product Reference Data. Full plan pricing is inspected before any normalization.</p><div className="form-grid"><Field label="Retailer"><select value={brand} onChange={e=>setBrand(e.target.value)}>{boot.aer_brands.map(b=><option key={b}>{b}</option>)}</select></Field><Field label="Postcode · optional"><input value={postcode} placeholder="2000" onChange={e=>setPostcode(e.target.value)}/></Field></div><button className="secondary" disabled={busy} onClick={()=>run(async()=>setPlans(await request('/api/aer_plans',{brand,postcode})))}>Read retailer plans <ArrowRight size={15}/></button></section></div>{live&&<section className="panel"><h2>Fetched market data</h2><Table rows={live.records.slice(0,100)} columns={Object.keys(live.records[0]||{}).map(k=>[k,k])}/><p className="subtle">Showing up to 100 of {live.records.length} source records.</p><details><summary>Source, retrieval time and completeness</summary><Json value={live.metadata}/></details><button className="secondary" onClick={()=>download(live,'electrocheap-live-feed.json')}><Download size={14}/>Download full response</button></section>}{plans&&<section className="panel"><h2>Published retailer plans</h2><Table rows={plans.records} columns={Object.keys(plans.records[0]||{}).map(k=>[k,k])}/><div className="button-row"><Field label="Plan ID"><input value={planId} onChange={e=>setPlanId(e.target.value)} placeholder="Copy from the plan table"/></Field><button className="secondary" disabled={busy||!planId} onClick={()=>run(async()=>setPlan(await request('/api/aer_detail',{brand,plan_id:planId})))}>Inspect full plan</button></div><details><summary>Plan list metadata</summary><Json value={plans.metadata}/></details>{plan&&<Json value={plan}/>}</section>}<section className="panel"><h2>Source registry</h2><Table rows={boot.sources} columns={Object.keys(boot.sources[0]||{}).map(k=>[k,k])}/></section><Notice>Australia covers the NEM, excluding WA and NT. Portugal is mainland only. German live data returns the last SMARD publication block in the month. Wholesale prices are not retail bills; national grids do not reveal retailer-level customer demand.</Notice></>}{tab==='api'&&<><section className="panel"><div className="section-title"><div><h2>Three tools. One auditable engine.</h2><p>Anonymous profiles, dated quotes and explicit evidence.</p></div><a className="secondary" href="/docs" target="_blank" rel="noreferrer">Open REST documentation <ArrowUpRight size={14}/></a></div><div className="api-cards"><div><code>consumer_compare</code><p>One household or site. Annual totals or the latest 12 monthly bills.</p></div><div><code>ngo_compare</code><p>Up to 100 anonymous profiles. Totals stay separate by currency.</p></div><div><code>model_evidence</code><p>Archived grid-demand scores and exact implementation versions.</p></div></div><div className="form-grid"><Field label="REST endpoint"><select value={apiType} onChange={e=>setApiType(e.target.value)}><option>consumer_compare</option><option>ngo_compare</option><option>model_evidence</option></select></Field><div className="button-row"><button className="secondary" onClick={()=>{let p=payload();if(apiType==='model_evidence')p={country};if(apiType==='ngo_compare')p={offers:p.offers,allow_illustrative:p.allow_illustrative,profiles:[{...p,profile_id:'anonymous-001'}]};setJsonInput(JSON.stringify(p,null,2))}}>Use current profile</button></div></div><Field label="JSON request · editable"><textarea rows="14" spellCheck="false" value={jsonInput} onChange={e=>setJsonInput(e.target.value)} placeholder={'{"country":"PT"}'}/></Field><button className="primary" disabled={busy||!jsonInput} onClick={()=>run(async()=>setApiOutput(await request('/api/'+apiType,JSON.parse(jsonInput))))}>Run API request <ArrowRight size={15}/></button>{apiOutput&&<Json value={apiOutput}/>}<details><summary>MCP connection for XenoWAttz</summary><Json value={{mcpServers:{xenowattz:{type:'streamable-http',url:location.origin+'/mcp-server/mcp'}}}}/></details></section><section className="panel"><h2>Keep the decision honest</h2><p>First-year quote cost = annual kWh × rate + 365 × daily charge + annual fees + switching cost − guaranteed credit. A two-period tariff uses the supplied peak/off-peak allocation. The quote must include taxes and all mandatory fees.</p><p>Unknown eligibility, incomplete tariff structures and stale quotes are excluded. Model selection is separate from tariff arithmetic. Forecast accuracy alone does not demonstrate financial savings.</p><Notice>This public research API has no customer billing, tenant isolation, contracting or automatic switching. Inputs are processed in memory. Do not submit personal identifiers. React uploads are parsed in your browser; the normalized data is sent to the API only when you run a request.</Notice></section></>}<footer><span><Zap size={13}/>Electrocheap · XenoWAttz × Bhor Bohr</span><span>Evidence before savings. Always.</span></footer></div></main></div>;1234567895 unmodified lines1516171819202122232425262728293031323334353637383940414243import React,{useState,useEffect} from 'react';import {Zap,Activity,BarChart3,ReceiptText,Network,FileJson,ArrowUpRight,Upload,ArrowRight,Play,CheckCircle2,AlertCircle,Download,RefreshCw,ChevronRight,Info} from 'lucide-react';import Papa from 'papaparse';import AnalysisPanel,{AuditDatasets} from './AnalysisPanel.jsx';const markets={PT:{name:'Portugal',scope:'Mainland grid',currency:'EUR',region:'PT-mainland',flag:'🇵🇹'},DE:{name:'Germany',scope:'National grid load',currency:'EUR',region:'DE-local-grid',flag:'🇩🇪'},AU:{name:'Australia',scope:'NEM · five regions',currency:'AUD',region:'NSW1',flag:'🇦🇺'}};const nav=[['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['analysis','Bulk & swaps',Network],['benchmark','Forecast lab',Activity],['models','Model evidence',BarChart3],['sources','Official feeds',Network],['api','API & methods',FileJson]];async function request(path,payload){let r=await fetch(path,{method:payload===undefined?'GET':'POST',headers:payload===undefined?{}:{'Content-Type':'application/json'},body:payload===undefined?undefined:JSON.stringify(payload)});let data=await r.json();if(!r.ok)throw Error(data.detail||'Request failed');return data;}const num=(n,d=0)=>Number(n).toLocaleString(undefined,{maximumFractionDigits:d});function Json({value}){return <pre className="json">{JSON.stringify(value,null,2)}</pre>}5 unmodified linesfunction download(value,name){let url=URL.createObjectURL(new Blob([JSON.stringify(value,null,2)],{type:'application/json'}));let a=document.createElement('a');a.href=url;a.download=name;a.click();URL.revokeObjectURL(url);}export default function App(){const [boot,setBoot]=useState(null),[country,setCountry]=useState('PT'),[tab,setTab]=useState('quotes'),[error,setError]=useState(''),[busy,setBusy]=useState(false);const [usage,setUsage]=useState(3500),[bill,setBill]=useState(1200),[region,setRegion]=useState('PT-mainland'),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(.5),[powerKva,setPowerKva]=useState(''),[profileSource,setProfileSource]=useState('annual_user_input'),[demo,setDemo]=useState(false),[quotes,setQuotes]=useState(null),[bills,setBills]=useState(null),[accepted,setAccepted]=useState(''),[comparison,setComparison]=useState(null);const [kind,setKind]=useState('demand'),[monthly,setMonthly]=useState(null),[provider,setProvider]=useState(''),[bench,setBench]=useState(null),[evidence,setEvidence]=useState(null);const [month,setMonth]=useState('2026-09'),[nemRegion,setNemRegion]=useState('NSW1'),[live,setLive]=useState(null),[brand,setBrand]=useState('agl'),[postcode,setPostcode]=useState(''),[plans,setPlans]=useState(null),[planId,setPlanId]=useState(''),[plan,setPlan]=useState(null);const [jsonInput,setJsonInput]=useState(''),[apiType,setApiType]=useState('consumer_compare'),[apiOutput,setApiOutput]=useState(null);useEffect(()=>{request('/api/bootstrap').then(d=>{setBoot(d);setMonth(d.latest_month)}).catch(e=>setError(e.message));},[]);useEffect(()=>{let cancel=false;request('/api/model_evidence',{country}).then(d=>{if(!cancel)setEvidence(d)}).catch(e=>setError(e.message));return()=>{cancel=true}},[country]);const market=markets[country];const history=boot?.histories[country]||[];const payload=()=>{let p={country,region,profile_source:profileSource,meter_type:meter,peak_share:Number(peak),allow_illustrative:demo,offers:quotes||(demo?boot.example_quotes.filter(q=>q.country===country):[]),accepted_conditions:accepted.split(',').map(x=>x.trim()).filter(Boolean)};if(powerKva)p.contracted_power_kva=Number(powerKva);if(bills){p.billing_months=bills;if(bills.every(x=>'peak_kwh'in x))delete p.peak_share;}else{p.annual_kwh=Number(usage);p.current_annual_bill=Number(bill)}return p};const run=async(fn)=>{setError('');setBusy(true);try{await fn()}catch(e){setError(e.message)}finally{setBusy(false)}};const changeMarket=c=>{setCountry(c);setRegion(markets[c].region);setComparison(null);setBench(null);setBills(null);setPowerKva('');setProfileSource('annual_user_input');setQuotes(null);setLive(null);setError('')};const best=comparison?.ranked_offers?.[0];let billingUsage=bills?bills.reduce((s,r)=>s+Number(r.kwh||0),0):Number(usage);let billingTotal=bills?bills.reduce((s,r)=>s+Number(r.billed_total||0),0):Number(bill);if(!boot)return <div className="loading"><Zap size={30}/><b>Electrocheap</b><p>{error||'Loading the evidence…'}</p>{error&&<button onClick={()=>location.reload()}>Retry</button>}</div>;return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('quotes')}}><div className="brand-symbol"><Zap size={23} fill="currentColor"/></div><div><strong>XenoWAttz</strong><small>WITH BHOR BOHR</small></div></a><div className="side-divider"/><div className="side-label">ELECTROCHEAP BENCHMARK</div><nav>{nav.map(([id,label,Icon])=><button key={id} onClick={()=>{setTab(id);setError('')}} className={tab===id?'nav-item active':'nav-item'}><Icon size={19}/>{label}{id===tab&&<ChevronRight size={15} className="nav-arrow"/>}</button>)}</nav><div className="side-character"><video autoPlay loop muted playsInline poster="/brand/xenowattz-poster.png" src="/brand/xenowattz_480.mp4"/><div><span className="tiny-dot"/>Bhor Bohr is in the grid.</div></div><div className="side-foot"><span className="status-dot"/>CPU research space<small>Source first. Estimate second.</small></div></aside><main><header className="topbar"><div className="crumb">XenoWAttz <ChevronRight size={13}/><b>Electrocheap</b></div><div className="top-links"><span className="research-badge">RESEARCH PREVIEW</span><a href="/docs" target="_blank" rel="noreferrer">API docs <ArrowUpRight size={14}/></a></div></header><div className="page"><div className="page-heading"><div><div className="eyebrow">ELECTRICITY, WITH THE EVIDENCE ATTACHED</div><h1>{tab==='quotes'?'More clarity. Less bill shock.':tab==='bills'?'Your year, in kilowatt-hours.':tab==='analysis'?'From billing archive to scenario.':tab==='benchmark'?'Challenge the forecast.':tab==='models'?'Every model earns its place.':tab==='sources'?'Go straight to the source.':'The engine behind XenoWAttz.'}</h1><p>{tab==='quotes'?'Compare the offers you can actually use, with every supplied cost included.':tab==='bills'?'A complete bill profile makes a better starting point than a national average.':tab==='analysis'?'Import compressed bills, inspect tariffs, and compare constrained provider plans.':tab==='benchmark'?'Chronological calibration, validation and test. Complexity gets no free pass.':tab==='models'?'TSF, transformers and Astra — inspect the versions and the measured evidence.':tab==='sources'?'Published demand, wholesale prices and Australian retailer plan data.':'React on the surface. Reproducible Python underneath.'}</p></div><div className="market-switch">{Object.entries(markets).map(([c,m])=><button key={c} className={c===country?'selected':''} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>{error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}<div className="stats-row"><div><span>SELECTED MARKET</span><strong>{market.name}<small>{market.flag}</small></strong><p>{market.scope}</p></div><div><span>YOUR CONSUMPTION SCENARIO</span><strong>{num(billingUsage)}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':profileSource==='annual_user_input'?'From your annual input':'Reviewed annualized invoice estimate'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{num(billingTotal,2)}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:'Full electricity cost, tax included'}</p></div></div>{tab==='analysis'&&<AnalysisPanel country={country} quotes={quotes} onError={setError} onProfile={p=>{setCountry(p.country);setRegion(p.region);setUsage(p.annual_kwh);setBill(p.current_annual_bill);setMeter(p.meter_type);setPowerKva(p.contracted_power_kva??'');setProfileSource(p.profile_source);setBills(null);setComparison(null);setTab('quotes')}}/>}{tab==='quotes'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><Zap size={18}/></span><div><h2>Build your comparison</h2><p>Complete quotes. One consistent usage scenario.</p></div><span className="step">01</span></div><div className="form-grid"><Field label="Annual usage · kWh"><input type="number" min="1" value={bills?billingUsage:usage} disabled={!!bills} onChange={e=>setUsage(e.target.value)}/></Field><Field label={`Current annual cost · ${market.currency}`}><input type="number" min="0" value={bills?billingTotal:bill} disabled={!!bills} onChange={e=>setBill(e.target.value)}/></Field><Field label="Eligibility region / grid"><input value={region} onChange={e=>setRegion(e.target.value)}/></Field><Field label="Contracted power · kVA (when applicable)"><input type="number" value={powerKva} placeholder="e.g. 3.45" min="0.1" step="0.05" onChange={e=>setPowerKva(e.target.value)}/></Field><Field label="Meter type"><select value={meter} onChange={e=>setMeter(e.target.value)}><option value="standard">Standard</option><option value="smart">Smart / time of use</option></select></Field></div>{meter==='smart'&&<Field label={`Peak usage share · ${Math.round(peak*100)}%`}><input type="range" min="0" max="1" step=".01" value={peak} onChange={e=>setPeak(e.target.value)}/></Field>}<CsvUpload label={quotes?`${quotes.length} supplied quotes loaded`:'Add your provider quotes'} onData={d=>{setQuotes(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/quote_template.csv" download>Get the empty template <Download size={13}/></a><button onClick={()=>setTab('bills')}>{bills?'Edit bill profile':'Use monthly bills'} <ArrowRight size={13}/></button></div><Field label="Acknowledged offer condition IDs · optional"><input value={accepted} placeholder="Comma-separated IDs" onChange={e=>setAccepted(e.target.value)}/></Field><label className="check-row"><input type="checkbox" checked={demo} onChange={e=>{setDemo(e.target.checked);setComparison(null)}}/><span>Try fictional example quotes<small>Illustrative sandbox · explicitly enabled</small></span></label><button className="primary full" disabled={busy} onClick={()=>run(async()=>setComparison(await request('/api/consumer_compare',payload())))}>{busy?<RefreshCw size={16}/>:<Zap size={16}/>}Compare eligible quotes<ArrowRight size={16}/></button></section><div className="right-stack"><section className="panel grid-card"><div className="section-title"><div><div className="eyebrow">THE MARKET IN CONTEXT</div><h2>{market.name} · grid demand</h2></div><span className="source-pill">{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'}</span></div><Chart series={[{name:'Published monthly grid energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/><div className="chart-caption">{history.length} monthly records · Jan 2015–Sep 2026<span>GWh</span></div><p className="subtle">Grid demand provides context. It does not describe an individual retailer or predict your bill.</p></section><section className="how-card"><span className="icon-box"><CheckCircle2 size={19}/></span><h3>The whole quoted cost.</h3><p>Energy + supply charges + annual fees + switching costs − guaranteed credits.</p><div className="how-tags"><span>Tax included</span><span>Eligibility checked</span><span>Dated evidence</span></div></section></div></div>{comparison&&<section className="panel result-panel"><div className="section-title"><div><div className="eyebrow">{demo?'ILLUSTRATIVE SCENARIO':'SUPPLIED QUOTE SCENARIO'}</div><h2>{best?`${best.provider} · lowest supplied first-year cost`:'No eligible quotes'}</h2></div>{best&&<strong className="result-cost">{num(best.first_year_cost,2)} <small>{market.currency}</small></strong>}</div>{best&&<p>Estimated difference from your supplied annual bill: <b>{num(best.estimated_saving,2)} {market.currency}</b>. {best.price_basis}.</p>}<Table rows={comparison.ranked_offers} columns={[["provider","Provider"],["first_year_cost","First-year cost"],["recurring_annual_cost","Recurring cost"],["estimated_saving","Estimated saving"],["evidence","Evidence"]]}/>{comparison.excluded_offers.length>0&&<details><summary>Excluded quotes and reasons ({comparison.excluded_offers.length})</summary><Table rows={comparison.excluded_offers} columns={[["offer_id","Offer"],["reason","Reason"]]}/></details>}<details><summary>Calculation evidence</summary><Json value={comparison}/></details></section>}<Notice>Quotes must be complete and tax inclusive. The comparison covers eligible supplied offers; it is not a whole-market promise. Complex indexed, tiered, demand-charge or export tariffs need a complete scoped quote.</Notice></>}{tab==='bills'&&<><div className="two-column"><section className="panel"><div className="section-title"><span className="icon-box"><ReceiptText size={18}/></span><div><h2>A complete latest-year profile</h2><p>Twelve complete months before the current month.</p></div></div><button className="secondary full" onClick={()=>setTab('analysis')}><Upload size={16}/>Import ZIP / PDF billing archives</button><CsvUpload label="Upload anonymous monthly bills" help="month, kwh, billed_total, currency · optional peak_kwh" onData={d=>{setBills(d);setComparison(null);setError('')}} onError={setError}/><div className="inline-links"><a href="/downloads/example_billing_months.csv" download>Download fictional EUR sample <Download size={13}/></a>{country==='PT'&&<button onClick={()=>{setBills(boot.example_bills);setComparison(null)}}>Load fictional sample</button>}</div><Notice>Use actual tax-inclusive electricity charges, not bank-payment instalments. Remove names, addresses and account numbers. Each month must appear once, in the selected market currency.</Notice><button className="primary full" onClick={()=>setTab('quotes')}>Compare using this profile <ArrowRight size={16}/></button>{bills&&<button className="text-button" onClick={()=>{setBills(null);setComparison(null)}}>Clear monthly profile</button>}</section><section className="panel"><h2>What your data can tell us</h2><div className="explain-row"><span>01</span><div><b>Consumption and current cost</b><p>Your latest-year totals replace the manual annual fields.</p></div></div><div className="explain-row"><span>02</span><div><b>Peak and off-peak allocation</b><p>Supply peak_kwh for every month, or supply your measured peak share separately.</p></div></div><div className="explain-row"><span>03</span><div><b>A starting scenario, not a model winner</b><p>Twelve monthly bills cover only one annual cycle. The grid-model leaderboard cannot select a reliable household forecaster.</p></div></div></section></div>{bills&&<section className="panel"><h2>Supplied monthly profile</h2><Chart series={[{name:'Monthly consumption',values:bills.map(x=>Number(x.kwh))}]} labels={bills.map(x=>x.month)} unit="kWh"/><Table rows={bills} columns={[["month","Month"],["kwh","Consumption · kWh"],["billed_total","Billed electricity cost"],["currency","Currency"]]}/></section>}</>}{tab==='benchmark'&&<><section className="panel"><div className="section-title"><div><h2>The forecast laboratory</h2><p>Same series. Same origins. Validation chooses; test measures.</p></div><span className="source-pill">PROTOCOL V2</span></div><div className="form-grid three"><Field label="Forecast target"><select value={kind} onChange={e=>{setKind(e.target.value);setBench(null)}}><option value="demand">Monthly grid energy · GWh</option><option value="price">Monthly wholesale price · {market.currency}/MWh</option></select></Field><Field label="Provider label · uploaded data only"><input value={provider} placeholder="Exact provider column value" onChange={e=>setProvider(e.target.value)}/></Field><div className="worker-note"><span className="status-dot"/>Single CPU benchmark worker<br/><small>No paid model calls</small></div></div><CsvUpload label={monthly?`${monthly.length} monthly records loaded`:'Use an optional monthly series'} help="timestamp,value,unit,coverage · ≥72 complete months" onData={d=>{setMonthly(d);setBench(null)}} onError={setError}/>{monthly&&<button className="text-button" onClick={()=>{setMonthly(null);setBench(null)}}>Use bundled grid snapshot instead</button>}<div className="protocol-strip"><span><b>1.</b> Training prefix</span><ArrowRight size={14}/><span><b>2.</b> Calibration</span><ArrowRight size={14}/><span><b>3.</b> Validation</span><ArrowRight size={14}/><span><b>4.</b> Test</span></div><div className="button-row"><button className="primary" disabled={busy} onClick={()=>run(async()=>setBench(await request('/api/benchmark',{country,kind,records:monthly,provider})))}>{busy?<RefreshCw size={16}/>:<Play size={16}/>}Run CPU benchmark</button><span className="subtle">Seasonal baselines · SARIMA · Grokked · SARIMAX · GARCH</span></div></section>{!bench&&<section className="panel"><div className="section-title"><h2>Published historical context</h2><span className="source-pill">{market.scope}</span></div>{kind==='demand'?<Chart series={[{name:'Monthly energy',values:history.map(x=>x.value)}]} labels={history.map(x=>x.timestamp)}/>:<div className="empty">Wholesale history is not bundled. Upload a complete monthly price series to run a pricing benchmark.</div>}</section>}{bench&&<section className="panel"><div className="section-title"><div><div className="eyebrow">VALIDATION-SELECTED</div><h2>{bench.selected_model}</h2><p>{bench.series_scope} · held-out test starts {bench.test_start}</p></div><button className="secondary" onClick={()=>download(bench,'electrocheap-benchmark.json')}><Download size={15}/>Evidence JSON</button></div><Chart unit={bench.unit} labels={bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.timestamp)} series={[{name:'Actual',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.actual),color:'#243344'},{name:bench.selected_model,values:bench.predictions.filter(p=>p.split==='test'&&p.model===bench.selected_model).map(p=>p.forecast),color:'#18a184'},{name:'Seasonal naive',values:bench.predictions.filter(p=>p.split==='test'&&p.model==='Seasonal naive').map(p=>p.forecast),color:'#e59b39',dashed:true}]}/><Table rows={bench.scores.filter(s=>s.split==='test')} columns={[["model","Model"],["MAE","MAE"],["RMSE","RMSE"],["MASE","MASE"],["selected_on_validation","Selected"]]}/><details><summary>Residual GARCH volatility and protocol</summary><Json value={{volatility:bench.residual_volatility,claim:bench.claim,input_sha256:bench.input_sha256,implementation_sha256:bench.implementation_sha256}}/></details></section>}<Notice>At least 72 consecutive complete months. No interpolation. Bias is frozen after calibration; a candidate needs 5% better validation MAE to replace the baseline. GARCH estimates residual volatility and keeps the SARIMAX mean unchanged. Tests are retrospective and descriptive.</Notice></>}{tab==='models'&&<><AuditDatasets/><section className="panel"><div className="section-title"><div><h2>The full recorded model family</h2><p>Archived grid-demand evidence · 24 test targets · six-month forecasts</p></div><span className="source-pill">2026-10-09 ARCHIVE</span></div><Table rows={evidence?.scores} columns={[["model","Model / variant"],["mae_gwh","MAE · GWh"],["mase","MASE"],["skill_vs_seasonal_naive_pct","Skill vs baseline · %"],["selected_on_validation","Selected"]]}/></section><div className="model-cards"><section className="panel"><div className="eyebrow">LIVE CPU CANDIDATES</div><h2>Statistical & Grokked</h2><p>Seasonal baselines, SARIMA, the explicit 80/20 Grokked blend, calendar SARIMAX and residual GARCH.</p><span className="availability live"><CheckCircle2 size={14}/>Runnable in Forecast lab</span></section><section className="panel"><div className="eyebrow">PINNED TRANSFORMERS</div><h2>TimesFM 2.5 · Chronos-2</h2><p>Exact checkpoint revisions and Python package versions preserved from the measured archived runs.</p><span className="availability"><BarChart3 size={14}/>Cached measured evidence</span></section><section className="panel"><div className="eyebrow">HOSTED MODEL DIAGNOSTICS</div><h2>Astra · Sol</h2><p>Archived delegated test diagnostics. No separately authenticated customer inference API is configured.</p><span className="availability"><BarChart3 size={14}/>Diagnostic only</span></section></div><Notice>A separate Super Grokked implementation and the original KMLAIOps SARIMAX-GARCHX source are unavailable. Newly written adapters are not presented under those identities. Grid scores do not establish household accuracy or bill savings.</Notice><section className="panel"><details><summary>Inspect exact versions, source commits and availability</summary><Json value={evidence}/></details></section></>}{tab==='sources'&&<><div className="two-column"><section className="panel"><h2>Official grid & wholesale feed</h2><p className="subtle">Fetch only on request. Freshness and completeness travel with the response.</p><div className="form-grid"><Field label="Complete month · YYYY-MM"><input value={month} onChange={e=>setMonth(e.target.value)}/></Field><Field label="Australian NEM region"><select value={nemRegion} onChange={e=>setNemRegion(e.target.value)}>{boot.au_regions.map(r=><option key={r}>{r}</option>)}</select></Field></div><button className="primary" disabled={busy} onClick={()=>run(async()=>setLive(await request('/api/live_market',{country,region:nemRegion,month})))}><RefreshCw size={15}/>Fetch official data</button></section><section className="panel"><h2>Australian retailer plans</h2><p className="subtle">AER Product Reference Data. Full plan pricing is inspected before any normalization.</p><div className="form-grid"><Field label="Retailer"><select value={brand} onChange={e=>setBrand(e.target.value)}>{boot.aer_brands.map(b=><option key={b}>{b}</option>)}</select></Field><Field label="Postcode · optional"><input value={postcode} placeholder="2000" onChange={e=>setPostcode(e.target.value)}/></Field></div><button className="secondary" disabled={busy} onClick={()=>run(async()=>setPlans(await request('/api/aer_plans',{brand,postcode})))}>Read retailer plans <ArrowRight size={15}/></button></section></div>{live&&<section className="panel"><h2>Fetched market data</h2><Table rows={live.records.slice(0,100)} columns={Object.keys(live.records[0]||{}).map(k=>[k,k])}/><p className="subtle">Showing up to 100 of {live.records.length} source records.</p><details><summary>Source, retrieval time and completeness</summary><Json value={live.metadata}/></details><button className="secondary" onClick={()=>download(live,'electrocheap-live-feed.json')}><Download size={14}/>Download full response</button></section>}{plans&&<section className="panel"><h2>Published retailer plans</h2><Table rows={plans.records} columns={Object.keys(plans.records[0]||{}).map(k=>[k,k])}/><div className="button-row"><Field label="Plan ID"><input value={planId} onChange={e=>setPlanId(e.target.value)} placeholder="Copy from the plan table"/></Field><button className="secondary" disabled={busy||!planId} onClick={()=>run(async()=>setPlan(await request('/api/aer_detail',{brand,plan_id:planId})))}>Inspect full plan</button></div><details><summary>Plan list metadata</summary><Json value={plans.metadata}/></details>{plan&&<Json value={plan}/>}</section>}<section className="panel"><h2>Source registry</h2><Table rows={boot.sources} columns={Object.keys(boot.sources[0]||{}).map(k=>[k,k])}/></section><Notice>Australia covers the NEM, excluding WA and NT. Portugal is mainland only. German live data returns the last SMARD publication block in the month. Wholesale prices are not retail bills; national grids do not reveal retailer-level customer demand.</Notice></>}{tab==='api'&&<><section className="panel"><div className="section-title"><div><h2>Three tools. One auditable engine.</h2><p>Anonymous profiles, dated quotes and explicit evidence.</p></div><a className="secondary" href="/docs" target="_blank" rel="noreferrer">Open REST documentation <ArrowUpRight size={14}/></a></div><div className="api-cards"><div><code>consumer_compare</code><p>One household or site. Annual totals or the latest 12 monthly bills.</p></div><div><code>ngo_compare</code><p>Up to 100 anonymous profiles. Totals stay separate by currency.</p></div><div><code>model_evidence</code><p>Archived grid-demand scores and exact implementation versions.</p></div></div><div className="form-grid"><Field label="REST endpoint"><select value={apiType} onChange={e=>setApiType(e.target.value)}><option>consumer_compare</option><option>ngo_compare</option><option>model_evidence</option></select></Field><div className="button-row"><button className="secondary" onClick={()=>{let p=payload();if(apiType==='model_evidence')p={country};if(apiType==='ngo_compare')p={offers:p.offers,allow_illustrative:p.allow_illustrative,profiles:[{...p,profile_id:'anonymous-001'}]};setJsonInput(JSON.stringify(p,null,2))}}>Use current profile</button></div></div><Field label="JSON request · editable"><textarea rows="14" spellCheck="false" value={jsonInput} onChange={e=>setJsonInput(e.target.value)} placeholder={'{"country":"PT"}'}/></Field><button className="primary" disabled={busy||!jsonInput} onClick={()=>run(async()=>setApiOutput(await request('/api/'+apiType,JSON.parse(jsonInput))))}>Run API request <ArrowRight size={15}/></button>{apiOutput&&<Json value={apiOutput}/>}<details><summary>MCP connection for XenoWAttz</summary><Json value={{mcpServers:{xenowattz:{type:'streamable-http',url:location.origin+'/mcp-server/mcp'}}}}/></details></section><section className="panel"><h2>Keep the decision honest</h2><p>First-year quote cost = annual kWh × rate + 365 × daily charge + annual fees + switching cost − guaranteed credit. A two-period tariff uses the supplied peak/off-peak allocation. The quote must include taxes and all mandatory fees.</p><p>Unknown eligibility, incomplete tariff structures and stale quotes are excluded. Model selection is separate from tariff arithmetic. Forecast accuracy alone does not demonstrate financial savings.</p><Notice>This public research API has no customer billing, tenant isolation, contracting or automatic switching. Inputs are processed in memory. Do not submit personal identifiers. React uploads are parsed in your browser; the normalized data is sent to the API only when you run a request.</Notice></section></>}<footer><span><Zap size={13}/>Electrocheap · XenoWAttz × Bhor Bohr</span><span>Evidence before savings. Always.</span></footer></div></main></div>;
1 unmodified line23456781 unmodified lineWORKDIR /buildCOPY package.json package-lock.json ./RUN npm ci --no-audit --no-fundCOPY index.html main.jsx App.jsx styles.css vite.config.js ./RUN npm run buildFROM python:3.12-slim1 unmodified line23456781 unmodified lineWORKDIR /buildCOPY package.json package-lock.json ./RUN npm ci --no-audit --no-fundCOPY index.html main.jsx App.jsx AnalysisPanel.jsx styles.css vite.config.js ./RUN npm run buildFROM python:3.12-slim
17 unmodified lines1819202122232450 unmodified lines757677787980818283848586878874 unmodified lines16316416516616716816917017 unmodified linesSpace: `kugguk/electrocheap`. CPU Basic; no hardware upgrades, paid inferencecalls, paid Jobs or new storage subscription are required by this build.The public React runtime, REST APIs, three MCP tools and a hosted PortugalCPU benchmark were verified on 2026-10-10. Publication evidence is tracked in`deployment_status.json` and `validation/build_status.json`.50 unmodified lines| POST `/api/consumer_compare` | One household/site's eligible supplied quotes || POST `/api/ngo_compare` | Up to 100 anonymous profiles; currencies separate || POST `/api/model_evidence` | Archived grid scores and exact model versions || POST `/api/benchmark` | CPU demand or wholesale-price benchmark || POST `/api/live_market` | Official data for a complete selected month || POST `/api/aer_plans` | Australian retailer plan list || POST `/api/aer_detail` | Full selected plan detail || GET `/api/health` | Build identity and readiness |The first three are also MCP tools through Streamable HTTP at`/mcp-server/mcp`. They perform calculations/read evidence; no contracting,supplier switching, paid inference, or account/payment mutation is exposed.### Latest-year bills74 unmodified linestests ensure test actuals cannot change selection, calibration or predictions.This is a public research service without customer billing, tenant isolation,PDF bill extraction or automatic switching. Payloads are processed in memory;there is no customer-data database. JSON/CSV limit is 2 MB. One benchmark workerruns at a time. Network readers use a 15-second timeout and reject failed orincomplete feeds; previous results are never labeled fresh. AER complex plansare shown as source records and never silently flattened into savings.17 unmodified lines1819202122232450 unmodified lines7576777879808182838485868788899091929394959674 unmodified lines17117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023117 unmodified linesSpace: `kugguk/electrocheap`. CPU Basic; no hardware upgrades, paid inferencecalls, paid Jobs or new storage subscription are required by this build.The public React runtime, REST APIs, MCP tools and a hosted PortugalCPU benchmark were verified on 2026-10-10. Publication evidence is tracked in`deployment_status.json` and `validation/build_status.json`.50 unmodified lines| POST `/api/consumer_compare` | One household/site's eligible supplied quotes || POST `/api/ngo_compare` | Up to 100 anonymous profiles; currencies separate || POST `/api/model_evidence` | Archived grid scores and exact model versions || POST `/api/billing_import` | Multipart ZIP/PDF/CSV/JSON import; temporary private job || POST `/api/provider_history` | Dated supplied provider tariffs, separated by VAT and contract || POST `/api/analysis_submit` | Bulk CPU forecasts, benchmarks or constrained swap scenarios || POST `/api/analysis_result` | Poll/page private results and get an audit export link || POST `/api/dataset_inspect` | Public benchmark dataset manifest or paged records || GET `/api/analysis/{job_id}/export` | Private normalized audit ZIP, one-hour expiry || GET `/api/datasets/audit.zip` | Public source snapshots, truth, predictions and protocol || POST `/api/benchmark` | CPU demand or wholesale-price benchmark || POST `/api/live_market` | Official data for a complete selected month || POST `/api/aer_plans` | Australian retailer plan list || POST `/api/aer_detail` | Full selected plan detail || GET `/api/health` | Build identity and readiness |MCP tools are `consumer_compare`, `ngo_compare`, `model_evidence`, `billing_import`,`provider_history`, `analysis_submit`, `analysis_result` and `dataset_inspect`,through Streamable HTTP at `/mcp-server/mcp`. They perform calculations/read evidence; no contracting,supplier switching, paid inference, or account/payment mutation is exposed.### Latest-year bills74 unmodified linestests ensure test actuals cannot change selection, calibration or predictions.This is a public research service without customer billing, tenant isolation,or automatic switching. EDP Portugal text PDFs can now be extracted; other templatesand scans require normalized data. Raw documents are discarded after processing;anonymous results are held in a bounded in-memory store for one hour or until restart.An opaque job ID is a bearer capability, not an authenticated customer account.There is no customer-data database. JSON/CSV analysis limit is 2 MB; compressedimports accept up to 25 MiB combined, 250 members / 100 MiB expanded, no nested ZIPs.One bulk CPU queue and the existing single benchmark workerruns at a time. Network readers use a 15-second timeout and reject failed orincomplete feeds; previous results are never labeled fresh. AER complex plansare shown as source records and never silently flattened into savings.## Compressed billing and bulk scenario workflow (v0.3)Open **Bulk & swaps** in React, upload one or more billing archives and wait forthe import to complete. Inspect each meter, its billing period, totals and sourcehashes, then explicitly accept any allocated/annualized profile before using it.Electricity, services, water and payment adjustments are not combined. PDF monthvalues are uniform daily allocations inside invoice periods, not measured monthlyconsumption. The archive parser supports EDP Portugal text PDFs and anonymous monthlyCSV/JSON for PT/DE/AU. Normalized German EUR rows must include `country=DE`.ChatGPT file inputs use the official top-level `files` array and`_meta["openai/fileParams"]`: the host supplies `download_url`, `file_id`, andoptional `file_name`/`mime_type`. Only direct signed OpenAI attachment URLs aredownloaded, without credentials and with size limits; arbitrary URLs and redirectsare rejected. Space upload is a fallback if file delivery is unsupported by the host.`analysis_submit` returns immediately with a private `job_id`; poll `analysis_result`.Use `kind=forecast` for up to ten series and 1–36-month live CPU inference. Availablemodels are `seasonal_naive`, `sarima`, `grokked_sarima`, `sarimax_garch`. Statisticalmodels require 36 consecutive complete months; seasonal naive needs twelve.Grokked is the explicit 80% SARIMA + 20% last-year template implementation, not anunavailable distinct Super Grokked source. Transformer and hosted LLM results remainarchived; no API keys or GPU expenditure are enabled. `kind=benchmark` accepts up tothree complete grid/wholesale histories with at least 72 months each.For `kind=switching`, supply reviewed anonymous profiles or `import_job_id`, completetax-inclusive offers, horizons such as `[3,12,36]`, and named `price_scenarios` withprovider-to-annual-change maps. Optional `rate_curve` maps YYYY-MM to a flat tariff'stax-inclusive energy rate. Supply matching `contracted_power_kva` where known.`minimum_term_months`, `exit_fee`, `credit_vesting_months` and `price_guaranteed_months`are enforced. Signup credit is granted once per provider, with early-exit clawback;unvested terminal credit is provisioned. Unpriced commitments beyond the horizonare excluded. Future enrolment is not presumed unless `assume_future_enrolment=true`is explicitly requested; otherwise later entries need dated `entry_months` withinthe supplied enrolment window. Default unknown term/exit fees are zero assumptions,not verified contract terms. Monthly switching has no activation-delay model.The dynamic program returns a constrained minimum **within the supplied assumptions**.It does not predict an unknowable future tariff winner, negotiate a contract or switchsuppliers. Short/middle/long scenarios can share supplied forecasts, but grid forecastaccuracy is not evidence of household savings or of collusion/market power.Download the private result ZIP before expiry. It contains normalized inputs/results,source hashes, implementation and version metadata, excluding raw bills and accountidentifiers. Public audit downloads contain official grid snapshots and recorded modelevidence only. Customer records are never added to public datasets or committed here.The plugin remains a private preview; this update does not submit it publicly.
4 unmodified lines567891011122 unmodified lines15161718192021222324252611 unmodified lines38394041424344454647484950515253545556575859606162637 unmodified lines7172737475764 unmodified linesimport osimport threadingimport anyiofrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import JSONResponsefrom fastapi.staticfiles import StaticFilesfrom mcp.server.fastmcp import FastMCPfrom mcp.types import ToolAnnotations2 unmodified linesimport pandas as pdfrom core import consumer_compare, ngo_comparefrom models import model_evidencefrom benchmark import run_benchmarkfrom sources import live_market, aer_plans, aer_detail, SOURCES, AU_REGIONS, AER_BRANDS, latest_complete_monthROOT = Path(__file__).resolve().parentBENCH_LOCK = threading.Lock()mcp = FastMCP("XenoWAttz × Bhor Bohr", host="0.0.0.0", instructions="Electrocheap electricity quote scenarios and archived grid-demand evidence. No switching or paid inference.", stateless_http=True, json_response=True)READ_ONLY = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)@mcp.tool(name="consumer_compare", annotations=READ_ONLY)11 unmodified lines"""Read archived PT/DE/AU grid-demand scores and exact TSF, TimesFM 2.5, Chronos-2 and Astra/Sol versions. Cached evidence, not household inference."""return model_evidence(payload)mcp_app = mcp.streamable_http_app()@asynccontextmanagerasync def lifespan(app):async with mcp.session_manager.run(): yieldapi = FastAPI(title="XenoWAttz × Bhor Bohr · Electrocheap", version="0.2.0", lifespan=lifespan)@api.middleware("http")async def body_limit(request: Request, call_next):if request.method == "POST":body = await request.body()if len(body) > 2_000_000:return JSONResponse({"detail":"JSON request limit is 2 MB."}, status_code=413)return await call_next(request)@api.exception_handler(ValueError)async def invalid(request, exc): return JSONResponse({"detail":str(exc)}, status_code=422)@api.get("/api/health")def health(): return {"status":"ok","benchmark":"Electrocheap","plugin":"XenoWAttz","identity":"Bhor Bohr","version":"0.2.0","paid_inference":False}@api.get("/api/bootstrap")def bootstrap():7 unmodified linesapi.post("/api/consumer_compare")(consumer_tool)api.post("/api/ngo_compare")(ngo_tool)api.post("/api/model_evidence")(evidence_tool)@api.post("/api/benchmark")def benchmark(payload: dict):4 unmodified lines567891011122 unmodified lines151617181920212223242526272829303111 unmodified lines4344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051067 unmodified lines1141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581594 unmodified linesimport osimport threadingimport anyiofrom fastapi import FastAPI, HTTPException, Request, UploadFile, Filefrom fastapi.responses import JSONResponse, Response, FileResponsefrom fastapi.staticfiles import StaticFilesfrom mcp.server.fastmcp import FastMCPfrom mcp.types import ToolAnnotations2 unmodified linesimport pandas as pdfrom core import consumer_compare, ngo_comparefrom models import model_evidencefrom archive_import import MAX_COMPRESSEDfrom file_inputs import OpenAIFile, download_filesfrom bulk import submit_import, submit_analysis, analysis_result, audit_exportfrom scenarios import provider_historyfrom datasets import manifest as dataset_manifest, dataset_inspect, public_audit_archive, REGISTRYfrom benchmark import run_benchmarkfrom sources import live_market, aer_plans, aer_detail, SOURCES, AU_REGIONS, AER_BRANDS, latest_complete_monthROOT = Path(__file__).resolve().parentBENCH_LOCK = threading.Lock()mcp = FastMCP("XenoWAttz × Bhor Bohr", host="0.0.0.0", instructions="Electrocheap: import attached billing ZIPs/PDFs with billing_import, poll analysis_result, inspect observed provider_history, and queue bulk forecasting/benchmark/switching with analysis_submit. File uploads are private temporary computations. Review allocated invoice estimates; future tariffs are scenarios. model_evidence reads archives; dataset_inspect exposes public audit data. No automatic switching or paid inference.", stateless_http=True, json_response=True)READ_ONLY = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False)@mcp.tool(name="consumer_compare", annotations=READ_ONLY)11 unmodified lines"""Read archived PT/DE/AU grid-demand scores and exact TSF, TimesFM 2.5, Chronos-2 and Astra/Sol versions. Cached evidence, not household inference."""return model_evidence(payload)@mcp.tool(name="billing_import", annotations=READ_ONLY, meta={"openai/fileParams":["files"]})def import_tool(files: list[OpenAIFile]) -> dict:"""Use this when the user attaches compressed electricity bills: 1–10 ZIP/PDF/CSV/JSON files, ≤25 MiB combined. EDP Portugal text PDFs and normalized PT/DE/AU monthly data supported. Returns a private job_id; poll analysis_result. Water and services are excluded; review estimates. Never send base64 or arbitrary URLs."""return submit_import(download_files(files))@mcp.tool(name="provider_history", annotations=READ_ONLY)def history_tool(payload: dict) -> dict:"""Use this to inspect dated supplied provider tariff observations. Needs records with provider, tariff_id, country, currency, rate_per_kwh, observed_at, tax_included and source_sha256/source_url. Separate tariff/meter and VAT bases. Historical movement is not a future guarantee."""if "import_job_id" in payload:result=analysis_result({"job_id":payload["import_job_id"]})if result["state"]!="completed" or result["kind"]!="billing_import":raise ValueError("Poll the completed billing import first.")payload={"records":result["result"]["price_history"]}return provider_history(payload)@mcp.tool(name="analysis_submit", annotations=READ_ONLY)def analysis_tool(payload: dict) -> dict:"""Use this for bulk CPU analysis. kind=forecast: 1–10 named series with timestamp,value,unit,coverage=1, models seasonal_naive/sarima/grokked_sarima/sarimax_garch, horizon 1–36; statistical models need 36 complete months. kind=benchmark: 1–3 grid/wholesale series, ≥72 complete months. kind=switching: profiles or import_job_id, complete supplied offers, horizons [3,12,36], price_scenarios, contract terms; accept_profile_estimates must be explicit. Returns job_id; poll analysis_result. Transformers/Astra are archives, not live models. No supplier switching."""return submit_analysis(payload)@mcp.tool(name="analysis_result", annotations=READ_ONLY)def result_tool(payload: dict) -> dict:"""Use this to poll a private import/analysis job_id and page results (offset, limit 1–100). queued/running means wait before polling again; completed returns auditable forecasts/plans or normalized profiles. Results expire in one hour/restart. Never claim job success before completed or turn failed forecasts into estimates."""result=analysis_result(payload)if "export_path" in result:result["export_url"]="https://kugguk-electrocheap.hf.space"+result["export_path"]return result@mcp.tool(name="dataset_inspect", annotations=READ_ONLY)def dataset_tool(payload: dict) -> dict:"""Use this for public audit datasets: list with {}, or page dataset_id with offset and limit ��1000. Returns source provenance, exact checksums, units and downloadable official grid snapshots/test predictions. Personal bills never enter this registry."""result=dataset_inspect(payload)result["audit_download_url"]="https://kugguk-electrocheap.hf.space/api/datasets/audit.zip"return resultmcp_app = mcp.streamable_http_app()@asynccontextmanagerasync def lifespan(app):async with mcp.session_manager.run(): yieldapi = FastAPI(title="XenoWAttz × Bhor Bohr · Electrocheap", version="0.3.0", lifespan=lifespan)@api.middleware("http")async def body_limit(request: Request, call_next):if request.method == "POST":maximum=MAX_COMPRESSED+1_000_000 if request.url.path=="/api/billing_import" else 2_000_000if int(request.headers.get("content-length","0"))>maximum:return JSONResponse({"detail":"Request size limit exceeded."},status_code=413)body = await request.body()if len(body) > maximum:return JSONResponse({"detail":"Request size limit exceeded."}, status_code=413)return await call_next(request)@api.exception_handler(ValueError)async def invalid(request, exc): return JSONResponse({"detail":str(exc)}, status_code=422)@api.get("/api/health")def health(): return {"status":"ok","benchmark":"Electrocheap","plugin":"XenoWAttz","identity":"Bhor Bohr","version":"0.3.0","paid_inference":False,"bulk_worker":"one bounded CPU queue","private_result_retention_seconds":3600}@api.get("/api/bootstrap")def bootstrap():7 unmodified linesapi.post("/api/consumer_compare")(consumer_tool)api.post("/api/ngo_compare")(ngo_tool)api.post("/api/model_evidence")(evidence_tool)api.post("/api/provider_history")(history_tool)api.post("/api/analysis_submit")(analysis_tool)api.post("/api/analysis_result")(result_tool)api.post("/api/dataset_inspect")(dataset_tool)@api.post("/api/billing_import")async def upload_bills(files: list[UploadFile] = File(...)):if not 1<=len(files)<=10:raise ValueError("Select 1–10 files.")inputs=[];size=0try:for file in files:content=await file.read(MAX_COMPRESSED+1)size+=len(content)if size>MAX_COMPRESSED:raise ValueError("Combined archive/file limit is 25 MiB.")inputs.append((file.filename or "attachment.zip",content))return submit_import(inputs)finally:for file in files:await file.close()@api.get("/api/analysis/{job_id}/export")def export_analysis(job_id: str):return Response(audit_export(job_id),media_type="application/zip",headers={"Content-Disposition":"attachment; filename=electrocheap-private-audit.zip","Cache-Control":"no-store"})@api.get("/api/datasets/manifest")def public_datasets():return dataset_manifest()@api.get("/api/datasets/audit.zip")def public_dataset_audit():return Response(public_audit_archive(),media_type="application/zip",headers={"Content-Disposition":"attachment; filename=electrocheap-public-benchmark-audit.zip"})@api.get("/api/datasets/{dataset_id}/download")def public_dataset_download(dataset_id: str):if dataset_id not in REGISTRY or not (ROOT/REGISTRY[dataset_id][0]).is_file():raise HTTPException(404,"Unknown public dataset.")path=ROOT/REGISTRY[dataset_id][0]return FileResponse(path,media_type="text/csv",filename=dataset_id+".csv")@api.post("/api/benchmark")def benchmark(payload: dict):
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Bounded, in-memory bill imports. No raw PDFs, account IDs or text are retained."""from collections import defaultdictfrom datetime import date, timedeltafrom io import BytesIO, StringIOfrom pathlib import PurePosixPathfrom zipfile import ZipFile, BadZipFileimport calendarimport csvimport hashlibimport hmacimport jsonimport mathimport reimport secretsimport statimport unicodedata
from pypdf import PdfReader
MAX_COMPRESSED = 25 * 1024 * 1024MAX_EXPANDED = 100 * 1024 * 1024MAX_MEMBER = 8 * 1024 * 1024MAX_FILES = 250MAX_PAGES = 30PARSER_VERSION = "electrocheap-billing-import-v1"MONTHS = {"jan": 1, "fev": 2, "mar": 3, "abr": 4, "mai": 5, "jun": 6, "jul": 7, "ago": 8, "set": 9, "out": 10, "nov": 11, "dez": 12}DATE_RANGE = re.compile(r"(\d{1,2})\s+(?:de\s+)?([a-zç]+)(?:\s+(?:de\s+)?(\d{4}))?\s+a\s+(\d{1,2})\s+(?:de\s+)?([a-zç]+)(?:\s+(?:de\s+)?(\d{4}))?", re.I)AMOUNT = r"(?<![\d.,])(-?(?:\d{1,3}(?: \d{3})+|\d+)(?:,\d+)?)"
def digest(data): return hashlib.sha256(data).hexdigest()
def decimal(value): n = float(value.replace(" ", "").replace(".", "").replace(",", ".")) if not math.isfinite(n): raise ValueError("Nonfinite bill value.") return n
def period(text, reference_year=None): match = DATE_RANGE.search(text.lower()) if not match: raise ValueError("Billing period could not be extracted.") d1, m1, y1, d2, m2, y2 = match.groups() m1, m2 = MONTHS[m1[:3]], MONTHS[m2[:3]] y2 = int(y2 or y1 or reference_year or date.today().year) y1 = int(y1 or (y2 - (m1 > m2))) start, end = date(y1, m1, int(d1)), date(y2, m2, int(d2)) if start > end or (end - start).days > 400: raise ValueError("Invalid or excessively long billing period.") return start, end
def parse_edp(text, source_hash, key): header = re.search(r"Per[ií]odo de fatura[çc][ãa]o:\s*([^\n]+)", text, re.I) if not header: raise ValueError("EDP billing period missing.") start, end = period(header.group(1)) cpe = re.search(r"\bPT\s*\d[\d ]{14,24}[A-Z]{2}\b", text) if not cpe: raise ValueError("Cannot safely separate electricity meters: CPE not found.") meter_id = hmac.new(key, cpe.group().replace(" ", "").encode(), "sha256").hexdigest()[:16] # Invoice identifiers are used only for duplicate detection, never returned. invoice_re = re.compile(r"Fatura\s+n[ºo.°]+\s*(FT[^\n]+?)\s*De:\s*[^\n]+?Valor:\s*" + AMOUNT + r"\s*€", re.I) invoices = list(invoice_re.finditer(text)) if not invoices: raise ValueError("EDP invoice charge could not be extracted.") first = invoices[0] invoice_key = digest(re.sub(r"\s+", "", first.group(1)).encode()) electricity_total = decimal(first.group(2)) unique = set() extra_electricity = 0.0 excluded_services = 0.0 for i, match in enumerate(invoices): ident = re.sub(r"\s+", "", match.group(1)) if ident in unique: continue unique.add(ident) if ident == re.sub(r"\s+", "", first.group(1)): continue section = text[match.end():invoices[i+1].start() if i+1 < len(invoices) else len(text)] value = decimal(match.group(2)) if re.search(r"Contribui[çc][ãa]o\s+Audiovisual", section, re.I): extra_electricity += value else: excluded_services += value energy_section = text[first.end():] power = re.search(r"Pot[eê]ncia\s*\(" + AMOUNT + r"\s*kVA\)", energy_section, re.I) if not power: raise ValueError("EDP contracted power missing; manual review required.") energy_only = energy_section[:power.start()] consumption, rates = 0.0, [] estimated = False for line in energy_only.splitlines(): if "estimado" in line.lower(): estimated = True found = re.search(AMOUNT + r"\s*kWh\s+" + AMOUNT + r"\s*€\s+" + AMOUNT + r"\s*€", line) if found and not re.search(r"IEC|imposto|taxa", line, re.I): kwh, rate = decimal(found.group(1)), decimal(found.group(2)) gross = decimal(found.group(3)) if not math.isclose(kwh*rate,gross,abs_tol=.03,rel_tol=.001): raise ValueError("EDP quantity/unit-price/charge reconciliation failed.") if kwh < 0 or not 0 <= rate <= 10: raise ValueError("EDP consumption adjustments need manual review.") consumption += kwh dates = DATE_RANGE.search(line) rs, re_ = period(dates.group(), end.year) if dates else (start, end) discount = re.search(r"(\d+(?:,\d+)?)\s*%\s*\(", line) fraction = decimal(discount.group(1)) / 100 if discount else 0 rates.append({"period_start": rs.isoformat(), "period_end": re_.isoformat(), "quantity_kwh": kwh, "rate_per_kwh": round(rate * (1 - fraction), 6), "list_rate_per_kwh": rate, "tax_included": False, "date_basis": "line_period" if dates else "invoice_period; rate-change date uncertain"}) if not rates: raise ValueError("No supported EDP energy charge rows found.") daily_rates = [] power_section = energy_section[power.end():] for line in power_section.splitlines(): if "Tarifa" in line or "tarifa" in line: continue found = re.search(r"(\d+)\s*dias\s+" + AMOUNT + r"\s*€", line) if found: dates = DATE_RANGE.search(line) ds, de = period(dates.group(), end.year) if dates else (start, end) discount = re.search(r"(\d+(?:,\d+)?)\s*%\s*\(", line) fraction = decimal(discount.group(1)) / 100 if discount else 0 daily_rates.append({"period_start": ds.isoformat(), "period_end": de.isoformat(), "daily_charge": round(decimal(found.group(2)) * (1 - fraction), 6), "tax_included": False}) if re.search(r"A Total|Total.*sem IVA", line): break return {"profile_id": "meter-" + meter_id, "country": "PT", "region": "PT-mainland", "currency": "EUR", "provider": "EDP Comercial", "tariff_type": "flat", "contracted_power_kva": decimal(power.group(1)), "meter_type": "standard", "period_start": start.isoformat(), "period_end": end.isoformat(), "kwh": consumption, "electricity_charges": round(electricity_total + extra_electricity, 2), "excluded_service_charges": round(excluded_services, 2), "estimated_readings_present": estimated, "energy_rates": rates, "daily_rates": daily_rates, "source_sha256": source_hash, "_invoice_key": invoice_key, "cost_basis": "Electricity invoice plus separately invoiced audiovisual charge; excludes services, credit notes and payment adjustments.", "review_required": True}
def parse_pdf(content, key): reader = PdfReader(BytesIO(content), strict=False) if reader.is_encrypted or len(reader.pages) > MAX_PAGES: raise ValueError("Encrypted PDFs or PDFs over 30 pages are unsupported.") text = "\n".join(p.extract_text() or "" for p in reader.pages) if len(text) > 500_000: raise ValueError("PDF text limit exceeded.") if len(text.strip()) < 60: return None, "scanned_pdf_requires_ocr_or_normalized_csv" text = unicodedata.normalize("NFKC", text) if "EDP Comercial" in text: return parse_edp(text, digest(content), key), None if re.search(r"água|saneamento|res[ií]duos.*urbanos", text, re.I): return None, "water_bill_excluded_from_electricity" return None, "unsupported_pdf_template; supply normalized CSV/JSON"
def unpack_inputs(files): members, expanded = [], 0 if not 1 <= len(files) <= 10 or sum(len(b) for _, b in files) > MAX_COMPRESSED: raise ValueError("Supply 1–10 files, at most 25 MiB combined.") for filename, content in files: extension = PurePosixPath(filename.lower()).suffix if extension == ".zip": try: with ZipFile(BytesIO(content)) as archive: infos = archive.infolist() if len(infos) > MAX_FILES: raise ValueError("ZIP contains more than 250 members.") for info in infos: path = PurePosixPath(info.filename.replace("\\", "/")) mode = info.external_attr >> 16 if path.is_absolute() or ".." in path.parts or re.match(r"^[a-zA-Z]:", str(path)) or stat.S_ISLNK(mode) or info.flag_bits & 1: raise ValueError("Unsafe ZIP path, symlink or encrypted member.") if info.is_dir() or path.name.startswith(".") or "__MACOSX" in path.parts: continue expanded += info.file_size if info.file_size > MAX_MEMBER or expanded > MAX_EXPANDED or info.file_size > max(info.compress_size, 1) * 200: raise ValueError("ZIP expansion/file/ratio limit exceeded.") if path.suffix.lower() == ".zip": raise ValueError("Nested ZIP archives are unsupported.") members.append((str(path), archive.read(info))) except BadZipFile: raise ValueError("Invalid ZIP archive.") from None else: expanded += len(content) if len(content) > MAX_MEMBER: raise ValueError("Individual file exceeds 8 MiB.") members.append((filename, content)) if len(members) > MAX_FILES or expanded > MAX_EXPANDED: raise ValueError("Import exceeds 250 files / 100 MiB expanded.") return members
def monthly_from_invoices(invoices): buckets = defaultdict(lambda: {"kwh": 0.0, "billed_total": 0.0, "days": set(), "sources": set()}) overlaps = set() for bill in invoices: start, end = date.fromisoformat(bill["period_start"]), date.fromisoformat(bill["period_end"]) days = (end - start).days + 1 for offset in range(days): current = start + timedelta(days=offset) month = current.strftime("%Y-%m") bucket = buckets[month] if current in bucket["days"]: overlaps.add(month) bucket["days"].add(current) bucket["sources"].add(bill["source_sha256"]) bucket["kwh"] += bill["kwh"] / days bucket["billed_total"] += bill["electricity_charges"] / days rows = [] for month, bucket in sorted(buckets.items()): y, m = map(int, month.split("-")) rows.append({"month": month, "kwh": round(bucket["kwh"], 6), "billed_total": round(bucket["billed_total"], 6), "currency": invoices[0]["currency"], "coverage": round(len(bucket["days"]) / calendar.monthrange(y, m)[1], 6), "allocation": "uniform daily allocation within each invoice; not measured monthly usage", "overlap": month in overlaps, "source_sha256": sorted(bucket["sources"])}) return rows
def import_files(files, key=None): key = key or secrets.token_bytes(32) members = unpack_inputs(files) invoices, documents, normalized, seen_bytes, seen_invoice = [], [], [], set(), set() for index, (filename, content) in enumerate(members): source_hash = digest(content) doc = {"document_id": f"document-{index+1:04d}", "sha256": source_hash, "bytes": len(content)} if source_hash in seen_bytes: doc["status"] = "duplicate_file_excluded" documents.append(doc) continue seen_bytes.add(source_hash) extension = PurePosixPath(filename.lower()).suffix try: if extension == ".pdf": bill, excluded = parse_pdf(content, key) if bill: if bill["_invoice_key"] in seen_invoice: doc["status"] = "duplicate_invoice_excluded" else: seen_invoice.add(bill.pop("_invoice_key")) bill["document_id"] = doc["document_id"] invoices.append(bill) doc["status"] = "electricity_extracted_review_required" else: doc["status"] = excluded elif extension in {".csv", ".json"}: text = content.decode("utf-8-sig") rows = list(csv.DictReader(StringIO(text))) if extension == ".csv" else json.loads(text) if not isinstance(rows, list) or len(rows) > 5000: raise ValueError("Normalized bill files need a list of at most 5000 rows.") allowed = {"profile_id", "country", "region", "provider", "meter_type", "month", "kwh", "billed_total", "currency", "peak_kwh"} staged=[] for row in rows: if not isinstance(row, dict) or set(row) - allowed or not {"month", "kwh", "billed_total", "currency"} <= set(row): raise ValueError("Normalized bills contain missing or unsupported fields; remove personal identifiers.") if not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", str(row["month"])): raise ValueError("Use YYYY-MM months.") country = row.get("country", "AU" if row["currency"] == "AUD" else "PT") if country not in {"PT", "DE", "AU"} or row["currency"] != ("AUD" if country == "AU" else "EUR"): raise ValueError("Country/currency mismatch.") safe = {k: row[k] for k in allowed & row.keys()} original_id = str(row.get("profile_id", "uploaded-profile")) safe["profile_id"] = "profile-" + hmac.new(key, original_id.encode(), "sha256").hexdigest()[:16] safe["country"] = country for field in ["kwh", "billed_total", "peak_kwh"]: if field in safe: value = float(safe[field]) if not math.isfinite(value) or not 0 <= value <= 1e8: raise ValueError("Bill values must be finite and nonnegative.") safe[field] = value safe.update(coverage=1.0, allocation="user-supplied monthly totals", source_sha256=[source_hash]) staged.append(safe) normalized.extend(staged) doc["status"] = "normalized_monthly_rows_imported" else: doc["status"] = "unsupported_file_type_excluded" except Exception as error: # PDF text, paths and upstream parser exceptions may contain private data. doc["status"] = "manual_review_required" doc["reason"] = str(error) if isinstance(error, ValueError) and extension != ".pdf" else "Template or PDF parsing failed; no financial values inferred." documents.append(doc) grouped = defaultdict(list) for bill in invoices: grouped[bill["profile_id"]].append(bill) profiles, price_history = [], [] for pid, bills in sorted(grouped.items()): monthly = monthly_from_invoices(bills) first = bills[0] covered = sum(row["coverage"] * calendar.monthrange(*map(int, row["month"].split("-")))[1] for row in monthly) total_kwh = sum(b["kwh"] for b in bills) total_cost = sum(b["electricity_charges"] for b in bills) overlap = any(row["overlap"] for row in monthly) profiles.append({"profile_id": pid, "country": first["country"], "region": first["region"], "currency": first["currency"], "provider": first["provider"], "meter_type": first["meter_type"], "contracted_power_kva": first["contracted_power_kva"], "invoice_count": len(bills), "observed_kwh": round(total_kwh, 3), "observed_electricity_charges": round(total_cost, 2), "covered_days": round(covered), "annual_kwh": round(total_kwh * 365 / covered, 3) if covered and not overlap else None, "current_annual_bill": round(total_cost * 365 / covered, 2) if covered and not overlap else None, "profile_source": "observed invoice totals annualized over covered days", "needs_review": True, "overlapping_periods": overlap, "monthly": monthly, "period_start": min(b["period_start"] for b in bills), "period_end": max(b["period_end"] for b in bills)}) for bill in bills: for rate in bill["energy_rates"]: price_history.append({**rate, "provider": first["provider"], "profile_id": pid, "tariff_id": pid, "country": first["country"], "currency": first["currency"], "unit": "EUR/kWh", "observed_at": bill["period_end"], "source_sha256": bill["source_sha256"]}) for pid in sorted({r["profile_id"] for r in normalized}): rows = sorted([r for r in normalized if r["profile_id"] == pid], key=lambda x: x["month"]) if len({r["month"] for r in rows}) != len(rows): raise ValueError("Duplicate normalized profile months; merge deliberately before import.") currencies = {r["currency"] for r in rows} if len(currencies) != 1 or len({r["country"] for r in rows}) != 1: raise ValueError("A profile cannot mix countries or currencies.") annual = rows[-12:] complete_year = len(annual) == 12 and all((int(b["month"][:4])*12+int(b["month"][5:]))-(int(a["month"][:4])*12+int(a["month"][5:])) == 1 for a,b in zip(annual,annual[1:])) profiles.append({"profile_id": pid, "country": rows[0]["country"], "region": rows[0].get("region", "PT-mainland" if rows[0]["country"]=="PT" else ""), "currency": rows[0]["currency"], "meter_type": rows[0].get("meter_type", "standard"), "provider": rows[0].get("provider", "supplied profile"), "monthly": rows, "annual_kwh": sum(r["kwh"] for r in annual) if complete_year else None, "current_annual_bill": sum(r["billed_total"] for r in annual) if complete_year else None, "profile_source": "latest supplied 12 complete months" if complete_year else "incomplete supplied monthly history", "needs_review": not complete_year}) return {"status": "billing_imported", "parser_version": PARSER_VERSION, "archive_sha256": [digest(b) for _, b in files], "documents": documents, "electricity_invoice_count": len(invoices), "profiles": profiles, "invoices": invoices, "price_history": price_history, "privacy": "In-memory extraction. Raw documents, names, addresses, CPEs, account and invoice IDs are not retained or returned. Anonymous normalized results expire after one hour.", "limits": ["EDP Portugal text PDFs plus normalized PT/DE/AU monthly CSV/JSON are supported; other PDF templates and scans need manual normalization.", "PDF months are allocated uniformly over invoice days, not measured monthly consumption. Review totals before comparison.", "Water, services and payment adjustments are excluded; bundled discounts and credit notes require manual review.", "Observed provider unit prices exclude VAT and cannot be substituted directly for tax-inclusive offers."]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262"""One bounded CPU queue for imports, forecasts, benchmarks and swap scenarios."""from concurrent.futures import ThreadPoolExecutorfrom datetime import date, datetime, timezonefrom io import BytesIOfrom pathlib import Pathfrom threading import Lockfrom zipfile import ZipFile, ZIP_DEFLATEDimport hashlibimport jsonimport secretsimport timeimport warnings
import numpy as npimport pandas as pdfrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom arch import arch_model
from archive_import import import_filesfrom benchmark import run_benchmark, fitted, calendarfrom scenarios import switching_scenarios, hash_json, integer
TTL_SECONDS = 3600MAX_JOBS = 12MAX_STORED_BYTES = 32 * 1024 * 1024POOL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="electrocheap-analysis")LOCK = Lock()JOBS = {}
def cleanup(): now = time.monotonic() for key in list(JOBS): if now - JOBS[key]["created"] > TTL_SECONDS: del JOBS[key]
def _reserve(kind, inputs): with LOCK: cleanup() stored = sum(j.get("size", 0) for j in JOBS.values()) if len(JOBS) >= MAX_JOBS or stored >= MAX_STORED_BYTES: raise ValueError("Analysis queue/storage is full; results expire after one hour.") jid = secrets.token_urlsafe(24) JOBS[jid] = {"created":time.monotonic(),"kind":kind,"state":"queued", "inputs":inputs, "created_at":datetime.now(timezone.utc).isoformat()} return jid
def _worker(jid, operation): with LOCK: if jid not in JOBS: return JOBS[jid]["state"] = "running" try: result = operation() packed = json.dumps(result, allow_nan=False).encode() if len(packed) > 8*1024*1024: raise ValueError("Result exceeds 8 MiB; reduce the batch.") with LOCK: if jid in JOBS: if sum(j.get("size",0) for j in JOBS.values())+len(packed)>MAX_STORED_BYTES: raise ValueError("Result storage is full; retry after expiry.") JOBS[jid].update(state="completed", result=result, size=len(packed)) except Exception as error: with LOCK: if jid in JOBS: JOBS[jid].update(state="failed",error=str(error)[:500] if isinstance(error,ValueError) else "Computation failed; no result claimed.")
def submit_import(files): # A preview of compressed bytes is held only by the pending worker, not in the store. inputs = {"file_count":len(files),"files_sha256":[hashlib.sha256(b).hexdigest() for _,b in files]} jid = _reserve("billing_import", inputs) POOL.submit(_worker,jid,lambda:import_files(files)) return ticket(jid)
def monthly_series(raw): records = raw.get("records",[]) if not isinstance(records,list) or not 12<=len(records)<=600: raise ValueError("Each live forecast needs 12–600 complete monthly observations; Grokked/SARIMA need at least 36.") d = pd.DataFrame(records) if not {"timestamp","value","unit","coverage"}<=set(d): raise ValueError("Series need timestamp,value,unit,coverage.") stamps = pd.to_datetime(d.timestamp,format="ISO8601",errors="raise") if stamps.dt.tz is not None or not (stamps==stamps.dt.to_period("M").dt.to_timestamp()).all(): raise ValueError("Use timezone-free month-start observations.") d = d.assign(timestamp=stamps).sort_values("timestamp") if not d.timestamp.reset_index(drop=True).equals(pd.Series(pd.date_range(d.timestamp.iloc[0],periods=len(d),freq="MS"))): raise ValueError("Complete consecutive months required; no interpolation.") if d.timestamp.iloc[-1]>=pd.Timestamp(date.today().replace(day=1)): raise ValueError("Current/future months are not complete actuals.") d["value"] = pd.to_numeric(d.value,errors="raise") if not np.isfinite(d.value).all() or not (pd.to_numeric(d.coverage)==1).all(): raise ValueError("Forecast actuals need finite values and coverage=1.") units = set(d.unit) if len(units)!=1 or not units <= {"kWh","GWh","EUR/kWh","AUD/kWh","EUR/MWh","AUD/MWh"}: raise ValueError("Use one explicit electricity usage or price unit per series.") if not next(iter(units)).endswith("/MWh") and (d.value<0).any(): raise ValueError("Only wholesale-price actuals may be negative.") return d.reset_index(drop=True)
def bulk_forecast(payload): raw_series = payload.get("series",[]) if not isinstance(raw_series,list) or not 1<=len(raw_series)<=10: raise ValueError("Supply 1–10 series per forecast job.") steps = integer(payload.get("horizon_months",12),"horizon_months",1,36) models = payload.get("models",["seasonal_naive","grokked_sarima"]) allowed = {"seasonal_naive","sarima","grokked_sarima","sarimax_garch"} if not isinstance(models,list) or not models or len(models)>4 or not set(models)<=allowed: raise ValueError("Live models: seasonal_naive, sarima, grokked_sarima, sarimax_garch. Transformers/Astra are archived evidence only.") output=[] seen=set() for raw in raw_series: sid = str(raw.get("series_id","")) if not sid or sid in seen or len(sid)>100: raise ValueError("Use unique anonymous series_id values, at most 100 characters.") seen.add(sid) d = monthly_series(raw) y = d.value.to_numpy(dtype=float) index = pd.DatetimeIndex(d.timestamp) future = pd.date_range(index[-1]+pd.offsets.MonthBegin(),periods=steps,freq="MS") template = np.resize(y[-12:],steps) mean,std = float(y.mean()),max(float(y.std()),1e-8) estimates, failures, notes = {}, [], [] for model in models: try: variance = None if model=="seasonal_naive": point=template.copy() else: if len(d)<36: raise ValueError("At least 36 consecutive measured months required for statistical seasonal models.") with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") x, xf = calendar(index), calendar(future) xm,xs = x.mean(axis=0),np.maximum(x.std(axis=0),1e-8) cal = model=="sarimax_garch" fit = fitted(SARIMAX((y-mean)/std, exog=(x-xm)/xs if cal else None, order=(1,1,1),seasonal_order=(1,0,1,12), enforce_stationarity=False,enforce_invertibility=False)) point=np.asarray(fit.forecast(steps,exog=(xf-xm)/xs if cal else None))*std+mean if model=="grokked_sarima": point=.8*point+.2*template if cal: vol=arch_model(np.asarray(fit.resid)[12:],mean="Zero",vol="GARCH",p=1,q=1,rescale=False).fit(disp="off",show_warning=False,options={"maxiter":300}) if vol.convergence_flag: raise ValueError("Residual GARCH did not converge.") variance=(np.asarray(vol.forecast(horizon=steps,reindex=False).residual_variance.iloc[-1])*std**2).tolist() notes.extend(sorted({type(w.message).__name__ for w in caught})) if not np.isfinite(point).all(): raise ValueError("Nonfinite forecast; no output accepted.") if not d.unit.iloc[0].endswith("/MWh"): point=np.maximum(point,0) estimates[model]={"predictions":[{"timestamp":t.date().isoformat(),"value":float(v)} for t,v in zip(future,point)], "residual_variance":variance,"unit":d.unit.iloc[0]} except Exception as error: failures.append({"model":model,"reason":str(error)[:300] if isinstance(error,ValueError) else "Fit failed; no forecast claimed."}) output.append({"series_id":sid,"origin":index[-1].date().isoformat(),"observations":len(d), "input_sha256":hash_json(raw),"models":estimates,"failures":failures,"warnings":sorted(set(notes))}) return {"status":"bulk_live_cpu_forecasts","series":output,"horizon_months":steps, "grokked_definition":"forecast_lab_pro_v2 Grokked SARIMA: 80% SARIMA(1,1,1)(1,0,1,12) + 20% last-year seasonal template. Distinct Super Grokked source unavailable.", "limits":"No model winner is inferred from these fits. Predictions are conditional extrapolations; GARCH is residual variance, not calibrated forecast intervals. Household, tariff and grid series are separate targets. Archived transformer/LLM evidence is not live inference."}
def bulk_benchmark(payload): series = payload.get("series",[]) if not isinstance(series,list) or not 1<=len(series)<=3: raise ValueError("Supply 1–3 benchmark series per job.") results=[] for raw in series: kind=raw.get("kind","demand") if kind not in {"demand","price"}: raise ValueError("Benchmark kind must be demand or price.") result=run_benchmark(pd.DataFrame(raw.get("records",[])),kind) results.append({"series_id":str(raw.get("series_id","series"))[:100],**result}) return {"status":"bulk_cpu_benchmark","series":results}
def submit_analysis(payload): if not isinstance(payload,dict): raise ValueError("Supply an analysis object.") kind=payload.get("kind","switching") request=dict(payload) imported=request.pop("import_job_id",None) if imported: with LOCK: cleanup() job=JOBS.get(imported) if not job or job["state"]!="completed" or job["kind"]!="billing_import": raise ValueError("Import result missing, expired or incomplete; upload again.") request.setdefault("profiles",job["result"]["profiles"]) operations={"switching":switching_scenarios,"forecast":bulk_forecast,"benchmark":bulk_benchmark} if kind not in operations: raise ValueError("Analysis kind must be switching, forecast or benchmark.") # Bound the queue's input memory; individual algorithms validate their schemas. if len(json.dumps(request,allow_nan=False).encode())>2_000_000: raise ValueError("Normalized analysis JSON limit is 2 MB.") jid=_reserve(kind,request) POOL.submit(_worker,jid,lambda:operations[kind](request)) return ticket(jid)
def ticket(jid): return {"status":"analysis_queued","job_id":jid,"expires_in_seconds":TTL_SECONDS, "next_tool":"analysis_result","privacy":"This opaque job_id is a private bearer capability; share only with intended viewers. In-memory results expire after one hour or restart."}
def analysis_result(payload): jid=str(payload.get("job_id","")) offset=integer(payload.get("offset",0),"offset",0,100000) limit=integer(payload.get("limit",20),"limit",1,100) with LOCK: cleanup() job=JOBS.get(jid) if not job: raise ValueError("Job not found or expired.") response={"job_id":jid,"state":job["state"],"kind":job["kind"],"created_at":job["created_at"], "expires_in_seconds":max(0,round(TTL_SECONDS-(time.monotonic()-job["created"])))} if job["state"]=="failed": response["error"]=job["error"] if job["state"]=="completed": result=job["result"] key="profiles" if "profiles" in result else "series" response["result"]={k:v for k,v in result.items() if k not in {key,"invoices","documents","price_history"}} response["result"][key]=result.get(key,[])[offset:offset+limit] if job["kind"]=="billing_import": response["result"]["document_counts"]={s:sum(d["status"]==s for d in result["documents"]) for s in {d["status"] for d in result["documents"]}} response["result"]["price_history"]=result["price_history"] response["total_items"]=len(result.get(key,[])) response["next_offset"]=offset+limit if offset+limit<response["total_items"] else None response["export_path"]=f"/api/analysis/{jid}/export" return response
def audit_export(jid): with LOCK: cleanup() job=JOBS.get(jid) if not job or job["state"]!="completed": raise ValueError("Completed job not found or expired.") inputs,result,created=job["inputs"],job["result"],job["created_at"] root=Path(__file__).resolve().parent versions={} from importlib.metadata import version for name in ["numpy","pandas","statsmodels","arch","mcp","pypdf","fonttools"]: versions[name]=version(name) files={"normalized_inputs.json":json.dumps(inputs,indent=2,allow_nan=False).encode(), "results.json":json.dumps(result,indent=2,allow_nan=False).encode()} for name in ["archive_import.py","scenarios.py","bulk.py","benchmark.py","core.py","billing.py","requirements.txt"]: files["implementation/"+name]=(root/name).read_bytes() manifest={"protocol":"electrocheap-audit-v3","created_at":created,"kind":job["kind"],"versions":versions, "files":{k:hashlib.sha256(v).hexdigest() for k,v in files.items()}, "privacy":"No raw PDFs or original account/meter identifiers. Normalized personal usage results are private; never publish without explicit permission."} files["manifest.json"]=json.dumps(manifest,indent=2).encode() buffer=BytesIO() with ZipFile(buffer,"w",ZIP_DEFLATED) as archive: for name,body in files.items(): archive.writestr(name,body) return buffer.getvalue()66 unmodified lines67686970717256 unmodified lines12913013113213313425 unmodified lines16016116216316416566 unmodified linesr[k] = iso(r[k], k).isoformat()if r["valid_to"] < r["valid_from"]:raise ValueError("valid_to precedes valid_from.")url = urlparse(r["source_url"])if url.scheme != "https" or not url.netloc:raise ValueError("source_url must be an HTTPS evidence link.")56 unmodified linesraise ValueError("Customer type is ineligible; NGO sites require NGO/all quotes.")if r["meter_type"] not in {meter, "any"}:raise ValueError("Meter is ineligible.")if r["tariff_type"] == "tou" and meter != "smart":raise ValueError("Time-of-use estimation requires a smart-meter profile.")if not r["tax_included"]:25 unmodified lines"country": country, "region": region, "currency": MARKETS[country],"as_of": as_of.isoformat(), "annual_kwh": kwh, "current_annual_bill": current,"billing_summary": bill_summary,"ranked_offers": ranked, "excluded_offers": excluded,"recommended_action": "Review the lowest eligible quote" if ranked and ranked[0]["estimated_saving"] > 0 else "Keep current contract under this scenario","method": "365-day tax-inclusive estimate. Rates assumed constant; includes all supplied annual fees, guaranteed credit and switching cost. No automatic switching.",66 unmodified lines676869707172737456 unmodified lines13113213313413513613713813914025 unmodified lines16616716816917017117266 unmodified linesr[k] = iso(r[k], k).isoformat()if r["valid_to"] < r["valid_from"]:raise ValueError("valid_to precedes valid_from.")if r.get("contracted_power_kva") not in {None,""}:r["contracted_power_kva"] = number(r["contracted_power_kva"], "contracted_power_kva", .1, 1000)url = urlparse(r["source_url"])if url.scheme != "https" or not url.netloc:raise ValueError("source_url must be an HTTPS evidence link.")56 unmodified linesraise ValueError("Customer type is ineligible; NGO sites require NGO/all quotes.")if r["meter_type"] not in {meter, "any"}:raise ValueError("Meter is ineligible.")if payload.get("contracted_power_kva") not in {None,""}:power = number(payload["contracted_power_kva"], "contracted_power_kva", .1, 1000)if r.get("contracted_power_kva") in {None,""} or not math.isclose(power,r["contracted_power_kva"],abs_tol=.001):raise ValueError("Quote must explicitly match the contracted kVA power.")if r["tariff_type"] == "tou" and meter != "smart":raise ValueError("Time-of-use estimation requires a smart-meter profile.")if not r["tax_included"]:25 unmodified lines"country": country, "region": region, "currency": MARKETS[country],"as_of": as_of.isoformat(), "annual_kwh": kwh, "current_annual_bill": current,"billing_summary": bill_summary,"profile_source": str(payload.get("profile_source", "latest_12_complete_monthly_bills" if bill_summary else "annual_user_input"))[:200],"ranked_offers": ranked, "excluded_offers": excluded,"recommended_action": "Review the lowest eligible quote" if ranked and ranked[0]["estimated_saving"] > 0 else "Keep current contract under this scenario","method": "365-day tax-inclusive estimate. Rates assumed constant; includes all supplied annual fees, guaranteed credit and switching cost. No automatic switching.",
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""Public benchmark data only. Customer billing imports never enter this registry."""from io import BytesIOfrom pathlib import Pathfrom zipfile import ZipFile, ZIP_DEFLATEDimport csvimport hashlibimport json
ROOT=Path(__file__).resolve().parentREGISTRY={ "pt-grid-monthly":("data/pt_monthly.csv","REN Portugal national grid demand","GWh","data/pt_provenance.json"), "de-grid-monthly":("data/de_monthly.csv","SMARD Germany national grid demand","GWh","data/de_provenance.json"), "au-nem-monthly":("data/au_monthly.csv","AEMO Australia five-region NEM demand proxy","GWh","data/au_provenance.json"), "model-test-metrics":("evidence/full_model_benchmark/outputs/test_metrics.csv","Archived model test scores","mixed metrics",None), "model-test-predictions":("evidence/full_model_benchmark/outputs/test_predictions_with_truth.csv","Archived test predictions and observed truth","GWh",None), "grokked-extension-predictions":("evidence/sarima_rl_extension/outputs/test_forecasts.csv","DE/AU SARIMA-bias-RL extension predictions","GWh",None),}
def manifest(): output=[] for key,(relative,title,unit,provenance) in REGISTRY.items(): path=ROOT/relative if not path.is_file(): continue rows=list(csv.DictReader(path.open())) item={"dataset_id":key,"title":title,"unit":unit,"rows":len(rows),"bytes":path.stat().st_size, "sha256":hashlib.sha256(path.read_bytes()).hexdigest(),"download_path":f"/api/datasets/{key}/download"} if provenance and (ROOT/provenance).is_file(): item["provenance"]=json.loads((ROOT/provenance).read_text()) output.append(item) return {"status":"public_auditable_datasets","datasets":output, "privacy":"Official grid snapshots and already recorded benchmark evidence only. User bills, normalized customer usage and private jobs are excluded.", "archive_scope":"Historical snapshots through September 2026; not a live provider-tariff history. Hosted LLM lanes contain delegated diagnostics rather than independently authenticated API competitor measurements."}
def dataset_inspect(payload): selected=payload.get("dataset_id") catalog=manifest() if not selected: return catalog if selected not in REGISTRY or not (ROOT/REGISTRY[selected][0]).is_file(): raise ValueError("Unknown dataset_id; request the manifest first.") offset=payload.get("offset",0);limit=payload.get("limit",100) if isinstance(offset,bool) or isinstance(limit,bool) or not isinstance(offset,int) or not isinstance(limit,int) or offset<0 or not 1<=limit<=1000: raise ValueError("Use integer offset>=0 and limit 1–1000.") path=ROOT/REGISTRY[selected][0] rows=list(csv.DictReader(path.open())) metadata=next(x for x in catalog["datasets"] if x["dataset_id"]==selected) return {**metadata,"records":rows[offset:offset+limit],"next_offset":offset+limit if offset+limit<len(rows) else None}
def public_audit_archive(): catalog=manifest() files={} for item in catalog["datasets"]: relative,_,_,provenance=REGISTRY[item["dataset_id"]] files[relative]=(ROOT/relative).read_bytes() if provenance and (ROOT/provenance).is_file(): files[provenance]=(ROOT/provenance).read_bytes() for relative in ["benchmark.py","evidence/full_model_benchmark/protocol.json", "evidence/full_model_benchmark/scoring_policy.json","evidence/full_model_benchmark/foundation_config.json", "evidence/full_model_benchmark/vendor/forecast_lab_pro_v2/SNAPSHOT.json", "evidence/sarima_rl_extension/protocol.json","evidence/sarima_rl_extension/outputs/selection.json", "evidence/full_model_benchmark/outputs/selection.json", "evidence/full_model_benchmark/benchmark_core.py", "evidence/full_model_benchmark/score_benchmark.py", "evidence/full_model_benchmark/foundation_runner.py", "evidence/full_model_benchmark/foundation_manifest.json", "evidence/full_model_benchmark/outputs/calibration_parameters.csv", "evidence/full_model_benchmark/outputs/development_metrics.csv", "evidence/full_model_benchmark/outputs/classical_environment.json", "evidence/sarima_rl_extension/source_reference/grokked_sarima.py"]: path=ROOT/relative if path.is_file(): files[relative]=path.read_bytes() hashes={name:hashlib.sha256(body).hexdigest() for name,body in files.items()} files["manifest.json"]=json.dumps({**catalog,"files_sha256":hashes},indent=2).encode() buf=BytesIO() with ZipFile(buf,"w",ZIP_DEFLATED) as archive: for name,body in files.items(): archive.writestr(name,body) return buf.getvalue()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""Download only user-authorized ChatGPT file URLs, bounded and without credentials."""import ipaddressimport reimport socketimport loggingfrom pathlib import PurePosixPathfrom urllib.parse import urlparse
import httpxfrom pydantic import BaseModel, ConfigDictfrom archive_import import MAX_COMPRESSED
# Signed attachment URLs are bearer credentials and must not appear in HTTP logs.logging.getLogger("httpx").setLevel(logging.WARNING)
class OpenAIFile(BaseModel): model_config=ConfigDict(extra="forbid") download_url: str file_id: str mime_type: str = "" file_name: str = ""
def validate_download_url(url): parsed=urlparse(url) host=(parsed.hostname or "").lower() trusted=(host=="files.oaiusercontent.com" or host.endswith(".oaiusercontent.com") or bool(re.fullmatch(r"oaisd(?:mnt|sor)pr[^.]*\.blob\.core\.windows\.net",host)) or bool(re.fullmatch(r"oaisdmntpr[^.]*aws\.s3\.[a-z0-9-]+\.amazonaws\.com",host))) if not trusted or parsed.scheme!="https" or parsed.username or parsed.password or parsed.port not in {None,443} or len(url)>8192: raise ValueError("Use a signed ChatGPT attachment URL, or upload ZIPs directly in the Space. Arbitrary provider/private-network URLs are not downloaded.") try: addresses=socket.getaddrinfo(host,443,type=socket.SOCK_STREAM) except socket.gaierror: raise ValueError("Attachment host could not be resolved; refresh the attachment URL.") from None if not addresses or any(not ipaddress.ip_address(a[4][0]).is_global for a in addresses): raise ValueError("Attachment URL resolved to a non-public address.") return url
def download_files(files): if not 1<=len(files)<=10: raise ValueError("Attach 1–10 ZIP, PDF, CSV or JSON files.") output=[];total=0 with httpx.Client(timeout=httpx.Timeout(30,connect=10),follow_redirects=False) as client: for file in files: url=validate_download_url(file.download_url) # Deliberately reject redirects; callers must provide the final signed file URL. try: with client.stream("GET",url) as response: if response.is_redirect: raise ValueError("Attachment URL redirects; obtain a fresh direct download URL.") if response.status_code!=200: raise ValueError("Attachment download failed or expired; select/attach the file again.") chunks=[] for chunk in response.iter_bytes(): total+=len(chunk) if total>MAX_COMPRESSED: raise ValueError("Combined compressed attachment limit is 25 MiB.") chunks.append(chunk) content=b"".join(chunks) except httpx.HTTPError: raise ValueError("Attachment download failed; try a fresh URL or the Space upload.") from None name=PurePosixPath(file.file_name.replace("\\","/")).name or "attachment" if not PurePosixPath(name).suffix: if content.startswith(b"PK"): name+=".zip" elif content.startswith(b"%PDF"): name+=".pdf" elif file.mime_type=="application/json": name+=".json" elif file.mime_type=="text/csv": name+=".csv" output.append((name,content)) return output29 unmodified lines30313233343529 unmodified lines"hosted_llm": {"Astra": "gpt-6-astra", "Sol": "gpt-6.1-sol", "status": "Archived delegated test diagnostics; no live customer API configured."},"unavailable_exact_implementations": ["Original KMLAIOps TSF SARIMAX-GARCHX", "Super Grokked (distinct source not supplied)"],"live_cpu_candidates": ["Seasonal naive", "Seasonal drift", "SARIMA", "SARIMA + frozen bias", "Grokked SARIMA · 80/20 blend", "SARIMAX · calendar", "SARIMAX + GARCH · calendar mean, residual volatility"],"limits": "Grid scores do not select a household forecaster or demonstrate bill savings. Transformer/LLM scores are cached evidence, not live inference. No significance claim or paid calls."}def model_table(country):29 unmodified lines303132333435363729 unmodified lines"hosted_llm": {"Astra": "gpt-6-astra", "Sol": "gpt-6.1-sol", "status": "Archived delegated test diagnostics; no live customer API configured."},"unavailable_exact_implementations": ["Original KMLAIOps TSF SARIMAX-GARCHX", "Super Grokked (distinct source not supplied)"],"live_cpu_candidates": ["Seasonal naive", "Seasonal drift", "SARIMA", "SARIMA + frozen bias", "Grokked SARIMA · 80/20 blend", "SARIMAX · calendar", "SARIMAX + GARCH · calendar mean, residual volatility"],"bulk_live_inference": {"submit_tool":"analysis_submit","result_tool":"analysis_result","models":["seasonal_naive","sarima","grokked_sarima","sarimax_garch"],"horizon_months":"1–36","series_per_job":10,"statistical_minimum_months":36,"scope":"User-supplied complete monthly series; no grid-to-household winner transfer."},"public_dataset_tool": "dataset_inspect","limits": "Grid scores do not select a household forecaster or demonstrate bill savings. Transformer/LLM scores are cached evidence, not live inference. No significance claim or paid calls."}def model_table(country):
123456789101112{"name": "electrocheap-xenowattz","version": "0.2.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "electrocheap-xenowattz","version": "0.2.0","dependencies": {"lucide-react": "1.55.0","papaparse": "5.5.3",123456789101112{"name": "electrocheap-xenowattz","version": "0.3.0","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "electrocheap-xenowattz","version": "0.3.0","dependencies": {"lucide-react": "1.55.0","papaparse": "5.5.3",
1{"name":"electrocheap-xenowattz","version":"0.2.0","private":true,"type":"module","scripts":{"dev":"vite --host 0.0.0.0","build":"vite build","preview":"vite preview --host 0.0.0.0"},"dependencies":{"react":"19.3.0","react-dom":"19.3.0","lucide-react":"1.55.0","papaparse":"5.5.3"},"devDependencies":{"vite":"8.3.4"}}1{"name":"electrocheap-xenowattz","version":"0.3.0","private":true,"type":"module","scripts":{"dev":"vite --host 0.0.0.0","build":"vite build","preview":"vite preview --host 0.0.0.0"},"dependencies":{"react":"19.3.0","react-dom":"19.3.0","lucide-react":"1.55.0","papaparse":"5.5.3"},"devDependencies":{"vite":"8.3.4"}}
6 unmodified lines7896 unmodified linesstatsmodels==0.15.0arch==8.0.0httpx[socks]==0.28.16 unmodified lines7891011126 unmodified linesstatsmodels==0.15.0arch==8.0.0httpx[socks]==0.28.1pypdf==6.20.1python-multipart==0.0.32fonttools==4.66.1
123version https://git-lfs.github.com/spec/v1oid sha256:b3ccfd8b3a22520a88e35a41c826245be5e30b189bf77953dd5a2607e30db72csize 2934405123version https://git-lfs.github.com/spec/v1oid sha256:c86c1f011c2b3acab9b9c7966c5244a81888209a07897501e87b3ba189f37845size 2963767
123451 unmodified line78910111213141512 unmodified lines28293031323349 unmodified lines8384858687888990919293949596979899100101102103104105106107108109110111112113114115{"archive_sha256": "b3ccfd8b3a22520a88e35a41c826245be5e30b189bf77953dd5a2607e30db72c","files": {"assets/xenowattz-poster.png": "ffe946861e3c9671750b55c1e101a017137974fe933d4ddb53e16c38b826c502","assets/xenowattz_480.mp4": "dfb29c1b1ceaaa5804b273a7e38aaa4d52398581cbac703c9089dd5065d80717",1 unmodified line"data/de_monthly.csv": "71618b6d81c9f68a3b9d9ff17af7a7e0ddd8b196f64bff87e91b307dd86470cc","data/example_billing_months.csv": "614bdd67d0d601613c17779a75f148a20ef3285a73290ea7a09866cdf943a655","data/example_quotes.csv": "958e0a27edd5139a41c60e19730f343239c3f3d33f4e97052b2d2e2210461985","data/pt_monthly.csv": "443edee4bfeea82fdbbddfdeb81f4a06bb7d06eb55ea24b7eb7d9ae03066bfe7","data/pt_provenance.json": "f0a6f91044ffef2e45357e3d45fa5674cb73424855343745d6ba6926401896e9","data/quote_template.csv": "333f14536146cfef42a9f0d6c20d00736ee97deb2f459f4e54ddff0461e09b93","evidence/full_model_benchmark/README.md": "98fd1b14dc4c587c053deeafe76ddee8cfa15edd35143012fb12803ab03cf3e9","evidence/full_model_benchmark/benchmark_core.py": "b39823bb360dbcf722689b32b0b5f88e0895863aa4ec46768b7f6705cc0717ff","evidence/full_model_benchmark/data/monthly_demand_all.csv": "4cf369e519f0bad05095dfa603f5e5c928cc6217ba433babcd03988cf7ee3d76",12 unmodified lines"evidence/full_model_benchmark/outputs/selection_eligibility.csv": "423e6130ede84e732c8d4d54c72ca7eb67ca735b03ac5dba5b439db93cd25e64","evidence/full_model_benchmark/outputs/significance.json": "b595630e876bc96089dde534ae572832a3c07fed8c11fc56272ac25dd1e10e2c","evidence/full_model_benchmark/outputs/test_metrics.csv": "84daa6562825d34076db684df89829f7b8101bd31e6aa6521008f11e30843107","evidence/full_model_benchmark/prepare_foundations.py": "f99a9532d4ed234c3246bc653fd65c970f1595377e7810f1db82e41460a66589","evidence/full_model_benchmark/protocol.json": "bfd0a42e66c3b5c4b809636450d29bb67bc1c44ead9d6698db16207aa3806905","evidence/full_model_benchmark/results/foundation/foundation_run_au.json": "83db8a6775aa77bff5a03579228d86c47f73c6ad503970303de9f69f987a6feb",49 unmodified lines"evidence/sarima_rl_extension/source_reference/grokked_sarima.py": "d17609440534e11afdc25d408d0b526cf4e634d3b6be2524cbe2ff977b1269b0","evidence/sarima_rl_extension/source_reference/sarima.py": "3b5f395f4c93932f45aa693a68f1e4a503e3b34e89a2a2daff90a8ad348a3ace","evidence/sarima_rl_extension/test_leakage_controls.py": "58df8e16d69d6f7df4eb208f254809ce5dda1fde949dccb6c1b593485b5e5e22","scripts/acquire_price_snapshots.py": "47197872de69a61dcaf7d24d7a1492e18957eead556f7b958688fa1303bb68df","scripts/acquire_snapshots.py": "238274834b3ab3efc1ad4e6a44805221edbb7566d2f229cc82a9f7ab4b0eb8fd","scripts/deploy.py": "ac91f0aa9376d2106733d55d762002318aefc63661f692e14b2643a038a5cde4","scripts/smoke_app.py": "b7922cee083ed285887e00c89682371daecbcff187b95fbcc7aff74ca7e81910","scripts/smoke_remote.py": "963bbea0726f921c26f37243ffe81218cd3e16ebb24239cda38677165d753eb6","tests/test_benchmark.py": "54743f9e2b1df351fa98a9a393a51f0a53e77ee90e6e6c0e1e0260c53c281a03","tests/test_billing.py": "7386e0a911028309da2b1e039d71d13980c6b3b68ce52e7e0f2fdb38d030d856","tests/test_core.py": "7698fbd68137165c70233c3f31e60388e041911fccc56c0c00d1f2d1c576c529","tests/test_sources.py": "cc62716a2a7e8cb0677e9c1ac2be736038587c6527bb3f87a2c5eb79db39bafa","validation/aer_plan_detail.json": "907dad24b0dd70cb9ef6ff813006ba28b44df2ca69fa020884061d0a5bc9b038","validation/aer_plan_meta.json": "5c8c67ef9f2a397a85d746c35eea9598b581e78890e1cd2904443b3b9fcf5fc7","validation/au_benchmark.json": "4dd009fd491cf7357f779d37bc845f6b7b1d412bfd60514f23327018ca53505d","validation/au_benchmark_v2.json": "5ecbb92e9c3a62d5675bcc510676b7852751a5f70b37574ca9dac96ad8c2cec6","validation/au_live_meta.json": "a339d41a5202523504ebb18f1728c68f453cfbafef660b5173f29c13cbd6f54f","validation/au_live_sample.csv": "a5730ab2ef4ca240c97e86e6e39b120c311072a28eaa47aac69bf25aab5b378b","validation/build_status.json": "7c7ec28546e37a3e5643187ec512e519cb70a57ff7dc9926c4ddf1002d2778a2","validation/de_benchmark.json": "dedd0f3095ee3a74738db1bbbcaa13f7b890e7a83483a7945aa5fa09b3b0a1ea","validation/de_benchmark_v2.json": "2b682afba1ba4e09d54955bff1350c4d96fd037e42ebb4c4ec04bf5a4392e69a","validation/de_live_meta.json": "56ac2d03ddec31cde98cd6b076c03b68a3df92767a3b84ef7bfc2356ae03fbe0","validation/de_live_sample.csv": "e2abf70e63375a32497ad7501e4b8e248fcf25d32f8e9504e2d5791832cffa60","validation/hosted_sources.json": "70b27647276114f470e5edb2aed266983a6d940217fa7e1366209acbdd0ade6d","validation/http_smoke.json": "279c7e8925f9925d9cb98a571940383e6280534709c28f01050d82f5bcbb45cf","validation/pt_benchmark.json": "a950c08a3e7c25ead474fff5a3bb1f25df3be13fa0432636cd09622f47ed16ac","validation/pt_benchmark_v2.json": "29e710307561a8089af070a4332ba25eafba14ac64209493bd41daaf5d301583","validation/pt_hosted_benchmark_v2.json": "0464dcb5c591448bd4c55647e6d75977a38486db00767b9ccaac62df52262e57","validation/pt_live_meta.json": "711d4fc31f64a1feb7a244911c833b6f31fb43059e9dbc075c18f626a39f9858","validation/pt_live_sample.csv": "be66c3b722833f3027d0ec1045c5d6d394f01071430bb07650092b546a2968c4","validation/remote_smoke.json": "6c5f70db6a30f2115e78108bf4460096a7ab22a8503e8df67920c50fe9aa2a90"}}123451 unmodified line7891011121314151612 unmodified lines2930313233343549 unmodified lines858687888990919293949596979899100101102103104105106107108109110111112113114115116117118{"archive_sha256": "c86c1f011c2b3acab9b9c7966c5244a81888209a07897501e87b3ba189f37845","files": {"assets/xenowattz-poster.png": "ffe946861e3c9671750b55c1e101a017137974fe933d4ddb53e16c38b826c502","assets/xenowattz_480.mp4": "dfb29c1b1ceaaa5804b273a7e38aaa4d52398581cbac703c9089dd5065d80717",1 unmodified line"data/de_monthly.csv": "71618b6d81c9f68a3b9d9ff17af7a7e0ddd8b196f64bff87e91b307dd86470cc","data/example_billing_months.csv": "614bdd67d0d601613c17779a75f148a20ef3285a73290ea7a09866cdf943a655","data/example_quotes.csv": "958e0a27edd5139a41c60e19730f343239c3f3d33f4e97052b2d2e2210461985","data/provider_history_template.csv": "d5135fb2090f196f98e824f8862169dbdda2b602d4209d81de64b19ddeb4e172","data/pt_monthly.csv": "443edee4bfeea82fdbbddfdeb81f4a06bb7d06eb55ea24b7eb7d9ae03066bfe7","data/pt_provenance.json": "f0a6f91044ffef2e45357e3d45fa5674cb73424855343745d6ba6926401896e9","data/quote_template.csv": "8e58a4279003f00904c07b010832fa959646f221a355ea3acbb5ee1467faf0e8","evidence/full_model_benchmark/README.md": "98fd1b14dc4c587c053deeafe76ddee8cfa15edd35143012fb12803ab03cf3e9","evidence/full_model_benchmark/benchmark_core.py": "b39823bb360dbcf722689b32b0b5f88e0895863aa4ec46768b7f6705cc0717ff","evidence/full_model_benchmark/data/monthly_demand_all.csv": "4cf369e519f0bad05095dfa603f5e5c928cc6217ba433babcd03988cf7ee3d76",12 unmodified lines"evidence/full_model_benchmark/outputs/selection_eligibility.csv": "423e6130ede84e732c8d4d54c72ca7eb67ca735b03ac5dba5b439db93cd25e64","evidence/full_model_benchmark/outputs/significance.json": "b595630e876bc96089dde534ae572832a3c07fed8c11fc56272ac25dd1e10e2c","evidence/full_model_benchmark/outputs/test_metrics.csv": "84daa6562825d34076db684df89829f7b8101bd31e6aa6521008f11e30843107","evidence/full_model_benchmark/outputs/test_predictions_with_truth.csv": "ef764d382d75a61bf753c5b4f8de63cd6401d8c2090331ceceb798d4205f109e","evidence/full_model_benchmark/prepare_foundations.py": "f99a9532d4ed234c3246bc653fd65c970f1595377e7810f1db82e41460a66589","evidence/full_model_benchmark/protocol.json": "bfd0a42e66c3b5c4b809636450d29bb67bc1c44ead9d6698db16207aa3806905","evidence/full_model_benchmark/results/foundation/foundation_run_au.json": "83db8a6775aa77bff5a03579228d86c47f73c6ad503970303de9f69f987a6feb",49 unmodified lines"evidence/sarima_rl_extension/source_reference/grokked_sarima.py": "d17609440534e11afdc25d408d0b526cf4e634d3b6be2524cbe2ff977b1269b0","evidence/sarima_rl_extension/source_reference/sarima.py": "3b5f395f4c93932f45aa693a68f1e4a503e3b34e89a2a2daff90a8ad348a3ace","evidence/sarima_rl_extension/test_leakage_controls.py": "58df8e16d69d6f7df4eb208f254809ce5dda1fde949dccb6c1b593485b5e5e22","tests/test_archive_import.py": "d642e02ca42e0d26657827827aef8b062dc9b8d82ad4562f4d9dd7f1c7583966","tests/test_benchmark.py": "54743f9e2b1df351fa98a9a393a51f0a53e77ee90e6e6c0e1e0260c53c281a03","tests/test_billing.py": "7386e0a911028309da2b1e039d71d13980c6b3b68ce52e7e0f2fdb38d030d856","tests/test_bulk.py": "44a3fd530fec0f05f33e5c8a813c8a4303bd60b756f37c8099f2bd126a37d184","tests/test_core.py": "b6aaae17f5d3a0cf8c24d05c327f0a9f760814963a4611c4eafd8b6a42ef778b","tests/test_scenarios.py": "746aaf769257a030a85a43abe9f3680d442ca68901f4035db1b459314adf1b44","tests/test_sources.py": "cc62716a2a7e8cb0677e9c1ac2be736038587c6527bb3f87a2c5eb79db39bafa","scripts/acquire_price_snapshots.py": "47197872de69a61dcaf7d24d7a1492e18957eead556f7b958688fa1303bb68df","scripts/acquire_snapshots.py": "238274834b3ab3efc1ad4e6a44805221edbb7566d2f229cc82a9f7ab4b0eb8fd","scripts/deploy.py": "ac91f0aa9376d2106733d55d762002318aefc63661f692e14b2643a038a5cde4","scripts/package_resources.py": "c51e8edd88e5cd9f8134bfd0bba36e9767a6e67665f15ba7a5319f929c498203","scripts/smoke_app.py": "5abf3dd730ecfabe5f0f27a9314cccaeddaefbc939fa7868bfa3a552f9db00cd","scripts/smoke_remote.py": "9b88019f707e363f91aeacfeb70e2cfd5b7088ad65e5ab1a855ab17d903da53c","validation/aer_plan_detail.json": "907dad24b0dd70cb9ef6ff813006ba28b44df2ca69fa020884061d0a5bc9b038","validation/aer_plan_meta.json": "5c8c67ef9f2a397a85d746c35eea9598b581e78890e1cd2904443b3b9fcf5fc7","validation/au_benchmark.json": "4dd009fd491cf7357f779d37bc845f6b7b1d412bfd60514f23327018ca53505d","validation/au_benchmark_v2.json": "5ecbb92e9c3a62d5675bcc510676b7852751a5f70b37574ca9dac96ad8c2cec6","validation/au_live_meta.json": "a339d41a5202523504ebb18f1728c68f453cfbafef660b5173f29c13cbd6f54f","validation/build_status.json": "7c7ec28546e37a3e5643187ec512e519cb70a57ff7dc9926c4ddf1002d2778a2","validation/de_benchmark.json": "dedd0f3095ee3a74738db1bbbcaa13f7b890e7a83483a7945aa5fa09b3b0a1ea","validation/de_benchmark_v2.json": "2b682afba1ba4e09d54955bff1350c4d96fd037e42ebb4c4ec04bf5a4392e69a","validation/de_live_meta.json": "56ac2d03ddec31cde98cd6b076c03b68a3df92767a3b84ef7bfc2356ae03fbe0","validation/hosted_sources.json": "70b27647276114f470e5edb2aed266983a6d940217fa7e1366209acbdd0ade6d","validation/http_smoke.json": "900c52fc28a9d49c9161354870878106b477030440e08c0554e8f94f33a8b8f8","validation/pt_benchmark.json": "a950c08a3e7c25ead474fff5a3bb1f25df3be13fa0432636cd09622f47ed16ac","validation/pt_benchmark_v2.json": "29e710307561a8089af070a4332ba25eafba14ac64209493bd41daaf5d301583","validation/pt_hosted_benchmark_v2.json": "0464dcb5c591448bd4c55647e6d75977a38486db00767b9ccaac62df52262e57","validation/pt_live_meta.json": "711d4fc31f64a1feb7a244911c833b6f31fb43059e9dbc075c18f626a39f9858","validation/remote_smoke.json": "6c5f70db6a30f2115e78108bf4460096a7ab22a8503e8df67920c50fe9aa2a90"}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236"""Transparent provider history and constrained monthly switching scenarios."""from datetime import dateimport calendarimport hashlibimport jsonimport math
from core import MARKETS, consumer_compare, number, boolean, iso, validate_offer
def hash_json(value): return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
def month_add(month, offset): d = date.fromisoformat(str(month)[:7] + "-01") n = d.year * 12 + d.month - 1 + offset return f"{n//12:04d}-{n%12+1:02d}"
def integer(value, name, low, high): n = number(value, name, low, high) if n != int(n): raise ValueError(f"{name} must be an integer.") return int(n)
def provider_history(payload): records = payload.get("records", []) if not isinstance(records, list) or not 1 <= len(records) <= 5000: raise ValueError("Supply 1–5000 dated price observations.") grouped = {} for r in records: if not isinstance(r, dict): raise ValueError("Price observations must be objects.") provider, tariff = str(r.get("provider", "")).strip(), str(r.get("tariff_id", r.get("profile_id", ""))).strip() if not provider or not tariff or len(provider) > 150 or len(tariff) > 150: raise ValueError("Each history row needs provider and tariff_id to separate contract terms.") country = r.get("country") if country not in MARKETS or r.get("currency") != MARKETS[country]: raise ValueError("Price histories must use PT/EUR, DE/EUR or AU/AUD.") checked = iso(r.get("observed_at", r.get("month", "") + "-01"), "observed_at") if checked > date.today(): raise ValueError("Future prices belong in assumptions, not observed history.") effective = iso(r.get("period_start", checked.isoformat()), "period_start") included = boolean(r.get("tax_included", False), "tax_included") rate = number(r.get("rate_per_kwh"), "rate_per_kwh", 0, 10) evidence = str(r.get("source_sha256", r.get("source_url", ""))) if not evidence: raise ValueError("Every price observation needs a source_sha256 or source_url.") key = (country, provider, tariff, included) grouped.setdefault(key, []).append({"observed_at": checked.isoformat(), "effective_from": effective.isoformat(), "rate_per_kwh": rate, "source": evidence, "date_basis": r.get("date_basis", "supplied observation")}) output = [] for (country, provider, tariff, included), values in sorted(grouped.items()): values.sort(key=lambda r: (r["effective_from"], r["observed_at"], r["rate_per_kwh"])) first, last = values[0]["rate_per_kwh"], values[-1]["rate_per_kwh"] uncertain = any("uncertain" in str(r["date_basis"]) for r in values) output.append({"country": country, "currency": MARKETS[country], "provider": provider, "tariff_id": tariff, "tax_included": included, "unit": MARKETS[country] + "/kWh", "observations": values, "first_observed_rate": first, "last_observed_rate": last, "change_pct": round((last / first - 1) * 100, 3) if first and not uncertain else None, "change_dates_uncertain": uncertain, "forecast_eligible": len({r["effective_from"][:7] for r in values}) >= 36}) return {"status": "observed_provider_price_history", "groups": output, "input_sha256": hash_json(records), "limits": "Tariff/meter groups and VAT bases remain separate. Repeated invoices are not independent monthly price observations. Historical direction does not guarantee future prices; Grokked needs a normalized, consecutive monthly series."}
def _plan(profile, offers, horizon, assumptions, start, as_of, options, current): months = [month_add(start, i) for i in range(horizon)] annual_kwh = number(profile.get("annual_kwh"), "annual_kwh", 1, 1e7) annual_bill = number(profile.get("current_annual_bill"), "current_annual_bill", 0, 1e8) supplied_usage = profile.get("usage_by_month", {}) if not isinstance(supplied_usage, dict): raise ValueError("usage_by_month must map YYYY-MM to kWh.") usage = [number(supplied_usage.get(m, annual_kwh / 12), "monthly_kwh", 0, 1e7) for m in months] peak = number(profile.get("peak_share", .5), "peak_share", 0, 1) max_switches = integer(options.get("max_switches", 3), "max_switches", 0, 3) futures = boolean(options.get("assume_future_enrolment", False), "assume_future_enrolment") eligible = consumer_compare({**options, **profile, "as_of": as_of, "offers": offers}) ids = {r["offer_id"] for r in eligible["ranked_offers"]} candidates = [{**validate_offer(r), **{k: r[k] for k in ["minimum_term_months", "exit_fee", "credit_vesting_months", "rate_curve", "entry_months"] if k in r}} for r in offers if str(r.get("offer_id")) in ids] if len(candidates) > 12: raise ValueError("Switching plans accept at most 12 eligible offers per profile.") current_provider = str(profile.get("provider", "current provider")) if current: baseline = validate_offer(current) if baseline["country"] != profile["country"] or baseline["region"] not in {profile["region"], "ALL"} or not baseline["tax_included"]: raise ValueError("Current offer country, region and VAT basis must match the profile.") baseline.update({k: current[k] for k in ["minimum_term_months", "exit_fee", "credit_vesting_months", "rate_curve"] if k in current}) baseline["guaranteed_credit"] = 0 current_provider = baseline["provider"] else: baseline = {"offer_id": "__current__", "provider": current_provider, "rate_per_kwh": 0, "offpeak_rate_per_kwh": 0, "daily_charge": 0, "annual_fees": annual_bill, "switching_cost": 0, "guaranteed_credit": 0, "price_guaranteed_months": 0, "minimum_term_months": 0, "exit_fee": options.get("current_exit_fee", 0), "tariff_type": "flat", "currency": MARKETS[profile["country"]], "evidence": "historical_bill_baseline"} all_offers = [baseline] + candidates providers = sorted({r["provider"] for r in all_offers}) bits = {p: 1 << i for i, p in enumerate(providers)} terms = [] for r in all_offers: minimum = integer(r.get("minimum_term_months", 0), "minimum_term_months", 0, 36) vesting = integer(r.get("credit_vesting_months", 12 if r["guaranteed_credit"] else 0), "credit_vesting_months", 0, 36) exit_fee = number(r.get("exit_fee", 0), "exit_fee", 0, 1e6) growth = number(assumptions.get(r["provider"], 0), "annual_price_change_pct", -90, 300) / 100 curve = r.get("rate_curve") if curve is not None and (r["tariff_type"] != "flat" or not isinstance(curve, dict)): raise ValueError("rate_curve is a YYYY-MM map for flat tax-inclusive tariffs only.") if curve: curve = {m: number(v, "curve_rate", 0, 10) for m, v in curve.items()} if set(months) - set(curve): raise ValueError("Each supplied rate_curve must cover every scenario month.") rate = r["rate_per_kwh"] if r["tariff_type"] == "flat" else peak*r["rate_per_kwh"]+(1-peak)*r["offpeak_rate_per_kwh"] rates = [curve[m] if curve else rate * (1 + growth)**(i/12) for i,m in enumerate(months)] terms.append((minimum, vesting, exit_fee, rates)) current_age = integer(options.get("current_contract_months", 36), "current_contract_months", 0, 600) # State: current offer, months held, switches, providers already credited. states = {(0, current_age, 0, bits[current_provider]): (0.0, [])} for t, month in enumerate(months): next_states = {} days = calendar.monthrange(int(month[:4]), int(month[5:]))[1] for (old, age, swaps, used), (cost, path) in states.items(): for new, r in enumerate(all_offers): changed = new != old if changed: if swaps >= max_switches or age < terms[old][0]: continue if new==0: # A cancelled historical contract is not an available future quote. continue if new and t > 0: permitted = r.get("entry_months", []) if not futures and month not in permitted: continue if not futures and not r["valid_from"] <= month + "-01" <= r["valid_to"]: continue # Do not finish with unpriced minimum-term obligations. if horizon-t < terms[new][0]: continue new_age = 0 if changed else age minimum, vesting, exit_fee, rates = terms[new] start_t = max(0, t-new_age) locked = new_age < int(r["price_guaranteed_months"]) rate = rates[start_t] if locked else rates[t] recurring = usage[t]*rate + days*r["daily_charge"] + r["annual_fees"]/12 fee, credit, clawback = 0.0, 0.0, 0.0 if changed: fee = r["switching_cost"] + terms[old][2] if path and path[-1]["credit_claimed_on_entry"] and age < terms[old][1]: clawback = all_offers[old]["guaranteed_credit"] elif age < terms[old][1] and any(x["offer_id"] == all_offers[old]["offer_id"] and x["signup_credit"] for x in path): clawback = all_offers[old]["guaranteed_credit"] if not used & bits[r["provider"]]: credit = r["guaranteed_credit"] claimed = credit > 0 if changed else (path[-1]["credit_claimed_on_entry"] if path else False) provision = r["guaranteed_credit"] if t==horizon-1 and claimed and new_age+1 < vesting else 0.0 increment = recurring + fee + clawback + provision - credit new_state = (new, new_age+1, swaps+int(changed), used | bits[r["provider"]]) row = {"month": month, "provider": r["provider"], "offer_id": r["offer_id"], "kwh": round(usage[t], 6), "rate_per_kwh": round(rate, 6), "recurring_cost": round(recurring, 4), "switch_fees": round(fee, 4), "signup_credit": round(credit, 4), "credit_clawback": round(clawback, 4), "terminal_credit_provision": round(provision, 4), "cost": round(increment, 4), "switch": changed, "credit_claimed_on_entry": claimed, "within_price_guarantee": locked} candidate = (cost+increment, path+[row]) if new_state not in next_states or candidate[0] < next_states[new_state][0]: next_states[new_state] = candidate if len(next_states) > 100_000: raise ValueError("Scenario state limit exceeded; reduce offers or max_switches.") states = next_states best_state, (best, schedule) = min(states.items(), key=lambda pair: (pair[1][0],pair[0])) staying = 0.0 for i, month in enumerate(months): r = all_offers[0] baseline_rate=terms[0][3][0] if current_age+i < r["price_guaranteed_months"] else terms[0][3][i] staying += usage[i]*baseline_rate + calendar.monthrange(int(month[:4]),int(month[5:]))[1]*r["daily_charge"] + r["annual_fees"]/12 return {"horizon_months": horizon, "currency": MARKETS[profile["country"]], "planned_cost": round(best, 2), "stay_cost": round(staying, 2), "saving_vs_stay_scenario": round(staying-best, 2), "switch_count": best_state[2], "schedule": schedule, "excluded_offers": eligible["excluded_offers"], "baseline_basis": "supplied current offer" if current else "historical annual bill held constant; not a current verified tariff", "future_enrolment": "assumed availability" if futures else "initial quotes now; later entries require supplied dated entry_months", "optimization": "Exact minimum within supplied monthly assumptions and constraints; no guaranteed future best provider."}
def switching_scenarios(payload): profiles = payload.get("profiles") or [payload.get("profile", {})] offers = payload.get("offers", []) if not isinstance(profiles, list) or not 1 <= len(profiles) <= 20: raise ValueError("Supply 1–20 profiles per switching batch.") if not isinstance(offers, list) or len(offers) > 50: raise ValueError("Supply at most 50 total quotes; at most 12 eligible per profile.") horizons = payload.get("horizons", [3,12,36]) if not isinstance(horizons, list) or not 1 <= len(horizons) <= 3: raise ValueError("Supply 1–3 horizons.") horizons = sorted({integer(v, "horizon", 1, 36) for v in horizons}) scenarios = payload.get("price_scenarios", [{"name":"constant-price", "annual_price_change_pct":{}}]) if not isinstance(scenarios, list) or not 1 <= len(scenarios) <= 5: raise ValueError("Supply 1–5 explicitly named price scenarios.") as_of = iso(payload.get("as_of", date.today().isoformat()), "as_of").isoformat() start = month_add(payload.get("start_month", month_add(as_of[:7],1)),0) if start < as_of[:7]: raise ValueError("Start month cannot precede as_of.") output, currencies = [], {} for index, profile in enumerate(profiles): if not isinstance(profile, dict) or profile.get("country") not in MARKETS: raise ValueError("Each profile must declare PT, DE or AU.") if profile.get("needs_review") and not boolean(payload.get("accept_profile_estimates", False), "accept_profile_estimates"): raise ValueError("Imported allocated/annualized bills need review and explicit accept_profile_estimates=true.") pid = str(profile.get("profile_id", f"profile-{index+1}")) if len(pid)>100 or not pid: raise ValueError("Use anonymous profile IDs of at most 100 characters.") plans = [] for scenario in scenarios: if not isinstance(scenario,dict) or not isinstance(scenario.get("annual_price_change_pct",{}),dict): raise ValueError("Each price scenario needs a name and provider-to-annual-change map.") label = str(scenario.get("name", "scenario"))[:100] for horizon in horizons: plan = _plan(profile, offers, horizon, scenario.get("annual_price_change_pct",{}), start, as_of, payload, payload.get("current_offer")) plans.append({"scenario": label, **plan}) key = f"{label}:{horizon}:{plan['currency']}" currencies[key] = round(currencies.get(key,0)+plan["saving_vs_stay_scenario"],2) output.append({"profile_id":pid,"plans":plans}) return {"status":"constrained_switching_scenarios", "profiles":output, "savings_totals_by_scenario_horizon_currency":currencies,"start_month":start,"as_of":as_of, "input_sha256":hash_json(payload), "assumptions":["Usage defaults to annual_kwh/12; override usage_by_month with a supplied forecast.", "Daily charges follow calendar days; annual fees are allocated monthly. Missing minimum terms and exit fees are zero assumptions.", "Signup credits are granted once per provider, with full early-exit clawback until credit_vesting_months (default 12). Unvested terminal credits are provisioned.", "Minimum-term commitments cannot extend beyond the planning horizon. Current contract age defaults to 36 months.", "Price guarantees freeze the entry rate. Outside guarantees, supplied curves or declared growth assumptions apply.", "Monthly switching has no activation delay; bundled products, deposits, early credit-note adjustments and indexed contracts need a complete supplied quote."], "limits":"Forecast prices and future availability are scenarios. No supplier switching, contract execution, paid inference, exchange conversion or claim of proven future savings."}123@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Manrope:wght@400;500;600;700;800&display=swap');:root{font-family:'DM Sans',system-ui,sans-serif;color:#1b2e37;background:#f5f7f7;font-synthesis:none;font-weight:400}*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit}button,a,input,select{transition:background .16s,color .16s,border-color .16s}button{cursor:pointer}button:disabled{opacity:.5;cursor:wait}a{color:inherit;text-decoration:none}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid #71d8bb;outline-offset:3px}button{border:none}h1,h2,h3,p{margin-top:0}h1,h2,h3,strong{font-family:'Manrope',system-ui,sans-serif}h1{font-size:34px;line-height:1.24;letter-spacing:-1.3px;margin:9px 0 10px;font-weight:800}h2{font-size:18px;letter-spacing:-.5px;margin-bottom:6px}h3{font-size:20px}p{line-height:1.65}.app-shell{display:flex;min-height:100vh}.sidebar{width:242px;background:#13212e;color:#bec8cd;position:fixed;inset:0 auto 0 0;display:flex;flex-direction:column;padding:31px 20px 22px;z-index:10}.brand{display:flex;gap:11px;align-items:center;color:white;padding:0 8px}.brand-symbol{background:#baf279;color:#16232c;width:40px;height:40px;border-radius:12px;display:grid;place-items:center}.brand strong{font-size:20px;letter-spacing:-.5px}.brand small{display:block;font-size:8px;letter-spacing:2px;color:#85959e;margin-top:5px}.side-divider{height:1px;background:#2b3844;margin:30px 8px}.side-label{font-size:9px;letter-spacing:1.7px;color:#74858f;margin:0 10px 15px}nav{display:grid;gap:6px}.nav-item{display:flex;align-items:center;gap:11px;width:100%;background:none;color:#a6b4bd;padding:13px 14px;border-radius:9px;font-size:12px;font-weight:500;text-align:left}.nav-item:hover{background:#223341}.nav-item.active{color:#c9f699;background:#2a4039}.nav-arrow{margin-left:auto}.side-character{margin-top:auto;padding:30px 9px 20px}.side-character video{display:block;width:100%;border-radius:15px;aspect-ratio:1;object-fit:cover;opacity:.85}.side-character>div{font-size:10px;color:#a1b1ba;padding-top:11px;display:flex;align-items:center;gap:6px}.tiny-dot,.status-dot{display:inline-block;border-radius:50%;width:6px;height:6px;background:#6fc9a5}.side-foot{margin:4px 8px 0;border-top:1px solid #2b3844;padding-top:19px;font-size:10px;color:#acbdc5;line-height:1.8}.side-foot .status-dot{margin-right:8px}.side-foot small{display:block;font-size:9px;color:#657985;padding-left:14px}main{margin-left:242px;min-width:0;width:calc(100% - 242px)}.topbar{height:73px;background:#fff;border-bottom:1px solid #e5ebeb;display:flex;align-items:center;justify-content:space-between;padding:0 40px}.crumb{display:flex;align-items:center;gap:10px;font-size:11px;color:#8b969a}.crumb b{color:#344a53;font-weight:500}.top-links{display:flex;align-items:center;gap:22px}.top-links a{display:flex;align-items:center;gap:7px;font-size:11px;color:#5c7079}.research-badge{font-size:8px;letter-spacing:1.2px;border:1px solid #d9e7df;border-radius:5px;padding:7px 9px;color:#577869;background:#f5faf7}.page{max-width:1470px;margin:0 auto;padding:39px 40px 0}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:25px;margin-bottom:27px}.page-heading p{font-size:12px;color:#7b8c94;margin:0}.eyebrow{font-size:9px;letter-spacing:1.6px;font-weight:700;color:#70958a}.market-switch{display:flex;align-self:center;padding:4px;background:#e9efec;border-radius:9px;gap:3px;flex-shrink:0}.market-switch button{padding:9px 12px;font-size:11px;font-weight:700;color:#88968f;background:none;border-radius:6px;white-space:nowrap}.market-switch button.selected{background:#fff;color:#234d3d;box-shadow:0 2px 6px #18332b0a}.stats-row{display:grid;grid-template-columns:repeat(3,1fr);background:#fff;border:1px solid #e5ebea;border-radius:13px;margin-bottom:26px;box-shadow:0 3px 10px #1d473307}.stats-row>div{padding:23px 27px;position:relative}.stats-row>div+div:before{content:'';height:55%;top:23%;width:1px;background:#edf0ef;position:absolute;left:0}.stats-row span{font-size:8px;color:#9aa8a9;font-weight:700;letter-spacing:1.25px}.stats-row strong{display:flex;align-items:center;gap:10px;font-size:25px;letter-spacing:-.9px;margin:9px 0 5px;color:#254039}.stats-row small{font-family:'DM Sans',system-ui,sans-serif;font-size:10px;color:#92a39c;letter-spacing:0;font-weight:400}.stats-row p{font-size:10px;color:#98a59f;margin:0}.panel{background:#fff;border:1px solid #e2e9e6;border-radius:13px;padding:25px 26px;margin-bottom:22px;box-shadow:0 2px 6px #26463104}.two-column{display:grid;grid-template-columns:1.05fr 1fr;gap:24px;align-items:start}.right-stack{min-width:0}.section-title{display:flex;align-items:center;gap:12px;margin-bottom:22px}.section-title p{margin:0;font-size:10px;color:#8a9a9a;line-height:1.4}.section-title>.source-pill,.section-title>.secondary,.section-title>.result-cost{margin-left:auto}.icon-box{display:grid;place-items:center;width:37px;height:37px;background:#e9f6ef;color:#3b997b;border-radius:10px;flex-shrink:0}.step{font-size:10px;color:#cad6d0;margin-left:auto}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 16px;margin-bottom:17px}.form-grid.three{grid-template-columns:1.2fr 1fr .7fr}.field{display:flex;flex-direction:column;gap:8px;margin-bottom:16px}.form-grid .field{margin-bottom:0}.field>span{font-size:10px;color:#748881;font-weight:500}.field input,.field select,.field textarea{width:100%;border:1px solid #dce6e0;background:#fbfcfb;border-radius:7px;padding:10px 12px;font-size:11px;color:#344e44;min-height:38px}.field input:disabled{opacity:.55}.field textarea{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;line-height:1.55}.field input[type=range]{padding:0;accent-color:#298870}.upload{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;border:1px dashed #bcd7c8;background:#f9fcfa;border-radius:10px;padding:21px 15px;text-align:center;cursor:pointer;margin:20px 0 12px;color:#619580}.upload:hover{background:#f0f9f3}.upload b{font-size:11px;color:#527d68}.upload span{font-size:9px;color:#97b09f}.upload input{position:absolute;width:1px;height:1px;opacity:0}.inline-links{display:flex;gap:15px;justify-content:space-between;font-size:9px;margin:0 0 21px;color:#608872}.inline-links a,.inline-links button{display:flex;align-items:center;gap:5px}.inline-links button{background:none;font-size:9px;color:#608872;padding:0}.check-row{display:flex;align-items:center;gap:9px;font-size:10px;margin:22px 0;color:#75857a}.check-row input{accent-color:#2e9176;width:13px;height:13px}.check-row small{display:block;color:#a7b2a8;font-size:8px;margin-top:3px}.primary,.secondary{display:inline-flex;align-items:center;justify-content:center;gap:9px;font-size:11px;font-weight:600;min-height:40px;border-radius:7px;padding:12px 17px;white-space:nowrap}.primary{color:#fff;background:#238b70;box-shadow:0 3px 6px #24796212}.primary:hover{background:#176f58}.primary.full{width:100%}.primary.full svg:last-child{margin-left:auto}.primary.full svg:first-child{margin-right:auto}.secondary{background:#f4f8f5;border:1px solid #dce9e0;color:#587568}.secondary:hover{background:#e9f4eb}.source-pill{background:#f5f8f6;border:1px solid #e5ece6;border-radius:5px;color:#789382;font-size:8px;letter-spacing:.8px;padding:7px 9px;white-space:nowrap}.grid-card .section-title{margin-bottom:8px}.grid-card .eyebrow{font-size:8px;margin-bottom:8px}.grid-card h2{font-size:16px}.chart svg{width:100%;display:block}.legend{display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-top:4px;font-size:8px;color:#81948a}.legend span{display:flex;align-items:center;gap:5px}.legend i{width:6px;height:6px;border-radius:50%}.legend .unit{margin-left:auto;color:#a0aea5}.chart-caption{display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#96a89c;border-top:1px solid #edf2ed;padding-top:14px;margin-top:19px}.subtle{font-size:10px;color:#93a49b;line-height:1.7;margin-bottom:0}.grid-card .subtle{margin-top:15px;font-size:9px}.how-card{position:relative;background:#e8f0e5;border:1px solid #d9e5d5;border-radius:13px;padding:25px 27px;margin-bottom:22px}.how-card>.icon-box{background:#dcebcf;color:#6e9950;margin-bottom:16px}.how-card h3{font-size:19px;color:#496649;letter-spacing:-.6px;margin-bottom:8px}.how-card p{font-size:11px;color:#87977e;max-width:290px}.how-tags{display:flex;gap:8px;flex-wrap:wrap}.how-tags span{font-size:8px;padding:6px 8px;border:1px solid #d1dec8;border-radius:4px;color:#84957c;background:#eef5e9}.notice{border:1px solid #e1e8de;background:#f0f4ed;border-radius:9px;padding:13px 16px;display:flex;gap:10px;align-items:flex-start;color:#829179;font-size:10px;line-height:1.7;margin:0 0 23px}.notice svg{flex-shrink:0;margin-top:1px}.error{background:#fff3ed;border:1px solid #f4d6c5;border-radius:8px;color:#a86646;display:flex;align-items:center;gap:9px;padding:13px 16px;font-size:12px;margin-bottom:20px}.error>button{background:none;color:inherit;margin-left:auto;font-size:20px}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:10px}th{text-align:left;color:#8b9f92;letter-spacing:.2px;font-weight:500;font-size:9px;border-bottom:1px solid #e4ece5;padding:12px 10px;white-space:nowrap}td{padding:13px 10px;border-bottom:1px solid #edf2ec;line-height:1.5;color:#66806c;max-width:350px;overflow-wrap:anywhere}td:first-child{color:#3d5b46;font-weight:500}.empty{display:grid;place-items:center;padding:38px;color:#97a69a;font-size:11px;text-align:center;border-radius:8px;background:#f8faf7}.result-panel p{font-size:12px;color:#80937e}.result-cost{font-size:28px;color:#287d5e;letter-spacing:-.8px}.result-cost small{font-size:12px;font-weight:400}details{border-top:1px solid #e6eee4;margin-top:18px;padding-top:16px}summary{cursor:pointer;color:#739069;font-size:11px}.json{font-size:10px;line-height:1.7;background:#f5f8f2;border:1px solid #e4ecdf;color:#56754c;max-height:410px;overflow:auto;padding:18px;border-radius:7px;margin:18px 0 0;white-space:pre-wrap;overflow-wrap:anywhere}.explain-row{display:flex;gap:17px;margin-top:27px}.explain-row>span{font-size:11px;color:#a4bea0;font-weight:700}.explain-row b{font-size:12px;color:#628258}.explain-row p{font-size:10px;color:#92a68a;margin:8px 0 0}.text-button{background:none;color:#86a077;font-size:10px;padding:12px 0}.worker-note{font-size:10px;color:#729366;line-height:1.9;padding-top:20px}.worker-note .status-dot{margin-right:5px}.worker-note small{color:#b0bda5;font-size:9px}.protocol-strip{display:flex;align-items:center;gap:16px;flex-wrap:wrap;font-size:10px;color:#899f7d;background:#f4f7ef;border:1px solid #e7edde;border-radius:8px;padding:16px 19px;margin:22px 0}.protocol-strip b{color:#5e8c4b;margin-right:5px}.protocol-strip svg{color:#b5c6aa}.button-row{display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-top:16px}.button-row .field{margin:0;min-width:230px}.model-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:20px}.model-cards .panel{padding:24px}.model-cards h2{margin-top:13px;font-size:16px}.model-cards p{font-size:10px;color:#90a480;line-height:1.8}.availability{display:inline-flex;align-items:center;gap:6px;background:#f1f5ec;color:#8eaa78;font-size:9px;padding:7px 9px;border-radius:6px}.availability.live{background:#e7f3dd;color:#76a051}.api-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:17px;margin-bottom:26px}.api-cards>div{background:#f7f9f3;border:1px solid #e9edde;border-radius:8px;padding:19px}.api-cards code{font-size:11px;color:#789552}.api-cards p{font-size:10px;color:#a0b08a;margin:10px 0 0}footer{display:flex;justify-content:space-between;align-items:center;font-size:8px;color:#a5b49c;padding:13px 0 24px;margin-top:3px;border-top:1px solid #e0e9d9}footer span:first-child{display:flex;align-items:center;gap:5px}.loading{min-height:100vh;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#329974;gap:15px}.loading b{font-size:25px}.loading p{font-size:12px;color:#8ea899}.loading button{background:#268a70;color:white;padding:10px 20px;border-radius:8px}@media(min-width:1500px){.page{padding-top:47px}.page-heading{margin-bottom:34px}.panel{padding:30px}.chart{margin-top:10px}}@media(max-width:1100px){.sidebar{width:205px;padding:28px 13px}.brand strong{font-size:18px}main{margin-left:205px;width:calc(100% - 205px)}.page{padding:30px 24px 0}.topbar{padding:0 24px}.page-heading{flex-wrap:wrap}h1{font-size:29px}.two-column{grid-template-columns:1fr}.right-stack{display:grid;grid-template-columns:1.1fr 1fr;gap:18px}.stats-row>div{padding:20px}.stats-row strong{font-size:22px}.model-cards{grid-template-columns:1fr}.model-cards .panel{margin-bottom:0}.model-cards{margin-bottom:23px}.form-grid.three{grid-template-columns:1fr 1fr}.worker-note{padding:0}.api-cards{grid-template-columns:1fr}}@media(max-width:750px){.sidebar{position:relative;width:100%;padding:16px 18px;display:block}.app-shell{display:block}.brand{padding:0}.brand small{font-size:7px}.side-label,.side-divider,.side-character,.side-foot{display:none}nav{display:flex;margin-top:17px;overflow:auto;gap:6px}.nav-item{width:auto;white-space:nowrap;font-size:10px;padding:9px 11px}.nav-item svg{width:15px}.nav-arrow{display:none!important}main{margin:0;width:100%}.topbar{height:55px;padding:0 20px}.research-badge{display:none}.page{padding:26px 18px 0}h1{font-size:26px}.page-heading{gap:17px}.eyebrow{font-size:8px}.market-switch{width:100%;justify-content:space-around}.market-switch button{flex:1}.stats-row{grid-template-columns:1fr}.stats-row>div{padding:17px 21px}.stats-row>div+div:before{height:1px;width:calc(100% - 42px);top:0;left:21px}.stats-row strong{font-size:24px;display:inline-flex;margin:6px 0}.stats-row>div>span{display:block}.stats-row p{float:right;margin-top:15px;text-align:right;font-size:9px;max-width:125px}.panel{padding:21px 18px}.right-stack{display:block}.form-grid,.form-grid.three{gap:14px}.two-column{gap:0}.top-links{gap:10px}.top-links a{font-size:10px}.section-title{flex-wrap:wrap}.protocol-strip{gap:10px;padding:13px}.how-card{padding:23px}.legend{font-size:7px}.primary.full{min-height:43px}.section-title>.secondary{margin:0}.button-row .field{min-width:0;width:100%}footer{font-size:7px;gap:15px}.upload{padding:23px 12px}}1234@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Manrope:wght@400;500;600;700;800&display=swap');.job-status{display:flex;align-items:center;gap:9px;padding:14px 0;font-size:12px}.job-status button{margin-left:auto}.dataset-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:15px 0;border-bottom:1px solid #e7ecec}.dataset-row b{font-size:12px}.dataset-row small{display:block;margin-top:5px;color:#6f8087;font-size:11px}.dataset-row code{display:block;max-width:600px;overflow-wrap:anywhere;font-size:9px;color:#7d8e95;margin-top:6px}.dataset-list{margin-bottom:20px}.history-group{margin-top:25px}.history-group h3{font-size:15px;margin-bottom:4px}.history-group p{font-size:11px;color:#6f8087}.field textarea{width:100%;border:1px solid #dce5e6;border-radius:8px;padding:12px;background:#fff;resize:vertical;font:11px/1.5 ui-monospace,monospace}:root{font-family:'DM Sans',system-ui,sans-serif;color:#1b2e37;background:#f5f7f7;font-synthesis:none;font-weight:400}*{box-sizing:border-box}body{margin:0}button,input,select,textarea{font:inherit}button,a,input,select{transition:background .16s,color .16s,border-color .16s}button{cursor:pointer}button:disabled{opacity:.5;cursor:wait}a{color:inherit;text-decoration:none}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:3px solid #71d8bb;outline-offset:3px}button{border:none}h1,h2,h3,p{margin-top:0}h1,h2,h3,strong{font-family:'Manrope',system-ui,sans-serif}h1{font-size:34px;line-height:1.24;letter-spacing:-1.3px;margin:9px 0 10px;font-weight:800}h2{font-size:18px;letter-spacing:-.5px;margin-bottom:6px}h3{font-size:20px}p{line-height:1.65}.app-shell{display:flex;min-height:100vh}.sidebar{width:242px;background:#13212e;color:#bec8cd;position:fixed;inset:0 auto 0 0;display:flex;flex-direction:column;padding:31px 20px 22px;z-index:10}.brand{display:flex;gap:11px;align-items:center;color:white;padding:0 8px}.brand-symbol{background:#baf279;color:#16232c;width:40px;height:40px;border-radius:12px;display:grid;place-items:center}.brand strong{font-size:20px;letter-spacing:-.5px}.brand small{display:block;font-size:8px;letter-spacing:2px;color:#85959e;margin-top:5px}.side-divider{height:1px;background:#2b3844;margin:30px 8px}.side-label{font-size:9px;letter-spacing:1.7px;color:#74858f;margin:0 10px 15px}nav{display:grid;gap:6px}.nav-item{display:flex;align-items:center;gap:11px;width:100%;background:none;color:#a6b4bd;padding:13px 14px;border-radius:9px;font-size:12px;font-weight:500;text-align:left}.nav-item:hover{background:#223341}.nav-item.active{color:#c9f699;background:#2a4039}.nav-arrow{margin-left:auto}.side-character{margin-top:auto;padding:30px 9px 20px}.side-character video{display:block;width:100%;border-radius:15px;aspect-ratio:1;object-fit:cover;opacity:.85}.side-character>div{font-size:10px;color:#a1b1ba;padding-top:11px;display:flex;align-items:center;gap:6px}.tiny-dot,.status-dot{display:inline-block;border-radius:50%;width:6px;height:6px;background:#6fc9a5}.side-foot{margin:4px 8px 0;border-top:1px solid #2b3844;padding-top:19px;font-size:10px;color:#acbdc5;line-height:1.8}.side-foot .status-dot{margin-right:8px}.side-foot small{display:block;font-size:9px;color:#657985;padding-left:14px}main{margin-left:242px;min-width:0;width:calc(100% - 242px)}.topbar{height:73px;background:#fff;border-bottom:1px solid #e5ebeb;display:flex;align-items:center;justify-content:space-between;padding:0 40px}.crumb{display:flex;align-items:center;gap:10px;font-size:11px;color:#8b969a}.crumb b{color:#344a53;font-weight:500}.top-links{display:flex;align-items:center;gap:22px}.top-links a{display:flex;align-items:center;gap:7px;font-size:11px;color:#5c7079}.research-badge{font-size:8px;letter-spacing:1.2px;border:1px solid #d9e7df;border-radius:5px;padding:7px 9px;color:#577869;background:#f5faf7}.page{max-width:1470px;margin:0 auto;padding:39px 40px 0}.page-heading{display:flex;align-items:center;justify-content:space-between;gap:25px;margin-bottom:27px}.page-heading p{font-size:12px;color:#7b8c94;margin:0}.eyebrow{font-size:9px;letter-spacing:1.6px;font-weight:700;color:#70958a}.market-switch{display:flex;align-self:center;padding:4px;background:#e9efec;border-radius:9px;gap:3px;flex-shrink:0}.market-switch button{padding:9px 12px;font-size:11px;font-weight:700;color:#88968f;background:none;border-radius:6px;white-space:nowrap}.market-switch button.selected{background:#fff;color:#234d3d;box-shadow:0 2px 6px #18332b0a}.stats-row{display:grid;grid-template-columns:repeat(3,1fr);background:#fff;border:1px solid #e5ebea;border-radius:13px;margin-bottom:26px;box-shadow:0 3px 10px #1d473307}.stats-row>div{padding:23px 27px;position:relative}.stats-row>div+div:before{content:'';height:55%;top:23%;width:1px;background:#edf0ef;position:absolute;left:0}.stats-row span{font-size:8px;color:#9aa8a9;font-weight:700;letter-spacing:1.25px}.stats-row strong{display:flex;align-items:center;gap:10px;font-size:25px;letter-spacing:-.9px;margin:9px 0 5px;color:#254039}.stats-row small{font-family:'DM Sans',system-ui,sans-serif;font-size:10px;color:#92a39c;letter-spacing:0;font-weight:400}.stats-row p{font-size:10px;color:#98a59f;margin:0}.panel{background:#fff;border:1px solid #e2e9e6;border-radius:13px;padding:25px 26px;margin-bottom:22px;box-shadow:0 2px 6px #26463104}.two-column{display:grid;grid-template-columns:1.05fr 1fr;gap:24px;align-items:start}.right-stack{min-width:0}.section-title{display:flex;align-items:center;gap:12px;margin-bottom:22px}.section-title p{margin:0;font-size:10px;color:#8a9a9a;line-height:1.4}.section-title>.source-pill,.section-title>.secondary,.section-title>.result-cost{margin-left:auto}.icon-box{display:grid;place-items:center;width:37px;height:37px;background:#e9f6ef;color:#3b997b;border-radius:10px;flex-shrink:0}.step{font-size:10px;color:#cad6d0;margin-left:auto}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px 16px;margin-bottom:17px}.form-grid.three{grid-template-columns:1.2fr 1fr .7fr}.field{display:flex;flex-direction:column;gap:8px;margin-bottom:16px}.form-grid .field{margin-bottom:0}.field>span{font-size:10px;color:#748881;font-weight:500}.field input,.field select,.field textarea{width:100%;border:1px solid #dce6e0;background:#fbfcfb;border-radius:7px;padding:10px 12px;font-size:11px;color:#344e44;min-height:38px}.field input:disabled{opacity:.55}.field textarea{font-family:ui-monospace,SFMono-Regular,Consolas,monospace;line-height:1.55}.field input[type=range]{padding:0;accent-color:#298870}.upload{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:8px;border:1px dashed #bcd7c8;background:#f9fcfa;border-radius:10px;padding:21px 15px;text-align:center;cursor:pointer;margin:20px 0 12px;color:#619580}.upload:hover{background:#f0f9f3}.upload b{font-size:11px;color:#527d68}.upload span{font-size:9px;color:#97b09f}.upload input{position:absolute;width:1px;height:1px;opacity:0}.inline-links{display:flex;gap:15px;justify-content:space-between;font-size:9px;margin:0 0 21px;color:#608872}.inline-links a,.inline-links button{display:flex;align-items:center;gap:5px}.inline-links button{background:none;font-size:9px;color:#608872;padding:0}.check-row{display:flex;align-items:center;gap:9px;font-size:10px;margin:22px 0;color:#75857a}.check-row input{accent-color:#2e9176;width:13px;height:13px}.check-row small{display:block;color:#a7b2a8;font-size:8px;margin-top:3px}.primary,.secondary{display:inline-flex;align-items:center;justify-content:center;gap:9px;font-size:11px;font-weight:600;min-height:40px;border-radius:7px;padding:12px 17px;white-space:nowrap}.primary{color:#fff;background:#238b70;box-shadow:0 3px 6px #24796212}.primary:hover{background:#176f58}.primary.full{width:100%}.primary.full svg:last-child{margin-left:auto}.primary.full svg:first-child{margin-right:auto}.secondary{background:#f4f8f5;border:1px solid #dce9e0;color:#587568}.secondary:hover{background:#e9f4eb}.source-pill{background:#f5f8f6;border:1px solid #e5ece6;border-radius:5px;color:#789382;font-size:8px;letter-spacing:.8px;padding:7px 9px;white-space:nowrap}.grid-card .section-title{margin-bottom:8px}.grid-card .eyebrow{font-size:8px;margin-bottom:8px}.grid-card h2{font-size:16px}.chart svg{width:100%;display:block}.legend{display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-top:4px;font-size:8px;color:#81948a}.legend span{display:flex;align-items:center;gap:5px}.legend i{width:6px;height:6px;border-radius:50%}.legend .unit{margin-left:auto;color:#a0aea5}.chart-caption{display:flex;align-items:center;justify-content:space-between;font-size:9px;color:#96a89c;border-top:1px solid #edf2ed;padding-top:14px;margin-top:19px}.subtle{font-size:10px;color:#93a49b;line-height:1.7;margin-bottom:0}.grid-card .subtle{margin-top:15px;font-size:9px}.how-card{position:relative;background:#e8f0e5;border:1px solid #d9e5d5;border-radius:13px;padding:25px 27px;margin-bottom:22px}.how-card>.icon-box{background:#dcebcf;color:#6e9950;margin-bottom:16px}.how-card h3{font-size:19px;color:#496649;letter-spacing:-.6px;margin-bottom:8px}.how-card p{font-size:11px;color:#87977e;max-width:290px}.how-tags{display:flex;gap:8px;flex-wrap:wrap}.how-tags span{font-size:8px;padding:6px 8px;border:1px solid #d1dec8;border-radius:4px;color:#84957c;background:#eef5e9}.notice{border:1px solid #e1e8de;background:#f0f4ed;border-radius:9px;padding:13px 16px;display:flex;gap:10px;align-items:flex-start;color:#829179;font-size:10px;line-height:1.7;margin:0 0 23px}.notice svg{flex-shrink:0;margin-top:1px}.error{background:#fff3ed;border:1px solid #f4d6c5;border-radius:8px;color:#a86646;display:flex;align-items:center;gap:9px;padding:13px 16px;font-size:12px;margin-bottom:20px}.error>button{background:none;color:inherit;margin-left:auto;font-size:20px}.table-wrap{overflow:auto}table{border-collapse:collapse;width:100%;font-size:10px}th{text-align:left;color:#8b9f92;letter-spacing:.2px;font-weight:500;font-size:9px;border-bottom:1px solid #e4ece5;padding:12px 10px;white-space:nowrap}td{padding:13px 10px;border-bottom:1px solid #edf2ec;line-height:1.5;color:#66806c;max-width:350px;overflow-wrap:anywhere}td:first-child{color:#3d5b46;font-weight:500}.empty{display:grid;place-items:center;padding:38px;color:#97a69a;font-size:11px;text-align:center;border-radius:8px;background:#f8faf7}.result-panel p{font-size:12px;color:#80937e}.result-cost{font-size:28px;color:#287d5e;letter-spacing:-.8px}.result-cost small{font-size:12px;font-weight:400}details{border-top:1px solid #e6eee4;margin-top:18px;padding-top:16px}summary{cursor:pointer;color:#739069;font-size:11px}.json{font-size:10px;line-height:1.7;background:#f5f8f2;border:1px solid #e4ecdf;color:#56754c;max-height:410px;overflow:auto;padding:18px;border-radius:7px;margin:18px 0 0;white-space:pre-wrap;overflow-wrap:anywhere}.explain-row{display:flex;gap:17px;margin-top:27px}.explain-row>span{font-size:11px;color:#a4bea0;font-weight:700}.explain-row b{font-size:12px;color:#628258}.explain-row p{font-size:10px;color:#92a68a;margin:8px 0 0}.text-button{background:none;color:#86a077;font-size:10px;padding:12px 0}.worker-note{font-size:10px;color:#729366;line-height:1.9;padding-top:20px}.worker-note .status-dot{margin-right:5px}.worker-note small{color:#b0bda5;font-size:9px}.protocol-strip{display:flex;align-items:center;gap:16px;flex-wrap:wrap;font-size:10px;color:#899f7d;background:#f4f7ef;border:1px solid #e7edde;border-radius:8px;padding:16px 19px;margin:22px 0}.protocol-strip b{color:#5e8c4b;margin-right:5px}.protocol-strip svg{color:#b5c6aa}.button-row{display:flex;align-items:center;gap:18px;flex-wrap:wrap;margin-top:16px}.button-row .field{margin:0;min-width:230px}.model-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:20px}.model-cards .panel{padding:24px}.model-cards h2{margin-top:13px;font-size:16px}.model-cards p{font-size:10px;color:#90a480;line-height:1.8}.availability{display:inline-flex;align-items:center;gap:6px;background:#f1f5ec;color:#8eaa78;font-size:9px;padding:7px 9px;border-radius:6px}.availability.live{background:#e7f3dd;color:#76a051}.api-cards{display:grid;grid-template-columns:repeat(3,1fr);gap:17px;margin-bottom:26px}.api-cards>div{background:#f7f9f3;border:1px solid #e9edde;border-radius:8px;padding:19px}.api-cards code{font-size:11px;color:#789552}.api-cards p{font-size:10px;color:#a0b08a;margin:10px 0 0}footer{display:flex;justify-content:space-between;align-items:center;font-size:8px;color:#a5b49c;padding:13px 0 24px;margin-top:3px;border-top:1px solid #e0e9d9}footer span:first-child{display:flex;align-items:center;gap:5px}.loading{min-height:100vh;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#329974;gap:15px}.loading b{font-size:25px}.loading p{font-size:12px;color:#8ea899}.loading button{background:#268a70;color:white;padding:10px 20px;border-radius:8px}@media(min-width:1500px){.page{padding-top:47px}.page-heading{margin-bottom:34px}.panel{padding:30px}.chart{margin-top:10px}}@media(max-width:1100px){.sidebar{width:205px;padding:28px 13px}.brand strong{font-size:18px}main{margin-left:205px;width:calc(100% - 205px)}.page{padding:30px 24px 0}.topbar{padding:0 24px}.page-heading{flex-wrap:wrap}h1{font-size:29px}.two-column{grid-template-columns:1fr}.right-stack{display:grid;grid-template-columns:1.1fr 1fr;gap:18px}.stats-row>div{padding:20px}.stats-row strong{font-size:22px}.model-cards{grid-template-columns:1fr}.model-cards .panel{margin-bottom:0}.model-cards{margin-bottom:23px}.form-grid.three{grid-template-columns:1fr 1fr}.worker-note{padding:0}.api-cards{grid-template-columns:1fr}}@media(max-width:750px){.sidebar{position:relative;width:100%;padding:16px 18px;display:block}.app-shell{display:block}.brand{padding:0}.brand small{font-size:7px}.side-label,.side-divider,.side-character,.side-foot{display:none}nav{display:flex;margin-top:17px;overflow:auto;gap:6px}.nav-item{width:auto;white-space:nowrap;font-size:10px;padding:9px 11px}.nav-item svg{width:15px}.nav-arrow{display:none!important}main{margin:0;width:100%}.topbar{height:55px;padding:0 20px}.research-badge{display:none}.page{padding:26px 18px 0}h1{font-size:26px}.page-heading{gap:17px}.eyebrow{font-size:8px}.market-switch{width:100%;justify-content:space-around}.market-switch button{flex:1}.stats-row{grid-template-columns:1fr}.stats-row>div{padding:17px 21px}.stats-row>div+div:before{height:1px;width:calc(100% - 42px);top:0;left:21px}.stats-row strong{font-size:24px;display:inline-flex;margin:6px 0}.stats-row>div>span{display:block}.stats-row p{float:right;margin-top:15px;text-align:right;font-size:9px;max-width:125px}.panel{padding:21px 18px}.right-stack{display:block}.form-grid,.form-grid.three{gap:14px}.two-column{gap:0}.top-links{gap:10px}.top-links a{font-size:10px}.section-title{flex-wrap:wrap}.protocol-strip{gap:10px;padding:13px}.how-card{padding:23px}.legend{font-size:7px}.primary.full{min-height:43px}.section-title>.secondary{margin:0}.button-row .field{min-width:0;width:100%}footer{font-size:7px;gap:15px}.upload{padding:23px 12px}}
AnalysisPanel.jsxAdded+31
App.jsx+11-9
Dockerfile+1-1
README.md+66-5
app.py+90-7
archive_import.pyAdded+342
bulk.pyAdded+262
core.py+7
datasets.pyAdded+83
file_inputs.pyAdded+76
models.py+2
package-lock.json+2-2
package.json+1-1
requirements.txt+3
resources.zip+2-2
resources_manifest.json+16-13
scenarios.pyAdded+236
styles.css+1