Spaces:
Sleeping
Sleeping
| import os | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| ENV_PATH = Path(".env") | |
| ENV_VAR_NAME = "GOOGLE_API_KEY" # Keep Google-style key name for Gemini | |
| # Load .env once on import (local runs) | |
| load_dotenv(dotenv_path=ENV_PATH, override=False) | |
| def in_hf_spaces() -> bool: | |
| """Detect if running inside Hugging Face Spaces.""" | |
| return bool(os.getenv("SPACE_ID")) | |
| def get_api_key() -> str | None: | |
| """Read the API key (from env or Space Secret).""" | |
| return os.getenv(ENV_VAR_NAME) | |
| def ensure_env_file() -> None: | |
| if not ENV_PATH.exists(): | |
| ENV_PATH.write_text("") | |
| def set_api_key(value: str, var_name: str = ENV_VAR_NAME) -> None: | |
| """ | |
| Persist the key to .env for local runs. | |
| On Spaces, DO NOT write to disk (no-op) — use session key instead. | |
| """ | |
| if in_hf_spaces(): | |
| return # no-op on Spaces | |
| value = (value or "").strip() | |
| ensure_env_file() | |
| lines = ENV_PATH.read_text().splitlines() | |
| out, found = [], False | |
| for line in lines: | |
| if line.strip().startswith(f"{var_name}="): | |
| out.append(f"{var_name}={value}") | |
| found = True | |
| else: | |
| out.append(line) | |
| if not found: | |
| out.append(f"{var_name}={value}") | |
| ENV_PATH.write_text("\n".join(out) + "\n") | |
| os.environ[var_name] = value # also set for this process | |