Spaces:
Running
Running
Download app.py from kugguk/electrocheap: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/app.py
- Command line
-
hf download hf://spaces/kugguk/electrocheap/app.py
-
curl -L -o app.py https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/app.py
17.2 kB
| """Electrocheap React frontend, Python REST APIs and XenoWAttz MCP server.""" | |
| from contextlib import asynccontextmanager | |
| from pathlib import Path | |
| import json | |
| import os | |
| import threading | |
| import anyio | |
| from fastapi import FastAPI, HTTPException, Request, UploadFile, File | |
| from fastapi.responses import JSONResponse, Response, FileResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from mcp.server.fastmcp import FastMCP | |
| from mcp.types import ToolAnnotations | |
| from bundle import ensure_resources | |
| ensure_resources() | |
| import pandas as pd | |
| from core import consumer_compare, ngo_compare | |
| from models import model_evidence | |
| from archive_import import MAX_COMPRESSED | |
| from file_inputs import OpenAIFile, download_files | |
| from bulk import submit_import, submit_analysis, analysis_result, audit_export | |
| from scenarios import provider_history | |
| from datasets import manifest as dataset_manifest, dataset_inspect, public_audit_archive, REGISTRY | |
| from benchmark import run_benchmark | |
| from sources import live_market, aer_plans, aer_detail, SOURCES, AU_REGIONS, AER_BRANDS, latest_complete_month | |
| from live_analysis import submit_live_analysis, runtime_status, VERSION | |
| from news import market_news as fetch_market_news | |
| from challenge import challenge_packet, challenge_score, challenge_export | |
| ROOT = Path(__file__).resolve().parent | |
| BENCH_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) | |
| def challenge_packet_tool(payload: dict) -> dict: | |
| """Download the public retrospective PT/DE/AU forecast challenge. Returns four origin-safe history prompts, 24 target IDs, frozen panel hash and response template. Use a chosen LLM/plugin/adapter externally, then challenge_score. No live Astra or paid inference is started. Fine-tuning ZIP is /api/challenge/{country}/export; training targets precede October 2022.""" | |
| return challenge_packet(payload) | |
| def challenge_score_tool(payload: dict) -> dict: | |
| """Score caller-submitted predictions against archived Grokked, Astra, Sol, TimesFM, Chronos and naive on identical targets. Supply country, panel_sha256, model {id,revision,...} and exactly 24 predictions {id,forecast}, or explicit failed status. Rejects missing/duplicate/nonfinite rows. Identity is self-reported; all rankings retrospective and descriptive, no auto-promotion.""" | |
| return challenge_score(payload) | |
| 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) | |
| 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) | |
| def consumer_tool(payload: dict) -> dict: | |
| """Compare dated supplied electricity quotes. Accepts anonymous latest-year billing_months or annual totals; fictional quotes require explicit opt-in. Estimates only.""" | |
| return consumer_compare(payload) | |
| def ngo_tool(payload: dict) -> dict: | |
| """Compare up to 100 anonymous household or NGO profiles against eligible supplied quotes. EUR and AUD totals remain separate.""" | |
| return ngo_compare(payload) | |
| def evidence_tool(payload: dict) -> dict: | |
| """Read archived PT/DE/AU grid-demand scores and exact TSF, TimesFM 2.5, Chronos-2 and Astra/Sol versions. Cached evidence, not household inference.""" | |
| return model_evidence(payload) | |
| def import_tool(files: list[OpenAIFile]) -> dict: | |
| """Use this when the user attaches compressed electricity bills: 1–10 ZIP/PDF/CSV/JSON files, ≤25 MiB combined. EDP Portugal text PDFs and normalized PT/DE/AU monthly data supported. Returns a private job_id; poll analysis_result. Water and services are excluded; review estimates. Never send base64 or arbitrary URLs.""" | |
| return submit_import(download_files(files)) | |
| def history_tool(payload: dict) -> dict: | |
| """Use this to inspect dated supplied provider tariff observations. Needs records with provider, tariff_id, country, currency, rate_per_kwh, observed_at, tax_included and source_sha256/source_url. Separate tariff/meter and VAT bases. Historical movement is not a future guarantee.""" | |
| if "import_job_id" in payload: | |
| result=analysis_result({"job_id":payload["import_job_id"]}) | |
| if result["state"]!="completed" or result["kind"]!="billing_import": | |
| raise ValueError("Poll the completed billing import first.") | |
| payload={"records":result["result"]["price_history"]} | |
| return provider_history(payload) | |
| def analysis_tool(payload: dict) -> dict: | |
| """Use this for bulk CPU analysis. kind=forecast: 1–10 named series with timestamp,value,unit,coverage=1, models seasonal_naive/sarima/grokked_sarima/sarimax_garch, horizon 1–36; statistical models need 36 complete months. kind=benchmark: 1–3 grid/wholesale series, ≥72 complete months. kind=switching: profiles or import_job_id, complete supplied offers, horizons [3,12,36], price_scenarios, contract terms; accept_profile_estimates must be explicit. Returns job_id; poll analysis_result. Transformers/Astra are archives, not live models. No supplier switching.""" | |
| return submit_analysis(payload) | |
| def result_tool(payload: dict) -> dict: | |
| """Use this to poll a private import/analysis job_id and page results (offset, limit 1–100). queued/running means wait before polling again; completed returns auditable forecasts/plans or normalized profiles. Results expire in one hour/restart. Never claim job success before completed or turn failed forecasts into estimates.""" | |
| result=analysis_result(payload) | |
| if "export_path" in result: | |
| result["export_url"]="https://kugguk-electrocheap.hf.space"+result["export_path"] | |
| return result | |
| def dataset_tool(payload: dict) -> dict: | |
| """Use this for public audit datasets: list with {}, or page dataset_id with offset and limit ≤1000. Returns source provenance, exact checksums, units and downloadable official grid snapshots/test predictions. Personal bills never enter this registry.""" | |
| result=dataset_inspect(payload) | |
| result["audit_download_url"]="https://kugguk-electrocheap.hf.space/api/datasets/audit.zip" | |
| return result | |
| mcp_app = mcp.streamable_http_app() | |
| async def lifespan(app): | |
| async with mcp.session_manager.run(): yield | |
| api = FastAPI(title="XenoWAttz × Bhor Bohr · Electrocheap", version=VERSION, lifespan=lifespan) | |
| async def body_limit(request: Request, call_next): | |
| if request.method == "POST": | |
| maximum=MAX_COMPRESSED+1_000_000 if request.url.path=="/api/billing_import" else 2_000_000 | |
| if int(request.headers.get("content-length","0"))>maximum: | |
| return JSONResponse({"detail":"Request size limit exceeded."},status_code=413) | |
| body = await request.body() | |
| if len(body) > maximum: | |
| return JSONResponse({"detail":"Request size limit exceeded."}, status_code=413) | |
| 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 | |
| async def invalid(request, exc): return JSONResponse({"detail":str(exc)}, status_code=422) | |
| 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.get("/health")(health) | |
| api.post("/api/live_analysis")(live_analysis_tool) | |
| api.post("/api/market_news")(market_news_tool) | |
| api.post("/api/challenge_packet")(challenge_packet_tool) | |
| api.post("/api/challenge_score")(challenge_score_tool) | |
| def export_challenge(country: str): | |
| return Response(challenge_export(country), media_type="application/zip", | |
| headers={"Content-Disposition":f'attachment; filename=electrocheap-{country}-challenge.zip'}) | |
| def connection_status(): | |
| """Configuration/readiness only; this does not probe external providers.""" | |
| return {"version": VERSION, "status": "configuration_only", | |
| "rest": {"status": "ready", "docs": "/docs"}, | |
| "mcp": {"status": "registered", "endpoint": "https://kugguk-electrocheap.hf.space/mcp-server/mcp", | |
| "tools": ["live_analysis", "market_news", "consumer_compare", "ngo_compare", "model_evidence", | |
| "billing_import", "provider_history", "analysis_submit", "analysis_result", "dataset_inspect", | |
| "challenge_packet", "challenge_score"]}, | |
| "news": runtime_status()["news"], | |
| "live_hosted_llm": {"status": "not_configured", "paid_inference": False}, | |
| "archived_comparators": {"status": "available", "fresh_inference": False}, | |
| "official_feeds": {"status": "on_demand", "countries": ["PT", "DE", "AU"], | |
| "note": "Provider reachability is checked on request; configuration is not a live health check."}, | |
| "plugin_note": "Point the LLM connector at this Space's MCP URL. A separate older Worker connection does not automatically gain these tools."} | |
| def bootstrap(): | |
| histories = {} | |
| for c in ["PT","DE","AU"]: | |
| d = pd.read_csv(ROOT / f"data/{c.lower()}_monthly.csv") | |
| histories[c] = json.loads(d.to_json(orient="records")) | |
| quotes = pd.read_csv(ROOT / "data/example_quotes.csv", keep_default_na=False) | |
| return {"histories":histories,"example_quotes":quotes.to_dict("records"),"example_bills":pd.read_csv(ROOT / "data/example_billing_months.csv").to_dict("records"), "sources":SOURCES,"au_regions":AU_REGIONS,"aer_brands":AER_BRANDS,"latest_month":latest_complete_month()} | |
| api.post("/api/consumer_compare")(consumer_tool) | |
| api.post("/api/ngo_compare")(ngo_tool) | |
| api.post("/api/model_evidence")(evidence_tool) | |
| api.post("/api/provider_history")(history_tool) | |
| api.post("/api/analysis_submit")(analysis_tool) | |
| api.post("/api/analysis_result")(result_tool) | |
| api.post("/api/dataset_inspect")(dataset_tool) | |
| async def upload_bills(files: list[UploadFile] = File(...)): | |
| if not 1<=len(files)<=10: | |
| raise ValueError("Select 1–10 files.") | |
| inputs=[];size=0 | |
| try: | |
| for file in files: | |
| content=await file.read(MAX_COMPRESSED+1) | |
| size+=len(content) | |
| if size>MAX_COMPRESSED: | |
| raise ValueError("Combined archive/file limit is 25 MiB.") | |
| inputs.append((file.filename or "attachment.zip",content)) | |
| return submit_import(inputs) | |
| finally: | |
| for file in files: | |
| await file.close() | |
| def export_analysis(job_id: str): | |
| return Response(audit_export(job_id),media_type="application/zip",headers={"Content-Disposition":"attachment; filename=electrocheap-private-audit.zip","Cache-Control":"no-store"}) | |
| def public_datasets(): | |
| return dataset_manifest() | |
| def public_dataset_audit(): | |
| return Response(public_audit_archive(),media_type="application/zip",headers={"Content-Disposition":"attachment; filename=electrocheap-public-benchmark-audit.zip"}) | |
| def public_dataset_download(dataset_id: str): | |
| if dataset_id not in REGISTRY or not (ROOT/REGISTRY[dataset_id][0]).is_file(): | |
| raise HTTPException(404,"Unknown public dataset.") | |
| path=ROOT/REGISTRY[dataset_id][0] | |
| return FileResponse(path,media_type="text/csv",filename=dataset_id+".csv") | |
| def benchmark(payload: dict): | |
| country = payload.get("country","PT") | |
| kind = payload.get("kind","demand") | |
| if country not in {"PT","DE","AU"} or kind not in {"demand","price"}: | |
| raise ValueError("Choose PT, DE or AU and demand or price.") | |
| records = payload.get("records") | |
| if records is None: | |
| if kind == "price": raise ValueError("Complete wholesale price history is not bundled. Upload at least 72 complete monthly records.") | |
| d = pd.read_csv(ROOT / f"data/{country.lower()}_monthly.csv") | |
| else: | |
| if not isinstance(records,list) or len(records)>600: raise ValueError("Supply at most 600 monthly records for one provider or grid.") | |
| d = pd.DataFrame(records) | |
| provider = str(payload.get("provider","")).strip() | |
| if provider: | |
| if records is None or "provider" not in d: raise ValueError("Provider demand requires an uploaded dataset with a provider column.") | |
| d = d[d.provider==provider] | |
| elif "provider" in d and d.provider.nunique()>1: raise ValueError("Choose one provider before benchmarking.") | |
| if kind=="price" and ("unit" not in d or set(d.unit) != ({"AUD/MWh"} if country=="AU" else {"EUR/MWh"})): raise ValueError("Price unit must match market currency.") | |
| if not BENCH_LOCK.acquire(blocking=False): raise HTTPException(429,"Benchmark worker is busy; retry shortly.") | |
| try: result = run_benchmark(d,kind) | |
| finally: BENCH_LOCK.release() | |
| result["country"] = country | |
| result["series_scope"] = "User-supplied provider: " + provider if provider else "Uploaded series" if records is not None else "Official grid snapshot" | |
| return result | |
| def market(payload: dict): | |
| try: | |
| d,meta = live_market(payload.get("country","PT"),payload.get("region","NSW1"),payload.get("month",latest_complete_month())) | |
| return {"records":json.loads(d.to_json(orient="records")),"metadata":meta} | |
| except Exception as exc: raise HTTPException(502,f"Official feed unavailable: {str(exc)[:250]}") from None | |
| def plans(payload: dict): | |
| try: | |
| d,meta = aer_plans(payload.get("brand","agl"),str(payload.get("postcode",""))) | |
| return {"records":json.loads(d.to_json(orient="records")),"metadata":meta} | |
| except Exception as exc: raise HTTPException(502,f"AER feed unavailable: {str(exc)[:250]}") from None | |
| def plan_detail(payload: dict): | |
| try: return aer_detail(payload.get("brand","agl"),str(payload.get("plan_id",""))) | |
| except Exception as exc: raise HTTPException(502,f"AER detail unavailable: {str(exc)[:250]}") from None | |
| api.mount("/mcp-server",mcp_app) | |
| api.mount("/brand",StaticFiles(directory=ROOT / "assets")) | |
| api.mount("/downloads",StaticFiles(directory=ROOT / "data")) | |
| if (ROOT / "dist").exists(): api.mount("/",StaticFiles(directory=ROOT / "dist",html=True)) | |
| if __name__=="__main__": | |
| import uvicorn | |
| uvicorn.run(api,host="0.0.0.0",port=int(os.environ.get("PORT","7860")),access_log=False) | |