Spaces:
Running

File size: 14,164 Bytes
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afb6251
684a9cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
"""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, timezone
import json

from bulk import bulk_forecast, monthly_series, submit_operation
from core import MARKETS, boolean, consumer_compare, ngo_compare
from live_sources import official_history, live_market_context
from news import market_news, news_status
from scenarios import hash_json, integer
from sources import AU_REGIONS, latest_complete_month

VERSION = "0.5.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))