grok2api-hf / deploy /hf-space /scripts /render_runtime_config.py
Codex
Add root Dockerfile for HF Space build
6bff6a1
from __future__ import annotations
import os
import tomllib
from pathlib import Path
from typing import Any
def parse_bool(raw: str) -> bool:
return raw.strip().lower() in {"1", "true", "yes", "on"}
def quote_string(value: str) -> str:
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
return f'"{escaped}"'
def format_toml_value(value: Any) -> str:
if isinstance(value, bool):
return "true" if value else "false"
if isinstance(value, (int, float)):
return str(value)
if isinstance(value, list):
return "[" + ",".join(format_toml_value(item) for item in value) + "]"
return quote_string(str(value))
def load_existing_config(path: Path) -> dict[str, Any]:
if not path.exists():
return {}
with path.open("rb") as handle:
return tomllib.load(handle)
def update_section(target: dict[str, Any], section: str, key: str, env_name: str, *, as_bool: bool = False) -> None:
raw = os.getenv(env_name)
if raw is None:
return
sec = target.setdefault(section, {})
sec[key] = parse_bool(raw) if as_bool else raw
def write_config(path: Path, config: dict[str, Any]) -> None:
lines: list[str] = []
for section, items in config.items():
if not isinstance(items, dict):
continue
lines.append(f"[{section}]")
for key, value in items.items():
lines.append(f"{key} = {format_toml_value(value)}")
lines.append("")
path.write_text("\n".join(lines).strip() + "\n", encoding="utf-8")
def main() -> None:
data_dir = Path(os.getenv("DATA_DIR", "/app/data"))
config_path = data_dir / "config.toml"
data_dir.mkdir(parents=True, exist_ok=True)
config = load_existing_config(config_path)
update_section(config, "app", "api_key", "GROK2API_API_KEYS")
update_section(config, "app", "app_key", "GROK2API_APP_KEY")
update_section(config, "app", "function_key", "GROK2API_FUNCTION_KEY")
update_section(config, "app", "function_enabled", "GROK2API_FUNCTION_ENABLED", as_bool=True)
update_section(config, "app", "app_url", "GROK2API_APP_URL")
update_section(config, "proxy", "base_proxy_url", "GROK2API_PROXY_BASE_URL")
update_section(config, "proxy", "asset_proxy_url", "GROK2API_PROXY_ASSET_URL")
update_section(config, "proxy", "cf_clearance", "GROK2API_CF_CLEARANCE")
update_section(config, "proxy", "cf_cookies", "GROK2API_CF_COOKIES")
write_config(config_path, config)
if __name__ == "__main__":
main()