Spaces:
Running
Make customer and NGO inference the default workflow with dated market news
Browse filesReplace the archived-first landing with an on-demand customer/NGO workspace. Reuse the bounded CPU queue, refresh official grid history before NGO fitting, preserve measured-input and origin checks, and expose live_analysis plus market_news over REST and MCP. Add server-side SerpApi Google News integration with public-only queries, shared cache, conservative quotas, source dates and explicit missing-secret status. Keep news separate from numeric forecasts and tariff quotes.
Validation: 109 packaged regression tests passed, plus the final currency guard and repeated API contract check (110 unique passing cases). React production build and actual local REST/MCP smoke passed. New official-history readers verified against PT, DE and all five AU NEM regions. Live SerpApi calls were not made because the Space has no SERPAPI_API_KEY. Existing CPU Basic hardware and private plugin visibility remain unchanged.
Files changed (13)
- .gitignoreAdded+20
- App.jsx+21-14
- Dockerfile+1-1
- LiveWorkspace.jsxAdded+263
- README.md+105-1
- app.py+24-4
- bulk.py+10-5
- live.cssAdded+1
- live_analysis.pyAdded+238
- live_sources.pyAdded+275
- news.pyAdded+437
- resources.zip+2-2
- resources_manifest.json+9-4
1234567891011121314151617181920.venv/node_modules/dist/__pycache__/*.py[cod].pytest_cache/# These verified assets are unpacked from resources.zip at runtime.assets/data/evidence/scripts/tests/validation/# Local credentials, caches and private job artifacts are never published..env.env.**.sqlite**.dbprivate-audit*.ziptests_new/1 unmodified line234567894 unmodified lines141516171819202122232425262728293031323334353637383940414243441 unmodified lineimport {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>}4 unmodified linesfunction Field({label,children}){return <label className="field"><span>{label}</span>{children}</label>}function 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><div hidden={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')}}/></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="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 line2345678910114 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950511 unmodified lineimport {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';import LiveWorkspace from './LiveWorkspace.jsx';import './live.css';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=[['live','Analyze now',Zap],['quotes','Quote explorer',Zap],['bills','Your bill profile',ReceiptText],['analysis','Import bills & 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>}4 unmodified linesfunction Field({label,children}){return <label className="field"><span>{label}</span>{children}</label>}function 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('live'),[error,setError]=useState(''),[busy,setBusy]=useState(false);const [usage,setUsage]=useState(''),[bill,setBill]=useState(''),[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 [runtime,setRuntime]=useState(null),[runtimeError,setRuntimeError]=useState(''),[liveBusy,setLiveBusy]=useState(false);const [month,setMonth]=useState(''),[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(()=>{let cancelled=false;request('/api/runtime').then(d=>{if(!cancelled){setRuntime(d);setMonth(d.latest_complete_month||d.latest_month||'')}}).catch(e=>{if(!cancelled)setRuntimeError(e.message)});return()=>{cancelled=true}},[]);useEffect(()=>{if(tab==='live'||boot)return;let cancelled=false;request('/api/bootstrap').then(d=>{if(!cancelled){setBoot(d);setMonth(d.latest_month)}}).catch(e=>{if(!cancelled)setError(e.message)});return()=>{cancelled=true}},[tab,boot]);useEffect(()=>{if(tab!=='models')return;setEvidence(null);let cancel=false;request('/api/model_evidence',{country}).then(d=>{if(!cancel)setEvidence(d)}).catch(e=>setError(e.message));return()=>{cancel=true}},[country,tab]);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=>{if(liveBusy)return;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);return <div className="app-shell"><aside className="sidebar"><a className="brand" href="#" onClick={e=>{e.preventDefault();setTab('live')}}><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 WORKSPACE</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==='live'?'Your data. A fresh analysis.':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==='live'?'Run a forecast, compare supplied offers, and check the market when you need it.':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':''} disabled={liveBusy} title={liveBusy?'Wait for the current analysis before changing markets':undefined} onClick={()=>changeMarket(c)}>{m.flag} {c}</button>)}</div></div>{error&&<div className="error" role="alert"><AlertCircle size={18}/>{error}<button onClick={()=>setError('')}>×</button></div>}{tab!=='live'&&<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>{bills||usage!==''?num(billingUsage):'—'}<small>kWh / year</small></strong><p>{bills?'From uploaded monthly bills':profileSource==='annual_user_input'?(usage!==''?'From your annual input':'Enter your consumption'):'Reviewed annualized invoice estimate'}</p></div><div><span>YOUR CURRENT BILL</span><strong>{bills||bill!==''?num(billingTotal,2):'—'}<small>{market.currency} / year</small></strong><p>{bills?`${bills.length} supplied monthly records`:bill!==''?'Full electricity cost, tax included':'Enter your electricity cost'}</p></div></div>}<div hidden={tab!=='live'}><LiveWorkspace key={country} country={country} market={market} runtime={runtime} runtimeError={runtimeError} onPendingChange={setLiveBusy} onOpenBills={()=>setTab('analysis')}/></div>{tab!=='live'&&!boot&&<section className="panel" role="status"><h2>Loading this workspace</h2><p>{error||'Retrieving the archive and source registry…'}</p>{error&&<button className="secondary" onClick={()=>{setError('');request('/api/bootstrap').then(setBoot).catch(e=>setError(e.message))}}>Retry</button>}</section>}{boot&&<><div hidden={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')}}/></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="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">ARCHIVED MARKET 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} archived monthly records · {String(history[0]?.timestamp||'').slice(0,7)}–{String(history.at(-1)?.timestamp||'').slice(0,7)}<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>On-demand analysis and audit APIs.</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>live_analysis</code><p>Run customer or NGO forecasts with dated market and news context.</p></div><div><code>market_news</code><p>Read SerpApi electricity news with source dates and cache metadata.</p></div><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>live_analysis</option><option>market_news</option><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(['model_evidence','market_news'].includes(apiType))p={country};if(apiType==='live_analysis')p={role:'customer',country,include_news:true,include_market:true,series:[],horizon_months:12,models:['seasonal_naive']};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 AnalysisPanel.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 LiveWorkspace.jsx styles.css live.css vite.config.js ./RUN npm run buildFROM python:3.12-slim
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import React, {useEffect, useMemo, useRef, useState} from 'react';import {Activity, AlertCircle, ArrowRight, ArrowUpRight, CheckCircle2, Clock3, Download, FileSpreadsheet, Home, Info, Newspaper, RefreshCw, Upload, Users, Zap} from 'lucide-react';import Papa from 'papaparse';
const MODEL_NAMES = {seasonal_naive:'Seasonal baseline', sarima:'SARIMA', grokked_sarima:'Grokked SARIMA', sarimax_garch:'Calendar SARIMAX + GARCH'};const COLORS = ['#16856b', '#416db7', '#b77b27', '#8c5cad'];const UNITS = new Set(['kWh','GWh','EUR/kWh','AUD/kWh','EUR/MWh','AUD/MWh']);const number = value => Number(value).toLocaleString(undefined,{maximumFractionDigits:2});const month = value => String(value || '').slice(0,7);const safeURL = value => {try {const url=new URL(value); return ['https:','http:'].includes(url.protocol)?url.href:null;} catch {return null;}};function dated(value) {if(!value)return 'Not supplied'; const date=new Date(value);return Number.isNaN(date.valueOf())?'Not supplied':date.toLocaleString(undefined,{dateStyle:'medium',timeStyle:'short'});}function noteText(value) {return typeof value==='string'?value:value?.message||value?.reason||JSON.stringify(value);}function Field({label,children}) {return <label className="field"><span>{label}</span>{children}</label>;}function Notice({children,warning=false}) {return <div className={`live-note${warning?' warning':''}`}><Info size={17}/><div>{children}</div></div>;}
async function call(path, payload, signal) { const bounded=new AbortController();let timedOut=false; const cancel=()=>bounded.abort(); signal?.addEventListener('abort',cancel,{once:true}); if(signal?.aborted)bounded.abort(); const timeout=setTimeout(()=>{timedOut=true;bounded.abort();},45000); try { const response=await fetch(path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload),signal:bounded.signal}); const data=await response.json(); if(!response.ok)throw Error(typeof data.detail==='string'?data.detail:'The request could not be completed. Review the inputs and try again.'); return data; }catch(error){if(timedOut)throw Error('The service took too long to respond. Try checking the request again.');throw error;} finally {clearTimeout(timeout);signal?.removeEventListener('abort',cancel);}}
function readCSV(file) { if(!file)return Promise.resolve(null); if(file.size>2_000_000)return Promise.reject(Error('Use a CSV smaller than 2 MB.')); return new Promise((resolve,reject)=>Papa.parse(file,{header:true,skipEmptyLines:'greedy',transformHeader:h=>h.replace(/^\uFEFF/,'').trim(),complete:result=>{ if(result.errors.length)return reject(Error(`CSV: ${result.errors[0].message}`)); if(!result.data.length)return reject(Error('This CSV has no data rows.')); resolve(result.data); },error:reject}));}
// Coverage is never invented from an invoice allocation: the uploader must// either supply coverage=1 or explicitly attest to complete measured months.export function normalizeSeries(rows, role, completeMonths) { if(!rows?.length)return []; const grouped=new Map(); for(const [index,row] of rows.entries()) { const allocation=String(row.allocation||'').toLowerCase(); if(/uniform|pro-rated|prorated|estimate/.test(allocation))throw Error(`Row ${index+2}: allocated or estimated invoice months cannot be used as measured forecast observations.`); const sid=String(row.series_id|| (role==='customer'?'anonymous-meter':'anonymous-series')).trim(); if(!sid||sid.length>100)throw Error(`Row ${index+2}: use an anonymous series_id of 1–100 characters.`); const isBill=Object.hasOwn(row,'month')&&Object.hasOwn(row,'kwh'); const stamp=isBill&&/^\d{4}-\d{2}$/.test(String(row.month).trim())?`${String(row.month).trim()}-01`:String(row.timestamp||'').trim(); const rawValue=isBill?row.kwh:row.value; const value=Number(rawValue); const unit=isBill?'kWh':String(row.unit||'').trim(); const suppliedCoverage=row.coverage!==undefined&&String(row.coverage).trim()!==''; if((!suppliedCoverage||isBill)&&!completeMonths)throw Error('Confirm that the uploaded rows represent complete, measured monthly usage. Allocated PDF months cannot be used as measured forecast observations.'); const coverage=suppliedCoverage?Number(row.coverage):1; if(!/^\d{4}-\d{2}-01(?:T00:00:00(?:\.0+)?)?$/.test(stamp))throw Error(`Row ${index+2}: use a month-start timestamp (YYYY-MM-01), or month and kwh columns.`); if(String(rawValue??'').trim()===''||!Number.isFinite(value)||!UNITS.has(unit)||coverage!==1)throw Error(`Row ${index+2}: supply a finite value, a supported electricity unit, and complete coverage=1.`); if(!grouped.has(sid))grouped.set(sid,[]); grouped.get(sid).push({timestamp:stamp.slice(0,10),value,unit,coverage}); } if(grouped.size>(role==='customer'?1:10))throw Error(role==='customer'?'Customer mode accepts one meter at a time. Use NGO mode for multiple named series.':'NGO mode accepts up to ten named series per run.'); const now=new Date(); const currentMonth=now.getUTCFullYear()*12+now.getUTCMonth(); return [...grouped].map(([series_id,records])=>{ records.sort((a,b)=>a.timestamp.localeCompare(b.timestamp)); if(records.length<12||records.length>600)throw Error(`${series_id}: upload 12–600 complete months. A shorter billing snapshot can still be reviewed under Import bills & swaps.`); if(new Set(records.map(r=>r.unit)).size!==1)throw Error(`${series_id}: keep usage, retail price and wholesale price in separate series.`); let previous; for(const record of records) { const [year,monthNumber]=record.timestamp.split('-').map(Number); const serial=year*12+monthNumber-1; if(monthNumber<1||monthNumber>12||year<1900||serial>=currentMonth)throw Error(`${series_id}: forecast inputs must be complete past months.`); if(previous!==undefined&&serial!==previous+1)throw Error(`${series_id}: months must be consecutive, without duplicates or gaps.`); if(!record.unit.endsWith('/MWh')&&record.value<0)throw Error(`${series_id}: only wholesale prices may contain negative values.`); previous=serial; } return {series_id,records}; });}
function csvTemplate(role) { const header=role==='ngo'?'series_id,timestamp,value,unit,coverage\n':'month,kwh\n'; const url=URL.createObjectURL(new Blob([header],{type:'text/csv;charset=utf-8'})); const anchor=document.createElement('a');anchor.href=url;anchor.download=`electrocheap-${role}-empty-template.csv`;anchor.click();URL.revokeObjectURL(url);}
function ForecastChart({history, models}) { const entries=Object.entries(models||{}).filter(([,m])=>m.predictions?.length); const actual=(history||[]).slice(-12); if(!entries.length)return null; const all=[...actual.map(r=>r.value),...entries.flatMap(([,m])=>m.predictions.map(p=>p.value))]; const low=Math.min(...all), high=Math.max(...all), padding=(high-low)*.15||1; const n=Math.max(actual.length+entries[0][1].predictions.length,2), width=720,height=226,left=57,right=16,top=18,bottom=38; const x=i=>left+i*(width-left-right)/(n-1); const y=value=>height-bottom-(value-low+padding)/(high-low+2*padding)*(height-top-bottom); const origin=actual.length-1; const labels=[...actual.map(r=>r.timestamp),...entries[0][1].predictions.map(p=>p.timestamp)]; return <div className="live-forecast-chart"><svg viewBox={`0 0 ${width} ${height}`} role="img" aria-label="Monthly observations followed by forecasts; dashed lines are predictions"> {[0,1,2].map(i=>{const v=high+padding-i*(high-low+2*padding)/2;return <g key={i}><line x1={left} x2={width-right} y1={y(v)} y2={y(v)} stroke="#e2ebe6"/><text x={left-9} y={y(v)+4} textAnchor="end">{number(v)}</text></g>;})} {actual.length>0&&<><polyline points={actual.map((r,i)=>`${x(i)},${y(r.value)}`).join(' ')} fill="none" stroke="#334e46" strokeWidth="2.4"/><line x1={x(origin)} x2={x(origin)} y1={top} y2={height-bottom} stroke="#9cb4a8" strokeDasharray="3 4"/></>} {entries.map(([name,model],k)=>{const points=[...(actual.length?[`${x(origin)},${y(actual.at(-1).value)}`]:[]),...model.predictions.map((r,i)=>`${x(actual.length+i)},${y(r.value)}`)];return <polyline key={name} points={points.join(' ')} fill="none" stroke={COLORS[k%COLORS.length]} strokeWidth="2.5" strokeDasharray="6 4"/>;})} {[0,...(origin>0?[origin]:[]),n-1].filter((v,i,a)=>a.indexOf(v)===i).map(i=><text key={i} x={x(i)} y={height-12} textAnchor={i===0?'start':i===n-1?'end':'middle'}>{month(labels[i])}</text>)} </svg><div className="live-legend">{actual.length>0&&<span><i style={{background:'#334e46'}}/>Measured history</span>}{entries.map(([name],k)=><span key={name}><i style={{background:COLORS[k%COLORS.length]}}/>{MODEL_NAMES[name]||name}</span>)}</div></div>;}
function SeriesResult({item,input}) { const models=Object.entries(item.models||{}), predictions=models[0]?.[1]?.predictions||[]; const unit=models[0]?.[1]?.unit||input?.records?.[0]?.unit||''; const quantity=['kWh','GWh'].includes(unit); const total=predictions.reduce((sum,p)=>sum+p.value,0); return <section className="panel live-series"><div className="live-result-heading"><div><span className="live-kicker">FRESH FORECAST</span><h3>{item.series_id}</h3><p>{item.observations} observations · last actual {month(item.origin)}</p></div>{predictions.length>0&&<div className="live-result-number"><small>{quantity?'Forecast total':'Mean forecast price'} · {predictions.length} months</small><strong>{number(quantity?total:total/predictions.length)} <span>{unit}</span></strong><small>{MODEL_NAMES[models[0][0]]||models[0][0]}</small></div>}</div> <ForecastChart history={input?.records} models={item.models}/> {!models.length&&<Notice warning>No selected model produced a forecast for this series.</Notice>} {(item.failures||[]).map((failure,i)=><Notice warning key={i}>{MODEL_NAMES[failure.model]||failure.model}: {failure.reason}</Notice>)} {predictions.length>0&&<p className="live-caption">Forecast starts {month(predictions[0].timestamp)}. These are point estimates; calibrated uncertainty intervals are not available.</p>} <details><summary>Monthly predictions and model diagnostics</summary><div className="table-wrap"><table><thead><tr><th>Month</th>{models.map(([name])=><th key={name}>{MODEL_NAMES[name]||name} · {unit}</th>)}</tr></thead><tbody>{predictions.map((p,i)=><tr key={p.timestamp}><td>{month(p.timestamp)}</td>{models.map(([name,m])=><td key={name}>{number(m.predictions[i]?.value)}</td>)}</tr>)}</tbody></table></div>{item.warnings?.length>0&&<p className="live-caption">Model warnings: {item.warnings.join(', ')}</p>}</details> </section>;}
function NewsResult({news}) { if(!news||['skipped','not_requested'].includes(news.status))return null; const articles=news.articles||[]; const stale=news.stale===true||news.status==='stale'; const unavailable={not_configured:'Market news is not connected.',unconfigured:'Market news is not connected.',quota_exhausted:'The news search allowance has been reached.',unavailable:'The news source is temporarily unavailable.',empty:'No matching articles were returned.',stale:'Showing an older news snapshot.'}; return <section className="panel live-news"><div className="section-title"><span className="icon-box"><Newspaper size={19}/></span><div><h2>What is changing in the market</h2><p>SerpApi · Google News · sourced context</p></div><span className="live-badge">{stale?'Older snapshot':news.cache_hit?'Cached':articles.length?'Retrieved':String(news.status||'unavailable').replaceAll('_',' ')}</span></div> {stale&&news.status!=='stale'&&<Notice warning>Showing an older news snapshot. Its publication and retrieval dates remain visible below.</Notice>} {unavailable[news.status]&&<Notice warning={!['empty'].includes(news.status)}>{unavailable[news.status]} Your numerical analysis does not depend on news availability.</Notice>} {articles.length>0&&<div className="live-news-list">{articles.slice(0,10).map((article,i)=>{const href=safeURL(article.url||article.link);return <article key={`${href}-${i}`}><div><span>{typeof article.source==='object'?article.source?.name:article.source||'Source not supplied'}</span><time>{article.published_at?dated(article.published_at):'Publication date unavailable'}</time></div><h3>{href?<a href={href} target="_blank" rel="noreferrer noopener">{article.title}<ArrowUpRight size={15}/></a>:article.title}</h3></article>;})}</div>} <p className="live-caption">Retrieved: {dated(news.fetched_at||news.retrieved_at)}{news.cache_expires_at?` · Cache valid until ${dated(news.cache_expires_at)}`:''}</p><p className="live-caption">Headlines provide context. A rate change enters a bill comparison only through a dated, complete tariff quote.</p> </section>;}
function MarketResult({market,country}) { if(!market||['skipped','not_requested'].includes(market.status))return null; const meta=market.metadata||{}, records=market.records||[]; const urls=[...(meta.source_urls||[]),...(meta.source_url?[meta.source_url]:[])].filter(safeURL); const columns=Object.keys(records[0]||{}).slice(0,6); return <section className="panel live-market"><div className="section-title"><span className="icon-box"><Activity size={19}/></span><div><h2>Official market context</h2><p>{country==='PT'?'REN · Portugal':country==='DE'?'SMARD · Germany':'AEMO · Australia'}</p></div><span className="live-badge">{String(market.status||'unknown').replaceAll('_',' ')}</span></div> <div className="live-source-facts"><div><span>Covered month</span><strong>{meta.month||market.month||'See source records'}</strong></div><div><span>Retrieved</span><strong>{dated(meta.retrieved_at||market.retrieved_at)}</strong></div><div><span>Source records</span><strong>{Number(meta.rows_total??records.length).toLocaleString()} total · {records.length.toLocaleString()} in preview</strong></div></div> {market.error||market.message?<Notice warning>{market.message||market.error}</Notice>:null} {meta.scope&&<p className="live-caption">{meta.scope}</p>} {meta.null_policy&&<p className="live-caption">{meta.null_policy}</p>} {urls.length>0&&<div className="live-source-links">{urls.map((url,i)=><a href={url} target="_blank" rel="noreferrer noopener" key={url}>Official source {urls.length>1?i+1:''}<ArrowUpRight size={13}/></a>)}</div>} {records.length>0&&<details><summary>Inspect latest source records</summary><div className="table-wrap"><table><thead><tr>{columns.map(c=><th key={c}>{c.replaceAll('_',' ')}</th>)}</tr></thead><tbody>{records.slice(-10).map((record,i)=><tr key={i}>{columns.map(c=><td key={c}>{typeof record[c]==='number'?number(record[c]):String(record[c]??'Missing')}</td>)}</tr>)}</tbody></table></div><p className="live-caption">Showing the last {Math.min(records.length,10)} preview records. The audit contains a bounded preview of {records.length} of {Number(meta.rows_total??records.length).toLocaleString()} publisher records, with the full publisher source URLs.</p></details>} <p className="live-caption">Grid demand and wholesale prices describe the market. Household bills use the customer's consumption and retail contract.</p> </section>;}
function ComparisonResult({comparison,currency}) { if(!comparison)return null; const data=comparison.result||comparison; const rows=data.ranked_offers||[]; if(comparison.error)return <section className="panel"><h2>Quote comparison</h2><Notice warning>{comparison.error}</Notice></section>; return <section className="panel"><div className="section-title"><div><span className="live-kicker">SUPPLIED OFFER COMPARISON</span><h2>{rows.length?`${rows[0].provider} has the lowest supplied first-year cost`:'No eligible supplied offers'}</h2><p>Annual usage scenario · tax-inclusive quotes · {currency}</p></div></div> {rows.length>0&&<div className="table-wrap"><table><thead><tr><th>Provider</th><th>First-year cost · {currency}</th><th>Difference from current bill · {currency}</th></tr></thead><tbody>{rows.map((row,i)=><tr key={row.offer_id||i}><td>{row.provider}</td><td>{number(row.first_year_cost)}</td><td>{number(row.estimated_saving)}</td></tr>)}</tbody></table></div>} {data.excluded_offers?.length>0&&<details><summary>Excluded offers and reasons ({data.excluded_offers.length})</summary>{data.excluded_offers.map((offer,i)=><p className="live-caption" key={i}>{offer.offer_id}: {offer.reason}</p>)}</details>} <p className="live-caption">This compares supplied offers, subject to their terms. Future rates and realized savings remain uncertain.</p> </section>;}
export default function LiveWorkspace({country,market,runtime,runtimeError,onOpenBills,onPendingChange}) { const [role,setRole]=useState('customer'),[rows,setRows]=useState(null),[filename,setFilename]=useState(''),[complete,setComplete]=useState(false),[official,setOfficial]=useState(false); const [horizon,setHorizon]=useState(12),[models,setModels]=useState(['seasonal_naive']); const [includeNews,setIncludeNews]=useState(true),[includeMarket,setIncludeMarket]=useState(true),[region,setRegion]=useState(market.region); const [annual,setAnnual]=useState(''),[annualCost,setAnnualCost]=useState(''),[power,setPower]=useState(''),[meter,setMeter]=useState('standard'),[peak,setPeak]=useState(''); const [offers,setOffers]=useState(null),[offerName,setOfferName]=useState(''),[accepted,setAccepted]=useState(''); const [error,setError]=useState(''),[submitting,setSubmitting]=useState(false),[job,setJob]=useState(null),[result,setResult]=useState(null),[submitted,setSubmitted]=useState(null),[pollVersion,setPollVersion]=useState(0); const controller=useRef(null), resultsRef=useRef(null), fileVersion=useRef(0); const pending=submitting||['queued','running'].includes(job?.state); const normalized=useMemo(()=>{try{return {series:normalizeSeries(rows,role,complete),error:null}}catch(e){return {series:[],error:e.message}}},[rows,role,complete]); const useOfficial=role==='ngo'&&official&&!rows?.length; const minimum=useOfficial?36:normalized.series.length?Math.min(...normalized.series.map(s=>s.records.length)):0; const hasProfile=annual!==''||annualCost!==''; const hasNumeric=!!rows?.length||hasProfile||useOfficial; const latest=runtime?.latest_complete_month||runtime?.latest_month;
useEffect(()=>{onPendingChange?.(pending);return()=>onPendingChange?.(false);},[pending,onPendingChange]);
useEffect(()=>()=>{controller.current?.abort();fileVersion.current+=1;},[]); useEffect(()=>{if(minimum<36)setModels(['seasonal_naive']);},[minimum]); useEffect(()=>{ if(!job?.job_id||!['queued','running'].includes(job.state))return; let cancelled=false,timer,attempts=0; const aborter=new AbortController(); const poll=async()=>{ try { const next=await call('/api/analysis_result',{job_id:job.job_id,limit:100},aborter.signal); if(cancelled)return; if(next.state==='completed'){setJob(next);setResult(next.result);requestAnimationFrame(()=>resultsRef.current?.scrollIntoView({behavior:'smooth',block:'start'}));return;} if(next.state==='failed'){setJob(next);setError(next.error||'The analysis failed. No completed result is being claimed.');return;} setJob(previous=>({...previous,state:next.state})); attempts+=1; if(attempts>=180){setJob(previous=>({...previous,state:'paused'}));setError('The analysis is taking longer than expected. Use Check job to resume status checks; it will not submit a second run.');return;} timer=setTimeout(poll,2500); }catch(e){if(!cancelled&&e.name!=='AbortError'){setJob(previous=>({...previous,state:'paused'}));setError('Could not read the job status. Use Check job to reconnect to the existing run.');}} }; timer=setTimeout(poll,900); return()=>{cancelled=true;clearTimeout(timer);aborter.abort();}; },[job?.job_id,pollVersion]);
const changeRole=next=>{if(pending)return;setRole(next);setOfficial(next==='ngo');setRows(null);setFilename('');setComplete(false);setOffers(null);setOfferName('');setAnnual('');setAnnualCost('');setError('');setJob(null);setResult(null);setSubmitted(null);fileVersion.current+=1;}; const upload=async(file,type)=>{ if(!file)return; const version=++fileVersion.current;setError(''); try {const data=await readCSV(file);if(fileVersion.current!==version)return; if(type==='series'){setRows(data);setOfficial(false);setFilename(file.name);setComplete(false);setModels(['seasonal_naive']);} else {if(data.length>500)throw Error('Supply at most 500 offers.');setOffers(data);setOfferName(file.name);} setResult(null);setJob(null); }catch(e){if(fileVersion.current===version)setError(e.message);} }; const submit=async()=>{ setError(''); if(normalized.error){setError(normalized.error);return;} if(rows?.length&&!complete){setError('Confirm that the uploaded rows are complete, measured observations before running inference.');return;} if(!normalized.series.length&&!hasProfile&&!useOfficial&&!includeNews&&!includeMarket){setError('Add data, or select market news or the official feed for a market brief.');return;} if((normalized.series.length||useOfficial)&&!models.length){setError('Select at least one forecast model.');return;} if(hasProfile&&(!annual||annualCost===''||Number(annual)<=0||Number(annualCost)<0)){setError('Supply positive annual usage and the full current electricity cost.');return;} if((hasProfile&&!offers?.length)||(offers?.length&&!hasProfile)){setError('An offer comparison needs both annual consumption/current cost and complete provider quotes.');return;} if(hasProfile&&meter==='smart'&&(peak===''||Number(peak)<0||Number(peak)>100)){setError('Supply the measured peak-use percentage for the smart-meter quote comparison.');return;} const payload={role,country,region,horizon_months:Number(horizon),models,series:normalized.series,include_news:includeNews,include_market:includeMarket,use_official_history:useOfficial,observations_are_measured:!!rows?.length&&complete}; if(hasProfile){payload.profile={country,region,annual_kwh:Number(annual),current_annual_bill:Number(annualCost),meter_type:meter,profile_source:'annual_user_input',customer_type:'consumer'};if(power!=='')payload.profile.contracted_power_kva=Number(power);if(meter==='smart')payload.profile.peak_share=Number(peak)/100;payload.offers=offers;payload.accepted_conditions=accepted.split(',').map(s=>s.trim()).filter(Boolean);} controller.current?.abort();controller.current=new AbortController();setSubmitting(true);setResult(null);setJob(null); try {const ticket=await call('/api/live_analysis',payload,controller.current.signal);setSubmitted(payload);setJob({...ticket,state:ticket.state||'queued'});} catch(e){if(e.name!=='AbortError')setError(e.message);} finally {setSubmitting(false);} }; const resultSeries=result?.series?.length?result.series:result?.forecast?.series||[]; const successful=resultSeries.reduce((count,s)=>count+Object.keys(s.models||{}).length,0);
return <div className="live-workspace"> <div className="live-mode-switch" aria-label="Analysis audience"><button type="button" aria-pressed={role==='customer'} className={role==='customer'?'selected':''} disabled={pending} onClick={()=>changeRole('customer')}><Home size={20}/><span><strong>For a customer</strong><small>One meter. Your costs and forecast.</small></span>{role==='customer'&&<CheckCircle2 size={17}/>}</button><button type="button" aria-pressed={role==='ngo'} className={role==='ngo'?'selected':''} disabled={pending} onClick={()=>changeRole('ngo')}><Users size={20}/><span><strong>For an NGO</strong><small>Compare series. Examine market changes.</small></span>{role==='ngo'&&<CheckCircle2 size={17}/>}</button></div> <div className="live-freshness"><span><Clock3 size={15}/> Analysis runs when you request it</span><span>{latest?`Latest complete month: ${latest}`:'Each source keeps its own publication date'}</span><span>Private results expire after one hour</span></div> {runtimeError&&<Notice warning>Service readiness could not be checked. You can retry the analysis; its response will show any connection error.</Notice>} <div className="live-columns"><section className="panel live-input-panel"><div className="section-title"><span className="icon-box"><Upload size={19}/></span><div><h2>{role==='customer'?'Start with your consumption':'Bring the series you want to examine'}</h2><p>{role==='customer'?'A monthly CSV gives your forecast its own history.':'Up to ten anonymous consumption or price series per run.'}</p></div><span className="step">01</span></div> <label className="live-upload"><FileSpreadsheet size={29}/><strong>{filename||'Add monthly electricity data'}</strong><span>{filename?`${rows.length.toLocaleString()} rows read · ready for review`:role==='customer'?'CSV · month + kwh, or normalized monthly records':'CSV · series_id, timestamp, value, unit, coverage'}</span><input aria-label="Upload monthly electricity data" type="file" accept=".csv,text/csv" disabled={pending} onChange={e=>{const file=e.target.files?.[0];e.target.value='';upload(file,'series');}}/></label> <div className="live-upload-actions"><button type="button" onClick={()=>csvTemplate(role)}><Download size={13}/>Empty CSV template</button><button type="button" onClick={onOpenBills}>Have ZIP / PDF bills?<ArrowRight size={13}/></button>{rows&&<button type="button" disabled={pending} onClick={()=>{setRows(null);setFilename('');setComplete(false);}}>Clear</button>}</div> {rows&&<><label className="live-check"><input type="checkbox" checked={complete} disabled={pending} onChange={e=>setComplete(e.target.checked)}/><span>These are complete, measured monthly observations.<small>Daily allocations from PDF bills and partial months are not measured monthly actuals.</small></span></label>{normalized.error?<p className="live-validation"><AlertCircle size={14}/>{normalized.error}</p>:<div className="live-data-summary">{normalized.series.map(series=><div key={series.series_id}><CheckCircle2 size={14}/><b>{series.series_id}</b><span>{series.records.length} months · {month(series.records[0].timestamp)} to {month(series.records.at(-1).timestamp)} · {series.records[0].unit}</span></div>)}</div>}</>} {role==='ngo'&&<label className="live-check live-official-choice"><input type="checkbox" checked={official} disabled={pending||!!rows?.length} onChange={e=>setOfficial(e.target.checked)}/><Activity size={17}/><span>Use official grid history<small>Refresh the latest complete month, then fit a new grid-demand forecast in GWh. {country==='AU'?'This uses the NEM-wide history; regional context remains separate.':'This forecasts the whole grid, not individual household usage.'}</small></span></label>} {!rows&&<p className="live-input-help">Use at least 12 consecutive measured months for a seasonal baseline, or 36 for statistical models. You can also run a market brief without personal data.</p>} {role==='customer'&&<details className="live-offer-options"><summary>Compare provider quotes with your annual usage</summary><p className="live-caption">Enter your own totals and upload complete, dated offers. This is a first-year cost scenario; it does not require a forecast.</p><div className="form-grid"><Field label="Annual consumption · kWh"><input type="number" min="0.01" step="any" value={annual} disabled={pending} onChange={e=>setAnnual(e.target.value)} placeholder="Your annual usage"/></Field><Field label={`Annual electricity cost · ${market.currency}`}><input type="number" min="0" step="any" value={annualCost} disabled={pending} onChange={e=>setAnnualCost(e.target.value)} placeholder="Tax included"/></Field><Field label="Contracted power · kVA (if applicable)"><input type="number" min="0.1" step="any" value={power} disabled={pending} onChange={e=>setPower(e.target.value)}/></Field><Field label="Meter"><select value={meter} disabled={pending} 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="Measured peak usage · %"><input type="number" min="0" max="100" step="any" value={peak} disabled={pending} onChange={e=>setPeak(e.target.value)}/></Field>}<label className="live-quote-upload"><Upload size={16}/>{offerName||'Add complete provider quotes · CSV'}<input aria-label="Upload provider quotes" type="file" accept=".csv" disabled={pending} onChange={e=>{const file=e.target.files?.[0];e.target.value='';upload(file,'offers');}}/></label><a className="live-template-link" href="/downloads/quote_template.csv" download>Offer template<Download size={12}/></a><Field label="Offer conditions you have accepted · IDs, comma separated"><input value={accepted} disabled={pending} onChange={e=>setAccepted(e.target.value)}/></Field></details>} </section> <section className="panel live-run-panel"><div className="section-title"><span className="icon-box"><Zap size={19}/></span><div><h2>Choose what to run</h2><p>New calculations with dated source context.</p></div><span className="step">02</span></div><div className="form-grid"><Field label="Forecast horizon"><select value={horizon} disabled={pending} onChange={e=>setHorizon(e.target.value)}>{[3,12,24,36].map(h=><option key={h} value={h}>{h} months</option>)}</select></Field><Field label={country==='AU'?'NEM region':'Eligibility region / grid'}>{country==='AU'?<select value={region} disabled={pending} onChange={e=>setRegion(e.target.value)}>{['NSW1','QLD1','SA1','TAS1','VIC1'].map(r=><option key={r}>{r}</option>)}</select>:<input value={region} disabled={pending} onChange={e=>setRegion(e.target.value)}/>}</Field></div> <div className="live-options"><label className="live-check"><input type="checkbox" checked={includeMarket} disabled={pending} onChange={e=>setIncludeMarket(e.target.checked)}/><Activity size={17}/><span>Fetch official market data<small>{country==='PT'?'REN':country==='DE'?'SMARD':'AEMO'} · latest complete month, with coverage</small></span></label><label className="live-check"><input type="checkbox" checked={includeNews} disabled={pending} onChange={e=>setIncludeNews(e.target.checked)}/><Newspaper size={17}/><span>Include electricity news<small>SerpApi / Google News · public market context</small></span></label></div> <details className="live-model-options"><summary>Forecast models <span>{models.length} selected</span></summary>{Object.entries(MODEL_NAMES).map(([name,label])=><label className="live-check" key={name}><input type="checkbox" checked={models.includes(name)} disabled={pending||(name!=='seasonal_naive'&&minimum<36)} onChange={e=>setModels(previous=>e.target.checked?[...previous,name]:previous.filter(value=>value!==name))}/><span>{label}<small>{name==='seasonal_naive'?'12 complete months':name==='grokked_sarima'?'36 months · 80% SARIMA + 20% seasonal template':name==='sarimax_garch'?'36 months · calendar features + residual variance':'36 complete months'}</small></span></label>)}<p className="live-caption">Model failures are reported separately. News does not silently alter model inputs or tariff prices.</p></details> {!hasNumeric&&<div className="live-brief-note"><Newspaper size={18}/><div><b>Market brief only</b><span>Add monthly data to calculate a forecast, or annual usage and quotes to compare offers.</span></div></div>} {error&&<div className="live-error" role="alert"><AlertCircle size={17}/><span>{error}</span></div>} <button className="primary full live-submit" type="button" disabled={pending||job?.state==='paused'} onClick={submit}>{pending?<RefreshCw size={17} className="live-spinning"/>:<Zap size={17}/>}<span>{submitting?'Submitting your request…':pending?'Analysis in progress…':hasNumeric?'Run analysis now':'Run market brief'}</span><ArrowRight size={17}/></button> {job&&<div className={`live-job ${job.state==='failed'?'failed':''}`} role="status" aria-live="polite"><span>{job.state==='completed'?<CheckCircle2 size={16}/>:<Clock3 size={16}/>} {job.state==='completed'?'Analysis completed':job.state==='queued'?'Queued for calculation':job.state==='running'?'Calculating and collecting sources':job.state==='paused'?'Status checks paused':'Analysis failed'}</span>{job.state==='paused'&&<button onClick={()=>{setError('');setJob(previous=>({...previous,state:'running'}));setPollVersion(v=>v+1);}}>Check job<RefreshCw size={13}/></button>}</div>} <p className="live-private-note">Use anonymous data. Results and audit links expire after one hour or a restart. Public news queries never include your billing data.</p> </section></div> {!result&&<div className="live-expectations"><div><Activity size={18}/><span><b>Calculated for this request</b><small>{useOfficial?'Forecast the refreshed official grid series.':'Forecasts use the series you supply.'}</small></span></div><div><Clock3 size={18}/><span><b>Dates stay visible</b><small>Actuals, forecasts and news have distinct dates.</small></span></div><div><Download size={18}/><span><b>Evidence you can inspect</b><small>Download inputs, results and provenance.</small></span></div></div>} {result&&<div className="live-results" ref={resultsRef}><div className="live-results-header"><div><span className="live-kicker">THIS REQUEST</span><h2>{successful?`${successful} forecast${successful===1?'':'s'} calculated`:result.inference_status==='failed'?'Forecast unavailable — inspect the diagnostics':result.comparison?'Your comparison and market context':'Your market brief'}</h2><p>{market.name} · {role==='ngo'?'NGO workspace':'Customer workspace'} · requested {dated(result.requested_at||job.created_at)}</p></div>{job.export_path&&<a className="secondary" href={job.export_path} download><Download size={16}/>Download private audit</a>}</div> {(result.warnings||[]).map((warning,i)=><Notice warning key={i}>{noteText(warning)}</Notice>)} {resultSeries.map(item=><SeriesResult key={item.series_id} item={item} input={submitted?.series.find(s=>s.series_id===item.series_id)||(submitted?.use_official_history?{records:result.official_history?.records}:null)}/>)} <ComparisonResult comparison={result.comparison} currency={market.currency}/> <div className="live-context-grid"><MarketResult market={result.market} country={country}/><NewsResult news={result.news}/></div> <details className="panel live-audit-details"><summary>Full result, input freshness and provenance</summary><pre className="json">{JSON.stringify(result,null,2)}</pre></details> </div>} </div>;}6 unmodified lines789101112132 unmodified lines1617181920216 unmodified linesapp_port: 7860pinned: falsesuggested_hardware: cpu-basicshort_description: XenoWAttz × Bhor Bohr — bills, quotes and forecast evidence---# Electrocheap · XenoWAttz × Bhor Bohr2 unmodified lines**XenoWAttz** is the plugin identity, with **Bhor Bohr** visibly associated.The interface is React; the calculations, REST APIs and MCP tools are Python.Space: `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 Portugal6 unmodified lines789101112132 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241256 unmodified linesapp_port: 7860pinned: falsesuggested_hardware: cpu-basicshort_description: XenoWAttz × Bhor Bohr — on-demand customer and NGO analysis---# Electrocheap · XenoWAttz × Bhor Bohr2 unmodified lines**XenoWAttz** is the plugin identity, with **Bhor Bohr** visibly associated.The interface is React; the calculations, REST APIs and MCP tools are Python.## On-demand customer and NGO workspace · v0.4.0The default **Analyze now** workspace runs a new private job when requested.It does not load an archived leaderboard or a prefilled customer bill as itsstarting state. Archived benchmarks remain available in their existing views.- **Customer:** upload an anonymous monthly CSV (`month,kwh`, or`timestamp,value,unit,coverage`), confirm that the months are complete measuredobservations, choose a horizon and run a forecast. Twelve consecutive monthssupport the seasonal baseline; SARIMA, Grokked SARIMA and calendar SARIMAX–GARCHrequire 36. A quarter of bills can still support the separate reviewed billingand quote workflow; it is not enough to fit these seasonal models.- **NGO:** request official grid-history inference or upload up to ten namedusage/price series. Official history combines the recorded archive prefix witha newly verified final archive month and up to twelve missing complete months.PT uses REN mainland `CONSUMPTION`; DE checks every hourly SMARD record acrosspublication blocks and local daylight-saving boundaries; AU preserves thefive-region NEM scope rather than splicing one regional series into it.- **Offers:** annual/monthly customer profiles and complete dated suppliedquotes use the existing eligibility and cost calculator. The live API alsoaccepts up to 100 NGO profiles. Grid forecasts and news do not become retailtariff quotes. Automatic whole-market retail collection remains incomplete.- **News:** server-side SerpApi Google News requests add dated public marketcontext for PT, DE and AU. Customer data never enters the query. News is notsilently used as a fitted exogenous regressor; that requires a separatelyrecorded historical feature dataset and prospective evaluation.The latest complete month is computed at request time. For example, on2026-10-23 it is September 2026; October is still incomplete. Current monthlyinference rejects older observation cutoffs unless API clients explicitly set`allow_historical_origin=true`, in which case the historical origin is disclosed.PDF daily allocations cannot be relabeled as measured monthly observations.Completed, partially successful and failed model runs have distinct statuses.Source or news failures are explicit; no fabricated data is substituted.### SerpApi configurationAdd **`SERPAPI_API_KEY` as a Hugging Face Space Secret** in the existing DockerSpace. Do not place the key in a React variable, source file, query supplied by acustomer, or browser request. No key is included in this repository.Optional server configuration:| Variable | Default | Purpose ||---|---|---|| `ELECTROCHEAP_NEWS_DAILY_LIMIT` | `6` | Conservative upstream attempts per UTC day || `ELECTROCHEAP_NEWS_MONTHLY_LIMIT` | `180` | Attempts per UTC calendar month || `ELECTROCHEAP_NEWS_DB_PATH` | Writable `/data`, otherwise `/tmp` | SQLite cache and local budget |Public news is shared in a one-hour cache. No API retry or uncached publicoverride is exposed. Local quotas cover processes sharing the SQLite file;ephemeral storage can reset on a Space restart, and independent replicas needa shared budget service. Use the provider's own account cap for an account-widespending limit. The default build uses one CPU Basic replica and does notpurchase hardware or a SerpApi plan. Without a key, news returns`not_configured` while numerical analysis remains available.Official monthly refreshes have a ten-minute public cache. Earlier archivedmonths retain their original vintage; they are not represented as all beingre-fetched. Private customer inputs/results are never placed in these caches.### Live endpoints and MCP tools| Endpoint | Purpose ||---|---|| GET `/api/runtime` | Lightweight readiness, limits and latest complete month; no source or inference call || POST `/api/live_analysis` | Queue a composed customer/NGO request; returns private `job_id` || POST `/api/market_news` | Dated public news, cache and source status || POST `/api/analysis_result` | Poll the existing job; completed response includes `inference_status` |The corresponding new MCP tools are **`live_analysis`** and **`market_news`**.All existing tools remain available at `/mcp-server/mcp`.Example NGO request, using the existing CPU queue and fresh source verification:```json{"role": "ngo","country": "PT","use_official_history": true,"horizon_months": 12,"models": ["seasonal_naive", "grokked_sarima"],"include_market": true,"include_news": true}```Uploaded series additionally require `observations_are_measured: true`. Arequest without numerical data is explicitly a market brief. News is presentedwith publisher date, ingestion date, cache status and article links. The privateaudit ZIP includes exact refreshed model inputs, normalized requested inputs,results, source provenance and implementation hashes. It expires with the jobafter one hour or restart. Navigating among workspace tabs preserves the activejob in that browser tab; this is not a persistent authenticated customer account.### Validation for this changeThe resource bundle includes tests for input freshness, measured/allocated data,private job separation, official publication coverage, model failures, API/MCPcompatibility, news normalization, quota concurrency, cache expiry and secretredaction. News tests use mocked provider responses; connecting a real SerpApiaccount still requires the server secret above. Test and live-source evidenceare recorded separately so a mocked test is never represented as a live search.Space: `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 Portugal
21 unmodified lines222324252627282930313250 unmodified lines838485868788894 unmodified lines94959697989910010110210310410510621 unmodified linesfrom 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)def consumer_tool(payload: dict) -> dict:50 unmodified linesasync 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):4 unmodified linesbody = 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():21 unmodified lines22232425262728293031323334353637383940414243444550 unmodified lines969798991001011024 unmodified lines10710810911011111211311411511611711811912012112212312412512621 unmodified linesfrom 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_monthfrom live_analysis import submit_live_analysis, runtime_status, VERSIONfrom news import market_news as fetch_market_newsROOT = Path(__file__).resolve().parentBENCH_LOCK = threading.Lock()mcp = FastMCP("XenoWAttz × Bhor Bohr", host="0.0.0.0", instructions="Electrocheap: start with live_analysis for on-demand customer/NGO CPU forecasts and dated official/news context. market_news uses bounded server-side SerpApi public queries, never personal billing data. News is contextual evidence, not a numerical model feature. 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)LIVE_READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, idempotentHint=False, openWorldHint=True)@mcp.tool(name="live_analysis", annotations=LIVE_READ)def live_analysis_tool(payload: dict) -> dict:"""Run on-demand customer/NGO analysis and poll analysis_result. Supply role, country, measured monthly series (observations_are_measured=true), models and horizon_months; NGO may use use_official_history=true to refresh official grid history before fitting. Optional profile/profiles+dated offers for cost comparison. include_news uses server-configured quota-capped SerpApi public market context, never customer details. Latest complete month required unless allow_historical_origin=true. CPU forecasts are fitted now; news is not an unvalidated exogenous input. No contracting or hardware purchase."""return submit_live_analysis(payload)@mcp.tool(name="market_news", annotations=LIVE_READ)def market_news_tool(payload: dict) -> dict:"""Retrieve dated public electricity news from SerpApi for PT/DE/AU. Fixed public country queries only, server secret, shared cache and request budget. Parameters country, days (1–30), limit (1–30). News is market context, not a verified tariff or a causal price forecast. Missing credentials/provider failure return explicit status without fabricated results."""return fetch_market_news(payload)@mcp.tool(name="consumer_compare", annotations=READ_ONLY)def consumer_tool(payload: dict) -> dict:50 unmodified linesasync def lifespan(app):async with mcp.session_manager.run(): yieldapi = FastAPI(title="XenoWAttz × Bhor Bohr · Electrocheap", version=VERSION, lifespan=lifespan)@api.middleware("http")async def body_limit(request: Request, call_next):4 unmodified linesbody = await request.body()if len(body) > maximum:return JSONResponse({"detail":"Request size limit exceeded."}, status_code=413)response = await call_next(request)if request.url.path.startswith("/api/") and (request.method == "POST" or request.url.path == "/api/runtime"):response.headers["Cache-Control"] = "no-store"return response@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":VERSION,"paid_inference":False,"bulk_worker":"one bounded CPU queue","private_result_retention_seconds":3600}api.get("/api/runtime")(runtime_status)api.post("/api/live_analysis")(live_analysis_tool)api.post("/api/market_news")(market_news_tool)@api.get("/api/bootstrap")def bootstrap():
194 unmodified lines19519619719819920020120220320420543 unmodified lines249250251252253254255194 unmodified linesoperations={"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)43 unmodified linesversions[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()},194 unmodified lines19519619719819920020120220320420520620720820943 unmodified lines253254255256257258259260194 unmodified linesoperations={"switching":switching_scenarios,"forecast":bulk_forecast,"benchmark":bulk_benchmark}if kind not in operations:raise ValueError("Analysis kind must be switching, forecast or benchmark.")return submit_operation(kind,request,lambda:operations[kind](request))def submit_operation(kind, inputs, operation):"""Reuse the bounded worker and private retention for composed live requests."""if len(json.dumps(inputs,allow_nan=False).encode())>2_000_000:raise ValueError("Normalized analysis JSON limit is 2 MB.")jid=_reserve(kind,inputs)POOL.submit(_worker,jid,operation)return ticket(jid)43 unmodified linesversions[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","live_analysis.py","live_sources.py","sources.py","news.py"]: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()},
1.live-workspace{color:#263e35}.live-workspace button:disabled{cursor:not-allowed}.live-mode-switch{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:19px}.live-mode-switch>button{display:flex;align-items:center;gap:15px;padding:19px 21px;border:1px solid #dbe5df;border-radius:12px;background:#fff;color:#5a7166;text-align:left;min-height:85px}.live-mode-switch>button.selected{border-color:#499a78;background:#eef7f0;box-shadow:inset 0 0 0 1px #499a781f}.live-mode-switch>button>span{flex:1}.live-mode-switch strong{display:block;color:#264d3b;font-size:14px;font-weight:700}.live-mode-switch small{display:block;font-size:11px;line-height:1.5;color:#62796c;margin-top:5px}.live-freshness{display:flex;gap:18px;align-items:center;flex-wrap:wrap;color:#63786c;font-size:10px;margin:0 2px 24px}.live-freshness>span{display:flex;gap:7px;align-items:center}.live-freshness>span+span:before{content:'';width:3px;height:3px;border-radius:50%;background:#91aa9a}.live-columns{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(0,1fr);gap:23px;align-items:start}.live-workspace .panel{border-color:#dfe7e1}.live-workspace .section-title p{font-size:11px;color:#677d70;line-height:1.5}.live-workspace .section-title h2{font-size:18px;color:#294a38}.live-workspace .field>span{color:#526b5b;font-size:11px;line-height:1.4}.live-workspace .field input,.live-workspace .field select{font-size:12px;color:#284f3a;padding:11px 12px;background:#fcfdfb;min-height:42px}.live-workspace .field input::placeholder{color:#839488}.live-upload{display:flex;align-items:center;justify-content:center;flex-direction:column;gap:11px;min-height:174px;border:1.5px dashed #a2c3ae;border-radius:10px;background:#f5faf6;padding:23px 15px;color:#357450;text-align:center;cursor:pointer;position:relative}.live-upload:hover,.live-upload:focus-within{background:#edf7ef;border-color:#398764}.live-upload strong{font-size:13px;line-height:1.5;overflow-wrap:anywhere;max-width:100%}.live-upload>span{font-size:11px;line-height:1.6;color:#678773}.live-upload input,.live-quote-upload input{position:absolute;width:1px;height:1px;opacity:0}.live-upload-actions{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin:11px 0 18px}.live-upload-actions button,.live-template-link{display:inline-flex;align-items:center;gap:5px;background:none;color:#39785a;padding:3px 0;font-size:10px;line-height:1.5}.live-input-help{color:#6b8072;font-size:11px;margin:14px 0 2px;line-height:1.8}.live-check{display:flex;gap:10px;align-items:flex-start;font-size:12px;color:#3e604b;line-height:1.5;margin:17px 0;cursor:pointer}.live-check>input{accent-color:#26855f;margin:3px 0 0;min-width:15px;width:15px;height:15px;flex-shrink:0}.live-check>svg{margin-top:1px;color:#4a8868;flex-shrink:0}.live-check>span{min-width:0}.live-check small{display:block;font-size:10px;line-height:1.7;color:#6e8575;margin-top:3px}.live-validation{display:flex;align-items:flex-start;gap:8px;font-size:11px;color:#90602d;line-height:1.65}.live-validation svg{flex-shrink:0;margin-top:3px}.live-data-summary{display:grid;gap:8px;background:#eef7f0;border:1px solid #d9e9dc;border-radius:8px;padding:13px 14px;margin:15px 0;color:#3c7651;font-size:10px}.live-data-summary>div{display:flex;align-items:center;gap:7px;flex-wrap:wrap}.live-data-summary span{color:#607c69}.live-data-summary b{overflow-wrap:anywhere}.live-offer-options summary,.live-model-options summary{font-size:11px;color:#3d7255;line-height:1.6}.live-offer-options[open]>summary{margin-bottom:14px}.live-offer-options .form-grid{margin-top:17px;gap:16px 12px}.live-quote-upload{position:relative;display:flex;align-items:center;gap:8px;min-height:43px;padding:12px;border:1px dashed #a9c8b3;border-radius:7px;color:#4d7d5f;font-size:11px;cursor:pointer}.live-template-link{margin:10px 0 15px}.live-run-panel .form-grid{gap:16px 12px}.live-options{background:#f6f9f4;border:1px solid #e1e9dd;border-radius:9px;padding:2px 15px;margin:23px 0 18px}.live-options .live-check{margin:16px 0}.live-options .live-check+.live-check{border-top:1px solid #e0e9da;padding-top:16px}.live-model-options{margin-top:0;padding-top:0;border-top:0;margin-bottom:21px}.live-model-options summary{display:flex;justify-content:space-between;gap:10px;list-style:disclosure-closed}.live-model-options summary>span{font-size:10px;color:#738b79}.live-brief-note{display:flex;gap:11px;align-items:flex-start;background:#f3f6f0;border-radius:8px;padding:14px;color:#57724f;margin:18px 0}.live-brief-note svg{flex-shrink:0;margin-top:2px}.live-brief-note b{display:block;font-size:11px}.live-brief-note span{display:block;font-size:10px;line-height:1.7;color:#6b8262;margin-top:4px}.live-submit{font-size:12px!important;min-height:47px!important;background:#237e59;box-shadow:0 3px 8px #1b603413}.live-submit:hover{background:#186444}.live-private-note{font-size:10px;line-height:1.75;color:#73856e;margin:13px 0 0}.live-error{display:flex;align-items:flex-start;gap:9px;font-size:11px;line-height:1.65;color:#995b38;background:#fff5ed;border:1px solid #f0d9c7;padding:13px 14px;border-radius:7px;margin:16px 0}.live-error svg{flex-shrink:0;margin-top:2px}.live-job{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 0 0;color:#44775a;font-size:11px}.live-job>span{display:flex;align-items:center;gap:7px}.live-job.failed{color:#9b603e}.live-job>button{display:flex;align-items:center;gap:6px;background:none;color:#3f7956;font-size:10px}.live-expectations{display:grid;grid-template-columns:repeat(3,1fr);gap:22px;margin:2px 3px 25px;padding:8px 0 17px}.live-expectations>div{display:flex;gap:11px;align-items:flex-start}.live-expectations svg{color:#638d6b;flex-shrink:0;margin-top:2px}.live-expectations b{display:block;font-size:11px;color:#59735b;font-weight:500;line-height:1.5}.live-expectations small{display:block;font-size:10px;color:#7c8e77;margin-top:4px;line-height:1.65}.live-note{display:flex;gap:9px;align-items:flex-start;padding:13px 15px;margin:0 0 15px;border:1px solid #dce8d8;background:#f3f7ee;color:#617953;border-radius:8px;font-size:11px;line-height:1.7}.live-note.warning{border-color:#eadcc7;background:#fcf7ee;color:#876639}.live-note svg{flex-shrink:0;margin-top:2px}.live-results{scroll-margin-top:18px}.live-results-header{display:flex;align-items:center;justify-content:space-between;gap:18px;margin:7px 0 23px;padding-top:12px;border-top:1px solid #d7e2d4}.live-kicker{display:block;font-size:9px;font-weight:700;letter-spacing:1.4px;color:#6a8e6a;margin-bottom:8px}.live-results-header h2{font-size:23px;margin:8px 0}.live-results-header p{font-size:11px;color:#687f65;margin:0}.live-result-heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start}.live-series h3{font-size:18px;color:#36572e;overflow-wrap:anywhere;margin:8px 0}.live-result-heading p{font-size:10px;color:#768e6b}.live-result-number{text-align:right;flex-shrink:0}.live-result-number>small{display:block;font-size:10px;color:#839377;line-height:1.7}.live-result-number strong{display:block;color:#3b7d4d;font-size:25px;margin:4px 0;letter-spacing:-.7px}.live-result-number strong>span{font-size:11px;letter-spacing:0;font-weight:400}.live-forecast-chart{margin-top:5px}.live-forecast-chart svg{width:100%;display:block}.live-forecast-chart text{font-size:11px;fill:#71886c}.live-legend{display:flex;flex-wrap:wrap;align-items:center;gap:15px;font-size:10px;color:#60775d;margin:5px 0 16px}.live-legend span{display:flex;align-items:center;gap:5px}.live-legend i{width:7px;height:7px;display:block;border-radius:50%}.live-caption{font-size:11px;line-height:1.75;color:#6b8062;margin:12px 0 0}.live-workspace table{font-size:11px}.live-workspace th{color:#5b7a55;font-size:10px}.live-workspace td{color:#476d42}.live-series summary{color:#4c7644;font-size:11px}.live-context-grid{display:grid;grid-template-columns:1fr 1fr;gap:23px;align-items:start}.live-badge{margin-left:auto;padding:6px 8px;border-radius:5px;background:#f0f5e9;border:1px solid #dfe8d5;color:#6c8057;font-size:9px;line-height:1.4;max-width:110px;overflow-wrap:anywhere}.live-context-grid .section-title{gap:10px;flex-wrap:wrap}.live-context-grid h2{font-size:16px}.live-news-list article{padding:16px 0;border-bottom:1px solid #e4ebdb}.live-news-list article:first-child{padding-top:0}.live-news-list article>div{display:flex;align-items:baseline;gap:8px;flex-wrap:wrap;color:#70875e;font-size:10px;line-height:1.6}.live-news-list time{color:#88967b;font-size:9px}.live-news-list h3{margin:7px 0 0;font-size:12px;line-height:1.7;letter-spacing:0;font-weight:600;color:#455f33}.live-news-list h3 a{display:flex;gap:8px;justify-content:space-between;align-items:flex-start}.live-news-list h3 a:hover{color:#20744a;text-decoration:underline}.live-news-list h3 svg{flex-shrink:0;margin-top:3px}.live-source-facts{display:grid;gap:16px;margin:0 0 19px}.live-source-facts>div{display:flex;justify-content:space-between;gap:14px;font-size:11px;line-height:1.6;border-bottom:1px solid #e9eddf;padding-bottom:11px}.live-source-facts span{color:#839470}.live-source-facts strong{font-size:11px;color:#5f7e4c;text-align:right;font-weight:500;max-width:65%}.live-source-links{display:flex;gap:15px;flex-wrap:wrap;margin-top:15px}.live-source-links a{display:flex;align-items:center;gap:5px;font-size:10px;color:#628548}.live-audit-details{padding:18px 23px}.live-audit-details summary{font-size:11px;color:#6a854b}.live-spinning{animation:live-spin 1.5s linear infinite}@keyframes live-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.live-spinning{animation:none}.live-workspace *{scroll-behavior:auto!important}}@media(max-width:1150px){.live-columns{grid-template-columns:1fr}.live-run-panel .form-grid{grid-template-columns:1fr 1fr}.live-expectations{gap:14px}.live-context-grid{grid-template-columns:1fr}.live-freshness{gap:12px;font-size:9px}.live-mode-switch>button{padding:17px 16px}.live-mode-switch small{font-size:10px}.live-mode-switch strong{font-size:13px}}@media(max-width:650px){.live-mode-switch{grid-template-columns:1fr;gap:10px}.live-mode-switch>button{min-height:76px}.live-freshness{gap:10px;margin-bottom:21px}.live-freshness>span+span:before{display:none}.live-freshness>span{width:100%}.live-freshness>span:first-child{font-size:10px}.live-columns{gap:0}.live-workspace .section-title h2{font-size:17px}.live-expectations{grid-template-columns:1fr;gap:16px}.live-results-header{align-items:flex-start;flex-direction:column}.live-results-header h2{font-size:21px}.live-result-heading{flex-direction:column;gap:6px}.live-result-number{text-align:left;margin-bottom:12px}.live-result-number strong{font-size:24px}.live-workspace .form-grid{grid-template-columns:1fr 1fr}.live-workspace .field>span{font-size:10px}.live-workspace .field input,.live-workspace .field select{font-size:11px}.live-source-facts strong{max-width:60%}.live-upload-actions{gap:10px}.live-upload-actions button{font-size:9px}.live-news-list h3{font-size:12px}.live-model-options summary{font-size:11px}}@media(max-width:380px){.live-workspace .form-grid{grid-template-columns:1fr}.live-source-facts>div{display:block}.live-source-facts strong{display:block;text-align:left;max-width:100%;margin-top:5px}.live-workspace .panel{padding:20px 15px}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238"""One request, one private analysis: measured inputs, fresh sources, dated news.
News remains explanatory evidence. It does not silently modify a retail quote,the numerical forecast, or an archived backtest."""from datetime import datetime, timezoneimport json
from bulk import bulk_forecast, monthly_series, submit_operationfrom core import MARKETS, boolean, consumer_compare, ngo_comparefrom live_sources import official_history, live_market_contextfrom news import market_news, news_statusfrom scenarios import hash_json, integerfrom sources import AU_REGIONS, latest_complete_month
VERSION = "0.4.0"MODELS = {"seasonal_naive", "sarima", "grokked_sarima", "sarimax_garch"}REGIONS = {"PT": "PT-mainland", "DE": "DE-local-grid", "AU": "NSW1"}
def runtime_status(): """Small landing-page payload. No archive reads or network/model calls.""" return { "version": VERSION, "requested_at": datetime.now(timezone.utc).isoformat(), "latest_month": latest_complete_month(), "latest_complete_month": latest_complete_month(), "markets": [{"country": c, "currency": v, "region": REGIONS[c]} for c, v in MARKETS.items()], "au_regions": AU_REGIONS, "news": news_status(), "models": sorted(MODELS), "limits": {"customer_series": 1, "ngo_series": 10, "seasonal_naive_minimum_months": 12, "statistical_minimum_months": 36, "horizon_months": 36, "private_result_retention_seconds": 3600}, "retail_offers": "Dated complete supplied quotes; no automatic whole-market tariff ranking.", "news_use": "Sourced market context; not a fitted exogenous feature or a tariff price feed.", }
def _series(raw, country, role, allow_historical): if not isinstance(raw, dict): raise ValueError("Each series must be an object.") sid = str(raw.get("series_id", "")).strip() if not sid or len(sid) > 100: raise ValueError("Use an anonymous series_id with 1–100 characters.") rows = raw.get("records", []) if not isinstance(rows, list) or any(not isinstance(r, dict) for r in rows): raise ValueError("Series records must be a list of monthly objects.") for row in rows: allocation = str(row.get("allocation", "")).lower() if any(word in allocation for word in ("uniform", "pro-rated", "prorated", "estimate")): raise ValueError("Allocated invoice estimates cannot be relabeled as measured monthly actuals.") frame = monthly_series(raw) unit = str(frame.unit.iloc[0]) if unit.startswith(("EUR/", "AUD/")) and not unit.startswith(MARKETS[country] + "/"): raise ValueError("The price series currency must match the selected market.") if role == "customer" and unit in {"GWh", "EUR/MWh", "AUD/MWh"}: raise ValueError("Customer inference uses measured kWh or retail currency/kWh; choose NGO for grid/wholesale series.") last_month = frame.timestamp.iloc[-1].strftime("%Y-%m") if last_month != latest_complete_month() and not allow_historical: raise ValueError( f"Series {sid} ends in {last_month}. A current forecast needs actuals through " f"{latest_complete_month()}; explicitly set allow_historical_origin=true for a dated historical-origin run." ) return {"series_id": sid, "records": [ {"timestamp": row.timestamp.date().isoformat(), "value": float(row.value), "unit": str(row.unit), "coverage": 1} for row in frame.itertuples(index=False) ]}
def prepare_request(payload): """Validate before queuing or spending a public news/source request.""" if not isinstance(payload, dict): raise ValueError("Supply an analysis object.") try: size = len(json.dumps(payload, allow_nan=False).encode()) except (ValueError, TypeError): raise ValueError("Supply finite JSON values.") from None if size > 2_000_000: raise ValueError("Normalized analysis JSON limit is 2 MB.") role, country = payload.get("role", "customer"), payload.get("country", "PT") if (not isinstance(role, str) or not isinstance(country, str) or role not in {"customer", "ngo"} or country not in MARKETS): raise ValueError("Choose customer or ngo and PT, DE or AU.") region = str(payload.get("region", REGIONS[country])).strip() if not region or len(region) > 100: raise ValueError("Supply a valid eligibility region.") official = boolean(payload.get("use_official_history", False), "use_official_history") historical = boolean(payload.get("allow_historical_origin", False), "allow_historical_origin") raw_series = payload.get("series", []) if not isinstance(raw_series, list) or len(raw_series) > (1 if role == "customer" else 10): raise ValueError("Supply at most one customer series or ten NGO series.") if official and (role != "ngo" or raw_series): raise ValueError("Official grid history is an NGO target; use it separately from uploaded series.") if raw_series and not boolean(payload.get("observations_are_measured", False), "observations_are_measured"): raise ValueError("Confirm observations_are_measured=true for complete measured monthly inputs.") series = [_series(r, country, role, historical) for r in raw_series] if len({s["series_id"] for s in series}) != len(series): raise ValueError("Use unique series_id values.") models = payload.get("models", ["seasonal_naive"]) if (not isinstance(models, list) or not models or len(models) > 4 or any(not isinstance(m, str) or m not in MODELS for m in models) or len(models) != len(set(models))): raise ValueError("Choose distinct supported CPU models.") steps = integer(payload.get("horizon_months", 12), "horizon_months", 1, 36) profiles = payload.get("profiles", []) profile = payload.get("profile") if profile is not None: if profiles: raise ValueError("Supply profile or profiles, not both.") profiles = [profile] if not isinstance(profiles, list) or len(profiles) > (1 if role == "customer" else 100): raise ValueError("Use one customer profile or at most 100 NGO profiles.") normalized_profiles = [] profile_ids = set() # Keep only calculator inputs. Never forward customer data to a search API. fields = {"profile_id", "annual_kwh", "current_annual_bill", "billing_months", "peak_share", "meter_type", "contracted_power_kva", "profile_source", "customer_type"} for i, p in enumerate(profiles): if not isinstance(p, dict): raise ValueError("Each profile must be an object.") if p.get("country", country) != country: raise ValueError("Every profile must match the selected market.") if p.get("currency", MARKETS[country]) != MARKETS[country]: raise ValueError("Profile currency must match the selected market; no currency conversion is inferred.") q = {k: v for k, v in p.items() if k in fields} q.update(country=country, region=str(p.get("region", region))) q.setdefault("profile_id", f"site-{i + 1}") q.setdefault("customer_type", "consumer" if role == "customer" else "ngo") pid = q["profile_id"] if not isinstance(pid, str) or not pid.strip() or len(pid) > 100 or pid in profile_ids: raise ValueError("Use distinct anonymous profile_id values with 1–100 characters.") profile_ids.add(pid) if not isinstance(q["customer_type"], str) or q["customer_type"] not in {"consumer", "ngo", "business"}: raise ValueError("Profile customer_type must be consumer, ngo or business.") consumer_compare({**q, "offers": []}) # validates the actual billing/profile inputs normalized_profiles.append(q) offers = payload.get("offers", []) if not isinstance(offers, list) or len(offers) > 500: raise ValueError("Supply at most 500 complete dated offers.") if offers and not normalized_profiles: raise ValueError("Supply an annual or monthly bill profile before comparing offers.") accepted = payload.get("accepted_conditions", []) if not isinstance(accepted, list) or any(not isinstance(v, str) or len(v) > 200 for v in accepted): raise ValueError("accepted_conditions must be a list of offer IDs.") include_news = boolean(payload.get("include_news", True), "include_news") include_market = boolean(payload.get("include_market", True), "include_market") if not (series or official or offers or include_news or include_market): raise ValueError("Select a forecast, a quote comparison, or market context to run.") return { "role": role, "country": country, "region": region, "requested_at": datetime.now(timezone.utc).isoformat(), "as_of": datetime.now(timezone.utc).date().isoformat(), "series": series, "use_official_history": official, "observations_are_measured": bool(series), "allow_historical_origin": historical, "models": models, "horizon_months": steps, "profiles": normalized_profiles, "offers": offers, "accepted_conditions": accepted, "include_news": include_news, "include_market": include_market, "news_days": integer(payload.get("news_days", 7), "news_days", 1, 30), }
def run_analysis(request): """Execute in the existing bounded CPU queue; partial failures are explicit.""" country, role = request["country"], request["role"] result = { "status": "on_demand_analysis", "version": VERSION, "role": role, "country": country, "requested_at": request["requested_at"], "input_sha256": hash_json(request), "series": [], "forecast": None, "comparison": None, "inference_status": "not_requested", "warnings": [], "news": {"status": "not_requested", "articles": []}, "market": {"status": "not_requested", "records": []}, "freshness": {"latest_complete_month": latest_complete_month(), "series": []}, "news_use": "Context only. Headlines have not been fitted as exogenous features and do not change numerical forecasts or quoted rates.", "retail_coverage": "Eligible supplied offers only. News and wholesale prices are not retail tariff quotes.", } series = request["series"] if request["use_official_history"]: try: history = official_history(country, request["region"]) series = [{"series_id": f"{country}-official-grid", "records": history["records"]}] # Exact model inputs belong in the private result/export, alongside provenance. result["official_history"] = history except Exception as exc: result["inference_status"] = "failed" result["warnings"].append(str(exc)[:350] if isinstance(exc, ValueError) else "Official history refresh failed; no archived forecast was substituted.") if series: forecast = bulk_forecast({"series": series, "models": request["models"], "horizon_months": request["horizon_months"]}) result["series"] = forecast.pop("series") result["forecast"] = forecast successful = sum(len(s["models"]) for s in result["series"]) expected = len(result["series"]) * len(request["models"]) result["inference_status"] = "succeeded" if successful == expected else "partial" if successful else "failed" for s in result["series"]: stale = s["origin"][:7] != result["freshness"]["latest_complete_month"] result["freshness"]["series"].append({"series_id": s["series_id"], "observations_through": s["origin"][:7], "historical_origin": stale, "basis": "verified official grid history" if request["use_official_history"] else "user-supplied measured monthly records"}) if stale: result["warnings"].append(f"{s['series_id']}: historical-origin forecast from {s['origin'][:7]}, not from today.") if result["inference_status"] != "succeeded": result["warnings"].append("Some requested models failed. Only successful fits have predictions; inspect per-series diagnostics.") if request["offers"]: opts = {"offers": request["offers"], "accepted_conditions": request["accepted_conditions"], "as_of": request["as_of"], "allow_illustrative": False} if role == "customer": result["comparison"] = consumer_compare({**request["profiles"][0], **opts}) else: result["comparison"] = ngo_compare({"profiles": request["profiles"], **opts}) elif request["profiles"]: result["warnings"].append("The supplied profile has no complete dated offers, so no tariff ranking or savings were computed.") if request["include_market"]: try: result["market"] = live_market_context(country, request["region"]) except Exception: result["market"] = {"status": "unavailable", "records": [], "message": "The official market feed is unavailable. No archived or fabricated context was substituted."} result["warnings"].append(result["market"]["message"]) if request["include_news"]: try: result["news"] = market_news({"country": country, "days": request["news_days"], "limit": 10}) except Exception: result["news"] = {"status": "unavailable", "articles": [], "message": "Market news is unavailable; the numerical result remains independent."} if result["news"]["status"] not in {"fresh", "cached", "empty"}: result["warnings"].append(result["news"].get("message", "Market news is not available for this request.")) result["completed_at"] = datetime.now(timezone.utc).isoformat() return result
def submit_live_analysis(payload): request = prepare_request(payload) return submit_operation("live_analysis", request, lambda: run_analysis(request))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""Refresh a bounded tail of official monthly demand before on-demand inference.
Archived prefixes retain their recorded geographic scope. Refreshed observationsare validated independently; a failed refresh never turns an archive into acurrent dataset. Only allowlisted official publisher URLs are fetched."""from collections import OrderedDictfrom copy import deepcopyfrom datetime import datetime, timezonefrom pathlib import Pathfrom threading import Lockfrom urllib.parse import urlencodeimport hashlibimport jsonimport mathimport time
import pandas as pd
from sources import (AU_REGIONS, REN_BASE, get_json, latest_complete_month, live_market, check_month)
ROOT = Path(__file__).resolve().parentMAX_BACKFILL_MONTHS = 12CACHE_TTL_SECONDS = 600MAX_CACHE_MONTHS = 40_MONTH_CACHE = OrderedDict()_CACHE_LOCK = Lock()
SCOPES = { "PT": "Portugal mainland grid consumption; not customer or retailer demand", "DE": "Germany SMARD country grid load; not total final energy consumption", "AU": "AEMO NEM TOTALDEMAND proxy: NSW1 + QLD1 + SA1 + TAS1 + VIC1; excludes WA/NT",}
def _now(): return datetime.now(timezone.utc).isoformat()
def _market(country, region=""): if country not in SCOPES: raise ValueError("country must be PT, DE or AU.") if country == "AU" and region not in {"", "NEM", *AU_REGIONS}: raise ValueError("Australian region must be NEM, NSW1, QLD1, VIC1, SA1 or TAS1.")
def _finite_nonnegative(value, label): if isinstance(value, bool): raise ValueError(f"{label} must be a finite nonnegative value.") try: number = float(value) except (TypeError, ValueError): raise ValueError(f"{label} must be a finite nonnegative value.") from None if not math.isfinite(number) or number < 0: raise ValueError(f"{label} must be a finite nonnegative value.") return number
def _pt_month(month): parsed = check_month(month) url = REN_BASE + "ElectricityConsumptionSupplyMonthly?" + urlencode( {"culture": "en-US", "year": parsed.year, "month": parsed.month}) data, digest, retrieved = get_json(url) if not isinstance(data, list): raise ValueError("REN monthly response schema changed.") consumption = [row for row in data if isinstance(row, dict) and row.get("type") == "CONSUMPTION"] if len(consumption) != 1: raise ValueError("REN must publish exactly one CONSUMPTION aggregate.") value = _finite_nonnegative(consumption[0].get("monthly_Accumulation"), "REN consumption") return value, {"source_urls": [url], "response_sha256": [digest], "source_retrieved_at": [retrieved], "coverage_basis": "Published non-null monthly aggregate; not an independent interval audit"}
def _de_month(month): parsed = check_month(month) start = pd.Timestamp(parsed).tz_localize("Europe/Berlin").tz_convert("UTC") end = (pd.Timestamp(parsed) + pd.offsets.MonthBegin()).tz_localize("Europe/Berlin").tz_convert("UTC") start_ms, end_ms = int(start.timestamp() * 1000), int(end.timestamp() * 1000) index_url = "https://www.smard.de/app/chart_data/410/DE/index_hour.json" index, index_digest, index_time = get_json(index_url) stamps = index.get("timestamps") if isinstance(index, dict) else None if not isinstance(stamps, list) or not stamps or any( isinstance(t, bool) or not isinstance(t, int) for t in stamps ): raise ValueError("SMARD hourly index schema changed.") stamps = sorted(set(stamps)) preceding = [t for t in stamps if t <= start_ms] if not preceding: raise ValueError("SMARD has no publication block covering the month start.") blocks = [preceding[-1]] + [t for t in stamps if start_ms < t < end_ms] if len(blocks) > 7: raise ValueError("SMARD publication layout exceeds the bounded monthly reader.") urls, hashes, times = [index_url], [index_digest], [index_time] observations = {} for block in blocks: url = f"https://www.smard.de/app/chart_data/410/DE/410_DE_hour_{block}.json" data, digest, retrieved = get_json(url) values = data.get("series") if isinstance(data, dict) else None if not isinstance(values, list): raise ValueError("SMARD hourly response schema changed.") for row in values: if not isinstance(row, list) or len(row) != 2: raise ValueError("SMARD hourly row schema changed.") stamp, value = row if isinstance(stamp, bool) or not isinstance(stamp, int): raise ValueError("SMARD hourly timestamp is invalid.") if start_ms <= stamp < end_ms: if stamp in observations: raise ValueError("Duplicate SMARD hourly observation in the requested month.") observations[stamp] = _finite_nonnegative(value, "SMARD grid load") urls.append(url); hashes.append(digest); times.append(retrieved) # Validate in UTC so March and October use their actual 743/745-hour lengths. expected = pd.date_range(start=start, end=end, freq="h", inclusive="left") expected_ms = [int(t.timestamp() * 1000) for t in expected] if sorted(observations) != expected_ms: raise ValueError("SMARD month has missing or unexpected hourly observations; no monthly total inferred.") return sum(observations.values()) / 1000, { "source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times, "coverage_basis": "Every expected UTC hourly MWh observation checked; DST follows Europe/Berlin", "observations": len(expected_ms), "transformation": "Sum hourly MWh / 1000 = monthly GWh", }
def _au_month(month): urls, hashes, times, values = [], [], [], [] for region in AU_REGIONS: _, meta = live_market("AU", region, month) value = _finite_nonnegative(meta.get("integrated_demand_GWh"), "AEMO integrated demand") values.append(value) urls.extend(meta["source_urls"]) hashes.extend(meta["response_sha256"]) # live_market AU performs an uncached bounded download and validates all # settlement interval ends. Record completion, not the outer request time. times.append(_now()) return sum(values), {"source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times, "regions": list(AU_REGIONS), "regional_demand_GWh": dict(zip(AU_REGIONS, values)), "coverage_basis": "All expected settlement intervals validated separately in all five NEM regions", "transformation": "Sum region TOTALDEMAND MW × interval hours / 1000; published demand proxy"}
def _fetch_month(country, month): """One synchronized, bounded public cache; no customer input is stored.""" key = (country, month) with _CACHE_LOCK: cached = _MONTH_CACHE.get(key) if cached and time.monotonic() - cached[0] < CACHE_TTL_SECONDS: _MONTH_CACHE.move_to_end(key) value, metadata = deepcopy(cached[1]) metadata["cache_hit"] = True return value, metadata try: value, metadata = {"PT": _pt_month, "DE": _de_month, "AU": _au_month}[country](month) except ValueError: raise except Exception: raise ValueError(f"{country} official feed is unavailable for {month}; archived data was not substituted.") from None metadata = {**metadata, "month": month, "retrieved_at": _now(), "cache_hit": False} _MONTH_CACHE[key] = (time.monotonic(), (value, deepcopy(metadata))) _MONTH_CACHE.move_to_end(key) while len(_MONTH_CACHE) > MAX_CACHE_MONTHS: _MONTH_CACHE.popitem(last=False) return value, metadata
def _archive(country, latest): path = ROOT / "data" / f"{country.lower()}_monthly.csv" try: raw = path.read_bytes() d = pd.read_csv(path) if not {"timestamp", "value", "unit", "coverage"} <= set(d) or not 12 <= len(d) <= 600: raise ValueError("invalid archive schema") dates = pd.to_datetime(d.timestamp, format="ISO8601", errors="raise") expected = pd.date_range(start=dates.iloc[0], periods=len(d), freq="MS") if dates.dt.tz is not None or not pd.DatetimeIndex(dates).equals(expected): raise ValueError("archive months are not ordered and consecutive") if set(d.unit) != {"GWh"} or not (pd.to_numeric(d.coverage) == 1).all(): raise ValueError("archive unit/coverage changed") values = [_finite_nonnegative(v, "Archived demand") for v in d.value] if dates.iloc[-1].strftime("%Y-%m") > latest: raise ValueError("archive contains incomplete/future months") except Exception: raise ValueError("The official archive failed validation; no forecast input returned.") from None records = [{"timestamp": t.date().isoformat(), "value": v, "unit": "GWh", "coverage": 1.0} for t, v in zip(dates, values)] return records, hashlib.sha256(raw).hexdigest()
def official_history(country, region=""): """Return archive + verified fresh tail, or raise without a stale fallback.
At least the final archived month is fetched again. Up to twelve subsequent complete months may be appended. Earlier archived months are not represented as freshly revalidated. Australian history always retains its five-region NEM scope, even when the caller requests a region for separate market context. """ _market(country, region) requested = _now() latest = latest_complete_month() records, archive_digest = _archive(country, latest) cutoff = records[-1]["timestamp"][:7] months = [t.strftime("%Y-%m") for t in pd.date_range(cutoff + "-01", latest + "-01", freq="MS")] if len(months) - 1 > MAX_BACKFILL_MONTHS: raise ValueError("Official archive is more than 12 complete months behind; rebuild the archive before live inference.") refreshed, sources = {}, [] for month in months: value, metadata = _fetch_month(country, month) refreshed[month] = {"timestamp": month + "-01", "value": value, "unit": "GWh", "coverage": 1.0} sources.append(metadata) merged = [row for row in records if row["timestamp"][:7] < cutoff] + list(refreshed.values()) urls = [url for source in sources for url in source["source_urls"]] hashes = [value for source in sources for value in source["response_sha256"]] times = [value for source in sources for value in source["source_retrieved_at"]] metadata = { "country": country, "scope": SCOPES[country], "region_used": "NEM" if country == "AU" else "PT-mainland" if country == "PT" else "DE", "requested_region": region, "requested_at": requested, "archive_cutoff": cutoff, "archive_sha256": archive_digest, "archive_prefix_refreshed": False, "latest_observation": merged[-1]["timestamp"], "latest_complete_month": latest, "verified_months": months, "refreshed_months": months, "appended_months": months[1:], "source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times, "cache_ttl_seconds": CACHE_TTL_SECONDS, "cache_hit": all(s["cache_hit"] for s in sources), "monthly_sources": sources, "record_sha256": hashlib.sha256(json.dumps(merged, sort_keys=True, allow_nan=False).encode()).hexdigest(), "limits": [ "Grid-demand target only; not a household consumption or retail-price forecast.", "Older archive observations retain their archived vintage; only listed months were rechecked.", "Publisher values can be revised. Current revised history is not a historical publication-vintage backtest.", ], } return {"status": "verified_official_history", "records": merged, "metadata": metadata}
def live_market_context(country, region="", month=None): """Return a bounded inspection of the existing official market reader.
DE's legacy context reader returns only its last monthly publication block. It is deliberately not used to construct official_history monthly totals. """ _market(country, region) month = month or latest_complete_month() check_month(month) if country == "AU" and region in {"", "NEM"}: region = "NSW1" requested = _now() try: frame, meta = live_market(country, region, month) except Exception: return {"status": "unavailable", "records": [], "metadata": {"country": country, "month": month, "requested_at": requested, "scope": SCOPES[country]}, "message": "Official market context is unavailable. No archived values substituted."} metadata = dict(meta) metadata["requested_at"] = requested metadata["rows_total"] = len(frame) metadata["preview_rows"] = min(120, len(frame)) metadata["preview_truncated"] = len(frame) > 120 metadata["complete_month"] = country != "DE" if country == "DE": # Re-read the same JSON cache entries to retain actual fetch timestamps, # rather than presenting the legacy request timestamp as retrieval time. metadata["source_retrieved_at"] = [get_json(url)[2] for url in meta["source_urls"]] metadata["retrieved_at"] = max(metadata["source_retrieved_at"]) metadata["coverage_note"] = "Last SMARD publication block only; not a complete monthly series or total." elif country == "PT": metadata["retrieved_at"] = max(metadata["source_retrieved_at"]) else: metadata["retrieved_at"] = _now() metadata["source_retrieved_at"] = [metadata["retrieved_at"]] metadata["cache_ttl_seconds"] = 0 # Existing AEMO context downloads are uncached. rows = json.loads(frame.tail(120).to_json(orient="records")) return {"status": "available", "records": rows, "metadata": metadata}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437"""On-demand public electricity news; never a source of customer tariff rates.
Only curated queries leave the server. SQLite shares cache, request leases andconservative attempt quotas among processes using the same database file. It isnot a distributed budget: replicas require a shared budget service, and /tmpstate can disappear when a Space restarts."""from contextlib import contextmanagerfrom datetime import datetime, timedelta, timezoneimport hashlibimport ipaddressimport jsonimport loggingimport osfrom pathlib import Pathimport reimport sqlite3import timefrom urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitimport uuid
import httpx
_ENDPOINT = "https://serpapi.com/search.json"_TTL = 3600_CACHE_LIMIT = 32_MAX_BYTES = 2_000_000_DEADLINE = 12_LEASE_SECONDS = 35_QUERIES = { "PT": {"q": "eletricidade (tarifas OR preços OR ERSE) Portugal", "gl": "pt", "hl": "pt-PT"}, "DE": {"q": "(Strompreise OR Stromtarife OR Stromkosten) Deutschland", "gl": "de", "hl": "de"}, "AU": {"q": '("electricity prices" OR "electricity tariffs" OR "energy rebates") Australia', "gl": "au", "hl": "en"},}_SCOPE = ( "Market context only. Headlines do not set retail tariffs, establish customer " "eligibility, or change a forecast. Verify prices and effective dates with the " "official provider or regulator.")
class _RedactApiKey(logging.Filter): """HTTPX INFO logs include request URLs, so redact before log handlers see them."""
def filter(self, record): message = record.getMessage() message = re.sub(r"(?i)(api_key=)[^&\s\"'<>]+", r"\1[redacted]", message) secret = os.environ.get("SERPAPI_API_KEY", "").strip() if secret: message = message.replace(secret, "[redacted]") record.msg, record.args = message, () return True
for _logger_name in ( "httpx", "httpcore.connection", "httpcore.http11", "httpcore.http2", "httpcore.proxy", "httpcore.http_proxy", "httpcore.socks",): _logger = logging.getLogger(_logger_name) if not any(isinstance(f, _RedactApiKey) for f in _logger.filters): _logger.addFilter(_RedactApiKey())
def _utcnow(): return datetime.now(timezone.utc)
def _iso(value): return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
def _config_int(name, default, maximum): raw = os.environ.get(name, str(default)) if not raw.isascii() or not raw.isdigit(): raise ValueError("Invalid news budget configuration.") value = int(raw) if not 0 <= value <= maximum: raise ValueError("Invalid news budget configuration.") return value
def _config(): configured_path = os.environ.get("ELECTROCHEAP_NEWS_DB_PATH") if configured_path: path = Path(configured_path) if not path.is_absolute(): raise ValueError("News database path must be absolute.") elif Path("/data").is_dir() and os.access("/data", os.W_OK | os.X_OK): path = Path("/data/electrocheap/news.sqlite3") else: path = Path("/tmp/electrocheap-news/news.sqlite3") is_tmp = path == Path("/tmp") or Path("/tmp") in path.parents in_data = Path("/data") in path.parents storage = { "kind": "sqlite", "durability": "ephemeral" if is_tmp else "operator_managed_unverified", "persistent_mount_required": not is_tmp, "location_class": "temporary" if is_tmp else "data_mount" if in_data else "configured", "budget_scope": "Processes sharing this SQLite file; not a hard cross-replica budget.", "restart_note": ( "Temporary storage can reset cache and quotas on restart or replacement." if is_tmp else "Persistence depends on the operator-provided storage mount." ), } return { "path": path, "daily_limit": _config_int("ELECTROCHEAP_NEWS_DAILY_LIMIT", 6, 10_000), "monthly_limit": _config_int("ELECTROCHEAP_NEWS_MONTHLY_LIMIT", 180, 300_000), "storage": storage, }
@contextmanagerdef _store(config): path = config["path"] path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) # Do not follow an existing database symlink or expose newly created data. flags = os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0) fd = os.open(path, flags, 0o600) try: os.fchmod(fd, 0o600) finally: os.close(fd) db = sqlite3.connect(path, timeout=3, isolation_level=None) db.row_factory = sqlite3.Row try: db.execute("PRAGMA busy_timeout=3000") db.execute("CREATE TABLE IF NOT EXISTS quota (bucket TEXT PRIMARY KEY, used INTEGER NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, fetched REAL NOT NULL, expires REAL NOT NULL, payload TEXT NOT NULL)") db.execute("CREATE TABLE IF NOT EXISTS leases (key TEXT PRIMARY KEY, token TEXT NOT NULL, expires REAL NOT NULL)") yield db finally: db.close()
def _bucket_keys(now): return "d:" + now.strftime("%Y-%m-%d"), "m:" + now.strftime("%Y-%m")
def _budget(db, config, now): day, month = _bucket_keys(now) counts = dict(db.execute("SELECT bucket, used FROM quota WHERE bucket IN (?, ?)", (day, month)).fetchall()) next_day = (now + timedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0) next_month = (now.replace(day=28) + timedelta(days=4)).replace(day=1, hour=0, minute=0, second=0, microsecond=0) return { "daily_limit": config["daily_limit"], "daily_used": counts.get(day, 0), "monthly_limit": config["monthly_limit"], "monthly_used": counts.get(month, 0), "daily_resets_at": _iso(next_day), "monthly_resets_at": _iso(next_month), "accounting": "Conservative upstream attempts, reserved before requests; cache hits are free locally.", }
def news_status(): """Return configuration and local quota metadata without making network calls.""" configured = bool(os.environ.get("SERPAPI_API_KEY", "").strip()) output = { "status": "configured" if configured else "not_configured", "configured": configured, "countries": list(_QUERIES), "cache_ttl_seconds": _TTL, "scope": _SCOPE, "budget": None, } try: config = _config() output["storage"] = config["storage"] with _store(config) as db: output["budget"] = _budget(db, config, _utcnow()) except (OSError, sqlite3.Error, ValueError): output.update(status="unavailable", message="News budget storage or configuration is unavailable.") output.setdefault("storage", {"kind": "sqlite", "durability": "unavailable"}) return output
def _validate(payload): if not isinstance(payload, dict) or set(payload) - {"country", "days", "limit"}: raise ValueError("News requests accept only country, days and limit.") country = payload.get("country", "PT") if not isinstance(country, str) or country.upper() not in _QUERIES: raise ValueError("News country must be PT, DE or AU.") days, limit = payload.get("days", 7), payload.get("limit", 10) if type(days) is not int or not 1 <= days <= 30: raise ValueError("News days must be an integer from 1 to 30.") if type(limit) is not int or not 1 <= limit <= 30: raise ValueError("News limit must be an integer from 1 to 30.") return country.upper(), days, limit
def _reserve(config, key, now): """Atomically reuse a cache entry, join a refresh, or reserve one paid attempt.""" with _store(config) as db: db.execute("BEGIN IMMEDIATE") try: row = db.execute("SELECT expires, payload FROM cache WHERE key=?", (key,)).fetchone() cached = json.loads(row["payload"]) if row else None budget = _budget(db, config, now) if row and row["expires"] > now.timestamp(): decision, token = "cached", None else: lease = db.execute("SELECT expires FROM leases WHERE key=?", (key,)).fetchone() if lease and lease["expires"] > now.timestamp(): decision, token = "refreshing", None elif budget["daily_used"] >= budget["daily_limit"] or budget["monthly_used"] >= budget["monthly_limit"]: decision, token = "quota_exhausted", None else: token = uuid.uuid4().hex for bucket in _bucket_keys(now): db.execute("INSERT INTO quota(bucket, used) VALUES(?, 1) ON CONFLICT(bucket) DO UPDATE SET used=used+1", (bucket,)) db.execute("INSERT INTO leases(key, token, expires) VALUES(?, ?, ?) ON CONFLICT(key) DO UPDATE SET token=excluded.token, expires=excluded.expires", (key, token, now.timestamp() + _LEASE_SECONDS)) db.execute("DELETE FROM leases WHERE expires < ?", (now.timestamp(),)) db.execute("DELETE FROM quota WHERE bucket LIKE 'd:%' AND bucket < ?", ("d:" + (now - timedelta(days=40)).strftime("%Y-%m-%d"),)) db.execute("DELETE FROM quota WHERE bucket LIKE 'm:%' AND bucket < ?", ("m:" + (now - timedelta(days=70)).strftime("%Y-%m"),)) budget = _budget(db, config, now) decision = "fetch" db.execute("COMMIT") return decision, token, cached, budget except Exception: db.execute("ROLLBACK") raise
def _finish(config, key, token, result=None): with _store(config) as db: db.execute("BEGIN IMMEDIATE") try: lease = db.execute("SELECT token FROM leases WHERE key=?", (key,)).fetchone() if lease and lease["token"] == token: if result is not None: fetched = datetime.fromisoformat(result["fetched_at"].replace("Z", "+00:00")).timestamp() db.execute("INSERT INTO cache(key, fetched, expires, payload) VALUES(?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET fetched=excluded.fetched, expires=excluded.expires, payload=excluded.payload", (key, fetched, fetched + _TTL, json.dumps(result, ensure_ascii=False))) db.execute("DELETE FROM cache WHERE key IN (SELECT key FROM cache ORDER BY fetched DESC, key LIMIT -1 OFFSET ?)", (_CACHE_LIMIT,)) db.execute("DELETE FROM leases WHERE key=? AND token=?", (key, token)) db.execute("COMMIT") except Exception: db.execute("ROLLBACK") raise
class _FetchError(Exception): def __init__(self, category): self.category = category super().__init__(category)
def _fetch(params): """Bounded request. Never raise/log upstream error text or credentialed URLs.""" started = time.monotonic() try: with httpx.Client(timeout=httpx.Timeout(8.0, connect=3.0), follow_redirects=False) as client: with client.stream("GET", _ENDPOINT, params=params, headers={"Accept": "application/json", "Accept-Encoding": "identity", "User-Agent": "Electrocheap/1.0"}) as response: if response.status_code != 200: category = "credentials_rejected" if response.status_code in (401, 403) else "provider_quota_or_rate_limit" if response.status_code == 429 else "provider_http_error" raise _FetchError(category) if response.headers.get("content-encoding", "identity").lower() != "identity": raise _FetchError("unexpected_response_encoding") chunks, length = [], 0 for chunk in response.iter_bytes(chunk_size=65_536): length += len(chunk) if length > _MAX_BYTES: raise _FetchError("response_too_large") if time.monotonic() - started > _DEADLINE: raise _FetchError("request_timeout") chunks.append(chunk) raw = b"".join(chunks) parsed = json.loads(raw) if not isinstance(parsed, dict): raise _FetchError("invalid_provider_response") metadata = parsed.get("search_metadata") if not isinstance(metadata, dict) or metadata.get("status") != "Success": raise _FetchError("provider_search_failed") results = parsed.get("news_results", []) if not isinstance(results, list): raise _FetchError("invalid_provider_response") # Success + empty results may legitimately include a provider error string. # It is intentionally neither displayed nor persisted. return parsed, hashlib.sha256(raw).hexdigest() except _FetchError: raise except httpx.TimeoutException: raise _FetchError("request_timeout") from None except (httpx.HTTPError, OSError, ValueError, UnicodeError): raise _FetchError("request_or_response_failed") from None
def _text(value, secret, maximum): if not isinstance(value, str): return "" value = value.replace(secret, "[redacted]") if secret else value return " ".join(value.split())[:maximum]
def _safe_url(value, secret): if not isinstance(value, str) or len(value) > 4096 or (secret and secret in value): return None try: url = urlsplit(value) host = (url.hostname or "").lower().rstrip(".") if url.scheme != "https" or not host or url.username or url.password or url.port not in (None, 443): return None if any(ord(c) < 33 for c in value) or "\\" in value: return None if "." not in host or host.endswith((".local", ".localhost", ".internal", ".invalid")): return None try: ipaddress.ip_address(host) return None except ValueError: pass if not all(re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", part) for part in host.encode("idna").decode("ascii").split(".")): return None query = [] for name, item in parse_qsl(url.query, keep_blank_values=True, max_num_fields=100): if name.lower() in {"api_key", "apikey", "access_token", "token", "key", "authorization"}: return None if not name.lower().startswith("utm_") and name.lower() not in {"gclid", "fbclid", "msclkid"}: query.append((name, item)) return urlunsplit(("https", host, url.path or "/", urlencode(query), "")) except (ValueError, UnicodeError): return None
def _article_nodes(results): # Traverse documented shapes only; never recursively crawl arbitrary metadata. for item in results[:500]: if not isinstance(item, dict): continue if isinstance(item.get("highlight"), dict): yield item["highlight"] if item.get("title") and item.get("link"): yield item stories = item.get("stories", []) if isinstance(stories, list): yield from (story for story in stories[:100] if isinstance(story, dict))
def _articles(data, secret, now, days): output, seen = [], set() cutoff = now - timedelta(days=days) for item in _article_nodes(data.get("news_results", [])): title = _text(item.get("title"), secret, 500) url = _safe_url(item.get("link"), secret) if not title or not url or url in seen: continue published, date_status = None, "unknown" stamp = item.get("iso_date") if isinstance(stamp, str) and len(stamp) <= 60: try: parsed = datetime.fromisoformat(stamp.replace("Z", "+00:00")) if parsed.tzinfo is not None: parsed = parsed.astimezone(timezone.utc) if parsed < cutoff or parsed > now + timedelta(minutes=5): continue published, date_status = _iso(parsed), "publisher_timestamp" except ValueError: pass source = item.get("source") source_name = _text(source.get("name"), secret, 160) if isinstance(source, dict) else _text(source, secret, 160) output.append({ "title": title, "url": url, "source": source_name or urlsplit(url).hostname, "published_at": published, "publication_date_status": date_status, "available_at": _iso(now), "retrieved_at": _iso(now), }) seen.add(url) if len(output) >= 120: break output.sort(key=lambda article: article["published_at"] or "", reverse=True) return output[:30]
def _base(country, days, now): return { "country": country, "days": days, "requested_at": _iso(now), "fetched_at": None, "cache_expires_at": None, "cache_hit": False, "stale": False, "articles": [], "article_count": 0, "budget": None, "provenance": { "provider": "SerpApi / Google News", "engine": "google_news", "documentation_url": "https://serpapi.com/google-news-api", "query": _QUERIES[country]["q"] + f" when:{days}d", "gl": _QUERIES[country]["gl"], "hl": _QUERIES[country]["hl"], "scope": _SCOPE, "tariff_effect": "none", "availability_note": "available_at is this application's ingestion time, not proof of earlier historical availability.", "provider_cache_note": "SerpApi may serve identical requests from its own one-hour cache.", }, }
def market_news(payload): """Fetch curated market context, sharing bounded cache and atomic local quotas.""" country, days, limit = _validate(payload) now = _utcnow() output = _base(country, days, now) secret = os.environ.get("SERPAPI_API_KEY", "").strip() if not secret: return dict(output, status="not_configured", message="Market news is not connected. Configure the server-side SerpApi secret.", storage={"kind": "sqlite", "accessed": False}) try: config = _config() output["storage"] = config["storage"] key = f"news-v1:{country}:{days}" decision, token, cached, budget = _reserve(config, key, now) output["budget"] = budget except (OSError, sqlite3.Error, ValueError): return dict(output, status="unavailable", message="News budget storage or configuration is unavailable; no search was made.", storage=output.get("storage", {"kind": "sqlite", "durability": "unavailable"})) if cached: for field in ("articles", "fetched_at", "cache_expires_at", "provenance"): output[field] = cached[field] output["cache_hit"] = True output["stale"] = decision != "cached" if decision == "cached": output.update(status="cached" if output["articles"] else "empty", message="Using dated market context from the shared cache.") elif decision in {"quota_exhausted", "refreshing"}: message = "The local news request budget is exhausted." if decision == "quota_exhausted" else "This market's news refresh is already in progress. Retry shortly." output.update(status=decision, message=message) else: result = None try: params = {"engine": "google_news", "api_key": secret, "q": output["provenance"]["query"], "gl": _QUERIES[country]["gl"], "hl": _QUERIES[country]["hl"], "output": "json"} data, response_sha = _fetch(params) fetched = _utcnow() result = _base(country, days, now) result.update(fetched_at=_iso(fetched), cache_expires_at=_iso(fetched + timedelta(seconds=_TTL)), articles=_articles(data, secret, fetched, days)) result["provenance"]["response_sha256"] = response_sha # Do not persist raw metadata, search URLs, keys, or provider error text. provider_time = data["search_metadata"].get("created_at") if isinstance(provider_time, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} UTC", provider_time): result["provenance"]["provider_search_created_at"] = provider_time for field in ("articles", "fetched_at", "cache_expires_at", "provenance"): output[field] = result[field] output.update(status="fresh" if output["articles"] else "empty", cache_hit=False, stale=False, message="Market context retrieved." if output["articles"] else "No usable articles were returned for this query window.") except _FetchError as exc: output.update(status="unavailable", message="Market news is temporarily unavailable. Bill analysis remains available.", error_category=exc.category) finally: try: _finish(config, key, token, result) except (OSError, sqlite3.Error, ValueError): output["storage"] = dict(config["storage"], write_status="unavailable") output["articles"] = output["articles"][:limit] output["article_count"] = len(output["articles"]) return output123version https://git-lfs.github.com/spec/v1oid sha256:e70d2f5681bb4e2512e8f862ea34d55498c039a137d3b89bc4ef15b01e619067size 2963922123version https://git-lfs.github.com/spec/v1oid sha256:7970983ad71bcf817a7abe7c14c40aabd012c093a817a8b8280b026611e67625size 2977968
1234583 unmodified lines89909192939495969798991001011025 unmodified lines108109110111112113114{"archive_sha256": "e70d2f5681bb4e2512e8f862ea34d55498c039a137d3b89bc4ef15b01e619067","files": {"assets/xenowattz-poster.png": "ffe946861e3c9671750b55c1e101a017137974fe933d4ddb53e16c38b826c502","assets/xenowattz_480.mp4": "dfb29c1b1ceaaa5804b273a7e38aaa4d52398581cbac703c9089dd5065d80717",83 unmodified lines"tests/test_benchmark.py": "54743f9e2b1df351fa98a9a393a51f0a53e77ee90e6e6c0e1e0260c53c281a03","tests/test_billing.py": "7386e0a911028309da2b1e039d71d13980c6b3b68ce52e7e0f2fdb38d030d856","tests/test_bulk.py": "44a3fd530fec0f05f33e5c8a813c8a4303bd60b756f37c8099f2bd126a37d184","tests/test_core.py": "b6aaae17f5d3a0cf8c24d05c327f0a9f760814963a4611c4eafd8b6a42ef778b","tests/test_scenarios.py": "a425cab65838fbb34edcbe29d870c5da971504ef10c2afd9a08810b247d6a20c","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",5 unmodified lines"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",1234583 unmodified lines89909192939495969798991001011021031041055 unmodified lines111112113114115116117118119{"archive_sha256": "7970983ad71bcf817a7abe7c14c40aabd012c093a817a8b8280b026611e67625","files": {"assets/xenowattz-poster.png": "ffe946861e3c9671750b55c1e101a017137974fe933d4ddb53e16c38b826c502","assets/xenowattz_480.mp4": "dfb29c1b1ceaaa5804b273a7e38aaa4d52398581cbac703c9089dd5065d80717",83 unmodified lines"tests/test_benchmark.py": "54743f9e2b1df351fa98a9a393a51f0a53e77ee90e6e6c0e1e0260c53c281a03","tests/test_billing.py": "7386e0a911028309da2b1e039d71d13980c6b3b68ce52e7e0f2fdb38d030d856","tests/test_bulk.py": "44a3fd530fec0f05f33e5c8a813c8a4303bd60b756f37c8099f2bd126a37d184","tests/test_core.py": "c426709d446f6df8c638bae69ce6d2cef590b1ad90fea61c45f6123cb9de0d8b","tests/test_live_analysis.py": "a5f48b961c646ea00d50e361efeacc4193a7d680937864951f1c9624d7bf4900","tests/test_live_sources.py": "365cf12d49150d707a2327106ba696dcf163768a8566d19200ce7fd54badc3bc","tests/test_news.py": "c12e76b4ace3d525e1b3330e333df5583d5095feb5748d8a0fd5bb2d9aea120b","tests/test_scenarios.py": "a425cab65838fbb34edcbe29d870c5da971504ef10c2afd9a08810b247d6a20c","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": "484ef60907bbf6f7eb6c5cbc2c9e0c5ecef6996c5be56a7ed2d83c778946c611","scripts/smoke_remote.py": "9b88019f707e363f91aeacfeb70e2cfd5b7088ad65e5ab1a855ab17d903da53c","validation/aer_plan_detail.json": "907dad24b0dd70cb9ef6ff813006ba28b44df2ca69fa020884061d0a5bc9b038","validation/aer_plan_meta.json": "5c8c67ef9f2a397a85d746c35eea9598b581e78890e1cd2904443b3b9fcf5fc7",5 unmodified lines"validation/de_benchmark_v2.json": "2b682afba1ba4e09d54955bff1350c4d96fd037e42ebb4c4ec04bf5a4392e69a","validation/de_live_meta.json": "56ac2d03ddec31cde98cd6b076c03b68a3df92767a3b84ef7bfc2356ae03fbe0","validation/hosted_sources.json": "70b27647276114f470e5edb2aed266983a6d940217fa7e1366209acbdd0ade6d","validation/http_smoke.json": "e9eaeccba59fefa98b86d8bb8527aba7735b60541824363439622537d6e71efc","validation/live_analysis_20261023.json": "abd5af1f05cb455e30d1c039c459153daf15155e49cfa22a02d8b0f1c60e02c0","validation/live_sources_20261023.json": "e4d767dc9334ef8ccc1e4ac205b56d2a9e14d47eb15b4ca3ddb5cd042c52cf37","validation/pt_benchmark.json": "a950c08a3e7c25ead474fff5a3bb1f25df3be13fa0432636cd09622f47ed16ac","validation/pt_benchmark_v2.json": "29e710307561a8089af070a4332ba25eafba14ac64209493bd41daaf5d301583","validation/pt_hosted_benchmark_v2.json": "0464dcb5c591448bd4c55647e6d75977a38486db00767b9ccaac62df52262e57",