File size: 2,393 Bytes
6d546ec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | """
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
|