Files
bus-department-schedule/timetable.py
T
2026-10-07 00:23:54 +02:00

110 lines
3.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Parse a DSZO per-stop timetable page into departures."""
import re
from dataclasses import dataclass
from datetime import date, time
KIND_WORKDAY = "workday"
KIND_REST_DAY = "rest_day"
KIND_SPECIAL = "special"
class ParseError(Exception):
"""The page did not look like a DSZO stop timetable."""
@dataclass(frozen=True)
class Departure:
line: str
stop: str
time: time
mark: str | None = None # footnote letter such as "v"; stored, not displayed
@dataclass(frozen=True)
class Column:
label: str
kind: str
valid_from: date
dates: tuple[date, ...] # explicit dates, only for KIND_SPECIAL
departures: tuple[Departure, ...]
@dataclass(frozen=True)
class Timetable:
line: str
stop: str
columns: tuple[Column, ...]
_DATE_RE = re.compile(r"(\d{1,2})\.(?:\s*[–-]\s*(\d{1,2})\.)?(\d{1,2})\.(\d{4})")
_TAG_RE = re.compile(r"<[^>]+>")
_ROW_RE = re.compile(r'<td class="hour-cell">(\d\d)</td>(.*?)</tr>', re.S)
_CELL_RE = re.compile(r'<td class="minutes-cell">(.*?)</td>', re.S)
_MINUTE_RE = re.compile(r'(\d\d)(?:<span class="idx">(.*?)</span>)?')
def _text(html: str) -> str:
return re.sub(r"\s+", " ", _TAG_RE.sub(" ", html)).strip()
def _dates_in(text: str) -> list[date]:
"""All dates in text; 'd1.–d2.m.yyyy' expands to every day of the range."""
found: list[date] = []
for d1, d2, month, year in _DATE_RE.findall(text):
first, last = int(d1), int(d2 or d1)
found += [date(int(year), int(month), d) for d in range(first, last + 1)]
return found
def _column_header(label_html: str) -> tuple[str, str, date, tuple[date, ...]]:
label = _text(label_html.replace("<br/>", " / "))
try:
dates = _dates_in(label)
except ValueError as exc: # e.g. 31.2.
raise ParseError(f"invalid date in column header: {label!r}") from exc
if not dates:
raise ParseError(f"no validity date in column header: {label!r}")
lowered = label.lower()
if "prázdniny" in lowered:
return label, KIND_SPECIAL, min(dates), tuple(dates)
if lowered.startswith("dny pracovního klidu"):
return label, KIND_REST_DAY, dates[0], ()
if lowered.startswith("pracovní dny"):
return label, KIND_WORKDAY, dates[0], ()
raise ParseError(f"unknown column header: {label!r}")
def parse_page(html: str, line: str, stop: str) -> Timetable:
headers = re.findall(r"<th>(.*?)</th>", html, re.S)
if not headers or "Hod" not in headers[0]:
raise ParseError("timetable header not found")
specs = [_column_header(h) for h in headers[1:]]
if not specs:
raise ParseError("timetable has no columns")
rows = _ROW_RE.findall(html)
if not rows:
raise ParseError("no timetable rows found")
per_column: list[list[Departure]] = [[] for _ in specs]
for hour, row_html in rows:
cells = _CELL_RE.findall(row_html)
if len(cells) != len(specs):
raise ParseError(f"hour {hour}: {len(cells)} cells for {len(specs)} columns")
for column, cell in zip(per_column, cells):
for minute, mark in _MINUTE_RE.findall(cell):
try:
departure_time = time(int(hour), int(minute))
except ValueError:
raise ParseError(f"hour {hour}: invalid time {hour}:{minute}")
column.append(Departure(line, stop, departure_time, mark or None))
if not any(per_column):
raise ParseError("timetable contains no departures")
columns = tuple(
Column(label, kind, valid_from, dates, tuple(deps))
for (label, kind, valid_from, dates), deps in zip(specs, per_column)
)
return Timetable(line, stop, columns)