Spaces:
Sleeping
Sleeping
Update app.py
Browse files25 unmodified lines2627282930313233343526 unmodified lines6263646566676869707172736 unmodified lines80818283848586618 unmodified lines70570670770870971071125 unmodified linesdf = pd.read_csv('02_simpleml_komplet_pohyb.csv')zony = pd.read_csv('00_zony.csv')# GTFS zastávky a linkystops = pd.read_csv('stops.txt', sep=';', low_memory=False)routes = pd.read_csv('routes.txt', sep=';', low_memory=False)stop_times = pd.read_csv('stop_times.txt', sep=';', low_memory=False)df = df.dropna()df = df[df['pocet_cest'] >= 0]26 unmodified lines]X = df[FEAT]; y = df['pocet_cest']Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)mdl = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=4, random_state=42)mdl.fit(Xtr, ytr)mae_m = mean_absolute_error(yte, mdl.predict(Xte))mae_b = mean_absolute_error(yte, [ytr.mean()]*len(yte))zlep = round((1 - mae_m/mae_b)*100, 1)FEAT_LABELS = {'rok':'Rok','ctvrtleti':'Čtvrtletí','denni_typ_enc':'Typ dne',6 unmodified lines'cil_uzel':'Dopravní uzel v cíli','zdroj_velikost':'Velikost výchozí obce','zdroj_izolace':'Izolovanost výchozí obce'}top5 = sorted(zip([FEAT_LABELS[f] for f in FEAT], mdl.feature_importances_), key=lambda x: -x[1])[:5]# ─────────────────────────────────────────────# 3. LOOKUP MAPY A KONSTANTY618 unmodified linesrefresh_btn.click(fn=get_forecast_html, inputs=[], outputs=weather_out)demo.load(fn=get_forecast_html, inputs=[], outputs=weather_out)# ── TAB 3: O modelu ───────────────────────────with gr.Tab("🧠 O modelu a etice"):gr.Markdown(f"""## Jak model funguje25 unmodified lines2627282930313233343526 unmodified lines6263646566676869707172737475767778798081828384858687888990916 unmodified lines9899100101102103104105106107108109110111112113114115618 unmodified lines73473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783825 unmodified linesdf = pd.read_csv('02_simpleml_komplet_pohyb.csv')zony = pd.read_csv('00_zony.csv')# GTFS zastávky a linky (encoding='utf-8-sig' odstraní BOM znak na začátku souboru)stops = pd.read_csv('stops.txt', sep=';', low_memory=False, encoding='utf-8-sig')routes = pd.read_csv('routes.txt', sep=';', low_memory=False, encoding='utf-8-sig')stop_times = pd.read_csv('stop_times.txt', sep=';', low_memory=False, encoding='utf-8-sig')df = df.dropna()df = df[df['pocet_cest'] >= 0]26 unmodified lines]X = df[FEAT]; y = df['pocet_cest']# ── Načti předtrénovaný model (model.pkl), nebo natrénuj znovu jako záloha ──import pickle, osif os.path.exists('model.pkl'):print("Načítám model.pkl ...")with open('model.pkl', 'rb') as f:_pkg = pickle.load(f)mdl = _pkg['model']le_dict = _pkg['le_dict']mae_m = _pkg['mae_model']mae_b = _pkg['mae_base']zlep = _pkg['zlepseni']feat_imp = _pkg['feat_imp']print(f"Model načten | MAE: {mae_m:.2f} | Zlepšení: {zlep} %")else:print("model.pkl nenalezen — trénuji za běhu ...")Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)mdl = GradientBoostingRegressor(n_estimators=200, learning_rate=0.1, max_depth=4, random_state=42)mdl.fit(Xtr, ytr)mae_m = mean_absolute_error(yte, mdl.predict(Xte))mae_b = mean_absolute_error(yte, [ytr.mean()]*len(yte))zlep = round((1 - mae_m/mae_b)*100, 1)feat_imp = list(zip(FEAT, mdl.feature_importances_))FEAT_LABELS = {'rok':'Rok','ctvrtleti':'Čtvrtletí','denni_typ_enc':'Typ dne',6 unmodified lines'cil_uzel':'Dopravní uzel v cíli','zdroj_velikost':'Velikost výchozí obce','zdroj_izolace':'Izolovanost výchozí obce'}top5 = sorted([(FEAT_LABELS.get(f, f), v) for f, v in feat_imp],key=lambda x: -x[1])[:5]# ── Načti trend forecast (vygenerovaný model_train.py) ──if os.path.exists('trend_forecast.csv'):trend_df = pd.read_csv('trend_forecast.csv')print(f"trend_forecast.csv načten ({len(trend_df)} řádků)")else:trend_df = pd.DataFrame()print("trend_forecast.csv nenalezen — tab Trend bude prázdný")# ─────────────────────────────────────────────# 3. LOOKUP MAPY A KONSTANTY618 unmodified linesrefresh_btn.click(fn=get_forecast_html, inputs=[], outputs=weather_out)demo.load(fn=get_forecast_html, inputs=[], outputs=weather_out)# ── TAB 3: Trend předpovědi ──────────────────with gr.Tab("📈 Trend poptávky (2026–2027)"):gr.HTML("""<div style="background:#fefce8;border:1px solid #fde047;border-radius:8px;padding:12px 16px;margin-bottom:12px;font-family:sans-serif"><b>📈 Čtvrtletní předpověď trendu</b> — generováno z model_train.py<br><span style="font-size:0.88em;color:#555">Lineární trend + sezónní korekce · Data 2019–2025 · Pro dopravní plánování</span></div>""")trend_oblast = gr.Dropdown(choices=sorted(df['zdroj'].unique().tolist()),label="Vyberte oblast",value=sorted(df['zdroj'].unique().tolist())[0])trend_btn = gr.Button("Zobrazit trend", variant="secondary")trend_out = gr.HTML()def zobraz_trend(oblast):if trend_df.empty:return """<div style="padding:20px;color:#888;font-family:sans-serif">⚠️ Soubor trend_forecast.csv nebyl nalezen.<br>Spusť <code>python model_train.py</code> lokálně a nahraj<b>model.pkl</b> a <b>trend_forecast.csv</b> na HuggingFace.</div>"""sub = trend_df[trend_df['oblast'] == oblast].sort_values(['rok','ctvrtleti'])if sub.empty:return f"<p>Žádná data pro oblast: {oblast}</p>"trend_dir = sub['trend'].iloc[0]trend_sklon = sub['trend_sklon'].iloc[0]trend_r2 = sub['trend_r2'].iloc[0]hist = df[df['zdroj'] == oblast].groupby(['rok','ctvrtleti'])['pocet_cest'].sum().reset_index()all_vals = list(hist['pocet_cest']) + list(sub['predikce_cest'])max_v = max(all_vals) if all_vals else 1min_v = min(all_vals) if all_vals else 0rng = max_v - min_v if max_v != min_v else 1def to_y(v, h=60): return h - int((v - min_v) / rng * (h-4)) - 2hist_pts = []for _, r in hist.iterrows():x = len(hist_pts) * 18 + 10hist_pts.append((x, to_y(r['pocet_cest'])))pred_pts = []offset = len(hist_pts) * 18 + 10for _, r in sub.iterrows():x = offset + len(pred_pts) * 18pred_pts.append((x, to_y(r['predikce_cest'])))def pts_to_path(pts):if not pts: return ""return "M " + " L ".join(f"{x},{y}" for x,y in pts)svg_w = max((len(hist_pts) + len(pred_pts)) * 18 + 20, 300)svg = f"""<svg width="{svg_w}" height="80" xmlns="http://www.w3.org/2000/svg"style="overflow:visible;display:block;margin:8px 0"><path d="{pts_to_path(hist_pts)}" fill="none" stroke="#1a56db" stroke-width="2.5" stroke-linejoin="round"/><path d="{pts_to_path(pred_pts)}" fill="none" stroke="#f59e0b" stroke-width="2.5" stroke-dasharray="6,3" stroke-linejoin="round"/>{"".join(f'<circle cx="{x}" cy="{y}" r="3.5" fill="#1a56db"/>' for x,y in hist_pts)}{"".join(f'<circle cx="{x}" cy="{y}" r="3.5" fill="#f59e0b" stroke="white" stroke-width="1.5"/>' for x,y in pred_pts)}<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"/><text x="{len(hist_pts)*18+14}" y="12" font-size="9" fill="#888">předpověď →</text></svg>"""rows = ""Q_LABEL = {1:"Q1 (leden–březen)", 2:"Q2 (duben–červen)", 3:"Q3 (červenec–září)", 4:"Q4 (říjen–prosinec)"}TREND_COLOR = {"↑ Rostoucí":"#16a34a","↓ Klesající":"#dc2626","→ Stabilní":"#2563eb"}for _, r in sub.iterrows():tc = TREND_COLOR.get(r['trend'], "#555")rows += (f'<tr><td style="padding:5px 10px">{r["rok"]}</td>' +f'<td style="padding:5px 10px">{Q_LABEL.get(r["ctvrtleti"], r["ctvrtleti"])}</td>' +f'<td style="padding:5px 10px;font-weight:700;color:#1a56db">{r["predikce_cest"]}</td>' +f'<td style="padding:5px 10px;color:{tc};font-weight:600">{r["trend"]}</td></tr>')tc_main = TREND_COLOR.get(trend_dir, "#555")return f"""<div style="font-family:'Segoe UI',sans-serif;padding:4px"><div style="display:flex;gap:24px;margin-bottom:12px;flex-wrap:wrap"><div style="background:#f0f4ff;border-radius:8px;padding:12px 18px;min-width:140px"><div style="font-size:0.8em;color:#666">Oblast</div><div style="font-size:1.2em;font-weight:700">{oblast}</div></div><div style="background:#f0fdf4;border-radius:8px;padding:12px 18px;min-width:140px"><div style="font-size:0.8em;color:#666">Trend</div><div style="font-size:1.2em;font-weight:700;color:{tc_main}">{trend_dir}</div><div style="font-size:0.78em;color:#888">sklon: {trend_sklon:+.2f}/čtvrtletí · R²: {trend_r2:.2f}</div></div></div><div style="margin-bottom:4px;font-size:0.85em;color:#555"><span style="color:#1a56db;font-weight:600">── Historie (2019–2025)</span> <span style="color:#f59e0b;font-weight:600">- - Předpověď (2026–2027)</span></div>{svg}<table style="border-collapse:collapse;width:100%;margin-top:10px;font-size:0.9em"><thead><tr style="background:#1a56db;color:white"><th style="padding:6px 10px;text-align:left">Rok</th><th style="padding:6px 10px;text-align:left">Čtvrtletí</th><th style="padding:6px 10px;text-align:left">Předp. cestujících</th><th style="padding:6px 10px;text-align:left">Trend</th></tr></thead><tbody>{rows}</tbody></table></div>"""trend_btn.click(zobraz_trend, inputs=trend_oblast, outputs=trend_out)# ── TAB 4: O modelu ───────────────────────────with gr.Tab("🧠 O modelu a etice"):gr.Markdown(f"""## Jak model funguje
app.py+139-12