cooler-demand 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ """cooler-demand: SDK for School Water Cooler Demand Prediction service."""
2
+
3
+ from .client import CoolerDemandClient
4
+ from .schemas import (
5
+ PredictionRequest,
6
+ PredictionResponse,
7
+ ForecastDayRequest,
8
+ ForecastDayResponse,
9
+ TemperatureTargetRequest,
10
+ TemperatureTargetResponse,
11
+ ShortageCheckRequest,
12
+ ShortageCheckResponse,
13
+ ValidateDataRequest,
14
+ ValidateDataResponse,
15
+ IntervalPrediction,
16
+ ModelInfo,
17
+ LiveWeatherRequest,
18
+ LiveWeatherResponse,
19
+ )
20
+
21
+ __version__ = "0.1.0"
22
+ __all__ = [
23
+ "CoolerDemandClient",
24
+ "PredictionRequest",
25
+ "PredictionResponse",
26
+ "ForecastDayRequest",
27
+ "ForecastDayResponse",
28
+ "TemperatureTargetRequest",
29
+ "TemperatureTargetResponse",
30
+ "ShortageCheckRequest",
31
+ "ShortageCheckResponse",
32
+ "ValidateDataRequest",
33
+ "ValidateDataResponse",
34
+ "IntervalPrediction",
35
+ "ModelInfo",
36
+ "LiveWeatherRequest",
37
+ "LiveWeatherResponse",
38
+ "__version__",
39
+ ]
@@ -0,0 +1,242 @@
1
+ """HTTP client for the Hugging Face Gradio / inference service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from typing import Any, Dict, List, Optional, Union
7
+
8
+ import httpx
9
+ from tenacity import (
10
+ retry,
11
+ retry_if_exception_type,
12
+ stop_after_attempt,
13
+ wait_exponential,
14
+ )
15
+
16
+ from .schemas import (
17
+ ForecastDayRequest,
18
+ ForecastDayResponse,
19
+ ModelInfo,
20
+ PredictionRequest,
21
+ PredictionResponse,
22
+ ShortageCheckRequest,
23
+ ShortageCheckResponse,
24
+ TemperatureTargetRequest,
25
+ TemperatureTargetResponse,
26
+ ValidateDataRequest,
27
+ ValidateDataResponse,
28
+ LiveWeatherRequest,
29
+ LiveWeatherResponse,
30
+ )
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ DEFAULT_TIMEOUT = 30.0
35
+ DEFAULT_RETRIES = 3
36
+
37
+
38
+ class CoolerDemandError(Exception):
39
+ """Base exception for SDK errors."""
40
+
41
+ def __init__(self, message: str, status_code: Optional[int] = None, detail: Any = None):
42
+ super().__init__(message)
43
+ self.status_code = status_code
44
+ self.detail = detail
45
+
46
+
47
+ class CoolerDemandClient:
48
+ """
49
+ Client for the School Water Demand Prediction Hugging Face Space.
50
+
51
+ The main application owns institute config, DB, sensors, and weather API.
52
+ This client only talks to the stateless prediction service.
53
+ """
54
+
55
+ def __init__(
56
+ self,
57
+ base_url: str,
58
+ api_token: Optional[str] = None,
59
+ timeout: float = DEFAULT_TIMEOUT,
60
+ max_retries: int = DEFAULT_RETRIES,
61
+ ):
62
+ """
63
+ Args:
64
+ base_url: Hugging Face Space URL, e.g.
65
+ https://username-school-water-demand.hf.space
66
+ or http://localhost:7860 for local Gradio.
67
+ api_token: Optional HF token if the Space is gated.
68
+ timeout: Request timeout seconds.
69
+ max_retries: Transient failure retries.
70
+ """
71
+ self.base_url = base_url.rstrip("/")
72
+ self.timeout = timeout
73
+ self.max_retries = max_retries
74
+ headers = {"Content-Type": "application/json", "Accept": "application/json"}
75
+ if api_token:
76
+ headers["Authorization"] = f"Bearer {api_token}"
77
+ self._client = httpx.Client(
78
+ base_url=self.base_url,
79
+ headers=headers,
80
+ timeout=timeout,
81
+ follow_redirects=True,
82
+ )
83
+
84
+ def close(self) -> None:
85
+ self._client.close()
86
+
87
+ def __enter__(self) -> "CoolerDemandClient":
88
+ return self
89
+
90
+ def __exit__(self, *args: Any) -> None:
91
+ self.close()
92
+
93
+ def _url(self, path: str) -> str:
94
+ # Gradio API style or custom REST endpoints exposed by the Space
95
+ if path.startswith("/"):
96
+ return path
97
+ return f"/{path}"
98
+
99
+ @retry(
100
+ retry=retry_if_exception_type((httpx.TransportError, httpx.TimeoutException)),
101
+ stop=stop_after_attempt(DEFAULT_RETRIES),
102
+ wait=wait_exponential(multiplier=0.5, min=0.5, max=8),
103
+ reraise=True,
104
+ )
105
+ def _post(self, path: str, payload: Dict[str, Any]) -> Dict[str, Any]:
106
+ url = self._url(path)
107
+ logger.debug("POST %s", url)
108
+ try:
109
+ resp = self._client.post(url, json=payload)
110
+ except httpx.TimeoutException as exc:
111
+ raise CoolerDemandError(f"Request timed out after {self.timeout}s", detail=str(exc)) from exc
112
+ except httpx.TransportError as exc:
113
+ raise CoolerDemandError(f"Transport error: {exc}") from exc
114
+
115
+ if resp.status_code >= 400:
116
+ detail = None
117
+ try:
118
+ detail = resp.json()
119
+ except Exception:
120
+ detail = resp.text
121
+ raise CoolerDemandError(
122
+ f"Service error {resp.status_code}",
123
+ status_code=resp.status_code,
124
+ detail=detail,
125
+ )
126
+ return resp.json()
127
+
128
+ def _call_gradio(self, api_name: str, data: List[Any]) -> Any:
129
+ """Call a Gradio endpoint via /call/{api_name} (Gradio 4+)."""
130
+ # First enqueue
131
+ enqueue = self._post(f"/call/{api_name}", {"data": data})
132
+ event_id = enqueue.get("event_id")
133
+ if not event_id:
134
+ # Some Spaces return result directly
135
+ return enqueue
136
+ # Poll result
137
+ with self._client.stream("GET", f"/call/{api_name}/{event_id}") as stream:
138
+ for line in stream.iter_lines():
139
+ if line.startswith("data:"):
140
+ import json
141
+ payload = json.loads(line[5:].strip())
142
+ if isinstance(payload, list) and payload:
143
+ return payload[0] if len(payload) == 1 else payload
144
+ return payload
145
+ raise CoolerDemandError("No result from Gradio event stream")
146
+
147
+ # ------------------------------------------------------------------
148
+ # Public API
149
+ # ------------------------------------------------------------------
150
+
151
+ def predict(self, request: Union[PredictionRequest, Dict[str, Any]]) -> PredictionResponse:
152
+ """Predict water demand for one or more intervals of a cooler."""
153
+ if isinstance(request, dict):
154
+ request = PredictionRequest.model_validate(request)
155
+ payload = request.model_dump(mode="json")
156
+ try:
157
+ raw = self._post("/api/predict", payload)
158
+ except CoolerDemandError:
159
+ # Fallback to Gradio named endpoint if custom REST not present
160
+ raw = self._call_gradio("predict", [payload])
161
+ return PredictionResponse.model_validate(raw)
162
+
163
+ def forecast_day(self, request: Union[ForecastDayRequest, Dict[str, Any]]) -> ForecastDayResponse:
164
+ """Forecast a full day of intervals and compute shortage risk."""
165
+ if isinstance(request, dict):
166
+ request = ForecastDayRequest.model_validate(request)
167
+ payload = request.model_dump(mode="json")
168
+ try:
169
+ raw = self._post("/api/forecast_day", payload)
170
+ except CoolerDemandError:
171
+ raw = self._call_gradio("forecast_day", [payload])
172
+ return ForecastDayResponse.model_validate(raw)
173
+
174
+ def get_temperature_target(
175
+ self, request: Union[TemperatureTargetRequest, float, Dict[str, Any]]
176
+ ) -> TemperatureTargetResponse:
177
+ """Deterministic outdoor → target water temperature mapping."""
178
+ if isinstance(request, (int, float)):
179
+ request = TemperatureTargetRequest(outdoor_temp_c=float(request))
180
+ elif isinstance(request, dict):
181
+ request = TemperatureTargetRequest.model_validate(request)
182
+ payload = request.model_dump(mode="json")
183
+ try:
184
+ raw = self._post("/api/temperature_target", payload)
185
+ except CoolerDemandError:
186
+ raw = self._call_gradio("temperature_target", [payload])
187
+ return TemperatureTargetResponse.model_validate(raw)
188
+
189
+ def check_shortage(
190
+ self, request: Union[ShortageCheckRequest, Dict[str, Any]]
191
+ ) -> ShortageCheckResponse:
192
+ """Evaluate shortage risk given capacity, level, and predicted demand."""
193
+ if isinstance(request, dict):
194
+ request = ShortageCheckRequest.model_validate(request)
195
+ payload = request.model_dump(mode="json")
196
+ try:
197
+ raw = self._post("/api/check_shortage", payload)
198
+ except CoolerDemandError:
199
+ raw = self._call_gradio("check_shortage", [payload])
200
+ return ShortageCheckResponse.model_validate(raw)
201
+
202
+ def validate_data(
203
+ self, request: Union[ValidateDataRequest, Dict[str, Any]]
204
+ ) -> ValidateDataResponse:
205
+ """Validate cooler / timetable / consumption payloads before prediction."""
206
+ if isinstance(request, dict):
207
+ request = ValidateDataRequest.model_validate(request)
208
+ payload = request.model_dump(mode="json")
209
+ try:
210
+ raw = self._post("/api/validate_data", payload)
211
+ except CoolerDemandError:
212
+ raw = self._call_gradio("validate_data", [payload])
213
+ return ValidateDataResponse.model_validate(raw)
214
+
215
+ def model_info(self) -> ModelInfo:
216
+ """Return service model version and capability flags."""
217
+ try:
218
+ raw = self._client.get(self._url("/api/model_info")).json()
219
+ except Exception:
220
+ raw = self._call_gradio("model_info", [])
221
+ return ModelInfo.model_validate(raw)
222
+
223
+ def get_live_weather(
224
+ self,
225
+ city: Optional[str] = "New Delhi",
226
+ latitude: Optional[float] = None,
227
+ longitude: Optional[float] = None,
228
+ ) -> LiveWeatherResponse:
229
+ """Detect live outdoor weather and temperature via free API."""
230
+ payload = LiveWeatherRequest(
231
+ city=city, latitude=latitude, longitude=longitude
232
+ ).model_dump(mode="json")
233
+ try:
234
+ raw = self._post("/api/live_weather", payload)
235
+ except CoolerDemandError:
236
+ try:
237
+ raw = self._call_gradio("live_weather", [payload])
238
+ except Exception:
239
+ # Direct fallback via local weather module if service endpoint is unreachable
240
+ from weather.service import fetch_live_weather
241
+ raw = fetch_live_weather(city=city, lat=latitude, lon=longitude)
242
+ return LiveWeatherResponse.model_validate(raw)
@@ -0,0 +1,231 @@
1
+ """Pydantic schemas for request/response contracts between SDK and HF service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime, timezone
6
+ from enum import Enum
7
+ from typing import Any, Dict, List, Optional
8
+
9
+ from pydantic import BaseModel, Field, field_validator, model_validator
10
+
11
+
12
+ class SlotType(str, Enum):
13
+ PERIOD = "period"
14
+ RECESS = "recess"
15
+ GAMES = "games"
16
+
17
+
18
+ class GamesIntensity(str, Enum):
19
+ NONE = "None"
20
+ LIGHT = "Light"
21
+ MODERATE = "Moderate"
22
+ HIGH = "High"
23
+
24
+
25
+ class WeatherCondition(str, Enum):
26
+ CLEAR = "Clear"
27
+ CLOUDY = "Cloudy"
28
+ RAINY = "Rainy"
29
+ HUMID = "Humid"
30
+ UNKNOWN = "Unknown"
31
+
32
+
33
+ class CoolerInfo(BaseModel):
34
+ cooler_id: str = Field(..., min_length=1, max_length=32)
35
+ location: str = "unknown"
36
+ capacity_liters: float = Field(..., gt=0)
37
+ floor: int = 0
38
+ near_games: bool = False
39
+ current_level_liters: Optional[float] = Field(None, ge=0)
40
+
41
+
42
+ class IntervalContext(BaseModel):
43
+ """One timetable interval (period / recess / games)."""
44
+
45
+ period_slot: str = Field(..., description="e.g. P1, P2, Recess, Games")
46
+ day_of_week: str
47
+ slot_type: SlotType = SlotType.PERIOD
48
+ games_intensity: GamesIntensity = GamesIntensity.NONE
49
+ duration_minutes: int = Field(40, ge=5, le=120)
50
+ subject: Optional[str] = None
51
+
52
+ @field_validator("day_of_week")
53
+ @classmethod
54
+ def normalize_day(cls, v: str) -> str:
55
+ v = v.strip().capitalize()
56
+ valid = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
57
+ if v not in valid:
58
+ raise ValueError(f"day_of_week must be one of {valid}")
59
+ return v
60
+
61
+ @model_validator(mode="after")
62
+ def infer_slot_type(self) -> "IntervalContext":
63
+ slot = self.period_slot.strip()
64
+ if slot.lower() == "recess":
65
+ self.slot_type = SlotType.RECESS
66
+ self.period_slot = "Recess"
67
+ elif slot.lower() == "games":
68
+ self.slot_type = SlotType.GAMES
69
+ self.period_slot = "Games"
70
+ else:
71
+ self.slot_type = SlotType.PERIOD
72
+ return self
73
+
74
+
75
+ class WeatherContext(BaseModel):
76
+ outdoor_temp_c: float = Field(..., ge=-20, le=55)
77
+ weather: WeatherCondition = WeatherCondition.UNKNOWN
78
+ humidity_pct: Optional[float] = Field(None, ge=0, le=100)
79
+
80
+
81
+ class HistoricalPoint(BaseModel):
82
+ date: str
83
+ period_slot: str
84
+ consumption_liters: float = Field(..., ge=0)
85
+ outdoor_temp_c: Optional[float] = None
86
+ weather: Optional[str] = None
87
+
88
+
89
+ class PredictionRequest(BaseModel):
90
+ """Single-interval or multi-interval prediction for one cooler."""
91
+
92
+ cooler: CoolerInfo
93
+ intervals: List[IntervalContext] = Field(..., min_length=1)
94
+ weather: WeatherContext
95
+ historical: Optional[List[HistoricalPoint]] = None
96
+ model_preference: str = Field("auto", description="auto | baseline | catboost")
97
+ request_id: Optional[str] = None
98
+
99
+
100
+ class IntervalPrediction(BaseModel):
101
+ period_slot: str
102
+ expected_liters: float = Field(..., ge=0)
103
+ p50_liters: Optional[float] = None
104
+ p90_liters: Optional[float] = None
105
+ conservative_liters: float = Field(..., ge=0, description="P90 or expected*1.25 fallback")
106
+ model_used: str
107
+ confidence: str = "low" # low | medium | high
108
+
109
+
110
+ class PredictionResponse(BaseModel):
111
+ request_id: Optional[str] = None
112
+ cooler_id: str
113
+ predictions: List[IntervalPrediction]
114
+ total_expected_liters: float
115
+ total_conservative_liters: float
116
+ model_version: str
117
+ fallback_used: bool = False
118
+ warnings: List[str] = Field(default_factory=list)
119
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
120
+
121
+
122
+ class ForecastDayRequest(BaseModel):
123
+ cooler: CoolerInfo
124
+ day_of_week: str
125
+ intervals: List[IntervalContext]
126
+ weather: WeatherContext
127
+ historical: Optional[List[HistoricalPoint]] = None
128
+ current_level_liters: Optional[float] = None
129
+ next_refill_after_slots: Optional[int] = Field(
130
+ None, description="Number of intervals until next manual refill opportunity"
131
+ )
132
+ model_preference: str = "auto"
133
+ request_id: Optional[str] = None
134
+
135
+
136
+ class ShortageRisk(BaseModel):
137
+ risk_level: str # none | low | medium | high | critical
138
+ projected_level_after_day: float
139
+ shortage_liters: float = 0.0
140
+ message: str
141
+
142
+
143
+ class ForecastDayResponse(BaseModel):
144
+ request_id: Optional[str] = None
145
+ cooler_id: str
146
+ day_of_week: str
147
+ predictions: List[IntervalPrediction]
148
+ total_expected_liters: float
149
+ total_conservative_liters: float
150
+ shortage: Optional[ShortageRisk] = None
151
+ model_version: str
152
+ fallback_used: bool = False
153
+ warnings: List[str] = Field(default_factory=list)
154
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
155
+
156
+
157
+ class TemperatureTargetRequest(BaseModel):
158
+ outdoor_temp_c: float = Field(..., ge=-30, le=60)
159
+ request_id: Optional[str] = None
160
+
161
+
162
+ class TemperatureTargetResponse(BaseModel):
163
+ outdoor_temp_c: float
164
+ target_water_temp_c: float
165
+ rule_applied: str
166
+ model_version: str = "temp-control-v1"
167
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
168
+
169
+
170
+ class ShortageCheckRequest(BaseModel):
171
+ cooler_id: str
172
+ capacity_liters: float = Field(..., gt=0)
173
+ current_level_liters: float = Field(..., ge=0)
174
+ expected_demand_liters: float = Field(..., ge=0)
175
+ conservative_demand_liters: float = Field(..., ge=0)
176
+ next_refill_hours: Optional[float] = None
177
+ request_id: Optional[str] = None
178
+
179
+
180
+ class ShortageCheckResponse(BaseModel):
181
+ cooler_id: str
182
+ risk_level: str
183
+ projected_level: float
184
+ shortage_liters: float
185
+ message: str
186
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
187
+
188
+
189
+ class ValidateDataRequest(BaseModel):
190
+ cooler: Optional[CoolerInfo] = None
191
+ intervals: Optional[List[IntervalContext]] = None
192
+ weather: Optional[WeatherContext] = None
193
+ historical: Optional[List[HistoricalPoint]] = None
194
+ consumption_records: Optional[List[Dict[str, Any]]] = None
195
+
196
+
197
+ class ValidateDataResponse(BaseModel):
198
+ valid: bool
199
+ errors: List[str] = Field(default_factory=list)
200
+ warnings: List[str] = Field(default_factory=list)
201
+ summary: Dict[str, Any] = Field(default_factory=dict)
202
+
203
+
204
+ class ModelInfo(BaseModel):
205
+ model_version: str
206
+ baseline_available: bool
207
+ catboost_available: bool
208
+ catboost_trained: bool
209
+ supported_slots: List[str]
210
+ temperature_rules_loaded: bool
211
+ notes: List[str] = Field(default_factory=list)
212
+
213
+
214
+ class LiveWeatherRequest(BaseModel):
215
+ city: Optional[str] = "New Delhi"
216
+ latitude: Optional[float] = None
217
+ longitude: Optional[float] = None
218
+
219
+
220
+ class LiveWeatherResponse(BaseModel):
221
+ success: bool
222
+ outdoor_temp_c: float
223
+ weather: str
224
+ humidity_pct: float
225
+ weather_code: int = 0
226
+ location_name: str
227
+ latitude: float
228
+ longitude: float
229
+ source: str
230
+ message: str
231
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
@@ -0,0 +1,369 @@
1
+ Metadata-Version: 2.4
2
+ Name: cooler-demand
3
+ Version: 0.1.0
4
+ Summary: School Water Cooler Demand Prediction SDK – communicates with Hugging Face inference service
5
+ Author: School Water Demand Team
6
+ License: MIT
7
+ Project-URL: Homepage, https://huggingface.co/spaces/yashvardhanyadav09/paanipahrapurvanumanapi
8
+ Project-URL: Repository, https://github.com/yashvardhanyadav09/paanipahrapurvanumanapi
9
+ Keywords: water,demand,prediction,school,cooler,catboost
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Requires-Python: >=3.10
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: httpx>=0.27.0
21
+ Requires-Dist: pydantic>=2.0
22
+ Requires-Dist: tenacity>=8.0
23
+ Requires-Dist: pandas>=2.0
24
+ Requires-Dist: numpy>=1.24
25
+ Provides-Extra: model
26
+ Requires-Dist: catboost>=1.2; extra == "model"
27
+ Requires-Dist: scikit-learn>=1.3; extra == "model"
28
+ Requires-Dist: openpyxl>=3.1; extra == "model"
29
+ Requires-Dist: gradio>=4.0; extra == "model"
30
+ Requires-Dist: pyyaml>=6.0; extra == "model"
31
+ Provides-Extra: dev
32
+ Requires-Dist: pytest>=7.0; extra == "dev"
33
+ Requires-Dist: pytest-cov>=4.0; extra == "dev"
34
+ Requires-Dist: httpx; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ ---
38
+ title: School Water Cooler Demand Prediction
39
+ emoji: 🚰
40
+ colorFrom: blue
41
+ colorTo: cyan
42
+ sdk: gradio
43
+ sdk_version: 4.44.0
44
+ app_file: app.py
45
+ pinned: false
46
+ ---
47
+
48
+ # School Water Demand Prediction Model & Inference Service
49
+
50
+ Production-oriented system that predicts **period-wise water consumption** for individual school water coolers, including the **Recess** interval after every fourth period (P4) and **Games** periods.
51
+
52
+ | Component | Description |
53
+ |-----------|-------------|
54
+ | **Inference service** | Gradio app deployable as a Hugging Face Space |
55
+ | **SDK** | Installable Python package `cooler-demand` (PyPI-ready) |
56
+ | **ML** | Historical-average baseline (primary) + optional CatBoost P50/P90 quantiles |
57
+ | **Temperature** | Deterministic outdoor → target water temperature mapping (not ML) |
58
+
59
+ > **Important:** The one-week simulated dataset shipped with this repository is **synthetic** and is used only for software testing and baseline demonstration. It is **not** treated as sufficient for reliable production CatBoost training. The service always prefers the robust baseline until multi-week real telemetry is available.
60
+
61
+ ---
62
+
63
+ ## Architecture
64
+
65
+ ```
66
+ ┌─────────────────────────────────────────────────────────────┐
67
+ │ Main Institute Application (your system) │
68
+ │ • Institute config, PostgreSQL, sensors, weather API │
69
+ │ • Timetable & consumption uploads, alerts, refill events │
70
+ └──────────────────────────┬──────────────────────────────────┘
71
+ │ cooler-demand SDK
72
+ │ predict() / forecast_day() /
73
+ │ get_temperature_target() /
74
+ │ check_shortage() / validate_data()
75
+ ┌──────────────────────────▼──────────────────────────────────┐
76
+ │ Hugging Face Space (Gradio) │
77
+ │ • Stateless JSON API under /api/* │
78
+ │ • Baseline (historical average + engineered defaults) │
79
+ │ • Optional CatBoost quantile models (when trained) │
80
+ │ • Deterministic temperature-control table │
81
+ └─────────────────────────────────────────────────────────────┘
82
+ ```
83
+
84
+ The model service **never** stores institute secrets, long-term history, or credentials. All institute-specific context is passed per request.
85
+
86
+ ### Feature engineering
87
+
88
+ - Day of week, period slot index
89
+ - Slot type flags: `is_recess`, `is_games`, `is_period`
90
+ - Games intensity (None / Light / Moderate / High)
91
+ - Cooler location attributes (capacity, floor, near_games)
92
+ - Outdoor temperature + weather code + temperature band
93
+ - Historical mean / std / count for the same cooler×day×slot (when provided)
94
+ - Interaction terms (`games_x_near`, `temp_x_recess`)
95
+
96
+ ### Prediction strategy
97
+
98
+ 1. **Baseline (always available)**
99
+ Hierarchical historical average:
100
+ `cooler+day+slot` → `cooler+slot` → `global slot` → engineered default (capacity × slot multiplier × mild temperature factor).
101
+ Conservative estimate = expected × 1.25.
102
+
103
+ 2. **CatBoost (optional upgrade)**
104
+ Independent Quantile regressors for P50 and P90.
105
+ Training is **refused** when fewer than 200 rows are available (configurable).
106
+ One-week synthetic data is deliberately treated as insufficient for production use.
107
+
108
+ ### Temperature control (deterministic)
109
+
110
+ Parsed from `Water_Temperature_Control_Table.xlsx`:
111
+
112
+ | Outdoor range (°C) | Target water (°C) |
113
+ |--------------------|-------------------|
114
+ | [-10, 10) | 18 |
115
+ | [10, 18) | 16 |
116
+ | [18, 25) | 14 |
117
+ | [25, 32) | 12 |
118
+ | [32, 55] | 10 |
119
+
120
+ ---
121
+
122
+
123
+ ## Institute upload formats (supported)
124
+
125
+ | File | Key columns |
126
+ |------|-------------|
127
+ | `Cooler_Water_Consumption_Record.csv` | `Day`, `Period_Number` (1–8 or Recess), `Cooler_Number` (e.g. Location01A), `Consumption_Value` |
128
+ | `School_Timetable_With_Recess.xlsx` (sheet Timetable) | `Class_section`, `day` (Mon…Sat), `period` (1–8 or Recess), `subject` (Games appears as subject) |
129
+ | `Water_Temperature_Control_Table.xlsx` (sheet Rules) | `ambient_min_c (>=)`, `ambient_max_c (<)`, `cooling_enabled`, `setpoint_*`, `target_c` (IS 1475:2024 aligned) |
130
+
131
+ Weather is supplied by the calling application (any weather API); the model service accepts `outdoor_temp_c` and a coarse `weather` label per request.
132
+
133
+
134
+ ## Repository layout
135
+
136
+ ```
137
+ school-water-demand/
138
+ ├── app.py # HF Space entrypoint
139
+ ├── requirements.txt
140
+ ├── pyproject.toml # cooler-demand package
141
+ ├── data/ # Institute demo & training data
142
+ │ ├── Cooler_Water_Consumption_Record.csv
143
+ │ ├── School_Timetable_With_Recess.xlsx
144
+ │ ├── Water_Temperature_Control_Table.xlsx
145
+ │ └── cooler_config.csv
146
+ ├── src/
147
+ │ ├── cooler_demand/ # Installable SDK
148
+ │ │ ├── client.py
149
+ │ │ └── schemas.py
150
+ │ ├── model/
151
+ │ │ ├── baseline.py
152
+ │ │ ├── catboost_model.py
153
+ │ │ ├── features.py
154
+ │ │ ├── predictor.py
155
+ │ │ └── preprocessing.py
156
+ │ ├── temp_control/
157
+ │ │ └── controller.py
158
+ │ └── app/
159
+ │ └── app.py # Gradio + /api/* routes
160
+ ├── tests/
161
+ └── scripts/
162
+ ```
163
+
164
+ ---
165
+
166
+ ## Quick start (local)
167
+
168
+ ```bash
169
+ # Clone / unpack and enter the repo
170
+ cd paanipahrapurvanumanapi
171
+
172
+ python -m venv .venv
173
+ source .venv/bin/activate # Windows: .venv\Scripts\activate
174
+ pip install -r requirements.txt
175
+ pip install -e . # installs cooler-demand SDK
176
+
177
+ # Run unit + integration tests
178
+ pytest tests/ -v
179
+
180
+ # Launch Gradio locally
181
+ python -m src.app.app
182
+ # → http://localhost:7860
183
+ ```
184
+
185
+ ### Example SDK usage (against a running Space or local Gradio)
186
+
187
+ ```python
188
+ from cooler_demand import CoolerDemandClient, PredictionRequest, CoolerInfo, IntervalContext, WeatherContext
189
+
190
+ client = CoolerDemandClient(base_url="http://localhost:7860")
191
+
192
+ req = {
193
+ "cooler": {
194
+ "cooler_id": "C04",
195
+ "capacity_liters": 250,
196
+ "near_games": True,
197
+ "current_level_liters": 160,
198
+ },
199
+ "intervals": [
200
+ {"period_slot": "P1", "day_of_week": "Tuesday"},
201
+ {"period_slot": "P2", "day_of_week": "Tuesday"},
202
+ {"period_slot": "P3", "day_of_week": "Tuesday"},
203
+ {"period_slot": "P4", "day_of_week": "Tuesday"},
204
+ {"period_slot": "Recess", "day_of_week": "Tuesday", "duration_minutes": 20},
205
+ {"period_slot": "P5", "day_of_week": "Tuesday"},
206
+ {"period_slot": "Games", "day_of_week": "Tuesday", "games_intensity": "High"},
207
+ ],
208
+ "weather": {"outdoor_temp_c": 31.0, "weather": "Humid"},
209
+ "model_preference": "auto",
210
+ }
211
+
212
+ # Single-shot prediction
213
+ resp = client.predict(req)
214
+ print(resp.total_expected_liters, resp.total_conservative_liters)
215
+
216
+ # Full-day forecast + shortage
217
+ day_resp = client.forecast_day({**req, "day_of_week": "Tuesday", "current_level_liters": 160})
218
+ print(day_resp.shortage)
219
+
220
+ # Deterministic temperature target
221
+ t = client.get_temperature_target(31.0)
222
+ print(t.target_water_temp_c) # 12.0
223
+
224
+ # Shortage check only
225
+ s = client.check_shortage({
226
+ "cooler_id": "C04",
227
+ "capacity_liters": 250,
228
+ "current_level_liters": 40,
229
+ "expected_demand_liters": 90,
230
+ "conservative_demand_liters": 115,
231
+ })
232
+ print(s.risk_level, s.message)
233
+
234
+ client.close()
235
+ ```
236
+
237
+ ---
238
+
239
+ ## Hugging Face Space deployment
240
+
241
+ 1. Create a new Space (Gradio / Python).
242
+ 2. Push this repository (or upload the zip contents).
243
+ 3. Ensure `requirements.txt` and `app.py` are at the Space root.
244
+ 4. The Space will run `app.py`, which launches the Gradio Blocks app and attaches `/api/*` routes.
245
+ 5. Point the SDK at the Space URL:
246
+
247
+ ```python
248
+ client = CoolerDemandClient(
249
+ base_url="https://<user>-school-water-demand.hf.space",
250
+ api_token="hf_..." # only if the Space is gated
251
+ )
252
+ ```
253
+
254
+ ---
255
+
256
+ ## Publishing the SDK to PyPI
257
+
258
+ ```bash
259
+ pip install build twine
260
+ python -m build
261
+ twine upload dist/*
262
+ # package name: cooler-demand
263
+ ```
264
+
265
+ Install elsewhere:
266
+
267
+ ```bash
268
+ pip install cooler-demand
269
+ ```
270
+
271
+ ---
272
+
273
+ ## Input / output schemas (summary)
274
+
275
+ ### PredictionRequest (core fields)
276
+
277
+ ```json
278
+ {
279
+ "cooler": {
280
+ "cooler_id": "C01",
281
+ "capacity_liters": 200,
282
+ "near_games": false,
283
+ "current_level_liters": 140
284
+ },
285
+ "intervals": [
286
+ {"period_slot": "Recess", "day_of_week": "Monday", "duration_minutes": 20}
287
+ ],
288
+ "weather": {"outdoor_temp_c": 28.0, "weather": "Clear"},
289
+ "model_preference": "auto"
290
+ }
291
+ ```
292
+
293
+ ### PredictionResponse (excerpt)
294
+
295
+ ```json
296
+ {
297
+ "cooler_id": "C01",
298
+ "predictions": [
299
+ {
300
+ "period_slot": "Recess",
301
+ "expected_liters": 14.2,
302
+ "p50_liters": 14.2,
303
+ "p90_liters": 17.75,
304
+ "conservative_liters": 17.75,
305
+ "model_used": "baseline:cooler_slot",
306
+ "confidence": "medium"
307
+ }
308
+ ],
309
+ "total_expected_liters": 14.2,
310
+ "total_conservative_liters": 17.75,
311
+ "model_version": "water-demand-v0.1.0-baseline",
312
+ "fallback_used": true
313
+ }
314
+ ```
315
+
316
+ ---
317
+
318
+ ## Testing
319
+
320
+ ```bash
321
+ pytest tests/ -v --tb=short
322
+ ```
323
+
324
+ Coverage includes:
325
+
326
+ - Excel/CSV ingestion and column validation
327
+ - Timetable parsing and Recess ordering
328
+ - Games intensity features
329
+ - All eight cooler configurations
330
+ - Temperature boundary and extrapolation rules
331
+ - Malformed / missing inputs and prediction fallbacks
332
+ - Quantile output shape (when CatBoost is force-trained in unit tests)
333
+ - Shortage risk levels and manual-refill-aware messaging
334
+ - Schema validation and SDK client construction
335
+ - End-to-end in-process service calls
336
+
337
+ Synthetic fixtures under `data/` and `fixtures/` are **explicitly for software testing only**.
338
+
339
+ ---
340
+
341
+ ## Limitations & future real-data retraining
342
+
343
+ 1. **Data volume** – One week of synthetic data cannot capture seasonal patterns, exam weeks, special events, or cooler-specific drift. Collect at least several weeks of real period-level telemetry before enabling CatBoost in production.
344
+ 2. **No automatic retraining** – Retrain offline, version the models, and deploy new artifacts to the Space. Update `MODEL_VERSION` accordingly.
345
+ 3. **Weather** – Built-in free Open-Meteo integration auto-detects outdoor temperature and conditions from the nearest meteorological base station grid node, with an **8-hour cache TTL**. The interactive temperature slider remains fully functional for manual adjustment and what-if simulation.
346
+ 4. **Sensor reconciliation** – Flow/level sensor fusion and manual refill event logging belong to the main application; the model only consumes the current level and predicted demand you supply.
347
+ 5. **Multi-school** – The service is deliberately institute-agnostic. Pass cooler metadata and history on every request (or maintain a thin cache in the main app).
348
+
349
+ ### Recommended retraining workflow
350
+
351
+ ```python
352
+ from model.preprocessing import load_consumption_record, load_cooler_config
353
+ from model.predictor import WaterDemandPredictor
354
+
355
+ meta = load_cooler_config("path/to/cooler_config.csv")
356
+ df = load_consumption_record("path/to/real_multiweek_consumption.xlsx")
357
+
358
+ pred = WaterDemandPredictor(model_dir="artifacts/models")
359
+ pred.load_cooler_meta(meta)
360
+ info = pred.fit_from_consumption(df, train_catboost=True) # only when rows >> 200
361
+ print(info)
362
+ # Deploy the saved .cbm files with the Space
363
+ ```
364
+
365
+ ---
366
+
367
+ ## License
368
+
369
+ MIT
@@ -0,0 +1,8 @@
1
+ cooler_demand/__init__.py,sha256=_F76fotqtV_trXosui705jlxCweVEktT6WSQLPZzePg,948
2
+ cooler_demand/client.py,sha256=_Tc6J4USlZgsMv3QxawkUpOv8mJlb-QIbMWeKY8nLhg,9184
3
+ cooler_demand/schemas.py,sha256=BW8NzNUY3ZfugMG1IJXY3FAmxY2DtfSU03uCc265SXk,7006
4
+ cooler_demand-0.1.0.dist-info/licenses/LICENSE,sha256=ZIPeTgciXirD7xSPDcWb9kBvB28BsIxVPNv08SJnn0M,1088
5
+ cooler_demand-0.1.0.dist-info/METADATA,sha256=yRN0xqhkaxlfCRUuDrRXVeqmIII4wTpsMjIjSRD0fHI,13282
6
+ cooler_demand-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ cooler_demand-0.1.0.dist-info/top_level.txt,sha256=A9TPIIM9zwbgN41hwySlJmNkpM-y_oUb9UuYG3G74I4,14
8
+ cooler_demand-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 School Water Demand contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ cooler_demand