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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import hashlib
|
| 4 |
+
import requests
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import matplotlib
|
| 8 |
+
matplotlib.use("Agg")
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
from PIL import Image
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn as nn
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
import torchvision
|
| 16 |
+
import gradio as gr
|
| 17 |
+
|
| 18 |
+
# 1. Personal settings (derived identically to Notebook 2 for roll 2415800016)
|
| 19 |
+
ROLL = "2415800016"
|
| 20 |
+
h = int(hashlib.sha256(ROLL.encode()).hexdigest(), 16)
|
| 21 |
+
SEED = h % 100000
|
| 22 |
+
LATENT = [3, 4, 5, 6][(h >> 4) & 3]
|
| 23 |
+
|
| 24 |
+
CITIES = [
|
| 25 |
+
("Chennai", 13.0827, 80.2707), ("Mumbai", 19.0760, 72.8777), ("Kolkata", 22.5726, 88.3639),
|
| 26 |
+
("Delhi", 28.6139, 77.2090), ("Bengaluru", 12.9716, 77.5946), ("Hyderabad", 17.3850, 78.4867),
|
| 27 |
+
("Kochi", 9.9312, 76.2673), ("Bhubaneswar", 20.2961, 85.8245), ("Visakhapatnam", 17.6868, 83.2185),
|
| 28 |
+
("Ahmedabad", 23.0225, 72.5714), ("Jaipur", 26.9124, 75.7873), ("Guwahati", 26.1445, 91.7362),
|
| 29 |
+
("Lucknow", 26.8467, 80.9462), ("Pune", 18.5204, 73.8567), ("Madurai", 9.9252, 78.1198),
|
| 30 |
+
("Coimbatore", 11.0168, 76.9558)
|
| 31 |
+
]
|
| 32 |
+
CITY, LAT, LON = CITIES[(h >> 24) % len(CITIES)]
|
| 33 |
+
WINDOW = [5, 7, 10][(h >> 30) % 3]
|
| 34 |
+
DEV = "cuda" if torch.cuda.is_available() else "cpu"
|
| 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 |
+
te = torchvision.datasets.MNIST("data", train=False, download=True)
|
| 54 |
+
Xte = (te.data.float() / 255.0).unsqueeze(1)
|
| 55 |
+
|
| 56 |
+
dae = AE().to(DEV)
|
| 57 |
+
ck = f"dae_{ROLL}.pt"
|
| 58 |
+
if os.path.exists(ck):
|
| 59 |
+
dae.load_state_dict(torch.load(ck, map_location=DEV))
|
| 60 |
+
else:
|
| 61 |
+
torch.manual_seed(SEED)
|
| 62 |
+
tr = torchvision.datasets.MNIST("data", train=True, download=True)
|
| 63 |
+
Xtr = (tr.data.float() / 255.0).unsqueeze(1).to(DEV)
|
| 64 |
+
opt = torch.optim.Adam(dae.parameters(), 1e-3)
|
| 65 |
+
for ep in range(3):
|
| 66 |
+
for i in range(0, len(Xtr), 256):
|
| 67 |
+
x = Xtr[i:i + 256]
|
| 68 |
+
loss = F.mse_loss(dae((x + 0.5 * torch.randn_like(x)).clamp(0, 1))[0], x)
|
| 69 |
+
opt.zero_grad()
|
| 70 |
+
loss.backward()
|
| 71 |
+
opt.step()
|
| 72 |
+
torch.save(dae.state_dict(), ck)
|
| 73 |
+
dae.eval()
|
| 74 |
+
|
| 75 |
+
def to28(img):
|
| 76 |
+
a = np.asarray(Image.fromarray(img).convert("L").resize((28, 28)), dtype=np.float32) / 255.0
|
| 77 |
+
if a.mean() > 0.5:
|
| 78 |
+
a = 1.0 - a
|
| 79 |
+
return torch.tensor(a)[None, None]
|
| 80 |
+
|
| 81 |
+
big = lambda t: (t[0, 0].clamp(0, 1).numpy() * 255).astype(np.uint8).repeat(8, 0).repeat(8, 1)
|
| 82 |
+
|
| 83 |
+
def denoise(img, idx, sigma):
|
| 84 |
+
x = to28(img) if img is not None else Xte[int(idx)][None]
|
| 85 |
+
g = torch.Generator().manual_seed(0)
|
| 86 |
+
xn = (x + sigma * torch.randn(x.shape, generator=g)).clamp(0, 1)
|
| 87 |
+
with torch.no_grad():
|
| 88 |
+
y = dae(xn.to(DEV))[0].cpu()
|
| 89 |
+
return big(x), big(xn), big(y)
|
| 90 |
+
|
| 91 |
+
# 3. Weather Anomaly Model & Threshold (Tab 2)
|
| 92 |
+
VARS = ["temperature_2m_max", "temperature_2m_min", "precipitation_sum", "wind_speed_10m_max", "wind_gusts_10m_max"]
|
| 93 |
+
ATTRIB = "Weather data by Open-Meteo.com (CC BY 4.0)"
|
| 94 |
+
|
| 95 |
+
def open_meteo(url, **params):
|
| 96 |
+
r = requests.get(url, params=params, timeout=90)
|
| 97 |
+
r.raise_for_status()
|
| 98 |
+
j = r.json()
|
| 99 |
+
df = pd.DataFrame(j["daily"])
|
| 100 |
+
df["time"] = pd.to_datetime(df["time"])
|
| 101 |
+
return df.set_index("time")[VARS].ffill().bfill(), j.get("daily_units", {})
|
| 102 |
+
|
| 103 |
+
def transform(df):
|
| 104 |
+
X = df[VARS].copy()
|
| 105 |
+
X["precipitation_sum"] = np.log1p(X["precipitation_sum"].clip(lower=0))
|
| 106 |
+
return X
|
| 107 |
+
|
| 108 |
+
hist, _ = open_meteo(
|
| 109 |
+
"https://archive-api.open-meteo.com/v1/archive",
|
| 110 |
+
latitude=LAT, longitude=LON,
|
| 111 |
+
start_date="1991-01-01", end_date="2024-12-31",
|
| 112 |
+
daily=",".join(VARS), timezone="Asia/Kolkata"
|
| 113 |
+
)
|
| 114 |
+
T = transform(hist)
|
| 115 |
+
tr_mask = T.index.year <= 2014
|
| 116 |
+
mu = T[tr_mask].groupby(T[tr_mask].index.month).mean()
|
| 117 |
+
sd = T[tr_mask].groupby(T[tr_mask].index.month).std() + 1e-6
|
| 118 |
+
|
| 119 |
+
def standardize(T_df):
|
| 120 |
+
m = T_df.index.month
|
| 121 |
+
return (T_df - mu.loc[m].values) / sd.loc[m].values
|
| 122 |
+
|
| 123 |
+
def windows(S, W=WINDOW):
|
| 124 |
+
a = S.values.astype(np.float32)
|
| 125 |
+
n = len(a) - W + 1
|
| 126 |
+
return np.stack([a[i:i + W].ravel() for i in range(n)]), S.index[:n]
|
| 127 |
+
|
| 128 |
+
Xw, starts = windows(standardize(T))
|
| 129 |
+
Xw_t = torch.tensor(Xw, device=DEV)
|
| 130 |
+
train_w = Xw_t[torch.tensor(starts.year <= 2014)]
|
| 131 |
+
D = Xw.shape[1]
|
| 132 |
+
|
| 133 |
+
torch.manual_seed(SEED)
|
| 134 |
+
wae = nn.Sequential(
|
| 135 |
+
nn.Linear(D, 32), nn.ReLU(), nn.Linear(32, 6),
|
| 136 |
+
nn.Linear(6, 32), nn.ReLU(), nn.Linear(32, D)
|
| 137 |
+
).to(DEV)
|
| 138 |
+
opt_w = torch.optim.Adam(wae.parameters(), 1e-3)
|
| 139 |
+
for ep in range(40):
|
| 140 |
+
perm = torch.randperm(len(train_w), device=DEV)
|
| 141 |
+
for i in range(0, len(perm), 256):
|
| 142 |
+
x = train_w[perm[i:i + 256]]
|
| 143 |
+
loss = F.mse_loss(wae(x), x)
|
| 144 |
+
opt_w.zero_grad()
|
| 145 |
+
loss.backward()
|
| 146 |
+
opt_w.step()
|
| 147 |
+
wae.eval()
|
| 148 |
+
with torch.no_grad():
|
| 149 |
+
err = ((wae(Xw_t) - Xw_t) ** 2).view(len(Xw), WINDOW, len(VARS)).cpu().numpy()
|
| 150 |
+
score = err.mean((1, 2))
|
| 151 |
+
THRESH = float(np.quantile(score[starts.year <= 2014], 0.99))
|
| 152 |
+
|
| 153 |
+
def live_window():
|
| 154 |
+
live, _ = open_meteo(
|
| 155 |
+
"https://api.open-meteo.com/v1/forecast",
|
| 156 |
+
latitude=LAT, longitude=LON,
|
| 157 |
+
daily=",".join(VARS), timezone="Asia/Kolkata",
|
| 158 |
+
past_days=WINDOW, forecast_days=1
|
| 159 |
+
)
|
| 160 |
+
return live.tail(WINDOW)
|
| 161 |
+
|
| 162 |
+
def live_score():
|
| 163 |
+
lw = live_window()
|
| 164 |
+
x = torch.tensor(standardize(transform(lw)).values.astype(np.float32).ravel()[None], device=DEV)
|
| 165 |
+
with torch.no_grad():
|
| 166 |
+
s = F.mse_loss(wae(x), x).item()
|
| 167 |
+
return s, lw
|
| 168 |
+
|
| 169 |
+
def weather():
|
| 170 |
+
s, lw = live_score()
|
| 171 |
+
fig, ax = plt.subplots(figsize=(6, 2.6))
|
| 172 |
+
ax.bar(lw.index.strftime("%d %b"), lw.precipitation_sum, color="tab:blue")
|
| 173 |
+
ax2 = ax.twinx()
|
| 174 |
+
ax2.plot(lw.index.strftime("%d %b"), lw.temperature_2m_max, "r-o")
|
| 175 |
+
ax.set_ylabel("rain mm")
|
| 176 |
+
ax2.set_ylabel("Tmax °C")
|
| 177 |
+
ax.set_title(ATTRIB, fontsize=8)
|
| 178 |
+
plt.tight_layout()
|
| 179 |
+
verdict = f"**{CITY}**, last {WINDOW} days: score **{s:.3f}** vs threshold {THRESH:.3f} → " + (
|
| 180 |
+
"⚠️ **UNUSUAL**" if s > THRESH else "✅ normal"
|
| 181 |
+
)
|
| 182 |
+
return verdict, fig
|
| 183 |
+
|
| 184 |
+
# 4. Feedback Logger (Tab 3)
|
| 185 |
+
FB = f"feedback_{ROLL}.csv"
|
| 186 |
+
|
| 187 |
+
def feedback(roll, stars, comment):
|
| 188 |
+
row = pd.DataFrame([{
|
| 189 |
+
"time": time.strftime("%Y-%m-%d %H:%M"),
|
| 190 |
+
"visitor_roll": str(roll).strip().upper(),
|
| 191 |
+
"stars": stars,
|
| 192 |
+
"comment": comment
|
| 193 |
+
}])
|
| 194 |
+
df = pd.concat([pd.read_csv(FB), row], ignore_index=True) if os.path.exists(FB) else row
|
| 195 |
+
df.to_csv(FB, index=False)
|
| 196 |
+
return df
|
| 197 |
+
|
| 198 |
+
# 5. Gradio Interface
|
| 199 |
+
with gr.Blocks(title=f"{ROLL} · Autoencoder app") as demo:
|
| 200 |
+
gr.Markdown(f"# 🧠 {ROLL}'s Autoencoder App\nBuilt in LearnLab Module 3")
|
| 201 |
+
with gr.Tab("Denoiser"):
|
| 202 |
+
with gr.Row():
|
| 203 |
+
inp = gr.Image(type="numpy", label="Upload a digit photo (optional)")
|
| 204 |
+
with gr.Column():
|
| 205 |
+
idx = gr.Slider(0, len(Xte) - 1, value=7, step=1, label="…or pick MNIST test image #")
|
| 206 |
+
sig = gr.Slider(0, 1, value=0.5, step=0.05, label="noise σ")
|
| 207 |
+
b1 = gr.Button("Denoise", variant="primary")
|
| 208 |
+
with gr.Row():
|
| 209 |
+
o1 = gr.Image(label="clean")
|
| 210 |
+
o2 = gr.Image(label="noisy")
|
| 211 |
+
o3 = gr.Image(label="denoised")
|
| 212 |
+
b1.click(denoise, [inp, idx, sig], [o1, o2, o3])
|
| 213 |
+
|
| 214 |
+
with gr.Tab(f"Weather alarm · {CITY}"):
|
| 215 |
+
b2 = gr.Button("Check the last days (live Open-Meteo)", variant="primary")
|
| 216 |
+
v = gr.Markdown()
|
| 217 |
+
p = gr.Plot()
|
| 218 |
+
b2.click(weather, None, [v, p])
|
| 219 |
+
|
| 220 |
+
with gr.Tab("Feedback"):
|
| 221 |
+
r_ = gr.Textbox(label="Your roll number")
|
| 222 |
+
st = gr.Slider(1, 5, value=4, step=1, label="Stars")
|
| 223 |
+
cm = gr.Textbox(label="Comment")
|
| 224 |
+
b3 = gr.Button("Submit")
|
| 225 |
+
tbl = gr.Dataframe()
|
| 226 |
+
b3.click(feedback, [r_, st, cm], tbl)
|
| 227 |
+
|
| 228 |
+
if __name__ == "__main__":
|
| 229 |
+
demo.launch()
|
dae_2415800016.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:df64db8fcaa31af534c0d5a5f0fbe871d1a47010b3780537251c9f93a71d9cde
|
| 3 |
+
size 1748989
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
pandas
|
| 4 |
+
requests
|
| 5 |
+
matplotlib
|
| 6 |
+
pillow
|
| 7 |
+
gradio
|