feat: parse DSZO stop timetable pages

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
rickzkmandClaude Sonnet 5.5 committed 2026-10-07 00:22:08 +02:00
1 parent c78c0f9460
commit 8099b4834b
3 files changed
+216

No files matched your search

+6
View File
@@ -1,6 +1,8 @@
"""Shared test data: the four frozen DSZO pages and where they came from.""" """Shared test data: the four frozen DSZO pages and where they came from."""
from pathlib import Path from pathlib import Path
from timetable import Timetable, parse_page
ROOT = Path(__file__).resolve().parent.parent ROOT = Path(__file__).resolve().parent.parent
FIXTURES = Path(__file__).parent / "fixtures" FIXTURES = Path(__file__).parent / "fixtures"
FONT_DIR = str(ROOT / "assets" / "fonts") FONT_DIR = str(ROOT / "assets" / "fonts")
@@ -16,3 +18,7 @@ SOURCES = [
def fixture_html(name: str) -> str: def fixture_html(name: str) -> str:
return (FIXTURES / name).read_text(encoding="utf-8") return (FIXTURES / name).read_text(encoding="utf-8")
def load_timetables() -> list[Timetable]:
return [parse_page(fixture_html(name), line, stop) for name, line, stop in SOURCES]
+105
View File
@@ -0,0 +1,105 @@
from datetime import date, time
import pytest
from tests.helpers import fixture_html
from timetable import (
KIND_REST_DAY,
KIND_SPECIAL,
KIND_WORKDAY,
ParseError,
parse_page,
)
def load(name, line, stop):
return parse_page(fixture_html(name), line, stop)
@pytest.fixture(scope="module")
def line4():
return load("line4_u_potoka.html", "4", "Štípa,u potoka")
def summary(timetable):
return [(c.kind, c.valid_from, len(c.departures)) for c in timetable.columns]
def test_line4_columns(line4):
assert summary(line4) == [
(KIND_WORKDAY, date(2026, 10, 1), 36),
(KIND_REST_DAY, date(2026, 10, 3), 29),
]
def test_line4_first_workday_departures(line4):
deps = line4.columns[0].departures
assert [d.time for d in deps[:3]] == [time(4, 16), time(4, 46), time(5, 32)]
assert all(d.line == "4" and d.stop == "Štípa,u potoka" for d in deps)
def test_line4_footnote_mark_is_kept_not_dropped(line4):
last = line4.columns[0].departures[-1]
assert (last.time, last.mark) == (time(23, 6), "v")
def test_line5_counts_and_mark():
t = load("line5_u_potoka.html", "5", "Štípa,u potoka")
assert summary(t) == [
(KIND_WORKDAY, date(2026, 10, 1), 16),
(KIND_REST_DAY, date(2026, 10, 3), 14),
]
marked = {(d.time, d.mark) for d in t.columns[0].departures if d.mark}
assert (time(7, 16), "A") in marked
def test_line35_has_special_school_holiday_column():
t = load("line35_druzstvo.html", "35", "Štípa,družstvo")
assert summary(t) == [
(KIND_WORKDAY, date(2026, 10, 1), 4),
(KIND_REST_DAY, date(2026, 10, 3), 0),
(KIND_SPECIAL, date(2026, 10, 29), 3),
]
assert t.columns[2].dates == (date(2026, 10, 29), date(2026, 10, 30), date(2026, 12, 23))
assert t.columns[0].dates == ()
def test_line36_counts():
t = load("line36_druzstvo.html", "36", "Štípa,družstvo")
assert [len(c.departures) for c in t.columns] == [4, 1, 3]
HEADER = '<table class="stop-timetable"><thead><tr><th>Hod.</th>{ths}</tr></thead><tbody>{rows}</tbody></table>'
WORKDAY_TH = "<th>Pracovní dny<br/>platnost od 1.10.2026</th>"
def test_zero_departures_is_a_parse_error():
html = HEADER.format(
ths=WORKDAY_TH, rows='<tr><td class="hour-cell">00</td><td class="minutes-cell"></td></tr>'
)
with pytest.raises(ParseError, match="no departures"):
parse_page(html, "4", "X")
@pytest.mark.parametrize("html", ["", "<html>redesigned page</html>", "<table></table>"])
def test_unrecognised_page_is_a_parse_error(html):
with pytest.raises(ParseError):
parse_page(html, "4", "X")
def test_unknown_column_header_is_a_parse_error():
html = HEADER.format(
ths="<th>Něco nového<br/>platnost od 1.10.2026</th>",
rows='<tr><td class="hour-cell">04</td><td class="minutes-cell">16 </td></tr>',
)
with pytest.raises(ParseError, match="unknown column"):
parse_page(html, "4", "X")
def test_cell_count_mismatch_is_a_parse_error():
html = HEADER.format(
ths=WORKDAY_TH,
rows='<tr><td class="hour-cell">04</td><td class="minutes-cell">16 </td><td class="minutes-cell">30 </td></tr>',
)
with pytest.raises(ParseError, match="cells"):
parse_page(html, "4", "X")
+105
View File
@@ -0,0 +1,105 @@
"""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):
column.append(Departure(line, stop, time(int(hour), int(minute)), 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)