File size: 7,827 Bytes
b373569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Auto-backup system: sync checkpoints, data, and configs to HuggingFace Hub.
Supports resume training from any new VPS.

Setup:
  1. huggingface-cli login
  2. python3 backup.py --init (tạo repos trên HF)
  3. python3 backup.py --backup (push lên HF)
  4. python3 backup.py --restore (pull về VPS mới)
"""
import argparse
import subprocess
import time
import threading
from pathlib import Path
from huggingface_hub import HfApi, create_repo, snapshot_download, upload_folder, upload_file


PROJECT_DIR = Path("/home/adminuser/chungcat")
HF_ORG = None  # Set to your HF username or org

REPOS = {
    "checkpoints": "{user}/4k-image-model-checkpoints",
    "data_meta": "{user}/4k-image-model-data",
    "scripts": "{user}/4k-image-model-scripts",
}

BACKUP_PATHS = {
    "checkpoints": [
        PROJECT_DIR / "checkpoints",
    ],
    "data_meta": [
        PROJECT_DIR / "data" / "raw" / "coyo_filtered",
        PROJECT_DIR / "configs",
    ],
    "scripts": [
        PROJECT_DIR / "scripts",
        PROJECT_DIR / "configs",
        PROJECT_DIR / "PLAN.md",
    ],
}


def get_hf_user():
    api = HfApi()
    info = api.whoami()
    return info["name"]


def init_repos(user):
    """Create HF repos if they don't exist."""
    api = HfApi()
    for key, repo_template in REPOS.items():
        repo_id = repo_template.format(user=user)
        try:
            create_repo(repo_id, repo_type="model" if key == "checkpoints" else "dataset", exist_ok=True)
            print(f"  Repo ready: {repo_id}")
        except Exception as e:
            print(f"  Error creating {repo_id}: {e}")


def backup_checkpoints(user):
    """Upload latest checkpoint to HF."""
    api = HfApi()
    repo_id = REPOS["checkpoints"].format(user=user)
    ckpt_dir = PROJECT_DIR / "checkpoints"

    if not ckpt_dir.exists():
        print("  No checkpoints to backup")
        return

    # Find all checkpoint dirs
    for model_dir in ckpt_dir.iterdir():
        if not model_dir.is_dir():
            continue

        # Upload latest checkpoint only (save bandwidth)
        checkpoints = sorted(model_dir.glob("checkpoint-*"), key=lambda p: int(p.name.split("-")[1]) if p.name.split("-")[1].isdigit() else 0)
        final = model_dir / "final"

        to_upload = None
        if final.exists():
            to_upload = final
        elif checkpoints:
            to_upload = checkpoints[-1]

        if to_upload:
            path_in_repo = f"{model_dir.name}/{to_upload.name}"
            print(f"  Uploading {to_upload}{repo_id}/{path_in_repo}")
            upload_folder(
                folder_path=str(to_upload),
                repo_id=repo_id,
                path_in_repo=path_in_repo,
                repo_type="model",
            )


def backup_data_meta(user):
    """Upload filtered parquets and configs."""
    api = HfApi()
    repo_id = REPOS["data_meta"].format(user=user)

    for path in BACKUP_PATHS["data_meta"]:
        if not path.exists():
            continue
        rel_path = path.relative_to(PROJECT_DIR)
        print(f"  Uploading {rel_path}{repo_id}")
        upload_folder(
            folder_path=str(path),
            repo_id=repo_id,
            path_in_repo=str(rel_path),
            repo_type="dataset",
        )


def backup_scripts(user):
    """Upload all scripts and configs."""
    api = HfApi()
    repo_id = REPOS["scripts"].format(user=user)

    for path in BACKUP_PATHS["scripts"]:
        if not path.exists():
            continue
        rel_path = path.relative_to(PROJECT_DIR)
        if path.is_file():
            print(f"  Uploading {rel_path}")
            upload_file(
                path_or_fileobj=str(path),
                repo_id=repo_id,
                path_in_repo=str(rel_path),
                repo_type="dataset",
            )
        else:
            print(f"  Uploading {rel_path}/")
            upload_folder(
                folder_path=str(path),
                repo_id=repo_id,
                path_in_repo=str(rel_path),
                repo_type="dataset",
            )


def backup_all(user):
    """Full backup."""
    print("\n=== Backing up scripts ===")
    backup_scripts(user)
    print("\n=== Backing up data metadata ===")
    backup_data_meta(user)
    print("\n=== Backing up checkpoints ===")
    backup_checkpoints(user)
    print("\n=== Backup complete! ===")


def restore(user):
    """Restore everything from HF to a new VPS."""
    print("\n=== Restoring from HuggingFace ===")

    # Restore scripts
    repo_id = REPOS["scripts"].format(user=user)
    print(f"\n  Restoring scripts from {repo_id}...")
    try:
        snapshot_download(
            repo_id=repo_id,
            repo_type="dataset",
            local_dir=str(PROJECT_DIR),
        )
    except Exception as e:
        print(f"  Warning: {e}")

    # Restore data metadata
    repo_id = REPOS["data_meta"].format(user=user)
    print(f"\n  Restoring data metadata from {repo_id}...")
    try:
        snapshot_download(
            repo_id=repo_id,
            repo_type="dataset",
            local_dir=str(PROJECT_DIR),
        )
    except Exception as e:
        print(f"  Warning: {e}")

    # Restore checkpoints
    repo_id = REPOS["checkpoints"].format(user=user)
    print(f"\n  Restoring checkpoints from {repo_id}...")
    try:
        snapshot_download(
            repo_id=repo_id,
            repo_type="model",
            local_dir=str(PROJECT_DIR / "checkpoints"),
        )
    except Exception as e:
        print(f"  Warning: {e}")

    print("\n=== Restore complete! ===")


class AutoBackup:
    """Background thread that backs up every N minutes."""

    def __init__(self, user, interval_minutes=30):
        self.user = user
        self.interval = interval_minutes * 60
        self.running = False
        self.thread = None

    def start(self):
        self.running = True
        self.thread = threading.Thread(target=self._loop, daemon=True)
        self.thread.start()
        print(f"Auto-backup started (every {self.interval // 60} minutes)")

    def stop(self):
        self.running = False
        if self.thread:
            self.thread.join()

    def _loop(self):
        while self.running:
            time.sleep(self.interval)
            if not self.running:
                break
            try:
                print(f"\n[Auto-backup] Starting backup at {time.strftime('%H:%M:%S')}...")
                backup_all(self.user)
                print(f"[Auto-backup] Done at {time.strftime('%H:%M:%S')}")
            except Exception as e:
                print(f"[Auto-backup] Error: {e}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Backup/restore to HuggingFace Hub")
    parser.add_argument("--init", action="store_true", help="Create HF repos")
    parser.add_argument("--backup", action="store_true", help="Backup to HF")
    parser.add_argument("--restore", action="store_true", help="Restore from HF")
    parser.add_argument("--auto", action="store_true", help="Start auto-backup daemon")
    parser.add_argument("--interval", type=int, default=30, help="Auto-backup interval (minutes)")
    parser.add_argument("--user", default=None, help="HF username (auto-detected if logged in)")
    args = parser.parse_args()

    user = args.user or get_hf_user()
    print(f"HuggingFace user: {user}")

    if args.init:
        print("\nInitializing repos...")
        init_repos(user)
    elif args.backup:
        backup_all(user)
    elif args.restore:
        restore(user)
    elif args.auto:
        ab = AutoBackup(user, args.interval)
        ab.start()
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            ab.stop()
    else:
        print("Specify --init, --backup, --restore, or --auto")