Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
File size: 7,609 Bytes
5f0f535 | 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 | #!/usr/bin/env python
"""Upload Examples-tab assets (manifest, scene image, audio clips) to the FFASR bucket.
Dry-run by default: prints what *would* be uploaded. Pass ``--yes`` to upload.
Guardrail: refuses to run unless ``FFASR_BUCKET_ID`` is set **explicitly** in the
environment (so a local run can never silently write to the production bucket through
the default in ``storage.py``). ``HF_TOKEN`` must have write access to that bucket.
Typical use::
# 1. encode clips (Opus, 48 kb/s is plenty for speech)
ffmpeg -i in.wav -c:a libopus -b:a 48k out.opus
# 2. put manifest.json + clips (+ scene.png) in one folder, then preview
FFASR_BUCKET_ID=my-org/ffasr-dev-storage \\
python scripts/upload_example_assets.py ./examples_upload
# 3. upload for real
FFASR_BUCKET_ID=my-org/ffasr-dev-storage \\
python scripts/upload_example_assets.py ./examples_upload --yes
Only files referenced by the manifest (plus the manifest itself) are uploaded unless
``--all`` is given. Files are uploaded under ``examples/`` (``--prefix`` to override,
also honours ``FFASR_EXAMPLES_BUCKET_PREFIX``).
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
MANIFEST_NAME = "manifest.json"
AUDIO_EXTENSIONS = (".opus", ".mp3", ".wav")
ALLOWED_SUFFIXES = AUDIO_EXTENSIONS + (".flac", ".ogg", ".m4a", ".png", ".jpg", ".jpeg", ".webp", ".json")
PROD_BUCKET = "treble-technologies/FFASR_Leaderboard-storage"
def _die(msg: str, code: int = 2) -> "None":
print(f"error: {msg}", file=sys.stderr)
sys.exit(code)
def _prefix(raw: str) -> str:
raw = (raw or "examples/").strip()
return raw if raw.endswith("/") else f"{raw}/"
def _manifest_files(folder: Path, manifest: dict) -> tuple[list[Path], list[str]]:
"""Local files referenced by the manifest, plus names that are missing locally."""
wanted: list[Path] = []
missing: list[str] = []
scene = str(manifest.get("scene_image") or "scene.png")
if (folder / scene).is_file():
wanted.append(folder / scene)
else:
missing.append(scene)
for clip in manifest.get("clips", []) or []:
file = str((clip or {}).get("file") or "").strip()
if not file:
continue
if Path(file).suffix:
candidates = [folder / file]
else:
candidates = [folder / f"{file}{ext}" for ext in AUDIO_EXTENSIONS]
found = [c for c in candidates if c.is_file()]
if found:
wanted.extend(found)
else:
missing.append(file)
return wanted, missing
def _validate_manifest(manifest: dict) -> list[str]:
problems: list[str] = []
if not isinstance(manifest, dict):
return ["manifest root must be an object"]
clips = manifest.get("clips")
if not isinstance(clips, list) or not clips:
problems.append("manifest.clips must be a non-empty list")
return problems
for i, c in enumerate(clips):
if not isinstance(c, dict):
problems.append(f"clips[{i}] is not an object")
continue
for key in ("condition", "file"):
if not str(c.get(key) or "").strip():
problems.append(f"clips[{i}].{key} is required")
t = c.get("transcripts")
if t is not None and not isinstance(t, dict):
problems.append(f"clips[{i}].transcripts must be an object (model id -> text)")
try:
from examples_renderer import CONDITIONS
for i, c in enumerate(clips):
cond = str((c or {}).get("condition") or "")
if cond and cond not in CONDITIONS:
problems.append(f"clips[{i}].condition {cond!r} is not one of {', '.join(CONDITIONS)}")
except Exception:
pass
return problems
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("folder", type=Path, help="Local folder with manifest.json and the asset files")
ap.add_argument("--yes", action="store_true", help="Actually upload (default is a dry run)")
ap.add_argument("--all", action="store_true", help="Upload every supported file in the folder, not only manifest-referenced ones")
ap.add_argument("--prefix", default=os.environ.get("FFASR_EXAMPLES_BUCKET_PREFIX") or "examples/", help="Bucket prefix (default: examples/)")
ap.add_argument("--allow-prod", action="store_true", help="Allow uploading to the production bucket id")
args = ap.parse_args(argv)
bucket = os.environ.get("FFASR_BUCKET_ID", "").strip()
if not bucket:
_die(
"FFASR_BUCKET_ID is not set. This script refuses to fall back to the default "
"(production) bucket. Export FFASR_BUCKET_ID=<org>/<dataset-repo> explicitly."
)
if bucket == PROD_BUCKET and not args.allow_prod:
_die(
f"FFASR_BUCKET_ID points at the production bucket ({PROD_BUCKET}). "
"Re-run with --allow-prod if you really mean it."
)
folder: Path = args.folder.expanduser().resolve()
if not folder.is_dir():
_die(f"{folder} is not a directory")
manifest_file = folder / MANIFEST_NAME
manifest: dict | None = None
if manifest_file.is_file():
try:
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
_die(f"{manifest_file} is not valid JSON: {exc}")
problems = _validate_manifest(manifest)
if problems:
_die("manifest problems:\n - " + "\n - ".join(problems))
elif not args.all:
_die(f"no {MANIFEST_NAME} in {folder} (pass --all to upload raw files without a manifest)")
files: list[Path] = []
if manifest is not None:
files.append(manifest_file)
wanted, missing = _manifest_files(folder, manifest)
files.extend(wanted)
if missing:
print("warning: manifest references files not present locally (skipped):")
for m in missing:
print(f" - {m}")
if args.all:
for p in sorted(folder.iterdir()):
if p.is_file() and p.suffix.lower() in ALLOWED_SUFFIXES and p not in files:
files.append(p)
if not files:
_die("nothing to upload")
prefix = _prefix(args.prefix)
plan = [(p, f"{prefix}{p.name}") for p in files]
total = sum(p.stat().st_size for p, _ in plan)
mode = "UPLOAD" if args.yes else "DRY RUN"
print(f"[{mode}] bucket={bucket} prefix={prefix} files={len(plan)} total={total/1024:.1f} KiB")
for p, dest in plan:
print(f" {p.name:45s} -> {dest} ({p.stat().st_size/1024:.1f} KiB)")
for p, _ in plan:
if p.suffix.lower() == ".wav":
print(f"hint: {p.name} is WAV; consider `ffmpeg -i {p.name} -c:a libopus -b:a 48k {p.stem}.opus`")
if not args.yes:
print("\nDry run only. Re-run with --yes to upload.")
return 0
from storage import HF_BUCKET_ID, HF_TOKEN, upload_to_bucket
if HF_BUCKET_ID != bucket:
_die(f"storage.HF_BUCKET_ID ({HF_BUCKET_ID}) != FFASR_BUCKET_ID ({bucket}); aborting")
if not HF_TOKEN:
_die("HF_TOKEN is not set (needs write access to the bucket)")
upload_to_bucket(bucket, add=[(p, dest) for p, dest in plan], token=HF_TOKEN)
print(f"Uploaded {len(plan)} file(s) to {bucket}/{prefix}")
return 0
if __name__ == "__main__":
sys.exit(main())
|