Buckets:
| """Smart subset builder for the LTX-2.5 curves-LoRA POC. | |
| Samples candidate clips from landed corpus shards (streaming), scores each on | |
| LUMINANCE dynamic range + MOTION dynamic range, keeps the most dynamic clips, | |
| extracts full curves for keepers, packages a private POC dataset: | |
| mp4 + curves .npz + meta .json + manifest.parquet + state.json. | |
| Env: OUT_REPO (default sassoshots/ltx-curves-poc), TARGET_PER_PREFIX (50), | |
| PREFIXES, SHARDS_PER_PREFIX (6), MAX_CANDIDATES_PER_SHARD (120). | |
| Resume: state.json in OUT_REPO. | |
| """ | |
| import io, json, os, shutil, subprocess, sys, tarfile, time | |
| import numpy as np | |
| from pathlib import Path | |
| from huggingface_hub import HfApi, hf_hub_download | |
| T0 = time.time() | |
| DEADLINE = T0 + 11.0 * 3600 | |
| REPO = "sassoshots/videoforge-t0-prototype" | |
| OUT = os.environ.get("OUT_REPO", "sassoshots/ltx-curves-poc") | |
| PREFIXES = os.environ.get("PREFIXES", "archive,archive2,vidgen,vidgen2,vggsound,nasa").split(",") | |
| TARGET = int(os.environ.get("TARGET_PER_PREFIX", "50")) | |
| CAND_MAX = int(os.environ.get("MAX_CANDIDATES_PER_SHARD", "120")) | |
| SHARDS_PER_PREFIX = int(os.environ.get("SHARDS_PER_PREFIX", "6")) | |
| TOKEN = os.environ["HF_TOKEN"] | |
| api = HfApi(token=TOKEN) | |
| import cv2 # noqa: F401 (extract module needs it) | |
| from huggingface_hub import snapshot_download # full package, not single file | |
| _snap = Path(snapshot_download("sassoshots/videoforge-controls", repo_type="dataset", token=TOKEN)) | |
| sys.path.insert(0, str(_snap)) | |
| from videoforge_controls.extract import ( # noqa: E402 | |
| extract_motion_energy, extract_luminance, extract_luminance_global, | |
| extract_saturation, extract_salience) | |
| def log(m): | |
| print(f"[{time.time()-T0:7.0f}s] {m}", flush=True) | |
| def probe(path): | |
| try: | |
| r = subprocess.run(["ffprobe", "-v", "error", "-print_format", "json", | |
| "-show_streams", "-show_format", path], capture_output=True, timeout=30) | |
| d = json.loads(r.stdout) | |
| dur = round(float(d.get("format", {}).get("duration", 0)), 2) | |
| streams = d.get("streams", []) | |
| v = next((s for s in streams if s.get("codec_type") == "video"), {}) if False else {} | |
| v = next((s for s in d.get("streams", []) if s.get("codec_type") == "video"), {}) | |
| aud = any(s.get("codec_type") == "audio" for s in d.get("streams", [])) | |
| return dur, int(v.get("width", 0)), int(v.get("height", 0)), aud, v.get("r_frame_rate", "0/1") | |
| except Exception: | |
| return 0.0, 0, 0, False, "0/1" | |
| def quick_score(path): | |
| try: | |
| r = subprocess.run(["ffmpeg", "-v", "error", "-i", path, | |
| "-vf", "select='not(mod(n,25))',scale=64:36", "-vsync", "0", | |
| "-f", "rawvideo", "-pix_fmt", "gray", "-"], | |
| capture_output=True, timeout=60) | |
| raw = r.stdout | |
| n = len(raw) // (64 * 36) | |
| if n < 3: | |
| return 0.0 | |
| frames = np.frombuffer(raw[: n * 64 * 36], np.uint8).reshape(n, 36, 64).astype(np.float32) | |
| lum_range = float(frames.mean(axis=(1, 2)).max() - frames.mean(axis=(1, 2)).min()) | |
| diff = np.abs(np.diff(frames, axis=0)).mean(axis=(1, 2)) | |
| return float(lum_range / 255.0 + (diff.max() - diff.min()) / 255.0) | |
| except Exception: | |
| return 0.0 | |
| def extract_curves(path): | |
| out = {} | |
| for name, fn in [("motion", extract_motion_energy), ("luminance", extract_luminance), | |
| ("luminance_global", extract_luminance_global), ("saturation", extract_saturation), | |
| ("salience", extract_salience)]: | |
| try: | |
| out[name] = np.asarray(fn(path).values, np.float32) | |
| except Exception as e: | |
| log(f" curve fail {name}: {e}") | |
| out[name] = np.full(64, 0.5, np.float32) | |
| return out | |
| STATE = {"done": [], "manifest": []} | |
| try: | |
| sp = hf_hub_download(OUT, "state.json", repo_type="dataset", token=TOKEN) | |
| STATE = json.load(open(sp)) | |
| log(f"resume: {len(STATE['done'])} done") | |
| except Exception: | |
| pass | |
| done = set(STATE["done"]) | |
| manifest = list(STATE.get("manifest", [])) | |
| out_dir = Path("/tmp/poc_out") | |
| out_dir.mkdir(exist_ok=True, parents=True) | |
| def flush(force=False): | |
| files = list(out_dir.iterdir()) | |
| n_files = len(files) | |
| if n_files == 0 and not force: | |
| return | |
| STATE["done"] = sorted(done) | |
| STATE["manifest"] = manifest | |
| (out_dir / "state.json").write_text(json.dumps(STATE)) | |
| if n_files > 0 and (n_files >= 40 or force): | |
| if manifest: | |
| import pandas as pd | |
| pd.DataFrame(manifest).to_parquet(out_dir / "manifest.parquet") | |
| for attempt in range(8): | |
| try: | |
| api.upload_folder(folder_path=str(out_dir), path_in_repo="", repo_id=OUT, | |
| repo_type="dataset", commit_message=f"poc subset batch {time.strftime('%H:%M')}") | |
| log(f" pushed {n_files} files") | |
| break | |
| except Exception as e: | |
| log(f" push retry {attempt+1}/8: {e}") | |
| time.sleep(min(600, 60 * (attempt + 1))) | |
| for f in files: | |
| f.unlink(missing_ok=True) | |
| total = 0 | |
| for prefix in PREFIXES: | |
| sel = 0 | |
| try: | |
| shards = sorted(f for f in api.list_repo_files(REPO, repo_type="dataset") | |
| if f.startswith(f"{prefix}/shards/") and f.endswith((".tar", ".tar.gz"))) | |
| except Exception as e: | |
| log(f"{prefix}: listing failed {e}") | |
| continue | |
| if not shards: | |
| log(f"{prefix}: no shards") | |
| continue | |
| step = max(1, len(shards) // SHARDS_PER_PREFIX) | |
| chosen = shards[::step][: SHARDS_PER_PREFIX] | |
| log(f"{prefix}: {len(shards)} shards, sampling {len(chosen)}") | |
| for shardf in chosen: | |
| if sel >= TARGET or time.time() > DEADLINE: | |
| break | |
| try: | |
| lp = hf_hub_download(REPO, shardf, repo_type="dataset", token=TOKEN) | |
| except Exception as e: | |
| log(f" shard dl fail: {e}") | |
| continue | |
| tf = tarfile.open(lp, "r:gz" if lp.endswith(".gz") else "r") | |
| scored = [] | |
| try: | |
| members = [m for m in tf if m.name.endswith(".mp4")] | |
| for m in members: | |
| if len(scored) >= CAND_MAX: | |
| break | |
| base = m.name.rsplit("/", 1)[-1].rsplit(".", 1)[0] | |
| if base in done: | |
| continue | |
| try: | |
| data = tf.extractfile(m).read() | |
| except Exception: | |
| continue | |
| tmp = Path("/tmp/poc_cand.mp4") | |
| tmp.write_bytes(data) | |
| dur, w, h, aud, fps = probe(str(tmp)) | |
| if w < 320: | |
| tmp.unlink() | |
| continue | |
| if dur > 20.0: | |
| # long-form source (archive features, NASA): cut a random 10s | |
| # training-style window instead of rejecting the clip | |
| start = (0.25 + 0.5 * ((len(base) * 7919) % 1000) / 1000.0) * max(dur - 10.5, 0.0) | |
| win = Path("/tmp/poc_win.mp4") | |
| r = subprocess.run(["ffmpeg", "-v", "error", "-ss", f"{start:.2f}", | |
| "-i", str(tmp), "-t", "10", "-c:v", "libx264", | |
| "-preset", "veryfast", "-crf", "20", "-an", "-y", str(win)], | |
| capture_output=True, timeout=120) | |
| tmp.unlink() | |
| if r.returncode != 0 or not win.exists(): | |
| continue | |
| wdur, ww, wh, _, _ = probe(str(win)) | |
| if not (4.0 <= wdur <= 20.0) or ww < 320: | |
| win.unlink() | |
| continue | |
| sc = quick_score(str(win)) | |
| data = win.read_bytes() | |
| win.unlink() | |
| elif 4.0 <= dur <= 20.0: | |
| sc = quick_score(str(tmp)) | |
| tmp.unlink() | |
| else: | |
| tmp.unlink() | |
| continue | |
| if sc > 0.02: | |
| scored.append((sc, base, data, dur, w, h, aud, fps)) | |
| finally: | |
| tf.close() | |
| scored.sort(key=lambda c: -c[0]) | |
| for sc, base, data, dur, w, h, aud, fps in scored: | |
| if sel >= TARGET: | |
| break | |
| if base in done: | |
| continue | |
| try: | |
| tmp = Path("/tmp/poc_item.mp4") | |
| tmp.write_bytes(data) | |
| curves = extract_curves(str(tmp)) | |
| meta = {"clip_id": f"{prefix}__{base}", "prefix": prefix, "source_shard": shardf, | |
| "duration_s": dur, "width": w, "height": h, "audio": aud, "fps": fps, | |
| "dyn_score": round(sc, 4)} | |
| tmp.rename(out_dir / f"{prefix}__{base}.mp4") | |
| np.savez(out_dir / f"{prefix}__{base}.npz", **curves) | |
| (out_dir / f"{prefix}__{base}.json").write_text(json.dumps(meta)) | |
| manifest.append(meta) | |
| done.add(base) | |
| sel += 1 | |
| total += 1 | |
| tmp.unlink(missing_ok=True) | |
| flush() | |
| except Exception as e: | |
| log(f" item fail {base}: {e}") | |
| try: | |
| os.remove(os.path.realpath(lp)) | |
| os.remove(lp) | |
| except Exception: | |
| pass | |
| flush(force=True) | |
| log(f"{prefix}: selected {sel}") | |
| flush(force=True) | |
| log(f"DONE selected={total} manifest_rows={len(manifest)}") | |
Xet Storage Details
- Size:
- 9.54 kB
- Xet hash:
- 50ff1f6399803ae7ebe8f5fe47defc41ddc3cfc0224e1cd2348c996c34307402
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.