Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -50,6 +50,23 @@ Was gegenüber der vorherigen Version kaputt war
|
|
| 50 |
ignoriert) – beides wird jetzt versionsabhängig übergeben. Die
|
| 51 |
Markdown-Tabelle kam mit Fehlerobjekten und leeren Listen nicht klar.
|
| 52 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
Start
|
| 54 |
-----
|
| 55 |
export client_id=... api_key=... # DB API Marketplace, "Timetables"
|
|
@@ -57,7 +74,8 @@ Start
|
|
| 57 |
python db_fahrplan_app.py
|
| 58 |
|
| 59 |
Optional: GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860,
|
| 60 |
-
HORIZON_HOURS, MAX_PLAN_REQUESTS, SEARCH_DEADLINE, EVA_CACHE_FILE
|
|
|
|
| 61 |
"""
|
| 62 |
from __future__ import annotations
|
| 63 |
|
|
@@ -90,14 +108,14 @@ BAHN_ORTE_URL = "https://www.bahn.de/web/api/reiseloesung/orte"
|
|
| 90 |
REQUEST_TIMEOUT = float(os.environ.get("REQUEST_TIMEOUT", 12))
|
| 91 |
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", 1))
|
| 92 |
RETRY_WAIT = 1.0
|
| 93 |
-
# Harte
|
| 94 |
# die App nach spaetestens so vielen Sekunden eine (erklaerte) Antwort liefern,
|
| 95 |
# statt minutenlang zu laufen.
|
| 96 |
SEARCH_DEADLINE = float(os.environ.get("SEARCH_DEADLINE", 25))
|
| 97 |
|
| 98 |
HORIZON_HOURS = int(os.environ.get("HORIZON_HOURS", 3)) # Abfahrtsfenster
|
| 99 |
MAX_RESULTS = 3
|
| 100 |
-
MAX_PLAN_REQUESTS = int(os.environ.get("MAX_PLAN_REQUESTS", 40)) # Budget pro
|
| 101 |
MAX_DIRECT_MINUTES = 4 * 60
|
| 102 |
TRANSFER_MIN_MINUTES = 4
|
| 103 |
TRANSFER_MAX_MINUTES = int(os.environ.get("TRANSFER_MAX_MINUTES", 45))
|
|
@@ -105,6 +123,11 @@ MAX_TRANSFER_HUBS = 5
|
|
| 105 |
MAX_HUB_HOURS = 8
|
| 106 |
STOP_TRAVEL_MINUTES = 3 # Grobeschaetzung pro Folgerhalt (nur Stundenwahl)
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
# Produkte, die auf einen Schienenhalt hinweisen (felder "products" der orte-Suche)
|
| 109 |
RAIL_PRODUCTS = {
|
| 110 |
"ICE", "EC_IC", "IR", "REGIONAL", "SBAHN", "NATIONAL",
|
|
@@ -195,6 +218,7 @@ def _path(raw) -> list[str]:
|
|
| 195 |
|
| 196 |
|
| 197 |
_START_TS: float | None = None
|
|
|
|
| 198 |
ORTE_BLOCKED = False
|
| 199 |
|
| 200 |
|
|
@@ -214,7 +238,7 @@ def _over_budget() -> bool:
|
|
| 214 |
"""Suchfrist ueberschritten oder Anfrage-Budget aufgebraucht?"""
|
| 215 |
if _START_TS and (time.monotonic() - _START_TS) > SEARCH_DEADLINE:
|
| 216 |
return True
|
| 217 |
-
return _STATS.get("plan", 0) >= MAX_PLAN_REQUESTS
|
| 218 |
|
| 219 |
|
| 220 |
def http_get(url: str, *, headers=None, params=None, accept_xml: bool = False,
|
|
@@ -442,7 +466,10 @@ def resolve_station(query: str, client_id: str, api_key: str, notes: Notes) -> d
|
|
| 442 |
others = "; ".join(f"{c['name']} ({c['eva']})" for c in pool[1:4])
|
| 443 |
notes.add(f"„{query}“ → {best['name']} ({best['eva']})"
|
| 444 |
+ (f" – weitere Treffer: {others}" if others else ""))
|
|
|
|
|
|
|
| 445 |
_MEM_CACHE[key] = {k: result[k] for k in ("name", "eva", "source", "products")}
|
|
|
|
| 446 |
_save_disk_cache()
|
| 447 |
return result
|
| 448 |
|
|
@@ -455,13 +482,21 @@ _PLAN_CACHE: dict[tuple, list[dict]] = {}
|
|
| 455 |
_STATS: dict[str, int] = {}
|
| 456 |
|
| 457 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
def _reset_stats() -> None:
|
| 459 |
"""Budget, Frist und Blockier-Marker zu Beginn jeder Suche zuruecksetzen."""
|
| 460 |
-
global
|
| 461 |
-
_START_TS = time.monotonic()
|
| 462 |
ORTE_BLOCKED = False
|
| 463 |
_STATS.clear()
|
| 464 |
_STATS.update({"plan": 0, "fchg": 0, "fehler": 0})
|
|
|
|
| 465 |
|
| 466 |
|
| 467 |
def parse_plan_xml(body) -> list[dict]:
|
|
@@ -936,6 +971,10 @@ HEADER_MAPPING = {
|
|
| 936 |
"hinweis": "Hinweis",
|
| 937 |
}
|
| 938 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 939 |
|
| 940 |
def json_to_markdown_table(json_data) -> str:
|
| 941 |
"""Toleriert Fehlerobjekte, den Ergebnis-Wrapper und leere Listen."""
|
|
@@ -951,18 +990,21 @@ def json_to_markdown_table(json_data) -> str:
|
|
| 951 |
text = data["error"]
|
| 952 |
extra = "\n\n".join(f"- {m}" for m in (data.get("diagnose") or [])[:6])
|
| 953 |
return f"**Fehler:** {text}" + (f"\n\n**Diagnose**\n{extra}" if extra else "")
|
|
|
|
| 954 |
if isinstance(data, dict):
|
|
|
|
| 955 |
data = data.get("verbindungen", [])
|
| 956 |
rows = [r for r in (data or []) if isinstance(r, dict)]
|
| 957 |
if not rows:
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
"
|
|
|
|
| 961 |
|
| 962 |
columns: list[str] = []
|
| 963 |
for row in rows:
|
| 964 |
for col in row:
|
| 965 |
-
if col not in columns and not col.startswith("_"):
|
| 966 |
columns.append(col)
|
| 967 |
headers = [HEADER_MAPPING.get(col, col) for col in columns]
|
| 968 |
lines = ["| " + " | ".join(headers) + " |",
|
|
@@ -996,6 +1038,46 @@ def _station_error(msg: str, notes: Notes, *, start=None, ziel=None, candidates=
|
|
| 996 |
return out
|
| 997 |
|
| 998 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 999 |
def search(departure: str, destination: str, *, hours: int = HORIZON_HOURS,
|
| 1000 |
max_results: int = MAX_RESULTS, allow_transfer: bool = True,
|
| 1001 |
via: str | None = None) -> dict:
|
|
@@ -1030,29 +1112,79 @@ def search(departure: str, destination: str, *, hours: int = HORIZON_HOURS,
|
|
| 1030 |
start=dep, ziel=dest,
|
| 1031 |
candidates=hub.get("candidates", []))
|
| 1032 |
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1038 |
result = {
|
| 1039 |
"status": "ok" if rows else "keine Verbindung gefunden",
|
| 1040 |
"verbindungen": rows,
|
| 1041 |
"zeitfenster": {"ab": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
| 1042 |
-
"stunden":
|
| 1043 |
-
"umstiege":
|
|
|
|
| 1044 |
"stationen": {
|
| 1045 |
"start": {k: dep.get(k) for k in ("name", "eva", "source", "products")},
|
| 1046 |
"ziel": {k: dest.get(k) for k in ("name", "eva", "source", "products")},
|
| 1047 |
-
"via": {k:
|
| 1048 |
},
|
| 1049 |
"diagnose": notes.items,
|
| 1050 |
"anfragen": dict(_STATS),
|
| 1051 |
}
|
| 1052 |
if not rows:
|
| 1053 |
-
result["hinweis"] = ("Keine Verbindung
|
| 1054 |
-
"
|
| 1055 |
-
"
|
|
|
|
|
|
|
|
|
|
| 1056 |
return result
|
| 1057 |
|
| 1058 |
|
|
@@ -1074,7 +1206,8 @@ with gr.Blocks(**_BLOCKS_KWARGS) as demo:
|
|
| 1074 |
gr.Markdown("# 🚆 DB │ Deutsche Bahn Zugverbindungen")
|
| 1075 |
gr.Markdown("_Bahnhöfe werden über die bahn.de-Ortssuche aufgelöst "
|
| 1076 |
"(unscharf, inkl. EVA-Nummern), Verbindungen aus dem "
|
| 1077 |
-
"DANA-Fahrplan – mit Umstiegen und Echtzeit-Overlay.
|
|
|
|
| 1078 |
|
| 1079 |
with gr.Row():
|
| 1080 |
dep_input = gr.Textbox(label="Abfahrtsort", placeholder="z.B. Schweinfurt Hbf")
|
|
@@ -1127,4 +1260,4 @@ if __name__ == "__main__":
|
|
| 1127 |
if not (CLIENT_ID and API_KEY):
|
| 1128 |
print("WARNUNG: Umgebungsvariablen client_id / api_key sind nicht gesetzt – "
|
| 1129 |
"die App startet, kann aber keine Fahrplandaten abrufen.")
|
| 1130 |
-
demo.launch(**_launch_kwargs())
|
|
|
|
| 50 |
ignoriert) – beides wird jetzt versionsabhängig übergeben. Die
|
| 51 |
Markdown-Tabelle kam mit Fehlerobjekten und leeren Listen nicht klar.
|
| 52 |
|
| 53 |
+
7) "Keine Verbindungen im gewählten Zeitfenster" (NEU, automatisch).
|
| 54 |
+
Statt dem Nutzer Tipps zu geben, erweitert `search()` die Suche selbst,
|
| 55 |
+
sobald nichts gefunden wird:
|
| 56 |
+
a) Umstiege einschalten,
|
| 57 |
+
b) Zeitfenster stufenweise vergrößern (6 h, dann `AUTO_MAX_HOURS` = 12 h),
|
| 58 |
+
c) einen festen "Umstieg über"-Halt verwerfen,
|
| 59 |
+
d) Name/EVA prüfen: alternative Bahnhöfe mit passendem Namen
|
| 60 |
+
(z.B. "Schweinfurt Mitte" statt "Schweinfurt Hbf") probieren.
|
| 61 |
+
Was automatisch angepasst wurde, steht in `diagnose`; das tatsächlich
|
| 62 |
+
genutzte Fenster in `zeitfenster`. Bei Zugriffsproblemen (401/403, kein
|
| 63 |
+
einziger Spielplan abrufbar) wird nicht erweitert – das würde nichts
|
| 64 |
+
ändern. Gesamtlimit: `AUTO_EXPAND_DEADLINE` Sekunden.
|
| 65 |
+
|
| 66 |
+
8) Ergebnistabelle schlanker. In der Markdown-Tabelle fehlen jetzt
|
| 67 |
+
Ankunftszeit, Zug, Richtung, Art (treffer) und Hinweis
|
| 68 |
+
(`HIDDEN_COLUMNS`). Das JSON ("Rohdaten") enthält weiterhin alles.
|
| 69 |
+
|
| 70 |
Start
|
| 71 |
-----
|
| 72 |
export client_id=... api_key=... # DB API Marketplace, "Timetables"
|
|
|
|
| 74 |
python db_fahrplan_app.py
|
| 75 |
|
| 76 |
Optional: GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860,
|
| 77 |
+
HORIZON_HOURS, MAX_PLAN_REQUESTS, SEARCH_DEADLINE, EVA_CACHE_FILE,
|
| 78 |
+
AUTO_MAX_HOURS, AUTO_EXPAND_DEADLINE.
|
| 79 |
"""
|
| 80 |
from __future__ import annotations
|
| 81 |
|
|
|
|
| 108 |
REQUEST_TIMEOUT = float(os.environ.get("REQUEST_TIMEOUT", 12))
|
| 109 |
MAX_RETRIES = int(os.environ.get("MAX_RETRIES", 1))
|
| 110 |
RETRY_WAIT = 1.0
|
| 111 |
+
# Harte Frist pro Suchstufe: wenn bahn.de/DANA haengen oder blockieren, soll
|
| 112 |
# die App nach spaetestens so vielen Sekunden eine (erklaerte) Antwort liefern,
|
| 113 |
# statt minutenlang zu laufen.
|
| 114 |
SEARCH_DEADLINE = float(os.environ.get("SEARCH_DEADLINE", 25))
|
| 115 |
|
| 116 |
HORIZON_HOURS = int(os.environ.get("HORIZON_HOURS", 3)) # Abfahrtsfenster
|
| 117 |
MAX_RESULTS = 3
|
| 118 |
+
MAX_PLAN_REQUESTS = int(os.environ.get("MAX_PLAN_REQUESTS", 40)) # Budget pro Suchstufe
|
| 119 |
MAX_DIRECT_MINUTES = 4 * 60
|
| 120 |
TRANSFER_MIN_MINUTES = 4
|
| 121 |
TRANSFER_MAX_MINUTES = int(os.environ.get("TRANSFER_MAX_MINUTES", 45))
|
|
|
|
| 123 |
MAX_HUB_HOURS = 8
|
| 124 |
STOP_TRAVEL_MINUTES = 3 # Grobeschaetzung pro Folgerhalt (nur Stundenwahl)
|
| 125 |
|
| 126 |
+
# Automatische Erweiterung bei leerem Ergebnis
|
| 127 |
+
AUTO_MAX_HOURS = max(1, min(int(os.environ.get("AUTO_MAX_HOURS", 12)), 12))
|
| 128 |
+
AUTO_EXPAND_DEADLINE = float(os.environ.get("AUTO_EXPAND_DEADLINE", 60)) # Sekunden gesamt
|
| 129 |
+
MAX_ALT_STATIONS = 2 # Alternativbahnhoefe je Seite (Start/Ziel)
|
| 130 |
+
|
| 131 |
# Produkte, die auf einen Schienenhalt hinweisen (felder "products" der orte-Suche)
|
| 132 |
RAIL_PRODUCTS = {
|
| 133 |
"ICE", "EC_IC", "IR", "REGIONAL", "SBAHN", "NATIONAL",
|
|
|
|
| 218 |
|
| 219 |
|
| 220 |
_START_TS: float | None = None
|
| 221 |
+
_PLAN_BASE = 0 # Zaehlerstand "plan" zu Beginn der aktuellen Suchstufe
|
| 222 |
ORTE_BLOCKED = False
|
| 223 |
|
| 224 |
|
|
|
|
| 238 |
"""Suchfrist ueberschritten oder Anfrage-Budget aufgebraucht?"""
|
| 239 |
if _START_TS and (time.monotonic() - _START_TS) > SEARCH_DEADLINE:
|
| 240 |
return True
|
| 241 |
+
return (_STATS.get("plan", 0) - _PLAN_BASE) >= MAX_PLAN_REQUESTS
|
| 242 |
|
| 243 |
|
| 244 |
def http_get(url: str, *, headers=None, params=None, accept_xml: bool = False,
|
|
|
|
| 466 |
others = "; ".join(f"{c['name']} ({c['eva']})" for c in pool[1:4])
|
| 467 |
notes.add(f"„{query}“ → {best['name']} ({best['eva']})"
|
| 468 |
+ (f" – weitere Treffer: {others}" if others else ""))
|
| 469 |
+
# Kandidaten mitcachen, damit die Alternativhalt-Suche auch bei Cache-Treffern
|
| 470 |
+
# funktioniert.
|
| 471 |
_MEM_CACHE[key] = {k: result[k] for k in ("name", "eva", "source", "products")}
|
| 472 |
+
_MEM_CACHE[key]["candidates"] = result["candidates"][:4]
|
| 473 |
_save_disk_cache()
|
| 474 |
return result
|
| 475 |
|
|
|
|
| 482 |
_STATS: dict[str, int] = {}
|
| 483 |
|
| 484 |
|
| 485 |
+
def _reset_budget() -> None:
|
| 486 |
+
"""Frist und Anfrage-Budget fuer eine neue Suchstufe frisch starten.
|
| 487 |
+
Die Zaehler in _STATS laufen weiter (fuer die Ausgabe 'anfragen')."""
|
| 488 |
+
global _START_TS, _PLAN_BASE
|
| 489 |
+
_START_TS = time.monotonic()
|
| 490 |
+
_PLAN_BASE = _STATS.get("plan", 0)
|
| 491 |
+
|
| 492 |
+
|
| 493 |
def _reset_stats() -> None:
|
| 494 |
"""Budget, Frist und Blockier-Marker zu Beginn jeder Suche zuruecksetzen."""
|
| 495 |
+
global ORTE_BLOCKED
|
|
|
|
| 496 |
ORTE_BLOCKED = False
|
| 497 |
_STATS.clear()
|
| 498 |
_STATS.update({"plan": 0, "fchg": 0, "fehler": 0})
|
| 499 |
+
_reset_budget()
|
| 500 |
|
| 501 |
|
| 502 |
def parse_plan_xml(body) -> list[dict]:
|
|
|
|
| 971 |
"hinweis": "Hinweis",
|
| 972 |
}
|
| 973 |
|
| 974 |
+
# Spalten, die in der Markdown-Tabelle NICHT angezeigt werden (im JSON bleiben
|
| 975 |
+
# sie erhalten). Zum Wieder-Einblenden einfach den Eintrag entfernen.
|
| 976 |
+
HIDDEN_COLUMNS = {"ankunftszeit", "zug", "richtung", "treffer", "hinweis"}
|
| 977 |
+
|
| 978 |
|
| 979 |
def json_to_markdown_table(json_data) -> str:
|
| 980 |
"""Toleriert Fehlerobjekte, den Ergebnis-Wrapper und leere Listen."""
|
|
|
|
| 990 |
text = data["error"]
|
| 991 |
extra = "\n\n".join(f"- {m}" for m in (data.get("diagnose") or [])[:6])
|
| 992 |
return f"**Fehler:** {text}" + (f"\n\n**Diagnose**\n{extra}" if extra else "")
|
| 993 |
+
diagnose: list = []
|
| 994 |
if isinstance(data, dict):
|
| 995 |
+
diagnose = data.get("diagnose") or []
|
| 996 |
data = data.get("verbindungen", [])
|
| 997 |
rows = [r for r in (data or []) if isinstance(r, dict)]
|
| 998 |
if not rows:
|
| 999 |
+
extra = "\n\n".join(f"- {m}" for m in diagnose[:6])
|
| 1000 |
+
return ("_Keine Verbindungen gefunden – auch nicht nach automatischer "
|
| 1001 |
+
"Erweiterung (Umstiege, größeres Zeitfenster, alternative Bahnhöfe)._"
|
| 1002 |
+
+ (f"\n\n**Diagnose**\n{extra}" if extra else ""))
|
| 1003 |
|
| 1004 |
columns: list[str] = []
|
| 1005 |
for row in rows:
|
| 1006 |
for col in row:
|
| 1007 |
+
if col not in columns and not col.startswith("_") and col not in HIDDEN_COLUMNS:
|
| 1008 |
columns.append(col)
|
| 1009 |
headers = [HEADER_MAPPING.get(col, col) for col in columns]
|
| 1010 |
lines = ["| " + " | ".join(headers) + " |",
|
|
|
|
| 1038 |
return out
|
| 1039 |
|
| 1040 |
|
| 1041 |
+
def _escalation_stages(hours: int, allow_transfer: bool, hub: dict | None) -> list[tuple]:
|
| 1042 |
+
"""Suchstufen (Stunden, Umstiege, fester Umstiegshalt, Beschriftung).
|
| 1043 |
+
Stufe 0 ist exakt die Nutzereinstellung; jede weitere Stufe ist 'weiter'
|
| 1044 |
+
als die vorige: Umstiege an -> 6 h -> AUTO_MAX_HOURS -> ohne festen Halt."""
|
| 1045 |
+
first_transfer = bool(allow_transfer) or hub is not None
|
| 1046 |
+
stages: list[tuple] = [(hours, first_transfer, hub, "")]
|
| 1047 |
+
seen = {(hours, first_transfer, bool(hub))}
|
| 1048 |
+
|
| 1049 |
+
def add(h: int, transfer: bool, hb: dict | None, label: str) -> None:
|
| 1050 |
+
key = (h, transfer, bool(hb))
|
| 1051 |
+
if key not in seen:
|
| 1052 |
+
seen.add(key)
|
| 1053 |
+
stages.append((h, transfer, hb, label))
|
| 1054 |
+
|
| 1055 |
+
add(hours, True, hub, "Umstiege aktiviert")
|
| 1056 |
+
for h in (6, AUTO_MAX_HOURS):
|
| 1057 |
+
if h > hours:
|
| 1058 |
+
add(h, True, hub, f"Zeitfenster auf {h} h vergrößert")
|
| 1059 |
+
if hub:
|
| 1060 |
+
add(max(hours, AUTO_MAX_HOURS), True, None,
|
| 1061 |
+
f"fester Umstieg über {hub['name']} verworfen")
|
| 1062 |
+
return stages
|
| 1063 |
+
|
| 1064 |
+
|
| 1065 |
+
def _alt_stations(query: str, base: dict, other_eva: str) -> list[dict]:
|
| 1066 |
+
"""Weitere Bahnhoefe mit passendem Namen aus der Kandidatenliste der Suche."""
|
| 1067 |
+
out: list[dict] = []
|
| 1068 |
+
for cand in base.get("candidates") or []:
|
| 1069 |
+
eva = str(cand.get("eva") or "")
|
| 1070 |
+
if not eva or eva in (base["eva"], other_eva):
|
| 1071 |
+
continue
|
| 1072 |
+
if not name_matches(query, cand.get("name") or ""):
|
| 1073 |
+
continue
|
| 1074 |
+
out.append({"name": cand["name"], "eva": eva, "source": "Alternativhalt",
|
| 1075 |
+
"products": cand.get("products") or []})
|
| 1076 |
+
if len(out) >= MAX_ALT_STATIONS:
|
| 1077 |
+
break
|
| 1078 |
+
return out
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
def search(departure: str, destination: str, *, hours: int = HORIZON_HOURS,
|
| 1082 |
max_results: int = MAX_RESULTS, allow_transfer: bool = True,
|
| 1083 |
via: str | None = None) -> dict:
|
|
|
|
| 1112 |
start=dep, ziel=dest,
|
| 1113 |
candidates=hub.get("candidates", []))
|
| 1114 |
|
| 1115 |
+
# ---- Suche mit automatischer Erweiterung bei leerem Ergebnis ----------
|
| 1116 |
+
def run(a: dict, b: dict, h: int, transfer: bool, hb: dict | None) -> list[dict]:
|
| 1117 |
+
_reset_budget()
|
| 1118 |
+
return search_connections(
|
| 1119 |
+
a, b, client_id=CLIENT_ID, api_key=API_KEY, notes=notes,
|
| 1120 |
+
hours=h, max_results=max_results, allow_transfer=transfer, hub=hb)
|
| 1121 |
+
|
| 1122 |
+
def no_access() -> bool:
|
| 1123 |
+
# Fehler, aber kein einziger Spielplan abrufbar (401/403/Netz): mehr
|
| 1124 |
+
# Stunden oder Alternativhalte aendern daran nichts.
|
| 1125 |
+
return bool(_STATS.get("fehler")) and not _STATS.get("plan")
|
| 1126 |
+
|
| 1127 |
+
t0 = time.monotonic()
|
| 1128 |
+
rows: list[dict] = []
|
| 1129 |
+
used_hours, used_transfer, used_hub = hours, bool(allow_transfer) or hub is not None, hub
|
| 1130 |
+
expanded = False
|
| 1131 |
+
|
| 1132 |
+
for idx, (h, transfer, hb, label) in enumerate(_escalation_stages(hours, allow_transfer, hub)):
|
| 1133 |
+
if idx and (time.monotonic() - t0) > AUTO_EXPAND_DEADLINE:
|
| 1134 |
+
notes.add(f"Automatische Erweiterung nach {AUTO_EXPAND_DEADLINE:.0f}s abgebrochen.")
|
| 1135 |
+
break
|
| 1136 |
+
rows = run(dep, dest, h, transfer, hb)
|
| 1137 |
+
used_hours, used_transfer, used_hub = h, transfer, hb
|
| 1138 |
+
if rows:
|
| 1139 |
+
if idx:
|
| 1140 |
+
expanded = True
|
| 1141 |
+
notes.add(f"Automatisch angepasst: {label}.")
|
| 1142 |
+
break
|
| 1143 |
+
if no_access():
|
| 1144 |
+
break
|
| 1145 |
+
|
| 1146 |
+
if not rows and not no_access():
|
| 1147 |
+
# Name/EVA pruefen: andere Bahnhoefe mit passendem Namen probieren
|
| 1148 |
+
combos = ([(alt, dest) for alt in _alt_stations(departure, dep, dest["eva"])]
|
| 1149 |
+
+ [(dep, alt) for alt in _alt_stations(destination, dest, dep["eva"])])
|
| 1150 |
+
for a, b in combos:
|
| 1151 |
+
if (time.monotonic() - t0) > AUTO_EXPAND_DEADLINE:
|
| 1152 |
+
notes.add(f"Alternativhalt-Suche nach {AUTO_EXPAND_DEADLINE:.0f}s abgebrochen.")
|
| 1153 |
+
break
|
| 1154 |
+
h = max(hours, AUTO_MAX_HOURS)
|
| 1155 |
+
rows = run(a, b, h, True, None)
|
| 1156 |
+
if rows:
|
| 1157 |
+
dep, dest = a, b
|
| 1158 |
+
used_hours, used_transfer, used_hub = h, True, None
|
| 1159 |
+
expanded = True
|
| 1160 |
+
notes.add(f"Automatisch angepasst: Alternativhalte verwendet "
|
| 1161 |
+
f"({a['name']} → {b['name']}, {a['eva']} → {b['eva']}).")
|
| 1162 |
+
break
|
| 1163 |
+
if no_access():
|
| 1164 |
+
break
|
| 1165 |
+
|
| 1166 |
result = {
|
| 1167 |
"status": "ok" if rows else "keine Verbindung gefunden",
|
| 1168 |
"verbindungen": rows,
|
| 1169 |
"zeitfenster": {"ab": datetime.now().strftime("%Y-%m-%d %H:%M"),
|
| 1170 |
+
"stunden": used_hours,
|
| 1171 |
+
"umstiege": used_transfer,
|
| 1172 |
+
"automatisch_erweitert": expanded},
|
| 1173 |
"stationen": {
|
| 1174 |
"start": {k: dep.get(k) for k in ("name", "eva", "source", "products")},
|
| 1175 |
"ziel": {k: dest.get(k) for k in ("name", "eva", "source", "products")},
|
| 1176 |
+
"via": {k: used_hub.get(k) for k in ("name", "eva", "source")} if used_hub else None,
|
| 1177 |
},
|
| 1178 |
"diagnose": notes.items,
|
| 1179 |
"anfragen": dict(_STATS),
|
| 1180 |
}
|
| 1181 |
if not rows:
|
| 1182 |
+
result["hinweis"] = ("Keine Verbindung gefunden – auch nach automatischer "
|
| 1183 |
+
"Erweiterung (Umstiege, bis zu "
|
| 1184 |
+
f"{AUTO_MAX_HOURS} h, Alternativhalte). Mögliche Gründe: "
|
| 1185 |
+
"Station ohne DANA-Fahrplan, Zugriffsproblem (siehe "
|
| 1186 |
+
"diagnose/anfragen) oder keine Verbindung mit höchstens "
|
| 1187 |
+
"einem Umstieg.")
|
| 1188 |
return result
|
| 1189 |
|
| 1190 |
|
|
|
|
| 1206 |
gr.Markdown("# 🚆 DB │ Deutsche Bahn Zugverbindungen")
|
| 1207 |
gr.Markdown("_Bahnhöfe werden über die bahn.de-Ortssuche aufgelöst "
|
| 1208 |
"(unscharf, inkl. EVA-Nummern), Verbindungen aus dem "
|
| 1209 |
+
"DANA-Fahrplan – mit Umstiegen und Echtzeit-Overlay. "
|
| 1210 |
+
"Ohne Treffer wird die Suche automatisch erweitert._")
|
| 1211 |
|
| 1212 |
with gr.Row():
|
| 1213 |
dep_input = gr.Textbox(label="Abfahrtsort", placeholder="z.B. Schweinfurt Hbf")
|
|
|
|
| 1260 |
if not (CLIENT_ID and API_KEY):
|
| 1261 |
print("WARNUNG: Umgebungsvariablen client_id / api_key sind nicht gesetzt – "
|
| 1262 |
"die App startet, kann aber keine Fahrplandaten abrufen.")
|
| 1263 |
+
demo.launch(**_launch_kwargs())
|