dataops-env / env_loader.py
visheshrathi's picture
Upload folder using huggingface_hub
a1b343c verified
Raw History Blame Contribute Delete
2.29 kB
"""Load local env files without overriding externally injected runtime env vars."""
import logging
import os
from pathlib import Path
from dotenv import dotenv_values, load_dotenv
logger = logging.getLogger(__name__)
_PROJECT_ROOT = Path(__file__).resolve().parent
_RUNTIME_ENV_KEYS = (
"ENV_FILE",
"HOST",
"PORT",
"DEBUG",
"ENV_BASE_URL",
"ADMIN_API_KEY",
"PUBLIC_GRADER_DETAILS",
"COOKIE_SECURE",
"HTTP_SESSION_TIMEOUT_S",
"CORS_ALLOW_ORIGINS",
"MAX_HTTP_SESSIONS",
"MAX_WS_SESSIONS",
"API_KEY",
"HF_TOKEN",
"MODEL_NAME",
"API_BASE_URL",
)
def _has_external_runtime_config() -> bool:
return any(bool(os.getenv(key, "").strip()) for key in _RUNTIME_ENV_KEYS)
def _resolve_env_file(env_file_name: str) -> Path:
env_path = (_PROJECT_ROOT / env_file_name).resolve()
try:
env_path.relative_to(_PROJECT_ROOT)
except ValueError as exc:
raise ValueError(
f"ENV_FILE '{env_file_name}' must resolve inside the project root."
) from exc
return env_path
def load_env() -> None:
"""Read repo-root .env to locate the active secondary env file."""
dot_env = _PROJECT_ROOT / ".env"
if not dot_env.exists():
if _has_external_runtime_config():
logger.debug(
".env not found at %s — assuming runtime env vars were injected externally",
dot_env,
)
return
logger.warning(
".env not found at %s — local runs expect it to define ENV_FILE for the active env file",
dot_env,
)
return
load_dotenv(dot_env, override=False)
env_file_name = str(
(dotenv_values(dot_env).get("ENV_FILE") or os.getenv("ENV_FILE") or "")
).strip()
if not env_file_name:
logger.debug(".env did not specify ENV_FILE — no secondary file loaded")
return
try:
env_file = _resolve_env_file(env_file_name)
except ValueError as exc:
logger.warning("%s", exc)
return
if not env_file.exists():
logger.warning("ENV_FILE '%s' not found at %s", env_file_name, env_file)
return
load_dotenv(env_file, override=False)
logger.debug("Loaded environment variables from %s", env_file)