Spaces:
Running
Running
Download bulk.py from kugguk/electrocheap: direct link, hf CLI and curl.
- Browser
- Download file 14 kB
-
https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/bulk.py
- Command line
-
hf download hf://spaces/kugguk/electrocheap/bulk.py
-
curl -L -o bulk.py https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/bulk.py
14 kB
| """One bounded CPU queue for imports, forecasts, benchmarks and swap scenarios.""" | |
| from concurrent.futures import ThreadPoolExecutor | |
| from datetime import date, datetime, timezone | |
| from io import BytesIO | |
| from pathlib import Path | |
| from threading import Lock | |
| from zipfile import ZipFile, ZIP_DEFLATED | |
| import hashlib | |
| import json | |
| import secrets | |
| import time | |
| import warnings | |
| import numpy as np | |
| import pandas as pd | |
| from statsmodels.tsa.statespace.sarimax import SARIMAX | |
| from arch import arch_model | |
| from archive_import import import_files | |
| from benchmark import run_benchmark, fitted, calendar | |
| from scenarios import switching_scenarios, hash_json, integer | |
| TTL_SECONDS = 3600 | |
| MAX_JOBS = 12 | |
| MAX_STORED_BYTES = 32 * 1024 * 1024 | |
| POOL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="electrocheap-analysis") | |
| LOCK = Lock() | |
| JOBS = {} | |
| def cleanup(): | |
| now = time.monotonic() | |
| for key in list(JOBS): | |
| if now - JOBS[key]["created"] > TTL_SECONDS: | |
| del JOBS[key] | |
| def _reserve(kind, inputs): | |
| with LOCK: | |
| cleanup() | |
| stored = sum(j.get("size", 0) for j in JOBS.values()) | |
| if len(JOBS) >= MAX_JOBS or stored >= MAX_STORED_BYTES: | |
| raise ValueError("Analysis queue/storage is full; results expire after one hour.") | |
| jid = secrets.token_urlsafe(24) | |
| JOBS[jid] = {"created":time.monotonic(),"kind":kind,"state":"queued", "inputs":inputs, | |
| "created_at":datetime.now(timezone.utc).isoformat()} | |
| return jid | |
| def _worker(jid, operation): | |
| with LOCK: | |
| if jid not in JOBS: | |
| return | |
| JOBS[jid]["state"] = "running" | |
| try: | |
| result = operation() | |
| packed = json.dumps(result, allow_nan=False).encode() | |
| if len(packed) > 8*1024*1024: | |
| raise ValueError("Result exceeds 8 MiB; reduce the batch.") | |
| with LOCK: | |
| if jid in JOBS: | |
| if sum(j.get("size",0) for j in JOBS.values())+len(packed)>MAX_STORED_BYTES: | |
| raise ValueError("Result storage is full; retry after expiry.") | |
| JOBS[jid].update(state="completed", result=result, size=len(packed)) | |
| except Exception as error: | |
| with LOCK: | |
| if jid in JOBS: | |
| JOBS[jid].update(state="failed",error=str(error)[:500] if isinstance(error,ValueError) else "Computation failed; no result claimed.") | |
| def submit_import(files): | |
| # A preview of compressed bytes is held only by the pending worker, not in the store. | |
| inputs = {"file_count":len(files),"files_sha256":[hashlib.sha256(b).hexdigest() for _,b in files]} | |
| jid = _reserve("billing_import", inputs) | |
| POOL.submit(_worker,jid,lambda:import_files(files)) | |
| return ticket(jid) | |
| def monthly_series(raw): | |
| records = raw.get("records",[]) | |
| if not isinstance(records,list) or not 12<=len(records)<=600: | |
| raise ValueError("Each live forecast needs 12–600 complete monthly observations; Grokked/SARIMA need at least 36.") | |
| d = pd.DataFrame(records) | |
| if not {"timestamp","value","unit","coverage"}<=set(d): | |
| raise ValueError("Series need timestamp,value,unit,coverage.") | |
| stamps = pd.to_datetime(d.timestamp,format="ISO8601",errors="raise") | |
| if stamps.dt.tz is not None or not (stamps==stamps.dt.to_period("M").dt.to_timestamp()).all(): | |
| raise ValueError("Use timezone-free month-start observations.") | |
| d = d.assign(timestamp=stamps).sort_values("timestamp") | |
| if not d.timestamp.reset_index(drop=True).equals(pd.Series(pd.date_range(d.timestamp.iloc[0],periods=len(d),freq="MS"))): | |
| raise ValueError("Complete consecutive months required; no interpolation.") | |
| if d.timestamp.iloc[-1]>=pd.Timestamp(date.today().replace(day=1)): | |
| raise ValueError("Current/future months are not complete actuals.") | |
| d["value"] = pd.to_numeric(d.value,errors="raise") | |
| if not np.isfinite(d.value).all() or not (pd.to_numeric(d.coverage)==1).all(): | |
| raise ValueError("Forecast actuals need finite values and coverage=1.") | |
| units = set(d.unit) | |
| if len(units)!=1 or not units <= {"kWh","GWh","EUR/kWh","AUD/kWh","EUR/MWh","AUD/MWh"}: | |
| raise ValueError("Use one explicit electricity usage or price unit per series.") | |
| if not next(iter(units)).endswith("/MWh") and (d.value<0).any(): | |
| raise ValueError("Only wholesale-price actuals may be negative.") | |
| return d.reset_index(drop=True) | |
| def bulk_forecast(payload): | |
| raw_series = payload.get("series",[]) | |
| if not isinstance(raw_series,list) or not 1<=len(raw_series)<=10: | |
| raise ValueError("Supply 1–10 series per forecast job.") | |
| steps = integer(payload.get("horizon_months",12),"horizon_months",1,36) | |
| models = payload.get("models",["seasonal_naive","grokked_sarima"]) | |
| allowed = {"seasonal_naive","sarima","grokked_sarima","sarimax_garch"} | |
| if not isinstance(models,list) or not models or len(models)>4 or not set(models)<=allowed: | |
| raise ValueError("Live models: seasonal_naive, sarima, grokked_sarima, sarimax_garch. Transformers/Astra are archived evidence only.") | |
| output=[] | |
| seen=set() | |
| for raw in raw_series: | |
| sid = str(raw.get("series_id","")) | |
| if not sid or sid in seen or len(sid)>100: | |
| raise ValueError("Use unique anonymous series_id values, at most 100 characters.") | |
| seen.add(sid) | |
| d = monthly_series(raw) | |
| y = d.value.to_numpy(dtype=float) | |
| index = pd.DatetimeIndex(d.timestamp) | |
| future = pd.date_range(index[-1]+pd.offsets.MonthBegin(),periods=steps,freq="MS") | |
| template = np.resize(y[-12:],steps) | |
| mean,std = float(y.mean()),max(float(y.std()),1e-8) | |
| estimates, failures, notes = {}, [], [] | |
| for model in models: | |
| try: | |
| variance = None | |
| if model=="seasonal_naive": | |
| point=template.copy() | |
| else: | |
| if len(d)<36: | |
| raise ValueError("At least 36 consecutive measured months required for statistical seasonal models.") | |
| with warnings.catch_warnings(record=True) as caught: | |
| warnings.simplefilter("always") | |
| x, xf = calendar(index), calendar(future) | |
| xm,xs = x.mean(axis=0),np.maximum(x.std(axis=0),1e-8) | |
| cal = model=="sarimax_garch" | |
| fit = fitted(SARIMAX((y-mean)/std, exog=(x-xm)/xs if cal else None, | |
| order=(1,1,1),seasonal_order=(1,0,1,12), | |
| enforce_stationarity=False,enforce_invertibility=False)) | |
| point=np.asarray(fit.forecast(steps,exog=(xf-xm)/xs if cal else None))*std+mean | |
| if model=="grokked_sarima": | |
| point=.8*point+.2*template | |
| if cal: | |
| vol=arch_model(np.asarray(fit.resid)[12:],mean="Zero",vol="GARCH",p=1,q=1,rescale=False).fit(disp="off",show_warning=False,options={"maxiter":300}) | |
| if vol.convergence_flag: | |
| raise ValueError("Residual GARCH did not converge.") | |
| variance=(np.asarray(vol.forecast(horizon=steps,reindex=False).residual_variance.iloc[-1])*std**2).tolist() | |
| notes.extend(sorted({type(w.message).__name__ for w in caught})) | |
| if not np.isfinite(point).all(): | |
| raise ValueError("Nonfinite forecast; no output accepted.") | |
| if not d.unit.iloc[0].endswith("/MWh"): | |
| point=np.maximum(point,0) | |
| estimates[model]={"predictions":[{"timestamp":t.date().isoformat(),"value":float(v)} for t,v in zip(future,point)], | |
| "residual_variance":variance,"unit":d.unit.iloc[0]} | |
| except Exception as error: | |
| failures.append({"model":model,"reason":str(error)[:300] if isinstance(error,ValueError) else "Fit failed; no forecast claimed."}) | |
| output.append({"series_id":sid,"origin":index[-1].date().isoformat(),"observations":len(d), | |
| "input_sha256":hash_json(raw),"models":estimates,"failures":failures,"warnings":sorted(set(notes))}) | |
| return {"status":"bulk_live_cpu_forecasts","series":output,"horizon_months":steps, | |
| "grokked_definition":"forecast_lab_pro_v2 Grokked SARIMA: 80% SARIMA(1,1,1)(1,0,1,12) + 20% last-year seasonal template. Distinct Super Grokked source unavailable.", | |
| "limits":"No model winner is inferred from these fits. Predictions are conditional extrapolations; GARCH is residual variance, not calibrated forecast intervals. Household, tariff and grid series are separate targets. Archived transformer/LLM evidence is not live inference."} | |
| def bulk_benchmark(payload): | |
| series = payload.get("series",[]) | |
| if not isinstance(series,list) or not 1<=len(series)<=3: | |
| raise ValueError("Supply 1–3 benchmark series per job.") | |
| results=[] | |
| for raw in series: | |
| kind=raw.get("kind","demand") | |
| if kind not in {"demand","price"}: | |
| raise ValueError("Benchmark kind must be demand or price.") | |
| result=run_benchmark(pd.DataFrame(raw.get("records",[])),kind) | |
| results.append({"series_id":str(raw.get("series_id","series"))[:100],**result}) | |
| return {"status":"bulk_cpu_benchmark","series":results} | |
| def submit_analysis(payload): | |
| if not isinstance(payload,dict): | |
| raise ValueError("Supply an analysis object.") | |
| kind=payload.get("kind","switching") | |
| request=dict(payload) | |
| imported=request.pop("import_job_id",None) | |
| if imported: | |
| with LOCK: | |
| cleanup() | |
| job=JOBS.get(imported) | |
| if not job or job["state"]!="completed" or job["kind"]!="billing_import": | |
| raise ValueError("Import result missing, expired or incomplete; upload again.") | |
| request.setdefault("profiles",job["result"]["profiles"]) | |
| operations={"switching":switching_scenarios,"forecast":bulk_forecast,"benchmark":bulk_benchmark} | |
| if kind not in operations: | |
| raise ValueError("Analysis kind must be switching, forecast or benchmark.") | |
| 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) | |
| def ticket(jid): | |
| return {"status":"analysis_queued","job_id":jid,"expires_in_seconds":TTL_SECONDS, | |
| "next_tool":"analysis_result","privacy":"This opaque job_id is a private bearer capability; share only with intended viewers. In-memory results expire after one hour or restart."} | |
| def analysis_result(payload): | |
| jid=str(payload.get("job_id","")) | |
| offset=integer(payload.get("offset",0),"offset",0,100000) | |
| limit=integer(payload.get("limit",20),"limit",1,100) | |
| with LOCK: | |
| cleanup() | |
| job=JOBS.get(jid) | |
| if not job: | |
| raise ValueError("Job not found or expired.") | |
| response={"job_id":jid,"state":job["state"],"kind":job["kind"],"created_at":job["created_at"], | |
| "expires_in_seconds":max(0,round(TTL_SECONDS-(time.monotonic()-job["created"])))} | |
| if job["state"]=="failed": | |
| response["error"]=job["error"] | |
| if job["state"]=="completed": | |
| result=job["result"] | |
| key="profiles" if "profiles" in result else "series" | |
| response["result"]={k:v for k,v in result.items() if k not in {key,"invoices","documents","price_history"}} | |
| response["result"][key]=result.get(key,[])[offset:offset+limit] | |
| if job["kind"]=="billing_import": | |
| response["result"]["document_counts"]={s:sum(d["status"]==s for d in result["documents"]) for s in {d["status"] for d in result["documents"]}} | |
| response["result"]["price_history"]=result["price_history"] | |
| response["total_items"]=len(result.get(key,[])) | |
| response["next_offset"]=offset+limit if offset+limit<response["total_items"] else None | |
| response["export_path"]=f"/api/analysis/{jid}/export" | |
| return response | |
| def audit_export(jid): | |
| with LOCK: | |
| cleanup() | |
| job=JOBS.get(jid) | |
| if not job or job["state"]!="completed": | |
| raise ValueError("Completed job not found or expired.") | |
| inputs,result,created=job["inputs"],job["result"],job["created_at"] | |
| root=Path(__file__).resolve().parent | |
| versions={} | |
| from importlib.metadata import version | |
| for name in ["numpy","pandas","statsmodels","arch","mcp","pypdf","fonttools"]: | |
| versions[name]=version(name) | |
| files={"normalized_inputs.json":json.dumps(inputs,indent=2,allow_nan=False).encode(), | |
| "results.json":json.dumps(result,indent=2,allow_nan=False).encode()} | |
| for name in ["archive_import.py","scenarios.py","bulk.py","benchmark.py","core.py","billing.py","requirements.txt", | |
| "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()}, | |
| "privacy":"No raw PDFs or original account/meter identifiers. Normalized personal usage results are private; never publish without explicit permission."} | |
| files["manifest.json"]=json.dumps(manifest,indent=2).encode() | |
| buffer=BytesIO() | |
| with ZipFile(buffer,"w",ZIP_DEFLATED) as archive: | |
| for name,body in files.items(): | |
| archive.writestr(name,body) | |
| return buffer.getvalue() | |