Files

152 lines
5.2 KiB
Python
Raw Permalink 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, timedelta
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, ...]
_N = "([0-9]{1,2})"
_Y = "([0-9]{4})"
_DASH = r"\s*[–-]\s*"
# one validity item: a single date, or a range whose start may omit month and/or year
_SINGLE_RE = re.compile(rf"(?<![0-9]){_N}\.{_N}\.{_Y}")
_RANGE_RE = re.compile(rf"(?<![0-9]){_N}\.(?:{_N}\.(?:{_Y})?)?{_DASH}{_N}\.{_N}\.{_Y}")
MAX_RANGE_DAYS = 366
_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 _make_date(year: int, month: int, day: int) -> date:
try:
return date(year, month, day)
except ValueError as exc: # e.g. 31.2.
raise ParseError(f"impossible date {day}.{month}.{year}") from exc
def _item_dates(item: str) -> list[date]:
single = _SINGLE_RE.fullmatch(item)
if single:
d, m, y = map(int, single.groups())
return [_make_date(y, m, d)]
rng = _RANGE_RE.fullmatch(item)
if not rng:
raise ParseError(f"unrecognised validity date {item!r}")
d1, m1, y1, d2, m2, y2 = rng.groups()
d1, d2, m2, y2 = int(d1), int(d2), int(m2), int(y2)
month1 = int(m1) if m1 else m2
if y1:
year1 = int(y1)
else: # infer from the end date: a start month after the end month means the year before
year1 = y2 - 1 if month1 > m2 else y2
first, last = _make_date(year1, month1, d1), _make_date(y2, m2, d2)
if last < first:
raise ParseError(f"reversed date range {item!r}")
if (last - first).days >= MAX_RANGE_DAYS:
raise ParseError(f"date range too long {item!r}")
return [first + timedelta(days=i) for i in range((last - first).days + 1)]
def _dates_in(validity: str) -> list[date]:
"""Dates of the text after 'platnost'. Anything not recognised raises ParseError."""
text = validity.strip()
from_only = text.lower().startswith("od ")
if from_only:
text = text[3:].strip()
found: list[date] = []
for item in text.split(","):
found += _item_dates(item.strip())
if from_only and len(found) != 1:
raise ParseError(f"'od' needs a single date: {validity!r}")
return found
def _column_header(label_html: str) -> tuple[str, str, date, tuple[date, ...]]:
label = _text(label_html.replace("<br/>", " / "))
lowered = label.lower()
marker = lowered.find("platnost")
if marker < 0 or not re.search("[0-9]", label[marker:]):
raise ParseError(f"no validity date in column header: {label!r}")
try:
dates = _dates_in(label[marker + len("platnost"):])
except ParseError as exc:
raise ParseError(f"bad validity in column header {label!r}: {exc}") from exc
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)