154 lines
4.9 KiB
Python
154 lines
4.9 KiB
Python
"""Download GOST sign diagrams from the drom.ru PDD page into assets/signs.
|
|
|
|
The page text is not copied. Only the SVG drawings are saved, and only for
|
|
sign numbers that exist in the app catalog.
|
|
|
|
python tools/fetch_drom_sign_svgs.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import urllib.request
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from html.parser import HTMLParser
|
|
from pathlib import Path
|
|
|
|
PAGE_URL = "https://www.drom.ru/pdd/pdd/signs/"
|
|
CATALOG = Path("lib/data/catalog/sign_definitions.dart")
|
|
ASSET_DIR = Path("assets/signs")
|
|
INDEX = Path("lib/data/catalog/sign_image_assets.dart")
|
|
CODE = re.compile(r"\d+\.\d+(?:\.\d+)*")
|
|
CATALOG_CODE = re.compile(r"_s\(\s*'([^']+)'")
|
|
|
|
|
|
class _SignPage(HTMLParser):
|
|
def __init__(self) -> None:
|
|
super().__init__(convert_charrefs=True)
|
|
self.depth = 0
|
|
self.capture_title = False
|
|
self.title: list[str] = []
|
|
self.images: list[str] = []
|
|
self.found: list[tuple[list[str], str]] = []
|
|
|
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
attributes = {key: value or "" for key, value in attrs}
|
|
classes = set(attributes.get("class", "").split())
|
|
if tag == "div":
|
|
if self.depth == 0 and "pub" in classes:
|
|
self.depth = 1
|
|
self.images = []
|
|
self.title = []
|
|
self.capture_title = False
|
|
elif self.depth:
|
|
self.depth += 1
|
|
if self.depth and tag == "img":
|
|
src = attributes.get("src", "")
|
|
if src.endswith(".svg"):
|
|
self.images.append(src)
|
|
if self.depth and tag == "h4":
|
|
self.capture_title = True
|
|
self.title = []
|
|
|
|
def handle_endtag(self, tag: str) -> None:
|
|
if tag == "h4":
|
|
self.capture_title = False
|
|
if tag == "div" and self.depth:
|
|
self.depth -= 1
|
|
if self.depth == 0 and self.images:
|
|
self.found.append((self.images, "".join(self.title)))
|
|
|
|
def handle_data(self, data: str) -> None:
|
|
if self.capture_title:
|
|
self.title.append(data)
|
|
|
|
|
|
def catalog_codes() -> list[str]:
|
|
text = CATALOG.read_text(encoding="utf-8")
|
|
return CATALOG_CODE.findall(text)
|
|
|
|
|
|
def sign_urls(html: str) -> dict[str, str]:
|
|
parser = _SignPage()
|
|
parser.feed(html)
|
|
chosen: dict[str, str] = {}
|
|
for images, title in parser.found:
|
|
codes = CODE.findall(title)
|
|
if not images or not codes:
|
|
continue
|
|
if len(images) == len(codes):
|
|
pairs = zip(codes, images)
|
|
else:
|
|
pairs = ((code, images[0]) for code in codes)
|
|
for code, src in pairs:
|
|
chosen.setdefault(code, src)
|
|
return chosen
|
|
|
|
|
|
def download(url: str, destination: Path) -> None:
|
|
request = urllib.request.Request(url, headers={"User-Agent": "sign-checker"})
|
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
payload = response.read()
|
|
if not payload.lstrip().startswith(b"<svg") and b"<svg" not in payload[:200]:
|
|
raise RuntimeError(f"{url} is not an SVG")
|
|
destination.write_bytes(payload)
|
|
|
|
|
|
def write_index(codes: list[str]) -> None:
|
|
lines = [
|
|
"// Generated by tools/fetch_drom_sign_svgs.py.",
|
|
"const Set<String> signImageAssets = {",
|
|
]
|
|
lines.extend(f" '{code}'," for code in codes)
|
|
lines.append("};")
|
|
lines.append("")
|
|
INDEX.write_text("\n".join(lines), encoding="utf-8")
|
|
|
|
|
|
def main() -> None:
|
|
request = urllib.request.Request(PAGE_URL, headers={"User-Agent": "sign-checker"})
|
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
html = response.read().decode("cp1251")
|
|
urls = sign_urls(html)
|
|
wanted = [code for code in catalog_codes() if not code.startswith("signal.")]
|
|
for code in list(wanted):
|
|
if code in urls:
|
|
continue
|
|
parent = max(
|
|
(name for name in urls if code.startswith(name + ".")),
|
|
key=len,
|
|
default="",
|
|
)
|
|
if parent:
|
|
urls[code] = urls[parent]
|
|
ASSET_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
saved: list[str] = []
|
|
missing: list[str] = []
|
|
jobs: list[tuple[str, str, Path]] = []
|
|
for code in wanted:
|
|
url = urls.get(code)
|
|
if url is None:
|
|
missing.append(code)
|
|
continue
|
|
jobs.append((code, url, ASSET_DIR / f"{code}.svg"))
|
|
|
|
def fetch(job: tuple[str, str, Path]) -> str:
|
|
code, url, destination = job
|
|
if destination.is_file() and destination.stat().st_size > 100:
|
|
return code
|
|
download(url, destination)
|
|
return code
|
|
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
saved = list(pool.map(fetch, jobs))
|
|
|
|
write_index(saved)
|
|
print(f"saved={len(saved)} missing={len(missing)}")
|
|
if missing:
|
|
print("missing: " + ", ".join(missing))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|