0xarchit commited on
Commit
e8196d6
·
verified ·
1 Parent(s): 36f389c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +349 -141
app.py CHANGED
@@ -1,7 +1,12 @@
1
- import spaces
2
  import os
3
  import time
4
  import hashlib
 
 
 
 
 
 
5
  import requests
6
  import numpy as np
7
  import pandas as pd
@@ -17,215 +22,418 @@ import torchvision
17
  import gradio as gr
18
 
19
 
20
- DEV = "cpu"
21
- # 1. Personal settings (derived identically to Notebook 2 for roll 2415800016)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  ROLL = "2415800016"
23
  h = int(hashlib.sha256(ROLL.encode()).hexdigest(), 16)
24
  SEED = h % 100000
25
  LATENT = [3, 4, 5, 6][(h >> 4) & 3]
26
 
27
  CITIES = [
28
- ("Chennai", 13.0827, 80.2707), ("Mumbai", 19.0760, 72.8777), ("Kolkata", 22.5726, 88.3639),
29
- ("Delhi", 28.6139, 77.2090), ("Bengaluru", 12.9716, 77.5946), ("Hyderabad", 17.3850, 78.4867),
30
- ("Kochi", 9.9312, 76.2673), ("Bhubaneswar", 20.2961, 85.8245), ("Visakhapatnam", 17.6868, 83.2185),
31
- ("Ahmedabad", 23.0225, 72.5714), ("Jaipur", 26.9124, 75.7873), ("Guwahati", 26.1445, 91.7362),
32
- ("Lucknow", 26.8467, 80.9462), ("Pune", 18.5204, 73.8567), ("Madurai", 9.9252, 78.1198),
33
- ("Coimbatore", 11.0168, 76.9558)
 
 
 
 
 
 
 
 
 
 
34
  ]
35
  CITY, LAT, LON = CITIES[(h >> 24) % len(CITIES)]
36
  WINDOW = [5, 7, 10][(h >> 30) % 3]
37
 
38
- # 2. Denoising Autoencoder (Tab 1)
 
39
  class AE(nn.Module):
40
  def __init__(self, z=LATENT):
41
  super().__init__()
42
  self.enc = nn.Sequential(
43
- nn.Flatten(), nn.Linear(784, 256), nn.ReLU(),
44
- nn.Linear(256, 64), nn.ReLU(), nn.Linear(64, z)
 
 
 
 
45
  )
46
  self.dec = nn.Sequential(
47
- nn.Linear(z, 64), nn.ReLU(), nn.Linear(64, 256),
48
- nn.ReLU(), nn.Linear(256, 784), nn.Sigmoid()
 
 
 
 
49
  )
50
 
51
  def forward(self, x):
52
  z = self.enc(x)
53
  return self.dec(z).view(-1, 1, 28, 28), z
54
 
55
- te = torchvision.datasets.MNIST("data", train=False, download=True)
56
- Xte = (te.data.float() / 255.0).unsqueeze(1)
57
 
58
- dae = AE().to(DEV)
59
- ck = f"dae_{ROLL}.pt"
60
- if os.path.exists(ck):
61
- dae.load_state_dict(torch.load(ck, map_location=DEV))
62
- else:
63
  torch.manual_seed(SEED)
64
- tr = torchvision.datasets.MNIST("data", train=True, download=True)
65
- Xtr = (tr.data.float() / 255.0).unsqueeze(1).to(DEV)
66
- opt = torch.optim.Adam(dae.parameters(), 1e-3)
67
- for ep in range(3):
68
- for i in range(0, len(Xtr), 256):
69
- x = Xtr[i:i + 256]
70
- loss = F.mse_loss(dae((x + 0.5 * torch.randn_like(x)).clamp(0, 1))[0], x)
71
- opt.zero_grad()
72
- loss.backward()
73
- opt.step()
74
- torch.save(dae.state_dict(), ck)
75
- dae.eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
  def to28(img):
78
- a = np.asarray(Image.fromarray(img).convert("L").resize((28, 28)), dtype=np.float32) / 255.0
79
- if a.mean() > 0.5:
80
- a = 1.0 - a
81
- return torch.tensor(a)[None, None]
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- big = lambda t: (t[0, 0].clamp(0, 1).numpy() * 255).astype(np.uint8).repeat(8, 0).repeat(8, 1)
84
 
85
  def denoise(img, idx, sigma):
86
  x = to28(img) if img is not None else Xte[int(idx)][None]
87
- g = torch.Generator().manual_seed(0)
88
- xn = (x + sigma * torch.randn(x.shape, generator=g)).clamp(0, 1)
89
- with torch.no_grad():
90
- y = dae(xn.to(DEV))[0].cpu()
91
- return big(x), big(xn), big(y)
92
-
93
- # 3. Weather Anomaly Model & Threshold (Tab 2)
94
- VARS = ["temperature_2m_max", "temperature_2m_min", "precipitation_sum", "wind_speed_10m_max", "wind_gusts_10m_max"]
 
 
 
 
 
 
 
 
 
 
 
95
  ATTRIB = "Weather data by Open-Meteo.com (CC BY 4.0)"
96
 
 
97
  def open_meteo(url, **params):
98
- r = requests.get(url, params=params, timeout=90)
99
- r.raise_for_status()
100
- j = r.json()
101
- df = pd.DataFrame(j["daily"])
102
- df["time"] = pd.to_datetime(df["time"])
103
- return df.set_index("time")[VARS].ffill().bfill(), j.get("daily_units", {})
104
-
105
- def transform(df):
106
- X = df[VARS].copy()
107
- X["precipitation_sum"] = np.log1p(X["precipitation_sum"].clip(lower=0))
108
- return X
109
-
110
- hist, _ = open_meteo(
 
 
 
 
 
 
 
 
 
 
 
 
111
  "https://archive-api.open-meteo.com/v1/archive",
112
- latitude=LAT, longitude=LON,
113
- start_date="1991-01-01", end_date="2024-12-31",
114
- daily=",".join(VARS), timezone="Asia/Kolkata"
 
 
 
115
  )
116
- T = transform(hist)
117
- tr_mask = T.index.year <= 2014
118
- mu = T[tr_mask].groupby(T[tr_mask].index.month).mean()
119
- sd = T[tr_mask].groupby(T[tr_mask].index.month).std() + 1e-6
120
-
121
- def standardize(T_df):
122
- m = T_df.index.month
123
- return (T_df - mu.loc[m].values) / sd.loc[m].values
124
-
125
- def windows(S, W=WINDOW):
126
- a = S.values.astype(np.float32)
127
- n = len(a) - W + 1
128
- return np.stack([a[i:i + W].ravel() for i in range(n)]), S.index[:n]
129
-
130
- Xw, starts = windows(standardize(T))
131
- Xw_t = torch.tensor(Xw, device=DEV)
132
- train_w = Xw_t[torch.tensor(starts.year <= 2014)]
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  D = Xw.shape[1]
134
 
135
  torch.manual_seed(SEED)
136
  wae = nn.Sequential(
137
- nn.Linear(D, 32), nn.ReLU(), nn.Linear(32, 6),
138
- nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, D)
 
 
 
 
139
  ).to(DEV)
140
- opt_w = torch.optim.Adam(wae.parameters(), 1e-3)
141
- for ep in range(40):
142
- perm = torch.randperm(len(train_w), device=DEV)
143
- for i in range(0, len(perm), 256):
144
- x = train_w[perm[i:i + 256]]
145
- loss = F.mse_loss(wae(x), x)
146
- opt_w.zero_grad()
 
 
 
 
147
  loss.backward()
148
- opt_w.step()
 
149
  wae.eval()
150
- with torch.no_grad():
151
- err = ((wae(Xw_t) - Xw_t) ** 2).view(len(Xw), WINDOW, len(VARS)).cpu().numpy()
152
- score = err.mean((1, 2))
153
- THRESH = float(np.quantile(score[starts.year <= 2014], 0.99))
 
 
 
 
154
 
155
  def live_window():
156
  live, _ = open_meteo(
157
  "https://api.open-meteo.com/v1/forecast",
158
- latitude=LAT, longitude=LON,
159
- daily=",".join(VARS), timezone="Asia/Kolkata",
160
- past_days=WINDOW, forecast_days=1
 
 
 
161
  )
162
  return live.tail(WINDOW)
163
 
 
164
  def live_score():
165
- lw = live_window()
166
- x = torch.tensor(standardize(transform(lw)).values.astype(np.float32).ravel()[None], device=DEV)
167
- with torch.no_grad():
168
- s = F.mse_loss(wae(x), x).item()
169
- return s, lw
 
 
 
 
170
 
171
  def weather():
172
- s, lw = live_score()
173
- fig, ax = plt.subplots(figsize=(6, 2.6))
174
- ax.bar(lw.index.strftime("%d %b"), lw.precipitation_sum, color="tab:blue")
175
- ax2 = ax.twinx()
176
- ax2.plot(lw.index.strftime("%d %b"), lw.temperature_2m_max, "r-o")
177
- ax.set_ylabel("rain mm")
178
- ax2.set_ylabel("Tmax °C")
179
- ax.set_title(ATTRIB, fontsize=8)
180
- plt.tight_layout()
181
- verdict = f"**{CITY}**, last {WINDOW} days: score **{s:.3f}** vs threshold {THRESH:.3f} → " + (
182
- "⚠️ **UNUSUAL**" if s > THRESH else "✅ normal"
183
- )
184
- return verdict, fig
185
 
186
- # 4. Feedback Logger (Tab 3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  FB = f"feedback_{ROLL}.csv"
188
 
 
189
  def feedback(roll, stars, comment):
 
 
 
 
190
  row = pd.DataFrame([{
191
  "time": time.strftime("%Y-%m-%d %H:%M"),
192
- "visitor_roll": str(roll).strip().upper(),
193
- "stars": stars,
194
- "comment": comment
195
  }])
196
- df = pd.concat([pd.read_csv(FB), row], ignore_index=True) if os.path.exists(FB) else row
197
- df.to_csv(FB, index=False)
198
- return df
199
 
200
- # 5. Gradio Interface
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
202
  gr.Markdown(f"# 🧠 {ROLL}'s Autoencoder App\nBuilt in LearnLab Module 3")
 
203
  with gr.Tab("Denoiser"):
204
  with gr.Row():
205
- inp = gr.Image(type="numpy", label="Upload a digit photo (optional)")
 
 
 
206
  with gr.Column():
207
- idx = gr.Slider(0, len(Xte) - 1, value=7, step=1, label="…or pick MNIST test image #")
208
- sig = gr.Slider(0, 1, value=0.5, step=0.05, label="noise σ")
209
- b1 = gr.Button("Denoise", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  with gr.Row():
211
- o1 = gr.Image(label="clean")
212
- o2 = gr.Image(label="noisy")
213
- o3 = gr.Image(label="denoised")
214
- b1.click(denoise, [inp, idx, sig], [o1, o2, o3])
 
 
 
 
 
215
 
216
  with gr.Tab(f"Weather alarm · {CITY}"):
217
- b2 = gr.Button("Check the last days (live Open-Meteo)", variant="primary")
218
- v = gr.Markdown()
219
- p = gr.Plot()
220
- b2.click(weather, None, [v, p])
 
 
 
 
 
 
 
 
 
 
221
 
222
  with gr.Tab("Feedback"):
223
- r_ = gr.Textbox(label="Your roll number")
224
- st = gr.Slider(1, 5, value=4, step=1, label="Stars")
225
- cm = gr.Textbox(label="Comment")
226
- b3 = gr.Button("Submit")
227
- tbl = gr.Dataframe()
228
- b3.click(feedback, [r_, st, cm], tbl)
 
 
 
 
 
229
 
230
  if __name__ == "__main__":
231
- demo.launch()
 
 
1
  import os
2
  import time
3
  import hashlib
4
+
5
+ # Keep CPU execution predictable on shared Hugging Face hardware.
6
+ os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
7
+ os.environ.setdefault("OMP_NUM_THREADS", "2")
8
+ os.environ.setdefault("MKL_NUM_THREADS", "2")
9
+
10
  import requests
11
  import numpy as np
12
  import pandas as pd
 
22
  import gradio as gr
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-only execution on HF ZeroGPU Spaces.
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)
51
  SEED = h % 100000
52
  LATENT = [3, 4, 5, 6][(h >> 4) & 3]
53
 
54
  CITIES = [
55
+ ("Chennai", 13.0827, 80.2707),
56
+ ("Mumbai", 19.0760, 72.8777),
57
+ ("Kolkata", 22.5726, 88.3639),
58
+ ("Delhi", 28.6139, 77.2090),
59
+ ("Bengaluru", 12.9716, 77.5946),
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(784, 256),
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
+ def load_or_train_denoiser():
 
 
 
 
103
  torch.manual_seed(SEED)
104
+ model = AE().to(DEV)
105
+ checkpoint = f"dae_{ROLL}.pt"
106
+
107
+ if os.path.exists(checkpoint):
108
+ try:
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
+ train_ds = torchvision.datasets.MNIST(
115
+ "data", train=True, download=True
116
+ )
117
+ x_train = (train_ds.data.float() / 255.0).unsqueeze(1).to(DEV)
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
+ reconstructed, _ = model(noisy)
126
+ loss = F.mse_loss(reconstructed, x)
127
+
128
+ optimizer.zero_grad(set_to_none=True)
129
+ loss.backward()
130
+ optimizer.step()
131
+
132
+ torch.save(model.state_dict(), checkpoint)
133
+
134
+ model.eval()
135
+ return model
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
+ def big(t):
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
  def denoise(img, idx, sigma):
164
  x = to28(img) if img is not None else Xte[int(idx)][None]
165
+ generator = torch.Generator(device="cpu").manual_seed(0)
166
+ noisy = (x + float(sigma) * torch.randn(
167
+ x.shape, generator=generator
168
+ )).clamp(0, 1)
169
+
170
+ with torch.inference_mode():
171
+ reconstructed, _ = dae(noisy.to(DEV))
172
+
173
+ return big(x), big(noisy), big(reconstructed)
174
+
175
+
176
+ # 3. Weather anomaly model
177
+ VARS = [
178
+ "temperature_2m_max",
179
+ "temperature_2m_min",
180
+ "precipitation_sum",
181
+ "wind_speed_10m_max",
182
+ "wind_gusts_10m_max",
183
+ ]
184
  ATTRIB = "Weather data by Open-Meteo.com (CC BY 4.0)"
185
 
186
+
187
  def open_meteo(url, **params):
188
+ response = requests.get(url, params=params, timeout=90)
189
+ response.raise_for_status()
190
+ payload = response.json()
191
+
192
+ if "daily" not in payload:
193
+ raise ValueError("Open-Meteo response did not contain daily weather data.")
194
+
195
+ frame = pd.DataFrame(payload["daily"])
196
+ frame["time"] = pd.to_datetime(frame["time"])
197
+ missing = [col for col in VARS if col not in frame.columns]
198
+ if missing:
199
+ raise ValueError(f"Weather response is missing: {', '.join(missing)}")
200
+
201
+ return frame.set_index("time")[VARS].ffill().bfill(), payload.get("daily_units", {})
202
+
203
+
204
+ def transform(frame):
205
+ result = frame[VARS].copy()
206
+ result["precipitation_sum"] = np.log1p(
207
+ result["precipitation_sum"].clip(lower=0)
208
+ )
209
+ return result
210
+
211
+
212
+ history, _ = open_meteo(
213
  "https://archive-api.open-meteo.com/v1/archive",
214
+ latitude=LAT,
215
+ longitude=LON,
216
+ start_date="1991-01-01",
217
+ end_date="2024-12-31",
218
+ daily=",".join(VARS),
219
+ timezone="Asia/Kolkata",
220
  )
221
+
222
+ T = transform(history)
223
+ train_mask = T.index.year <= 2014
224
+ monthly_mean = T[train_mask].groupby(T[train_mask].index.month).mean()
225
+ monthly_std = T[train_mask].groupby(T[train_mask].index.month).std() + 1e-6
226
+
227
+
228
+ def standardize(frame):
229
+ months = frame.index.month
230
+ return (
231
+ frame - monthly_mean.loc[months].values
232
+ ) / monthly_std.loc[months].values
233
+
234
+
235
+ def make_windows(frame, width=WINDOW):
236
+ values = frame.values.astype(np.float32)
237
+ count = len(values) - width + 1
238
+ if count <= 0:
239
+ raise ValueError("Not enough weather history to build training windows.")
240
+
241
+ windows = np.stack([
242
+ values[i:i + width].ravel()
243
+ for i in range(count)
244
+ ])
245
+ return windows, frame.index[:count]
246
+
247
+
248
+ Xw, starts = make_windows(standardize(T))
249
+ Xw_t = torch.from_numpy(Xw.copy()).to(DEV)
250
+ train_w = Xw_t[torch.from_numpy((starts.year <= 2014).to_numpy())]
251
  D = Xw.shape[1]
252
 
253
  torch.manual_seed(SEED)
254
  wae = nn.Sequential(
255
+ nn.Linear(D, 32),
256
+ nn.ReLU(),
257
+ nn.Linear(32, 6),
258
+ nn.Linear(6, 32),
259
+ nn.ReLU(),
260
+ nn.Linear(32, D),
261
  ).to(DEV)
262
+
263
+ weather_optimizer = make_adam(wae.parameters(), 1e-3)
264
+ wae.train()
265
+
266
+ for _ in range(40):
267
+ permutation = torch.randperm(len(train_w), device=DEV)
268
+ for start in range(0, len(permutation), 256):
269
+ batch = train_w[permutation[start:start + 256]]
270
+ loss = F.mse_loss(wae(batch), batch)
271
+
272
+ weather_optimizer.zero_grad(set_to_none=True)
273
  loss.backward()
274
+ weather_optimizer.step()
275
+
276
  wae.eval()
277
+ with torch.inference_mode():
278
+ reconstruction_error = (
279
+ (wae(Xw_t) - Xw_t) ** 2
280
+ ).view(len(Xw), WINDOW, len(VARS)).cpu().numpy()
281
+
282
+ scores = reconstruction_error.mean(axis=(1, 2))
283
+ THRESH = float(np.quantile(scores[starts.year <= 2014], 0.99))
284
+
285
 
286
  def live_window():
287
  live, _ = open_meteo(
288
  "https://api.open-meteo.com/v1/forecast",
289
+ latitude=LAT,
290
+ longitude=LON,
291
+ daily=",".join(VARS),
292
+ timezone="Asia/Kolkata",
293
+ past_days=WINDOW,
294
+ forecast_days=1,
295
  )
296
  return live.tail(WINDOW)
297
 
298
+
299
  def live_score():
300
+ live = live_window()
301
+ values = standardize(transform(live)).values.astype(np.float32).ravel()
302
+ x = torch.from_numpy(values.copy()[None]).to(DEV)
303
+
304
+ with torch.inference_mode():
305
+ score = F.mse_loss(wae(x), x).item()
306
+
307
+ return score, live
308
+
309
 
310
  def weather():
311
+ try:
312
+ score, live = live_score()
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ fig, ax = plt.subplots(figsize=(7, 3))
315
+ labels = live.index.strftime("%d %b")
316
+ ax.bar(labels, live["precipitation_sum"], label="Rain (mm)")
317
+ ax.set_ylabel("Rain (mm)")
318
+ ax.set_xlabel("Date")
319
+
320
+ ax2 = ax.twinx()
321
+ ax2.plot(
322
+ labels,
323
+ live["temperature_2m_max"],
324
+ "r-o",
325
+ label="Maximum temperature",
326
+ )
327
+ ax2.set_ylabel("Tmax (°C)")
328
+ ax.set_title(ATTRIB, fontsize=8)
329
+ fig.tight_layout()
330
+
331
+ status = "⚠️ **UNUSUAL**" if score > THRESH else "✅ **Normal**"
332
+ verdict = (
333
+ f"**{CITY}**, last {WINDOW} days: "
334
+ f"score **{score:.3f}** vs threshold **{THRESH:.3f}** → {status}"
335
+ )
336
+ return verdict, fig
337
+
338
+ except Exception as exc:
339
+ return f"Weather check failed: `{type(exc).__name__}: {exc}`", None
340
+
341
+
342
+ # 4. Feedback logger
343
  FB = f"feedback_{ROLL}.csv"
344
 
345
+
346
  def feedback(roll, stars, comment):
347
+ visitor_roll = str(roll or "").strip().upper()
348
+ if not visitor_roll:
349
+ raise gr.Error("Please enter your roll number.")
350
+
351
  row = pd.DataFrame([{
352
  "time": time.strftime("%Y-%m-%d %H:%M"),
353
+ "visitor_roll": visitor_roll,
354
+ "stars": int(stars),
355
+ "comment": str(comment or "").strip(),
356
  }])
 
 
 
357
 
358
+ if os.path.exists(FB):
359
+ try:
360
+ existing = pd.read_csv(FB)
361
+ result = pd.concat([existing, row], ignore_index=True)
362
+ except Exception:
363
+ result = row
364
+ else:
365
+ result = row
366
+
367
+ result.to_csv(FB, index=False)
368
+ return result
369
+
370
+
371
+ # 5. Gradio interface
372
  with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
373
  gr.Markdown(f"# 🧠 {ROLL}'s Autoencoder App\nBuilt in LearnLab Module 3")
374
+
375
  with gr.Tab("Denoiser"):
376
  with gr.Row():
377
+ image_input = gr.Image(
378
+ type="numpy",
379
+ label="Upload a digit photo (optional)",
380
+ )
381
  with gr.Column():
382
+ image_index = gr.Slider(
383
+ 0,
384
+ len(Xte) - 1,
385
+ value=7,
386
+ step=1,
387
+ label="Or pick MNIST test image #",
388
+ )
389
+ noise_sigma = gr.Slider(
390
+ 0,
391
+ 1,
392
+ value=0.5,
393
+ step=0.05,
394
+ label="Noise σ",
395
+ )
396
+ denoise_button = gr.Button("Denoise", variant="primary")
397
+
398
  with gr.Row():
399
+ clean_output = gr.Image(label="Clean")
400
+ noisy_output = gr.Image(label="Noisy")
401
+ denoised_output = gr.Image(label="Denoised")
402
+
403
+ denoise_button.click(
404
+ fn=denoise,
405
+ inputs=[image_input, image_index, noise_sigma],
406
+ outputs=[clean_output, noisy_output, denoised_output],
407
+ )
408
 
409
  with gr.Tab(f"Weather alarm · {CITY}"):
410
+ gr.Markdown(
411
+ f"Anomaly detection for **{CITY}** using the previous {WINDOW} days."
412
+ )
413
+ weather_button = gr.Button(
414
+ "Check the last days (live Open-Meteo)",
415
+ variant="primary",
416
+ )
417
+ weather_verdict = gr.Markdown()
418
+ weather_plot = gr.Plot()
419
+ weather_button.click(
420
+ fn=weather,
421
+ inputs=None,
422
+ outputs=[weather_verdict, weather_plot],
423
+ )
424
 
425
  with gr.Tab("Feedback"):
426
+ roll_input = gr.Textbox(label="Your roll number")
427
+ stars_input = gr.Slider(1, 5, value=4, step=1, label="Stars")
428
+ comment_input = gr.Textbox(label="Comment")
429
+ feedback_button = gr.Button("Submit", variant="primary")
430
+ feedback_table = gr.Dataframe()
431
+ feedback_button.click(
432
+ fn=feedback,
433
+ inputs=[roll_input, stars_input, comment_input],
434
+ outputs=feedback_table,
435
+ )
436
+
437
 
438
  if __name__ == "__main__":
439
+ demo.queue().launch()