Spaces:
Sleeping
Sleeping
zerogpu compat
Browse files
app.py
CHANGED
|
@@ -1,11 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
import hashlib
|
| 4 |
-
|
| 5 |
-
# Train on CPU at startup; ZeroGPU is allocated only inside @spaces.GPU calls.
|
| 6 |
-
os.environ.setdefault("OMP_NUM_THREADS", "2")
|
| 7 |
-
os.environ.setdefault("MKL_NUM_THREADS", "2")
|
| 8 |
-
|
| 9 |
import requests
|
| 10 |
import numpy as np
|
| 11 |
import pandas as pd
|
|
@@ -21,30 +16,6 @@ import torchvision
|
|
| 21 |
import gradio as gr
|
| 22 |
import spaces
|
| 23 |
|
| 24 |
-
|
| 25 |
-
# This app intentionally runs entirely on CPU.
|
| 26 |
-
# It does not request or initialize a ZeroGPU CUDA device.
|
| 27 |
-
DEV = torch.device("cpu")
|
| 28 |
-
torch.set_num_threads(min(2, os.cpu_count() or 1))
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
class CPUAdam(torch.optim.Adam):
|
| 32 |
-
"""
|
| 33 |
-
Adam for CPU-side startup training in a ZeroGPU Space.
|
| 34 |
-
|
| 35 |
-
Some PyTorch/ZeroGPU combinations call torch.accelerator.current_stream()
|
| 36 |
-
from Adam's graph-capture health check, even when every parameter is on CPU.
|
| 37 |
-
That can incorrectly trigger CUDA initialization. Since this app is strictly
|
| 38 |
-
CPU-only, CUDA graph capture cannot apply, so skip that CUDA-specific check.
|
| 39 |
-
"""
|
| 40 |
-
def _accelerator_graph_capture_health_check(self):
|
| 41 |
-
return
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
def make_adam(params, lr):
|
| 45 |
-
return CPUAdam(params, lr=lr, foreach=False, fused=False, capturable=False)
|
| 46 |
-
|
| 47 |
-
|
| 48 |
# 1. Personal settings
|
| 49 |
ROLL = "2415800016"
|
| 50 |
h = int(hashlib.sha256(ROLL.encode()).hexdigest(), 16)
|
|
@@ -52,308 +23,209 @@ SEED = h % 100000
|
|
| 52 |
LATENT = [3, 4, 5, 6][(h >> 4) & 3]
|
| 53 |
|
| 54 |
CITIES = [
|
| 55 |
-
("Chennai", 13.0827, 80.2707),
|
| 56 |
-
("
|
| 57 |
-
("
|
| 58 |
-
("
|
| 59 |
-
("
|
| 60 |
-
("Hyderabad", 17.3850, 78.4867),
|
| 61 |
-
("Kochi", 9.9312, 76.2673),
|
| 62 |
-
("Bhubaneswar", 20.2961, 85.8245),
|
| 63 |
-
("Visakhapatnam", 17.6868, 83.2185),
|
| 64 |
-
("Ahmedabad", 23.0225, 72.5714),
|
| 65 |
-
("Jaipur", 26.9124, 75.7873),
|
| 66 |
-
("Guwahati", 26.1445, 91.7362),
|
| 67 |
-
("Lucknow", 26.8467, 80.9462),
|
| 68 |
-
("Pune", 18.5204, 73.8567),
|
| 69 |
-
("Madurai", 9.9252, 78.1198),
|
| 70 |
("Coimbatore", 11.0168, 76.9558),
|
| 71 |
]
|
| 72 |
CITY, LAT, LON = CITIES[(h >> 24) % len(CITIES)]
|
| 73 |
WINDOW = [5, 7, 10][(h >> 30) % 3]
|
| 74 |
|
| 75 |
-
|
| 76 |
-
# 2. Denoising Autoencoder
|
| 77 |
class AE(nn.Module):
|
| 78 |
def __init__(self, z=LATENT):
|
| 79 |
super().__init__()
|
| 80 |
self.enc = nn.Sequential(
|
| 81 |
-
nn.Flatten(),
|
| 82 |
-
nn.Linear(
|
| 83 |
-
nn.ReLU(),
|
| 84 |
-
nn.Linear(256, 64),
|
| 85 |
-
nn.ReLU(),
|
| 86 |
-
nn.Linear(64, z),
|
| 87 |
)
|
| 88 |
self.dec = nn.Sequential(
|
| 89 |
-
nn.Linear(z, 64),
|
| 90 |
-
nn.ReLU(),
|
| 91 |
-
nn.Linear(64, 256),
|
| 92 |
-
nn.ReLU(),
|
| 93 |
-
nn.Linear(256, 784),
|
| 94 |
-
nn.Sigmoid(),
|
| 95 |
)
|
| 96 |
|
| 97 |
def forward(self, x):
|
| 98 |
z = self.enc(x)
|
| 99 |
return self.dec(z).view(-1, 1, 28, 28), z
|
| 100 |
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
|
|
|
|
|
|
|
| 107 |
if os.path.exists(checkpoint):
|
| 108 |
-
|
| 109 |
-
state = torch.load(checkpoint, map_location=DEV, weights_only=True)
|
| 110 |
-
except TypeError:
|
| 111 |
-
state = torch.load(checkpoint, map_location=DEV)
|
| 112 |
model.load_state_dict(state)
|
| 113 |
else:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
)
|
| 117 |
-
|
| 118 |
-
optimizer = make_adam(model.parameters(), 1e-3)
|
| 119 |
-
|
| 120 |
model.train()
|
| 121 |
for _ in range(3):
|
| 122 |
for start in range(0, len(x_train), 256):
|
| 123 |
x = x_train[start:start + 256]
|
| 124 |
noisy = (x + 0.5 * torch.randn_like(x)).clamp(0, 1)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
optimizer.zero_grad(set_to_none=True)
|
| 129 |
loss.backward()
|
| 130 |
-
|
| 131 |
-
|
| 132 |
torch.save(model.state_dict(), checkpoint)
|
| 133 |
|
| 134 |
model.eval()
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
dae = load_or_train_denoiser()
|
| 139 |
-
|
| 140 |
-
test_ds = torchvision.datasets.MNIST("data", train=False, download=True)
|
| 141 |
-
Xte = (test_ds.data.float() / 255.0).unsqueeze(1)
|
| 142 |
-
|
| 143 |
|
| 144 |
def to28(img):
|
| 145 |
arr = np.asarray(
|
| 146 |
-
Image.fromarray(np.asarray(img).astype(np.uint8))
|
| 147 |
-
.convert("L")
|
| 148 |
-
.resize((28, 28)),
|
| 149 |
dtype=np.float32,
|
| 150 |
) / 255.0
|
| 151 |
-
|
| 152 |
if arr.mean() > 0.5:
|
| 153 |
arr = 1.0 - arr
|
| 154 |
-
|
| 155 |
return torch.from_numpy(arr.copy())[None, None]
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
arr = t[0, 0].detach().clamp(0, 1).cpu().numpy()
|
| 160 |
return (arr * 255).astype(np.uint8).repeat(8, 0).repeat(8, 1)
|
| 161 |
|
| 162 |
-
|
| 163 |
@spaces.GPU
|
| 164 |
def denoise(img, idx, sigma):
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
)).clamp(0, 1)
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
reconstructed = reconstructed.cpu()
|
| 176 |
-
finally:
|
| 177 |
-
dae.to("cpu")
|
| 178 |
-
|
| 179 |
-
return big(x), big(noisy), big(reconstructed)
|
| 180 |
-
|
| 181 |
-
# 3. Weather anomaly model
|
| 182 |
VARS = [
|
| 183 |
-
"temperature_2m_max",
|
| 184 |
-
"
|
| 185 |
-
"precipitation_sum",
|
| 186 |
-
"wind_speed_10m_max",
|
| 187 |
-
"wind_gusts_10m_max",
|
| 188 |
]
|
| 189 |
ATTRIB = "Weather data by Open-Meteo.com (CC BY 4.0)"
|
| 190 |
|
| 191 |
-
|
| 192 |
def open_meteo(url, **params):
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
payload =
|
| 196 |
-
|
| 197 |
-
if "daily" not in payload:
|
| 198 |
-
raise ValueError("Open-Meteo response did not contain daily weather data.")
|
| 199 |
-
|
| 200 |
frame = pd.DataFrame(payload["daily"])
|
| 201 |
frame["time"] = pd.to_datetime(frame["time"])
|
| 202 |
-
missing = [col for col in VARS if col not in frame.columns]
|
| 203 |
-
if missing:
|
| 204 |
-
raise ValueError(f"Weather response is missing: {', '.join(missing)}")
|
| 205 |
-
|
| 206 |
return frame.set_index("time")[VARS].ffill().bfill(), payload.get("daily_units", {})
|
| 207 |
|
| 208 |
-
|
| 209 |
def transform(frame):
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
)
|
| 214 |
-
return result
|
| 215 |
-
|
| 216 |
|
| 217 |
history, _ = open_meteo(
|
| 218 |
"https://archive-api.open-meteo.com/v1/archive",
|
| 219 |
-
latitude=LAT,
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
end_date="2024-12-31",
|
| 223 |
-
daily=",".join(VARS),
|
| 224 |
-
timezone="Asia/Kolkata",
|
| 225 |
)
|
| 226 |
-
|
| 227 |
T = transform(history)
|
| 228 |
-
|
| 229 |
-
monthly_mean = T[
|
| 230 |
-
monthly_std = T[
|
| 231 |
-
|
| 232 |
|
| 233 |
def standardize(frame):
|
| 234 |
months = frame.index.month
|
| 235 |
-
return (
|
| 236 |
-
frame - monthly_mean.loc[months].values
|
| 237 |
-
) / monthly_std.loc[months].values
|
| 238 |
-
|
| 239 |
|
| 240 |
def make_windows(frame, width=WINDOW):
|
| 241 |
values = frame.values.astype(np.float32)
|
| 242 |
count = len(values) - width + 1
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
windows = np.stack([
|
| 247 |
-
values[i:i + width].ravel()
|
| 248 |
-
for i in range(count)
|
| 249 |
-
])
|
| 250 |
-
return windows, frame.index[:count]
|
| 251 |
-
|
| 252 |
|
| 253 |
Xw, starts = make_windows(standardize(T))
|
| 254 |
-
Xw_t = torch.from_numpy(Xw.copy()).to(DEV)
|
| 255 |
-
train_mask = torch.from_numpy(np.asarray(starts.year <= 2014, dtype=np.bool_))
|
| 256 |
-
train_w = Xw_t[train_mask]
|
| 257 |
D = Xw.shape[1]
|
| 258 |
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
nn.Linear(D, 32),
|
| 262 |
-
nn.ReLU(),
|
| 263 |
-
nn.Linear(32, 6),
|
| 264 |
-
nn.Linear(6, 32),
|
| 265 |
-
nn.ReLU(),
|
| 266 |
-
nn.Linear(32, D),
|
| 267 |
-
).to(DEV)
|
| 268 |
-
|
| 269 |
-
weather_optimizer = make_adam(wae.parameters(), 1e-3)
|
| 270 |
-
wae.train()
|
| 271 |
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
loss = F.mse_loss(wae(batch), batch)
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
(
|
| 286 |
-
).
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 290 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
|
| 292 |
def live_window():
|
| 293 |
live, _ = open_meteo(
|
| 294 |
"https://api.open-meteo.com/v1/forecast",
|
| 295 |
-
latitude=LAT,
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
timezone="Asia/Kolkata",
|
| 299 |
-
past_days=WINDOW,
|
| 300 |
-
forecast_days=1,
|
| 301 |
)
|
| 302 |
return live.tail(WINDOW)
|
| 303 |
|
| 304 |
-
|
| 305 |
-
def live_score():
|
| 306 |
-
live = live_window()
|
| 307 |
-
values = standardize(transform(live)).values.astype(np.float32).ravel()
|
| 308 |
-
x = torch.from_numpy(values.copy()[None])
|
| 309 |
-
|
| 310 |
-
try:
|
| 311 |
-
wae.to("cuda")
|
| 312 |
-
with torch.inference_mode():
|
| 313 |
-
x_gpu = x.to("cuda")
|
| 314 |
-
score = F.mse_loss(wae(x_gpu), x_gpu).item()
|
| 315 |
-
finally:
|
| 316 |
-
wae.to("cpu")
|
| 317 |
-
|
| 318 |
-
return score, live
|
| 319 |
-
|
| 320 |
@spaces.GPU
|
| 321 |
def weather():
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
)
|
| 347 |
-
return verdict, fig
|
| 348 |
-
|
| 349 |
-
except Exception as exc:
|
| 350 |
-
return f"Weather check failed: `{type(exc).__name__}: {exc}`", None
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
# 4. Feedback logger
|
| 354 |
FB = f"feedback_{ROLL}.csv"
|
| 355 |
|
| 356 |
-
|
| 357 |
def feedback(roll, stars, comment):
|
| 358 |
visitor_roll = str(roll or "").strip().upper()
|
| 359 |
if not visitor_roll:
|
|
@@ -378,39 +250,21 @@ def feedback(roll, stars, comment):
|
|
| 378 |
result.to_csv(FB, index=False)
|
| 379 |
return result
|
| 380 |
|
| 381 |
-
|
| 382 |
-
# 5. Gradio interface
|
| 383 |
with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
|
| 384 |
gr.Markdown(f"# 🧠 {ROLL}'s Autoencoder App\nBuilt in LearnLab Module 3")
|
| 385 |
|
| 386 |
with gr.Tab("Denoiser"):
|
| 387 |
with gr.Row():
|
| 388 |
-
image_input = gr.Image(
|
| 389 |
-
type="numpy",
|
| 390 |
-
label="Upload a digit photo (optional)",
|
| 391 |
-
)
|
| 392 |
with gr.Column():
|
| 393 |
-
image_index = gr.Slider(
|
| 394 |
-
|
| 395 |
-
len(Xte) - 1,
|
| 396 |
-
value=7,
|
| 397 |
-
step=1,
|
| 398 |
-
label="Or pick MNIST test image #",
|
| 399 |
-
)
|
| 400 |
-
noise_sigma = gr.Slider(
|
| 401 |
-
0,
|
| 402 |
-
1,
|
| 403 |
-
value=0.5,
|
| 404 |
-
step=0.05,
|
| 405 |
-
label="Noise σ",
|
| 406 |
-
)
|
| 407 |
denoise_button = gr.Button("Denoise", variant="primary")
|
| 408 |
-
|
| 409 |
with gr.Row():
|
| 410 |
clean_output = gr.Image(label="Clean")
|
| 411 |
noisy_output = gr.Image(label="Noisy")
|
| 412 |
denoised_output = gr.Image(label="Denoised")
|
| 413 |
-
|
| 414 |
denoise_button.click(
|
| 415 |
fn=denoise,
|
| 416 |
inputs=[image_input, image_index, noise_sigma],
|
|
@@ -418,13 +272,8 @@ with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
|
|
| 418 |
)
|
| 419 |
|
| 420 |
with gr.Tab(f"Weather alarm · {CITY}"):
|
| 421 |
-
gr.Markdown(
|
| 422 |
-
|
| 423 |
-
)
|
| 424 |
-
weather_button = gr.Button(
|
| 425 |
-
"Check the last days (live Open-Meteo)",
|
| 426 |
-
variant="primary",
|
| 427 |
-
)
|
| 428 |
weather_verdict = gr.Markdown()
|
| 429 |
weather_plot = gr.Plot()
|
| 430 |
weather_button.click(
|
|
@@ -445,6 +294,5 @@ with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
|
|
| 445 |
outputs=feedback_table,
|
| 446 |
)
|
| 447 |
|
| 448 |
-
|
| 449 |
if __name__ == "__main__":
|
| 450 |
-
demo.queue().launch()
|
|
|
|
| 1 |
import os
|
| 2 |
import time
|
| 3 |
import hashlib
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import requests
|
| 5 |
import numpy as np
|
| 6 |
import pandas as pd
|
|
|
|
| 16 |
import gradio as gr
|
| 17 |
import spaces
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# 1. Personal settings
|
| 20 |
ROLL = "2415800016"
|
| 21 |
h = int(hashlib.sha256(ROLL.encode()).hexdigest(), 16)
|
|
|
|
| 23 |
LATENT = [3, 4, 5, 6][(h >> 4) & 3]
|
| 24 |
|
| 25 |
CITIES = [
|
| 26 |
+
("Chennai", 13.0827, 80.2707), ("Mumbai", 19.0760, 72.8777), ("Kolkata", 22.5726, 88.3639),
|
| 27 |
+
("Delhi", 28.6139, 77.2090), ("Bengaluru", 12.9716, 77.5946), ("Hyderabad", 17.3850, 78.4867),
|
| 28 |
+
("Kochi", 9.9312, 76.2673), ("Bhubaneswar", 20.2961, 85.8245), ("Visakhapatnam", 17.6868, 83.2185),
|
| 29 |
+
("Ahmedabad", 23.0225, 72.5714), ("Jaipur", 26.9124, 75.7873), ("Guwahati", 26.1445, 91.7362),
|
| 30 |
+
("Lucknow", 26.8467, 80.9462), ("Pune", 18.5204, 73.8567), ("Madurai", 9.9252, 78.1198),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
("Coimbatore", 11.0168, 76.9558),
|
| 32 |
]
|
| 33 |
CITY, LAT, LON = CITIES[(h >> 24) % len(CITIES)]
|
| 34 |
WINDOW = [5, 7, 10][(h >> 30) % 3]
|
| 35 |
|
| 36 |
+
# 2. Denoising Autoencoder (Tab 1)
|
|
|
|
| 37 |
class AE(nn.Module):
|
| 38 |
def __init__(self, z=LATENT):
|
| 39 |
super().__init__()
|
| 40 |
self.enc = nn.Sequential(
|
| 41 |
+
nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
|
| 42 |
+
nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, z),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
)
|
| 44 |
self.dec = nn.Sequential(
|
| 45 |
+
nn.Linear(z, 64), nn.ReLU(), nn.Linear(64, 256),
|
| 46 |
+
nn.ReLU(), nn.Linear(256, 784), nn.Sigmoid(),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
)
|
| 48 |
|
| 49 |
def forward(self, x):
|
| 50 |
z = self.enc(x)
|
| 51 |
return self.dec(z).view(-1, 1, 28, 28), z
|
| 52 |
|
| 53 |
+
test_ds = torchvision.datasets.MNIST("data", train=False, download=True)
|
| 54 |
+
Xte = (test_ds.data.float() / 255.0).unsqueeze(1)
|
| 55 |
|
| 56 |
+
dae_gpu = None
|
| 57 |
+
|
| 58 |
+
def get_dae_gpu():
|
| 59 |
+
global dae_gpu
|
| 60 |
+
if dae_gpu is not None:
|
| 61 |
+
return dae_gpu
|
| 62 |
|
| 63 |
+
model = AE().to("cuda")
|
| 64 |
+
checkpoint = f"dae_{ROLL}.pt"
|
| 65 |
if os.path.exists(checkpoint):
|
| 66 |
+
state = torch.load(checkpoint, map_location="cuda")
|
|
|
|
|
|
|
|
|
|
| 67 |
model.load_state_dict(state)
|
| 68 |
else:
|
| 69 |
+
torch.manual_seed(SEED)
|
| 70 |
+
train_ds = torchvision.datasets.MNIST("data", train=True, download=True)
|
| 71 |
+
x_train = (train_ds.data.float() / 255.0).unsqueeze(1).to("cuda")
|
| 72 |
+
opt = torch.optim.Adam(model.parameters(), 1e-3)
|
|
|
|
|
|
|
| 73 |
model.train()
|
| 74 |
for _ in range(3):
|
| 75 |
for start in range(0, len(x_train), 256):
|
| 76 |
x = x_train[start:start + 256]
|
| 77 |
noisy = (x + 0.5 * torch.randn_like(x)).clamp(0, 1)
|
| 78 |
+
loss = F.mse_loss(model(noisy)[0], x)
|
| 79 |
+
opt.zero_grad()
|
|
|
|
|
|
|
| 80 |
loss.backward()
|
| 81 |
+
opt.step()
|
|
|
|
| 82 |
torch.save(model.state_dict(), checkpoint)
|
| 83 |
|
| 84 |
model.eval()
|
| 85 |
+
dae_gpu = model
|
| 86 |
+
return dae_gpu
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
def to28(img):
|
| 89 |
arr = np.asarray(
|
| 90 |
+
Image.fromarray(np.asarray(img).astype(np.uint8)).convert("L").resize((28, 28)),
|
|
|
|
|
|
|
| 91 |
dtype=np.float32,
|
| 92 |
) / 255.0
|
|
|
|
| 93 |
if arr.mean() > 0.5:
|
| 94 |
arr = 1.0 - arr
|
|
|
|
| 95 |
return torch.from_numpy(arr.copy())[None, None]
|
| 96 |
|
| 97 |
+
def big_from_gpu(t_gpu):
|
| 98 |
+
arr = t_gpu[0, 0].detach().clamp(0, 1).cpu().numpy()
|
|
|
|
| 99 |
return (arr * 255).astype(np.uint8).repeat(8, 0).repeat(8, 1)
|
| 100 |
|
|
|
|
| 101 |
@spaces.GPU
|
| 102 |
def denoise(img, idx, sigma):
|
| 103 |
+
model = get_dae_gpu()
|
| 104 |
+
x_cpu = to28(img) if img is not None else Xte[int(idx)][None]
|
| 105 |
+
x_gpu = x_cpu.to("cuda")
|
| 106 |
+
gen = torch.Generator(device="cuda").manual_seed(0)
|
| 107 |
+
noisy_gpu = (x_gpu + float(sigma) * torch.randn(x_gpu.shape, device="cuda", generator=gen)).clamp(0, 1)
|
| 108 |
+
with torch.inference_mode():
|
| 109 |
+
recon_gpu, _ = model(noisy_gpu)
|
| 110 |
+
return big_from_gpu(x_gpu), big_from_gpu(noisy_gpu), big_from_gpu(recon_gpu)
|
| 111 |
+
|
| 112 |
+
# 3. Weather Anomaly Model (Tab 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
VARS = [
|
| 114 |
+
"temperature_2m_max", "temperature_2m_min",
|
| 115 |
+
"precipitation_sum", "wind_speed_10m_max", "wind_gusts_10m_max",
|
|
|
|
|
|
|
|
|
|
| 116 |
]
|
| 117 |
ATTRIB = "Weather data by Open-Meteo.com (CC BY 4.0)"
|
| 118 |
|
|
|
|
| 119 |
def open_meteo(url, **params):
|
| 120 |
+
r = requests.get(url, params=params, timeout=90)
|
| 121 |
+
r.raise_for_status()
|
| 122 |
+
payload = r.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
frame = pd.DataFrame(payload["daily"])
|
| 124 |
frame["time"] = pd.to_datetime(frame["time"])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
return frame.set_index("time")[VARS].ffill().bfill(), payload.get("daily_units", {})
|
| 126 |
|
|
|
|
| 127 |
def transform(frame):
|
| 128 |
+
res = frame[VARS].copy()
|
| 129 |
+
res["precipitation_sum"] = np.log1p(res["precipitation_sum"].clip(lower=0))
|
| 130 |
+
return res
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
history, _ = open_meteo(
|
| 133 |
"https://archive-api.open-meteo.com/v1/archive",
|
| 134 |
+
latitude=LAT, longitude=LON,
|
| 135 |
+
start_date="1991-01-01", end_date="2024-12-31",
|
| 136 |
+
daily=",".join(VARS), timezone="Asia/Kolkata",
|
|
|
|
|
|
|
|
|
|
| 137 |
)
|
|
|
|
| 138 |
T = transform(history)
|
| 139 |
+
tr_mask = T.index.year <= 2014
|
| 140 |
+
monthly_mean = T[tr_mask].groupby(T[tr_mask].index.month).mean()
|
| 141 |
+
monthly_std = T[tr_mask].groupby(T[tr_mask].index.month).std() + 1e-6
|
|
|
|
| 142 |
|
| 143 |
def standardize(frame):
|
| 144 |
months = frame.index.month
|
| 145 |
+
return (frame - monthly_mean.loc[months].values) / monthly_std.loc[months].values
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
def make_windows(frame, width=WINDOW):
|
| 148 |
values = frame.values.astype(np.float32)
|
| 149 |
count = len(values) - width + 1
|
| 150 |
+
wins = np.stack([values[i:i + width].ravel() for i in range(count)])
|
| 151 |
+
return wins, frame.index[:count]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
Xw, starts = make_windows(standardize(T))
|
|
|
|
|
|
|
|
|
|
| 154 |
D = Xw.shape[1]
|
| 155 |
|
| 156 |
+
wae_gpu = None
|
| 157 |
+
thresh_val = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
|
| 159 |
+
def get_wae_and_thresh():
|
| 160 |
+
global wae_gpu, thresh_val
|
| 161 |
+
if wae_gpu is not None and thresh_val is not None:
|
| 162 |
+
return wae_gpu, thresh_val
|
|
|
|
| 163 |
|
| 164 |
+
Xw_t = torch.from_numpy(Xw.copy()).to("cuda")
|
| 165 |
+
tr_idx = torch.from_numpy(np.asarray(starts.year <= 2014, dtype=np.bool_)).to("cuda")
|
| 166 |
+
train_w = Xw_t[tr_idx]
|
| 167 |
|
| 168 |
+
torch.manual_seed(SEED)
|
| 169 |
+
model = nn.Sequential(
|
| 170 |
+
nn.Linear(D, 32), nn.ReLU(), nn.Linear(32, 6),
|
| 171 |
+
nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, D),
|
| 172 |
+
).to("cuda")
|
| 173 |
+
opt = torch.optim.Adam(model.parameters(), 1e-3)
|
| 174 |
+
model.train()
|
| 175 |
+
for _ in range(40):
|
| 176 |
+
perm = torch.randperm(len(train_w), device="cuda")
|
| 177 |
+
for start in range(0, len(perm), 256):
|
| 178 |
+
batch = train_w[perm[start:start + 256]]
|
| 179 |
+
loss = F.mse_loss(model(batch), batch)
|
| 180 |
+
opt.zero_grad()
|
| 181 |
+
loss.backward()
|
| 182 |
+
opt.step()
|
| 183 |
|
| 184 |
+
model.eval()
|
| 185 |
+
with torch.inference_mode():
|
| 186 |
+
err = ((model(Xw_t) - Xw_t) ** 2).view(len(Xw), WINDOW, len(VARS)).cpu().numpy()
|
| 187 |
+
scores = err.mean(axis=(1, 2))
|
| 188 |
+
thresh_val = float(np.quantile(scores[starts.year <= 2014], 0.99))
|
| 189 |
+
wae_gpu = model
|
| 190 |
+
return wae_gpu, thresh_val
|
| 191 |
|
| 192 |
def live_window():
|
| 193 |
live, _ = open_meteo(
|
| 194 |
"https://api.open-meteo.com/v1/forecast",
|
| 195 |
+
latitude=LAT, longitude=LON,
|
| 196 |
+
daily=",".join(VARS), timezone="Asia/Kolkata",
|
| 197 |
+
past_days=WINDOW, forecast_days=1,
|
|
|
|
|
|
|
|
|
|
| 198 |
)
|
| 199 |
return live.tail(WINDOW)
|
| 200 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
@spaces.GPU
|
| 202 |
def weather():
|
| 203 |
+
model, thresh = get_wae_and_thresh()
|
| 204 |
+
live = live_window()
|
| 205 |
+
values = standardize(transform(live)).values.astype(np.float32).ravel()
|
| 206 |
+
x_gpu = torch.from_numpy(values.copy()[None]).to("cuda")
|
| 207 |
+
with torch.inference_mode():
|
| 208 |
+
sc = F.mse_loss(model(x_gpu), x_gpu).item()
|
| 209 |
+
|
| 210 |
+
fig, ax = plt.subplots(figsize=(7, 3))
|
| 211 |
+
labels = live.index.strftime("%d %b")
|
| 212 |
+
ax.bar(labels, live["precipitation_sum"], label="Rain (mm)")
|
| 213 |
+
ax.set_ylabel("Rain (mm)")
|
| 214 |
+
ax.set_xlabel("Date")
|
| 215 |
+
|
| 216 |
+
ax2 = ax.twinx()
|
| 217 |
+
ax2.plot(labels, live["temperature_2m_max"], "r-o", label="Tmax")
|
| 218 |
+
ax2.set_ylabel("Tmax (°C)")
|
| 219 |
+
ax.set_title(ATTRIB, fontsize=8)
|
| 220 |
+
fig.tight_layout()
|
| 221 |
+
|
| 222 |
+
status = "⚠️ **UNUSUAL**" if sc > thresh else "✅ **Normal**"
|
| 223 |
+
verdict = f"**{CITY}**, last {WINDOW} days: score **{sc:.3f}** vs threshold **{thresh:.3f}** → {status}"
|
| 224 |
+
return verdict, fig
|
| 225 |
+
|
| 226 |
+
# 4. Feedback Logger (Tab 3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
FB = f"feedback_{ROLL}.csv"
|
| 228 |
|
|
|
|
| 229 |
def feedback(roll, stars, comment):
|
| 230 |
visitor_roll = str(roll or "").strip().upper()
|
| 231 |
if not visitor_roll:
|
|
|
|
| 250 |
result.to_csv(FB, index=False)
|
| 251 |
return result
|
| 252 |
|
| 253 |
+
# 5. Gradio Interface
|
|
|
|
| 254 |
with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
|
| 255 |
gr.Markdown(f"# 🧠 {ROLL}'s Autoencoder App\nBuilt in LearnLab Module 3")
|
| 256 |
|
| 257 |
with gr.Tab("Denoiser"):
|
| 258 |
with gr.Row():
|
| 259 |
+
image_input = gr.Image(type="numpy", label="Upload a digit photo (optional)")
|
|
|
|
|
|
|
|
|
|
| 260 |
with gr.Column():
|
| 261 |
+
image_index = gr.Slider(0, len(Xte) - 1, value=7, step=1, label="Or pick MNIST test image #")
|
| 262 |
+
noise_sigma = gr.Slider(0, 1, value=0.5, step=0.05, label="Noise σ")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
denoise_button = gr.Button("Denoise", variant="primary")
|
|
|
|
| 264 |
with gr.Row():
|
| 265 |
clean_output = gr.Image(label="Clean")
|
| 266 |
noisy_output = gr.Image(label="Noisy")
|
| 267 |
denoised_output = gr.Image(label="Denoised")
|
|
|
|
| 268 |
denoise_button.click(
|
| 269 |
fn=denoise,
|
| 270 |
inputs=[image_input, image_index, noise_sigma],
|
|
|
|
| 272 |
)
|
| 273 |
|
| 274 |
with gr.Tab(f"Weather alarm · {CITY}"):
|
| 275 |
+
gr.Markdown(f"Anomaly detection for **{CITY}** using the previous {WINDOW} days.")
|
| 276 |
+
weather_button = gr.Button("Check the last days (live Open-Meteo)", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
weather_verdict = gr.Markdown()
|
| 278 |
weather_plot = gr.Plot()
|
| 279 |
weather_button.click(
|
|
|
|
| 294 |
outputs=feedback_table,
|
| 295 |
)
|
| 296 |
|
|
|
|
| 297 |
if __name__ == "__main__":
|
| 298 |
+
demo.queue().launch()
|