File size: 7,997 Bytes
e965652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21ff762
 
 
 
 
 
e965652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21ff762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e965652
21ff762
 
 
 
 
 
 
 
 
 
 
 
 
e965652
 
 
 
 
 
 
 
 
 
 
69988c6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e965652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21ff762
e965652
 
 
69988c6
 
e965652
 
69988c6
 
 
e965652
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
"""Sync the current git tree to Hugging Face with HF-only card metadata."""

from __future__ import annotations

import argparse
import os
import shutil
import subprocess
import tempfile
from pathlib import Path

DEFAULT_REPO_ID = "Stevesolun/ctx"
DEFAULT_REPO_TYPE = "dataset"

HF_CARD_METADATA = """---

license: mit

pretty_name: ctx

tags:

  - agents

  - mcp

  - skills

  - knowledge-graph

  - llm-wiki

  - recommendation-system

  - harness

  - codex

  - claude-code

---



"""

LFS_POINTER_PREFIX = b"version https://git-lfs.github.com/spec/v1"
HYDRATED_ARTIFACT_MIN_BYTES = {
    Path("graph/wiki-graph.tar.gz"): 100_000_000,
    Path("graph/skills-sh-catalog.json.gz"): 1_000_000,
}


def with_hf_repo_card_metadata(readme_text: str) -> str:
    """Return README text with Hugging Face repo-card metadata prepended."""
    return HF_CARD_METADATA + _strip_leading_yaml_frontmatter(readme_text)


def _strip_leading_yaml_frontmatter(text: str) -> str:
    if not text.startswith("---\n"):
        return text
    end = text.find("\n---\n", 4)
    if end == -1:
        return text
    return text[end + len("\n---\n") :].lstrip("\n")


def _git(repo: Path, *args: str) -> str:
    return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()


def _git_bytes(repo: Path, *args: str) -> bytes:
    return subprocess.check_output(["git", *args], cwd=repo)


def _iter_tracked_files(repo: Path) -> list[Path]:
    output = _git_bytes(repo, "ls-files", "-z")
    files: list[Path] = []
    for raw in output.split(b"\0"):
        if not raw:
            continue
        rel = Path(raw.decode("utf-8"))
        if rel.is_absolute() or ".." in rel.parts:
            raise ValueError(f"unsafe git path: {rel}")
        files.append(rel)
    return files


def _assert_hydrated_artifacts(repo: Path) -> None:
    for rel, min_bytes in HYDRATED_ARTIFACT_MIN_BYTES.items():
        artifact = repo / rel
        if not artifact.is_file():
            raise FileNotFoundError(
                f"{rel.as_posix()} is required before Hugging Face sync"
            )
        size = artifact.stat().st_size
        if size < min_bytes:
            raise RuntimeError(
                f"{rel.as_posix()} is {size:,} bytes; expected at least "
                f"{min_bytes:,}. Run git lfs pull before publishing."
            )
        with artifact.open("rb") as fh:
            prefix = fh.read(len(LFS_POINTER_PREFIX))
        if prefix == LFS_POINTER_PREFIX:
            raise RuntimeError(
                f"{rel.as_posix()} is a Git LFS pointer, not the hydrated artifact"
            )


def _export_tracked_tree(repo: Path, export_dir: Path) -> None:
    _assert_hydrated_artifacts(repo)
    repo_root = repo.resolve()
    export_root = export_dir.resolve()
    for rel in _iter_tracked_files(repo):
        source = (repo_root / rel).resolve()
        if source != repo_root and not source.is_relative_to(repo_root):
            raise ValueError(f"unsafe source path: {rel}")
        if source.is_symlink():
            raise ValueError(f"refusing to follow symlink during HF sync: {rel}")
        if not source.is_file():
            continue
        target = (export_root / rel).resolve()
        if target != export_root and not target.is_relative_to(export_root):
            raise ValueError(f"unsafe export path: {rel}")
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(source, target)


def _patch_export_readme(export_dir: Path) -> None:
    readme = export_dir / "README.md"
    readme.write_text(
        with_hf_repo_card_metadata(readme.read_text(encoding="utf-8")),
        encoding="utf-8",
        newline="\n",
    )


def _iter_export_file_names(export_dir: Path) -> set[str]:
    names: set[str] = set()
    for path in export_dir.rglob("*"):
        if not path.is_file():
            continue
        rel = path.relative_to(export_dir).as_posix()
        if rel == ".cache" or rel.startswith(".cache/"):
            continue
        names.add(rel)
    return names


def _repo_url(*, repo_id: str, repo_type: str) -> str:
    prefix = {"dataset": "datasets", "space": "spaces"}.get(repo_type)
    repo_path = f"{prefix}/{repo_id}" if prefix else repo_id
    return f"https://huggingface.co/{repo_path}"


def _repo_commit_url(*, repo_id: str, repo_type: str, sha: str) -> str:
    return f"{_repo_url(repo_id=repo_id, repo_type=repo_type)}/commit/{sha}"


def _remote_has_no_stale_paths(

    *,

    api: object,

    export_dir: Path,

    repo_id: str,

    repo_type: str,

) -> bool:
    try:
        remote_files = set(api.list_repo_files(repo_id=repo_id, repo_type=repo_type))
    except Exception:
        return False
    return remote_files <= _iter_export_file_names(export_dir)


def _upload_export(

    *,

    api: object,

    export_dir: Path,

    repo_id: str,

    repo_type: str,

    head: str,

    prefer_large_upload: bool,

) -> str:
    if (
        prefer_large_upload
        and hasattr(api, "upload_large_folder")
        and _remote_has_no_stale_paths(
            api=api,
            export_dir=export_dir,
            repo_id=repo_id,
            repo_type=repo_type,
        )
    ):
        api.upload_large_folder(
            repo_id=repo_id,
            repo_type=repo_type,
            folder_path=str(export_dir),
            print_report=True,
        )
        info = api.repo_info(repo_id=repo_id, repo_type=repo_type)
        sha = getattr(info, "sha", None)
        if sha:
            return _repo_commit_url(repo_id=repo_id, repo_type=repo_type, sha=str(sha))
        return _repo_url(repo_id=repo_id, repo_type=repo_type)

    info = api.upload_folder(
        repo_id=repo_id,
        repo_type=repo_type,
        folder_path=str(export_dir),
        commit_message=f"Sync ctx {head[:7]}",
        commit_description=f"GitHub commit: {head}",
        delete_patterns="*",
    )
    return str(getattr(info, "commit_url", info))


def sync_to_huggingface(

    *,

    repo: Path,

    repo_id: str,

    repo_type: str,

    token: str,

) -> str:
    """Upload HEAD to Hugging Face and return the commit URL."""
    from huggingface_hub import HfApi

    head = _git(repo, "rev-parse", "HEAD")
    workspace = Path(tempfile.mkdtemp(prefix="ctx-hf-upload-"))
    export_dir = workspace / "export"
    try:
        export_dir.mkdir()
        _export_tracked_tree(repo, export_dir)
        _patch_export_readme(export_dir)
        api = HfApi(token=token)
        api.create_repo(repo_id, repo_type=repo_type, exist_ok=True)
        return _upload_export(
            api=api,
            repo_id=repo_id,
            repo_type=repo_type,
            export_dir=export_dir,
            head=head,
            prefer_large_upload=True,
        )
    finally:
        shutil.rmtree(workspace, ignore_errors=True)


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Upload this git checkout to Hugging Face with repo-card metadata"
    )
    parser.add_argument("--repo", default=".", help="Git checkout path")
    parser.add_argument(
        "--repo-id",
        default=os.environ.get("HF_REPO_ID", DEFAULT_REPO_ID),
        help="Hugging Face repo ID",
    )
    parser.add_argument(
        "--repo-type",
        default=os.environ.get("HF_REPO_TYPE", DEFAULT_REPO_TYPE),
        help="Hugging Face repo type",
    )
    args = parser.parse_args()
    token = os.environ.get("HF_TOKEN")
    if not token:
        raise SystemExit("HF_TOKEN is required")
    print(
        sync_to_huggingface(
            repo=Path(args.repo).resolve(),
            repo_id=args.repo_id,
            repo_type=args.repo_type,
            token=token,
        )
    )


if __name__ == "__main__":
    main()