File size: 35,892 Bytes
e490f0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
"""tabUM, a 14M-parameter tabular foundation model: forecasting and prediction without training, on ZeroGPU."""
from __future__ import annotations

import html
import io
import os
import time

import gradio as gr
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import torch
from huggingface_hub import snapshot_download

import forecast as FC
import tables as TB
from examples import SERIES, TABLES
from tabum.inference import TabUMClassifier, TabUMRegressor
from tabum.model import TabUM

try:
    import spaces
    GPU = spaces.GPU(duration=60)
except ImportError:                                          # running locally
    GPU = lambda f: f

REPO = os.environ.get("TABUM_REPO", "helmo/tabum-v1.1")
DEVICE = os.environ.get("TABUM_DEVICE") or ("cuda" if torch.cuda.is_available() else "cpu")
MODEL = TabUM.from_pretrained(snapshot_download(REPO), device=DEVICE)
HERE = os.path.dirname(os.path.abspath(__file__))
SER = pd.read_parquet(os.path.join(HERE, "data", "series.parquet"))
TAB = {k: pd.read_parquet(os.path.join(HERE, "data", "tables", f"{k}.parquet")) for k in TABLES}

reg_factory = lambda ens: (lambda: TabUMRegressor(model=MODEL, device=DEVICE, n_ensemble=int(ens)))
clf_factory = lambda ens: (lambda: TabUMClassifier(model=MODEL, device=DEVICE, n_ensemble=int(ens)))

C = {"ink": "#14202e", "ink2": "#4b5a6d", "ink3": "#8593a5", "hist": "#64748b", "actual": "#14202e",
     "fc": "#e8590c", "band": "rgba(232,89,12,0.16)", "naive": "#7c8ba1", "tab": "#5b3fd6"}

# ------------------------------------------------------------------------------------------------ shared pieces
CSS = """
:root { --tu-bg:#f6f4f1; --tu-card:#ffffff; --tu-ink:#14202e; --tu-ink2:#4b5a6d; --tu-ink3:#8593a5; --tu-line:#e7e3dc;
        --tu-track:#f1ede7; --tu-fc:#e8590c; --tu-fc-soft:#fff1e8; --tu-tab:#5b3fd6; --tu-tab-soft:#f1edff;
        --tu-ok:#15803d; --tu-bad:#b91c1c; }
.gradio-container { max-width: 1240px !important; margin: 0 auto !important;
                    font-family: "Inter", -apple-system, "Segoe UI", sans-serif !important; }
#tu-hero { padding: 6px 2px 2px; }
#tu-hero h1 { font-size: 34px; font-weight: 800; letter-spacing: -0.02em; margin: 0; }
#tu-hero h1 .u { color: var(--tu-fc); }
#tu-hero p { color: var(--tu-ink2); font-size: 15.5px; margin: 4px 0 8px; max-width: 900px; }
.tu-chips { display:flex; gap:8px; flex-wrap:wrap; margin: 2px 0 6px; }
.tu-chip { font-size: 12.5px; border: 1px solid var(--tu-line); background: var(--tu-card); color: var(--tu-ink2);
           border-radius: 999px; padding: 3px 10px; text-decoration: none !important; }
.tu-chip b { color: var(--tu-ink); }
.tu-card { background: var(--tu-card); border: 1px solid var(--tu-line); border-radius: 14px; padding: 14px 16px;
           color: var(--tu-ink); }
.tu-card h3 { margin: 0 0 6px; font-size: 15px; }
.tu-blurb { background: var(--tu-fc-soft); border: 1px solid #fed7bf; color: #7c2d12; border-radius: 12px;
            padding: 10px 14px; font-size: 13.5px; line-height: 1.45; }
.tu-blurb.tab { background: var(--tu-tab-soft); border-color: #d9d0ff; color: #2e1f7a; }
.tu-blurb .credit { display:block; margin-top: 6px; font-size: 12px; opacity: .85; }
.tu-blurb a { color: inherit; text-decoration: underline; }
.tu-stats { display:grid; grid-template-columns: repeat(auto-fit, minmax(132px, 1fr)); gap: 10px; }
.tu-stat { background: var(--tu-card); border: 1px solid var(--tu-line); border-radius: 14px; padding: 12px 14px; color: var(--tu-ink); }
.tu-stat .k { font-size: 11.5px; text-transform: uppercase; letter-spacing: .06em; color: var(--tu-ink3); font-weight: 700; }
.tu-stat .v { font-size: 24px; font-weight: 800; letter-spacing: -0.01em; margin-top: 2px; }
.tu-stat .s { font-size: 12.5px; color: var(--tu-ink2); margin-top: 2px; }
.tu-stat.fc .v { color: var(--tu-fc); } .tu-stat.tab .v { color: var(--tu-tab); }
.tu-stat .good { color: var(--tu-ok); font-weight: 700; } .tu-stat .bad { color: var(--tu-bad); font-weight: 700; }
.tu-bars { display:flex; flex-direction:column; gap: 6px; }
.tu-bar { display:grid; grid-template-columns: minmax(120px, 230px) 1fr 52px; gap: 10px; align-items:center; font-size: 13px; color: var(--tu-ink); }
.tu-bar .t { display:block; height: 9px; border-radius: 6px; background: var(--tu-track); overflow:hidden; }
.tu-bar .f { display:block; height: 100%; border-radius: 6px; }
.tu-bar .n { font-family: ui-monospace, monospace; text-align:right; color: var(--tu-ink2); }
.tu-note { color: var(--tu-ink3); font-size: 12.5px; margin-top: 8px; line-height: 1.4; }
.tu-scroll { overflow-x: auto; }
.tu-card table, .tu-preview table, .tu-rows tr, .tu-rows th, .tu-rows td, .tu-tbl tr { border-left: 0 !important;
  border-right: 0 !important; }
.tu-card table, .tu-preview table { border-top: 0 !important; border-bottom: 0 !important; }
#tb-row th, #tb-row th * { white-space: nowrap !important; word-break: keep-all !important; overflow-wrap: normal !important; }
.tu-rows { width:100%; border-collapse: collapse; font-size: 13px; color: var(--tu-ink); margin: 0 !important;
           border: none !important; }
.tu-preview { max-height: 250px; overflow: auto; border: 1px solid var(--tu-line); border-radius: 12px; background: var(--tu-card); }
.tu-preview .tu-rows th { position: sticky; top: 0; background: var(--tu-card) !important; }
.tu-preview .tu-cap { font-size: 12px; color: var(--tu-ink3); padding: 8px 10px 0; }
.tu-rows th, .tu-rows td { border-left: none !important; border-right: none !important; border-top: none !important;
                           background: transparent !important; white-space: nowrap; }
.tu-rows td.v { font-family: ui-monospace, monospace; font-size: 12.5px; color: var(--tu-ink2); }
.tu-rows td.miss { color: var(--tu-ink3); font-style: italic; }
#fc-go { background: var(--tu-fc) !important; border: none !important; color: #fff !important; }
#tb-go { background: var(--tu-tab) !important; border: none !important; color: #fff !important; }
#tb-ask { border: 1.5px solid var(--tu-tab) !important; color: var(--tu-tab) !important; background: #fff !important; }
.tu-sec { font-size: 15px; font-weight: 800; color: var(--tu-ink); margin: 6px 0 -4px; }
.tu-rows th { text-align:left; font-size: 11px; text-transform: uppercase; letter-spacing: .05em; color: var(--tu-ink3);
              border-bottom: 1px solid var(--tu-line); padding: 6px 8px; }
.tu-rows td { border-bottom: 1px solid var(--tu-line); padding: 6px 8px; vertical-align: middle; }
.tu-rows .feat { color: var(--tu-ink2); font-size: 12px; max-width: 420px; }
.tu-ok { color: var(--tu-ok); font-weight: 800; } .tu-bad { color: var(--tu-bad); font-weight: 800; }
.tu-mini { display:inline-block; width: 56px; height: 7px; border-radius: 5px; background: var(--tu-track); vertical-align: middle; overflow: hidden; margin-right: 6px; }
.tu-mini i { display:block; height:100%; background: var(--tu-tab); border-radius: 5px; }
.tu-how { font-size: 14px; line-height: 1.55; color: var(--tu-ink); }
.tu-how code { font-size: 12.5px; }
.tu-tbl { border-collapse: collapse; font-size: 13.5px; margin: 0 !important; }
.tu-tbl th, .tu-tbl td { border-left: none !important; border-right: none !important; border-top: none !important;
                         background: transparent !important; }
.tu-tbl th, .tu-tbl td { padding: 6px 10px; border-bottom: 1px solid var(--tu-line); text-align: left; }
.tu-tbl td.num { font-family: ui-monospace, monospace; text-align: right; }
"""


def esc(x) -> str:
    return html.escape(str(x))


def fmt(v: float) -> str:
    if v is None or not np.isfinite(v):
        return "n/a"
    if float(v).is_integer() and abs(v) < 1e7:
        return f"{int(v):,}"
    a = abs(v)
    if a >= 1000:
        return f"{v:,.0f}"
    if a >= 10:
        return f"{v:,.1f}"
    if a >= 1:
        return f"{v:,.2f}"
    return f"{v:.3f}"


def bars(d: dict[str, float], color: str, top: int = 8, unit: str = "") -> str:
    items = list(d.items())[:top]
    if not items:
        return ""
    m = max(max(v for _, v in items), 1e-12)
    rows = "".join(
        f'<div class="tu-bar"><span>{esc(k)}</span><span class="t"><span class="f" style="width:{max(v, 0) / m * 100:.1f}%;'
        f'background:{color}"></span></span><span class="n">{max(v, 0) / m * 100:.0f}{unit}</span></div>' for k, v in items)
    return f'<div class="tu-bars">{rows}</div>'


def stat(k: str, v: str, s: str = "", cls: str = "") -> str:
    return f'<div class="tu-stat {cls}"><div class="k">{k}</div><div class="v">{v}</div><div class="s">{s}</div></div>'


def blurb(info: dict, cls: str = "") -> str:
    return (f'<div class="tu-blurb {cls}">{esc(info["blurb"])}<span class="credit">Data: {info["credit"]}</span></div>')


# ------------------------------------------------------------------------------------------------ forecasting
FC_CHOICES = [f'{v["icon"]} {v["title"]}' for v in SERIES.values()] + ["📤 Your own series (CSV)"]
FC_KEY = dict(zip(FC_CHOICES, list(SERIES) + ["own"]))
MODES = ["Backtest: hide the last stretch, then check", "Forecast past the end of the data"]


def series_names(key: str) -> list[str]:
    return sorted(SER[SER.dataset == key].series.unique(), key=lambda s: (("all departments" not in s), s)) if key != "own" else []


def get_series(key: str, name: str) -> pd.Series:
    g = SER[(SER.dataset == key) & (SER.series == name)]
    return pd.Series(g.value.to_numpy(float), index=pd.DatetimeIndex(g.time), name=name)


def read_own_series(file) -> pd.Series:
    if file is None:
        raise gr.Error("Upload a CSV with a date column and a value column.")
    df = pd.read_csv(file if isinstance(file, str) else file.name)
    tcol = next((c for c in df.columns if pd.to_datetime(df[c], errors="coerce").notna().mean() > 0.9
                 and not pd.api.types.is_numeric_dtype(df[c])), None)
    vcol = next((c for c in df.columns[::-1] if c != tcol and pd.api.types.is_numeric_dtype(df[c])), None)
    if tcol is None or vcol is None:
        raise gr.Error("Could not find a date column and a numeric value column in that CSV.")
    s = pd.Series(df[vcol].to_numpy(float), index=pd.to_datetime(df[tcol])).sort_index()
    s = s[~s.index.duplicated()]
    freq = pd.infer_freq(s.index[: min(len(s), 200)]) or (s.index.to_series().diff().mode().iloc[0])
    s = s.asfreq(freq)
    if len(s) < 60:
        raise gr.Error("The series needs at least 60 points.")
    s.name = f"{vcol} (uploaded)"
    return s


def unit_name(step: pd.Timedelta, n: int) -> str:
    if step >= pd.Timedelta("1D"):
        return f"{n} days" if n % 7 else f"{n // 7} weeks"
    hours = n * step / pd.Timedelta("1h")
    return f"{hours:.0f} hours" if hours < 48 or hours % 24 else f"{hours / 24:.0f} days"


def fc_plot(s: pd.Series, out: dict, unit: str, title: str) -> go.Figure:
    p = out["plan"]
    end = out["end"]
    show = max(3 * p.season, 3 * len(out["index"]))
    hist = s.iloc[max(0, end - show):end]
    idx = out["index"]
    T = lambda ix: [t.isoformat() for t in ix]          # plain lists: the browser's plotly does not read binary arrays
    L = lambda v: [None if not np.isfinite(x) else float(x) for x in np.asarray(v, float)]
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=T(hist.index), y=L(hist.values), name="history", line=dict(color=C["hist"], width=1.6)))
    fig.add_trace(go.Scatter(x=T(idx) + T(idx[::-1]), y=L(out[0.9]) + L(out[0.1][::-1]), fill="toself",
                             fillcolor=C["band"], line=dict(width=0), name="tabUM 80% range", hoverinfo="skip"))
    fig.add_trace(go.Scatter(x=T(idx), y=L(out["naive"]), name="repeat last season",
                             line=dict(color=C["naive"], width=1.4, dash="dot")))
    if "actual" in out:
        fig.add_trace(go.Scatter(x=T(idx), y=L(out["actual"]), name="what happened", line=dict(color=C["actual"], width=1.8)))
    fig.add_trace(go.Scatter(x=T(idx), y=L(out["median"]), name="tabUM forecast", line=dict(color=C["fc"], width=2.6)))
    fig.add_shape(type="line", x0=idx[0].isoformat(), x1=idx[0].isoformat(), y0=0, y1=1, yref="paper",
                  line=dict(color="#c9c2b8", width=1, dash="dash"))
    fig.update_layout(template="plotly_white", height=440, margin=dict(l=10, r=10, t=40, b=10),
                      title=dict(text=esc(title), font=dict(size=15, color=C["ink"]), x=0.01),
                      legend=dict(orientation="h", y=-0.12, x=0, xanchor="left", yanchor="top", font=dict(size=12)),
                      yaxis=dict(title=unit, gridcolor="#efebe5", zeroline=False), xaxis=dict(gridcolor="#f4f1ec"),
                      hovermode="x unified", paper_bgcolor="#ffffff", plot_bgcolor="#ffffff",
                      font=dict(family="Inter, -apple-system, Segoe UI, sans-serif", color=C["ink2"]))
    return fig


@GPU
def _fc_compute(s: pd.Series, horizon: int, context: int, backtest: bool, ens: int) -> dict:
    return FC.run(reg_factory(ens), s, horizon, context, backtest)


def fc_run(choice, name, mode, horizon, context, ens, file):
    key = FC_KEY[choice]
    if key == "own":
        s = read_own_series(file)
        unit, info = "value", None
    else:
        if not name:
            raise gr.Error("Pick a series.")
        s = get_series(key, name)
        info = SERIES[key]
        unit = info["unit"]
    backtest = mode == MODES[0]
    horizon = int(horizon)
    if len(s) < 2 * horizon + 30:
        raise gr.Error("This series is too short for that horizon.")
    out = _fc_compute(s, horizon, int(context), backtest, int(ens))
    step = s.index[1] - s.index[0]
    title = f"{s.name}: the next {unit_name(step, horizon)}" + (" (held back, then compared)" if backtest else "")
    fig = fc_plot(s, out, unit, title)
    sc = FC.scores(out)
    n_ctx = out["end"] - out["start"]
    cards = []
    if sc:
        gain = 1 - sc["tabum"] / max(sc["naive"], 1e-12)
        verdict = (f'<span class="good">{gain:.0%} lower error</span> than repeating the last season' if gain > 0
                   else f'<span class="bad">{-gain:.0%} higher error</span> than repeating the last season')
        cards += [stat("tabUM error (MAE)", fmt(sc["tabum"]), verdict, "fc"),
                  stat("Repeat last season", fmt(sc["naive"]), "the classic baseline: copy the last week (or day)"),
                  stat("80% range caught", f'{sc["coverage"]:.0%}', "of what happened fell inside the shaded band "
                       "(ideal: about 80%)"),
                  stat("Error vs level", f'{sc["wape"]:.1%}', "mean absolute error as a share of the mean level")]
    else:
        cards += [stat("Forecast", unit_name(step, horizon), "past the last data point", "fc")]
    cards.append(stat("Read in context", f"{n_ctx:,} rows", f"{int(ens)} view{'s' if int(ens) > 1 else ''}, "
                      f"{out['seconds']:.1f} s, no training"))
    stats = f'<div class="tu-stats">{"".join(cards)}</div>'
    p = out["plan"]
    imp = (f'<div class="tu-card"><h3>What the forecast leaned on</h3>{bars(out["importances"], C["fc"], unit="")}'
           f'<div class="tu-note">Each bar: how much the forecast moves when that column is removed from every row '
           f'(context and future alike), relative to the largest. Lags used: '
           f'{", ".join(FC.lag_label(f"lag{L}", p) for L in p.lags)}.</div></div>')
    return fig, stats, imp


def fc_dataset_changed(choice):
    key = FC_KEY[choice]
    if key == "own":
        return (gr.update(choices=[], value=None, visible=False), gr.update(visible=True),
                '<div class="tu-blurb">Upload a CSV with a date column and a numeric column (one row per time step, '
                'regular spacing; gaps are fine). Use <b>Backtest</b> to see how tabUM would have done on your last '
                'stretch.</div>', gr.update(), gr.update())
    names = series_names(key)
    info = SERIES[key]
    return (gr.update(choices=names, value=names[0], visible=True), gr.update(visible=False), blurb(info),
            gr.update(value=info["horizon"], maximum=max(info["horizon"] * 3, 60)), gr.update(value=info["context"]))


# ------------------------------------------------------------------------------------------------ tables
TB_CHOICES = [f'{v["icon"]} {v["title"]}' for v in TABLES.values()] + ["📤 Your own table (CSV)"]
TB_KEY = dict(zip(TB_CHOICES, list(TABLES) + ["own"]))
OWN: dict[str, pd.DataFrame] = {}


def tb_frame(choice, file) -> tuple[pd.DataFrame, str | None, dict | None]:
    key = TB_KEY[choice]
    if key != "own":
        return TAB[key], TABLES[key]["target"], TABLES[key]
    if file is None:
        raise gr.Error("Upload a CSV first.")
    path = file if isinstance(file, str) else file.name
    if path not in OWN:
        OWN.clear()
        OWN[path] = pd.read_csv(path)
    return OWN[path], None, None


def clean(df: pd.DataFrame) -> pd.DataFrame:
    """Missing cells as empty text, so the browser table shows them (JSON has no NaN)."""
    return df.astype(object).where(df.notna(), "")


def preview(df: pd.DataFrame, target: str | None, n: int = 8) -> str:
    cols = ([target] if target in df.columns else []) + [c for c in df.columns if c != target]
    cell = lambda v: ('<td class="v miss">missing</td>' if pd.isna(v) else
                      f'<td class="v">{esc(fmt(float(v)) if isinstance(v, (int, float, np.integer, np.floating)) else v)}</td>')
    head = "".join(f'<th>{"🎯 " if c == target else ""}{esc(c)}</th>' for c in cols)
    body = "".join("<tr>" + "".join(cell(r[c]) for c in cols) + "</tr>" for _, r in df.head(n).iterrows())
    return (f'<div class="tu-preview"><div class="tu-cap">{len(df):,} rows × {len(df.columns)} columns'
            f'{" · 🎯 = the column to predict" if target else ""}</div>'
            f'<table class="tu-rows"><tr>{head}</tr>{body}</table></div>')


def row_text(r: pd.Series, feats: list[str], k: int = 6) -> str:
    parts = []
    for c in feats[:k]:
        v = r[c]
        v = "missing" if pd.isna(v) else (fmt(float(v)) if isinstance(v, (int, float, np.floating, np.integer)) else str(v))
        parts.append(f"{esc(c)} <b>{esc(v)}</b>")
    return " · ".join(parts) + (" · …" if len(feats) > k else "")


@GPU
def _tb_compute(df, target, n_train, ens, extra=None):
    return TB.run(clf_factory(ens), reg_factory(ens), df, target, int(n_train), 400, extra=extra, baselines=False)


BASE_CACHE: dict = {}


def baselines(key, df, target, n_train):
    """The fitted baselines on the same split, on CPU, outside the GPU call; cached for the bundled examples."""
    ck = (key, target, int(n_train))
    if key == "own" or ck not in BASE_CACHE:
        tr, te = TB.split(df, target, int(n_train), 400)
        val = TB._baselines(tr, te, target, TB.is_regression(df[target]))
        if key == "own":
            return val
        BASE_CACHE[ck] = val
    return BASE_CACHE[ck]


def tb_run(choice, target_own, n_train, ens, file):
    df, target, info = tb_frame(choice, file)
    target = target or target_own
    if not target or target not in df.columns:
        raise gr.Error("Pick the column to predict.")
    if df[target].nunique() < 2:
        raise gr.Error("That column has a single value.")
    if not TB.is_regression(df[target]) and df[target].nunique() > 100:
        raise gr.Error("More than 100 classes: tabUM's limit. Pick another column.")
    res = _tb_compute(df, target, n_train, ens)
    res["baselines"] = baselines(TB_KEY[choice], df, target, n_train)
    reg = res["reg"]
    metric = "R²" if reg else "accuracy"
    b = res["baselines"]
    best_fit = max(b.values())
    rel = res["score"] - best_fit
    show = (lambda v: f"{v:.3f}") if reg else (lambda v: f"{v:.1%}")
    cards = [stat(f"tabUM {metric}", show(res["score"]),
                  f'{len(res["train"]):,} rows read in context, {res["seconds"]:.1f} s, no training', "tab"),
             stat(f"Linear model {metric}", show(b["linear"]), "fitted: " + ("ridge regression" if reg else "logistic regression")),
             stat(f"Gradient boosting {metric}", show(b["boosting"]), "fitted: scikit-learn HistGradientBoosting, defaults"),
             stat("Test rows", f'{len(res["test"]):,}', "never seen by any of the three")]
    stats = f'<div class="tu-stats">{"".join(cards)}</div>'
    test, feats = res["test"], res["features"]
    show_cols = feats[:5]
    cell = lambda v: ('<td class="v miss">missing</td>' if pd.isna(v) else
                      f'<td class="v">{esc(fmt(float(v)) if isinstance(v, (int, float, np.integer, np.floating)) else v)}</td>')
    rows = []
    for i in range(min(12, len(test))):
        r = test.iloc[i]
        cells = "".join(cell(r[c]) for c in show_cols)
        if reg:
            y = float(r[target]); p, lo, hi = res["pred"][i], res["lo"][i], res["hi"][i]
            ok = lo <= y <= hi
            rows.append(f'<tr>{cells}<td><b>{fmt(y)}</b></td><td>{fmt(p)}</td><td>{fmt(lo)} to {fmt(hi)}</td>'
                        f'<td class="{"tu-ok" if ok else "tu-bad"}">{"✓" if ok else "✗"}</td></tr>')
        else:
            y = str(r[target]); pr = res["proba"][i]; j = int(pr.argmax()); p = res["classes"][j]
            ok = p == y
            rows.append(f'<tr>{cells}<td><b>{esc(y)}</b></td><td>{esc(p)}</td>'
                        f'<td><span class="tu-mini"><i style="width:{pr[j] * 100:.0f}%"></i></span>{pr[j]:.0%}</td>'
                        f'<td class="{"tu-ok" if ok else "tu-bad"}">{"✓" if ok else "✗"}</td></tr>')
    fh = "".join(f"<th>{esc(c)}</th>" for c in show_cols)
    more = f" (first {len(show_cols)} of {len(feats)} columns)" if len(feats) > len(show_cols) else ""
    head = (f"<tr>{fh}<th>truth</th><th>tabUM</th><th>80% range</th><th>in range</th></tr>" if reg else
            f"<tr>{fh}<th>truth</th><th>tabUM</th><th>confidence</th><th>right</th></tr>")
    rows_html = (f'<div class="tu-card"><h3>Test rows{esc(more)}</h3><div class="tu-scroll"><table class="tu-rows">'
                 f'{head}{"".join(rows)}</table></div></div>')
    imp = (f'<div class="tu-card"><h3>What it leaned on</h3>{bars(res["importances"], C["tab"])}'
           f'<div class="tu-note">How much the predictions change when a column is removed from every row, relative to '
           f'the largest. Free here: tabUM has nothing to retrain.</div></div>')
    fig = None
    if reg:
        y = test[target].to_numpy(float)
        Lf = lambda v: [float(x) for x in np.asarray(v, float)]
        fig = go.Figure()
        fig.add_trace(go.Scatter(x=Lf(y), y=Lf(res["pred"]), mode="markers", name="test rows",
                                 marker=dict(color=C["tab"], size=6, opacity=0.55),
                                 error_y=dict(type="data", symmetric=False, array=Lf(res["hi"] - res["pred"]),
                                              arrayminus=Lf(res["pred"] - res["lo"]), color="rgba(91,63,214,0.18)",
                                              thickness=1)))
        lo_, hi_ = float(np.nanmin(y)), float(np.nanmax(y))
        fig.add_trace(go.Scatter(x=[lo_, hi_], y=[lo_, hi_], mode="lines", name="perfect", line=dict(color="#b9b2a8", dash="dash")))
        fig.update_layout(template="plotly_white", height=380, margin=dict(l=10, r=10, t=36, b=10),
                          title=dict(text="Predicted vs true, with the 80% range", font=dict(size=14), x=0.01),
                          xaxis_title=f"true {target}", yaxis_title="tabUM", showlegend=False,
                          font=dict(family="Inter, -apple-system, Segoe UI, sans-serif", color=C["ink2"]))
    first = clean(test.drop(columns=[target]).head(1))
    return stats, rows_html, imp, gr.update(value=fig, visible=reg), gr.update(value=first, col_count=(len(first.columns), "fixed"))


def tb_whatif(choice, target_own, n_train, ens, file, row):
    df, target, _ = tb_frame(choice, file)
    target = target or target_own
    if row is None or len(row) == 0:
        raise gr.Error("Run the table first.")
    extra = pd.DataFrame(row).head(1).copy()
    for c in extra.columns:
        if c in df.columns and pd.api.types.is_numeric_dtype(df[c]):
            extra[c] = pd.to_numeric(extra[c], errors="coerce")
        else:
            extra[c] = extra[c].map(lambda v: None if v is None or str(v).strip() in ("", "nan", "None") else str(v))
    extra = extra[[c for c in df.columns if c != target]]
    res = _tb_compute(df, target, n_train, ens, extra=extra)
    e = res["extra"]
    if res["reg"]:
        rng = "80% range " + fmt(e["lo"]) + " to " + fmt(e["hi"])
        return (f'<div class="tu-card"><h3>tabUM says</h3><div class="tu-stats">'
                f'{stat(target, fmt(e["pred"]), rng, "tab")}</div>'
                f'<div class="tu-note">Change any value above (or blank it: missing is allowed) and predict again.</div></div>')
    order = np.argsort(-e["proba"])
    dist = {res["classes"][j]: float(e["proba"][j]) for j in order[:8]}
    m = sum(dist.values()) or 1
    probs = "".join(
        f'<div class="tu-bar"><span><b>{esc(k)}</b></span><span class="t"><span class="f" style="width:{v * 100:.1f}%;'
        f'background:{C["tab"]}"></span></span><span class="n">{v:.0%}</span></div>' for k, v in dist.items())
    tr = res["train"]
    nb = "".join(f'<tr><td>{w:.0%}</td><td><b>{esc(tr.iloc[int(i)][target])}</b></td><td class="feat">'
                 f'{row_text(tr.iloc[int(i)], res["features"])}</td></tr>' for i, w in zip(e["neighbors"], e["weights"]))
    return (f'<div class="tu-card"><h3>tabUM says</h3><div class="tu-bars">{probs}</div>'
            f'<h3 style="margin-top:14px">The training rows it weighted most</h3><table class="tu-rows">'
            f'<tr><th>weight</th><th>label</th><th>row</th></tr>{nb}</table>'
            f'<div class="tu-note">These are the actual votes the classifier counted (its retrieval head attends over all '
            f'context rows; the top five are shown). Change any value above, or blank it, and predict again.</div></div>')


def tb_dataset_changed(choice):
    key = TB_KEY[choice]
    if key == "own":
        return (gr.update(visible=True), gr.update(visible=True, choices=[], value=None),
                '<div class="tu-blurb tab">Upload a CSV, then pick the column to predict. Text columns are read as '
                'categories, empty cells as missing; up to 100 classes or any numeric target.</div>', None,
                gr.update(), "")
    info = TABLES[key]
    return (gr.update(visible=False), gr.update(visible=False), blurb(info, "tab"), preview(TAB[key], info["target"]),
            gr.update(value=info.get("ens", 4)), "")


def tb_auto(choice, target_own, n_train, ens, file):
    if TB_KEY[choice] == "own":
        return "", "", "", gr.update(visible=False), gr.update(value=None)
    return tb_run(choice, target_own, n_train, ens, file)


def fc_auto(choice, name, mode, horizon, context, ens, file):
    if FC_KEY[choice] == "own" and file is None:
        return None, "", ""
    return fc_run(choice, name, mode, horizon, context, ens, file)


def tb_file_changed(file):
    if file is None:
        return gr.update(choices=[], value=None), None
    df = pd.read_csv(file if isinstance(file, str) else file.name)
    OWN.clear(); OWN[file if isinstance(file, str) else file.name] = df
    return gr.update(choices=list(df.columns), value=df.columns[-1]), preview(df, None)


def _warm():
    for k, info in TABLES.items():
        try:
            baselines(k, TAB[k], info["target"], 2000)
        except Exception as e:                                   # a cache miss later just recomputes
            print("baseline warm-up failed for", k, e)


import threading
threading.Thread(target=_warm, daemon=True).start()

# ------------------------------------------------------------------------------------------------ about
ABOUT = f"""
<div class="tu-how">
<div class="tu-card"><h3>What tabUM is</h3>
A 14.3M-parameter transformer pretrained only on synthetic tables (causal graphs, Gaussian processes, random trees).
It never trains on your data: <code>fit()</code> stores the rows and <code>predict()</code> runs one forward pass in
which every new row attends to every stored row. That is <b>in-context learning</b> for tables: classification up to 100
classes, regression with a full distribution, missing values read as they are.
</div><br>
<div class="tu-card"><h3>How a table model forecasts</h3>
tabUM does not know about time: it reads the rows as an unordered set. So time goes into columns. Every past step is a
row with its <b>position in time</b> (daily data), the <b>calendar</b> (hour, weekday, time of year, as numbers and as sine/cosine
pairs so 23:00 sits next to midnight) and <b>seasonal lags</b> (the value one, two, three and four weeks or days
earlier, only lags at least as long as the horizon, so each one is already known). Every future step is a row with
the same columns and no value. One forward pass fills in the whole horizon, with an 80% range from the predicted
distribution. The idea follows TabPFN-TS (Hoo et al., 2025), which showed a tabular foundation model can forecast well
this way.<br><br>
The baseline, <b>repeat last season</b> (copy the last week for hourly data, the last week of days for daily data), is
hard to beat on regular series; it is the standard yardstick.
</div><br>
<div class="tu-card"><h3>TabArena-v0.1, 51 datasets (self-run: at most 2,000 train / 1,000 test rows, seed 0)</h3>
<table class="tu-tbl"><tr><th>model</th><th>params</th><th>classification accuracy (38)</th><th>regression R² (13)</th></tr>
<tr><td>logistic / linear regression (fitted)</td><td></td><td class="num">0.8417</td><td class="num">0.5597</td></tr>
<tr><td>tabUM zero-shot, 1 pass</td><td>14M</td><td class="num">0.8523</td><td class="num">0.6284</td></tr>
<tr><td>tabUM zero-shot, 8-view ensemble</td><td>14M</td><td class="num">0.8581</td><td class="num">0.6519</td></tr>
<tr><td><b>tabUM finetune() + 8 views</b></td><td>14M</td><td class="num"><b>0.8635</b></td><td class="num"><b>0.6907</b></td></tr>
<tr><td>HistGradientBoosting (fitted, default)</td><td></td><td class="num">0.8669</td><td class="num">0.7091</td></tr>
<tr><td>TabPFN v2 (zero-shot)</td><td>~11M</td><td class="num">0.8768</td><td class="num">0.7471</td></tr>
<tr><td>TabICL (zero-shot)</td><td>~500M</td><td class="num">0.8801</td><td class="num">n/a</td></tr></table>
<div class="tu-note">This Space runs tabUM zero-shot (no finetune()). Model card:
<a href="https://huggingface.co/{REPO}" target="_blank">{REPO}</a> · code and per-dataset results:
<a href="https://github.com/heldernoid/tabum" target="_blank">github.com/heldernoid/tabum</a>.</div>
</div><br>
<div class="tu-card"><h3>Data credits</h3><ul>
{"".join(f'<li><b>{esc(v["title"])}</b>: {v["credit"]}</li>' for v in SERIES.values())}
{"".join(f'<li><b>{esc(v["title"])}</b>: {v["credit"]}</li>' for v in TABLES.values())}
</ul></div>
</div>
"""

HERO = f"""
<div id="tu-hero">
<h1>tab<span class="u">UM</span></h1>
<p>A 14M-parameter tabular foundation model. Give it rows, it predicts new ones in a single forward pass, with no
training: forecasts with a range, classes with probabilities, prices with a distribution.</p>
<div class="tu-chips">
<a class="tu-chip" href="https://huggingface.co/{REPO}" target="_blank">🤗 <b>{REPO}</b></a>
<a class="tu-chip" href="https://github.com/heldernoid/tabum" target="_blank">💻 <b>code</b> · MIT</a>
<span class="tu-chip">📊 TabArena-v0.1: <b>0.858</b> accuracy zero-shot</span>
<span class="tu-chip">🔢 up to <b>100 classes</b> · <b>2,000 features</b> · missing values native</span>
</div></div>
"""

# ------------------------------------------------------------------------------------------------ layout
with gr.Blocks(title="tabUM: forecasting and prediction in one pass", css=CSS, theme=gr.themes.Base()) as demo:
    gr.HTML(HERO)
    with gr.Tab("📈 Forecast"):
        with gr.Row():
            with gr.Column(scale=4, min_width=320):
                fc_choice = gr.Radio(FC_CHOICES, value=FC_CHOICES[0], label="Example", elem_id="fc-choice")
                fc_series = gr.Dropdown(series_names("walmart"), value=series_names("walmart")[0], label="Series")
                fc_file = gr.File(label="CSV: a date column and a value column", file_types=[".csv"], visible=False)
                fc_mode = gr.Radio(MODES, value=MODES[0], label="Mode")
                with gr.Accordion("Settings", open=False):
                    fc_h = gr.Slider(7, 336, value=SERIES["walmart"]["horizon"], step=1, label="Horizon (steps ahead)")
                    fc_ctx = gr.Slider(200, 6000, value=SERIES["walmart"]["context"], step=100,
                                       label="History rows read in context")
                    fc_ens = gr.Radio([1, 4, 8], value=4, label="Ensemble views (more: steadier, slower)")
                fc_go = gr.Button("Forecast", variant="primary", elem_id="fc-go")
            with gr.Column(scale=8):
                fc_blurb = gr.HTML(blurb(SERIES["walmart"]))
                fc_fig = gr.Plot(show_label=False)
                fc_stats = gr.HTML()
                fc_imp = gr.HTML()
    with gr.Tab("🧮 Tables"):
        with gr.Row():
            with gr.Column(scale=4, min_width=320):
                tb_choice = gr.Radio(TB_CHOICES, value=TB_CHOICES[0], label="Example")
                tb_file = gr.File(label="Your CSV", file_types=[".csv"], visible=False)
                tb_target = gr.Dropdown([], label="Column to predict", visible=False)
                with gr.Accordion("Settings", open=False):
                    tb_n = gr.Slider(50, 3000, value=2000, step=50, label="Training rows read in context")
                    tb_ens = gr.Radio([1, 4, 8], value=4, label="Ensemble views")
                tb_go = gr.Button("Predict the test rows", variant="primary", elem_id="tb-go")
            with gr.Column(scale=8):
                tb_blurb = gr.HTML(blurb(TABLES["titanic"], "tab"))
                tb_preview = gr.HTML(preview(TAB["titanic"], "survived"))
                tb_stats = gr.HTML()
                tb_fig = gr.Plot(show_label=False, visible=False)
                tb_rows = gr.HTML()
                tb_imp = gr.HTML()
                gr.HTML('<div class="tu-sec">Try your own row</div><div class="tu-note">A test row, ready to edit: change '
                        'any cell, or clear it (missing is fine), then ask tabUM.</div>')
                tb_row = gr.Dataframe(value=clean(TB.split(TAB["titanic"], "survived", 2000, 400)[1]
                                                  .drop(columns=["survived"]).head(1)),
                                      interactive=True, label="One row", show_label=False, row_count=(1, "fixed"),
                                      elem_id="tb-row")
                tb_ask = gr.Button("Predict this row", elem_id="tb-ask")
                tb_answer = gr.HTML()
    with gr.Tab("ℹ️ About"):
        gr.HTML(ABOUT)

    fc_inputs = [fc_choice, fc_series, fc_mode, fc_h, fc_ctx, fc_ens, fc_file]
    fc_outputs = [fc_fig, fc_stats, fc_imp]
    fc_choice.change(fc_dataset_changed, fc_choice, [fc_series, fc_file, fc_blurb, fc_h, fc_ctx]).then(
        fc_auto, fc_inputs, fc_outputs)
    for ev in (fc_go.click, fc_series.input, fc_mode.change):
        ev(fc_run, fc_inputs, fc_outputs)
    fc_file.upload(fc_run, fc_inputs, fc_outputs)

    tb_inputs = [tb_choice, tb_target, tb_n, tb_ens, tb_file]
    tb_outputs = [tb_stats, tb_rows, tb_imp, tb_fig, tb_row]
    tb_choice.change(tb_dataset_changed, tb_choice, [tb_file, tb_target, tb_blurb, tb_preview, tb_ens, tb_answer]).then(
        tb_auto, tb_inputs, tb_outputs)
    tb_file.upload(tb_file_changed, tb_file, [tb_target, tb_preview])
    tb_go.click(tb_run, tb_inputs, tb_outputs)
    tb_ask.click(tb_whatif, tb_inputs + [tb_row], tb_answer)
    demo.load(fc_run, fc_inputs, fc_outputs).then(tb_run, tb_inputs, tb_outputs)

if __name__ == "__main__":
    demo.launch()