File size: 37,156 Bytes
d74a1c3
 
24a1d45
62ec2a2
d74a1c3
 
24a1d45
 
 
 
cdbdc4e
c338911
 
 
 
 
 
c1e7f62
c338911
 
c1e7f62
c338911
733e7ab
 
 
c338911
 
 
 
 
 
c1e7f62
c338911
 
c1e7f62
c338911
733e7ab
 
af37f41
 
 
 
 
 
cdbdc4e
24a1d45
733e7ab
62ec2a2
cdbdc4e
a383814
 
 
 
 
 
 
c1e7f62
a383814
 
c1e7f62
c338911
a383814
 
 
 
 
 
 
 
c1e7f62
a383814
 
c1e7f62
c338911
a383814
 
 
 
 
 
 
 
c1e7f62
a383814
 
c1e7f62
c338911
a383814
cdbdc4e
 
7798619
a383814
af37f41
a383814
7798619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a1d45
733e7ab
24a1d45
733e7ab
cdbdc4e
bf6c8de
cdbdc4e
bf6c8de
733e7ab
bf6c8de
733e7ab
cdbdc4e
bf6c8de
af37f41
ecb8eec
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ec2a2
af37f41
62ec2a2
 
 
 
 
af37f41
 
 
 
 
 
 
e70cead
 
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
62ec2a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af37f41
 
 
 
62ec2a2
 
af37f41
 
 
7798619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fb339e
 
24a1d45
20096cc
836f057
20096cc
 
 
 
 
 
 
836f057
20096cc
 
6a3a5e7
af37f41
 
20096cc
 
 
 
 
 
 
e70cead
20096cc
 
 
 
 
 
 
7798619
 
 
 
 
20096cc
 
 
5fb339e
7798619
 
 
 
 
 
 
 
 
 
 
 
 
 
5fb339e
7798619
 
 
 
5fb339e
20096cc
af37f41
20096cc
e70cead
20096cc
e70cead
7798619
 
 
 
5fb339e
e70cead
 
 
 
7798619
5fb339e
e70cead
 
 
7798619
5fb339e
af37f41
e70cead
7798619
20096cc
 
 
 
ecb8eec
7798619
ecb8eec
7798619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecb8eec
836f057
 
 
 
af37f41
836f057
24a1d45
 
af37f41
 
 
 
 
 
 
62ec2a2
af37f41
7798619
 
 
 
af37f41
 
ecb8eec
 
af37f41
e70cead
af37f41
 
 
e70cead
af37f41
3acd4b8
af37f41
 
 
ecb8eec
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62ec2a2
 
af37f41
 
 
e70cead
ecb8eec
af37f41
 
 
7798619
5fb339e
ecb8eec
5fb339e
7798619
af37f41
 
 
 
 
 
 
ecb8eec
7798619
 
ecb8eec
7798619
ecb8eec
7798619
 
3acd4b8
7798619
e70cead
7798619
e70cead
7798619
 
 
 
 
 
 
ecb8eec
7798619
 
ecb8eec
7798619
ecb8eec
7798619
 
3acd4b8
7798619
 
 
 
ecb8eec
7798619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24a1d45
7798619
af37f41
7798619
3acd4b8
836f057
e70cead
 
 
 
 
af37f41
ecb8eec
af37f41
 
62ec2a2
af37f41
 
 
 
24a1d45
af37f41
 
 
 
 
 
 
 
7798619
af37f41
 
7798619
 
 
 
 
 
af37f41
7798619
af37f41
7798619
af37f41
 
 
 
 
 
 
 
 
ecb8eec
af37f41
 
7798619
e70cead
7798619
 
 
af37f41
3acd4b8
7798619
af37f41
7798619
24a1d45
836f057
 
 
 
24a1d45
af37f41
 
24a1d45
 
af37f41
24a1d45
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecb8eec
 
 
af37f41
62ec2a2
af37f41
 
 
62ec2a2
 
 
 
ecb8eec
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7798619
24a1d45
836f057
af37f41
 
5fb339e
af37f41
ecb8eec
 
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a3a5e7
af37f41
 
 
 
 
 
 
 
5fb339e
7798619
5fb339e
ecb8eec
 
7798619
5fb339e
7798619
af37f41
7798619
 
af37f41
7798619
5fb339e
7798619
5fb339e
7798619
ecb8eec
 
 
 
 
7798619
 
 
 
 
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7798619
8a03aea
af37f41
 
 
 
 
 
 
 
 
 
 
 
e70cead
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecb8eec
7798619
af37f41
 
 
 
5fb339e
af37f41
 
e70cead
af37f41
 
 
 
 
 
 
 
 
 
 
 
 
8a03aea
7798619
 
ecb8eec
7798619
8a03aea
af37f41
 
 
 
 
 
 
 
5fb339e
af37f41
 
 
7798619
af37f41
 
3acd4b8
62ec2a2
af37f41
 
 
 
 
 
 
 
 
 
 
7798619
af37f41
 
 
 
 
 
 
 
 
8a03aea
 
7798619
 
 
 
8a03aea
 
af37f41
3acd4b8
7798619
 
af37f41
7798619
 
 
 
836f057
 
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import poisson, nbinom, gamma, lognorm, kstest
import gradio as gr

# =========================
# Stat mapping & milestones
# =========================

STAT_MAP = {
    "pass_att":   "att",
    "pass_yds":   "pass_yds",
    "pass_td":    "pass_td",
    "rush_att":   "rush_att",
    "rush_yds":   "rush_yds",
    "rush_td":    "rush_td",
    "targets":    "targets",
    "receptions": "receptions",
    "rec_yds":    "rec_yds",
    "rec_td":     "rec_td",
    "fg_made":    "fg_made",
}

STAT_LABELS = {
    "pass_att":   "Pass Attempts",
    "pass_yds":   "Passing Yards",
    "pass_td":    "Passing TDs",
    "rush_att":   "Rush Attempts",
    "rush_yds":   "Rushing Yards",
    "rush_td":    "Rushing TDs",
    "targets":    "Targets",
    "receptions": "Receptions",
    "rec_yds":    "Receiving Yards",
    "rec_td":     "Receiving TDs",
    "fg_made":    "Field Goals Made",
}

STAT_OPTIONS = [
    "pass_att", "pass_yds", "pass_td",
    "rush_att", "rush_yds", "rush_td",
    "targets", "receptions", "rec_yds", "rec_td",
    "fg_made",
]

TIMEFRAMES = {"Game": "", "1H": "_1h", "1Q": "_1q"}

# Timeframe-specific milestones
NFL_MILESTONES = {
    "Game": {
        "pass_att":  [15, 20, 25, 30, 35, 40, 45, 50],
        "pass_yds":  [150, 200, 225, 250, 275, 300, 325, 350, 400],
        "pass_td":   [1, 2, 3, 4, 5],
        "rush_att":  [8, 10, 12, 14, 16, 18, 20, 22],
        "rush_yds":  [25, 40, 50, 60, 75, 80, 90, 100, 110, 125, 150],
        "rush_td":   [1, 2, 3],
        "targets":   [4, 6, 8, 10, 12],
        "receptions":[3, 4, 5, 6, 7, 8, 9, 10],
        "rec_yds":   [25, 40, 50, 60, 75, 80, 90, 100, 110, 125, 150],
        "rec_td":    [1, 2, 3],
        "fg_made":   [1, 2, 3, 4, 5],
    },
    "1H": {
        "pass_att":  [8, 10, 12, 15, 18, 20, 22, 25],
        "pass_yds":  [100, 125, 150, 175, 200, 225, 250, 275, 300],
        "pass_td":   [1, 2, 3],
        "rush_att":  [5, 7, 9, 11, 13, 15],
        "rush_yds":  [20, 30, 40, 50, 60, 70, 80, 90, 100],
        "rush_td":   [1, 2],
        "targets":   [3, 4, 5, 6, 7, 8],
        "receptions":[2, 3, 4, 5, 6, 7, 8],
        "rec_yds":   [20, 30, 40, 50, 60, 70, 80, 90, 100],
        "rec_td":    [1, 2],
        "fg_made":   [1, 2, 3],
    },
    "1Q": {
        "pass_att":  [4, 6, 8, 10, 12, 14, 16, 18],
        "pass_yds":  [50, 75, 100, 125, 150, 175, 200],
        "pass_td":   [1, 2],
        "rush_att":  [3, 4, 5, 6, 7, 8, 9],
        "rush_yds":  [10, 20, 30, 40, 50, 60, 70],
        "rush_td":   [1, 2],
        "targets":   [1, 2, 3, 4, 5, 6],
        "receptions":[1, 2, 3, 4, 5, 6],
        "rec_yds":   [10, 20, 30, 40, 50, 60, 70],
        "rec_td":    [1, 2],
        "fg_made":   [1, 2],
    },
}

def milestones_for(stat_key: str, timeframe: str):
    tf = NFL_MILESTONES.get(timeframe, NFL_MILESTONES["Game"])
    return tf.get(stat_key, NFL_MILESTONES["Game"].get(stat_key, []))

# ============
# Market columns (exact, full-game only)
# ============
MARKET_LINE_MAP = {
    "pass_att":   "prop_pass_att_line",
    "pass_yds":   "prop_pass_yds_line",
    "pass_td":    "prop_pass_td_line",
    "rush_att":   "prop_rush_att_line",
    "rush_yds":   "prop_rush_yds_line",
    "rush_td":    "prop_rush_td_line",
    "receptions": "prop_rec_line",
    "rec_yds":    "prop_rec_yds_line",
    "rec_td":     "prop_rec_td_line",
    # fg_made not included here (we model K-ball separately)
}

# ============
# Odds helpers
# ============
def to_american_odds(prob: float) -> str:
    prob = max(min(float(prob), 0.9999), 0.0001)
    if prob >= 0.5:
        return str(int(-100 * prob / (1 - prob)))
    else:
        return f"+{int(100 * (1 - prob) / prob)}"

def apply_vig(prob: float, vig_pct: float) -> float:
    return max(min(float(prob) + float(vig_pct) / 100.0, 0.9999), 0.0001)

# ======================
# Modeling helpers (NBA-style blend kept for non-FG if needed later)
# ======================
def bayesian_model_weights(poisson_ll, nb_ll, gamma_ll, lognorm_ll):
    log_likelihoods = np.array([poisson_ll, nb_ll, gamma_ll, lognorm_ll])
    log_likelihoods = np.nan_to_num(log_likelihoods, nan=-np.inf)
    max_log_likelihood = np.max(log_likelihoods)
    exp_likelihoods = np.exp(log_likelihoods - max_log_likelihood)
    s = np.sum(exp_likelihoods)
    if s == 0:
        return {"Poisson": 0.25, "Negative Binomial": 0.25, "Gamma-Poisson": 0.25, "Log-Normal": 0.25}
    w = exp_likelihoods / s
    return {"Poisson": w[0], "Negative Binomial": w[1], "Gamma-Poisson": w[2], "Log-Normal": w[3]}

def determine_best_fit(data):
    data = data.dropna()
    mean = np.mean(data)
    variance = np.var(data)
    if len(data) < 5 or mean <= 0 or variance <= 0:
        return bayesian_model_weights(-np.inf, -np.inf, -np.inf, -np.inf)
    poisson_ll = np.sum(poisson.logpmf(data, mean)) if mean > 0 else -np.inf
    nb_r = mean ** 2 / (variance - mean) if variance > mean else 10
    nb_p = mean / variance if variance > mean else 0.5
    nb_ll = np.sum(nbinom.logpmf(data, nb_r, nb_p)) if nb_r > 0 and nb_p > 0 else -np.inf
    gamma_ll = np.sum(gamma.logpdf(data, a=nb_r, scale=nb_p)) if nb_r > 0 and nb_p > 0 else -np.inf
    log_data = np.log1p(data[data > 0])
    ks_stat, ks_p = kstest(log_data, 'norm', args=(np.mean(log_data), np.std(log_data))) if len(log_data) > 1 else (0, 0)
    lognorm_ll = np.sum(lognorm.logpdf(data[data > 0], s=(np.std(log_data) if len(log_data) > 1 else 1),
                                       scale=np.exp(np.mean(log_data) if len(log_data) > 1 else 0))) if ks_p > 0.01 else -np.inf
    return bayesian_model_weights(poisson_ll, nb_ll, gamma_ll, lognorm_ll)

def calculate_probability(mean, variance, weights, milestones, raw_data):
    probabilities = {}
    if mean <= 0:
        return {f"{m}+": 0.001 for m in milestones}
    for m in milestones:
        poisson_prob = 1 - poisson.cdf(m - 1, mean)
        probabilities[f"{m}+"] = round(max(poisson_prob, 0.001), 4)
    return probabilities

def generate_pie(weights, player, stat):
    fig, ax = plt.subplots()
    labels = list(weights.keys())
    sizes  = list(weights.values())
    nz_idx = [i for i, s in enumerate(sizes) if s > 0]
    sizes_nz  = [sizes[i] for i in nz_idx] or [1.0]
    labels_nz = [labels[i] for i in nz_idx] or ["Poisson"]
    wedges, _ = ax.pie(sizes_nz, startangle=140, radius=1.0)
    for i, w in enumerate(wedges):
        angle = (w.theta2 + w.theta1) / 2.
        rad = np.deg2rad(angle)
        ax.annotate(f"{labels_nz[i]} ({sizes_nz[i]*100:.1f}%)",
                    xy=(np.cos(rad), np.sin(rad)),
                    xytext=(1.2*np.cos(rad), 1.2*np.sin(rad)),
                    ha="center", va="center",
                    arrowprops=dict(arrowstyle='-', lw=0.8))
    ax.set_title(f"Distribution Blend – {player} ({STAT_LABELS.get(stat, stat)})")
    ax.axis('equal')
    return fig

def generate_histogram(raw_data, weights, mean, variance):
    x = np.linspace(0, max(raw_data.max() if len(raw_data) else 1, 10) + 10, 500)
    poisson_pdf = poisson.pmf(np.floor(x), mean) if mean > 0 else np.zeros_like(x)
    nb_r = mean ** 2 / (variance - mean) if variance > mean else 10
    nb_p = mean / variance if variance > mean else 0.5
    nb_pdf = nbinom.pmf(np.floor(x), nb_r, nb_p) if nb_r > 0 and nb_p > 0 else np.zeros_like(x)
    gamma_pdf = gamma.pdf(x, a=mean, scale=variance / mean) if mean > 0 and variance > 0 else np.zeros_like(x)
    lognorm_pdf = np.zeros_like(x)
    log_data = np.log1p(raw_data[raw_data > 0])
    if len(log_data) > 1:
        lognorm_pdf = lognorm.pdf(x, s=np.std(log_data), scale=np.exp(np.mean(log_data)))
    blended_pdf = (weights["Poisson"] * poisson_pdf +
                   weights["Negative Binomial"] * nb_pdf +
                   weights["Gamma-Poisson"] * gamma_pdf +
                   weights["Log-Normal"] * lognorm_pdf)
    fig, ax = plt.subplots()
    bins = range(int(raw_data.min()) if len(raw_data) > 0 else 0,
                 int(raw_data.max()) + 2 if len(raw_data) > 0 else 2)
    ax.hist(raw_data, bins=bins, density=True, alpha=0.6)
    ax.plot(x, blended_pdf, 'k-', label="Blended Model", linewidth=2)
    ax.set_title("Histogram vs. Blended Model PDF")
    ax.legend()
    return fig

# ====================
# Recency weighting helpers
# ====================
def _order_key(df_slice: pd.DataFrame):
    if "gameday" in df_slice.columns:
        return pd.to_datetime(df_slice["gameday"], errors="coerce")
    if {"season", "week"}.issubset(df_slice.columns):
        # coerce tuples; older first
        return df_slice["season"].astype(float) * 100 + df_slice["week"].astype(float)
    # fallback to row order
    return pd.Series(np.arange(len(df_slice)), index=df_slice.index)

def recency_weights(df_slice: pd.DataFrame, half_life_games: float) -> pd.Series:
    """
    Exponential decay by 'games ago' (0 = most recent).
    weight = 0.5 ** (age / half_life_games)
    """
    if half_life_games is None or half_life_games <= 0:
        # equal weights
        return pd.Series(1.0, index=df_slice.index)
    # sort by time
    key = _order_key(df_slice)
    ord_idx = key.sort_values(na_position="first").index
    # ages: oldest -> largest age; we want most recent = age 0
    # create rank so that the last in sorted order is most recent
    ranks = pd.Series(np.arange(len(ord_idx)), index=ord_idx)  # oldest=0 ... most recent= n-1
    ages = (ranks.max() - ranks).reindex(df_slice.index).fillna(0).astype(float)
    w = 0.5 ** (ages / float(half_life_games))
    return w.clip(lower=1e-6)

# ====================
# FG K-ball model helpers (used ONLY for fg_made and kickers)
# ====================
FG_BINS = [
    ("lt40",    35),
    ("40_49",   45),
    ("50_54",   52),
    ("55_59",   57),
    ("60_plus", 62),
]

def _beta_smooth_rate(makes, atts, alpha=8.0, beta=2.0):
    return (makes + alpha) / (atts + alpha + beta) if (atts + alpha + beta) > 0 else (alpha / (alpha + beta))

def _fit_logistic_from_bins(dists, rates):
    def logit(p):
        p = np.clip(p, 1e-6, 1-1e-6)
        return np.log(p/(1-p))
    R = 50.0
    x = (R - np.array(dists))
    y = np.array([logit(p) for p in rates])
    X = np.vstack([np.ones_like(x), x]).T
    try:
        coef, _, _, _ = np.linalg.lstsq(X, y, rcond=None)
        a, b = coef[0], coef[1]
    except Exception:
        a, b = 0.0, -0.15
    return a, b, R

def _p_make(a, b, R, d):
    z = a + b*(R - d)
    return 1.0 / (1.0 + np.exp(-z))

def _fg_lambda_p_from_slice(pdata: pd.DataFrame, timeframe: str, hist_weights: pd.Series = None):
    """
    Return per-game attempt rates per bin and smoothed accuracy per bin,
    with optional per-row recency weights applied to attempts/makes.
    """
    suf = {"Game":"", "1H":"_1h", "1Q":"_1q"}[timeframe]
    att_cols  = [f"fg_att_{k}{suf}"  for k,_ in FG_BINS]
    made_cols = [f"fg_made_{k}{suf}" for k,_ in FG_BINS]

    if hist_weights is None:
        hist_weights = pd.Series(1.0, index=pdata.index)

    atts = []
    made = []
    for c in att_cols:
        s = pd.to_numeric(pdata.get(c, pd.Series(dtype=float)), errors="coerce").fillna(0.0)
        atts.append((s * hist_weights.reindex(pdata.index).fillna(0)).sum())
    for c in made_cols:
        s = pd.to_numeric(pdata.get(c, pd.Series(dtype=float)), errors="coerce").fillna(0.0)
        made.append((s * hist_weights.reindex(pdata.index).fillna(0)).sum())

    atts = np.array(atts, dtype=float)
    made = np.array(made, dtype=float)

    # "weighted games" is sum of weights (each row ~ one game)
    games_w = float(hist_weights.sum())
    games_w = max(games_w, 1e-9)
    lam_bins = atts / games_w

    dist_mid = np.array([mid for _, mid in FG_BINS])
    p_hat = np.array([_beta_smooth_rate(m, a) for m, a in zip(made, atts)])
    a, b, R = _fit_logistic_from_bins(dist_mid, p_hat)
    return lam_bins, (a, b, R), dist_mid

def fg_kball_mean_var_for_slice(pdata: pd.DataFrame, timeframe: str,
                                range_gain_yds=7.0, acc_bump_abs=0.02, long_propensity=0.10,
                                hist_weights: pd.Series = None):
    lam_bins, (a, b, R), dist_mid = _fg_lambda_p_from_slice(pdata, timeframe, hist_weights)

    # Tilt long attempts
    tilt = np.ones_like(lam_bins)
    long_idx = np.array([i for i,(k,_) in enumerate(FG_BINS) if k in ("55_59","60_plus")])
    tilt[long_idx] = 1.0 + float(long_propensity)
    lam_bins = lam_bins * tilt

    # Keep total attempts per game constant after tilting
    total = lam_bins.sum()
    if total > 1e-12:
        lam_bins = lam_bins * (total / lam_bins.sum())

    # Range + accuracy bump
    def p_range(d): return _p_make(a, b, R + float(range_gain_yds), d)
    p_vec = np.array([np.clip(p_range(d) + float(acc_bump_abs), 0.0, 1.0) for d in dist_mid])

    mu = float(np.sum(lam_bins * p_vec))
    var = float(np.sum(lam_bins * p_vec * (1.0 - p_vec)))
    return mu, var

# ====================
# Market + Historical (recency) helpers
# ====================
def weighted_mean(series: pd.Series, weights: pd.Series):
    s = pd.to_numeric(series, errors="coerce").replace([np.inf, -np.inf], np.nan)
    mask = s.notna() & weights.reindex(s.index).notna()
    if not mask.any():
        return float("nan"), 0
    s = s[mask]
    w = weights.reindex(s.index).astype(float)
    denom = w.sum()
    if denom <= 0:
        return float("nan"), 0
    return float((s * w).sum() / denom), int(s.shape[0])

def market_mean_for_player(pdata: pd.DataFrame, stat_key: str, market_half_life_games: float):
    col = MARKET_LINE_MAP.get(stat_key, None)
    if not col or col not in pdata.columns:
        return float("nan"), 0
    w = recency_weights(pdata, market_half_life_games)
    return weighted_mean(pdata[col], w)

def historical_mean_for_player(pdata: pd.DataFrame, stat_col: str, hist_half_life_games: float):
    w = recency_weights(pdata, hist_half_life_games)
    return weighted_mean(pdata[stat_col], w)

# ====================
# Globals
# ====================
df = None
model_weights_df = None
temp_df = None

# =========================
# Loading + preprocessing
# =========================
def csv_col_for(stat_key: str, timeframe_key: str) -> str:
    return f"{STAT_MAP.get(stat_key, stat_key)}{TIMEFRAMES.get(timeframe_key, '')}"

def load_and_prepare_data(file):
    """Populate globals and return UI choices."""
    global df, model_weights_df, temp_df
    if file is None:
        return (gr.update(choices=[], value=None),   # team_dd
                gr.update(choices=[], value=[]),     # players_ms
                gr.update(choices=[], value=None),   # position_dd
                gr.update(choices=[], value=None),   # league_pos
                "Upload the CSV to begin.")

    raw = pd.read_csv(file.name)
    raw.columns = [c.strip() for c in raw.columns]
    df = raw.copy()
    temp_df = raw.copy()

    teams = sorted(df.get("player_team", pd.Series(dtype=str)).dropna().astype(str).str.strip().replace("", np.nan).dropna().unique().tolist())
    players = sorted(df.get("player", pd.Series(dtype=str)).dropna().astype(str).str.strip().replace("", np.nan).dropna().unique().tolist())
    positions = sorted(df.get("position", pd.Series(dtype=str)).dropna().astype(str).str.strip().replace("", np.nan).dropna().unique().tolist())

    # Precompute per-player model weights (non-FG stats; kept as before)
    rows = []
    for player in players:
        pdata = df[df["player"] == player]
        row = {"player": player, "games_played": pdata["game_id"].nunique() if "game_id" in pdata.columns else len(pdata)}
        for stat_key in STAT_OPTIONS:
            stat_col = csv_col_for(stat_key, "Game")
            if stat_col not in pdata.columns:
                weights = {"Poisson":0.25, "Negative Binomial":0.25, "Gamma-Poisson":0.25, "Log-Normal":0.25}
            else:
                raw_data = pd.to_numeric(pdata.get(stat_col, pd.Series(dtype=float)), errors="coerce").dropna()
                weights = determine_best_fit(raw_data)
            row[f"Poisson_Weight_{stat_key}"] = round(weights["Poisson"], 4)
            row[f"Negative_Binomial_Weight_{stat_key}"] = round(weights["Negative Binomial"], 4)
            row[f"Gamma_Poisson_Weight_{stat_key}"] = round(weights["Gamma-Poisson"], 4)
            row[f"Log_Normal_Weight_{stat_key}"] = round(weights["Log-Normal"], 4)
        rows.append(row)
    model_weights_df = pd.DataFrame(rows)

    msg = "βœ… File loaded."
    if "player_team" not in df.columns:
        msg = "⚠️ 'player_team' not found. Team tab will not filter correctly until your exporter adds it."

    return (gr.update(choices=teams, value=(teams[0] if teams else None)),
            gr.update(choices=players, value=[]),
            gr.update(choices=positions, value=None),
            gr.update(choices=positions, value=None),
            msg)

# =========================
# Player tab (position filter + league average + K-ball + Market/Hist blend + Recency + Small-sample prior)
# =========================
def estimate(player, stat_key, timeframe, mean_sel, custom_mean, vig, show_extremes,
             range_gain_yds, acc_bump_abs, long_propensity,
             market_hist_blend, hist_half_life, market_half_life, prior_strength_games):
    if df is None or model_weights_df is None:
        return "⚠️ Upload the CSV.", pd.DataFrame(), {"Poisson":1,"Negative Binomial":0,"Gamma-Poisson":0,"Log-Normal":0}, pd.Series(dtype=float)

    if player not in df['player'].values:
        return f"⚠️ Player '{player}' not found.", pd.DataFrame(), {"Poisson":1,"Negative Binomial":0,"Gamma-Poisson":0,"Log-Normal":0}, pd.Series(dtype=float)

    stat_col = csv_col_for(stat_key, timeframe)
    pdata = df[df['player'] == player]

    # RAW (for hit rates & charts)
    raw_data = pd.to_numeric(pdata.get(stat_col, pd.Series(dtype=float)), errors="coerce").dropna()
    n_hist_rows = int(raw_data.shape[0])

    # ===== Historical mean (recency-weighted) =====
    hist_mean, _hist_used = historical_mean_for_player(pdata, stat_col, hist_half_life)

    # ===== K-ball for FG (kickers only) overrides hist_mean/variance =====
    is_kicker = (pdata.get("position") == "K").any()
    variance = raw_data.var() if len(raw_data) else 0.0
    if stat_key == "fg_made" and is_kicker:
        w_hist = recency_weights(pdata, hist_half_life)
        mu, var = fg_kball_mean_var_for_slice(
            pdata, timeframe,
            range_gain_yds, acc_bump_abs, long_propensity,
            hist_weights=w_hist
        )
        hist_mean, variance = mu, var

    # ===== Market mean (recency-weighted; partial rows OK) =====
    market_mean, market_rows = market_mean_for_player(pdata, stat_key, market_half_life)

    # ===== Market ↔ Historical Blend (unless custom) =====
    if mean_sel == "Use Custom Projection" and custom_mean is not None:
        mean_after_market = float(custom_mean)
        mean_src = "Custom"
    else:
        if np.isfinite(market_mean):
            w = float(market_hist_blend)  # 0..1  (1 = all market)
            mean_after_market = w * market_mean + (1.0 - w) * hist_mean
            mean_src = f"Blend ({w:.2f} market / {1-w:.2f} hist)"
        else:
            mean_after_market = hist_mean
            mean_src = "Historical"

    # ===== Small-sample league-average prior (position-based) =====
    # Compute league avg for same position (same stat/timeframe)
    position_vals = pdata.get("position").dropna().astype(str).unique().tolist()
    player_pos = position_vals[0] if position_vals else None
    league_mean_for_prior = None
    if player_pos:
        pos_slice = df[df.get("position") == player_pos].copy()
        if stat_key == "fg_made" and player_pos == "K":
            # use K-ball mean across position (no recency here to keep fast)
            mu_pos, _ = fg_kball_mean_var_for_slice(pos_slice, timeframe)
            league_mean_for_prior = mu_pos
        else:
            series_pos = pd.to_numeric(pos_slice.get(stat_col, pd.Series(dtype=float)), errors="coerce").dropna()
            league_mean_for_prior = float(series_pos.mean()) if len(series_pos) else None

    n_games = n_hist_rows  # rows with non-null stat for the player
    if league_mean_for_prior is not None and prior_strength_games > 0:
        # shrink towards league avg when sample is small; continuous shrinkage
        w_player = n_games / (n_games + float(prior_strength_games))
        mean_to_use = w_player * mean_after_market + (1.0 - w_player) * league_mean_for_prior
        prior_note = f" (shrunken with {player_pos} league avg, w={w_player:.2f})"
    else:
        mean_to_use = mean_after_market
        prior_note = ""

    # ===== Probabilities and table =====
    ms = milestones_for(stat_key, timeframe)
    probs_all = calculate_probability(mean_to_use, variance, {"Poisson":1,"Negative Binomial":0,"Gamma-Poisson":0,"Log-Normal":0}, ms, raw_data)

    if show_extremes == "Hide Extreme Probabilities":
        probs = {k: v for k, v in probs_all.items() if 0.005 <= v <= 0.99}
        if len(probs) == 0:
            probs = probs_all.copy()
    else:
        probs = probs_all

    games = pdata['game_id'].nunique() if "game_id" in pdata.columns else len(pdata)
    hit_rates = []
    for m in ms:
        hits = (raw_data >= m).sum() if len(raw_data) else 0
        hit_rates.append(round((hits / games) * 100, 2) if games > 0 else 0.0)

    filtered = list(probs.keys())
    filt_hr = [hr for m, hr in zip(ms, hit_rates) if f"{m}+" in filtered]

    table = pd.DataFrame({
        "Milestone": filtered,
        "Probability": [f"{v * 100:.2f}%" for v in probs.values()],
        "True Odds": [to_american_odds(v) for v in probs.values()],
        "Odds w/Vig": [to_american_odds(apply_vig(v, vig)) for v in probs.values()],
        "Hit Rate": [f"{x:.2f}%" for x in filt_hr],
    })

    mm_text = f"{market_mean:.2f}" if np.isfinite(market_mean) else "n/a"
    summary_md = f"""
### πŸ“Š {player} β€” {STAT_LABELS.get(stat_key, stat_key)} ({timeframe})
- Games in sample (non-null {stat_col}): **{n_games}**
- Historical mean (recency HL={hist_half_life:.1f} games): **{(hist_mean if np.isfinite(hist_mean) else 0.0):.2f}**
- Market mean (rows used, HL={market_half_life:.1f}): **{mm_text}** (rows: **{market_rows}**)
- Projection used: **{mean_to_use:.2f}** β€” {mean_src}{prior_note}
- Variance (hist/K-ball): **{variance:.2f}**
- Vig: **{vig:.2f}%** β€” Extremes: **{'Shown' if show_extremes == 'Show All' else 'Hidden (fallback if empty)'}**
"""
    return summary_md, table, {"Poisson":1,"Negative Binomial":0,"Gamma-Poisson":0,"Log-Normal":0}, raw_data

def league_avg_by_position(position, stat_key, timeframe, vig, range_gain_yds, acc_bump_abs, long_propensity):
    if df is None:
        return pd.DataFrame(), "Upload a CSV first."
    if not position:
        return pd.DataFrame(), "Pick a position."

    slice_df = df[df.get("position") == position].copy()
    if slice_df.empty:
        return pd.DataFrame(), f"No rows for position {position}."

    stat_col = csv_col_for(stat_key, timeframe)
    ms = milestones_for(stat_key, timeframe)

    # FG uses K-ball mean ONLY if position is K and stat is fg_made
    if stat_key == "fg_made" and position == "K":
        mu, _ = fg_kball_mean_var_for_slice(slice_df, timeframe,
                                            range_gain_yds, acc_bump_abs, long_propensity)
        mean_to_use = mu
    else:
        series = pd.to_numeric(slice_df.get(stat_col, pd.Series(dtype=float)), errors="coerce").dropna()
        mean_to_use = series.mean() if len(series) else 0.0

    probs = {f"{m}+": round(1 - poisson.cdf(m-1, mean_to_use), 4) for m in ms}
    table = pd.DataFrame({
        "Milestone": list(probs.keys()),
        "Probability": [f"{p*100:.2f}%" for p in probs.values()],
        "True Odds": [to_american_odds(p) for p in probs.values()],
        "Odds w/Vig": [to_american_odds(apply_vig(p, vig)) for p in probs.values()],
    })
    title = f"{position} League Avg β€” {STAT_LABELS.get(stat_key, stat_key)} ({timeframe})"
    return table, title

# =========================
# Team tab
# =========================
def team_table(team, stat_key, timeframe, vig, subset_players):
    if df is None:
        return pd.DataFrame(), "Upload a CSV first."
    if not team:
        return pd.DataFrame(), "Pick a team."

    stat_col = csv_col_for(stat_key, timeframe)
    milestones = milestones_for(stat_key, timeframe)

    work = df[df.get("player_team") == team].copy()
    if subset_players:
        work = work[work.get("player").isin(subset_players)]

    if work.empty:
        return pd.DataFrame(), f"No rows for {team}."

    rows = []
    for player, pdata in work.groupby("player", dropna=True):
        series = pd.to_numeric(pdata.get(stat_col, pd.Series(dtype=float)), errors="coerce").dropna()
        games = pdata['game_id'].nunique() if "game_id" in pdata.columns else len(pdata)
        mean = series.mean() if len(series) else 0.0
        for m in milestones:
            prob_hist = float((series >= m).sum()) / float(games) if (games > 0 and len(series)) else (1 - poisson.cdf(m-1, mean))
            rows.append({
                "Player": player,
                "Games": games,
                "Milestone": f"{m}+",
                "Prob": round(prob_hist, 4),
                "True Odds": to_american_odds(prob_hist),
                "Odds w/ Vig": to_american_odds(apply_vig(prob_hist, vig)),
                "Mean": round(mean, 2),
            })

    out = pd.DataFrame(rows)
    def m_to_int(s):
        try: return int(str(s).replace("+", ""))
        except: return 0
    out["_m"] = out["Milestone"].apply(m_to_int)
    out = out.sort_values(["Prob","Player","_m"], ascending=[False,True,True]).drop(columns=["_m"])
    return out, f"{team} β€’ {STAT_LABELS.get(stat_key, stat_key)} β€’ {timeframe}"

# ==============
# UI (Gradio)
# ==============
with gr.Blocks(title="🏈 NFL Milestone Explorer",
               css=".green-button {background-color: #28a745 !important; color: white !important; font-weight: bold;}") as demo:
    gr.Markdown("## 🏈 NFL Milestone Explorer")
    gr.Markdown("Upload the `nfl_milestone_logs.csv` from your exporter. Team tab uses the **player_team** column.")

    file_in = gr.File(label="Upload nfl_milestone_logs.csv", file_types=[".csv"])
    status = gr.Markdown("")

    # Populate choices on upload
    def on_file(f):
        team_upd, players_upd, pos_upd, league_pos_upd, msg = load_and_prepare_data(f)
        return team_upd, players_upd, pos_upd, league_pos_upd, msg

    with gr.Tabs():

        # ===== Team Tab =====
        with gr.Tab("Team"):
            with gr.Row():
                team_dd = gr.Dropdown(label="Team (player_team)", choices=[])
                team_stat = gr.Dropdown(label="Stat", choices=STAT_OPTIONS, value="rec_yds")
                team_time = gr.Radio(list(TIMEFRAMES.keys()), value="Game", label="Timeframe")
                team_vig = gr.Number(label="Vig (%)", value=4.92, precision=2)
            team_players = gr.Dropdown(choices=[], multiselect=True, label="Filter to Players (optional)")
            team_btn = gr.Button("Compute Team Table", elem_classes=["green-button"])
            team_title = gr.Markdown(visible=False)
            team_table_out = gr.Dataframe(visible=False, label="Team Milestones")

        # ===== Player Tab =====
        with gr.Tab("Player"):
            gr.Markdown("### Filters")
            with gr.Row():
                position_dd = gr.Dropdown(choices=[], label="Position (optional, filters player list)")
                players_ms = gr.Dropdown(choices=[], multiselect=True, label="Players (select none to use all in position)")
            with gr.Row():
                p_stat = gr.Dropdown(label="Stat", choices=STAT_OPTIONS, value="rec_yds")
                p_time = gr.Radio(list(TIMEFRAMES.keys()), value="Game", label="Timeframe")

            gr.Markdown("### Projection Controls")
            with gr.Row():
                mean_sel = gr.Radio(["Use Per-Game Average", "Use Custom Projection"], label="Projection Source", value="Use Per-Game Average")
                custom_proj = gr.Number(label="Custom Mean (if selected)", precision=2)
                market_hist_blend = gr.Slider(0, 1, value=0.5, step=0.05, label="Projection Blend: Market ↔ Historical")

            gr.Markdown("### Recency Weighting (Half-life in games)")
            with gr.Row():
                hist_half_life = gr.Slider(0, 20, value=6, step=1, label="Historical Half-life")
                market_half_life = gr.Slider(0, 20, value=6, step=1, label="Market Half-life")

            gr.Markdown("### Small-Sample League Average Prior")
            with gr.Row():
                prior_strength = gr.Slider(0, 20, value=7, step=1, label="Prior Strength (games)")

            gr.Markdown("### (Optional) K-ball Adjustments (used only when Stat = FG Made & Position = K)")
            with gr.Row():
                range_gain = gr.Slider(0, 10, value=7, step=1, label="K-ball: Range gain (yds)")
                acc_bump = gr.Slider(0, 0.10, value=0.02, step=0.01, label="K-ball: Accuracy bump (abs prob)")
                long_prop = gr.Slider(0, 0.5, value=0.10, step=0.05, label="K-ball: Long-attempt propensity")

            gr.Markdown("### Odds Settings")
            with gr.Row():
                p_vig = gr.Number(label="Vig (%)", value=4.92, precision=2)
                extreme_toggle = gr.Radio(["Hide Extreme Probabilities", "Show All"], label="Extreme Probabilities", value="Hide Extreme Probabilities")

            player_btn = gr.Button("Compute Selected Players", elem_classes=["green-button"])
            p_summary = gr.Markdown(visible=False)
            p_table = gr.Dataframe(visible=False, label="Milestones")
            p_pie = gr.Plot(visible=False)
            p_hist = gr.Plot(visible=False)
            recent_games = gr.Dataframe(visible=False, label="Recent Games")

            gr.Markdown("### League Average Pricing (by Position)")
            with gr.Row():
                league_pos = gr.Dropdown(choices=[], label="Position for League Avg")
                league_stat = gr.Dropdown(label="Stat", choices=STAT_OPTIONS, value="fg_made")
                league_time = gr.Radio(list(TIMEFRAMES.keys()), value="Game", label="Timeframe")
                league_vig = gr.Number(label="Vig (%)", value=4.92, precision=2)
            with gr.Row():
                league_range_gain = gr.Slider(0, 10, value=7, step=1, label="K-ball: Range gain (yds)")
                league_acc_bump = gr.Slider(0, 0.10, value=0.02, step=0.01, label="K-ball: Accuracy bump (abs prob)")
                league_long_prop = gr.Slider(0, 0.5, value=0.10, step=0.05, label="K-ball: Long-attempt propensity")
            league_btn = gr.Button("Compute League Avg", elem_classes=["green-button"])
            league_title = gr.Markdown(visible=False)
            league_table = gr.Dataframe(visible=False, label="League Avg Milestones")

    # Hook file load (also fills league_pos)
    file_in.change(on_file, inputs=[file_in], outputs=[team_dd, players_ms, position_dd, league_pos, status])

    # Team roster subset choices
    def on_team_change(team):
        if df is None or not team:
            return gr.update(choices=[], value=[])
        team_players_list = (
            df.loc[df.get("player_team") == team, "player"]
              .dropna().astype(str).str.strip().replace("", np.nan).dropna().unique().tolist()
        )
        return gr.update(choices=sorted(team_players_list), value=[])
    team_dd.change(on_team_change, inputs=[team_dd], outputs=[team_players])

    # Player list filtered by position (or all)
    def on_position_change(pos):
        if df is None:
            return gr.update(choices=[], value=[])
        if not pos:
            plist = df["player"].dropna().astype(str).str.strip().unique().tolist()
        else:
            plist = (df.loc[df.get("position") == pos, "player"]
                       .dropna().astype(str).str.strip().unique().tolist())
        plist = sorted(plist)
        return gr.update(choices=plist, value=[])
    position_dd.change(on_position_change, inputs=[position_dd], outputs=[players_ms])

    # Team run
    def run_team(team, stat, timeframe, vig, subset):
        table, title = team_table(team, stat, timeframe, vig, subset)
        return gr.update(value=title, visible=True), gr.update(value=table, visible=True)
    team_btn.click(run_team, inputs=[team_dd, team_stat, team_time, team_vig, team_players],
                   outputs=[team_title, team_table_out])

    # Player run (multi-player; charts only when a single player is selected)
    def run_players(pos, players, stat, timeframe, mean_sel_v, custom_mean, vig, extreme_v,
                    rg, acc, lp, blend, hist_hl, market_hl, prior_g):
        if df is None:
            return (gr.update(visible=False), gr.update(visible=False),
                    gr.update(visible=False), gr.update(visible=False),
                    gr.update(visible=False))
        # If no players selected but position chosen -> use all players of that position
        if (not players) and pos:
            players = sorted(df.loc[df.get("position") == pos, "player"].dropna().astype(str).str.strip().unique().tolist())

        if not players:
            return (gr.update(value="⚠️ Select a position or at least one player.", visible=True),
                    gr.update(visible=False),
                    gr.update(visible=False),
                    gr.update(visible=False),
                    gr.update(visible=False))

        all_rows = []
        first_summary = None
        first_weights = None
        first_raw = None

        for i, player in enumerate(players):
            summary_md, table, weights, raw = estimate(
                player, stat, timeframe,
                mean_sel_v, custom_mean, vig, extreme_v,
                rg, acc, lp,
                blend, hist_hl, market_hl, prior_g
            )
            t = table.copy()
            t.insert(0, "Player", player)
            all_rows.append(t)
            if i == 0:
                first_summary, first_weights, first_raw = summary_md, weights, raw

        stacked = pd.concat(all_rows, ignore_index=True) if all_rows else pd.DataFrame()

        # Charts & recent games only when exactly one player is selected
        if len(players) == 1 and first_weights is not None:
            pie = generate_pie(first_weights, players[0], stat)
            raw = first_raw if first_raw is not None else pd.Series(dtype=float)
            hist = generate_histogram(
                raw,
                first_weights,
                custom_mean if mean_sel_v == "Use Custom Projection" and custom_mean is not None else (raw.mean() if len(raw)>0 else 0.0),
                raw.var() if len(raw)>0 else 0.0
            )
            recent = temp_df[temp_df['player'] == players[0]].copy()
            if "game_id" in recent.columns and "gameday" in recent.columns:
                recent = recent.sort_values(by=['season','week','game_id'] if {'season','week','game_id'}.issubset(recent.columns) else 'gameday', ascending=False)
            recent = recent.head(10)
            keep_cols = [c for c in ["gameday","season","week","home_team","away_team",
                                     csv_col_for(stat, timeframe)] if c in recent.columns]
            recent_disp = recent[keep_cols] if keep_cols else recent
            return (gr.update(value=first_summary, visible=True),
                    gr.update(value=stacked, visible=True),
                    gr.update(value=pie, visible=True),
                    gr.update(value=hist, visible=True),
                    gr.update(value=recent_disp, visible=True))
        else:
            title = f"{', '.join(players[:6])}{' …' if len(players) > 6 else ''} β€” {STAT_LABELS.get(stat, stat)} ({timeframe})"
            return (gr.update(value=title, visible=True),
                    gr.update(value=stacked, visible=True),
                    gr.update(visible=False),
                    gr.update(visible=False),
                    gr.update(visible=False))

    player_btn.click(
        run_players,
        inputs=[
            position_dd, players_ms, p_stat, p_time, mean_sel, custom_proj, p_vig, extreme_toggle,
            range_gain, acc_bump, long_prop, market_hist_blend, hist_half_life, market_half_life, prior_strength
        ],
        outputs=[p_summary, p_table, p_pie, p_hist, recent_games]
    )

    # League average run (by position)
    def run_league_avg(pos, stat, timeframe, vig, rg, acc, lp):
        table, title = league_avg_by_position(pos, stat, timeframe, vig, rg, acc, lp)
        return gr.update(value=title, visible=True), gr.update(value=table, visible=True)
    league_btn.click(run_league_avg,
                     inputs=[league_pos, league_stat, league_time, league_vig,
                             league_range_gain, league_acc_bump, league_long_prop],
                     outputs=[league_title, league_table])

demo.launch()