""" core/paths.py — Sentinel-AI ============================== Path resolution helpers. All previously hard-coded relative paths were resolved against the *current working directory*. That made the application work only when uvicorn was started from ``backend/`` and made ``build_index.py`` fail when run from the project root (or from another drive). These helpers anchor every default to the backend package directory instead, while still honouring absolute values from ``.env`` and values that are valid relative to the current directory. """ from __future__ import annotations import math import os from pathlib import Path # .../AI Infra/backend BASE_DIR = Path(__file__).resolve().parent.parent # .../AI Infra PROJECT_ROOT = BASE_DIR.parent def resolve_path(value: str | os.PathLike[str] | None, default: str) -> Path: """ Resolve ``value`` (normally an env var) to an absolute path. The search order for relative paths is: 1. current working directory (backwards compatible) 2. backend directory 3. project root For input paths the first existing candidate wins. For output paths (files that do not exist yet) the backend directory is used, which matches the historical ``cd backend && python ...`` workflow. """ raw = str(value) if value not in (None, "") else default path = Path(raw).expanduser() if path.is_absolute(): return path candidates = [Path.cwd() / path, BASE_DIR / path, PROJECT_ROOT / path] for candidate in candidates: if candidate.exists(): return candidate.resolve() return (BASE_DIR / path).resolve() def env_int(name: str, default: int) -> int: """Read a positive integer env var, falling back to ``default``.""" try: value = int(os.getenv(name, str(default))) except (TypeError, ValueError): return default return value if value > 0 else default def env_float(name: str, default: float) -> float: """Read a finite float env var, falling back to ``default`` when malformed.""" try: value = float(os.getenv(name, str(default))) except (TypeError, ValueError): return default # NaN would make every comparison false (silently disabling matching) and # infinity would break threshold arithmetic. Treat both as misconfiguration. return value if math.isfinite(value) else default