Spaces:
Running on Zero

controlplane-ai / deploy /deploy_hf.py
Pawan2605's picture
Deploy ControlPlane.ai
3953bb6 verified
Raw History Blame Contribute Delete
10.4 kB
"""
Deploy ControlPlane.ai to a Hugging Face Space (Gradio SDK, ZeroGPU) in ONE commit.
pip install -U huggingface_hub
huggingface-cli login # or: export HF_TOKEN=hf_xxx (write token)
python deploy/deploy_hf.py --space <hf-username>/controlplane-ai --dry-run
python deploy/deploy_hf.py --space <hf-username>/controlplane-ai
python deploy/deploy_hf.py --space <hf-username>/controlplane-ai --push-secrets
Uploads straight from this working copy - including the prebuilt FAISS/BM25/
JSON indexes that .gitignore keeps out of GitHub - with large/binary files sent
via LFS automatically. `deploy/space_README.md` becomes the Space's README.md
(it carries the Space config: sdk gradio, app.py). Never uploads .env files.
--push-secrets copies the keys listed in SECRET_KEYS from your environment /
.env files into the Space's *secrets* (encrypted, not visible in the repo).
"""
from __future__ import annotations
import argparse
import fnmatch
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# never uploaded (mirrors .dockerignore + local-only files)
EXCLUDE = [
".env", "*/.env", ".env.*", "*/.env.*", ".streamlit/secrets.toml",
".git/*", ".github/*", "*/.DS_Store", ".DS_Store", "*/__pycache__/*", "*.pyc",
"*/__MACOSX/*", ".pytest_cache/*", "*/.pytest_cache/*", ".data/*", ".venv/*", ".claude/*",
"_to_delete/*", "implementation_plan-2.md", "*.ipynb", "README.md",
"web/*", "docs/*", ".superpowers/*", # Vercel site + design docs
"Responsiblity Agent/Dataset/*", "Responsiblity Agent/data/chroma_db/*",
"Responsiblity Agent/data/chroma_db_local/*", "Responsiblity Agent/data/graph_vis.html",
"rag_agents/hr_policy/*.pdf", "rag_agents/internal_knowledge/documents/*",
"rag_agents/internal_knowledge/azure-docs-sparse/*", "rag_agents/Toxic_RAG/Toxic_RAG/Dataset/*",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/combined_meetings.*",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/*.csv",
"master_router/performance_branch/hallucination_classifier/processed_data/*",
]
ALLOW_DOTFILES = {".dockerignore", ".streamlit/config.toml", ".env.example"}
HARDWARE = "zero-a10g" # ZeroGPU; free for personal accounts (max 2 Spaces)
def space_requirements(text: str) -> str:
"""deploy/requirements.txt -> the Space's requirements.txt.
The CPU-only torch index is dropped: ZeroGPU's `spaces` helper reads CUDA
fields that the CPU wheel lacks and crashes at import. The standard PyPI
torch wheel (CUDA build) runs fine on the CPU. The helper itself (`spaces`)
is NOT listed: Hugging Face installs its own pinned copy in every ZeroGPU
build, and a second pin makes pip fail with ResolutionImpossible.
"""
lines = [ln for ln in text.splitlines() if not ln.strip().startswith("--extra-index-url")]
return "\n".join(lines) + "\n"
# files the app cannot start without (checked before uploading)
REQUIRED = [
"app.py", "packages.txt", "Dockerfile", "start.py", "deploy/requirements.txt", "deploy/prefetch_models.py",
"rag_agents/customer_support/faiss_index/index.faiss",
"rag_agents/customer_support/faiss_index/index.pkl",
"rag_agents/customer_support/faiss_index/bm25_index.pkl",
"rag_agents/hr_policy/faiss_index/index.faiss",
"rag_agents/hr_policy/faiss_index/parent_store.json",
"rag_agents/internal_knowledge/faiss_index/index.faiss",
"rag_agents/internal_knowledge/faiss_index/chunks.jsonl",
"rag_agents/Toxic_RAG/Toxic_RAG/.index_cache/faiss_index/index.faiss",
"rag_agents/Toxic_RAG/Toxic_RAG/.index_cache/bm25_retriever.pkl",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/faiss_index.bin",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/bm25_index.pkl",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/parents_store.json",
"rag_agents/Decision Support Rag/Decision Support Rag/Data/children_store.json",
"Responsiblity Agent/data/chunk_store.json",
"Responsiblity Agent/data/bm25_index.pkl",
"Responsiblity Agent/data/graph_triples.json",
"Responsiblity Agent/data/resp_minilm_matrix.npz",
"master_router/performance_branch/hallucination_classifier/model/xgb_hallucination_model.json",
]
SECRET_KEYS = [
"GROQ_API_KEYS", "GROQ_API_KEY", "GEMINI_API_KEYS", "GOOGLE_API_KEY",
"LANGCHAIN_API_KEY", "LANGCHAIN_PROJECT", "LANGCHAIN_TRACING_V2",
"NEO4J_URI", "NEO4J_USERNAME", "NEO4J_PASSWORD", "NEO4J_DATABASE",
"DATABASE_URL", "GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET", "AUTH_COOKIE_SECRET",
"SMTP_USER", "SMTP_PASSWORD", "SMTP_HOST", "SMTP_PORT", "SMTP_FROM",
"BACKEND_SECRET", "ALLOWED_ORIGINS", # Vercel site <-> this API
]
def _excluded(rel: str) -> bool:
if any(fnmatch.fnmatch(rel, pat) for pat in EXCLUDE):
return True
parts = rel.split("/")
# hidden dirs/files are skipped unless explicitly allowed (keeps e.g. Toxic_RAG/.index_cache)
if rel not in ALLOW_DOTFILES and any(p.startswith(".") and p not in {".index_cache", ".streamlit"}
for p in parts):
return True
return False
def collect() -> list[tuple[str, Path]]:
out = []
for p in sorted(ROOT.rglob("*")):
if p.is_file():
rel = p.relative_to(ROOT).as_posix()
if not _excluded(rel):
out.append((rel, p))
return out
def _load_env_files() -> None:
try:
from dotenv import dotenv_values
except ImportError:
return
for f in (ROOT / ".env", ROOT / "controlplane" / ".env"):
if f.exists():
for k, v in dotenv_values(f).items():
if v and k not in os.environ:
os.environ[k] = v
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--space", required=True, help="<hf-username>/<space-name>")
ap.add_argument("--private", action="store_true", help="create the Space as private")
ap.add_argument("--dry-run", action="store_true", help="list what would be uploaded, upload nothing")
ap.add_argument("--push-secrets", action="store_true", help="copy SECRET_KEYS from env/.env into Space secrets")
args = ap.parse_args()
missing = [r for r in REQUIRED if not (ROOT / r).exists()]
if missing:
sys.exit("Missing required files (build the indexes first):\n " + "\n ".join(missing))
files = collect()
total = sum(p.stat().st_size for _, p in files)
print(f"{len(files)} files, {total / 1e6:.1f} MB")
if args.dry_run:
big = sorted(files, key=lambda x: -x[1].stat().st_size)[:12]
for rel, p in big:
print(f" {p.stat().st_size / 1e6:7.1f} MB {rel}")
leaked = [r for r, _ in files if r.endswith(".env") or "secrets.toml" in r]
print("secret files included:", leaked or "none")
return
from huggingface_hub import CommitOperationAdd, HfApi
from huggingface_hub.errors import HfHubHTTPError
api = HfApi(token=os.getenv("HF_TOKEN") or None)
# Gradio SDK on ZeroGPU: the only compute a FREE personal account may create
# (Docker / cpu-basic Spaces now need PRO and fail with 402). The pipeline
# never uses the GPU; the host's 16 GB RAM is what matters.
try:
api.create_repo(args.space, repo_type="space", space_sdk="gradio", space_hardware=HARDWARE,
private=args.private, exist_ok=True)
except HfHubHTTPError as e:
if e.response is not None and e.response.status_code == 402:
sys.exit("Hugging Face refused to create the Space (402). A free account can host at most 2 "
"ZeroGPU Spaces and must be older than 30 days with a verified e-mail; delete an old "
"Space at https://huggingface.co/spaces or subscribe to PRO.\n" + str(e))
raise
rt = api.get_space_runtime(args.space)
current = str(getattr(rt, "requested_hardware", None) or rt.hardware or "")
if HARDWARE not in current:
print(f"hardware is {current or 'unset'} -> requesting {HARDWARE}")
api.request_space_hardware(args.space, HARDWARE)
if args.push_secrets:
_load_env_files()
pushed = []
for k in SECRET_KEYS:
v = os.getenv(k, "").strip()
if v:
api.add_space_secret(args.space, k, v)
pushed.append(k)
print("secrets set:", ", ".join(pushed) or "(none found)")
# non-secret pipeline tuning (CP_*) -> public Space *variables*, so the hosted
# app behaves like your local one. Local-only / debug flags are skipped.
skip = {"CP_LLM_MOCK", "CP_AUTH_DISABLED", "CP_HF_ONLINE", "CP_DETOXIFY_ALLOW_DOWNLOAD",
"CP_DISABLE_DETOXIFY", # local-only shortcut; production runs the full ensemble
"CP_DEBUG", "CP_CACHE_DIR", "CP_DB_PATH", "CP_SKIP_WARMUP", "CP_CACHE_PERSIST"}
tuned = []
for k, v in sorted(os.environ.items()):
if k.startswith("CP_") and k not in skip and v.strip():
api.add_space_variable(args.space, k, v.split(" #", 1)[0].strip())
tuned.append(k)
print("variables set:", ", ".join(tuned) or "(none)")
ops = [CommitOperationAdd(path_in_repo=rel, path_or_fileobj=str(p)) for rel, p in files]
ops.append(CommitOperationAdd(path_in_repo="README.md",
path_or_fileobj=str(ROOT / "deploy" / "space_README.md")))
# the Gradio SDK installs the root requirements.txt (and apt packages.txt)
req = space_requirements((ROOT / "deploy" / "requirements.txt").read_text(encoding="utf-8"))
ops.append(CommitOperationAdd(path_in_repo="requirements.txt", path_or_fileobj=req.encode("utf-8")))
info = api.create_commit(repo_id=args.space, repo_type="space", operations=ops,
commit_message="Deploy ControlPlane.ai")
user, name = args.space.split("/", 1)
host = f"{user}-{name}".lower().replace("_", "-").replace(".", "-")
print(f"\nPushed: {info.commit_url}")
print(f"Build logs: https://huggingface.co/spaces/{args.space}?logs=build")
print(f"API URL (use this as BACKEND_URL / NEXT_PUBLIC_BACKEND_URL on Vercel): https://{host}.hf.space")
if __name__ == "__main__":
main()