Spaces:
Sleeping
Sleeping
Download src/coveragecheck/deploy/space.py from TBM99/CoverageCheck: direct link, hf CLI and curl.
- Browser
- Download file 6.95 kB
-
https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/deploy/space.py
- Command line
-
hf download hf://spaces/TBM99/CoverageCheck/src/coveragecheck/deploy/space.py
-
curl -L -o space.py https://huggingface.co/spaces/TBM99/CoverageCheck/resolve/main/src/coveragecheck/deploy/space.py
6.95 kB
| """Step 10b: upload the app to a Hugging Face Docker Space, which then builds the image | |
| from the Dockerfile. | |
| uv run python -m coveragecheck.deploy.space <user>/<space> # push | |
| uv run python -m coveragecheck.deploy.space <user>/<space> --dry-run # list only | |
| uv run python -m coveragecheck.deploy.space --stage <folder> # copy locally | |
| Why not git: data/index/ (the prebuilt search index the app needs) is git-ignored, so | |
| the upload goes through huggingface_hub's commit API (binary files, no local git-lfs). | |
| What is uploaded is an explicit ALLOW-LIST (UPLOAD): never .env, the corpus PDFs, the | |
| eval runs or the LLM cache. One commit holds every file and deletes whatever the Space | |
| has that is no longer in the list, so the Space is exactly the list, nothing stale. | |
| The Space's README is the repo README with Hugging Face's YAML header in front: only the | |
| uploaded copy gets it, so GitHub shows the README without it. | |
| """ | |
| import argparse | |
| import shutil | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| from coveragecheck import config | |
| SPACE_PORT = 7860 # Hugging Face's default app_port; the Dockerfile's PORT must match | |
| # Glob patterns relative to the repo root (Path.glob: "**" = any depth). | |
| UPLOAD = ( | |
| "Dockerfile", | |
| ".dockerignore", | |
| ".python-version", | |
| "pyproject.toml", | |
| "uv.lock", | |
| "src/coveragecheck/**/*.py", | |
| "data/index/**/*", | |
| "web/package.json", | |
| "web/package-lock.json", | |
| "web/index.html", | |
| "web/components.json", | |
| "web/vite.config.ts", | |
| "web/tsconfig*.json", | |
| "web/src/**/*", | |
| "web/public/**/*", | |
| ) | |
| # What the app cannot start without (checked before anything is sent). | |
| REQUIRED = ( | |
| "data/index/chunks.parquet", | |
| "data/index/sections.parquet", | |
| "data/index/naive_chunks.parquet", | |
| "data/index/xrefs.parquet", | |
| "data/index/dense_a/meta.json", | |
| "data/index/dense_b/meta.json", | |
| "web/public/data/systems.json", | |
| ) | |
| # A file that matches UPLOAD but must never leave the machine anyway (belt and braces). | |
| NEVER = ("__pycache__", ".env", "node_modules") | |
| HEADER = """--- | |
| title: CoverageCheck | |
| emoji: 📑 | |
| colorFrom: blue | |
| colorTo: indigo | |
| sdk: docker | |
| app_port: {port} | |
| pinned: false | |
| short_description: Ontario auto insurance Q&A, three RAG designs compared | |
| --- | |
| """ | |
| def files_to_upload(root: Path) -> list[str]: | |
| """Every file the Space gets (besides its README), as sorted POSIX paths relative | |
| to root: the UPLOAD patterns, minus anything with a NEVER part in its path.""" | |
| found = set() | |
| for pattern in UPLOAD: | |
| for path in root.glob(pattern): | |
| relative = path.relative_to(root) | |
| if path.is_file() and not any(n in part for part in relative.parts for n in NEVER): | |
| found.add(relative.as_posix()) | |
| return sorted(found) | |
| def missing(root: Path) -> list[str]: | |
| """The REQUIRED files root does not have (the app would fail at boot without them).""" | |
| return [r for r in REQUIRED if not (root / r).is_file()] | |
| def space_readme(readme: str, port: int = SPACE_PORT) -> str: | |
| """The README with Hugging Face's Space header (sdk, app_port, title) in front.""" | |
| return HEADER.format(port=port) + readme | |
| def stage(root: Path, dest: Path) -> list[str]: | |
| """Copy exactly what would be uploaded (incl. the Space README) into dest, which | |
| must not exist yet: the local stand-in for the Space's checkout (10b': no Docker on | |
| this laptop). Returns the files copied.""" | |
| dest.mkdir(parents=True) | |
| files = files_to_upload(root) | |
| for name in files: | |
| (dest / name).parent.mkdir(parents=True, exist_ok=True) | |
| shutil.copyfile(root / name, dest / name) | |
| readme = space_readme((root / "README.md").read_text(encoding="utf-8")) | |
| (dest / "README.md").write_bytes(readme.encode("utf-8")) | |
| return files + ["README.md"] | |
| def operations(root: Path, remote_files: list[str]) -> list: | |
| """The one commit: add every uploaded file and the Space README; delete each remote | |
| file no longer uploaded (.gitattributes is the Space's own, kept).""" | |
| from huggingface_hub import CommitOperationAdd, CommitOperationDelete | |
| files = files_to_upload(root) | |
| readme = space_readme((root / "README.md").read_text(encoding="utf-8")).encode("utf-8") | |
| ops = [CommitOperationAdd(path_in_repo=f, path_or_fileobj=str(root / f)) for f in files] | |
| ops.append(CommitOperationAdd(path_in_repo="README.md", path_or_fileobj=readme)) | |
| keep = set(files) | {"README.md", ".gitattributes"} | |
| ops += [CommitOperationDelete(path_in_repo=f) for f in remote_files if f not in keep] | |
| return ops | |
| def git_commit(root: Path) -> str: | |
| """The commit being deployed; refuses a dirty working tree, so the Space always runs | |
| code that exists in git (the commit message names it).""" | |
| status = subprocess.run( | |
| ["git", "status", "--porcelain"], cwd=root, capture_output=True, text=True, check=True | |
| ).stdout | |
| if status.strip(): | |
| raise SystemExit("the working tree has uncommitted changes: commit them first") | |
| return subprocess.run( | |
| ["git", "rev-parse", "--short", "HEAD"], | |
| cwd=root, | |
| capture_output=True, | |
| text=True, | |
| check=True, | |
| ).stdout.strip() | |
| def push(api, repo_id: str, root: Path, commit: str) -> str: | |
| """Send the one commit to an EXISTING Space (created by the owner on the website, | |
| where the hardware, visibility and secrets are chosen). Returns the commit URL.""" | |
| remote = api.list_repo_files(repo_id, repo_type="space") | |
| info = api.create_commit( | |
| repo_id, | |
| operations(root, remote), | |
| commit_message=f"Deploy coverage-check {commit}", | |
| repo_type="space", | |
| ) | |
| return info.commit_url | |
| def main(argv: list[str] | None = None) -> None: | |
| parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) | |
| parser.add_argument("repo_id", nargs="?", help="the Space, e.g. <user>/coverage-check") | |
| parser.add_argument("--dry-run", action="store_true", help="list what would be sent") | |
| parser.add_argument("--stage", type=Path, help="copy the upload into this new folder") | |
| args = parser.parse_args(argv) | |
| root = config.ROOT | |
| if missing(root): | |
| sys.exit(f"missing (build them first): {', '.join(missing(root))}") | |
| if args.stage: | |
| files = stage(root, args.stage) | |
| print(f"staged {len(files)} files into {args.stage}") | |
| return | |
| if not args.repo_id: | |
| parser.error("give the Space id (or --stage)") | |
| files = files_to_upload(root) | |
| size = sum((root / f).stat().st_size for f in files) | |
| print(f"{len(files) + 1} files, {size / 1e6:.1f} MB (+ README) -> spaces/{args.repo_id}") | |
| if args.dry_run: | |
| print("\n".join(files)) | |
| return | |
| from huggingface_hub import HfApi | |
| url = push(HfApi(), args.repo_id, root, git_commit(root)) | |
| print(f"pushed: {url}\nthe Space now builds the image (watch its Logs tab)") | |
| if __name__ == "__main__": | |
| main() | |