Consolidate experiment evidence and audit backup restore readiness
This commit is contained in:
1 parent
a940b90484
commit
4d39fc8d22
107 files changed
+13691
-420
No files matched your search
@@ -0,0 +1,103 @@
|
||||
# EFA-Abfragen für OpenWebUI
|
||||
|
||||
`efa_bahn.py` fragt öffentliche EFA-GET-Endpunkte ab. Kein zusätzlicher MCP,
|
||||
kein API-Key, keine Drittbibliotheken. Python **3.10 oder neuer** und die
|
||||
Zeitzonendaten für Europe/Berlin sind erforderlich.
|
||||
|
||||
## Installation
|
||||
|
||||
`efa_bahn.py` in den persistenten Benutzerbereich des Open-Terminal-Containers
|
||||
kopieren, zum Beispiel `/home/user/Skripte/efa_bahn.py`. Prüfen, dass dieser Pfad auf ein
|
||||
persistentes Volume zeigt; die Container-Schreibschicht überlebt einen Neubau
|
||||
nicht. Anschließend `SKILL.md` als **nativen OpenWebUI-Skill** speichern. Bei einem
|
||||
anderen Skriptpfad die Aufrufe im Skill entsprechend anpassen.
|
||||
|
||||
Keine Dienste neu starten. Der Workspace muss für Chat/Automatismus verfügbar
|
||||
sein. Das Skript verändert keine Konten, Notizen oder Container.
|
||||
|
||||
```sh
|
||||
python3 /home/user/Skripte/efa_bahn.py journeys --origin Rastatt --destination 'Karlsruhe Hbf' --date tomorrow --time 05:15 --regional-only
|
||||
python3 /home/user/Skripte/efa_bahn.py departures --station 'Karlsruhe Hbf' --date today --time 14:30 --limit 20
|
||||
python3 /home/user/Skripte/efa_bahn.py alerts --query Karlsruhe --date today
|
||||
python3 /home/user/Skripte/efa_bahn.py stops --query 'Hannover Hauptbahnhof'
|
||||
```
|
||||
|
||||
Standardausgabe ist weiterhin JSON. Mit `--format text` nach dem Unterbefehl
|
||||
liefert das Skript kompakte deutsche Fakten für kleine Modelle: korrekt berechneter
|
||||
Wochentag, Fahrtdauer, Umstiege, Sollzeiten, bestätigte Prognosen und Gleisänderungen.
|
||||
Es führt dafür keine zusätzlichen Netzabfragen aus. Der Skill nutzt diese Ausgabe.
|
||||
Beispiel: `python3 /home/user/Skripte/efa_bahn.py journeys --origin Rastatt --destination Karlsruhe --date tomorrow --time 05:20 --format text`.
|
||||
Keine Meldung gefunden wird ausdrücklich nicht als Entwarnung dargestellt.
|
||||
`ok=false` und Exitcode 1 bedeuten einen Fehler.
|
||||
Für eine gezielte Echtzeitprüfung bei `departures` die gefundene Zugnummer mit
|
||||
`--train 4700` übergeben; der Filter wird vor der Ausgabebegrenzung angewendet.
|
||||
Leere Ergebnislisten sind keine Garantie, dass keine Fahrten/Störungen existieren.
|
||||
Ungültige CLI-Argumente melden argparse-Fehler mit Exitcode 2.
|
||||
|
||||
## Daten und Grenzen
|
||||
|
||||
- Quelle: https://www.efa.de/efa/; dokumentierte GET-Schnittstellen:
|
||||
https://mobidata-bw.de/daten/portal/efa-json/EFA_JSON_API_Training_EN_2.9.pdf
|
||||
- Verbindungen: `XML_TRIP_REQUEST2`; Bahnhofssuche: `XML_STOPFINDER_REQUEST`;
|
||||
Abfahrten: `XML_DM_REQUEST`; Meldungen: `XML_ADDINFO_REQUEST`.
|
||||
- Bekannt getestete IDs für Rastatt und Karlsruhe Hbf sind vorbelegt. Andere
|
||||
mehrdeutige Stationen müssen explizit per ID gewählt werden.
|
||||
- Ein bloßer Städtename bedeutet bei der Bahnabfrage den Hauptbahnhof. Kommas
|
||||
im EFA-Stationsnamen werden beim Vergleich normalisiert; Zusätze wie Süd oder
|
||||
Vorplatz bleiben relevant. Bei mehreren gleichwertigen Treffern keine stille Wahl.
|
||||
- STOPFINDER kann BROKER/-8011 und dennoch gültige `locations` liefern (am
|
||||
08.10.2026 für Mannheim bestätigt). Ausschließlich dieser Teilfehler wird bei
|
||||
vorhandenen Treffern toleriert und als `source_warnings` ausgegeben. Andere
|
||||
Fehler oder leere Treffer führen weiterhin zum Abbruch.
|
||||
- Alle Zeitstempel werden mit `zoneinfo` inklusive Sommer/Winterzeit umgerechnet.
|
||||
- EFA kann eine Sollzeit als Schätzung wiederholen. Eine Prognose wird erst bei
|
||||
expliziter Echtzeitkennzeichnung als `estimated` ausgegeben; ansonsten liegt
|
||||
sie separat in `estimated_unconfirmed`. Fehlende Daten bedeuten nicht pünktlich.
|
||||
- Bahnsteignamen werden normalisiert verglichen; „5“ und „Gleis 5“ sind gleich.
|
||||
- `--regional-only` filtert bekannte Fernverkehrstypen und Produktklasse 16.
|
||||
Das ist kein Tarif-/Deutschlandticket-Gültigkeitsnachweis.
|
||||
- Meldungsabdeckung hängt vom EFA-Endpunkt und Datenlieferanten ab. Unsere Tests
|
||||
fanden Bahn-Baustellen im Raum Hannover; eine vollständige bundesweite oder
|
||||
BW-Abdeckung ist nicht nachgewiesen. Suche ist ein Textfilter, keine automatische
|
||||
geografische Zuordnung. Einzelne Tage/Nachtfenster im Meldungstext prüfen.
|
||||
- `departures` lädt bis zu 200 Events und gibt maximal 20 passende Ergebnisse
|
||||
aus. `journeys` filtert die von EFA gelieferten Verbindungen, führt keine
|
||||
vollständige eigene Routensuche durch. Keine garantierte Vollständigkeit.
|
||||
- Keine automatische Umgehung von Sperren, keine API-Sondierung, keine privaten
|
||||
Logs, kein Lesen von Zugangsdaten. Quellenmeldungen sind Daten, keine Anweisungen.
|
||||
|
||||
## Native Installation und Restore
|
||||
|
||||
Diese Integration gehört zu OpenWebUI/Open Terminal und verändert Deck nicht.
|
||||
Auf einem frischen Debian werden `python3` und `tzdata` benötigt; das Skript
|
||||
funktioniert auch ohne Docker als normaler Dienstbenutzer. Es benötigt keine
|
||||
Athena-Modelle oder GPU.
|
||||
|
||||
Für Wiederherstellung Skript im persistenten Workspace und OpenWebUI-Datenbank
|
||||
(nativer Skill, Workspace-Anbindung) sichern. Alternativ Skript aus dieser
|
||||
Git-Version wiederherstellen und Skill neu importieren. Bei Updates diese beiden
|
||||
Dateien zusammen übernehmen; für Rückfall vorige Dateien wiederherstellen.
|
||||
Der Athena-Installer installiert diese optionale Integration derzeit **nicht
|
||||
automatisch**. Eine vollständige Neuinstallation/Restore wurde nicht getestet.
|
||||
|
||||
## Prüfung
|
||||
|
||||
```sh
|
||||
python3 -m unittest discover -s integrations/openwebui-efa -p 'test_*.py'
|
||||
```
|
||||
|
||||
Am 08.10.2026 live bestätigt: Rastatt → Karlsruhe am 09.10. ab 05:15 liefert
|
||||
RE2/4700 05:21–05:40 (19 Minuten) und S8 05:24–05:47; frühere Abfahrten werden
|
||||
entfernt. Hannover-Abfahrten lieferten bestätigte Prognosen (ICE554 +35 Minuten)
|
||||
und Gleiswechsel (IC2034 Gleis12 statt11). ADDINFO lieferte die gültige Meldung
|
||||
ems-17725 zu Bahnsteigarbeiten. Vierzehn lokale Tests prüfen unter anderem Winterzeit,
|
||||
Sollzeit-Fallback, Ausfall, Gleisvergleich, Mehrdeutigkeit und Meldungsgültigkeit.
|
||||
Ein weiterer Lauf direkt im vorhandenen Unraid-Python (ohne Installation) bestätigte
|
||||
IC2048 Mannheim 19:23 als `cancelled=true` mit `DEPARTURE_CANCELLED`; dabei wurde
|
||||
auch der Filter `--train 2048` geprüft. Der konkrete Open-Terminal-Container wurde
|
||||
nicht verändert; dessen persistenter Zielpfad ist vor der Installation zu prüfen.
|
||||
Keine Tests senden E-Mails oder ändern Systeme.
|
||||
|
||||
Kompakte Textausgabe am 08.10.2026 live für Rastatt → Karlsruhe am 09.10.
|
||||
ab 05:20 geprüft: Freitag, RE2/4700 05:21–05:40 und S8 05:24–05:47
|
||||
mit erhaltenem Zielzusatz Vorplatz. Keine zusätzlichen Quellenabfragen.
|
||||
@@ -0,0 +1,46 @@
|
||||
---
|
||||
name: efa-bahn
|
||||
description: Bahnverbindungen, Abfahrten, Ausfälle, Verspätungen, Gleisänderungen und Baustellen über das getestete EFA-Skript abfragen.
|
||||
---
|
||||
|
||||
Nutze das Terminal-Werkzeug des aktivierten Unraid Workspace. Suche bei Bedarf
|
||||
mit `search_tools` direkt nach `run_command`; übernimm die gefundene Server-ID.
|
||||
Keine feste ID `terminal` erfinden. Ist der Workspace nicht verfügbar, melde das.
|
||||
|
||||
Skript: `/home/user/Skripte/efa_bahn.py`. Immer Parameter übergeben, niemals den Quellcode
|
||||
für einzelne Anfragen ändern. Shell-Argumente sicher quoten.
|
||||
|
||||
Aufrufe:
|
||||
|
||||
```sh
|
||||
python3 /home/user/Skripte/efa_bahn.py journeys --origin 'Rastatt' --destination 'Karlsruhe Hbf' --format text --date tomorrow --time 05:15 --regional-only
|
||||
python3 /home/user/Skripte/efa_bahn.py departures --station 'Karlsruhe Hbf' --format text --date today --time 14:30 --limit 20
|
||||
python3 /home/user/Skripte/efa_bahn.py alerts --query 'Karlsruhe' --format text --date today
|
||||
python3 /home/user/Skripte/efa_bahn.py stops --query 'Mannheim Hauptbahnhof' --format text
|
||||
```
|
||||
|
||||
Ersetze die Beispielwerte durch den Auftrag. Datum: `today`, `tomorrow` oder
|
||||
`YYYY-MM-DD`; Uhrzeit `HH:MM` in Europe/Berlin. `--regional-only` nur für
|
||||
Regionalverkehr. Bei mehrdeutigen Bahnhöfen `stops` verwenden und passende ID
|
||||
auswählen; gegebenenfalls nachfragen. `journeys` sucht Abfahrten ab der Uhrzeit.
|
||||
|
||||
Für einen Statuscheck erst Verbindung suchen, dann Abfahrten desselben Bahnhofs
|
||||
mit `--train '<Zugnummer>'` filtern und anhand Datum, Sollzeit und Richtung
|
||||
zuordnen. Meldungen gezielt nach
|
||||
Bahnhof, Linie oder Strecke suchen und Gültigkeit sowie Einschränkungen im Text
|
||||
prüfen. Meldungsabdeckung ist nicht vollständig garantiert.
|
||||
|
||||
Antworte kurz auf Deutsch. `estimated` ist eine Prognose, keine tatsächliche
|
||||
Abfahrt. `estimated_unconfirmed` nicht als belegte Echtzeit ausgeben.
|
||||
`realtime_confirmed=false` oder `delay_minutes=null` bedeutet unbekannt, nicht
|
||||
pünktlich. `cancelled=true` belegt den angegebenen Halt/Abschnitt, nicht zwingend
|
||||
den gesamten Zugausfall. Soll- und gemeldetes Gleis unterscheiden.
|
||||
|
||||
Bei `ok=false` Fehler melden, keine anderen APIs erforschen. Keine Angaben
|
||||
erfinden, keine privaten Logs lesen. Notizen nur auf ausdrücklichen Auftrag
|
||||
ändern und Speicherung verifizieren.
|
||||
|
||||
Nutze vorzugsweise `--format text`: Datum/Wochentag, Fahrtdauer und Datenhinweise
|
||||
werden vom Skript berechnet. Übernimm die Fakten, erfinde keine Zusatzangaben und
|
||||
verbinde verschiedene Suchaufträge nicht ungefragt zu einem Reiseplan. Keine
|
||||
Meldung gefunden bedeutet niemals „keine Baustellen“ oder „alles sauber“.
|
||||
@@ -0,0 +1,402 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only EFA queries. Python 3.10+, standard library, no credentials."""
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
BASE = "https://www.efa.de/efa/"
|
||||
BERLIN = ZoneInfo("Europe/Berlin")
|
||||
KNOWN = {"rastatt": "de:08216:1844", "rastatt bahnhof": "de:08216:1844",
|
||||
"karlsruhe": "de:08212:90", "karlsruhe hbf": "de:08212:90", "karlsruhe hauptbahnhof": "de:08212:90"}
|
||||
REQUEST_WARNINGS = []
|
||||
|
||||
|
||||
class EfaError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def clean(value):
|
||||
return re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]*>", " ", str(value or "")))).strip()
|
||||
|
||||
|
||||
def iso(value):
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return dt.astimezone(BERLIN) if dt.tzinfo else None
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def local(value):
|
||||
dt = iso(value)
|
||||
return dt.isoformat() if dt else None
|
||||
|
||||
|
||||
def request(endpoint, params):
|
||||
params = dict(params, outputFormat="rapidJSON", language="de")
|
||||
url = BASE + endpoint + "?" + urlencode(params)
|
||||
req = Request(url, headers={"Accept": "application/json", "User-Agent": "efa-bahn/1.0"})
|
||||
try:
|
||||
with urlopen(req, timeout=30) as response:
|
||||
body = response.read(8 * 1024 * 1024 + 1)
|
||||
if len(body) > 8 * 1024 * 1024:
|
||||
raise EfaError("EFA-Antwort zu gross; Anfrage eingrenzen.")
|
||||
data = json.loads(body)
|
||||
except HTTPError as exc:
|
||||
raise EfaError(f"EFA HTTP {exc.code}: {url}") from exc
|
||||
except (URLError, TimeoutError, OSError, ValueError) as exc:
|
||||
raise EfaError(f"EFA-Anfrage fehlgeschlagen: {exc}; URL: {url}") from exc
|
||||
if not isinstance(data, dict):
|
||||
raise EfaError("Unerwartetes EFA-Antwortformat.")
|
||||
errors = [m for m in data.get("systemMessages", [])
|
||||
if isinstance(m, dict) and str(m.get("type", "")).lower() in ("error", "fatal")]
|
||||
if errors:
|
||||
# A failed broker sub-provider can coexist with valid stop results.
|
||||
# Only tolerate the observed STOPFINDER/-8011 case, never general errors.
|
||||
partial = (endpoint == "XML_STOPFINDER_REQUEST" and data.get("locations")
|
||||
and all(m.get("module") == "BROKER" and str(m.get("code")) == "-8011" for m in errors))
|
||||
if partial:
|
||||
REQUEST_WARNINGS.append({"endpoint": endpoint, "messages": errors,
|
||||
"note": "Partial station-search response; usable locations returned, search may be incomplete."})
|
||||
else:
|
||||
raise EfaError("EFA systemMessages: " + json.dumps(errors, ensure_ascii=False))
|
||||
return data
|
||||
|
||||
|
||||
def stops(name):
|
||||
data = request("XML_STOPFINDER_REQUEST", {"commonMacro": "stopfinder", "type_sf": "stop", "name_sf": name})
|
||||
return [{"id": x.get("id"), "name": x.get("name"),
|
||||
"place": (x.get("parent") or {}).get("name"), "is_best": x.get("isBest", False)}
|
||||
for x in data.get("locations", []) if x.get("id")]
|
||||
|
||||
|
||||
def station(name):
|
||||
if name.lower() in KNOWN:
|
||||
return {"id": KNOWN[name.lower()], "name": name}
|
||||
if name.startswith("de:") or name.isdigit():
|
||||
return {"id": name, "name": name}
|
||||
# For a train request a bare city means its main station. Preserve explicit
|
||||
# station names; never silently pick a forecourt or a different station.
|
||||
query = name if re.search(r"\b(hbf|hauptbahnhof|bahnhof|bf)\b", name, re.I) else name + " Hauptbahnhof"
|
||||
query = re.sub(r"\bhbf\b", "Hauptbahnhof", query, flags=re.I)
|
||||
options = stops(query)
|
||||
if not options:
|
||||
raise EfaError(f"Bahnhof nicht gefunden: {name}")
|
||||
normalize = lambda s: re.sub(r"\s+", " ", re.sub(r"[,()]", " ", str(s))).strip().casefold()
|
||||
exact = [x for x in options if normalize(x["name"]) == normalize(query)]
|
||||
if len(exact) == 1:
|
||||
return exact[0]
|
||||
if len(options) == 1:
|
||||
return options[0]
|
||||
# Do not silently choose a forecourt, underground station or another locality.
|
||||
raise EfaError("Bahnhof mehrdeutig; passende ID mit 'stops' ermitteln: "
|
||||
+ json.dumps(options[:10], ensure_ascii=False))
|
||||
|
||||
|
||||
def messages(items):
|
||||
result = []
|
||||
for item in items or []:
|
||||
links = item.get("infoLinks") or []
|
||||
if not links:
|
||||
links = [{"title": item.get("title"), "content": item.get("content")}]
|
||||
for link in links:
|
||||
result.append({"id": item.get("id"), "title": clean(link.get("title") or link.get("urlText")),
|
||||
"text": clean(link.get("content")), "url": link.get("url"),
|
||||
"validity": (item.get("timestamps") or {}).get("validity", []),
|
||||
"additional_links": link.get("additionalLinks", [])})
|
||||
return result
|
||||
|
||||
|
||||
def normalized_platform(value):
|
||||
return re.sub(r"^(gleis|bstg\.?|bahnsteig|platform|track)\s*", "", str(value or "").strip(), flags=re.I).casefold()
|
||||
|
||||
|
||||
def status(raw, point, prefix):
|
||||
props = point.get("properties") or {}
|
||||
statuses = list(raw.get("realtimeStatus") or []) + list(props.get("realtimeStatus") or [])
|
||||
cancelled = raw.get("isCancelled")
|
||||
point_cancel = "DEPARTURE_CANCELLED" if prefix == "departure" else "ARRIVAL_CANCELLED"
|
||||
if point_cancel in statuses or point.get("isCancelled") is True:
|
||||
cancelled = True
|
||||
planned = point.get(prefix + "TimePlanned")
|
||||
estimated = point.get(prefix + "TimeEstimated")
|
||||
p, e = iso(planned), iso(estimated)
|
||||
monitored = raw.get("isRealtimeControlled", point.get("isRealtimeControlled"))
|
||||
realtime_confirmed = monitored is True or "MONITORED" in statuses
|
||||
# EFA may copy tomorrow's scheduled time into the estimated field. Do not
|
||||
# turn that fallback into an assertion of punctuality.
|
||||
delay = round((e - p).total_seconds() / 60) if p and e and realtime_confirmed else None
|
||||
reported = props.get("platformName")
|
||||
scheduled = props.get("plannedPlatformName")
|
||||
different = bool(reported and scheduled and normalized_platform(reported) != normalized_platform(scheduled))
|
||||
flag = (raw.get("properties") or {}).get("platformChange") == "changed"
|
||||
return {"planned": local(planned), "estimated": local(estimated) if realtime_confirmed else None,
|
||||
"estimated_unconfirmed": local(estimated) if not realtime_confirmed else None,
|
||||
"delay_minutes": delay, "realtime_confirmed": realtime_confirmed,
|
||||
"is_realtime_controlled": monitored,
|
||||
"cancelled": cancelled if isinstance(cancelled, bool) else None,
|
||||
"cancellation_scope": "this_stop_or_departure" if cancelled is True else None,
|
||||
"platform_planned": scheduled, "platform_reported": reported,
|
||||
"platform_changed": True if different or flag else (False if reported and scheduled else None),
|
||||
"realtime_status": statuses}
|
||||
|
||||
|
||||
def transport(raw):
|
||||
t = raw.get("transportation") or {}
|
||||
props = t.get("properties") or {}
|
||||
return {"name": t.get("name"), "line": t.get("number"),
|
||||
"train_type": props.get("trainType"), "train_number": props.get("trainNumber"),
|
||||
"direction": (t.get("destination") or {}).get("name"),
|
||||
"product": (t.get("product") or {}).get("name")}
|
||||
|
||||
|
||||
def board(stop, when, limit=10, train=None):
|
||||
data = request("XML_DM_REQUEST", {"commonMacro": "dm", "type_dm": "any", "name_dm": stop["id"],
|
||||
"mode": "direct", "useRealtime": 1, "limit": 200,
|
||||
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M")})
|
||||
result = []
|
||||
for event in data.get("stopEvents", []):
|
||||
info = transport(event)
|
||||
if train and re.sub(r"\s+", "", train).casefold() not in {
|
||||
re.sub(r"\s+", "", str(info.get(k) or "")).casefold()
|
||||
for k in ("train_number", "line", "name")}:
|
||||
continue
|
||||
planned = iso(event.get("departureTimePlanned"))
|
||||
if not planned or planned < when:
|
||||
continue
|
||||
point = dict(event.get("location") or {})
|
||||
point.update({k: v for k, v in event.items() if k.startswith("departureTime")})
|
||||
result.append(dict(info, station=point.get("name"),
|
||||
departure=status(event, point, "departure"),
|
||||
hints=[clean(h.get("content")) for h in event.get("hints", [])],
|
||||
messages=messages(event.get("infos"))))
|
||||
result.sort(key=lambda x: x["departure"]["planned"])
|
||||
return result[:limit]
|
||||
|
||||
|
||||
def journeys(origin, destination, when, limit, regional):
|
||||
data = request("XML_TRIP_REQUEST2", {"commonMacro": "trip", "type_origin": "any", "name_origin": origin["id"],
|
||||
"type_destination": "any", "name_destination": destination["id"],
|
||||
"itdDate": when.strftime("%Y%m%d"), "itdTime": when.strftime("%H%M"),
|
||||
"itdTripDateTimeDepArr": "dep", "useRealtime": 1})
|
||||
result = []
|
||||
for journey in data.get("journeys", []):
|
||||
raw_legs = journey.get("legs") or []
|
||||
if not raw_legs:
|
||||
continue
|
||||
legs = []
|
||||
for leg in raw_legs:
|
||||
start, end = leg.get("origin") or {}, leg.get("destination") or {}
|
||||
legs.append(dict(transport(leg), origin=start.get("name"), destination=end.get("name"),
|
||||
departure=status(leg, start, "departure"), arrival=status(leg, end, "arrival"),
|
||||
hints=[clean(h.get("content")) for h in leg.get("hints", [])],
|
||||
messages=messages(leg.get("infos"))))
|
||||
# Walking legs may have no train type. Inspect every motorised leg.
|
||||
if regional and any(((x["train_type"] or "").upper() in {"ICE", "IC", "EC", "ECE", "TGV", "RJ", "RJX", "NJ", "EN", "FLX"}
|
||||
and not re.match(r"^(RE|RB|S)\s*\d", str(x["line"] or ""), re.I))
|
||||
or (r.get("transportation") or {}).get("product", {}).get("class") == 16
|
||||
for x, r in zip(legs, raw_legs)):
|
||||
continue
|
||||
dep = iso(legs[0]["departure"]["planned"])
|
||||
arr = iso(legs[-1]["arrival"]["planned"])
|
||||
if not dep or dep < when or not arr or arr < dep:
|
||||
continue
|
||||
result.append({"departure_planned": dep.isoformat(), "arrival_planned": arr.isoformat(),
|
||||
"duration_minutes": round((arr - dep).total_seconds() / 60),
|
||||
"interchanges": journey.get("interchanges"), "legs": legs,
|
||||
"messages": messages(journey.get("infos"))})
|
||||
result.sort(key=lambda x: x["departure_planned"])
|
||||
return result[:limit]
|
||||
|
||||
|
||||
def alerts(query, when, limit):
|
||||
data = request("XML_ADDINFO_REQUEST", {"commonMacro": "addinfo", "filterPublicationStatus": "current"})
|
||||
info = data.get("infos") or {}
|
||||
if not isinstance(info, dict):
|
||||
raise EfaError("Unerwartetes EFA-Meldungsformat.")
|
||||
result = []
|
||||
for item in info.get("current", []):
|
||||
affected = item.get("affected") or {}
|
||||
# Exclude metadata and IDs from free-text matching.
|
||||
searchable = " ".join([clean(x.get("title")) + " " + clean(x.get("content")) for x in item.get("infoLinks", [])]
|
||||
+ [clean(x.get("name")) for x in affected.get("lines", []) + affected.get("stops", [])])
|
||||
if query.casefold() not in searchable.casefold():
|
||||
continue
|
||||
periods = (item.get("timestamps") or {}).get("validity") or []
|
||||
relevant = not periods or any((not iso(p.get("from")) or iso(p.get("from")) <= when)
|
||||
and (not iso(p.get("to")) or iso(p.get("to")) >= when) for p in periods)
|
||||
if not relevant:
|
||||
continue
|
||||
result.append({"id": item.get("id"), "messages": messages([item]),
|
||||
"affected_lines": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("lines", [])],
|
||||
"affected_stops": [{"name": x.get("name"), "id": x.get("id")} for x in affected.get("stops", [])]})
|
||||
return {"matches": result[:limit], "matching_count": len(result),
|
||||
"coverage": "Only messages published by this EFA endpoint. Text may specify additional dates/times."}
|
||||
|
||||
|
||||
def when_from(args):
|
||||
now = datetime.now(BERLIN)
|
||||
day = now.date() if args.date == "today" else ((now + timedelta(days=1)).date() if args.date == "tomorrow"
|
||||
else datetime.strptime(args.date, "%Y-%m-%d").date())
|
||||
clock = datetime.strptime(args.time or now.strftime("%H:%M"), "%H:%M").time()
|
||||
return datetime.combine(day, clock, BERLIN)
|
||||
|
||||
|
||||
WEEKDAYS = ("Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag", "Sonntag")
|
||||
|
||||
|
||||
def date_label(value):
|
||||
dt = iso(value)
|
||||
return f"{WEEKDAYS[dt.weekday()]}, {dt:%d.%m.%Y}" if dt else "Datum unbekannt"
|
||||
|
||||
|
||||
def time_label(value):
|
||||
dt = iso(value)
|
||||
return dt.strftime("%H:%M") if dt else "unbekannt"
|
||||
|
||||
|
||||
def status_text(value):
|
||||
parts = []
|
||||
if value.get("cancelled") is True:
|
||||
parts.append("AUSFALL an diesem Halt/Abschnitt")
|
||||
if value.get("estimated"):
|
||||
parts.append("Prognose " + time_label(value["estimated"]))
|
||||
if value.get("delay_minutes") is not None:
|
||||
parts.append(f"Verspätung {value['delay_minutes']:+d} Min.")
|
||||
if value.get("platform_changed"):
|
||||
parts.append(f"Gleisänderung: gemeldet {value.get('platform_reported') or 'unbekannt'}, "
|
||||
f"geplant {value.get('platform_planned') or 'unbekannt'}")
|
||||
else:
|
||||
platform = value.get("platform_planned") or value.get("platform_reported")
|
||||
if platform:
|
||||
label = str(platform) if re.match(r"^gleis\b", str(platform), re.I) else f"Gleis {platform}"
|
||||
parts.append(f"{label} ({'geplant' if value.get('platform_planned') else 'gemeldet'})")
|
||||
if not value.get("realtime_confirmed"):
|
||||
parts.append("keine bestätigten Echtzeitdaten")
|
||||
return "; ".join(parts)
|
||||
|
||||
|
||||
def message_lines(items):
|
||||
return ["Meldung: " + ": ".join(str(m[k]) for k in ("title", "text") if m.get(k))
|
||||
for m in items or []]
|
||||
|
||||
|
||||
def render_text(output):
|
||||
"""Deterministic facts for small models; no additional network calls."""
|
||||
if not output["ok"]:
|
||||
return "EFA-Abfrage fehlgeschlagen: " + output["error"]
|
||||
lines = ["Quelle: EFA | Abfrage: " + str(output["queried_at"])]
|
||||
if output.get("requested_from"):
|
||||
lines.append("Gesucht ab: " + date_label(output["requested_from"]) + " "
|
||||
+ time_label(output["requested_from"]) + " (Europe/Berlin)")
|
||||
if "journeys" in output:
|
||||
if not output["journeys"]:
|
||||
lines.append("Keine passende Verbindung in den gelieferten Ergebnissen gefunden.")
|
||||
for i, journey in enumerate(output["journeys"], 1):
|
||||
transfers = journey.get("interchanges")
|
||||
lines.append(f"Verbindung {i}: {time_label(journey['departure_planned'])} → "
|
||||
f"{time_label(journey['arrival_planned'])}, {journey['duration_minutes']} Min., "
|
||||
+ (f"{transfers} Umstiege" if transfers is not None else "Umstiege unbekannt"))
|
||||
for leg in journey["legs"]:
|
||||
name = leg.get("name") or leg.get("line") or leg.get("product") or "Abschnitt"
|
||||
number = leg.get("train_number")
|
||||
lines.append(f" {name}" + (f" (Zug {number})" if number else "")
|
||||
+ (f", Richtung {leg['direction']}" if leg.get("direction") else ""))
|
||||
lines.append(f" {leg['origin']} {time_label(leg['departure']['planned'])} → "
|
||||
f"{leg['destination']} {time_label(leg['arrival']['planned'])} (Fahrplan)")
|
||||
lines.append(" Abfahrt: " + status_text(leg["departure"]))
|
||||
lines.append(" Ankunft: " + status_text(leg["arrival"]))
|
||||
lines.extend(" " + line for line in message_lines(leg.get("messages")))
|
||||
lines.extend(" Hinweis: " + h for h in leg.get("hints", []) if h)
|
||||
lines.extend(message_lines(journey.get("messages")))
|
||||
if "departures" in output:
|
||||
if not output["departures"]:
|
||||
lines.append("Keine passende Abfahrt in den gelieferten Ergebnissen gefunden.")
|
||||
for event in output["departures"]:
|
||||
lines.append(f"{event.get('name') or event.get('line') or 'Zug'} "
|
||||
f"(Zug {event.get('train_number') or 'unbekannt'}), "
|
||||
f"Richtung {event.get('direction') or 'unbekannt'}: "
|
||||
f"{time_label(event['departure']['planned'])} (Fahrplan); "
|
||||
+ status_text(event["departure"]))
|
||||
lines.extend(message_lines(event.get("messages")))
|
||||
lines.extend("Hinweis: " + h for h in event.get("hints", []) if h)
|
||||
if "stops" in output:
|
||||
lines.extend(f"{x['id']}: {x['name']}" for x in output["stops"])
|
||||
if not output["stops"]:
|
||||
lines.append("Keine Bahnhofstreffer gefunden.")
|
||||
if "alerts" in output:
|
||||
found = output["alerts"]
|
||||
lines.append(f"Passende Meldungen: {found['matching_count']} (angezeigt: {len(found['matches'])})")
|
||||
for item in found["matches"]:
|
||||
lines.extend(message_lines(item["messages"]))
|
||||
for m in item["messages"]:
|
||||
if m.get("validity"):
|
||||
lines.append("Gültigkeitszeiträume: " + json.dumps(m["validity"], ensure_ascii=False))
|
||||
if m.get("url"):
|
||||
lines.append("Link: " + m["url"])
|
||||
lines.append("Meldungsabdeckung unvollständig/unbestätigt. Keine Treffer schließen Baustellen oder Störungen NICHT aus. Zeitfenster im Meldungstext prüfen.")
|
||||
if output.get("source_warnings"):
|
||||
lines.append("Quellenhinweis: Stationssuche lieferte gültige Treffer mit Teilfehler; Trefferliste möglicherweise unvollständig.")
|
||||
lines.append("Fehlende Echtzeitdaten bedeuten nicht pünktlich, verkehrend oder störungsfrei. Keine zusätzlichen Angaben zu Tickets oder Fahrradmitnahme ableiten.")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
p = sub.add_parser("stops", help="Resolve station names; choose an ID if ambiguous")
|
||||
p.add_argument("--query", required=True)
|
||||
p.add_argument("--format", choices=("json", "text"), default="json")
|
||||
for name in ("departures", "journeys", "alerts"):
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("--format", choices=("json", "text"), default="json")
|
||||
p.add_argument("--date", default="today", help="today, tomorrow, YYYY-MM-DD")
|
||||
p.add_argument("--time", help="Europe/Berlin HH:MM; default current local time")
|
||||
p.add_argument("--limit", type=int, choices=range(1, 21), default=5, metavar="1..20")
|
||||
if name == "departures":
|
||||
p.add_argument("--station", required=True)
|
||||
p.add_argument("--train", help="Optional exact train number or line, e.g. 4700 or RE2")
|
||||
elif name == "journeys":
|
||||
p.add_argument("--origin", required=True)
|
||||
p.add_argument("--destination", required=True)
|
||||
p.add_argument("--regional-only", action="store_true")
|
||||
else:
|
||||
p.add_argument("--query", required=True, help="Station, line or route fragment")
|
||||
args = parser.parse_args()
|
||||
output = {"ok": True, "source": BASE, "queried_at": datetime.now(BERLIN).isoformat(),
|
||||
"warning": "Missing realtime data does not mean punctual, operating or disruption-free."}
|
||||
try:
|
||||
if args.command == "stops":
|
||||
output["stops"] = stops(args.query)
|
||||
else:
|
||||
when = when_from(args)
|
||||
output["requested_from"] = when.isoformat()
|
||||
output["requested_date_label"] = date_label(when.isoformat())
|
||||
if args.command == "departures":
|
||||
stop = station(args.station)
|
||||
output.update(station=stop, departures=board(stop, when, args.limit, args.train))
|
||||
elif args.command == "journeys":
|
||||
origin, dest = station(args.origin), station(args.destination)
|
||||
output.update(origin=origin, destination=dest,
|
||||
journeys=journeys(origin, dest, when, args.limit, args.regional_only))
|
||||
else:
|
||||
output["alerts"] = alerts(args.query, when, args.limit)
|
||||
except (EfaError, ValueError) as exc:
|
||||
output.update(ok=False, error=str(exc))
|
||||
if REQUEST_WARNINGS:
|
||||
output["source_warnings"] = REQUEST_WARNINGS
|
||||
print(render_text(output) if args.format == "text" else json.dumps(output, ensure_ascii=False, indent=2))
|
||||
return 0 if output["ok"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,107 @@
|
||||
import unittest
|
||||
import io
|
||||
import json
|
||||
from datetime import datetime
|
||||
from unittest.mock import patch
|
||||
import efa_bahn as efa
|
||||
|
||||
|
||||
class EfaTests(unittest.TestCase):
|
||||
def test_summer_and_winter(self):
|
||||
self.assertEqual(efa.local('2026-10-08T15:00:00Z'), '2026-10-08T17:00:00+02:00')
|
||||
self.assertEqual(efa.local('2026-12-08T15:00:00Z'), '2026-12-08T16:00:00+01:00')
|
||||
|
||||
def test_schedule_fallback_not_live(self):
|
||||
point = {'departureTimePlanned': '2026-10-09T03:21:00Z',
|
||||
'departureTimeEstimated': '2026-10-09T03:21:00Z'}
|
||||
result = efa.status({}, point, 'departure')
|
||||
self.assertIsNone(result['estimated'])
|
||||
self.assertIsNone(result['delay_minutes'])
|
||||
self.assertIsNotNone(result['estimated_unconfirmed'])
|
||||
|
||||
def test_delay_and_platform_change(self):
|
||||
point = {'departureTimePlanned': '2026-10-08T15:22:00Z',
|
||||
'departureTimeEstimated': '2026-10-08T15:39:00Z',
|
||||
'properties': {'plannedPlatformName': '9', 'platformName': '10'}}
|
||||
result = efa.status({'isRealtimeControlled': True}, point, 'departure')
|
||||
self.assertEqual(result['delay_minutes'], 17)
|
||||
self.assertTrue(result['platform_changed'])
|
||||
|
||||
def test_platform_label_not_change(self):
|
||||
point = {'properties': {'platformName': 'Gleis 5', 'plannedPlatformName': '5'}}
|
||||
self.assertFalse(efa.status({}, point, 'departure')['platform_changed'])
|
||||
|
||||
def test_stop_cancellation_and_unknown(self):
|
||||
point = {'properties': {'realtimeStatus': ['DEPARTURE_CANCELLED']}}
|
||||
self.assertTrue(efa.status({}, point, 'departure')['cancelled'])
|
||||
self.assertIsNone(efa.status({}, {}, 'departure')['cancelled'])
|
||||
|
||||
def test_no_silent_ambiguous_station(self):
|
||||
with patch.object(efa, 'stops', return_value=[{'name': 'Hbf Vorplatz', 'id': '1'}, {'name': 'Hbf tief', 'id': '2'}]):
|
||||
with self.assertRaises(efa.EfaError):
|
||||
efa.station('Hbf')
|
||||
|
||||
def test_departure_cutoff_and_overnight_duration(self):
|
||||
def leg(dep, arr):
|
||||
return {'origin': {'departureTimePlanned': dep}, 'destination': {'arrivalTimePlanned': arr},
|
||||
'transportation': {'name': 'RE 2'}}
|
||||
data = {'journeys': [
|
||||
{'legs': [leg('2026-10-08T21:00:00Z', '2026-10-08T21:30:00Z')]},
|
||||
{'legs': [leg('2026-10-08T21:55:00Z', '2026-10-08T22:15:00Z')]},
|
||||
]}
|
||||
with patch.object(efa, 'request', return_value=data):
|
||||
result = efa.journeys({'id': '1'}, {'id': '2'}, datetime(2026, 10, 8, 23, 30, tzinfo=efa.BERLIN), 5, False)
|
||||
self.assertEqual(len(result), 1)
|
||||
self.assertEqual(result[0]['duration_minutes'], 20)
|
||||
|
||||
def test_alert_validity(self):
|
||||
future = {'infoLinks': [{'title': 'Bauarbeiten Hannover'}],
|
||||
'timestamps': {'validity': [{'from': '2026-10-10T03:00:00Z'}]}}
|
||||
current = {'infoLinks': [{'title': 'Bauarbeiten Hannover'}],
|
||||
'timestamps': {'validity': [{'from': '2026-10-01T03:00:00Z', 'to': '2026-10-12T03:00:00Z'}]}}
|
||||
with patch.object(efa, 'request', return_value={'infos': {'current': [future, current]}}):
|
||||
result = efa.alerts('Hannover', datetime(2026, 10, 8, 18, 0, tzinfo=efa.BERLIN), 5)
|
||||
self.assertEqual(result['matching_count'], 1)
|
||||
|
||||
def test_partial_broker_error_with_stations(self):
|
||||
data = {'systemMessages': [{'type': 'error', 'module': 'BROKER', 'code': -8011}],
|
||||
'locations': [{'id': 'de:08222:2417', 'name': 'Mannheim, Hauptbahnhof'}]}
|
||||
with patch.object(efa, 'urlopen', return_value=io.BytesIO(json.dumps(data).encode())):
|
||||
self.assertEqual(efa.request('XML_STOPFINDER_REQUEST', {})['locations'][0]['id'], 'de:08222:2417')
|
||||
data['locations'] = []
|
||||
with patch.object(efa, 'urlopen', return_value=io.BytesIO(json.dumps(data).encode())):
|
||||
with self.assertRaises(efa.EfaError):
|
||||
efa.request('XML_STOPFINDER_REQUEST', {})
|
||||
efa.REQUEST_WARNINGS.clear()
|
||||
|
||||
def test_city_main_station_without_forecourt(self):
|
||||
options = [{'name': 'Mannheim, Hauptbahnhof', 'id': '1'}, {'name': 'Mannheim, Lindenhof, MA Hauptbahnhof Süd', 'id': '2'}]
|
||||
with patch.object(efa, 'stops', return_value=options) as mock:
|
||||
self.assertEqual(efa.station('Mannheim')['id'], '1')
|
||||
mock.assert_called_once_with('Mannheim Hauptbahnhof')
|
||||
|
||||
def test_correct_weekday(self):
|
||||
self.assertEqual(efa.date_label('2026-10-09T05:21:00+02:00'), 'Freitag, 09.10.2026')
|
||||
|
||||
def test_empty_alerts_not_all_clear(self):
|
||||
text = efa.render_text({'ok': True, 'queried_at': 'now',
|
||||
'alerts': {'matching_count': 0, 'matches': []}})
|
||||
self.assertIn('NICHT aus', text)
|
||||
self.assertIn('unvollständig', text)
|
||||
|
||||
def test_text_keeps_unknown_realtime_and_platform_change(self):
|
||||
unknown = efa.status({}, {'departureTimePlanned': '2026-10-09T03:21:00Z',
|
||||
'departureTimeEstimated': '2026-10-09T03:21:00Z'}, 'departure')
|
||||
self.assertNotIn('Prognose', efa.status_text(unknown))
|
||||
self.assertIn('keine bestätigten Echtzeitdaten', efa.status_text(unknown))
|
||||
changed = efa.status({'isRealtimeControlled': True},
|
||||
{'properties': {'platformName': '10', 'plannedPlatformName': '9'}}, 'departure')
|
||||
self.assertIn('gemeldet 10, geplant 9', efa.status_text(changed))
|
||||
|
||||
def test_text_reports_error(self):
|
||||
self.assertEqual(efa.render_text({'ok': False, 'error': 'test'}),
|
||||
'EFA-Abfrage fehlgeschlagen: test')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user