Spaces:
Running
Running
update electricity.py
Browse files- electricity_prices.py +17 -118
electricity_prices.py
CHANGED
|
@@ -1,129 +1,28 @@
|
|
| 1 |
# electricity_prices.py
|
|
|
|
|
|
|
| 2 |
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
from typing import Dict, Optional
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
# Private dataset repo on Hugging Face containing the CSV files
|
| 15 |
-
HF_DATASET_REPO = "sithuWiki/electricity"
|
| 16 |
-
HF_DATASET_TOKEN_ENV = "HF_DATASET_TOKEN" # set this in your Space secrets
|
| 17 |
-
|
| 18 |
-
# Fallback / base rates used when a date is outside the CSV range
|
| 19 |
-
BASE_ELECTRICITY_RATES: Dict[str, float] = {
|
| 20 |
-
"texas": 0.1549,
|
| 21 |
"china": 0.08,
|
| 22 |
"ethiopia": 0.01,
|
| 23 |
}
|
| 24 |
|
| 25 |
-
|
| 26 |
-
REGION_FILES: Dict[str, str] = {
|
| 27 |
-
"texas": "texas_residential_daily_df.csv",
|
| 28 |
-
"china": "china_electricity_prices_daily.csv",
|
| 29 |
-
"ethiopia": "ethiopia_electricity_prices_daily.csv",
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
# In-memory cache: region -> pandas.Series indexed by python date with float prices
|
| 33 |
-
_ELECTRICITY_SERIES: Dict[str, Optional[pd.Series]] = {}
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
def _get_token() -> str:
|
| 37 |
-
token = os.environ.get(HF_DATASET_TOKEN_ENV)
|
| 38 |
-
if not token:
|
| 39 |
-
raise RuntimeError(
|
| 40 |
-
f"Environment variable {HF_DATASET_TOKEN_ENV} is not set. "
|
| 41 |
-
"Add a read token for the private dataset to your Space secrets."
|
| 42 |
-
)
|
| 43 |
-
return token
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def _load_region_series(region: str, filename: str) -> Optional[pd.Series]:
|
| 47 |
-
"""
|
| 48 |
-
Load a single region's CSV from the private HF dataset as a Series.
|
| 49 |
-
|
| 50 |
-
Expected columns in CSV:
|
| 51 |
-
- 'date' (any format parsable by pandas.to_datetime, e.g. '10/1/15')
|
| 52 |
-
- 'price' (electricity price per kWh)
|
| 53 |
-
"""
|
| 54 |
-
try:
|
| 55 |
-
token = _get_token()
|
| 56 |
-
file_path = hf_hub_download(
|
| 57 |
-
repo_id=HF_DATASET_REPO,
|
| 58 |
-
filename=filename,
|
| 59 |
-
repo_type="dataset",
|
| 60 |
-
token=token,
|
| 61 |
-
)
|
| 62 |
-
df = pd.read_csv(file_path)
|
| 63 |
-
|
| 64 |
-
if "date" not in df.columns or "price" not in df.columns:
|
| 65 |
-
raise ValueError(f"{filename} must contain 'date' and 'price' columns.")
|
| 66 |
-
|
| 67 |
-
# Normalize date to python date objects
|
| 68 |
-
df["date"] = pd.to_datetime(df["date"]).dt.date
|
| 69 |
-
df = df[["date", "price"]].copy()
|
| 70 |
-
df = df.sort_values("date")
|
| 71 |
-
series = df.set_index("date")["price"].astype(float)
|
| 72 |
-
return series
|
| 73 |
-
except Exception as e:
|
| 74 |
-
print(f"⚠️ Could not load electricity data for {region} from {filename}: {e}")
|
| 75 |
-
return None
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# Load all regions at import time (one-time cost)
|
| 79 |
-
for _region, _fname in REGION_FILES.items():
|
| 80 |
-
_ELECTRICITY_SERIES[_region] = _load_region_series(_region, _fname)
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
def get_electricity_rate(region: str, d) -> float:
|
| 84 |
"""
|
| 85 |
-
|
|
|
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
- If d is outside the CSV range or data is missing, we fall back to
|
| 90 |
-
BASE_ELECTRICITY_RATES[region].
|
| 91 |
"""
|
| 92 |
-
|
| 93 |
-
raise ValueError(
|
| 94 |
-
f"Unknown region '{region}'. Expected one of {list(BASE_ELECTRICITY_RATES.keys())}"
|
| 95 |
-
)
|
| 96 |
-
|
| 97 |
-
# Normalise input date
|
| 98 |
-
if isinstance(d, pd.Timestamp):
|
| 99 |
-
d = d.date()
|
| 100 |
-
elif isinstance(d, str):
|
| 101 |
-
d = pd.to_datetime(d).date()
|
| 102 |
-
elif isinstance(d, Date):
|
| 103 |
-
pass # already ok
|
| 104 |
-
else:
|
| 105 |
-
raise TypeError(
|
| 106 |
-
f"Unsupported date type {type(d)}; expected datetime.date, pandas.Timestamp, or str"
|
| 107 |
-
)
|
| 108 |
-
|
| 109 |
-
base_rate = BASE_ELECTRICITY_RATES[region]
|
| 110 |
-
series = _ELECTRICITY_SERIES.get(region)
|
| 111 |
-
|
| 112 |
-
if series is None or series.empty:
|
| 113 |
-
return base_rate
|
| 114 |
-
|
| 115 |
-
idx = series.index
|
| 116 |
-
|
| 117 |
-
# Outside known range → use base constant rate
|
| 118 |
-
if d < idx[0] or d > idx[-1]:
|
| 119 |
-
return base_rate
|
| 120 |
-
|
| 121 |
-
# Exact match
|
| 122 |
-
if d in series.index:
|
| 123 |
-
return float(series.loc[d])
|
| 124 |
-
|
| 125 |
-
# Otherwise, use the last available price before this date
|
| 126 |
-
prev = series.loc[:d]
|
| 127 |
-
if prev.empty:
|
| 128 |
-
return base_rate
|
| 129 |
-
return float(prev.iloc[-1])
|
|
|
|
| 1 |
# electricity_prices.py
|
| 2 |
+
"""
|
| 3 |
+
Simplified electricity price module for Hugging Face demo.
|
| 4 |
|
| 5 |
+
We don't load CSVs or use HF_DATASET_TOKEN anymore.
|
| 6 |
+
The real-time app takes electricity_rate directly from the user.
|
|
|
|
| 7 |
|
| 8 |
+
This file only exists:
|
| 9 |
+
- to provide a simple default ELECTRICITY_RATES dict (if needed)
|
| 10 |
+
- to keep compatibility with older imports (get_electricity_rate)
|
| 11 |
+
"""
|
| 12 |
|
| 13 |
+
# Simple default average rates for reference / fallback
|
| 14 |
+
ELECTRICITY_RATES = {
|
| 15 |
+
"texas": 0.15, # average residential USD/kWh (example)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"china": 0.08,
|
| 17 |
"ethiopia": 0.01,
|
| 18 |
}
|
| 19 |
|
| 20 |
+
def get_electricity_rate(region: str, day=None) -> float:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
+
For the real-time demo, we don't actually use this in feature construction
|
| 23 |
+
(we rely on user input). But some legacy code may still call it.
|
| 24 |
|
| 25 |
+
We simply return a region-average from ELECTRICITY_RATES,
|
| 26 |
+
without reading any CSV or using HF_DATASET_TOKEN.
|
|
|
|
|
|
|
| 27 |
"""
|
| 28 |
+
return ELECTRICITY_RATES.get(region, 0.10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|