File size: 4,477 Bytes
574a22c
2ddf2d2
 
 
 
 
574a22c
 
 
 
 
 
 
 
 
2ddf2d2
 
 
574a22c
 
 
 
 
2ddf2d2
574a22c
 
2ddf2d2
574a22c
2ddf2d2
574a22c
2ddf2d2
574a22c
2ddf2d2
 
 
 
 
 
 
574a22c
 
 
 
 
 
2ddf2d2
 
 
 
 
 
 
 
 
 
 
574a22c
 
2ddf2d2
 
 
574a22c
2ddf2d2
 
574a22c
 
 
2ddf2d2
 
 
 
 
 
 
 
 
 
574a22c
 
2ddf2d2
 
574a22c
 
2ddf2d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574a22c
2ddf2d2
574a22c
2ddf2d2
574a22c
2ddf2d2
 
574a22c
2ddf2d2
 
 
574a22c
2ddf2d2
 
574a22c
 
 
 
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
#!/usr/bin/env python3
"""Upload selected workspace artifacts to a Hugging Face dataset repository.

The script is intentionally conservative: dry-run mode never imports
``huggingface_hub``, empty targets are skipped, and result targets are resolved from
``/root`` while source/code targets are resolved from ``/workspace``.
"""

from __future__ import annotations

import argparse
import getpass
import os
from pathlib import Path

WORKSPACE_ROOT = Path(os.environ.get("VSI_WORKSPACE_ROOT", "/workspace"))
RESULTS_HOST_ROOT = Path(os.environ.get("VSI_RESULTS_HOST_ROOT", "/root"))
DEFAULT_REPO = os.environ.get("VSI_BACKUP_REPO", "AntonioJun/workspace")

TARGETS = {
    "code": [
        "README.md",
        "setup.sh",
        "backup.py",
        "analysis",
        "encoder",
        "harness",
        "inference",
        "symbolic",
        "tests",
        "selective_frame_counts.csv",
    ],
    "reports": ["reports"],
    "spatial-codes": ["data/spatial codes", "bundles/spatial-codes.tar.gz"],
    "caches": ["data/caches"],
    "A": ["results/A"],
    "B": ["results/B"],
    "C": ["results/C"],
    "F": ["results/F"],
}


def _resolve_targets(target):
    if target == "all":
        return list(TARGETS)
    requested = [part.strip() for part in str(target).split(",") if part.strip()]
    unknown = [name for name in requested if name not in TARGETS]
    if unknown:
        raise ValueError(f"unknown target(s): {', '.join(unknown)}")
    return requested


def _local_path(relative):
    relative = str(relative).lstrip("/")
    root = RESULTS_HOST_ROOT if relative.startswith("results/") else WORKSPACE_ROOT
    return root / relative


def _has_files(path):
    path = Path(path)
    if path.is_file():
        return True
    if path.is_dir():
        return any(child.is_file() for child in path.rglob("*"))
    return False


def _target_root(relatives):
    roots = {
        "results" if str(rel).lstrip("/").startswith("results/") else "workspace"
        for rel in relatives
    }
    if len(roots) > 1:
        raise ValueError(
            f"target mixes incompatible workspace/results roots: {relatives}"
        )
    return RESULTS_HOST_ROOT if "results" in roots else WORKSPACE_ROOT


def _path_in_repo(relative):
    return str(relative).lstrip("/")


def backup(repo_id=DEFAULT_REPO, target="all", dry_run=False, token=None):
    selected = _resolve_targets(target)
    uploaded = []
    for name in selected:
        relatives = TARGETS[name]
        _target_root(relatives)
        existing = [(relative, _local_path(relative)) for relative in relatives]
        existing = [(relative, path) for relative, path in existing if _has_files(path)]
        if not existing:
            print(f"[{name}] skipped: no files found")
            continue
        uploaded.append(name)
        if dry_run:
            for relative, path in existing:
                print(
                    f"[{name}] would upload {path} -> {repo_id}/{_path_in_repo(relative)}"
                )
            continue
        from huggingface_hub import HfApi

        api = HfApi(token=token)
        for relative, path in existing:
            repo_path = _path_in_repo(relative)
            if path.is_dir():
                api.upload_folder(
                    folder_path=str(path),
                    repo_id=repo_id,
                    repo_type="dataset",
                    path_in_repo=repo_path,
                )
            else:
                api.upload_file(
                    path_or_fileobj=str(path),
                    repo_id=repo_id,
                    repo_type="dataset",
                    path_in_repo=repo_path,
                )
            print(f"[{name}] uploaded {path} -> {repo_id}/{repo_path}")
    return uploaded


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "target", nargs="?", default="all", help="target name, comma list, or all"
    )
    parser.add_argument("--repo", default=DEFAULT_REPO)
    parser.add_argument(
        "--token",
        default=os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN"),
    )
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args(argv)
    token = args.token
    if not args.dry_run and not token:
        token = getpass.getpass("HF token: ")
    backup(args.repo, args.target, dry_run=args.dry_run, token=token)


if __name__ == "__main__":
    main()