File size: 15,748 Bytes
e740887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
#!/usr/bin/env python3
"""Offline release planning; --publish explicitly uploads a verified snapshot.

The dataset repository contains this mathematical research artifact and its
synthetic reference data. No remote file is deleted. Authentication uses the
existing Hugging Face token store or HF_TOKEN.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import stat
import sys
import tempfile
import time
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Callable, Optional, Tuple


PROJECT_NAME = "ORYNTHRA-H6"
HUB_DATASET_URL = "https://huggingface.co/datasets/"
MANIFEST_NAME = "SHA256SUMS.txt"
BLOCKED_PARTS = {
    ".git", ".hg", ".svn", ".venv", "venv", "__pycache__", ".cache",
    ".pytest_cache", ".mypy_cache", ".upload_state",
}
BLOCKED_NAMES = {
    ".env", ".netrc", ".npmrc", ".pypirc", "credentials.json",
    "secrets.json", "token", "token.txt", "hf_token", "hf_token.txt",
}
MANIFEST_LINE = re.compile(r"^([0-9a-fA-F]{64}) [ *](.+)$")


class ReleaseError(Exception):
    """A local release check failed; its message contains no credentials."""


class HubOperationError(Exception):
    def __init__(self, operation: str, error_class: str,
                 status_code: Optional[int] = None):
        super().__init__(operation)
        self.operation = operation
        self.error_class = error_class
        self.status_code = status_code


@dataclass(frozen=True)
class FileEntry:
    path: str
    sha256: str
    size: int


@dataclass(frozen=True)
class VerifiedRelease:
    root: Path
    entries: Tuple[FileEntry, ...]
    manifest_bytes: bytes

    @property
    def allow_patterns(self):
        # Each path is literal: manifest parsing prohibits glob metacharacters.
        return [entry.path for entry in self.entries] + [MANIFEST_NAME]


def validate_relative_path(value: str) -> str:
    if not value or value != value.strip():
        raise ReleaseError("Manifest paths must be nonempty without outer spaces.")
    if any(ord(c) < 32 or ord(c) == 127 for c in value):
        raise ReleaseError("Manifest paths cannot contain control characters.")
    if any(c in value for c in "\\:*?[]{}<>\"|") or value.startswith("/"):
        raise ReleaseError("Manifest paths must be relative, literal POSIX paths.")
    parts = value.split("/")
    if any(p in ("", ".", "..") for p in parts):
        raise ReleaseError("Manifest path traversal or empty path components rejected.")
    for part in parts:
        lower = part.lower()
        if lower in BLOCKED_PARTS or lower in BLOCKED_NAMES:
            raise ReleaseError("Manifest contains a cache, credential, or upload-state path.")
        if lower.startswith(".env.") or lower.endswith((".pem", ".key")):
            raise ReleaseError("Manifest contains a possible credential file.")
        if part.endswith((" ", ".")):
            raise ReleaseError("Manifest path is unsafe on Windows.")
        stem = part.split(".")[0].upper()
        if stem in {"CON", "PRN", "AUX", "NUL"} or re.fullmatch(r"(?:COM|LPT)[1-9]", stem):
            raise ReleaseError("Manifest contains a Windows reserved path.")
    return value


def checked_path(root: Path, relative: str) -> Path:
    value = validate_relative_path(relative)
    current = root
    for part in value.split("/"):
        current = current / part
        if current.is_symlink():
            raise ReleaseError("Symlink rejected: " + value)
    if not current.is_file():
        raise ReleaseError("Manifest file is missing or is not a regular file: " + value)
    try:
        current.resolve(strict=True).relative_to(root)
    except (ValueError, OSError):
        raise ReleaseError("Manifest file escapes the release root: " + value) from None
    if not stat.S_ISREG(current.stat().st_mode):
        raise ReleaseError("Non-regular file rejected: " + value)
    return current


def digest_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as source:
        for block in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def verify_release(root: Path) -> VerifiedRelease:
    if root.is_symlink():
        raise ReleaseError("The release root cannot be a symlink.")
    root = root.resolve(strict=True)
    if not root.is_dir():
        raise ReleaseError("The release root must be a directory.")
    manifest_path = checked_path(root, MANIFEST_NAME)
    manifest_bytes = manifest_path.read_bytes()
    try:
        manifest_text = manifest_bytes.decode("utf-8")
    except UnicodeError:
        raise ReleaseError("SHA256SUMS.txt must use UTF-8 text.") from None
    entries = []
    seen = set()
    for line_number, line in enumerate(manifest_text.splitlines(), 1):
        if not line.strip() or line.startswith("#"):
            continue
        match = MANIFEST_LINE.fullmatch(line)
        if not match:
            raise ReleaseError("Malformed SHA256SUMS.txt line " + str(line_number) + ".")
        expected, relative = match.groups()
        validate_relative_path(relative)
        if relative.casefold() == MANIFEST_NAME.casefold():
            raise ReleaseError("The manifest cannot contain a checksum of itself.")
        if relative.casefold() in seen:
            raise ReleaseError("Duplicate or case-colliding manifest path rejected.")
        seen.add(relative.casefold())
        path = checked_path(root, relative)
        if digest_file(path) != expected.lower():
            raise ReleaseError("SHA-256 mismatch: " + relative + ". Rebuild the release manifest.")
        entries.append(FileEntry(relative, expected.lower(), path.stat().st_size))
    if not entries:
        raise ReleaseError("The release manifest has no approved files.")
    return VerifiedRelease(root, tuple(entries), manifest_bytes)


def stage_release(release: VerifiedRelease, destination: Path) -> None:
    """Copy only approved bytes; rehash before any Hub network request."""
    for entry in release.entries:
        source = checked_path(release.root, entry.path)
        target = destination.joinpath(*entry.path.split("/"))
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copyfile(source, target)
        if digest_file(target) != entry.sha256:
            raise ReleaseError("File changed while preparing the upload: " + entry.path)
    (destination / MANIFEST_NAME).write_bytes(release.manifest_bytes)


def validate_repo_id(value: str) -> str:
    parts = value.split("/")
    if len(parts) != 2:
        raise ReleaseError("Use a full repository ID: account-or-organization/ORYNTHRA-H6.")
    for part in parts:
        if (not re.fullmatch(r"[A-Za-z0-9_-][A-Za-z0-9_.-]{0,95}", part)
                or part.endswith((".", "-")) or ".." in part or "--" in part):
            raise ReleaseError("Invalid Hugging Face repository ID.")
    return value


def status_code_of(error: Exception) -> Optional[int]:
    response = getattr(error, "response", None)
    status = getattr(response, "status_code", None)
    return status if isinstance(status, int) else None


def is_transient(error: Exception, status_code: Optional[int]) -> bool:
    if status_code == 429 or (status_code is not None and 500 <= status_code <= 599):
        return True
    error_name = type(error).__name__.lower()
    return isinstance(error, TimeoutError) or any(
        marker in error_name for marker in (
            "timeout", "connectionerror", "connecterror", "readerror",
            "networkerror", "transporterror", "remoteprotocolerror",
        )
    )


def hub_call(operation: str, function: Callable, max_attempts: int):
    for attempt in range(1, max_attempts + 1):
        try:
            return function()
        except Exception as error:
            status = status_code_of(error)
            if is_transient(error, status) and attempt < max_attempts:
                delay = min(2 ** attempt, 8)
                detail = "HTTP " + str(status) if status is not None else type(error).__name__
                print(f"{operation}: temporary failure ({detail}); retry {attempt + 1}/{max_attempts} in {delay}s.")
                time.sleep(delay)
                continue
            raise HubOperationError(operation, type(error).__name__, status) from None


def authentication_guidance() -> None:
    print("Install the upload dependency: python -m pip install -r requirements-upload.txt")
    print("Then authenticate locally: hf auth login")
    print("Use a write-enabled token authorized for the target repository.")
    print("HF_TOKEN is also supported; never put a token in this release or a command shared with others.")


def write_receipt(release: VerifiedRelease, repo_id: str, commit_info) -> Path:
    directory = release.root / ".upload_state"
    if directory.is_symlink():
        raise ReleaseError("Upload receipt directory is a symlink.")
    directory.mkdir(exist_ok=True)
    target = directory / "last_upload.json"
    if target.is_symlink():
        raise ReleaseError("Upload receipt target is a symlink.")
    receipt = {
        "project": PROJECT_NAME,
        "repo_id": repo_id,
        "repo_type": "dataset",
        "repo_url": HUB_DATASET_URL + repo_id,
        "uploaded_at_utc": datetime.now(timezone.utc).isoformat(),
        "commit_oid": getattr(commit_info, "oid", None),
        "manifest_sha256": hashlib.sha256(release.manifest_bytes).hexdigest(),
        "approved_paths": release.allow_patterns,
        "remote_deletions": False,
    }
    descriptor, temporary_name = tempfile.mkstemp(prefix="receipt-", suffix=".json", dir=directory)
    try:
        with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
            json.dump(receipt, stream, indent=2)
            stream.write("\n")
        os.replace(temporary_name, target)
    finally:
        if os.path.exists(temporary_name):
            os.unlink(temporary_name)
    return target


def publish_release(release: VerifiedRelease, args) -> int:
    # Dependency and token handling are deliberately absent from offline planning.
    try:
        from huggingface_hub import HfApi, get_token
    except ImportError:
        print("Upload dependency is missing.")
        authentication_guidance()
        return 2
    if not get_token():
        print("No Hugging Face authentication was found.")
        authentication_guidance()
        return 2

    # Upload a temporary snapshot so generated logs, caches and receipts cannot
    # enter the upload, and source changes cannot alter the verified content.
    with tempfile.TemporaryDirectory(prefix="orynthra-h6-upload-") as temporary:
        snapshot = Path(temporary)
        stage_release(release, snapshot)
        api = HfApi(token=True)
        repo_id = args.repo_id
        if repo_id is None:
            identity = hub_call("Account lookup", api.whoami, args.max_attempts)
            account_name = identity.get("name")
            if not isinstance(account_name, str):
                raise ReleaseError("Authenticated account lookup returned no username.")
            repo_id = validate_repo_id(account_name + "/" + PROJECT_NAME)
        print("Publishing verified research files to " + HUB_DATASET_URL + repo_id)
        hub_call(
            "Repository creation/check",
            lambda: api.create_repo(repo_id=repo_id, repo_type="dataset", private=args.private, exist_ok=True),
            args.max_attempts,
        )
        result = hub_call(
            "Upload",
            lambda: api.upload_folder(
                repo_id=repo_id,
                repo_type="dataset",
                folder_path=str(snapshot),
                allow_patterns=release.allow_patterns,
                commit_message="ORYNTHRA-H6 verified research packaging edition v1.0.2",
            ),
            args.max_attempts,
        )
    print("Upload completed: " + HUB_DATASET_URL + repo_id)
    try:
        receipt = write_receipt(release, repo_id, result)
        print("Local receipt: " + str(receipt.relative_to(release.root)))
    except Exception as error:
        # Successful publication is not reported as failed because a local receipt
        # cannot be written. Do not print an exception body or traceback.
        print("Upload succeeded; a local receipt could not be saved (" + type(error).__name__ + ").")
    return 0


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("repo_id", nargs="?", help="Full account-or-organization/repository ID.")
    parser.add_argument("--publish", action="store_true", help="Explicitly authorize network publication.")
    parser.add_argument("--private", action="store_true", help="Create a new repository privately; existing visibility is preserved.")
    parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent,
                        help="Release directory; defaults to this script's project directory.")
    parser.add_argument("--max-attempts", type=int, choices=range(1, 6), default=3,
                        help="Bounded attempts per Hub operation, including the first attempt (default: 3).")
    args = parser.parse_args(argv)
    try:
        if sys.version_info < (3, 9):
            raise ReleaseError("Python 3.9 or newer is required.")
        if args.repo_id is not None:
            args.repo_id = validate_repo_id(args.repo_id)
        release = verify_release(args.root)
        destination = args.repo_id or "<authenticated-account>/" + PROJECT_NAME
        size = sum(entry.size for entry in release.entries) + len(release.manifest_bytes)
        print("SHA-256 verification passed.")
        print("Repository container: dataset (mathematical research artifact and synthetic reference data).")
        print("Destination: " + destination)
        print("New repository visibility: " + ("private" if args.private else "public") + "; existing visibility is preserved.")
        print(f"Approved upload: {len(release.allow_patterns)} files, {size:,} bytes.")
        for relative in release.allow_patterns:
            print("  " + relative)
        print("Remote deletions: none. Unlisted local files will not be uploaded.")
        if not args.publish:
            print("OFFLINE PLAN ONLY: no dependency import, token access, or network request was made.")
            print("To publish: python tools/hf_upload.py [account-or-organization/repository] --publish")
            return 0
        print("--publish selected: publication is authorized for the verified files above.")
        return publish_release(release, args)
    except ReleaseError as error:
        print("Release check failed: " + str(error), file=sys.stderr)
        return 2
    except HubOperationError as error:
        detail = error.error_class
        if error.status_code is not None:
            detail += ", HTTP " + str(error.status_code)
        print(error.operation + " failed (" + detail + ").", file=sys.stderr)
        if error.status_code in (401, 403) or "Token" in error.error_class:
            authentication_guidance()
        else:
            print("No remote files were deleted. Retry after checking connectivity and service status.")
        return 3
    except KeyboardInterrupt:
        print("Upload interrupted. No remote files were deleted; rerun to retry.", file=sys.stderr)
        return 130
    except Exception as error:
        # HTTP exception bodies can contain request details. Never print them.
        print("Operation failed (" + type(error).__name__ + "). No credential traceback was printed.", file=sys.stderr)
        return 4


if __name__ == "__main__":
    raise SystemExit(main())