humanize-text-python / scripts /run_hf_space.py
thanhnv2323's picture
init: add app fastapi
09da05c
Raw History Blame Contribute Delete
1.8 kB
"""Run the FastAPI backend in a Hugging Face Docker Space."""
from __future__ import annotations
import os
from pathlib import Path
import sys
def _runtime_root() -> Path:
data_root = Path("/data")
if data_root.exists() and os.access(data_root, os.W_OK | os.X_OK):
return data_root / "adsp"
return Path("/tmp/adsp")
def _ensure_runtime_dirs() -> None:
runtime_root = _runtime_root()
hf_home = Path(os.environ.setdefault("HF_HOME", str(runtime_root / "huggingface")))
hub_cache = Path(
os.environ.setdefault("HUGGINGFACE_HUB_CACHE", str(hf_home / "hub"))
)
sentence_cache = Path(os.environ.setdefault("SENTENCE_TRANSFORMERS_HOME", str(hf_home / "sentence_transformers")))
vectorstore_dir = Path(
os.environ.setdefault(
"ADSP_VECTORSTORE_PERSIST_DIR",
str(runtime_root / "vectorstores"),
)
)
for path in (runtime_root, hf_home, hub_cache, sentence_cache, vectorstore_dir):
path.mkdir(parents=True, exist_ok=True)
def _configure_env() -> int:
api_port = int(os.environ.get("PORT", os.environ.get("ADSP_API_PORT", "7860")))
os.environ["ADSP_API_HOST"] = "0.0.0.0"
os.environ["ADSP_API_PORT"] = str(api_port)
os.environ.setdefault("ADSP_API_RUN_MODE", "uvicorn")
os.environ.setdefault("ADSP_API_RELOAD", "false")
os.environ.setdefault("ADSP_API_WORKERS", "1")
_ensure_runtime_dirs()
return api_port
def main() -> int:
api_port = _configure_env()
api_cmd = [
sys.executable,
"scripts/run_api.py",
"--port",
str(api_port),
"--no-reload",
]
print(f"Starting API on 0.0.0.0:{api_port}", flush=True)
os.execv(sys.executable, api_cmd)
if __name__ == "__main__":
raise SystemExit(main())