Исходный код iduedu.config

import os
import sys
import threading
from contextlib import contextmanager
from datetime import date as _date
from datetime import datetime as _datetime
from typing import TYPE_CHECKING, Iterable, Iterator, Literal, Optional

from loguru import logger

from ._version import VERSION

if TYPE_CHECKING:
    import geopandas as gpd
    from shapely import MultiPolygon, Polygon

LogLevel = Literal["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
OsmSource = Literal["overpass", "pbf"]
OSM_SOURCES = ("overpass", "pbf")


_LOGURU_DEFAULT_FORMAT = (
    "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | "
    "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
)


def _is_iduedu(record) -> bool:
    name = record["name"] or ""
    return name == "iduedu" or name.startswith("iduedu.")


def _interactive_session() -> bool:
    """Whether progress bars have a reader: a terminal on standard error or a Jupyter kernel."""
    try:
        if sys.stderr is not None and sys.stderr.isatty():
            return True
    except (AttributeError, ValueError):
        pass
    return "ipykernel" in sys.modules


def _loguru_has_only_default_sink() -> bool:
    """Whether loguru still has just the sink it starts with, so no application has configured it."""
    try:
        return list(logger._core.handlers) == [0]  # pylint: disable=protected-access
    except AttributeError:  # another loguru layout: leave the sinks as they are
        return False


[документация] class Config: """Global runtime settings for the OSM data source, Overpass, caching, logging and graph builders.""" def __init__(self): """Initialize runtime settings from environment variables.""" # --- Overpass endpoints --- self.overpass_url: str = os.getenv("OVERPASS_URL", "https://overpass-api.de/api/interpreter") self.user_agent: str = os.getenv( "OVERPASS_USER_AGENT", f"iduedu/{VERSION} (+https://github.com/IDUclub/IduEdu)" ) self.proxies: Optional[dict[str, str]] = None self.verify_ssl: bool = True # --- Networking / retries --- self.timeout: int = int(os.getenv("OVERPASS_TIMEOUT", "120")) self.overpass_min_interval: float = float(os.getenv("OVERPASS_MIN_INTERVAL", "2")) self.overpass_max_retries: int = int(os.getenv("OVERPASS_MAX_RETRIES", "5")) self.overpass_retry_statuses: tuple[int, ...] = (429, 502, 503, 504) self.overpass_backoff_base: float = float(os.getenv("OVERPASS_BACKOFF_BASE", "2")) # --- Overpass date / header control --- self.overpass_date: str | None = None env_date = os.getenv("OVERPASS_DATE") if env_date: try: self.set_overpass_date(date=env_date) except ValueError as exc: logger.warning(f"Invalid OVERPASS_DATE env value {env_date!r}: {exc}") # --- OSM data source --- self.osm_source: OsmSource = "overpass" self.pbf_path: str | None = os.getenv("IDUEDU_PBF_PATH") or None env_source = os.getenv("IDUEDU_OSM_SOURCE") if env_source: source = env_source.strip().lower() if source in OSM_SOURCES: self.osm_source = source else: logger.warning(f"Invalid IDUEDU_OSM_SOURCE env value {env_source!r}; expected one of {OSM_SOURCES}") # --- Caching --- self.overpass_cache_dir: str = os.getenv("OVERPASS_CACHE_DIR", ".iduedu_cache") self.overpass_cache_enabled: bool = os.getenv("OVERPASS_CACHE_ENABLED", "1").lower() not in {"0", "false"} # --- UX --- env_tqdm = os.getenv("ENABLE_TQDM") self.enable_tqdm_bar: bool = ( env_tqdm.strip().lower() not in {"0", "false"} if env_tqdm is not None else _interactive_session() ) # --- Tags to keep on edges --- # bridge and tunnel are always kept on drive, walk and bike edges (see STRUCTURE_TAGS). self.drive_useful_edges_attr = frozenset({"highway", "name", "lanes"}) self.walk_useful_edges_attr = frozenset({"highway", "name"}) self.bike_useful_edges_attr = frozenset({"highway", "name", "lanes", "maxspeed", "surface"}) self.transport_useful_edges_attr = frozenset({"name"}) # Tags of a route relation that become columns of the routes table of a public-transport graph. self.transport_route_attr = frozenset( {"ref", "name", "from", "to", "network", "operator", "colour", "interval", "service"} ) # --- Logging --- self.logger = logger self._log_handlers: list[int] = [] self._replaced_default_sink = False # The sinks of an application that set up loguru before importing IduEdu are left alone; only the bare # default sink of a fresh interpreter is replaced, so that IduEdu stays at LOG_LEVEL in notebooks. if _loguru_has_only_default_sink(): self.configure_logging(level=os.getenv("LOG_LEVEL", "WARNING").upper()) # --- Internals --- self._lock = threading.RLock() # ------------- Logging -------------
[документация] def configure_logging(self, level: LogLevel = "INFO", *, to_file: str | None = None, json: bool = False): """ Write IduEdu messages of ``level`` and above to standard error and, with ``to_file``, to a file. Only the sinks added by an earlier call and the default sink of loguru are replaced; sinks added by the application stay. When the default sink is replaced, messages of other packages keep its level and format. """ for handler_id in self._log_handlers: try: self.logger.remove(handler_id) except ValueError: # already removed by the application pass self._log_handlers = [] try: self.logger.remove(0) self._replaced_default_sink = True except ValueError: pass replaced_default = self._replaced_default_sink threshold = self.logger.level(level).no fmt = "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:<8} | {message}" if not json else "{message}" add = self._log_handlers.append add(self.logger.add(sys.stderr, level=threshold, filter=_is_iduedu, backtrace=True, diagnose=False, format=fmt)) if replaced_default: add( self.logger.add( sys.stderr, level=os.getenv("LOGURU_LEVEL", "DEBUG"), filter=lambda record: not _is_iduedu(record), format=os.getenv("LOGURU_FORMAT", _LOGURU_DEFAULT_FORMAT), ) ) if to_file: add( self.logger.add( to_file, level=threshold, filter=_is_iduedu, rotation="20 MB", retention="14 days", compression="zip", enqueue=True, backtrace=True, diagnose=False, format=fmt, ) )
# ------------- Overpass control -------------
[документация] def set_overpass_url(self, url: str): """ Set active Overpass URL (validated), keeps the pool intact. """ if not (url.startswith("http://") or url.startswith("https://")): raise ValueError(f"Invalid Overpass URL: {url!r}") with self._lock: self.overpass_url = url
[документация] def set_overpass_cache(self, *, enabled: bool | None = None, cache_dir: str | None = None): """ Managing the file cache of Overpass requests. enabled=True -> read/write cache enabled=False -> ignore cache completely """ if enabled is not None: self.overpass_cache_enabled = bool(enabled) if cache_dir is not None: self.overpass_cache_dir = cache_dir
[документация] def set_timeout(self, timeout: int): """Set the default Overpass request timeout in seconds. Args: timeout: Positive timeout value in seconds. Raises: ValueError: If ``timeout`` is not positive. """ if timeout <= 0: raise ValueError("timeout must be > 0") self.timeout = int(timeout)
[документация] def set_overpass_date( self, date: str | None = None, *, year: int | None = None, month: int | None = None, day: int | None = None, ): """Set the snapshot date for Overpass queries. The date is stored in ISO 8601 UTC format: ``YYYY-MM-DDTHH:MM:SSZ`` and used in the Overpass header as ``[date:"..."]``. Calling this method allows you to fix the OSM data to a specific historical snapshot or reset back to the "current" data. Usage examples: * ``set_overpass_date()`` or ``set_overpass_date(None)`` - reset the date (no ``[date:...]`` in queries). * ``set_overpass_date(date="2020-01-01")`` -> ``2020-01-01T00:00:00Z``. * ``set_overpass_date(date="2020-01-01T12:34:56Z")`` -> stores the normalized value of this timestamp. * ``set_overpass_date(year=2020)`` -> ``2020-01-01T00:00:00Z``. * ``set_overpass_date(year=2020, month=5)`` -> ``2020-05-01T00:00:00Z``. * ``set_overpass_date(year=2020, month=5, day=10)`` -> ``2020-05-10T00:00:00Z``. Args: date: A date string in ``YYYY-MM-DD`` or ``YYYY-MM-DDTHH:MM:SSZ`` format. If provided, ``year``, ``month`` and ``day`` must all be ``None``. year: Year component of the date. If provided without ``date``, at least the year must be set; ``month`` and ``day`` are optional and default to January 1 if omitted. month: Month component of the date (1-12). Optional when used with ``year``. Defaults to 1 (January) if not provided. day: Day component of the date (1-31). Optional when used with ``year`` and ``month``. Defaults to 1 if not provided. Raises: ValueError: If both ``date`` and any of ``year``, ``month``, ``day`` are provided, if the date string is not in a supported format, or if the constructed date is invalid. """ if date is None and year is None and month is None and day is None: self.overpass_date = None return if date is not None and any(v is not None for v in (year, month, day)): raise ValueError("Use either `date` or (`year`, `month`, `day`), not both") if date is not None: if len(date) == 10: try: _date.fromisoformat(date) except ValueError as exc: raise ValueError("overpass date must be in YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ format") from exc self.overpass_date = f"{date}T00:00:00Z" return else: try: dt = _datetime.fromisoformat(date.replace("Z", "+00:00")) except ValueError as exc: raise ValueError("overpass date must be in YYYY-MM-DD or YYYY-MM-DDTHH:MM:SSZ format") from exc self.overpass_date = dt.strftime("%Y-%m-%dT%H:%M:%SZ") return if year is None: raise ValueError("year must be provided if `date` is not used") if month is None: month = 1 if day is None: day = 1 try: d = _date(year, month, day) except ValueError as exc: raise ValueError(f"Invalid date: {exc}") from exc self.overpass_date = f"{d.isoformat()}T00:00:00Z"
# ------------- OSM data source -------------
[документация] def set_osm_source(self, source: OsmSource, *, path: str | os.PathLike | None = None): """Choose where OpenStreetMap data comes from. ``"overpass"`` (the default) sends queries to the Overpass API. ``"pbf"`` answers the same queries from a local ``.osm.pbf`` file, read by IduEdu's Rust core; the Overpass cache and ``overpass_date`` are not used then. Args: source: ``"overpass"`` or ``"pbf"``. path: The OSM file for ``"pbf"``. May be omitted when ``pbf_path`` is already set. Ignored by ``"overpass"`` apart from being stored. Raises: ValueError: For an unknown source, or ``"pbf"`` without a file. FileNotFoundError: If the file does not exist. """ normalized = str(source).strip().lower() if normalized not in OSM_SOURCES: raise ValueError(f"Unknown osm_source {source!r}; expected one of {OSM_SOURCES}") new_path = os.fspath(path) if path is not None else self.pbf_path if normalized == "pbf": if new_path is None: raise ValueError("osm_source='pbf' requires a path to an OSM file") if not os.path.isfile(new_path): raise FileNotFoundError(f"OSM file not found: {new_path}") with self._lock: self.osm_source = normalized self.pbf_path = new_path
[документация] @contextmanager def use_pbf( self, path: str | os.PathLike | None = None, *, osm_id: int | None = None, territory: "Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries | None" = None, region: str | None = None, **download_kwargs, ) -> Iterator["Config"]: """Temporarily read OSM data from a local file; the previous source is restored on exit. The file is either given as ``path`` or downloaded for a territory: ``osm_id``, ``territory``, ``region`` and any other keyword argument go unchanged to :func:`~iduedu.osm_pbf.download_osm_pbf`, which picks the Geofabrik extract, caches it and cuts the territory out. A file that is already cached is reused without any download. Also available as ``iduedu.use_pbf``. Args: path: The ``.osm.pbf`` file. osm_id: OSM relation id of the territory to download, instead of ``path``. territory: Territory polygon in EPSG:4326, or a GeoDataFrame/GeoSeries, instead of ``path``. region: Geofabrik region id to cut the territory from; chosen automatically when omitted. **download_kwargs: Further arguments of :func:`~iduedu.osm_pbf.download_osm_pbf` (``update``, ``out_dir``, ``name``, ...). Raises: ValueError: If both ``path`` and download arguments are given, or neither. Example: >>> with config.use_pbf("berlin.osm.pbf"): ... walk = get_walk_graph(territory=polygon) >>> with iduedu.use_pbf(osm_id=1114252, region="northwestern-fed-district"): ... graph = get_intermodal_graph(osm_id=1114252) """ download = {"osm_id": osm_id, "territory": territory, "region": region} download = {key: value for key, value in download.items() if value is not None} | download_kwargs if path is not None and download: raise ValueError("use_pbf takes either a path or the download arguments of download_osm_pbf, not both") if path is None: if osm_id is None and territory is None: raise ValueError("use_pbf needs a path, or osm_id or territory to download the territory") from iduedu.osm_pbf.download import download_osm_pbf # pylint: disable=import-outside-toplevel path = download_osm_pbf(**download) previous = (self.osm_source, self.pbf_path) self.set_osm_source("pbf", path=path) try: yield self finally: with self._lock: self.osm_source, self.pbf_path = previous
[документация] def build_overpass_header(self, *, timeout: int | None = None, date: str | None = None) -> str: """Build the Overpass query header for JSON requests. Args: timeout: Optional timeout override in seconds. If omitted, the configured default timeout is used. date: Optional Overpass snapshot date override in ISO UTC format. If omitted, ``self.overpass_date`` is used. Returns: Header string such as ``[out:json][timeout:120];`` or ``[out:json][timeout:120][date:"2020-01-01T00:00:00Z"];``. Raises: ValueError: If the effective timeout is not positive. """ t = int(timeout) if timeout is not None else int(self.timeout) if t <= 0: raise ValueError("timeout must be > 0") effective_date = date if date is not None else self.overpass_date parts = [f"[out:json][timeout:{t}]"] if effective_date: parts.append(f'[date:"{effective_date}"]') return "".join(parts) + ";"
@property def overpass_header(self) -> str: """Current default Overpass query header.""" return self.build_overpass_header()
[документация] def set_enable_tqdm(self, enable: bool): """Enable or disable progress bars for long-running operations.""" self.enable_tqdm_bar = bool(enable)
[документация] def set_drive_useful_edges_attr(self, attr: Iterable[str]): """Set OSM edge tags retained by drive graph builders.""" self.drive_useful_edges_attr = frozenset(attr)
[документация] def set_walk_useful_edges_attr(self, attr: Iterable[str]): """Set OSM edge tags retained by walk graph builders.""" self.walk_useful_edges_attr = frozenset(attr)
[документация] def set_bike_useful_edges_attr(self, attr: Iterable[str]): """Set OSM edge tags retained by bike graph builders.""" self.bike_useful_edges_attr = frozenset(attr)
[документация] def set_transport_useful_edges_attr(self, attr: Iterable[str]): """Set OSM edge tags retained by public-transport graph builders.""" self.transport_useful_edges_attr = frozenset(attr)
[документация] def set_transport_route_attr(self, attr: Iterable[str]): """Set the tags of OSM route relations kept in the ``routes`` table of public-transport graphs.""" self.transport_route_attr = frozenset(attr)
[документация] def set_rate_limit( self, *, min_interval: float | None = None, max_retries: int | None = None, backoff_base: float | None = None ): """Configure Overpass request pacing and retry behavior. Args: min_interval: Minimum delay between Overpass requests in seconds. max_retries: Maximum number of retry attempts for retryable HTTP statuses. backoff_base: Base multiplier for exponential retry backoff. Raises: ValueError: If any provided value is outside its accepted range. """ if min_interval is not None: if min_interval < 0: raise ValueError("min_interval must be >= 0") self.overpass_min_interval = float(min_interval) if max_retries is not None: if max_retries < 0: raise ValueError("max_retries must be >= 0") self.overpass_max_retries = int(max_retries) if backoff_base is not None: if backoff_base <= 0: raise ValueError("backoff_base must be > 0") self.overpass_backoff_base = float(backoff_base)
[документация] def to_dict(self) -> dict: """Return a serializable snapshot of the current configuration.""" return { "overpass_url": self.overpass_url, "timeout": self.timeout, "overpass_date": self.overpass_date, "enable_tqdm_bar": self.enable_tqdm_bar, "drive_useful_edges_attr": sorted(self.drive_useful_edges_attr), "walk_useful_edges_attr": sorted(self.walk_useful_edges_attr), "bike_useful_edges_attr": sorted(self.bike_useful_edges_attr), "transport_useful_edges_attr": sorted(self.transport_useful_edges_attr), "transport_route_attr": sorted(self.transport_route_attr), "overpass_min_interval": self.overpass_min_interval, "overpass_max_retries": self.overpass_max_retries, "overpass_retry_statuses": self.overpass_retry_statuses, "overpass_backoff_base": self.overpass_backoff_base, "user_agent": self.user_agent, "proxies": self.proxies, "verify_ssl": self.verify_ssl, "overpass_cache_dir": self.overpass_cache_dir, "overpass_cache_enabled": self.overpass_cache_enabled, "osm_source": self.osm_source, "pbf_path": self.pbf_path, }
[документация] @classmethod def from_env(cls) -> "Config": """ Construct Config using environment variables where available. Besides the ``OVERPASS_*`` variables, ``IDUEDU_OSM_SOURCE`` (``overpass`` or ``pbf``) and ``IDUEDU_PBF_PATH`` select the OSM data source. """ cfg = cls() return cfg
config = Config()
[документация] def use_pbf( path: str | os.PathLike | None = None, *, osm_id: int | None = None, territory: "Polygon | MultiPolygon | gpd.GeoDataFrame | gpd.GeoSeries | None" = None, region: str | None = None, **download_kwargs, ): """Temporarily read OSM data from a local file, or from a territory downloaded from Geofabrik. Shortcut for :meth:`config.use_pbf <Config.use_pbf>` on the global ``config``; the arguments are the same. Example: >>> with use_pbf(osm_id=1114252, region="northwestern-fed-district"): ... graph = get_intermodal_graph(osm_id=1114252) >>> with use_pbf("berlin.osm.pbf"): ... walk = get_walk_graph(territory=polygon) """ return config.use_pbf(path, osm_id=osm_id, territory=territory, region=region, **download_kwargs)