File size: 17,862 Bytes
2861100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/env python3
"""Upload the verified AILITH research kit to a Hugging Face Dataset repo.

Offline check: python hf_upload.py --dry-run --folder <release folder or ZIP>
Upload:       python hf_upload.py --folder <folder> --repo <name or owner/name>
Only SHA256SUMS-listed files, plus SHA256SUMS itself, are eligible for upload.
"""
from __future__ import annotations

import argparse
from contextlib import contextmanager
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import stat
import sys
import tempfile
import time
from urllib.parse import urlsplit
import zipfile

MARKERS = ("README.md", "release_metadata.json", "SHA256SUMS")
MAX_FILES, MAX_BYTES = 20000, 1024 * 1024 * 1024
FORBIDDEN = {".git", ".venv", "venv", "__pycache__", ".cache", ".huggingface",
             ".netrc", ".hf_token", "token", "token.txt", "credentials"}


class UploadError(Exception):
    """A user-correctable uploader error."""


def safe_relative(name: str) -> str:
    """Return a literal POSIX repository path safe on Windows and POSIX."""
    if not name or "\\" in name or any(ord(c) < 32 for c in name):
        raise UploadError(f"Unsafe file path: {name!r}")
    parts = name.split("/")
    if any(p in ("", ".", "..") or p.rstrip(" .") != p for p in parts):
        raise UploadError(f"Unsafe file path: {name!r}")
    for part in parts:
        lower = part.lower()
        stem = lower.split(".")[0]
        if (any(c in part for c in ':*?[]<>|"') or lower in FORBIDDEN
                or lower == ".env" or lower.startswith(".env.")
                or stem in {"con", "prn", "aux", "nul"}
                or re.fullmatch(r"(?:com|lpt)[1-9]", stem)):
            raise UploadError(f"Reserved, sensitive, or nonliteral path: {name!r}")
    return PurePosixPath(name).as_posix()


def locate_release(base: Path) -> Path:
    """Find one unambiguous release root, at most four directories below base."""
    if all((base / marker).is_file() for marker in MARKERS):
        return base.resolve()
    matches = []
    for parent, dirs, files in os.walk(base, followlinks=False):
        root = Path(parent)
        if len(root.relative_to(base).parts) >= 4:
            dirs[:] = []
        else:
            dirs[:] = [d for d in dirs if not (root / d).is_symlink()
                       and d.lower() not in FORBIDDEN]
        if all(marker in files for marker in MARKERS):
            matches.append(root.resolve())
    if len(matches) != 1:
        raise UploadError("Select the release folder containing README.md, "
                          "release_metadata.json and SHA256SUMS "
                          f"(found {len(matches)} matching folders).")
    return matches[0]


def extract_zip(source: Path, destination: Path) -> None:
    """Extract a bounded, plain-file archive without links or path traversal."""
    with zipfile.ZipFile(source) as archive:
        entries = archive.infolist()
        if len(entries) > MAX_FILES or sum(i.file_size for i in entries) > MAX_BYTES:
            raise UploadError("ZIP exceeds the 20,000-entry / 1 GiB safety limit.")
        names = set()
        for item in entries:
            name = item.filename.rstrip("/")
            if not name:
                raise UploadError("ZIP contains an empty path.")
            name = safe_relative(name)
            folded = name.casefold()
            mode = item.external_attr >> 16
            kind = stat.S_IFMT(mode)
            if (kind not in (0, stat.S_IFREG, stat.S_IFDIR)
                    or item.flag_bits & 1 or folded in names):
                raise UploadError("ZIP contains duplicate, encrypted or special entries.")
            if item.file_size > 10 * 1024 * 1024 and item.file_size > 1000 * max(1, item.compress_size):
                raise UploadError("ZIP has an excessive compression ratio.")
            names.add(folded)
            target = destination.joinpath(*PurePosixPath(name).parts)
            if item.is_dir():
                target.mkdir(parents=True, exist_ok=True)
            else:
                target.parent.mkdir(parents=True, exist_ok=True)
                with archive.open(item) as reader, target.open("xb") as writer:
                    remaining = item.file_size
                    while remaining:
                        chunk = reader.read(min(1024 * 1024, remaining))
                        if not chunk:
                            raise UploadError("Truncated ZIP entry.")
                        writer.write(chunk)
                        remaining -= len(chunk)
                    if reader.read(1):
                        raise UploadError("ZIP entry exceeds its declared size.")


@contextmanager
def release_source(source: Path):
    if source.is_file() and zipfile.is_zipfile(source):
        with tempfile.TemporaryDirectory(prefix="ailith-release-") as temporary:
            extract_zip(source, Path(temporary))
            yield locate_release(Path(temporary))
    elif source.is_dir():
        yield locate_release(source)
    else:
        raise UploadError("The selected path is not a release folder or a valid ZIP.")


def checked_file(root: Path, relative: str) -> Path:
    path = root.joinpath(*PurePosixPath(relative).parts)
    current = root
    for part in PurePosixPath(relative).parts:
        current /= part
        if current.is_symlink():
            raise UploadError(f"Symbolic links cannot be uploaded: {relative}")
    if not path.is_file() or not path.resolve().is_relative_to(root.resolve()):
        raise UploadError(f"Missing or unsafe release file: {relative}")
    return path


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


def verify_release(root: Path) -> tuple[list[str], dict]:
    """Bind the payload to its checksum manifest; ignore every unlisted file."""
    manifest = checked_file(root, "SHA256SUMS")
    if manifest.stat().st_size > 8 * 1024 * 1024:
        raise UploadError("Checksum manifest is too large.")
    entries, folded = {}, set()
    for line in manifest.read_text(encoding="utf-8-sig").splitlines():
        if not line.strip():
            continue
        match = re.fullmatch(r"([0-9a-fA-F]{64}) [ *](.+)", line)
        if not match:
            raise UploadError("SHA256SUMS contains an invalid line.")
        expected, relative = match.groups()
        relative = safe_relative(relative)
        if relative == "SHA256SUMS" or relative.casefold() in folded:
            raise UploadError("Manifest contains a duplicate or self-checksum.")
        folded.add(relative.casefold())
        entries[relative] = expected.lower()
    if not entries or len(entries) > MAX_FILES:
        raise UploadError("Checksum manifest is empty or has too many files.")
    if not {"README.md", "release_metadata.json"}.issubset(entries):
        raise UploadError("README.md and release_metadata.json must be checksummed.")
    total = 0
    for relative, expected in entries.items():
        path = checked_file(root, relative)
        total += path.stat().st_size
        if total > MAX_BYTES:
            raise UploadError("Release exceeds the 1 GiB safety limit.")
        if digest(path) != expected:
            raise UploadError(f"Checksum mismatch: {relative}. Restore the original file.")
    metadata_file = checked_file(root, "release_metadata.json")
    if metadata_file.stat().st_size > 1024 * 1024:
        raise UploadError("Release metadata is too large.")
    metadata = json.loads(metadata_file.read_text(encoding="utf-8-sig"))
    if not isinstance(metadata, dict):
        raise UploadError("Release metadata must be a JSON object.")
    if metadata.get("suggested_repository_type", "dataset") != "dataset":
        raise UploadError("This uploader supports Hugging Face Dataset repositories.")
    return sorted(entries) + ["SHA256SUMS"], metadata


def parse_repo(value: str, username: str | None = None) -> str:
    value = value.strip()
    if "://" in value:
        parsed = urlsplit(value)
        parts = parsed.path.strip("/").split("/")
        if (parsed.scheme != "https" or parsed.netloc != "huggingface.co"
                or parsed.query or parsed.fragment or len(parts) != 3
                or parts[0] != "datasets"):
            raise UploadError("Use https://huggingface.co/datasets/OWNER/NAME.")
        value = "/".join(parts[1:])
    if "/" not in value and username:
        value = f"{username}/{value}"
    parts = value.split("/")
    if len(parts) not in (1, 2) or len(value) > 193:
        raise UploadError("Repository must be NAME or OWNER/NAME.")
    for part in parts:
        if (not re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]{0,95}", part)
                or part.endswith((".", "-", ".git")) or ".." in part or "--" in part):
            raise UploadError("Repository names use letters, digits, _, - and .; "
                              "no repeated dots/dashes or .git suffix.")
    return value


def status_code(error: Exception) -> int | None:
    return getattr(getattr(error, "response", None), "status_code", None)


def transient(error: Exception) -> bool:
    code = status_code(error)
    return (code == 429 or (code is not None and 500 <= code <= 599)
            or isinstance(error, (TimeoutError, ConnectionError))
            or any(cls.__name__ in {"TransportError", "TimeoutException", "NetworkError",
                                        "ProtocolError"} for cls in type(error).__mro__))


def retry(operation, attempts=3, sleep=time.sleep):
    for attempt in range(attempts):
        try:
            return operation()
        except Exception as error:
            if not transient(error) or attempt + 1 == attempts:
                raise
            delay = min(2 ** (attempt + 1), 8)
            print(f"Temporary Hub/network error; retrying in {delay}s...")
            sleep(delay)


def load_hub():
    try:
        from huggingface_hub import HfApi, login
    except ImportError as error:
        raise UploadError("Hugging Face Hub is not installed. Run UPLOAD_TO_HF.bat "
                          'or install: python -m pip install "huggingface_hub>=1.0,<3"') from error
    return HfApi, login


def authenticate(api_factory, login):
    api = api_factory()
    try:
        account = retry(api.whoami)
    except Exception as error:
        if status_code(error) != 401 and type(error).__name__ != "LocalTokenNotFoundError":
            raise
        print("Sign in through Hugging Face. Use an account/token with repository write access.")
        print("Authentication uses the standard Hugging Face login/cache; tokens are not upload files.")
        login(skip_if_logged_in=False)
        api = api_factory()
        account = retry(api.whoami)
    if not isinstance(account.get("name"), str):
        raise UploadError("Could not determine the signed-in Hugging Face username.")
    return api, account["name"]


def publish(root: Path, files: list[str], metadata: dict, args, api, username: str, prompt=input):
    suggested = metadata.get("suggested_repository_slug", "AILITH-Beyond-Reinforcement-Learning")
    value = args.repo
    if not value:
        if args.yes:
            raise UploadError("--yes requires an explicit --repo.")
        default = parse_repo(str(suggested), username)
        value = prompt(f"Dataset repository [{default}]: ").strip() or default
    repo = parse_repo(value, username)
    existing = None
    try:
        existing = retry(lambda: api.repo_info(repo_id=repo, repo_type="dataset"))
    except Exception as error:
        if status_code(error) != 404:
            raise
        print("Repository was not found or is inaccessible. Creation may require namespace permissions.")
    visibility = args.visibility
    if existing is not None:
        visibility = "private" if existing.private else "public"
        print(f"Existing repository: visibility stays {visibility}.")
    elif visibility is None:
        if args.yes:
            raise UploadError("For a new/unresolved repo, --yes requires --visibility public or private.")
        while visibility not in ("public", "private"):
            visibility = prompt("New repository visibility [public/private] (default: public): ").strip().lower() or "public"
    print(f"\nDestination: https://huggingface.co/datasets/{repo}")
    print(f"Payload: {len(files)} verified release files. New-repository visibility: {visibility}.")
    print("Matching remote paths will be updated; no remote files will be deleted.")
    print("If the repository already exists, its current visibility is preserved.")
    if not args.yes and prompt("Upload this release now? [y/N]: ").strip().lower() not in ("y", "yes"):
        print("Cancelled. No repository or remote files were changed.")
        return None
    # Verify a temporary snapshot before any repository creation or upload.
    with tempfile.TemporaryDirectory(prefix="ailith-upload-") as temporary:
        staged = Path(temporary)
        for relative in files:
            source = checked_file(root, relative)
            destination = staged.joinpath(*PurePosixPath(relative).parts)
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(source, destination)
        current, _ = verify_release(staged)
        if current != files:
            raise UploadError("Release changed while preparing upload; start again.")
        if existing is None:
            retry(lambda: api.create_repo(repo_id=repo, repo_type="dataset", exist_ok=True,
                                          private=visibility == "private"))
            # A hidden/existing repository may have won the create race.
            existing = retry(lambda: api.repo_info(repo_id=repo, repo_type="dataset"))
            actual_visibility = "private" if existing.private else "public"
            if actual_visibility != visibility:
                raise UploadError(f"Repository is actually {actual_visibility}; you selected {visibility}. "
                                  "No files uploaded and visibility was not changed. "
                                  "Re-run to review the existing destination.")
            print(f"Repository visibility: {actual_visibility}")
        result = retry(lambda: api.upload_folder(
            repo_id=repo, repo_type="dataset", folder_path=str(staged),
            path_in_repo="", allow_patterns=files,
            commit_message=f"Upload AILITH research release {metadata.get('research_version', '0.5.0')}"))
    print(f"\nUpload complete: https://huggingface.co/datasets/{repo}")
    commit = getattr(result, "commit_url", None)
    if commit:
        print(f"Commit: {commit}")
    return result


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--folder", type=Path, help="Release folder or outer release ZIP")
    parser.add_argument("--repo", help="NAME, OWNER/NAME, or a Hugging Face Dataset URL")
    parser.add_argument("--visibility", choices=("public", "private"), help="Visibility only when creating a repository")
    parser.add_argument("--yes", action="store_true", help="Skip final confirmation; requires explicit repository and known visibility")
    parser.add_argument("--dry-run", action="store_true", help="Offline checksum and payload check; no Hub import, login, or network")
    args = parser.parse_args(argv)
    if sys.version_info < (3, 10):
        parser.error("Python 3.10 or newer is required.")
    try:
        if args.repo:
            parse_repo(args.repo)
        source = args.folder
        if source is None:
            try:
                source = locate_release(Path(__file__).resolve().parent)
            except UploadError:
                if not sys.stdin.isatty():
                    raise UploadError("Specify --folder with your release folder or ZIP.")
                value = input("Release folder or ZIP path (you can paste/drag it here): ").strip().strip('"')
                source = Path(value)
        with release_source(source.expanduser().resolve()) as root:
            files, metadata = verify_release(root)
            size = sum((root / f).stat().st_size for f in files)
            print(f"Verified {len(files)} files ({size / 1024 / 1024:.2f} MiB).")
            if args.dry_run:
                print("Offline dry run passed. Upload allowlist:")
                for relative in files:
                    print(f"  {relative}")
                return 0
            factory, login = load_hub()
            api, username = authenticate(factory, login)
            print(f"Signed in as: {username}")
            publish(root, files, metadata, args, api, username)
        return 0
    except KeyboardInterrupt:
        print("\nInterrupted. Re-run the uploader; completed commits remain on the Hub.")
        return 130
    except Exception as error:
        # Do not print API response bodies, authentication headers, or token values.
        if isinstance(error, (UploadError, zipfile.BadZipFile, json.JSONDecodeError, OSError)):
            print(f"ERROR: {error}", file=sys.stderr)
        else:
            code = status_code(error)
            label = f"HTTP {code}" if code is not None else type(error).__name__
            print(f"ERROR: Hugging Face operation failed ({label}).", file=sys.stderr)
            if code in (401, 403):
                print("Check your login and repository write permissions, then re-run.", file=sys.stderr)
            else:
                print("Check your connection and re-run; no remote files are deleted.", file=sys.stderr)
        return 1


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