Spaces:
Running

File size: 4,632 Bytes
5edd575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Load the saved pipeline and predict. Shared by Streamlit, the Hugging Face Space and the FastAPI app."""

import json
import os
import pathlib
import tempfile
import joblib
import requests
import numpy as np
import pandas as pd
from datetime import datetime
from src.config import MODEL_PATH, WEATHER_FEATURES, COUNTRIES
from src.features import make_features, local_to_utc

_model = None


DEFAULT_MODEL_URL = "https://huggingface.co/shahzaim/sunpulse-solar-rf/resolve/main/sunpulse_random_forest.joblib"


def _model_file() -> pathlib.Path:
    """The model file in models/ if present, otherwise a copy downloaded once from the Hugging Face Hub
    (used on Vercel, where the 80 MB file is not part of the deployment). Set SUNPULSE_MODEL_URL to change the
    source, and HF_TOKEN if the model repository is private."""
    if MODEL_PATH.exists():
        return MODEL_PATH
    cache = pathlib.Path(tempfile.gettempdir()) / "sunpulse_random_forest.joblib"
    if cache.exists():
        return cache
    url = os.environ.get("SUNPULSE_MODEL_URL", DEFAULT_MODEL_URL)
    headers = (
        {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}
        if os.environ.get("HF_TOKEN")
        else {}
    )
    part = cache.with_suffix(".part")
    try:
        with requests.get(url, headers=headers, stream=True, timeout=120) as r:
            r.raise_for_status()
            with open(part, "wb") as f:
                for chunk in r.iter_content(1 << 20):
                    f.write(chunk)
        part.replace(cache)
    except requests.RequestException:
        raise FileNotFoundError(
            "Model file not found and it could not be downloaded from the Hugging Face Hub."
        ) from None
    return cache


def load_model():
    global _model
    if _model is None:
        _model = joblib.load(_model_file())
    return _model


def load_metadata() -> dict:
    path = MODEL_PATH.with_name("model_metadata.json")
    return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}


def predict_with_band(X):
    """Return (mean, p10, p90) in MW. The band is the spread of individual trees, not a statistical CI."""
    pipe = load_model()
    pre, rf = pipe.named_steps["preprocessor"], pipe.named_steps["model"]
    Xt = pre.transform(X)
    per_tree = np.stack([t.predict(Xt) for t in rf.estimators_])
    return (
        float(per_tree.mean()),
        float(np.percentile(per_tree, 10)),
        float(np.percentile(per_tree, 90)),
    )


def predict_scenario(country: str, local_dt: datetime, **weather) -> dict:
    """Estimate generation (MW) for one scenario. weather: the six WEATHER_FEATURES. Raises ValueError if invalid."""
    X = make_features(country, local_dt, **weather)
    mean, lo, hi = predict_with_band(X)
    return {
        "mw": max(mean, 0.0),
        "low": max(lo, 0.0),
        "high": max(hi, 0.0),
        "utc": local_to_utc(country, local_dt),
    }


def radiation_curve(
    country: str, local_dt: datetime, weather: dict, values
) -> np.ndarray:
    """Predicted MW when only shortwave radiation changes (other inputs fixed)."""
    rows = [
        make_features(country, local_dt, **{**weather, "shortwave_radiation": float(v)})
        for v in values
    ]
    return np.maximum(load_model().predict(pd.concat(rows, ignore_index=True)), 0.0)


def consistency_warnings(
    local_dt: datetime, radiation: float, cloud_cover: float
) -> list:
    """Soft warnings for input combinations that look physically unlikely (they do not block the prediction)."""
    out = []
    h = local_dt.hour
    if radiation > 50 and (h >= 22 or h <= 4):
        out.append(
            "Radiation is above 0 in the middle of the night. Check the time and the radiation value."
        )
    if radiation < 5 and 10 <= h <= 14:
        out.append(
            "Radiation is almost zero around midday. This only happens in very dark, stormy weather."
        )
    if radiation > 700 and cloud_cover > 90:
        out.append(
            "Very high radiation together with almost full cloud cover is unusual."
        )
    return out


def top_features(n: int = 10) -> pd.Series:
    """Impurity-based importance of the saved forest, one-hot country columns grouped as 'country'."""
    pipe = load_model()
    names = pipe.named_steps["preprocessor"].get_feature_names_out()
    imp = pd.Series(pipe.named_steps["model"].feature_importances_, index=names)
    grouped = imp.groupby(
        lambda x: (
            "country" if x.startswith("categorical__country") else x.split("__", 1)[1]
        )
    ).sum()
    return grouped.sort_values(ascending=False).head(n)