simikkk commited on
Commit
fc10d48
·
verified ·
1 Parent(s): 9e88493

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -12
app.py CHANGED
@@ -26,10 +26,10 @@ import gradio as gr
26
  df = pd.read_csv('02_simpleml_komplet_pohyb.csv')
27
  zony = pd.read_csv('00_zony.csv')
28
 
29
- # GTFS zastávky a linky
30
- stops = pd.read_csv('stops.txt', sep=';', low_memory=False)
31
- routes = pd.read_csv('routes.txt', sep=';', low_memory=False)
32
- stop_times = pd.read_csv('stop_times.txt', sep=';', low_memory=False)
33
 
34
  df = df.dropna()
35
  df = df[df['pocet_cest'] >= 0]
@@ -62,12 +62,30 @@ FEAT = [
62
  ]
63
 
64
  X = df[FEAT]; y = df['pocet_cest']
65
- Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
66
- mdl = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=4, random_state=42)
67
- mdl.fit(Xtr, ytr)
68
- mae_m = mean_absolute_error(yte, mdl.predict(Xte))
69
- mae_b = mean_absolute_error(yte, [ytr.mean()]*len(yte))
70
- zlep = round((1 - mae_m/mae_b)*100, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  FEAT_LABELS = {
73
  'rok':'Rok','ctvrtleti':'Čtvrtletí','denni_typ_enc':'Typ dne',
@@ -80,7 +98,18 @@ FEAT_LABELS = {
80
  'cil_uzel':'Dopravní uzel v cíli','zdroj_velikost':'Velikost výchozí obce',
81
  'zdroj_izolace':'Izolovanost výchozí obce'
82
  }
83
- top5 = sorted(zip([FEAT_LABELS[f] for f in FEAT], mdl.feature_importances_), key=lambda x: -x[1])[:5]
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  # ─────────────────────────────────────────────
86
  # 3. LOOKUP MAPY A KONSTANTY
@@ -705,7 +734,105 @@ with gr.Blocks(title="FlexBus Dispatch | Plzeňský kraj", theme=gr.themes.Base(
705
  refresh_btn.click(fn=get_forecast_html, inputs=[], outputs=weather_out)
706
  demo.load(fn=get_forecast_html, inputs=[], outputs=weather_out)
707
 
708
- # ── TAB 3: O modelu ───────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
709
  with gr.Tab("🧠 O modelu a etice"):
710
  gr.Markdown(f"""
711
  ## Jak model funguje
 
26
  df = pd.read_csv('02_simpleml_komplet_pohyb.csv')
27
  zony = pd.read_csv('00_zony.csv')
28
 
29
+ # GTFS zastávky a linky (encoding='utf-8-sig' odstraní BOM znak na začátku souboru)
30
+ stops = pd.read_csv('stops.txt', sep=';', low_memory=False, encoding='utf-8-sig')
31
+ routes = pd.read_csv('routes.txt', sep=';', low_memory=False, encoding='utf-8-sig')
32
+ stop_times = pd.read_csv('stop_times.txt', sep=';', low_memory=False, encoding='utf-8-sig')
33
 
34
  df = df.dropna()
35
  df = df[df['pocet_cest'] >= 0]
 
62
  ]
63
 
64
  X = df[FEAT]; y = df['pocet_cest']
65
+
66
+ # ── Načti předtrénovaný model (model.pkl), nebo natrénuj znovu jako záloha ──
67
+ import pickle, os
68
+
69
+ if os.path.exists('model.pkl'):
70
+ print("Načítám model.pkl ...")
71
+ with open('model.pkl', 'rb') as f:
72
+ _pkg = pickle.load(f)
73
+ mdl = _pkg['model']
74
+ le_dict = _pkg['le_dict']
75
+ mae_m = _pkg['mae_model']
76
+ mae_b = _pkg['mae_base']
77
+ zlep = _pkg['zlepseni']
78
+ feat_imp = _pkg['feat_imp']
79
+ print(f"Model načten | MAE: {mae_m:.2f} | Zlepšení: {zlep} %")
80
+ else:
81
+ print("model.pkl nenalezen — trénuji za běhu ...")
82
+ Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
83
+ mdl = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=4, random_state=42)
84
+ mdl.fit(Xtr, ytr)
85
+ mae_m = mean_absolute_error(yte, mdl.predict(Xte))
86
+ mae_b = mean_absolute_error(yte, [ytr.mean()]*len(yte))
87
+ zlep = round((1 - mae_m/mae_b)*100, 1)
88
+ feat_imp = list(zip(FEAT, mdl.feature_importances_))
89
 
90
  FEAT_LABELS = {
91
  'rok':'Rok','ctvrtleti':'Čtvrtletí','denni_typ_enc':'Typ dne',
 
98
  'cil_uzel':'Dopravní uzel v cíli','zdroj_velikost':'Velikost výchozí obce',
99
  'zdroj_izolace':'Izolovanost výchozí obce'
100
  }
101
+ top5 = sorted(
102
+ [(FEAT_LABELS.get(f, f), v) for f, v in feat_imp],
103
+ key=lambda x: -x[1]
104
+ )[:5]
105
+
106
+ # ── Načti trend forecast (vygenerovaný model_train.py) ──
107
+ if os.path.exists('trend_forecast.csv'):
108
+ trend_df = pd.read_csv('trend_forecast.csv')
109
+ print(f"trend_forecast.csv načten ({len(trend_df)} řádků)")
110
+ else:
111
+ trend_df = pd.DataFrame()
112
+ print("trend_forecast.csv nenalezen — tab Trend bude prázdný")
113
 
114
  # ─────────────────────────────────────────────
115
  # 3. LOOKUP MAPY A KONSTANTY
 
734
  refresh_btn.click(fn=get_forecast_html, inputs=[], outputs=weather_out)
735
  demo.load(fn=get_forecast_html, inputs=[], outputs=weather_out)
736
 
737
+ # ── TAB 3: Trend předpovědi ──────────────────
738
+ with gr.Tab("📈 Trend poptávky (2026–2027)"):
739
+ gr.HTML("""
740
+ <div style="background:#fefce8;border:1px solid #fde047;border-radius:8px;
741
+ padding:12px 16px;margin-bottom:12px;font-family:sans-serif">
742
+ <b>📈 Čtvrtletní předpověď trendu</b> — generováno z model_train.py<br>
743
+ <span style="font-size:0.88em;color:#555">
744
+ Lineární trend + sezónní korekce · Data 2019–2025 · Pro dopravní plánování
745
+ </span>
746
+ </div>""")
747
+ trend_oblast = gr.Dropdown(
748
+ choices=sorted(df['zdroj'].unique().tolist()),
749
+ label="Vyberte oblast",
750
+ value=sorted(df['zdroj'].unique().tolist())[0]
751
+ )
752
+ trend_btn = gr.Button("Zobrazit trend", variant="secondary")
753
+ trend_out = gr.HTML()
754
+
755
+ def zobraz_trend(oblast):
756
+ if trend_df.empty:
757
+ return """<div style="padding:20px;color:#888;font-family:sans-serif">
758
+ ⚠️ Soubor trend_forecast.csv nebyl nalezen.<br>
759
+ Spusť <code>python model_train.py</code> lokálně a nahraj
760
+ <b>model.pkl</b> a <b>trend_forecast.csv</b> na HuggingFace.</div>"""
761
+ sub = trend_df[trend_df['oblast'] == oblast].sort_values(['rok','ctvrtleti'])
762
+ if sub.empty:
763
+ return f"<p>Žádná data pro oblast: {oblast}</p>"
764
+ trend_dir = sub['trend'].iloc[0]
765
+ trend_sklon = sub['trend_sklon'].iloc[0]
766
+ trend_r2 = sub['trend_r2'].iloc[0]
767
+ hist = df[df['zdroj'] == oblast].groupby(['rok','ctvrtleti'])['pocet_cest'].sum().reset_index()
768
+ all_vals = list(hist['pocet_cest']) + list(sub['predikce_cest'])
769
+ max_v = max(all_vals) if all_vals else 1
770
+ min_v = min(all_vals) if all_vals else 0
771
+ rng = max_v - min_v if max_v != min_v else 1
772
+ def to_y(v, h=60): return h - int((v - min_v) / rng * (h-4)) - 2
773
+ hist_pts = []
774
+ for _, r in hist.iterrows():
775
+ x = len(hist_pts) * 18 + 10
776
+ hist_pts.append((x, to_y(r['pocet_cest'])))
777
+ pred_pts = []
778
+ offset = len(hist_pts) * 18 + 10
779
+ for _, r in sub.iterrows():
780
+ x = offset + len(pred_pts) * 18
781
+ pred_pts.append((x, to_y(r['predikce_cest'])))
782
+ def pts_to_path(pts):
783
+ if not pts: return ""
784
+ return "M " + " L ".join(f"{x},{y}" for x,y in pts)
785
+ svg_w = max((len(hist_pts) + len(pred_pts)) * 18 + 20, 300)
786
+ svg = f"""<svg width="{svg_w}" height="80" xmlns="http://www.w3.org/2000/svg"
787
+ style="overflow:visible;display:block;margin:8px 0">
788
+ <path d="{pts_to_path(hist_pts)}" fill="none" stroke="#1a56db" stroke-width="2.5" stroke-linejoin="round"/>
789
+ <path d="{pts_to_path(pred_pts)}" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-dasharray="6,3" stroke-linejoin="round"/>
790
+ {"".join(f'<circle cx="{x}" cy="{y}" r="3.5" fill="#1a56db"/>' for x,y in hist_pts)}
791
+ {"".join(f'<circle cx="{x}" cy="{y}" r="3.5" fill="#f59e0b" stroke="white" stroke-width="1.5"/>' for x,y in pred_pts)}
792
+ <line x1="{len(hist_pts)*18+10}" y1="0" x2="{len(hist_pts)*18+10}" y2="80" stroke="#ccc" stroke-width="1.5" stroke-dasharray="4,3"/>
793
+ <text x="{len(hist_pts)*18+14}" y="12" font-size="9" fill="#888">předpověď →</text>
794
+ </svg>"""
795
+ rows = ""
796
+ Q_LABEL = {1:"Q1 (leden–březen)", 2:"Q2 (duben–červen)", 3:"Q3 (červenec–září)", 4:"Q4 (říjen–prosinec)"}
797
+ TREND_COLOR = {"↑ Rostoucí":"#16a34a","↓ Klesající":"#dc2626","→ Stabilní":"#2563eb"}
798
+ for _, r in sub.iterrows():
799
+ tc = TREND_COLOR.get(r['trend'], "#555")
800
+ rows += (f'<tr><td style="padding:5px 10px">{r["rok"]}</td>' +
801
+ f'<td style="padding:5px 10px">{Q_LABEL.get(r["ctvrtleti"], r["ctvrtleti"])}</td>' +
802
+ f'<td style="padding:5px 10px;font-weight:700;color:#1a56db">{r["predikce_cest"]}</td>' +
803
+ f'<td style="padding:5px 10px;color:{tc};font-weight:600">{r["trend"]}</td></tr>')
804
+ tc_main = TREND_COLOR.get(trend_dir, "#555")
805
+ return f"""<div style="font-family:'Segoe UI',sans-serif;padding:4px">
806
+ <div style="display:flex;gap:24px;margin-bottom:12px;flex-wrap:wrap">
807
+ <div style="background:#f0f4ff;border-radius:8px;padding:12px 18px;min-width:140px">
808
+ <div style="font-size:0.8em;color:#666">Oblast</div>
809
+ <div style="font-size:1.2em;font-weight:700">{oblast}</div>
810
+ </div>
811
+ <div style="background:#f0fdf4;border-radius:8px;padding:12px 18px;min-width:140px">
812
+ <div style="font-size:0.8em;color:#666">Trend</div>
813
+ <div style="font-size:1.2em;font-weight:700;color:{tc_main}">{trend_dir}</div>
814
+ <div style="font-size:0.78em;color:#888">sklon: {trend_sklon:+.2f}/čtvrtletí · R²: {trend_r2:.2f}</div>
815
+ </div>
816
+ </div>
817
+ <div style="margin-bottom:4px;font-size:0.85em;color:#555">
818
+ <span style="color:#1a56db;font-weight:600">── Historie (2019–2025)</span>&nbsp;&nbsp;
819
+ <span style="color:#f59e0b;font-weight:600">- - Předpověď (2026–2027)</span>
820
+ </div>
821
+ {svg}
822
+ <table style="border-collapse:collapse;width:100%;margin-top:10px;font-size:0.9em">
823
+ <thead><tr style="background:#1a56db;color:white">
824
+ <th style="padding:6px 10px;text-align:left">Rok</th>
825
+ <th style="padding:6px 10px;text-align:left">Čtvrtletí</th>
826
+ <th style="padding:6px 10px;text-align:left">Předp. cestujících</th>
827
+ <th style="padding:6px 10px;text-align:left">Trend</th>
828
+ </tr></thead>
829
+ <tbody>{rows}</tbody>
830
+ </table>
831
+ </div>"""
832
+
833
+ trend_btn.click(zobraz_trend, inputs=trend_oblast, outputs=trend_out)
834
+
835
+ # ── TAB 4: O modelu ───────────────────────────
836
  with gr.Tab("🧠 O modelu a etice"):
837
  gr.Markdown(f"""
838
  ## Jak model funguje