Team Ai
Apppublic

Maverick9876/document-extraction-workbench-cloud

sourceHugging Faceupdated 5mo agoView on Hugging Face
0likes
workbench_env.py71 linesDownload Raw Back to root
1import os2from pathlib import Path3 4 5APP_DIR = Path(__file__).resolve().parent6ENV_FILE = APP_DIR / ".env"7 8 9def _parse_env_line(line: str):10    stripped = line.strip()11    if not stripped or stripped.startswith("#") or "=" not in stripped:12        return None, None13 14    key, value = stripped.split("=", 1)15    key = key.strip()16    value = value.strip()17    if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:18        value = value[1:-1]19    return key, value20 21 22def read_app_env(path: Path = ENV_FILE) -> dict:23    if not path.exists():24        return {}25 26    values = {}27    for raw_line in path.read_text(encoding="utf-8").splitlines():28        key, value = _parse_env_line(raw_line)29        if key:30            values[key] = value31    return values32 33 34def load_app_env(path: Path = ENV_FILE, override: bool = True) -> dict:35    values = read_app_env(path=path)36    for key, value in values.items():37        if override or key not in os.environ:38            os.environ[key] = value39    return values40 41 42def write_app_env(values: dict, path: Path = ENV_FILE) -> Path:43    existing = read_app_env(path=path)44    for key, value in values.items():45        if value is None:46            existing.pop(key, None)47        else:48            existing[key] = str(value)49 50    ordered_keys = sorted(existing.keys())51    rendered = "\n".join(f"{key}={existing[key]}" for key in ordered_keys)52    path.write_text((rendered + "\n") if rendered else "", encoding="utf-8")53    return path54 55 56def bootstrap_env_file(path: Path = ENV_FILE) -> Path:57    if path.exists():58        return path59 60    initial_values = {}61    if os.getenv("AI_PROVIDER", "").strip():62        initial_values["AI_PROVIDER"] = os.getenv("AI_PROVIDER", "").strip()63    if os.getenv("OPENAI_API_KEY", "").strip():64        initial_values["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY", "").strip()65    initial_values["OPENAI_MODEL"] = os.getenv("OPENAI_MODEL", "gpt-4o").strip() or "gpt-4o"66    if os.getenv("GEMINI_API_KEY", "").strip():67        initial_values["GEMINI_API_KEY"] = os.getenv("GEMINI_API_KEY", "").strip()68    initial_values["GEMINI_MODEL"] = os.getenv("GEMINI_MODEL", "gemini-2.5-flash").strip() or "gemini-2.5-flash"69 70    return write_app_env(initial_values, path=path)71