File size: 6,947 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""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()