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
 
8bdd018
 
 
 
 
 
bd37cca
 
 
 
 
 
 
 
 
 
 
 
 
 
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/env python
"""
Bootstrap this project into your own Hugging Face Space and/or Endpoint repo.

Examples:
  python scripts/hf_clone.py space --repo-id your-name/ace-step-lora-studio
  python scripts/hf_clone.py endpoint --repo-id your-name/ace-step-endpoint
  python scripts/hf_clone.py af3-endpoint --repo-id your-name/af3-caption-endpoint
  python scripts/hf_clone.py af3-nvidia-endpoint --repo-id your-name/af3-nvidia-endpoint
  python scripts/hf_clone.py all --space-repo-id your-name/ace-step-lora-studio --endpoint-repo-id your-name/ace-step-endpoint
"""

from __future__ import annotations

import argparse
import os
import shutil
import tempfile
from pathlib import Path
from typing import Iterable

from huggingface_hub import HfApi


PROJECT_ROOT = Path(__file__).resolve().parents[1]

COMMON_SKIP_DIRS = {
    ".git",
    "__pycache__",
    ".pytest_cache",
    ".mypy_cache",
    ".ruff_cache",
    ".venv",
    "venv",
    "env",
    ".idea",
    ".vscode",
    ".cache",
    ".huggingface",
    ".gradio",
    "checkpoints",
    "lora_output",
    "outputs",
    "artifacts",
    "models",
    "datasets",
    "Lora-ace-step",
}

COMMON_SKIP_FILES = {
    ".env",
}

COMMON_SKIP_PREFIXES = (
    "song_summaries_llm",
)

COMMON_SKIP_SUFFIXES = {
    ".wav",
    ".flac",
    ".mp3",
    ".ogg",
    ".opus",
    ".m4a",
    ".aac",
    ".pt",
    ".bin",
    ".safetensors",
    ".ckpt",
    ".onnx",
    ".log",
    ".pyc",
    ".pyo",
    ".pyd",
}

MAX_FILE_BYTES = 30 * 1024 * 1024  # 30MB safety cap for upload snapshot


def _should_skip_common(rel_path: Path, is_dir: bool) -> bool:
    if any(part in COMMON_SKIP_DIRS for part in rel_path.parts):
        return True
    if rel_path.name in COMMON_SKIP_FILES:
        return True
    if any(rel_path.name.startswith(prefix) for prefix in COMMON_SKIP_PREFIXES):
        return True
    if not is_dir and rel_path.suffix.lower() in COMMON_SKIP_SUFFIXES:
        return True
    return False


def _copy_file(src: Path, dst: Path) -> None:
    dst.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(src, dst)


def _stage_space_snapshot(staging_dir: Path) -> tuple[int, int, list[str]]:
    copied = 0
    bytes_total = 0
    skipped: list[str] = []

    for src in PROJECT_ROOT.rglob("*"):
        rel = src.relative_to(PROJECT_ROOT)

        if src.is_dir():
            if _should_skip_common(rel, is_dir=True):
                skipped.append(f"{rel}/")
            continue

        if _should_skip_common(rel, is_dir=False):
            skipped.append(str(rel))
            continue

        size = src.stat().st_size
        if size > MAX_FILE_BYTES:
            skipped.append(f"{rel} (>{MAX_FILE_BYTES // (1024 * 1024)}MB)")
            continue

        dst = staging_dir / rel
        _copy_file(src, dst)
        copied += 1
        bytes_total += size

    return copied, bytes_total, skipped


def _iter_endpoint_paths() -> Iterable[Path]:
    # Minimal runtime set for custom endpoint repos.
    required = [
        PROJECT_ROOT / "handler.py",
        PROJECT_ROOT / "requirements.txt",
        PROJECT_ROOT / "packages.txt",
        PROJECT_ROOT / "acestep",
    ]
    for p in required:
        if p.exists():
            yield p

    template_readme = PROJECT_ROOT / "templates" / "hf-endpoint" / "README.md"
    if template_readme.exists():
        yield template_readme


def _stage_endpoint_snapshot(staging_dir: Path) -> tuple[int, int]:
    copied = 0
    bytes_total = 0

    for src in _iter_endpoint_paths():
        if src.is_file():
            rel_dst = Path("README.md") if src.name == "README.md" and "templates" in src.parts else Path(src.name)
            dst = staging_dir / rel_dst
            _copy_file(src, dst)
            copied += 1
            bytes_total += src.stat().st_size
            continue

        if src.is_dir():
            for nested in src.rglob("*"):
                rel_nested = nested.relative_to(src)
                if nested.is_dir():
                    if _should_skip_common(Path(src.name) / rel_nested, is_dir=True):
                        continue
                    continue
                if _should_skip_common(Path(src.name) / rel_nested, is_dir=False):
                    continue
                if nested.suffix.lower() in {".wav", ".flac", ".mp3", ".ogg"}:
                    continue

                dst = staging_dir / src.name / rel_nested
                _copy_file(nested, dst)
                copied += 1
                bytes_total += nested.stat().st_size

    return copied, bytes_total


def _iter_qwen_endpoint_template_paths() -> Iterable[tuple[Path, Path]]:
    template_dir = PROJECT_ROOT / "templates" / "hf-qwen-caption-endpoint"
    mapping = {
        "handler.py": Path("handler.py"),
        "requirements.txt": Path("requirements.txt"),
        "README.md": Path("README.md"),
    }
    for src_name, dst_rel in mapping.items():
        src = template_dir / src_name
        if src.exists():
            yield src, dst_rel


def _stage_qwen_endpoint_snapshot(staging_dir: Path) -> tuple[int, int]:
    copied = 0
    bytes_total = 0
    for src, rel_dst in _iter_qwen_endpoint_template_paths():
        dst = staging_dir / rel_dst
        _copy_file(src, dst)
        copied += 1
        bytes_total += src.stat().st_size
    return copied, bytes_total


def _iter_af3_endpoint_template_paths() -> Iterable[tuple[Path, Path]]:
    template_dir = PROJECT_ROOT / "templates" / "hf-af3-caption-endpoint"
    mapping = {
        "handler.py": Path("handler.py"),
        "requirements.txt": Path("requirements.txt"),
        "README.md": Path("README.md"),
    }
    for src_name, dst_rel in mapping.items():
        src = template_dir / src_name
        if src.exists():
            yield src, dst_rel


def _stage_af3_endpoint_snapshot(staging_dir: Path) -> tuple[int, int]:
    copied = 0
    bytes_total = 0
    for src, rel_dst in _iter_af3_endpoint_template_paths():
        dst = staging_dir / rel_dst
        _copy_file(src, dst)
        copied += 1
        bytes_total += src.stat().st_size
    return copied, bytes_total


def _iter_af3_nvidia_endpoint_template_paths() -> Iterable[tuple[Path, Path]]:
    template_dir = PROJECT_ROOT / "templates" / "hf-af3-nvidia-endpoint"
    mapping = {
        "handler.py": Path("handler.py"),
        "requirements.txt": Path("requirements.txt"),
        "README.md": Path("README.md"),
    }
    for src_name, dst_rel in mapping.items():
        src = template_dir / src_name
        if src.exists():
            yield src, dst_rel


def _stage_af3_nvidia_endpoint_snapshot(staging_dir: Path) -> tuple[int, int]:
    copied = 0
    bytes_total = 0
    for src, rel_dst in _iter_af3_nvidia_endpoint_template_paths():
        dst = staging_dir / rel_dst
        _copy_file(src, dst)
        copied += 1
        bytes_total += src.stat().st_size
    return copied, bytes_total


def _resolve_token(arg_token: str) -> str | None:
    if arg_token:
        return arg_token
    env_token = os.getenv("HF_TOKEN") or os.getenv("hf_token")
    if env_token:
        return env_token

    dotenv = PROJECT_ROOT / ".env"
    if dotenv.exists():
        for raw in dotenv.read_text(encoding="utf-8").splitlines():
            line = raw.strip()
            if not line or line.startswith("#") or "=" not in line:
                continue
            k, v = line.split("=", 1)
            if k.strip() in {"HF_TOKEN", "hf_token"}:
                return v.strip().strip('"').strip("'")
    return None


def _ensure_repo(
    api: HfApi,
    repo_id: str,
    repo_type: str,
    private: bool,
    space_sdk: str | None = None,
) -> None:
    kwargs = {
        "repo_id": repo_id,
        "repo_type": repo_type,
        "private": private,
        "exist_ok": True,
    }
    if repo_type == "space" and space_sdk:
        kwargs["space_sdk"] = space_sdk
    api.create_repo(**kwargs)


def _upload_snapshot(
    api: HfApi,
    repo_id: str,
    repo_type: str,
    folder_path: Path,
    commit_message: str,
) -> None:
    api.upload_folder(
        repo_id=repo_id,
        repo_type=repo_type,
        folder_path=str(folder_path),
        commit_message=commit_message,
        delete_patterns=[],
    )


def _fmt_mb(num_bytes: int) -> str:
    return f"{num_bytes / (1024 * 1024):.2f} MB"


def clone_space(repo_id: str, private: bool, token: str | None, dry_run: bool) -> None:
    with tempfile.TemporaryDirectory(prefix="hf_space_clone_") as tmp:
        staging = Path(tmp)
        copied, bytes_total, skipped = _stage_space_snapshot(staging)
        print(f"[space] staged files: {copied}, size: {_fmt_mb(bytes_total)}")
        if skipped:
            print(f"[space] skipped entries: {len(skipped)}")
            for item in skipped[:20]:
                print(f"  - {item}")
            if len(skipped) > 20:
                print(f"  ... and {len(skipped) - 20} more")

        if dry_run:
            print("[space] dry-run complete (nothing uploaded).")
            return

        api = HfApi(token=token)
        _ensure_repo(api, repo_id=repo_id, repo_type="space", private=private, space_sdk="gradio")
        _upload_snapshot(
            api,
            repo_id=repo_id,
            repo_type="space",
            folder_path=staging,
            commit_message="Bootstrap ACE-Step LoRA Studio Space",
        )
        print(f"[space] uploaded to https://huggingface.co/spaces/{repo_id}")


def clone_endpoint(repo_id: str, private: bool, token: str | None, dry_run: bool) -> None:
    with tempfile.TemporaryDirectory(prefix="hf_endpoint_clone_") as tmp:
        staging = Path(tmp)
        copied, bytes_total = _stage_endpoint_snapshot(staging)
        print(f"[endpoint] staged files: {copied}, size: {_fmt_mb(bytes_total)}")

        if dry_run:
            print("[endpoint] dry-run complete (nothing uploaded).")
            return

        api = HfApi(token=token)
        _ensure_repo(api, repo_id=repo_id, repo_type="model", private=private)
        _upload_snapshot(
            api,
            repo_id=repo_id,
            repo_type="model",
            folder_path=staging,
            commit_message="Bootstrap ACE-Step custom endpoint repo",
        )
        print(f"[endpoint] uploaded to https://huggingface.co/{repo_id}")


def clone_qwen_endpoint(repo_id: str, private: bool, token: str | None, dry_run: bool) -> None:
    with tempfile.TemporaryDirectory(prefix="hf_qwen_endpoint_clone_") as tmp:
        staging = Path(tmp)
        copied, bytes_total = _stage_qwen_endpoint_snapshot(staging)
        print(f"[qwen-endpoint] staged files: {copied}, size: {_fmt_mb(bytes_total)}")

        if dry_run:
            print("[qwen-endpoint] dry-run complete (nothing uploaded).")
            return

        api = HfApi(token=token)
        _ensure_repo(api, repo_id=repo_id, repo_type="model", private=private)
        _upload_snapshot(
            api,
            repo_id=repo_id,
            repo_type="model",
            folder_path=staging,
            commit_message="Bootstrap Qwen2-Audio custom endpoint repo",
        )
        print(f"[qwen-endpoint] uploaded to https://huggingface.co/{repo_id}")


def clone_af3_endpoint(repo_id: str, private: bool, token: str | None, dry_run: bool) -> None:
    with tempfile.TemporaryDirectory(prefix="hf_af3_endpoint_clone_") as tmp:
        staging = Path(tmp)
        copied, bytes_total = _stage_af3_endpoint_snapshot(staging)
        print(f"[af3-endpoint] staged files: {copied}, size: {_fmt_mb(bytes_total)}")

        if dry_run:
            print("[af3-endpoint] dry-run complete (nothing uploaded).")
            return

        api = HfApi(token=token)
        _ensure_repo(api, repo_id=repo_id, repo_type="model", private=private)
        _upload_snapshot(
            api,
            repo_id=repo_id,
            repo_type="model",
            folder_path=staging,
            commit_message="Bootstrap Audio Flamingo 3 custom endpoint repo",
        )
        print(f"[af3-endpoint] uploaded to https://huggingface.co/{repo_id}")


def clone_af3_nvidia_endpoint(repo_id: str, private: bool, token: str | None, dry_run: bool) -> None:
    with tempfile.TemporaryDirectory(prefix="hf_af3_nvidia_endpoint_clone_") as tmp:
        staging = Path(tmp)
        copied, bytes_total = _stage_af3_nvidia_endpoint_snapshot(staging)
        print(f"[af3-nvidia-endpoint] staged files: {copied}, size: {_fmt_mb(bytes_total)}")

        if dry_run:
            print("[af3-nvidia-endpoint] dry-run complete (nothing uploaded).")
            return

        api = HfApi(token=token)
        _ensure_repo(api, repo_id=repo_id, repo_type="model", private=private)
        _upload_snapshot(
            api,
            repo_id=repo_id,
            repo_type="model",
            folder_path=staging,
            commit_message="Bootstrap Audio Flamingo 3 NVIDIA-stack endpoint repo",
        )
        print(f"[af3-nvidia-endpoint] uploaded to https://huggingface.co/{repo_id}")


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Clone this project into your own HF Space/Endpoint repos.")
    subparsers = parser.add_subparsers(dest="cmd", required=True)

    p_space = subparsers.add_parser("space", help="Create/update your HF Space from this project.")
    p_space.add_argument("--repo-id", required=True, help="Target space repo id, e.g. username/my-space.")
    p_space.add_argument("--private", action="store_true", help="Create repo as private.")
    p_space.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_space.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    p_endpoint = subparsers.add_parser("endpoint", help="Create/update your custom endpoint model repo.")
    p_endpoint.add_argument("--repo-id", required=True, help="Target model repo id, e.g. username/my-endpoint.")
    p_endpoint.add_argument("--private", action="store_true", help="Create repo as private.")
    p_endpoint.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_endpoint.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    p_qwen_endpoint = subparsers.add_parser("qwen-endpoint", help="Create/update Qwen2-Audio custom endpoint repo.")
    p_qwen_endpoint.add_argument("--repo-id", required=True, help="Target model repo id, e.g. username/my-qwen-endpoint.")
    p_qwen_endpoint.add_argument("--private", action="store_true", help="Create repo as private.")
    p_qwen_endpoint.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_qwen_endpoint.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    p_af3_endpoint = subparsers.add_parser("af3-endpoint", help="Create/update Audio Flamingo 3 custom endpoint repo.")
    p_af3_endpoint.add_argument("--repo-id", required=True, help="Target model repo id, e.g. username/my-af3-endpoint.")
    p_af3_endpoint.add_argument("--private", action="store_true", help="Create repo as private.")
    p_af3_endpoint.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_af3_endpoint.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    p_af3_nvidia_endpoint = subparsers.add_parser(
        "af3-nvidia-endpoint",
        help="Create/update AF3 NVIDIA-stack (llava+stage35) endpoint repo.",
    )
    p_af3_nvidia_endpoint.add_argument(
        "--repo-id",
        required=True,
        help="Target model repo id, e.g. username/my-af3-nvidia-endpoint.",
    )
    p_af3_nvidia_endpoint.add_argument("--private", action="store_true", help="Create repo as private.")
    p_af3_nvidia_endpoint.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_af3_nvidia_endpoint.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    p_all = subparsers.add_parser("all", help="Run both Space and Endpoint bootstrap.")
    p_all.add_argument("--space-repo-id", required=True, help="Target space repo id.")
    p_all.add_argument("--endpoint-repo-id", required=True, help="Target endpoint model repo id.")
    p_all.add_argument("--space-private", action="store_true", help="Create Space as private.")
    p_all.add_argument("--endpoint-private", action="store_true", help="Create endpoint repo as private.")
    p_all.add_argument("--token", type=str, default="", help="HF token (default: HF_TOKEN env var).")
    p_all.add_argument("--dry-run", action="store_true", help="Stage files only; do not upload.")

    return parser


def main() -> int:
    args = build_parser().parse_args()
    token = _resolve_token(args.token)

    if not token and not args.dry_run:
        print("HF token not found. Set HF_TOKEN or pass --token.")
        return 1

    if args.cmd == "space":
        clone_space(args.repo_id, private=bool(args.private), token=token, dry_run=bool(args.dry_run))
    elif args.cmd == "endpoint":
        clone_endpoint(args.repo_id, private=bool(args.private), token=token, dry_run=bool(args.dry_run))
    elif args.cmd == "qwen-endpoint":
        clone_qwen_endpoint(args.repo_id, private=bool(args.private), token=token, dry_run=bool(args.dry_run))
    elif args.cmd == "af3-endpoint":
        clone_af3_endpoint(args.repo_id, private=bool(args.private), token=token, dry_run=bool(args.dry_run))
    elif args.cmd == "af3-nvidia-endpoint":
        clone_af3_nvidia_endpoint(args.repo_id, private=bool(args.private), token=token, dry_run=bool(args.dry_run))
    else:
        clone_space(args.space_repo_id, private=bool(args.space_private), token=token, dry_run=bool(args.dry_run))
        clone_endpoint(
            args.endpoint_repo_id,
            private=bool(args.endpoint_private),
            token=token,
            dry_run=bool(args.dry_run),
        )

    return 0


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