Sen Fang commited on
Commit ·
bc864be
1
Parent(s): 1279c9c
Harden runtime state and exclude uploaded videos
Browse filesFiles changed (20)
- reproduce_independently.sh+4
- reproduce_independently_slurm.sh+177-70
- scripts/pipeline01_download_video_fix_caption.py+53-45
- scripts/pipeline02_extract_dwpose_from_video.py+28-9
- scripts/pipeline03_upload_to_huggingface.py+286-102
- scripts/runtime_status.py+155-18
- scripts/sync_processed_csv_from_runtime.py+13-2
- slurm/orchestrator_autorestart.slurm+39-8
- slurm/process_download_array.slurm+8
- slurm/process_dwpose_array.slurm+107-49
- slurm/process_upload_parallel_array.slurmAdded+99
- slurm/run_reproduce_independently_slurm.slurm+2-2
- slurm/submit_download_slurm.sh+50-14
- slurm/submit_dwpose_slurm.sh+223-58
- slurm/submit_upload_parallel_drain.shAdded+87
- slurm/submit_upload_parallel_slurm.shAdded+95
- slurm/watch_submit_dwpose.slurm+2-2
- utils/dataset_pool.pyAdded+74
- utils/raw_video_pool.pyAdded+164
- utils/stats_npz.py+133-3
293 unmodified lines294295296297298299300301302303304305306293 unmodified lineslocal require_target="${1:-0}"local cmd=(python "$PIPELINE03"--dataset-dir "$DATASET_DIR"--raw-video-dir "$RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--archive-dir "$ARCHIVE_DIR"--progress-path "$PROGRESS_JSON"--stats-npz "$STATS_NPZ"--repo-id "$REPO_ID"--target-bytes "$TARGET_BYTES"--target-folders "$TARGET_FOLDERS")293 unmodified lines294295296297298299300301302303304305306307308309310293 unmodified lineslocal require_target="${1:-0}"local cmd=(python "$PIPELINE03"--dataset-dir "$DATASET_DIR"--scratch-dataset-dir "$SCRATCH_DATASET_DIR"--raw-video-dir "$RAW_VIDEO_DIR"--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--archive-dir "$ARCHIVE_DIR"--progress-path "$PROGRESS_JSON"--stats-npz "$STATS_NPZ"--status-journal-path "$RUNTIME_ROOT/upload_status_journal.jsonl"--repo-id "$REPO_ID"--repo-revision "$REPO_REVISION"--target-bytes "$TARGET_BYTES"--target-folders "$TARGET_FOLDERS")
12 unmodified lines13141516171819202122232411 unmodified lines363738394041424344454647482 unmodified lines515253545556579 unmodified lines6768697071727335 unmodified lines1091101111121131146 unmodified lines121122123124125126138 unmodified lines26526626726826927014 unmodified lines28528628728828929062 unmodified lines3533543553563573583593603613623633643653663673683693708 unmodified lines37938038138238338438516 unmodified lines40240340440540640740847 unmodified lines45645745845946046146246346446546660 unmodified lines52752852953053153215 unmodified lines5485495505515525535545555562 unmodified lines55956056156256356456556656756856957057111 unmodified lines58358458558658758858959059159259359459559659759859960018 unmodified lines619620621622623624625626627628629630631174 unmodified lines8068078088098108118124 unmodified lines81781881982082182282340 unmodified lines86486586686786886987087187287387487587687787887988088188288388488588688788888922 unmodified lines9129139149159169175 unmodified lines9239249259269279289293 unmodified lines9339349359369379381 unmodified line9409419429439449457 unmodified lines9539549559569579584 unmodified lines96396496596696796896997020 unmodified lines99199299399499599611 unmodified lines1008100910101011101210131014101557 unmodified lines10731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112320 unmodified lines1144114511461147114811491150137 unmodified lines12881289129012911292129312941295129612971298129912 unmodified linesfiOUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"ARCHIVE_DIR="${ARCHIVE_DIR:-$RUNTIME_ROOT/archives}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PROGRESS_JSON="${PROGRESS_JSON:-$RUNTIME_ROOT/archive_upload_progress.json}"PIPELINE01="${PIPELINE01:-$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py}"PIPELINE02="${PIPELINE02:-$ROOT_DIR/scripts/pipeline02_extract_dwpose_from_video.py}"11 unmodified linesDOWNLOAD_WORKERS="${DOWNLOAD_WORKERS:-60}"USE_SLURM_DOWNLOAD="${USE_SLURM_DOWNLOAD:-1}"PROCESS_BATCH_SIZE="${PROCESS_BATCH_SIZE:-}"MIN_PROCESS_START_BACKLOG="${MIN_PROCESS_START_BACKLOG:-4}"PROCESS_PENDING_TIMEOUT_SECONDS="${PROCESS_PENDING_TIMEOUT_SECONDS:-1800}"RAW_BACKLOG_LIMIT="${RAW_BACKLOG_LIMIT:-180}"MAX_RAW_VIDEO_BYTES="${MAX_RAW_VIDEO_BYTES:-0}"MAX_ITERATIONS="${MAX_ITERATIONS:-0}"IDLE_SLEEP_SECONDS="${IDLE_SLEEP_SECONDS:-5}"REPO_ID="${REPO_ID:-SignerX/SignVerse-2M}"COOKIES_FILE="${COOKIES_FILE:-$ROOT_DIR/www.youtube.com_cookies (2).txt}"COOKIES_FROM_BROWSER="${COOKIES_FROM_BROWSER:-}"EXTRACTOR_ARGS="${EXTRACTOR_ARGS:-}"2 unmodified linesGPU_PARTITIONS="gpu,gpu-redhat,cgpu"GPU_ACCOUNT="${GPU_ACCOUNT:-}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-180}"DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv.lock}"DOWNLOAD_PARTITIONS="${DOWNLOAD_PARTITIONS:-main}"9 unmodified linesDOWNLOAD_PARTIAL_TIMEOUT_SECONDS="${DOWNLOAD_PARTIAL_TIMEOUT_SECONDS:-1800}"ORCHESTRATOR_PARTITION="${ORCHESTRATOR_PARTITION:-main}"ORCHESTRATOR_ACCOUNT="${ORCHESTRATOR_ACCOUNT:-}"ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-24:00:00}"ORCHESTRATOR_CPUS_PER_TASK="${ORCHESTRATOR_CPUS_PER_TASK:-4}"ORCHESTRATOR_MEM="${ORCHESTRATOR_MEM:-8G}"RUN_LOCAL="${RUN_LOCAL:-0}"35 unmodified lines--target-folders N--download-batch-size N--process-batch-size N--use-slurm-download {0,1}--download-partitions P1[,P2,...]--download-account NAME6 unmodified lines--max-iterations N--idle-sleep-seconds N--repo-id REPO--cookies FILE--cookies-from-browser BROWSER--extractor-args VALUE138 unmodified linesPROCESS_BATCH_SIZE="$2"shift 2;;--raw-backlog-limit)RAW_BACKLOG_LIMIT="$2"shift 214 unmodified linesREPO_ID="$2"shift 2;;--cookies)COOKIES_FILE="$2"shift 262 unmodified linesecho "Missing orchestration wrapper: $wrapper" >&2exit 1fiexport_args="ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,SOURCE_METADATA_CSV=$SOURCE_METADATA_CSV,OUTPUT_METADATA_CSV=$OUTPUT_METADATA_CSV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,RAW_CAPTION_DIR=$RAW_CAPTION_DIR,RAW_METADATA_DIR=$RAW_METADATA_DIR,DATASET_DIR=$DATASET_DIR,ARCHIVE_DIR=$ARCHIVE_DIR,STATS_NPZ=$STATS_NPZ,PROGRESS_JSON=$PROGRESS_JSON,STAGE=$STAGE,LIMIT=$LIMIT,FPS=$FPS,WORKERS=$WORKERS,TARGET_BYTES=$TARGET_BYTES,DOWNLOAD_BATCH_SIZE=$DOWNLOAD_BATCH_SIZE,DOWNLOAD_WORKERS=$DOWNLOAD_WORKERS,USE_SLURM_DOWNLOAD=$USE_SLURM_DOWNLOAD,SLURM_DOWNLOAD_SUBMIT_SCRIPT=$SLURM_DOWNLOAD_SUBMIT_SCRIPT,DOWNLOAD_PARTITIONS=$DOWNLOAD_PARTITIONS,DOWNLOAD_ACCOUNT=$DOWNLOAD_ACCOUNT,DOWNLOAD_TIME=$DOWNLOAD_TIME,DOWNLOAD_CPUS_PER_TASK=$DOWNLOAD_CPUS_PER_TASK,DOWNLOAD_MEM=$DOWNLOAD_MEM,DOWNLOAD_ARRAY_PARALLEL=$DOWNLOAD_ARRAY_PARALLEL,DOWNLOAD_MAX_ACTIVE=$DOWNLOAD_MAX_ACTIVE,DOWNLOAD_START_STAGGER_MIN=$DOWNLOAD_START_STAGGER_MIN,DOWNLOAD_START_STAGGER_MAX=$DOWNLOAD_START_STAGGER_MAX,PROCESS_BATCH_SIZE=$PROCESS_BATCH_SIZE,DOWNLOAD_CLAIM_DIR=$DOWNLOAD_CLAIM_DIR,DOWNLOAD_CSV_LOCK_PATH=$DOWNLOAD_CSV_LOCK_PATH,MIN_PROCESS_START_BACKLOG=$MIN_PROCESS_START_BACKLOG,RAW_BACKLOG_LIMIT=$RAW_BACKLOG_LIMIT,MAX_RAW_VIDEO_BYTES=$MAX_RAW_VIDEO_BYTES,MAX_ITERATIONS=$MAX_ITERATIONS,IDLE_SLEEP_SECONDS=$IDLE_SLEEP_SECONDS,REPO_ID=$REPO_ID,COOKIES_FILE=$COOKIES_FILE,COOKIES_FROM_BROWSER=$COOKIES_FROM_BROWSER,EXTRACTOR_ARGS=$EXTRACTOR_ARGS,GPU_PARTITIONS=$GPU_PARTITIONS,GPU_ACCOUNT=$GPU_ACCOUNT,ARRAY_PARALLEL=$ARRAY_PARALLEL,MAX_BACKLOG_VIDEOS=$MAX_BACKLOG_VIDEOS,FORCE_METADATA=$FORCE_METADATA,FORCE_SUBTITLES=$FORCE_SUBTITLES,FORCE_DOWNLOAD=$FORCE_DOWNLOAD,FORCE_PROCESS=$FORCE_PROCESS,SKIP_VIDEO_DOWNLOAD=$SKIP_VIDEO_DOWNLOAD,SKIP_SUBTITLES=$SKIP_SUBTITLES,DRY_RUN_UPLOAD=$DRY_RUN_UPLOAD,RUN_LOCAL=1"if [[ ${#VIDEO_IDS[@]} -gt 0 ]]; thenexport VIDEO_IDS_JOINEDVIDEO_IDS_JOINED="${VIDEO_IDS[*]}"export_args+=",VIDEO_IDS_JOINED=$VIDEO_IDS_JOINED"ficmd=(sbatch--partition "$ORCHESTRATOR_PARTITION"--time "$ORCHESTRATOR_TIME"--cpus-per-task "$ORCHESTRATOR_CPUS_PER_TASK"--mem "$ORCHESTRATOR_MEM"--export "$export_args")if [[ -n "$ORCHESTRATOR_ACCOUNT" ]]; thencmd+=(--account "$ORCHESTRATOR_ACCOUNT")8 unmodified linesIFS=' ' read -r -a VIDEO_IDS <<< "$VIDEO_IDS_JOINED"fimkdir -p "$RAW_VIDEO_DIR" "$RAW_CAPTION_DIR" "$RAW_METADATA_DIR" "$DATASET_DIR"if [[ ! -x "$SLURM_PROCESS_SUBMIT_SCRIPT" ]]; thenecho "Missing Slurm submit script: $SLURM_PROCESS_SUBMIT_SCRIPT" >&2exit 116 unmodified lines--time "$DOWNLOAD_TIME"--cpus-per-task "$DOWNLOAD_CPUS_PER_TASK"--mem "$DOWNLOAD_MEM"--max-backlog-videos "$RAW_BACKLOG_LIMIT"--workers "$DOWNLOAD_WORKERS"--max-active-downloads "$DOWNLOAD_MAX_ACTIVE"--claim-dir "$DOWNLOAD_CLAIM_DIR"47 unmodified lineslocal cmd=(python "$PIPELINE01"--source-metadata-csv "$SOURCE_METADATA_CSV"--output-metadata-csv "$OUTPUT_METADATA_CSV"--raw-video-dir "$RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--dataset-dir "$DATASET_DIR"--stats-npz "$STATS_NPZ"--claim-dir "$DOWNLOAD_CLAIM_DIR"--csv-lock-path "$DOWNLOAD_CSV_LOCK_PATH")60 unmodified linesif [[ -n "$ARRAY_PARALLEL" ]]; thencmd+=(--array-parallel "$ARRAY_PARALLEL")fiif [[ -n "$GPU_ACCOUNT" ]]; thencmd+=(--account "$GPU_ACCOUNT")fi15 unmodified lines--source-metadata-csv "$SOURCE_METADATA_CSV" \--output-metadata-csv "$OUTPUT_METADATA_CSV" \--raw-video-dir "$RAW_VIDEO_DIR" \--raw-caption-dir "$RAW_CAPTION_DIR" \--raw-metadata-dir "$RAW_METADATA_DIR" \--dataset-dir "$DATASET_DIR" \--progress-path "$PROGRESS_JSON" \--status-journal-path "$RUNTIME_ROOT/upload_status_journal.jsonl"}2 unmodified lineslocal require_target="${1:-0}"local cmd=(python "$PIPELINE03"--dataset-dir "$DATASET_DIR"--raw-video-dir "$RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--archive-dir "$ARCHIVE_DIR"--progress-path "$PROGRESS_JSON"--stats-npz "$STATS_NPZ"--repo-id "$REPO_ID"--target-bytes "$TARGET_BYTES"--target-folders "$TARGET_FOLDERS")11 unmodified linesprune_processed_raw_videos() {python - <<PYfrom pathlib import Pathraw_dir = Path("$RAW_VIDEO_DIR")dataset_dir = Path("$DATASET_DIR")video_extensions = {".mp4", ".mkv", ".webm", ".mov"}removed = 0if raw_dir.exists():for video_path in raw_dir.iterdir():if not video_path.is_file() or video_path.suffix.lower() not in video_extensions:continuevideo_id = video_path.stemif (dataset_dir / video_id / "npz" / ".complete").exists():video_path.unlink(missing_ok=True)removed += 1print(removed)PY}18 unmodified linescount_pending_process() {python - <<PYfrom pathlib import Pathraw_dir = Path("$RAW_VIDEO_DIR")video_extensions = {".mp4", ".mkv", ".webm", ".mov"}pending = 0if raw_dir.exists():for video_path in raw_dir.iterdir():if video_path.is_file() and video_path.suffix.lower() in video_extensions:pending += 1print(pending)PY}174 unmodified linesimport timefrom pathlib import Pathclaim_dir = Path("$DOWNLOAD_CLAIM_DIR")raw_dir = Path("$RAW_VIDEO_DIR")timeout = int("$DOWNLOAD_PARTIAL_TIMEOUT_SECONDS")now = time.time()active_ids = set()4 unmodified linesexcept Exception:passremoved = 0if raw_dir.exists():for path in raw_dir.iterdir():if not path.is_file():continue40 unmodified linescount_active_process_claims() {python - <<PYimport subprocessfrom datetime import datetime, timedeltafrom pathlib import Pathfrom datetime import datetime, timedeltaclaim_dir = Path("$STATE_ROOT/slurm/state/claims")claim_dir.mkdir(parents=True, exist_ok=True)timeout_seconds = int("$PROCESS_PENDING_TIMEOUT_SECONDS")now = datetime.now()job_states = {}base_states = {}try:result = subprocess.run(["squeue", "-h", "-u", "$USER", "-o", "%i|%T"], check=True, capture_output=True, text=True)for line in result.stdout.splitlines():if not line.strip() or "|" not in line:continuejob_key, state = line.split("|", 1)job_key = job_key.strip()state = state.strip().upper()job_states[job_key] = statebase_states[job_key.split("_", 1)[0]] = stateexcept Exception:job_states = {}base_states = {}22 unmodified lineselse:state = base_states.get(job_id)if not state:claim_path.unlink(missing_ok=True)continuesubmitted_at = meta.get("submitted_at", "")5 unmodified linesexcept Exception:stale_pending = Falseif stale_pending:subprocess.run(["scancel", job_id], check=False)claim_path.unlink(missing_ok=True)continuecount += 13 unmodified linescleanup_stale_process_jobs() {python - <<PYimport subprocessfrom datetime import datetime, timedeltafrom pathlib import Path1 unmodified lineclaim_dir = Path("$STATE_ROOT/slurm/state/claims")claim_dir.mkdir(parents=True, exist_ok=True)timeout_seconds = int("$PROCESS_PENDING_TIMEOUT_SECONDS")now = datetime.now()bad_reason_tokens = (7 unmodified linestimed_pending_reasons = ("Priority", "Resources", "QOS")squeue_rows = {}try:proc = subprocess.run(["squeue", "-h", "-u", "$USER", "-n", "dwpose", "-o", "%i|%T|%R"],4 unmodified linesfor line in proc.stdout.splitlines():if not line.strip() or "|" not in line:continuejob_key, state, reason = line.split("|", 2)squeue_rows[job_key.strip()] = (state.strip().upper(), reason.strip())except Exception:squeue_rows = {}20 unmodified linescontinuerow = squeue_rows.get(job_key)if not row:claim_path.unlink(missing_ok=True)removed_claims += 1continue11 unmodified linesexcept Exception:passif should_cancel:subprocess.run(["scancel", job_id], check=False)cancelled_jobs.add(job_id)claim_path.unlink(missing_ok=True)removed_claims += 157 unmodified lines}count_complete_pending_upload() {python - <<PYimport jsonfrom pathlib import Pathdataset_dir = Path("$DATASET_DIR")progress_path = Path("$PROGRESS_JSON")uploaded = set()if progress_path.exists():uploaded = set(json.loads(progress_path.read_text()).get("uploaded_folders", {}).keys())count = 0if dataset_dir.exists():for folder_path in dataset_dir.iterdir():if not folder_path.is_dir():continueif folder_path.name in uploaded:continueif (folder_path / "npz" / ".complete").exists():count += 1print(count)PY}bytes_complete_pending_upload() {python - <<PYimport jsonfrom pathlib import Pathdataset_dir = Path("$DATASET_DIR")progress_path = Path("$PROGRESS_JSON")uploaded = set()if progress_path.exists():uploaded = set(json.loads(progress_path.read_text()).get("uploaded_folders", {}).keys())total = 0if dataset_dir.exists():for folder_path in dataset_dir.iterdir():if not folder_path.is_dir():continueif folder_path.name in uploaded:continueif not (folder_path / "npz" / ".complete").exists():continuefor path in folder_path.rglob("*"):if path.is_file():try:total += path.stat().st_sizeexcept OSError:passprint(total)PY}20 unmodified lines[[ "$pending_download" =~ ^[0-9]+$ ]] || pending_download=0pending_process="$(count_pending_process 2>/dev/null || true)"[[ "$pending_process" =~ ^[0-9]+$ ]] || pending_process=0raw_video_bytes="$(dir_size_bytes "$RAW_VIDEO_DIR" 2>/dev/null || true)"[[ "$raw_video_bytes" =~ ^[0-9]+$ ]] || raw_video_bytes=0echo "[download] iteration=$iteration pending_download=$pending_download raw_backlog=$pending_process raw_video_bytes=$raw_video_bytes pruned_raw_videos=$pruned stale_download_claims=$stale_download_claims stale_download_partials=$stale_download_partials stale_process_jobs=$stale_process_jobs stale_process_claims=$stale_process_claims stale_orphan_process_jobs=$stale_orphan_process_jobs"137 unmodified lineswhile true; doiteration=$((iteration + 1))local prunedpruned="$(prune_processed_raw_videos)"local pending_download pending_process complete_pending_upload complete_pending_upload_bytespending_download="$(count_pending_downloads)"pending_process="$(count_pending_process)"complete_pending_upload="$(count_complete_pending_upload)"complete_pending_upload_bytes="$(bytes_complete_pending_upload)"echo "[upload] iteration=$iteration pending_download=$pending_download raw_backlog=$pending_process complete_pending_upload=$complete_pending_upload complete_pending_upload_bytes=$complete_pending_upload_bytes pruned_raw_videos=$pruned"if [[ "$MAX_ITERATIONS" -gt 0 && "$iteration" -gt "$MAX_ITERATIONS" ]]; then12 unmodified lines13141516171819202122232425262728293011 unmodified lines4243444546474849505152535455562 unmodified lines596061626364659 unmodified lines7576777879808135 unmodified lines1171181191201211221236 unmodified lines130131132133134135136138 unmodified lines27527627727827928028128228328414 unmodified lines29930030130230330430530630730862 unmodified lines3713723733743753763773783793803813823833843853863873883893903918 unmodified lines40040140240340440540616 unmodified lines42342442542642742842943043143247 unmodified lines48048148248348448548648748848949049149249360 unmodified lines55455555655755855956056156215 unmodified lines5785795805815825835845855865875882 unmodified lines59159259359459559659759859960060160260360460560660711 unmodified lines61962062162262362462562662762862963063163263363463563663763863964018 unmodified lines659660661662663664665666667668669670671672673674675676677678174 unmodified lines8538548558568578588594 unmodified lines86486586686786886987087187240 unmodified lines91391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695722 unmodified lines9809819829839849859869879889899909919929939949959965 unmodified lines100210031004100510061007100810093 unmodified lines10131014101510161017101810191 unmodified line10211022102310241025102610277 unmodified lines1035103610371038103910401041104210431044104510461047104810491050105110524 unmodified lines1057105810591060106110621063106410651066106710681069107020 unmodified lines10911092109310941095109610971098109911001101110211031104110511 unmodified lines11171118111911201121112211231124112557 unmodified lines118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122520 unmodified lines1246124712481249125012511252137 unmodified lines1390139113921393139413951396139713981399140014011402140314041405140612 unmodified linesfiOUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"HOME_RAW_VIDEO_LIMIT="${HOME_RAW_VIDEO_LIMIT:-180}"SCRATCH_RAW_VIDEO_LIMIT="${SCRATCH_RAW_VIDEO_LIMIT:-2800}"DEFAULT_TOTAL_RAW_VIDEO_LIMIT="$((HOME_RAW_VIDEO_LIMIT + SCRATCH_RAW_VIDEO_LIMIT))"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"ARCHIVE_DIR="${ARCHIVE_DIR:-$RUNTIME_ROOT/archives}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PROGRESS_JSON="${PROGRESS_JSON:-$RUNTIME_ROOT/archive_upload_progress.json}"RUNTIME_LOG_ROOT="${RUNTIME_LOG_ROOT:-/scratch/$USER/SignVerse-2M-runtime/slurm/logs}"PIPELINE01="${PIPELINE01:-$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py}"PIPELINE02="${PIPELINE02:-$ROOT_DIR/scripts/pipeline02_extract_dwpose_from_video.py}"11 unmodified linesDOWNLOAD_WORKERS="${DOWNLOAD_WORKERS:-60}"USE_SLURM_DOWNLOAD="${USE_SLURM_DOWNLOAD:-1}"PROCESS_BATCH_SIZE="${PROCESS_BATCH_SIZE:-}"VIDEOS_PER_JOB="${VIDEOS_PER_JOB:-5}"MIN_PROCESS_START_BACKLOG="${MIN_PROCESS_START_BACKLOG:-4}"PROCESS_PENDING_TIMEOUT_SECONDS="${PROCESS_PENDING_TIMEOUT_SECONDS:-1800}"RAW_BACKLOG_LIMIT="${RAW_BACKLOG_LIMIT:-$DEFAULT_TOTAL_RAW_VIDEO_LIMIT}"MAX_RAW_VIDEO_BYTES="${MAX_RAW_VIDEO_BYTES:-0}"MAX_ITERATIONS="${MAX_ITERATIONS:-0}"IDLE_SLEEP_SECONDS="${IDLE_SLEEP_SECONDS:-5}"REPO_ID="${REPO_ID:-SignerX/SignVerse-2M}"REPO_REVISION="${REPO_REVISION:-dev}"COOKIES_FILE="${COOKIES_FILE:-$ROOT_DIR/www.youtube.com_cookies (2).txt}"COOKIES_FROM_BROWSER="${COOKIES_FROM_BROWSER:-}"EXTRACTOR_ARGS="${EXTRACTOR_ARGS:-}"2 unmodified linesGPU_PARTITIONS="gpu,gpu-redhat,cgpu"GPU_ACCOUNT="${GPU_ACCOUNT:-}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-$DEFAULT_TOTAL_RAW_VIDEO_LIMIT}"DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv.lock}"DOWNLOAD_PARTITIONS="${DOWNLOAD_PARTITIONS:-main}"9 unmodified linesDOWNLOAD_PARTIAL_TIMEOUT_SECONDS="${DOWNLOAD_PARTIAL_TIMEOUT_SECONDS:-1800}"ORCHESTRATOR_PARTITION="${ORCHESTRATOR_PARTITION:-main}"ORCHESTRATOR_ACCOUNT="${ORCHESTRATOR_ACCOUNT:-}"ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"ORCHESTRATOR_CPUS_PER_TASK="${ORCHESTRATOR_CPUS_PER_TASK:-4}"ORCHESTRATOR_MEM="${ORCHESTRATOR_MEM:-8G}"RUN_LOCAL="${RUN_LOCAL:-0}"35 unmodified lines--target-folders N--download-batch-size N--process-batch-size N--videos-per-job N--use-slurm-download {0,1}--download-partitions P1[,P2,...]--download-account NAME6 unmodified lines--max-iterations N--idle-sleep-seconds N--repo-id REPO--repo-revision BRANCH--cookies FILE--cookies-from-browser BROWSER--extractor-args VALUE138 unmodified linesPROCESS_BATCH_SIZE="$2"shift 2;;--videos-per-job)VIDEOS_PER_JOB="$2"shift 2;;--raw-backlog-limit)RAW_BACKLOG_LIMIT="$2"shift 214 unmodified linesREPO_ID="$2"shift 2;;--repo-revision)REPO_REVISION="$2"shift 2;;--cookies)COOKIES_FILE="$2"shift 262 unmodified linesecho "Missing orchestration wrapper: $wrapper" >&2exit 1fiexport_args="ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,SOURCE_METADATA_CSV=$SOURCE_METADATA_CSV,OUTPUT_METADATA_CSV=$OUTPUT_METADATA_CSV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,SCRATCH_RAW_VIDEO_DIR=$SCRATCH_RAW_VIDEO_DIR,HOME_RAW_VIDEO_LIMIT=$HOME_RAW_VIDEO_LIMIT,SCRATCH_RAW_VIDEO_LIMIT=$SCRATCH_RAW_VIDEO_LIMIT,RAW_CAPTION_DIR=$RAW_CAPTION_DIR,RAW_METADATA_DIR=$RAW_METADATA_DIR,DATASET_DIR=$DATASET_DIR,SCRATCH_DATASET_DIR=$SCRATCH_DATASET_DIR,ARCHIVE_DIR=$ARCHIVE_DIR,STATS_NPZ=$STATS_NPZ,PROGRESS_JSON=$PROGRESS_JSON,STAGE=$STAGE,LIMIT=$LIMIT,FPS=$FPS,WORKERS=$WORKERS,TARGET_BYTES=$TARGET_BYTES,DOWNLOAD_BATCH_SIZE=$DOWNLOAD_BATCH_SIZE,DOWNLOAD_WORKERS=$DOWNLOAD_WORKERS,USE_SLURM_DOWNLOAD=$USE_SLURM_DOWNLOAD,SLURM_DOWNLOAD_SUBMIT_SCRIPT=$SLURM_DOWNLOAD_SUBMIT_SCRIPT,DOWNLOAD_PARTITIONS=$DOWNLOAD_PARTITIONS,DOWNLOAD_ACCOUNT=$DOWNLOAD_ACCOUNT,DOWNLOAD_TIME=$DOWNLOAD_TIME,DOWNLOAD_CPUS_PER_TASK=$DOWNLOAD_CPUS_PER_TASK,DOWNLOAD_MEM=$DOWNLOAD_MEM,DOWNLOAD_ARRAY_PARALLEL=$DOWNLOAD_ARRAY_PARALLEL,DOWNLOAD_MAX_ACTIVE=$DOWNLOAD_MAX_ACTIVE,DOWNLOAD_START_STAGGER_MIN=$DOWNLOAD_START_STAGGER_MIN,DOWNLOAD_START_STAGGER_MAX=$DOWNLOAD_START_STAGGER_MAX,PROCESS_BATCH_SIZE=$PROCESS_BATCH_SIZE,VIDEOS_PER_JOB=$VIDEOS_PER_JOB,DOWNLOAD_CLAIM_DIR=$DOWNLOAD_CLAIM_DIR,DOWNLOAD_CSV_LOCK_PATH=$DOWNLOAD_CSV_LOCK_PATH,MIN_PROCESS_START_BACKLOG=$MIN_PROCESS_START_BACKLOG,RAW_BACKLOG_LIMIT=$RAW_BACKLOG_LIMIT,MAX_RAW_VIDEO_BYTES=$MAX_RAW_VIDEO_BYTES,MAX_ITERATIONS=$MAX_ITERATIONS,IDLE_SLEEP_SECONDS=$IDLE_SLEEP_SECONDS,REPO_ID=$REPO_ID,COOKIES_FILE=$COOKIES_FILE,COOKIES_FROM_BROWSER=$COOKIES_FROM_BROWSER,EXTRACTOR_ARGS=$EXTRACTOR_ARGS,GPU_PARTITIONS=$GPU_PARTITIONS,GPU_ACCOUNT=$GPU_ACCOUNT,ARRAY_PARALLEL=$ARRAY_PARALLEL,MAX_BACKLOG_VIDEOS=$MAX_BACKLOG_VIDEOS,FORCE_METADATA=$FORCE_METADATA,FORCE_SUBTITLES=$FORCE_SUBTITLES,FORCE_DOWNLOAD=$FORCE_DOWNLOAD,FORCE_PROCESS=$FORCE_PROCESS,SKIP_VIDEO_DOWNLOAD=$SKIP_VIDEO_DOWNLOAD,SKIP_SUBTITLES=$SKIP_SUBTITLES,DRY_RUN_UPLOAD=$DRY_RUN_UPLOAD,RUN_LOCAL=1"if [[ ${#VIDEO_IDS[@]} -gt 0 ]]; thenexport VIDEO_IDS_JOINEDVIDEO_IDS_JOINED="${VIDEO_IDS[*]}"export_args+=",VIDEO_IDS_JOINED=$VIDEO_IDS_JOINED"fimkdir -p "$RUNTIME_LOG_ROOT"cmd=(sbatch--partition "$ORCHESTRATOR_PARTITION"--time "$ORCHESTRATOR_TIME"--cpus-per-task "$ORCHESTRATOR_CPUS_PER_TASK"--mem "$ORCHESTRATOR_MEM"--output "$RUNTIME_LOG_ROOT/sign-dwpose-orch_%j.out"--error "$RUNTIME_LOG_ROOT/sign-dwpose-orch_%j.err"--export "$export_args,RUNTIME_LOG_ROOT=$RUNTIME_LOG_ROOT")if [[ -n "$ORCHESTRATOR_ACCOUNT" ]]; thencmd+=(--account "$ORCHESTRATOR_ACCOUNT")8 unmodified linesIFS=' ' read -r -a VIDEO_IDS <<< "$VIDEO_IDS_JOINED"fimkdir -p "$RAW_VIDEO_DIR" "$SCRATCH_RAW_VIDEO_DIR" "$RAW_CAPTION_DIR" "$RAW_METADATA_DIR" "$DATASET_DIR" "$SCRATCH_DATASET_DIR"if [[ ! -x "$SLURM_PROCESS_SUBMIT_SCRIPT" ]]; thenecho "Missing Slurm submit script: $SLURM_PROCESS_SUBMIT_SCRIPT" >&2exit 116 unmodified lines--time "$DOWNLOAD_TIME"--cpus-per-task "$DOWNLOAD_CPUS_PER_TASK"--mem "$DOWNLOAD_MEM"--max-backlog-videos "$RAW_BACKLOG_LIMIT" \--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR" \--home-raw-video-limit "$HOME_RAW_VIDEO_LIMIT" \--scratch-raw-video-limit "$SCRATCH_RAW_VIDEO_LIMIT"--workers "$DOWNLOAD_WORKERS"--max-active-downloads "$DOWNLOAD_MAX_ACTIVE"--claim-dir "$DOWNLOAD_CLAIM_DIR"47 unmodified lineslocal cmd=(python "$PIPELINE01"--source-metadata-csv "$SOURCE_METADATA_CSV"--output-metadata-csv "$OUTPUT_METADATA_CSV"--raw-video-dir "$RAW_VIDEO_DIR" \--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--dataset-dir "$DATASET_DIR"--scratch-dataset-dir "$SCRATCH_DATASET_DIR"--stats-npz "$STATS_NPZ"--status-journal-path "$RUNTIME_ROOT/upload_status_journal.jsonl"--claim-dir "$DOWNLOAD_CLAIM_DIR"--csv-lock-path "$DOWNLOAD_CSV_LOCK_PATH")60 unmodified linesif [[ -n "$ARRAY_PARALLEL" ]]; thencmd+=(--array-parallel "$ARRAY_PARALLEL")fiif [[ -n "$VIDEOS_PER_JOB" ]]; thencmd+=(--videos-per-job "$VIDEOS_PER_JOB")fiif [[ -n "$GPU_ACCOUNT" ]]; thencmd+=(--account "$GPU_ACCOUNT")fi15 unmodified lines--source-metadata-csv "$SOURCE_METADATA_CSV" \--output-metadata-csv "$OUTPUT_METADATA_CSV" \--raw-video-dir "$RAW_VIDEO_DIR" \--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR" \--raw-caption-dir "$RAW_CAPTION_DIR" \--raw-metadata-dir "$RAW_METADATA_DIR" \--dataset-dir "$DATASET_DIR" \--scratch-dataset-dir "$SCRATCH_DATASET_DIR" \--progress-path "$PROGRESS_JSON" \--status-journal-path "$RUNTIME_ROOT/upload_status_journal.jsonl"}2 unmodified lineslocal require_target="${1:-0}"local cmd=(python "$PIPELINE03"--dataset-dir "$DATASET_DIR"--scratch-dataset-dir "$SCRATCH_DATASET_DIR"--raw-video-dir "$RAW_VIDEO_DIR"--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--archive-dir "$ARCHIVE_DIR"--progress-path "$PROGRESS_JSON"--stats-npz "$STATS_NPZ"--status-journal-path "$RUNTIME_ROOT/upload_status_journal.jsonl"--repo-id "$REPO_ID"--repo-revision "$REPO_REVISION"--target-bytes "$TARGET_BYTES"--target-folders "$TARGET_FOLDERS")11 unmodified linesprune_processed_raw_videos() {python - <<PYfrom pathlib import Pathraw_dirs = [Path("$RAW_VIDEO_DIR"), Path("$SCRATCH_RAW_VIDEO_DIR")]dataset_dirs = [Path("$DATASET_DIR"), Path("$SCRATCH_DATASET_DIR")]video_extensions = {".mp4", ".mkv", ".webm", ".mov"}removed = 0complete = set()for current_dataset_dir in dataset_dirs:if current_dataset_dir.exists():complete.update({p.parent.parent.name for p in current_dataset_dir.glob("*/npz/.complete")})for raw_dir in raw_dirs:if raw_dir.exists():for video_path in raw_dir.iterdir():if not video_path.is_file() or video_path.suffix.lower() not in video_extensions:continueif video_path.stem in complete:video_path.unlink(missing_ok=True)removed += 1print(removed)PY}18 unmodified linescount_pending_process() {python - <<PYfrom pathlib import Pathraw_dirs = [Path("$RAW_VIDEO_DIR"), Path("$SCRATCH_RAW_VIDEO_DIR")]video_extensions = {".mp4", ".mkv", ".webm", ".mov"}pending = 0seen = set()for raw_dir in raw_dirs:if not raw_dir.exists():continuefor video_path in raw_dir.iterdir():if not video_path.is_file() or video_path.suffix.lower() not in video_extensions:continueif video_path.stem in seen:continueseen.add(video_path.stem)pending += 1print(pending)PY}174 unmodified linesimport timefrom pathlib import Pathclaim_dir = Path("$DOWNLOAD_CLAIM_DIR")raw_dirs = [Path("$RAW_VIDEO_DIR"), Path("$SCRATCH_RAW_VIDEO_DIR")]timeout = int("$DOWNLOAD_PARTIAL_TIMEOUT_SECONDS")now = time.time()active_ids = set()4 unmodified linesexcept Exception:passremoved = 0for raw_dir in raw_dirs:if not raw_dir.exists():continuefor path in raw_dir.iterdir():if not path.is_file():continue40 unmodified linescount_active_process_claims() {python - <<PYimport reimport subprocessfrom datetime import datetime, timedeltafrom pathlib import Pathclaim_dir = Path("$STATE_ROOT/slurm/state/claims")claim_dir.mkdir(parents=True, exist_ok=True)timeout_seconds = int("$PROCESS_PENDING_TIMEOUT_SECONDS")videos_per_job = int("${VIDEOS_PER_JOB:-1}")now = datetime.now()job_states = {}base_states = {}array_re = re.compile(r"^(?P<base>\d+)_\[(?P<start>\d+)-(?P<end>\d+)(?:%(?P<limit>\d+))?\]$")def expand_job_token(job_token: str):job_token = job_token.strip()match = array_re.match(job_token)if not match:return [job_token]base = match.group("base")start = int(match.group("start"))end = int(match.group("end"))return [f"{base}_{index}" for index in range(start, end + 1)]try:result = subprocess.run(["squeue", "-h", "-u", "$USER", "-o", "%i|%T"], check=True, capture_output=True, text=True)for line in result.stdout.splitlines():if not line.strip() or "|" not in line:continuejob_token, state = line.split("|", 1)state = state.strip().upper()if videos_per_job > 1:for job_key in expand_job_token(job_token):job_states[job_key] = statebase_states[job_key.split("_", 1)[0]] = stateelse:job_key = job_token.strip()job_states[job_key] = statebase_states[job_key.split("_", 1)[0]] = stateexcept Exception:job_states = {}base_states = {}22 unmodified lineselse:state = base_states.get(job_id)if not state:submitted_at = meta.get("submitted_at", "")fresh_missing = Falseif submitted_at:try:submitted_dt = datetime.strptime(submitted_at, "%Y-%m-%d %H:%M:%S")fresh_missing = (now - submitted_dt) <= timedelta(seconds=min(timeout_seconds, 600))except Exception:fresh_missing = Falseif fresh_missing:count += 1continueclaim_path.unlink(missing_ok=True)continuesubmitted_at = meta.get("submitted_at", "")5 unmodified linesexcept Exception:stale_pending = Falseif stale_pending:cancel_target = job_key or (f"{job_id}_{task_id}" if task_id else job_id)subprocess.run(["scancel", cancel_target], check=False)claim_path.unlink(missing_ok=True)continuecount += 13 unmodified linescleanup_stale_process_jobs() {python - <<PYimport reimport subprocessfrom datetime import datetime, timedeltafrom pathlib import Path1 unmodified lineclaim_dir = Path("$STATE_ROOT/slurm/state/claims")claim_dir.mkdir(parents=True, exist_ok=True)timeout_seconds = int("$PROCESS_PENDING_TIMEOUT_SECONDS")videos_per_job = int("${VIDEOS_PER_JOB:-1}")now = datetime.now()bad_reason_tokens = (7 unmodified linestimed_pending_reasons = ("Priority", "Resources", "QOS")squeue_rows = {}array_re = re.compile(r"^(?P<base>\d+)_\[(?P<start>\d+)-(?P<end>\d+)(?:%(?P<limit>\d+))?\]$")def expand_job_token(job_token: str):job_token = job_token.strip()match = array_re.match(job_token)if not match:return [job_token]base = match.group("base")start = int(match.group("start"))end = int(match.group("end"))return [f"{base}_{index}" for index in range(start, end + 1)]try:proc = subprocess.run(["squeue", "-h", "-u", "$USER", "-n", "dwpose", "-o", "%i|%T|%R"],4 unmodified linesfor line in proc.stdout.splitlines():if not line.strip() or "|" not in line:continuejob_token, state, reason = line.split("|", 2)state = state.strip().upper()reason = reason.strip()if videos_per_job > 1:for job_key in expand_job_token(job_token):squeue_rows[job_key] = (state, reason)else:squeue_rows[job_token.strip()] = (state, reason)except Exception:squeue_rows = {}20 unmodified linescontinuerow = squeue_rows.get(job_key)if not row:fresh_missing = Falseif submitted_at:try:submitted_dt = datetime.strptime(submitted_at, "%Y-%m-%d %H:%M:%S")fresh_missing = (now - submitted_dt) <= timedelta(seconds=min(timeout_seconds, 600))except Exception:fresh_missing = Falseif fresh_missing:continueclaim_path.unlink(missing_ok=True)removed_claims += 1continue11 unmodified linesexcept Exception:passif should_cancel:cancel_target = job_key or (f"{job_id}_{task_id}" if task_id else job_id)subprocess.run(["scancel", cancel_target], check=False)cancelled_jobs.add(cancel_target)claim_path.unlink(missing_ok=True)removed_claims += 157 unmodified lines}count_complete_pending_upload() {PYTHONPATH="$ROOT_DIR${PYTHONPATH:+:$PYTHONPATH}" python - <<PYimport jsonfrom pathlib import Pathfrom utils.dataset_pool import list_unuploaded_folder_pathsdataset_dir = Path("$DATASET_DIR")scratch_dataset_dir = Path("$SCRATCH_DATASET_DIR")progress_path = Path("$PROGRESS_JSON")uploaded = {}if progress_path.exists():uploaded = json.loads(progress_path.read_text()).get("uploaded_folders", {})print(len(list_unuploaded_folder_paths(dataset_dir, scratch_dataset_dir, uploaded)))PY}bytes_complete_pending_upload() {PYTHONPATH="$ROOT_DIR${PYTHONPATH:+:$PYTHONPATH}" python - <<PYimport jsonfrom pathlib import Pathfrom utils.dataset_pool import list_unuploaded_folder_pathsdataset_dir = Path("$DATASET_DIR")scratch_dataset_dir = Path("$SCRATCH_DATASET_DIR")progress_path = Path("$PROGRESS_JSON")uploaded = {}if progress_path.exists():uploaded = json.loads(progress_path.read_text()).get("uploaded_folders", {})total = 0for _video_id, folder_path in list_unuploaded_folder_paths(dataset_dir, scratch_dataset_dir, uploaded):for path in folder_path.rglob("*"):if path.is_file():try:stat_result = path.stat()except FileNotFoundError:continueallocated = getattr(stat_result, "st_blocks", 0) * 512total += allocated if allocated > 0 else stat_result.st_sizeprint(total)PY}20 unmodified lines[[ "$pending_download" =~ ^[0-9]+$ ]] || pending_download=0pending_process="$(count_pending_process 2>/dev/null || true)"[[ "$pending_process" =~ ^[0-9]+$ ]] || pending_process=0raw_video_bytes="$(( $(dir_size_bytes "$RAW_VIDEO_DIR" 2>/dev/null || echo 0) + $(dir_size_bytes "$SCRATCH_RAW_VIDEO_DIR" 2>/dev/null || echo 0) ))"[[ "$raw_video_bytes" =~ ^[0-9]+$ ]] || raw_video_bytes=0echo "[download] iteration=$iteration pending_download=$pending_download raw_backlog=$pending_process raw_video_bytes=$raw_video_bytes pruned_raw_videos=$pruned stale_download_claims=$stale_download_claims stale_download_partials=$stale_download_partials stale_process_jobs=$stale_process_jobs stale_process_claims=$stale_process_claims stale_orphan_process_jobs=$stale_orphan_process_jobs"137 unmodified lineswhile true; doiteration=$((iteration + 1))local prunedpruned="$(prune_processed_raw_videos 2>/dev/null || true)"[[ "$pruned" =~ ^[0-9]+$ ]] || pruned=0local pending_download pending_process complete_pending_upload complete_pending_upload_bytespending_download="$(count_pending_downloads 2>/dev/null || true)"[[ "$pending_download" =~ ^[0-9]+$ ]] || pending_download=0pending_process="$(count_pending_process 2>/dev/null || true)"[[ "$pending_process" =~ ^[0-9]+$ ]] || pending_process=0complete_pending_upload="$(count_complete_pending_upload 2>/dev/null || true)"[[ "$complete_pending_upload" =~ ^[0-9]+$ ]] || complete_pending_upload=0complete_pending_upload_bytes="$(bytes_complete_pending_upload 2>/dev/null || true)"[[ "$complete_pending_upload_bytes" =~ ^[0-9]+$ ]] || complete_pending_upload_bytes=0echo "[upload] iteration=$iteration pending_download=$pending_download raw_backlog=$pending_process complete_pending_upload=$complete_pending_upload complete_pending_upload_bytes=$complete_pending_upload_bytes pruned_raw_videos=$pruned"if [[ "$MAX_ITERATIONS" -gt 0 && "$iteration" -gt "$MAX_ITERATIONS" ]]; then
20 unmodified lines212223242526273 unmodified lines31323334353629 unmodified lines66676869707172737475394 unmodified lines470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524328 unmodified lines85385485585685785885948 unmodified lines90890991091191291391432 unmodified lines94794894995095195295320 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import update_video_statsDEFAULT_SOURCE_METADATA_CSV = REPO_ROOT / "SignVerse-2M-metadata_ori.csv"3 unmodified linesDEFAULT_RAW_METADATA_DIR = REPO_ROOT / "raw_metadata"DEFAULT_DATASET_DIR = REPO_ROOT / "dataset"DEFAULT_STATS_NPZ = REPO_ROOT / "stats.npz"DEFAULT_YT_DLP_EXTRACTOR_ARGS = "youtube:player_client=web_safari,web"COOKIE_DOMAINS = ("youtube.com", "google.com", "googlevideo.com", "ytimg.com")TIMESTAMP_LINE_RE = re.compile(29 unmodified linesparser.add_argument("--source-metadata-csv", type=Path, default=DEFAULT_SOURCE_METADATA_CSV)parser.add_argument("--output-metadata-csv", type=Path, default=DEFAULT_OUTPUT_METADATA_CSV)parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--raw-caption-dir", type=Path, default=DEFAULT_RAW_CAPTION_DIR)parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--limit", type=int, default=None)parser.add_argument("--video-ids", nargs="*", default=None)parser.add_argument("--force-metadata", action="store_true")394 unmodified linesreturn dataset_dir / video_id / "captions"def find_video_file(raw_video_dir: Path, video_id: str) -> Path | None:candidates = []for path in raw_video_dir.glob(f"{video_id}.*"):if path.suffix in {".mp4", ".mkv", ".webm", ".mov"}:candidates.append(path)return sorted(candidates)[0] if candidates else Nonedef iter_partial_download_files(raw_video_dir: Path, video_id: str) -> Iterable[Path]:seen: set[Path] = set()for path in raw_video_dir.glob(f"{video_id}*"):if not path.is_file():continuesuffixes = set(path.suffixes)if ".part" in suffixes or ".ytdl" in suffixes or path.suffix in {".part", ".ytdl"}:resolved = path.resolve()if resolved not in seen:seen.add(resolved)yield pathdef cleanup_partial_downloads(raw_video_dir: Path, video_id: str) -> None:for partial_path in iter_partial_download_files(raw_video_dir, video_id):partial_path.unlink(missing_ok=True)def download_video(video_id: str, raw_video_dir: Path, args: argparse.Namespace) -> Tuple[str, str]:raw_video_dir.mkdir(parents=True, exist_ok=True)cleanup_partial_downloads(raw_video_dir, video_id)command = build_yt_dlp_base_command(args)command.extend(["--output",str(raw_video_dir / "%(id)s.%(ext)s"),"--format","worstvideo*+worstaudio/worst","--format-sort","+res,+size,+br,+fps","--merge-output-format","mp4",youtube_url(video_id),])result = run_command(command)video_path = find_video_file(raw_video_dir, video_id)cleanup_partial_downloads(raw_video_dir, video_id)if result.returncode != 0 and not video_path:raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "video download failed")return repo_relative_or_absolute(video_path) if video_path else "", ""def subtitle_file_language(path: Path, video_id: str) -> str:328 unmodified linesfailure_count, should_skip = record_row_failure(row, stats_record, metadata_error, args.max_failures_before_skip)stats_record["last_error"] = row["error"]persist_row_update(args, video_id, row, fieldnames)update_video_stats(args.stats_npz, video_id, **stats_record)print(f" metadata failed: {metadata_error}")if should_skip:print(f" skipping after {failure_count} failures")48 unmodified linesrow["raw_caption_dir"] = ""try:existing_video = find_video_file(args.raw_video_dir, video_id)if args.skip_video_download:row["download_status"] = "skipped"row["raw_video_path"] = repo_relative_or_absolute(existing_video) if existing_video else ""32 unmodified linesstats_record["last_error"] = row["error"]stats_record["updated_at"] = row["processed_at"]persist_row_update(args, video_id, row, fieldnames)update_video_stats(args.stats_npz, video_id, **stats_record)if row["download_status"] == "failed":print(f" video download failed: {download_error}")20 unmodified lines212223242526272829303132333 unmodified lines3738394041424329 unmodified lines7374757677787980818283848586394 unmodified lines481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532328 unmodified lines86186286386486586686748 unmodified lines91691791891992092192232 unmodified lines95595695795895996096120 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import update_video_stats_best_effortfrom utils.raw_video_pool import (choose_download_target,cleanup_partial_downloads as cleanup_partial_downloads_pool,find_video_file as find_video_file_pool,release_download_reservation,)DEFAULT_SOURCE_METADATA_CSV = REPO_ROOT / "SignVerse-2M-metadata_ori.csv"3 unmodified linesDEFAULT_RAW_METADATA_DIR = REPO_ROOT / "raw_metadata"DEFAULT_DATASET_DIR = REPO_ROOT / "dataset"DEFAULT_STATS_NPZ = REPO_ROOT / "stats.npz"DEFAULT_STATUS_JOURNAL_PATH = REPO_ROOT / "upload_status_journal.jsonl"DEFAULT_YT_DLP_EXTRACTOR_ARGS = "youtube:player_client=web_safari,web"COOKIE_DOMAINS = ("youtube.com", "google.com", "googlevideo.com", "ytimg.com")TIMESTAMP_LINE_RE = re.compile(29 unmodified linesparser.add_argument("--source-metadata-csv", type=Path, default=DEFAULT_SOURCE_METADATA_CSV)parser.add_argument("--output-metadata-csv", type=Path, default=DEFAULT_OUTPUT_METADATA_CSV)parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--scratch-raw-video-dir", type=Path, default=None)parser.add_argument("--home-raw-video-limit", type=int, default=180)parser.add_argument("--scratch-raw-video-limit", type=int, default=2800)parser.add_argument("--raw-caption-dir", type=Path, default=DEFAULT_RAW_CAPTION_DIR)parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)parser.add_argument("--limit", type=int, default=None)parser.add_argument("--video-ids", nargs="*", default=None)parser.add_argument("--force-metadata", action="store_true")394 unmodified linesreturn dataset_dir / video_id / "captions"def find_video_file(raw_video_dir: Path, video_id: str, scratch_raw_video_dir: Path | None = None) -> Path | None:return find_video_file_pool(video_id, raw_video_dir, scratch_raw_video_dir)def iter_partial_download_files(raw_video_dir: Path, video_id: str, scratch_raw_video_dir: Path | None = None) -> Iterable[Path]:yield from cleanup_partial_downloads_pool.__globals__['iter_partial_download_files'](video_id, raw_video_dir, scratch_raw_video_dir)def cleanup_partial_downloads(raw_video_dir: Path, video_id: str, scratch_raw_video_dir: Path | None = None) -> None:cleanup_partial_downloads_pool(video_id, raw_video_dir, scratch_raw_video_dir)def download_video(video_id: str, raw_video_dir: Path, args: argparse.Namespace) -> Tuple[str, str]:target_raw_video_dir, reservation_path = choose_download_target(raw_video_dir,args.scratch_raw_video_dir,args.home_raw_video_limit,args.scratch_raw_video_limit,args.claim_dir,video_id,)target_raw_video_dir.mkdir(parents=True, exist_ok=True)try:cleanup_partial_downloads(raw_video_dir, video_id, args.scratch_raw_video_dir)command = build_yt_dlp_base_command(args)command.extend(["--output",str(target_raw_video_dir / "%(id)s.%(ext)s"),"--format","worstvideo*+worstaudio/worst","--format-sort","+res,+size,+br,+fps","--merge-output-format","mp4",youtube_url(video_id),])result = run_command(command)video_path = find_video_file(raw_video_dir, video_id, args.scratch_raw_video_dir)cleanup_partial_downloads(raw_video_dir, video_id, args.scratch_raw_video_dir)if result.returncode != 0 and not video_path:raise RuntimeError(result.stderr.strip() or result.stdout.strip() or "video download failed")return repo_relative_or_absolute(video_path) if video_path else "", ""finally:release_download_reservation(reservation_path)def subtitle_file_language(path: Path, video_id: str) -> str:328 unmodified linesfailure_count, should_skip = record_row_failure(row, stats_record, metadata_error, args.max_failures_before_skip)stats_record["last_error"] = row["error"]persist_row_update(args, video_id, row, fieldnames)update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)print(f" metadata failed: {metadata_error}")if should_skip:print(f" skipping after {failure_count} failures")48 unmodified linesrow["raw_caption_dir"] = ""try:existing_video = find_video_file(args.raw_video_dir, video_id, args.scratch_raw_video_dir)if args.skip_video_download:row["download_status"] = "skipped"row["raw_video_path"] = repo_relative_or_absolute(existing_video) if existing_video else ""32 unmodified linesstats_record["last_error"] = row["error"]stats_record["updated_at"] = row["processed_at"]persist_row_update(args, video_id, row, fieldnames)update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)if row["download_status"] == "failed":print(f" video download failed: {download_error}")
28 unmodified lines29303132333435363738394052 unmodified lines939495969798992 unmodified lines10210310410510610777 unmodified lines185186187188189190191192193194195196197198199200201202363 unmodified lines5665675685695705716 unmodified lines578579580581582583584147 unmodified lines7327337347357367377387392 unmodified lines7427437447457467475 unmodified lines7537547557567577587597603 unmodified lines76476576676776876977077128 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import load_stats, update_video_statsDEFAULT_RAW_VIDEO_DIR = REPO_ROOT / "raw_video"DEFAULT_DATASET_DIR = REPO_ROOT / "dataset"DEFAULT_STATS_NPZ = REPO_ROOT / "stats.npz"VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov"}COMPLETE_MARKER_NAME = ".complete"52 unmodified linesdescription="Extract DWpose NPZ files from raw videos.")parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--fps", type=int, default=24)parser.add_argument("--limit", type=int, default=None)parser.add_argument("--workers", type=int, default=None)2 unmodified linesparser.add_argument("--delete-source-on-success", action="store_true")parser.add_argument("--tmp-root", type=Path, default=Path("/tmp"))parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--single-poses-npz",dest="single_poses_npz",77 unmodified linesdef select_video_paths(args: argparse.Namespace) -> List[Path]:args.raw_video_dir.mkdir(parents=True, exist_ok=True)args.dataset_dir.mkdir(parents=True, exist_ok=True)video_id_filter = set(args.video_ids or [])stats = load_stats(args.stats_npz)selected = []for path in sorted(args.raw_video_dir.iterdir()):if not path.is_file() or path.suffix.lower() not in VIDEO_EXTENSIONS:continuevideo_id = path.stemif video_id_filter and video_id not in video_id_filter:continuenpz_dir = args.dataset_dir / video_id / "npz"complete_marker = npz_dir / COMPLETE_MARKER_NAMEif (not args.force363 unmodified linesdef process_video(video_path: Path,dataset_dir: Path,fps: int,detector: DWposeDetector,tmp_root: Path,6 unmodified linesoptimized_frame_stride: int,) -> None:video_id = video_path.stemoutput_npz_dir = dataset_dir / video_id / "npz"complete_marker = output_npz_dir / COMPLETE_MARKER_NAMEposes_npz_path = output_npz_dir / "poses.npz"if output_npz_dir.exists() and complete_marker.exists() and not force:147 unmodified linesif index % worker_count != rank:continuetry:update_video_stats(args.stats_npz,video_path.stem,process_status="running",last_error="",2 unmodified linesprocess_video(video_path=video_path,dataset_dir=args.dataset_dir,fps=args.fps,detector=detector,tmp_root=args.tmp_root,5 unmodified linesoptimized_detect_resolution=args.optimized_detect_resolution,optimized_frame_stride=args.optimized_frame_stride,)update_video_stats(args.stats_npz,video_path.stem,process_status="ok",last_error="",3 unmodified linesvideo_path.unlink()print(f"Worker {rank}: deleted source video {video_path.name}")except Exception as exc:update_video_stats(args.stats_npz,video_path.stem,process_status="failed",last_error=str(exc),28 unmodified lines29303132333435363738394041424352 unmodified lines969798991001011021031042 unmodified lines10710810911011111211377 unmodified lines191192193194195196197198199200201202203204205206207208209210211363 unmodified lines5755765775785795805815825836 unmodified lines590591592593594595596597147 unmodified lines7457467477487497507517527532 unmodified lines7567577587597607617627637645 unmodified lines7707717727737747757767777783 unmodified lines78278378478578678778878979028 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import load_stats, update_video_stats_best_effortfrom utils.raw_video_pool import iter_raw_video_filesfrom utils.dataset_pool import dataset_dir_for_video, find_dataset_video_dirDEFAULT_RAW_VIDEO_DIR = REPO_ROOT / "raw_video"DEFAULT_DATASET_DIR = REPO_ROOT / "dataset"DEFAULT_STATS_NPZ = REPO_ROOT / "stats.npz"DEFAULT_STATUS_JOURNAL_PATH = REPO_ROOT / "upload_status_journal.jsonl"VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov"}COMPLETE_MARKER_NAME = ".complete"52 unmodified linesdescription="Extract DWpose NPZ files from raw videos.")parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--scratch-raw-video-dir", type=Path, default=None)parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--scratch-dataset-dir", type=Path, default=None)parser.add_argument("--fps", type=int, default=24)parser.add_argument("--limit", type=int, default=None)parser.add_argument("--workers", type=int, default=None)2 unmodified linesparser.add_argument("--delete-source-on-success", action="store_true")parser.add_argument("--tmp-root", type=Path, default=Path("/tmp"))parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)parser.add_argument("--single-poses-npz",dest="single_poses_npz",77 unmodified linesdef select_video_paths(args: argparse.Namespace) -> List[Path]:args.raw_video_dir.mkdir(parents=True, exist_ok=True)if args.scratch_raw_video_dir is not None:args.scratch_raw_video_dir.mkdir(parents=True, exist_ok=True)args.dataset_dir.mkdir(parents=True, exist_ok=True)if args.scratch_dataset_dir is not None:args.scratch_dataset_dir.mkdir(parents=True, exist_ok=True)video_id_filter = set(args.video_ids or [])stats = load_stats(args.stats_npz)selected = []for path in sorted(iter_raw_video_files(args.raw_video_dir, args.scratch_raw_video_dir), key=lambda p: (p.stem, str(p))):video_id = path.stemif video_id_filter and video_id not in video_id_filter:continuedataset_root = find_dataset_video_dir(video_id, args.dataset_dir, args.scratch_dataset_dir)npz_dir = dataset_root / video_id / "npz"complete_marker = npz_dir / COMPLETE_MARKER_NAMEif (not args.force363 unmodified linesdef process_video(video_path: Path,dataset_dir: Path,scratch_dataset_dir: Path | None,raw_video_dir: Path,scratch_raw_video_dir: Path | None,fps: int,detector: DWposeDetector,tmp_root: Path,6 unmodified linesoptimized_frame_stride: int,) -> None:video_id = video_path.stemoutput_dataset_dir = dataset_dir_for_video(video_path, raw_video_dir, scratch_raw_video_dir, dataset_dir, scratch_dataset_dir)output_npz_dir = output_dataset_dir / video_id / "npz"complete_marker = output_npz_dir / COMPLETE_MARKER_NAMEposes_npz_path = output_npz_dir / "poses.npz"if output_npz_dir.exists() and complete_marker.exists() and not force:147 unmodified linesif index % worker_count != rank:continuetry:update_video_stats_best_effort(args.stats_npz,args.status_journal_path,video_path.stem,process_status="running",last_error="",2 unmodified linesprocess_video(video_path=video_path,dataset_dir=args.dataset_dir,scratch_dataset_dir=args.scratch_dataset_dir,raw_video_dir=args.raw_video_dir,scratch_raw_video_dir=args.scratch_raw_video_dir,fps=args.fps,detector=detector,tmp_root=args.tmp_root,5 unmodified linesoptimized_detect_resolution=args.optimized_detect_resolution,optimized_frame_stride=args.optimized_frame_stride,)update_video_stats_best_effort(args.stats_npz,args.status_journal_path,video_path.stem,process_status="ok",last_error="",3 unmodified linesvideo_path.unlink()print(f"Worker {rank}: deleted source video {video_path.name}")except Exception as exc:update_video_stats_best_effort(args.stats_npz,args.status_journal_path,video_path.stem,process_status="failed",last_error=str(exc),
1234567811 unmodified lines2021222324252616 unmodified lines434445464748495051525354555657585918 unmodified lines7879808182831 unmodified line85868788899091929394952 unmodified lines989910010110210310410510610710810911011111211311410 unmodified lines12512612712812913013113213313413513613713813914014114214314443 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092101 unmodified line2122132142152162171 unmodified line21922022122222322422522622722822923023112 unmodified lines24424524624724824923 unmodified lines2732742752762772782793 unmodified lines2832842852862872882896 unmodified lines2962972982993003013023033043053063073083 unmodified lines3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603619 unmodified lines3713723733743753763774 unmodified lines3823833843853863871 unmodified line3893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334345 unmodified lines4404414424434444454 unmodified lines4504514524534544554564574584594604614624631 unmodified line4654664674684694704714724734744754764774784794804814824834844854864874884894904914921 unmodified line4944954964974984995001 unmodified line502503504505506507508509510511512513514515516517518519520521#!/usr/bin/env python3import argparseimport jsonimport osimport shutilimport subprocessimport sys11 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import update_many_video_stats_with_retryDEFAULT_DATASET_DIR = REPO_ROOT / "dataset"16 unmodified linesdescription="Archive NPZ folders into 14GB tar files and upload them to Hugging Face.")parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--raw-caption-dir", type=Path, default=DEFAULT_RAW_CAPTION_DIR)parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)parser.add_argument("--archive-dir", type=Path, default=DEFAULT_ARCHIVE_DIR)parser.add_argument("--progress-path", type=Path, default=DEFAULT_PROGRESS_PATH)parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)parser.add_argument("--repo-id", default="SignerX/SignVerse-2M")parser.add_argument("--repo-type", default="dataset")parser.add_argument("--target-bytes", type=int, default=DEFAULT_TARGET_BYTES)parser.add_argument("--target-folders", type=int, default=DEFAULT_TARGET_FOLDERS)parser.add_argument("--require-target-bytes", action="store_true", default=True)parser.add_argument("--allow-small-final-batch", action="store_true")parser.add_argument("--dry-run", action="store_true")18 unmodified linesdef append_status_journal(journal_path: Path, video_ids: Sequence[str], **updates: str) -> None:journal_path.parent.mkdir(parents=True, exist_ok=True)payload = {1 unmodified line"updates": {k: ("" if v is None else str(v)) for k, v in updates.items()},"recorded_at": time.strftime("%Y-%m-%d %H:%M:%S"),}with journal_path.open("a", encoding="utf-8") as handle:handle.write(json.dumps(payload, ensure_ascii=False) + "\n")def update_many_video_stats_best_effort(stats_path: Path, journal_path: Path, video_ids: Sequence[str], **updates: str) -> None:try:update_many_video_stats_with_retry(stats_path, video_ids, **updates)except Exception as exc:2 unmodified linesappend_status_journal(journal_path, video_ids, **payload)print(f"Warning: stats.npz update deferred to journal due to: {exc}")def load_progress(progress_path: Path) -> Dict[str, object]:if progress_path.exists():with progress_path.open("r", encoding="utf-8") as handle:return json.load(handle)return {"archives": {}, "uploaded_folders": {}}def save_progress(progress_path: Path, progress: Dict[str, object]) -> None:progress_path.parent.mkdir(parents=True, exist_ok=True)with progress_path.open("w", encoding="utf-8") as handle:json.dump(progress, handle, ensure_ascii=False, indent=2)def folder_size_bytes(folder_path: Path) -> int:10 unmodified linesreturn totaldef list_unuploaded_folder_paths(dataset_dir: Path, progress: Dict[str, object]) -> List[Tuple[str, Path]]:uploaded_folders = progress.get("uploaded_folders", {})folders = []for folder_path in sorted(dataset_dir.iterdir()):if not folder_path.is_dir():continuefolder_name = folder_path.nameif folder_name in uploaded_folders:continuenpz_dir = folder_path / "npz"if not (npz_dir / COMPLETE_MARKER_NAME).exists():continuefolders.append((folder_name, folder_path))return foldersdef enrich_folder_sizes(folders: Sequence[Tuple[str, Path]]) -> List[Tuple[str, Path, int]]:43 unmodified linespath.mkdir(parents=True, exist_ok=True)return pathdef create_tar_archive(archive_path: Path, dataset_dir: Path, folder_names: Sequence[str]) -> None:archive_path.parent.mkdir(parents=True, exist_ok=True)with tarfile.open(archive_path, mode="w") as tar:for folder_name in folder_names:tar.add(dataset_dir / folder_name, arcname=folder_name, recursive=True)def upload_archive(api: HfApi, repo_id: str, repo_type: str, archive_path: Path) -> None:api.upload_file(path_or_fileobj=str(archive_path),path_in_repo=f"dataset/{archive_path.name}",repo_id=repo_id,repo_type=repo_type,)def upload_runtime_state_files(api: HfApi | None, repo_id: str, repo_type: str, progress_path: Path, journal_path: Path) -> None:if api is None:returnapi.upload_file(1 unmodified linepath_in_repo="runtime_state/archive_upload_progress.json",repo_id=repo_id,repo_type=repo_type,)if journal_path.exists():api.upload_file(1 unmodified linepath_in_repo="runtime_state/upload_status_journal.jsonl",repo_id=repo_id,repo_type=repo_type,)def upload_archive_streaming(api: HfApi, repo_id: str, repo_type: str, dataset_dir: Path, folder_names: Sequence[str], archive_name: str) -> None:if api is None:raise RuntimeError('api-stream upload requires a Hugging Face token')command = ['tar', '-cf', '-', '-C', str(dataset_dir), *folder_names]process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)assert process.stdout is not Nonestderr_chunks = []12 unmodified linespath_in_repo=f"dataset/{archive_name}",repo_id=repo_id,repo_type=repo_type,)finally:try:23 unmodified linesreturn (result.stdout or result.stderr or "").strip()def ensure_git_upload_repo(clone_dir: Path, repo_id: str, repo_type: str) -> Path:remote_url = repo_git_url(repo_id, repo_type)clone_dir.parent.mkdir(parents=True, exist_ok=True)if not (clone_dir / '.git').exists():3 unmodified linesif configured != remote_url:raise RuntimeError(f"Git upload clone remote mismatch: {configured} != {remote_url}")run_git(["git", "fetch", "origin"], clone_dir)run_git(["git", "reset", "--hard", "origin/main"], clone_dir)run_git(["git", "lfs", "install", "--local"], clone_dir)try:run_git(["git", "config", "user.name"], clone_dir)6 unmodified linesreturn clone_dirdef list_repo_files_via_git(clone_dir: Path, repo_id: str, repo_type: str) -> List[str]:repo_dir = ensure_git_upload_repo(clone_dir, repo_id, repo_type)return [path.name for path in repo_dir.iterdir() if path.is_file()]def upload_archive_via_git(clone_dir: Path, repo_id: str, repo_type: str, archive_path: Path) -> None:repo_dir = ensure_git_upload_repo(clone_dir, repo_id, repo_type)target_path = repo_dir / archive_path.nameshutil.copy2(archive_path, target_path)run_git(["git", "add", archive_path.name], repo_dir)3 unmodified linesif diff_result.returncode != 1:raise RuntimeError(f"git diff --cached failed for {archive_path.name}")run_git(["git", "commit", "-m", f"Add {archive_path.name}"], repo_dir)run_git(["git", "push", "origin", "main"], repo_dir)def cleanup_local_assets(video_ids: Sequence[str],dataset_dir: Path,raw_video_dir: Path,raw_caption_dir: Path,raw_metadata_dir: Path,) -> None:for video_id in video_ids:dataset_video_dir = dataset_dir / video_idif dataset_video_dir.exists():shutil.rmtree(dataset_video_dir, ignore_errors=True)for path in raw_video_dir.glob(f"{video_id}.*"):if path.is_file():path.unlink()caption_dir = raw_caption_dir / video_idif caption_dir.exists():shutil.rmtree(caption_dir, ignore_errors=True)metadata_path = raw_metadata_dir / f"{video_id}.json"if metadata_path.exists():metadata_path.unlink()def prune_uploaded_runtime_residue(progress: Dict[str, object],dataset_dir: Path,raw_video_dir: Path,raw_caption_dir: Path,raw_metadata_dir: Path,) -> None:uploaded = set(progress.get("uploaded_folders", {}))for video_id in uploaded:for path in raw_video_dir.glob(f"{video_id}.*"):if path.is_file():path.unlink(missing_ok=True)caption_dir = raw_caption_dir / video_idif caption_dir.exists():shutil.rmtree(caption_dir, ignore_errors=True)metadata_path = raw_metadata_dir / f"{video_id}.json"if metadata_path.exists():metadata_path.unlink()dataset_video_dir = dataset_dir / video_idif dataset_video_dir.exists() and not (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists():shutil.rmtree(dataset_video_dir, ignore_errors=True)9 unmodified linesdef main() -> None:args = parse_args()print(f"[pipeline03] start upload_mode={args.upload_mode} repo_id={args.repo_id}", flush=True)progress = load_progress(args.progress_path)print(f"[pipeline03] loaded progress archives={len(progress.get('archives', {}))} "4 unmodified linesprint(f"[pipeline03] token_present={bool(resolved_token)}", flush=True)api = HfApi(token=resolved_token) if args.upload_mode in {"api", "api-stream"} else Noneargs.dataset_dir.mkdir(parents=True, exist_ok=True)try:if args.upload_mode in {"api", "api-stream"}:1 unmodified linerepo_files = []else:print("[pipeline03] listing repo files via git", flush=True)repo_files = list_repo_files_via_git(args.git_clone_dir, args.repo_id, args.repo_type)except Exception as exc:print(f"[pipeline03] repo file listing failed: {exc}", flush=True)traceback.print_exc()repo_files = []while True:prune_uploaded_runtime_residue(progress,args.dataset_dir,args.raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)remaining_folder_paths = list_unuploaded_folder_paths(args.dataset_dir, progress)if not remaining_folder_paths:print("No unuploaded dataset folders remain.")breakremaining_count = len(remaining_folder_paths)print(f"[pipeline03] remaining completed folders available={remaining_count}", flush=True)if remaining_count >= args.target_folders:selected_folder_paths = remaining_folder_paths[: args.target_folders]batch = enrich_folder_sizes(selected_folder_paths)batch_names = [name for name, _, _ in batch]batch_bytes = sum(folder_bytes for _, _, folder_bytes in batch)print(f"[pipeline03] folder threshold reached; selecting first {len(batch_names)} folders without global size scan", flush=True)else:remaining_folders = enrich_folder_sizes(remaining_folder_paths)remaining_bytes = total_batchable_bytes(remaining_folders)require_target_bytes = args.require_target_bytes and not args.allow_small_final_batchif require_target_bytes and remaining_bytes < args.target_bytes:print(f"Skip upload: only {format_size(remaining_bytes)} across {remaining_count} completed NPZ folders available, below targets {format_size(args.target_bytes)} or {args.target_folders} folders.")breakbatch = build_batch(remaining_folders, args.target_bytes)batch_names = [name for name, _, _ in batch]batch_bytes = sum(folder_bytes for _, _, folder_bytes in batch)archive_index = next_archive_index(progress, repo_files)archive_name = f"Sign_DWPose_NPZ_{archive_index:06d}.tar"archive_root = args.archive_dir if args.upload_mode == "git-ssh" else preferred_temp_archive_dir()archive_path = archive_root / archive_name5 unmodified linesbreakargs.archive_dir.mkdir(parents=True, exist_ok=True)append_status_journal(args.status_journal_path,batch_names,4 unmodified lines)try:if args.upload_mode == "api-stream":upload_archive_streaming(api, args.repo_id, args.repo_type, args.dataset_dir, batch_names, archive_name)else:create_tar_archive(archive_path, args.dataset_dir, batch_names)if args.upload_mode == "api":upload_archive(api, args.repo_id, args.repo_type, archive_path)else:upload_archive_via_git(args.git_clone_dir, args.repo_id, args.repo_type, archive_path)except Exception as exc:update_many_video_stats_best_effort(args.stats_npz,args.status_journal_path,1 unmodified lineupload_status="failed",local_cleanup_status="pending",archive_name=archive_name,last_error=str(exc),updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)if archive_path.exists():archive_path.unlink(missing_ok=True)raiseprogress["archives"][archive_name] = {"folders": batch_names,"size_bytes": batch_bytes,"uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),}for folder_name in batch_names:progress["uploaded_folders"][folder_name] = archive_namesave_progress(args.progress_path, progress)cleanup_error = ""try:cleanup_local_assets(batch_names,args.dataset_dir,args.raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)1 unmodified linearchive_path.unlink(missing_ok=True)except Exception as exc:cleanup_error = str(exc)repo_files.append(f"dataset/{archive_name}")update_many_video_stats_best_effort(args.stats_npz,args.status_journal_path,1 unmodified lineupload_status="uploaded",local_cleanup_status="deleted" if not cleanup_error else "failed",archive_name=archive_name,last_error=cleanup_error,updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)upload_runtime_state_files(api, args.repo_id, args.repo_type, args.progress_path, args.status_journal_path)prune_uploaded_runtime_residue(progress,args.dataset_dir,args.raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)if cleanup_error:raise RuntimeError(f"Uploaded {archive_name} but local cleanup failed: {cleanup_error}")print(f"Uploaded {archive_name} and cleaned raw assets for {len(batch_names)} videos.")if __name__ == "__main__":12345678910111211 unmodified lines242526272829303116 unmodified lines484950515253545556575859606162636465666768697071727318 unmodified lines92939495969798991001011021031041051061071081091101111121131 unmodified line1151161171181191201211221231241251261271281292 unmodified lines13213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219310 unmodified lines20420520620720820921021121243 unmodified lines2562572582592602612622632642652662672682692702712722732742752762772782791 unmodified line2812822832842852862871 unmodified line28929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932012 unmodified lines33333433533633733833923 unmodified lines3633643653663673683693 unmodified lines3733743753763773783793803813823833846 unmodified lines3913923933943953963973983994004014024033 unmodified lines4074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654669 unmodified lines4764774784794804814824834844854864874884894904914924934944 unmodified lines4995005015025035045055061 unmodified line5085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685 unmodified lines5745755765775785795805815825834 unmodified lines5885895905915925935945955965975985996006016026036046056066076086096101 unmodified line6126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676681 unmodified line6706716726736746751 unmodified line677678679680681682683684685686687688689690691692693694695696697698699700701702703704705#!/usr/bin/env python3import argparseimport contextlibimport fcntlimport hashlibimport jsonimport osimport randomimport shutilimport subprocessimport sys11 unmodified linesif str(REPO_ROOT) not in sys.path:sys.path.insert(0, str(REPO_ROOT))from utils.stats_npz import apply_status_journal_to_stats, update_many_video_stats_with_retryfrom utils.dataset_pool import find_dataset_video_dir, list_unuploaded_folder_paths as list_unuploaded_folder_paths_poolDEFAULT_DATASET_DIR = REPO_ROOT / "dataset"16 unmodified linesdescription="Archive NPZ folders into 14GB tar files and upload them to Hugging Face.")parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)parser.add_argument("--scratch-dataset-dir", type=Path, default=None)parser.add_argument("--raw-video-dir", type=Path, default=DEFAULT_RAW_VIDEO_DIR)parser.add_argument("--scratch-raw-video-dir", type=Path, default=None)parser.add_argument("--raw-caption-dir", type=Path, default=DEFAULT_RAW_CAPTION_DIR)parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)parser.add_argument("--archive-dir", type=Path, default=DEFAULT_ARCHIVE_DIR)parser.add_argument("--progress-path", type=Path, default=DEFAULT_PROGRESS_PATH)parser.add_argument("--stats-npz", type=Path, default=DEFAULT_STATS_NPZ)parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)parser.add_argument("--processed-csv-path", type=Path, default=None)parser.add_argument("--repo-id", default="SignerX/SignVerse-2M")parser.add_argument("--repo-type", default="dataset")parser.add_argument("--repo-revision", default=os.environ.get("HF_REPO_REVISION", "main"))parser.add_argument("--target-bytes", type=int, default=DEFAULT_TARGET_BYTES)parser.add_argument("--target-folders", type=int, default=DEFAULT_TARGET_FOLDERS)parser.add_argument("--parallel-shards", type=int, default=1)parser.add_argument("--shard-index", type=int, default=0)parser.add_argument("--start-stagger-min", type=int, default=0)parser.add_argument("--start-stagger-max", type=int, default=0)parser.add_argument("--skip-stats-write", action="store_true")parser.add_argument("--require-target-bytes", action="store_true", default=True)parser.add_argument("--allow-small-final-batch", action="store_true")parser.add_argument("--dry-run", action="store_true")18 unmodified linesdef journal_lock_path(journal_path: Path) -> Path:return journal_path.with_suffix(journal_path.suffix + '.lock')@contextlib.contextmanagerdef locked_journal(journal_path: Path):lock_path = journal_lock_path(journal_path)lock_path.parent.mkdir(parents=True, exist_ok=True)with lock_path.open('a+', encoding='utf-8') as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:yieldfinally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)def append_status_journal(journal_path: Path, video_ids: Sequence[str], **updates: str) -> None:journal_path.parent.mkdir(parents=True, exist_ok=True)payload = {1 unmodified line"updates": {k: ("" if v is None else str(v)) for k, v in updates.items()},"recorded_at": time.strftime("%Y-%m-%d %H:%M:%S"),}with locked_journal(journal_path):with journal_path.open("a", encoding="utf-8") as handle:handle.write(json.dumps(payload, ensure_ascii=False) + "\n")def update_many_video_stats_best_effort(stats_path: Path, journal_path: Path, video_ids: Sequence[str], skip_stats_write: bool = False, **updates: str) -> None:if skip_stats_write:append_status_journal(journal_path, video_ids, **updates)returntry:update_many_video_stats_with_retry(stats_path, video_ids, **updates)except Exception as exc:2 unmodified linesappend_status_journal(journal_path, video_ids, **payload)print(f"Warning: stats.npz update deferred to journal due to: {exc}")def progress_lock_path(progress_path: Path) -> Path:return progress_path.with_suffix(progress_path.suffix + '.lock')@contextlib.contextmanagerdef locked_progress(progress_path: Path):lock_path = progress_lock_path(progress_path)lock_path.parent.mkdir(parents=True, exist_ok=True)with lock_path.open('a+', encoding='utf-8') as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:yieldfinally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)def shard_for_video_id(video_id: str, shard_count: int) -> int:if shard_count <= 1:return 0digest = hashlib.sha1(video_id.encode('utf-8')).hexdigest()return int(digest[:8], 16) % shard_countdef filter_folders_for_shard(folders: Sequence[Tuple[str, Path]], shard_count: int, shard_index: int) -> List[Tuple[str, Path]]:if shard_count <= 1:return list(folders)return [(video_id, folder_path) for video_id, folder_path in folders if shard_for_video_id(video_id, shard_count) == shard_index]def load_progress(progress_path: Path, retries: int = 8, retry_delay: float = 0.2) -> Dict[str, object]:if not progress_path.exists():return {"archives": {}, "uploaded_folders": {}}last_error = Nonefor _ in range(retries):try:with progress_path.open("r", encoding="utf-8") as handle:data = handle.read()if not data.strip():raise json.JSONDecodeError("empty progress file", data, 0)return json.loads(data)except (json.JSONDecodeError, OSError) as exc:last_error = exctime.sleep(retry_delay)if last_error is not None:raise last_errorreturn {"archives": {}, "uploaded_folders": {}}def save_progress(progress_path: Path, progress: Dict[str, object]) -> None:progress_path.parent.mkdir(parents=True, exist_ok=True)tmp_path = progress_path.parent / f'.{progress_path.name}.{os.getpid()}.tmp'with tmp_path.open("w", encoding="utf-8") as handle:json.dump(progress, handle, ensure_ascii=False, indent=2)handle.flush()os.fsync(handle.fileno())os.replace(tmp_path, progress_path)def folder_size_bytes(folder_path: Path) -> int:10 unmodified linesreturn totaldef list_unuploaded_folder_paths(dataset_dir: Path, scratch_dataset_dir: Path | None, progress: Dict[str, object]) -> List[Tuple[str, Path]]:uploaded_folders = progress.get("uploaded_folders", {})return list_unuploaded_folder_paths_pool(dataset_dir, scratch_dataset_dir, uploaded_folders)def enrich_folder_sizes(folders: Sequence[Tuple[str, Path]]) -> List[Tuple[str, Path, int]]:43 unmodified linespath.mkdir(parents=True, exist_ok=True)return pathdef create_tar_archive(archive_path: Path, folder_paths: Sequence[Tuple[str, Path]]) -> None:archive_path.parent.mkdir(parents=True, exist_ok=True)with tarfile.open(archive_path, mode="w") as tar:for folder_name, folder_path in folder_paths:tar.add(folder_path, arcname=folder_name, recursive=True)def upload_archive(api: HfApi, repo_id: str, repo_type: str, repo_revision: str, archive_path: Path) -> None:api.upload_file(path_or_fileobj=str(archive_path),path_in_repo=f"dataset/{archive_path.name}",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)def upload_runtime_state_files(api: HfApi | None, repo_id: str, repo_type: str, repo_revision: str, progress_path: Path, journal_path: Path, stats_path: Path | None = None, processed_csv_path: Path | None = None) -> None:if api is None:returnapi.upload_file(1 unmodified linepath_in_repo="runtime_state/archive_upload_progress.json",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)if journal_path.exists():api.upload_file(1 unmodified linepath_in_repo="runtime_state/upload_status_journal.jsonl",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)if stats_path is not None and stats_path.exists():api.upload_file(path_or_fileobj=str(stats_path),path_in_repo="runtime_state/stats.npz",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)if processed_csv_path is not None and processed_csv_path.exists():api.upload_file(path_or_fileobj=str(processed_csv_path),path_in_repo="runtime_state/SignVerse-2M-metadata_processed.csv",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)def upload_archive_streaming(api: HfApi, repo_id: str, repo_type: str, repo_revision: str, folder_paths: Sequence[Tuple[str, Path]], archive_name: str) -> None:if api is None:raise RuntimeError('api-stream upload requires a Hugging Face token')command = ['tar', '-cf', '-']for folder_name, folder_path in folder_paths:command.extend(['-C', str(folder_path.parent), folder_name])process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)assert process.stdout is not Nonestderr_chunks = []12 unmodified linespath_in_repo=f"dataset/{archive_name}",repo_id=repo_id,repo_type=repo_type,revision=repo_revision,)finally:try:23 unmodified linesreturn (result.stdout or result.stderr or "").strip()def ensure_git_upload_repo(clone_dir: Path, repo_id: str, repo_type: str, repo_revision: str) -> Path:remote_url = repo_git_url(repo_id, repo_type)clone_dir.parent.mkdir(parents=True, exist_ok=True)if not (clone_dir / '.git').exists():3 unmodified linesif configured != remote_url:raise RuntimeError(f"Git upload clone remote mismatch: {configured} != {remote_url}")run_git(["git", "fetch", "origin"], clone_dir)remote_branch = f"origin/{repo_revision}"existing = subprocess.run(["git", "show-ref", "--verify", f"refs/remotes/{remote_branch}"], cwd=str(clone_dir))if existing.returncode == 0:run_git(["git", "checkout", "-B", repo_revision, remote_branch], clone_dir)else:run_git(["git", "checkout", "-B", repo_revision, "origin/main"], clone_dir)run_git(["git", "lfs", "install", "--local"], clone_dir)try:run_git(["git", "config", "user.name"], clone_dir)6 unmodified linesreturn clone_dirdef list_repo_files_via_git(clone_dir: Path, repo_id: str, repo_type: str, repo_revision: str) -> List[str]:repo_dir = ensure_git_upload_repo(clone_dir, repo_id, repo_type, repo_revision)return [path.name for path in repo_dir.iterdir() if path.is_file()]def upload_archive_via_git(clone_dir: Path, repo_id: str, repo_type: str, repo_revision: str, archive_path: Path) -> None:repo_dir = ensure_git_upload_repo(clone_dir, repo_id, repo_type, repo_revision)target_path = repo_dir / archive_path.nameshutil.copy2(archive_path, target_path)run_git(["git", "add", archive_path.name], repo_dir)3 unmodified linesif diff_result.returncode != 1:raise RuntimeError(f"git diff --cached failed for {archive_path.name}")run_git(["git", "commit", "-m", f"Add {archive_path.name}"], repo_dir)run_git(["git", "push", "origin", repo_revision], repo_dir)def cleanup_local_assets(video_ids: Sequence[str],dataset_dir: Path,scratch_dataset_dir: Path | None,raw_video_dir: Path,scratch_raw_video_dir: Path | None,raw_caption_dir: Path,raw_metadata_dir: Path,) -> None:for video_id in video_ids:dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)if dataset_video_dir.exists():shutil.rmtree(dataset_video_dir, ignore_errors=True)for raw_dir in [raw_video_dir, scratch_raw_video_dir]:if raw_dir is None:continuefor path in raw_dir.glob(f"{video_id}.*"):if path.is_file():path.unlink()caption_dir = raw_caption_dir / video_idif caption_dir.exists():shutil.rmtree(caption_dir, ignore_errors=True)metadata_path = raw_metadata_dir / f"{video_id}.json"if metadata_path.exists():metadata_path.unlink(missing_ok=True)def prune_uploaded_runtime_residue(progress: Dict[str, object],dataset_dir: Path,scratch_dataset_dir: Path | None,raw_video_dir: Path,scratch_raw_video_dir: Path | None,raw_caption_dir: Path,raw_metadata_dir: Path,) -> None:uploaded = set(progress.get("uploaded_folders", {}))for video_id in uploaded:for raw_dir in [raw_video_dir, scratch_raw_video_dir]:if raw_dir is None:continuefor path in raw_dir.glob(f"{video_id}.*"):if path.is_file():path.unlink(missing_ok=True)caption_dir = raw_caption_dir / video_idif caption_dir.exists():shutil.rmtree(caption_dir, ignore_errors=True)metadata_path = raw_metadata_dir / f"{video_id}.json"if metadata_path.exists():metadata_path.unlink(missing_ok=True)dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)if dataset_video_dir.exists() and not (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists():shutil.rmtree(dataset_video_dir, ignore_errors=True)9 unmodified linesdef main() -> None:args = parse_args()if args.parallel_shards < 1:raise ValueError('--parallel-shards must be >= 1')if not (0 <= args.shard_index < args.parallel_shards):raise ValueError('--shard-index must satisfy 0 <= shard-index < parallel-shards')if args.start_stagger_max < args.start_stagger_min:raise ValueError('--start-stagger-max must be >= --start-stagger-min')if args.start_stagger_max > 0:delay = random.randint(args.start_stagger_min, args.start_stagger_max)if delay > 0:print(f"[pipeline03] stagger sleep {delay}s shard={args.shard_index}/{args.parallel_shards}", flush=True)time.sleep(delay)print(f"[pipeline03] start upload_mode={args.upload_mode} repo_id={args.repo_id} shard={args.shard_index}/{args.parallel_shards}", flush=True)skip_stats_write = args.skip_stats_write or args.parallel_shards > 1progress = load_progress(args.progress_path)print(f"[pipeline03] loaded progress archives={len(progress.get('archives', {}))} "4 unmodified linesprint(f"[pipeline03] token_present={bool(resolved_token)}", flush=True)api = HfApi(token=resolved_token) if args.upload_mode in {"api", "api-stream"} else Noneargs.dataset_dir.mkdir(parents=True, exist_ok=True)if args.scratch_dataset_dir is not None:args.scratch_dataset_dir.mkdir(parents=True, exist_ok=True)try:if args.upload_mode in {"api", "api-stream"}:1 unmodified linerepo_files = []else:print("[pipeline03] listing repo files via git", flush=True)repo_files = list_repo_files_via_git(args.git_clone_dir, args.repo_id, args.repo_type, args.repo_revision)except Exception as exc:print(f"[pipeline03] repo file listing failed: {exc}", flush=True)traceback.print_exc()repo_files = []while True:with locked_progress(args.progress_path):progress = load_progress(args.progress_path)prune_uploaded_runtime_residue(progress,args.dataset_dir,args.scratch_dataset_dir,args.raw_video_dir,args.scratch_raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)remaining_folder_paths = list_unuploaded_folder_paths(args.dataset_dir, args.scratch_dataset_dir, progress)remaining_folder_paths = filter_folders_for_shard(remaining_folder_paths, args.parallel_shards, args.shard_index)if not remaining_folder_paths:print(f"No unuploaded dataset folders remain for shard {args.shard_index}/{args.parallel_shards}.")breakremaining_count = len(remaining_folder_paths)print(f"[pipeline03] remaining completed folders available={remaining_count} shard={args.shard_index}/{args.parallel_shards}", flush=True)if remaining_count >= args.target_folders:selected_folder_paths = remaining_folder_paths[: args.target_folders]batch = enrich_folder_sizes(selected_folder_paths)batch_names = [name for name, _, _ in batch]batch_bytes = sum(folder_bytes for _, _, folder_bytes in batch)print(f"[pipeline03] folder threshold reached; selecting first {len(batch_names)} folders without global size scan", flush=True)else:remaining_folders = enrich_folder_sizes(remaining_folder_paths)remaining_bytes = total_batchable_bytes(remaining_folders)require_target_bytes = args.require_target_bytes and not args.allow_small_final_batchif require_target_bytes and remaining_bytes < args.target_bytes:print(f"Skip upload: only {format_size(remaining_bytes)} across {remaining_count} completed NPZ folders available, below targets {format_size(args.target_bytes)} or {args.target_folders} folders.")breakbatch = build_batch(remaining_folders, args.target_bytes)batch_names = [name for name, _, _ in batch]batch_bytes = sum(folder_bytes for _, _, folder_bytes in batch)archive_index = next_archive_index(progress, repo_files)archive_name = f"Sign_DWPose_NPZ_{archive_index:06d}.tar"progress["archives"][archive_name] = {"folders": batch_names,"size_bytes": batch_bytes,"status": "uploading","reserved_at": time.strftime("%Y-%m-%d %H:%M:%S"),"shard_index": args.shard_index,"parallel_shards": args.parallel_shards,}save_progress(args.progress_path, progress)archive_root = args.archive_dir if args.upload_mode == "git-ssh" else preferred_temp_archive_dir()archive_path = archive_root / archive_name5 unmodified linesbreakargs.archive_dir.mkdir(parents=True, exist_ok=True)try:apply_status_journal_to_stats(args.stats_npz, args.status_journal_path)except Exception as exc:print(f"Warning: pre-upload status compaction skipped due to: {exc}")append_status_journal(args.status_journal_path,batch_names,4 unmodified lines)try:if args.upload_mode == "api-stream":upload_archive_streaming(api, args.repo_id, args.repo_type, [(name, path) for name, path, _ in batch], archive_name)else:create_tar_archive(archive_path, [(name, path) for name, path, _ in batch])if args.upload_mode == "api":upload_archive(api, args.repo_id, args.repo_type, args.repo_revision, archive_path)else:upload_archive_via_git(args.git_clone_dir, args.repo_id, args.repo_type, args.repo_revision, archive_path)except Exception as exc:with locked_progress(args.progress_path):progress = load_progress(args.progress_path)archive_meta = progress.get("archives", {}).get(archive_name, {})if isinstance(archive_meta, dict):archive_meta["status"] = "failed"archive_meta["last_error"] = str(exc)archive_meta["failed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")progress["archives"][archive_name] = archive_metasave_progress(args.progress_path, progress)update_many_video_stats_best_effort(args.stats_npz,args.status_journal_path,1 unmodified lineupload_status="failed",local_cleanup_status="pending",archive_name=archive_name,skip_stats_write=skip_stats_write,last_error=str(exc),updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)try:apply_status_journal_to_stats(args.stats_npz, args.status_journal_path)except Exception as compact_exc:print(f"Warning: failed-upload compaction skipped due to: {compact_exc}")if archive_path.exists():archive_path.unlink(missing_ok=True)raisewith locked_progress(args.progress_path):progress = load_progress(args.progress_path)progress["archives"][archive_name] = {"folders": batch_names,"size_bytes": batch_bytes,"uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),"status": "uploaded","shard_index": args.shard_index,"parallel_shards": args.parallel_shards,}for folder_name in batch_names:progress["uploaded_folders"][folder_name] = archive_namesave_progress(args.progress_path, progress)repo_files.append(f"dataset/{archive_name}")update_many_video_stats_best_effort(args.stats_npz,args.status_journal_path,batch_names,upload_status="uploaded",local_cleanup_status="pending",archive_name=archive_name,skip_stats_write=skip_stats_write,last_error="",updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)try:apply_status_journal_to_stats(args.stats_npz, args.status_journal_path)except Exception as exc:print(f"Warning: post-upload status compaction skipped due to: {exc}")cleanup_error = ""try:cleanup_local_assets(batch_names,args.dataset_dir,args.scratch_dataset_dir,args.raw_video_dir,args.scratch_raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)1 unmodified linearchive_path.unlink(missing_ok=True)except Exception as exc:cleanup_error = str(exc)update_many_video_stats_best_effort(args.stats_npz,args.status_journal_path,1 unmodified lineupload_status="uploaded",local_cleanup_status="deleted" if not cleanup_error else "failed",archive_name=archive_name,skip_stats_write=skip_stats_write,last_error=cleanup_error,updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)try:apply_status_journal_to_stats(args.stats_npz, args.status_journal_path)except Exception as exc:print(f"Warning: post-cleanup status compaction skipped due to: {exc}")upload_runtime_state_files(api, args.repo_id, args.repo_type, args.repo_revision, args.progress_path, args.status_journal_path, args.stats_npz, args.processed_csv_path if hasattr(args, "processed_csv_path") else None)with locked_progress(args.progress_path):progress = load_progress(args.progress_path)prune_uploaded_runtime_residue(progress,args.dataset_dir,args.scratch_dataset_dir,args.raw_video_dir,args.scratch_raw_video_dir,args.raw_caption_dir,args.raw_metadata_dir,)if cleanup_error:raise RuntimeError(f"Uploaded {archive_name} but local cleanup failed: {cleanup_error}")print(f"Uploaded {archive_name} and cleaned raw assets for {len(batch_names)} videos. shard={args.shard_index}/{args.parallel_shards}")if __name__ == "__main__":
3 unmodified lines456789101112131415161 unmodified line18192021222310 unmodified lines3435363738394041424322 unmodified lines6667686970717216 unmodified lines8990919293949596973 unmodified lines10110210310410510610710810911011111211311411511611711811912012112212393 unmodified lines2172182192202212222232242258 unmodified lines2342352362372382392402412422432442452462472482494 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812821 unmodified line28428528628728828929017 unmodified lines3083093103113123136 unmodified lines32032132232332432513 unmodified lines3393403413423433443 unmodified linesimport argparseimport csvimport jsonimport reimport subprocessfrom collections import Counterfrom pathlib import PathVIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov'}ARRAY_RANGE_RE = re.compile(r'^(\d+)_(\[(.+)\])$')PROCESSED_REQUIRED_COLUMNS = {'video_id','download_status',1 unmodified line'upload_status','archive_name',}def run_command(cmd: list[str]) -> str:10 unmodified linesreturn sum(1 for _ in directory.glob('*.claim'))def count_complete(dataset_dir: Path) -> int:if not dataset_dir.exists():return 0return sum(1 for _ in dataset_dir.glob('*/npz/.complete'))def sum_file_sizes(paths: list[Path]) -> int:22 unmodified linesm = ARRAY_RANGE_RE.match(jobid_token)if not m:return 1body = m.group(3)if '%' in body:body = body.split('%', 1)[0]total = 016 unmodified linesoutput = run_command(['squeue', '-u', username, '-h', '-o', '%i|%j|%T|%P'])job_counts: Counter[str] = Counter()partition_counts: Counter[str] = Counter()running_dwpose = 0running_download = 0pending_download = 0if output:for line in output.splitlines():parts = line.split('|')3 unmodified linescount = expand_task_count(jobid_token)job_counts[f'{job}|{state}'] += countpartition_counts[f'{job}|{partition}|{state}'] += countif job == 'dwpose' and state == 'RUNNING':running_dwpose += countif job == 'download' and state == 'RUNNING':running_download += countif job == 'download' and state in {'PENDING', 'CONFIGURING'}:pending_download += counttotal_download = running_download + pending_downloadreturn {'running_dwpose': running_dwpose,'running_download': running_download,'pending_download_jobs': pending_download,'total_download_jobs': total_download,'job_state_counts': dict(job_counts),'job_partition_state_counts': dict(partition_counts),}def filesystem_avail_bytes(path: Path) -> int:try:proc = subprocess.run(['df', '-B1', str(path)], check=False, capture_output=True, text=True)93 unmodified lines'--source-metadata-csv', str(runtime_root / 'SignVerse-2M-metadata_ori.csv'),'--output-metadata-csv', str(runtime_root / 'SignVerse-2M-metadata_processed.csv'),'--raw-video-dir', str(runtime_root / 'raw_video'),'--raw-caption-dir', str(runtime_root / 'raw_caption'),'--raw-metadata-dir', str(runtime_root / 'raw_metadata'),'--dataset-dir', str(runtime_root / 'dataset'),'--progress-path', str(runtime_root / 'archive_upload_progress.json'),'--status-journal-path', str(runtime_root / 'upload_status_journal.jsonl'),]8 unmodified linesdef main() -> None:parser = argparse.ArgumentParser(description='Report Sign-DWPose runtime status.')parser.add_argument('--runtime-root', default='/home/sf895/SignVerse-2M-runtime')parser.add_argument('--username', default='sf895')parser.add_argument('--no-sync', action='store_true')parser.add_argument('--json', action='store_true')args = parser.parse_args()runtime_root = Path(args.runtime_root)raw_dir = runtime_root / 'raw_video'dataset_dir = runtime_root / 'dataset'claims_dir = runtime_root / 'slurm' / 'state' / 'claims'download_claims_dir = runtime_root / 'slurm' / 'state' / 'download_claims'progress_path = runtime_root / 'archive_upload_progress.json'4 unmodified linesif not args.no_sync:sync_result = run_sync(runtime_root)raw_complete: list[Path] = []raw_temp: list[Path] = []if raw_dir.exists():for path in raw_dir.iterdir():if not path.is_file():continueif path.suffix.lower() in VIDEO_EXTS:raw_complete.append(path)else:raw_temp.append(path)raw_size = sum_file_sizes(raw_complete)runtime_size = 0if runtime_root.exists():for path in runtime_root.rglob('*'):try:if path.is_file():runtime_size += path.stat().st_sizeexcept FileNotFoundError:continuesource_rows = read_source_manifest_count(source_csv)progress = read_processed_progress(processed_csv)payload = {'sync_result': sync_result,1 unmodified line'raw_videos': len(raw_complete),'raw_temp_files': len(raw_temp),'sent_to_gpu': count_claims(claims_dir),'processed_complete': count_complete(dataset_dir),'active_downloads': count_claims(download_claims_dir),'uploaded_archives': 0,'uploaded_folders': 0,17 unmodified linespayload['uploaded_archives'] = uploaded_archivespayload['uploaded_folders'] = uploaded_folderspayload.update(queue_status(args.username))payload['csv_row_match'] = (payload['processed_rows'] == payload['source_rows']) if payload['csv_ok'] else Falseif args.json:6 unmodified linesprint(f"raw_temp_files={payload['raw_temp_files']}")print(f"sent_to_gpu={payload['sent_to_gpu']}")print(f"running_dwpose={payload['running_dwpose']}")print(f"processed_complete={payload['processed_complete']}")print(f"active_downloads={payload['active_downloads']}")print(f"running_download_jobs={payload['running_download']}")13 unmodified linesprint(f"process_ok_rows={payload['process_ok_rows']}")print(f"process_running_rows={payload['process_running_rows']}")print(f"upload_uploaded_rows={payload['upload_uploaded_rows']}")print(f"raw_size={human_bytes(payload['raw_size_bytes'])}")print(f"runtime_size={human_bytes(payload['runtime_size_bytes'])}")print(f"filesystem_avail={human_bytes(payload['filesystem_avail_bytes'])}")3 unmodified lines456789101112131415161718191 unmodified line212223242526272810 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757622 unmodified lines9910010110210310410516 unmodified lines1221231241251261271281291301311323 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421593 unmodified lines3093103113123133143153163173183198 unmodified lines3283293303313323333343353363373383393403413423433443453463473483494 unmodified lines3543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843851 unmodified line38738838939039139239317 unmodified lines4114124134144154164174184194204214224234244254264274284294304314326 unmodified lines43944044144244344444544644744844945045145245345413 unmodified lines4684694704714724734744754764774784794804813 unmodified linesimport argparseimport csvimport jsonimport osimport reimport subprocessfrom collections import Counterfrom pathlib import Pathfrom utils.dataset_pool import count_completeVIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov'}ARRAY_RANGE_RE = re.compile(r'^(\d+)_\[(.+)\]$')PROCESSED_REQUIRED_COLUMNS = {'video_id','download_status',1 unmodified line'upload_status','archive_name',}GPU_PARTITIONS = ['gpu', 'gpu-redhat', 'cgpu']DEFAULT_VIDEOS_PER_DWPOSE_JOB = 20def run_command(cmd: list[str]) -> str:10 unmodified linesreturn sum(1 for _ in directory.glob('*.claim'))def aggregate_claims_by_job_key(directory: Path) -> dict[str, int]:counts: Counter[str] = Counter()if not directory.exists():return {}for path in directory.glob('*.claim'):try:lines = path.read_text(encoding='utf-8').splitlines()except OSError:continuejob_key = ''for line in lines:if line.startswith('job_key='):job_key = line.split('=', 1)[1].strip()breakif job_key:counts[job_key] += 1return dict(counts)def read_videos_per_dwpose_job(root_dir: Path) -> int:worker = root_dir / 'slurm' / 'process_dwpose_array.slurm'if not worker.exists():return DEFAULT_VIDEOS_PER_DWPOSE_JOBtry:for line in worker.read_text().splitlines():if line.startswith('VIDEOS_PER_JOB='):m = re.search(r'\$\{VIDEOS_PER_JOB:-([0-9]+)\}', line)if m:return int(m.group(1))except Exception:passreturn DEFAULT_VIDEOS_PER_DWPOSE_JOBdef sum_file_sizes(paths: list[Path]) -> int:22 unmodified linesm = ARRAY_RANGE_RE.match(jobid_token)if not m:return 1body = m.group(2)if '%' in body:body = body.split('%', 1)[0]total = 016 unmodified linesoutput = run_command(['squeue', '-u', username, '-h', '-o', '%i|%j|%T|%P'])job_counts: Counter[str] = Counter()partition_counts: Counter[str] = Counter()active_tasks_by_partition: Counter[str] = Counter()running_dwpose = 0running_download = 0pending_download = 0pending_dwpose = 0if output:for line in output.splitlines():parts = line.split('|')3 unmodified linescount = expand_task_count(jobid_token)job_counts[f'{job}|{state}'] += countpartition_counts[f'{job}|{partition}|{state}'] += countif state in {'RUNNING', 'PENDING', 'CONFIGURING'}:active_tasks_by_partition[partition] += countif job == 'dwpose' and state == 'RUNNING':running_dwpose += countif job == 'download' and state == 'RUNNING':running_download += countif job == 'download' and state in {'PENDING', 'CONFIGURING'}:pending_download += countif job == 'dwpose' and state in {'PENDING', 'CONFIGURING'}:pending_dwpose += counttotal_download = running_download + pending_downloadreturn {'running_dwpose': running_dwpose,'running_download': running_download,'pending_dwpose_jobs': pending_dwpose,'pending_download_jobs': pending_download,'total_download_jobs': total_download,'job_state_counts': dict(job_counts),'job_partition_state_counts': dict(partition_counts),'active_tasks_by_partition': dict(active_tasks_by_partition),}def gpu_partition_capacity(partitions: list[str], active_tasks_by_partition: dict[str, int]) -> list[dict[str, object]]:qos_limit_by_part: dict[str, int] = {}qos_output = run_command(['sacctmgr', 'show', 'qos', 'format=Name,MaxSubmitPU', '-P'])if qos_output:for line in qos_output.splitlines():if not line.strip() or '|' not in line:continuename, max_submit = line.split('|', 1)name = name.strip()max_submit = max_submit.strip()if name in partitions and max_submit:try:qos_limit_by_part[name] = int(max_submit)except ValueError:passrows: list[dict[str, object]] = []for partition in partitions:free_gpus = 0nodes_output = run_command(['sinfo', '-h', '-N', '-p', partition, '-o', '%N'])nodes = [line.strip() for line in nodes_output.splitlines() if line.strip()]for node in nodes:node_line = run_command(['scontrol', 'show', 'node', node, '-o'])if not node_line:continuestate_m = re.search(r'\bState=([^ ]+)', node_line)state = state_m.group(1).lower() if state_m else ''if any(flag in state for flag in ('drain', 'drained', 'down', 'fail', 'inval')):continuecfg_m = re.search(r'\bCfgTRES=.*?(?:,|^)gres/gpu=(\d+)', node_line)alloc_m = re.search(r'\bAllocTRES=.*?(?:,|^)gres/gpu=(\d+)', node_line)total = int(cfg_m.group(1)) if cfg_m else 0used = int(alloc_m.group(1)) if alloc_m else 0free = total - usedif free > 0:free_gpus += freeactive_tasks = int(active_tasks_by_partition.get(partition, 0))qos_limit = qos_limit_by_part.get(partition)submit_slots = free_gpusif qos_limit is not None:submit_slots = min(submit_slots, max(0, qos_limit - active_tasks))rows.append({'partition': partition,'free_gpus': free_gpus,'active_tasks': active_tasks,'qos_limit': qos_limit,'submit_slots': submit_slots,})return rowsdef filesystem_avail_bytes(path: Path) -> int:try:proc = subprocess.run(['df', '-B1', str(path)], check=False, capture_output=True, text=True)93 unmodified lines'--source-metadata-csv', str(runtime_root / 'SignVerse-2M-metadata_ori.csv'),'--output-metadata-csv', str(runtime_root / 'SignVerse-2M-metadata_processed.csv'),'--raw-video-dir', str(runtime_root / 'raw_video'),'--scratch-raw-video-dir', str(Path(f'/scratch/{os.environ.get("USER", "sf895")}/SignVerse-2M-runtime/raw_video')),'--raw-caption-dir', str(runtime_root / 'raw_caption'),'--raw-metadata-dir', str(runtime_root / 'raw_metadata'),'--dataset-dir', str(runtime_root / 'dataset'),'--scratch-dataset-dir', str(Path(f'/scratch/{os.environ.get("USER", "sf895")}/SignVerse-2M-runtime/dataset')),'--progress-path', str(runtime_root / 'archive_upload_progress.json'),'--status-journal-path', str(runtime_root / 'upload_status_journal.jsonl'),]8 unmodified linesdef main() -> None:parser = argparse.ArgumentParser(description='Report SignVerse runtime status.')parser.add_argument('--runtime-root', default='/home/sf895/SignVerse-2M-runtime')parser.add_argument('--username', default='sf895')parser.add_argument('--no-sync', action='store_true')parser.add_argument('--json', action='store_true')parser.add_argument('--include-partitions', action='store_true')parser.add_argument('--scan-complete', action='store_true')parser.add_argument('--scan-runtime-size', action='store_true')args = parser.parse_args()runtime_root = Path(args.runtime_root)root_dir = Path('/cache/home/sf895/SignVerse-2M')raw_dir = runtime_root / 'raw_video'scratch_raw_dir = Path(f'/scratch/{os.environ.get("USER", "sf895")}/SignVerse-2M-runtime/raw_video')dataset_dir = runtime_root / 'dataset'scratch_dataset_dir = Path(f'/scratch/{os.environ.get("USER", "sf895")}/SignVerse-2M-runtime/dataset')claims_dir = runtime_root / 'slurm' / 'state' / 'claims'download_claims_dir = runtime_root / 'slurm' / 'state' / 'download_claims'progress_path = runtime_root / 'archive_upload_progress.json'4 unmodified linesif not args.no_sync:sync_result = run_sync(runtime_root)raw_complete: dict[str, Path] = {}raw_temp: list[Path] = []for current_raw_dir in [raw_dir, scratch_raw_dir]:if not current_raw_dir.exists():continuefor path in current_raw_dir.iterdir():if not path.is_file():continueif path.suffix.lower() in VIDEO_EXTS:raw_complete.setdefault(path.stem, path)else:raw_temp.append(path)raw_size = sum_file_sizes(list(raw_complete.values()))runtime_size = 0if runtime_root.exists():proc = subprocess.run(['du', '-sb', str(runtime_root)], check=False, capture_output=True, text=True)if proc.returncode == 0 and proc.stdout.strip():try:runtime_size = int(proc.stdout.split()[0])except Exception:runtime_size = 0source_rows = read_source_manifest_count(source_csv)progress = read_processed_progress(processed_csv)videos_per_dwpose_job = read_videos_per_dwpose_job(root_dir)payload = {'sync_result': sync_result,1 unmodified line'raw_videos': len(raw_complete),'raw_temp_files': len(raw_temp),'sent_to_gpu': count_claims(claims_dir),'processed_complete': count_complete(dataset_dir, scratch_dataset_dir),'active_downloads': count_claims(download_claims_dir),'uploaded_archives': 0,'uploaded_folders': 0,17 unmodified linespayload['uploaded_archives'] = uploaded_archivespayload['uploaded_folders'] = uploaded_folderspayload.update(queue_status(args.username))process_claims_by_job = aggregate_claims_by_job_key(claims_dir)payload['videos_per_dwpose_job'] = videos_per_dwpose_jobpayload['process_claim_job_keys'] = len(process_claims_by_job)payload['process_claim_videos_actual'] = sum(process_claims_by_job.values())payload['process_claim_videos_max_per_job'] = max(process_claims_by_job.values(), default=0)payload['running_dwpose_jobs'] = payload['running_dwpose']payload['running_dwpose_videos_estimated'] = payload['running_dwpose'] * videos_per_dwpose_jobpayload['pending_dwpose_videos_estimated'] = payload['pending_dwpose_jobs'] * videos_per_dwpose_jobpayload['total_dwpose_jobs'] = payload['running_dwpose'] + payload['pending_dwpose_jobs']payload['total_dwpose_videos_estimated'] = payload['running_dwpose_videos_estimated'] + payload['pending_dwpose_videos_estimated']if args.include_partitions:payload['gpu_partition_capacity'] = gpu_partition_capacity(GPU_PARTITIONS, payload.get('active_tasks_by_partition', {}))else:payload['gpu_partition_capacity'] = []payload['job_partition_state_counts'] = {}payload['active_tasks_by_partition'] = {}payload['csv_row_match'] = (payload['processed_rows'] == payload['source_rows']) if payload['csv_ok'] else Falseif args.json:6 unmodified linesprint(f"raw_temp_files={payload['raw_temp_files']}")print(f"sent_to_gpu={payload['sent_to_gpu']}")print(f"running_dwpose={payload['running_dwpose']}")print(f"running_dwpose_jobs={payload['running_dwpose_jobs']}")print(f"pending_dwpose_jobs={payload['pending_dwpose_jobs']}")print(f"total_dwpose_jobs={payload['total_dwpose_jobs']}")print(f"videos_per_dwpose_job={payload['videos_per_dwpose_job']}")print(f"process_claim_job_keys={payload['process_claim_job_keys']}")print(f"process_claim_videos_actual={payload['process_claim_videos_actual']}")print(f"process_claim_videos_max_per_job={payload['process_claim_videos_max_per_job']}")print(f"running_dwpose_videos_estimated={payload['running_dwpose_videos_estimated']}")print(f"pending_dwpose_videos_estimated={payload['pending_dwpose_videos_estimated']}")print(f"total_dwpose_videos_estimated={payload['total_dwpose_videos_estimated']}")print(f"processed_complete={payload['processed_complete']}")print(f"active_downloads={payload['active_downloads']}")print(f"running_download_jobs={payload['running_download']}")13 unmodified linesprint(f"process_ok_rows={payload['process_ok_rows']}")print(f"process_running_rows={payload['process_running_rows']}")print(f"upload_uploaded_rows={payload['upload_uploaded_rows']}")for key in sorted(payload.get('job_partition_state_counts', {})):print(f"job_partition_state[{key}]={payload['job_partition_state_counts'][key]}")for row in payload.get('gpu_partition_capacity', []):qos_limit = row['qos_limit'] if row['qos_limit'] is not None else 'na'print(f"gpu_partition[{row['partition']}]=free_gpus={row['free_gpus']},"f"active_tasks={row['active_tasks']},qos_limit={qos_limit},submit_slots={row['submit_slots']}")print(f"raw_size={human_bytes(payload['raw_size_bytes'])}")print(f"runtime_size={human_bytes(payload['runtime_size_bytes'])}")print(f"filesystem_avail={human_bytes(payload['filesystem_avail_bytes'])}")
34 unmodified lines35363738394063 unmodified lines10410510610710810911011111218 unmodified lines13113213313413513613713813934 unmodified linesVIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov'}def read_csv_rows(path: Path) -> Tuple[List[Dict[str, str]], List[str]]:text = path.read_text(encoding='utf-8-sig')lines = [line for line in text.splitlines() if line.strip()]63 unmodified linesap.add_argument('--source-metadata-csv', type=Path, required=True)ap.add_argument('--output-metadata-csv', type=Path, required=True)ap.add_argument('--raw-video-dir', type=Path, required=True)ap.add_argument('--raw-caption-dir', type=Path, required=True)ap.add_argument('--raw-metadata-dir', type=Path, required=True)ap.add_argument('--dataset-dir', type=Path, required=True)ap.add_argument('--progress-path', type=Path, required=True)ap.add_argument('--status-journal-path', type=Path, required=True)args = ap.parse_args()18 unmodified linesmerged[k] = out_by_id[vid].get(k, '')rows.append(merged)raw_videos = {p.stem: p for p in args.raw_video_dir.iterdir() if p.is_file() and p.suffix.lower() in VIDEO_EXTS} if args.raw_video_dir.exists() else {}raw_metadata = {p.stem: p for p in args.raw_metadata_dir.glob('*.json')} if args.raw_metadata_dir.exists() else {}complete = {p.parent.parent.name for p in args.dataset_dir.glob('*/npz/.complete')} if args.dataset_dir.exists() else set()process_claims_dir = args.dataset_dir.parent / 'slurm' / 'state' / 'claims'download_claims_dir = args.dataset_dir.parent / 'slurm' / 'state' / 'download_claims'process_claims = {p.stem for p in process_claims_dir.glob('*.claim')} if process_claims_dir.exists() else set()34 unmodified lines35363738394041424363 unmodified lines10710810911011111211311411511611718 unmodified lines13613713813914014114214314414514614714814915034 unmodified linesVIDEO_EXTS = {'.mp4', '.mkv', '.webm', '.mov'}from utils.dataset_pool import complete_video_idsdef read_csv_rows(path: Path) -> Tuple[List[Dict[str, str]], List[str]]:text = path.read_text(encoding='utf-8-sig')lines = [line for line in text.splitlines() if line.strip()]63 unmodified linesap.add_argument('--source-metadata-csv', type=Path, required=True)ap.add_argument('--output-metadata-csv', type=Path, required=True)ap.add_argument('--raw-video-dir', type=Path, required=True)ap.add_argument('--scratch-raw-video-dir', type=Path, default=None)ap.add_argument('--raw-caption-dir', type=Path, required=True)ap.add_argument('--raw-metadata-dir', type=Path, required=True)ap.add_argument('--dataset-dir', type=Path, required=True)ap.add_argument('--scratch-dataset-dir', type=Path, default=None)ap.add_argument('--progress-path', type=Path, required=True)ap.add_argument('--status-journal-path', type=Path, required=True)args = ap.parse_args()18 unmodified linesmerged[k] = out_by_id[vid].get(k, '')rows.append(merged)raw_videos = {}if args.raw_video_dir.exists():raw_videos.update({p.stem: p for p in args.raw_video_dir.iterdir() if p.is_file() and p.suffix.lower() in VIDEO_EXTS})if args.scratch_raw_video_dir is not None and args.scratch_raw_video_dir.exists():for p in args.scratch_raw_video_dir.iterdir():if p.is_file() and p.suffix.lower() in VIDEO_EXTS and p.stem not in raw_videos:raw_videos[p.stem] = praw_metadata = {p.stem: p for p in args.raw_metadata_dir.glob('*.json')} if args.raw_metadata_dir.exists() else {}complete = complete_video_ids(args.dataset_dir, args.scratch_dataset_dir)process_claims_dir = args.dataset_dir.parent / 'slurm' / 'state' / 'claims'download_claims_dir = args.dataset_dir.parent / 'slurm' / 'state' / 'download_claims'process_claims = {p.stem for p in process_claims_dir.glob('*.claim')} if process_claims_dir.exists() else set()
5 unmodified lines6789101112131415161718192021222324252627282930317 unmodified lines39404142434445464714 unmodified lines626364656667686 unmodified lines7576777879805 unmodified lines868788899091925 unmodified lines98991001011021031045 unmodified lines#SBATCH --cpus-per-task=1#SBATCH --mem=512M#SBATCH --time=12:30:00#SBATCH --output=/home/sf895/SignVerse-2M-runtime/slurm/logs/orchestrator_launcher_%j.out#SBATCH --error=/home/sf895/SignVerse-2M-runtime/slurm/logs/orchestrator_launcher_%j.errset -euo pipefailROOT_DIR="${ROOT_DIR:-/cache/home/sf895/SignVerse-2M}"RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"ORCH_SUBMIT_SCRIPT="${ORCH_SUBMIT_SCRIPT:-$ROOT_DIR/reproduce_independently_slurm.sh}"STOP_FILE="${STOP_FILE:-$RUNTIME_ROOT/STOP_AUTORESTART}"ROTATE_SECONDS="${ROTATE_SECONDS:-43200}"CHECK_INTERVAL_SECONDS="${CHECK_INTERVAL_SECONDS:-60}"ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"LAUNCHER_SCRIPT="${LAUNCHER_SCRIPT:-$(readlink -f "$0")}"LAUNCHER_PARTITION="${LAUNCHER_PARTITION:-main}"LAUNCHER_ACCOUNT="${LAUNCHER_ACCOUNT:-}"LAUNCHER_TIME="${LAUNCHER_TIME:-12:30:00}"LAUNCHER_CPUS_PER_TASK="${LAUNCHER_CPUS_PER_TASK:-1}"LAUNCHER_MEM="${LAUNCHER_MEM:-512M}"mkdir -p "$RUNTIME_ROOT/slurm/logs"now_ts() {date '+%Y-%m-%d %H:%M:%S'7 unmodified linessqueue -u "$USER" -h -o '%A|%j|%T' | awk -F'|' '$2=="sign-dwpose-orch" && ($3=="RUNNING" || $3=="PENDING" || $3=="CONFIGURING") {print $1}'}submit_orchestrator() {log "submitting orchestration with ORCHESTRATOR_TIME=$ORCHESTRATOR_TIME"env -u SLURM_JOB_ID -u SLURM_JOB_NAME -u SLURM_JOB_NODELIST -u SLURM_ARRAY_JOB_ID -u SLURM_ARRAY_TASK_ID ORCHESTRATOR_TIME="$ORCHESTRATOR_TIME" bash "$ORCH_SUBMIT_SCRIPT"}cancel_orchestrators() {14 unmodified linesif [[ -n "$LAUNCHER_ACCOUNT" ]]; thencmd+=("--account=$LAUNCHER_ACCOUNT")ficmd+=("--export=ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,ORCH_SUBMIT_SCRIPT=$ORCH_SUBMIT_SCRIPT,STOP_FILE=$STOP_FILE,ROTATE_SECONDS=$ROTATE_SECONDS,CHECK_INTERVAL_SECONDS=$CHECK_INTERVAL_SECONDS,ORCHESTRATOR_TIME=$ORCHESTRATOR_TIME,LAUNCHER_SCRIPT=$LAUNCHER_SCRIPT,LAUNCHER_PARTITION=$LAUNCHER_PARTITION,LAUNCHER_ACCOUNT=$LAUNCHER_ACCOUNT,LAUNCHER_TIME=$LAUNCHER_TIME,LAUNCHER_CPUS_PER_TASK=$LAUNCHER_CPUS_PER_TASK,LAUNCHER_MEM=$LAUNCHER_MEM")cmd+=("$LAUNCHER_SCRIPT")log "submitting next launcher""${cmd[@]}"6 unmodified linesfiif [[ -z "$(current_orchestrator_ids || true)" ]]; thensubmit_orchestratorelselog "existing orchestration detected; not submitting a duplicate"5 unmodified linesexit 0fiif [[ -z "$(current_orchestrator_ids || true)" ]]; thenlog "no live orchestration detected; submitting a replacement"submit_orchestratorfisleep "$CHECK_INTERVAL_SECONDS"5 unmodified linesexit 0filog "rotation boundary reached; restarting orchestration and handing off to next launcher"cancel_orchestratorssleep 5submit_orchestrator5 unmodified lines6789101112131415161718192021222324252627282930313233347 unmodified lines4243444546474849505152535455565758596061626364656667686970717273747514 unmodified lines909192939495966 unmodified lines1031041051061071081095 unmodified lines1151161171181191201211225 unmodified lines1281291301311321331341355 unmodified lines#SBATCH --cpus-per-task=1#SBATCH --mem=512M#SBATCH --time=12:30:00#SBATCH --output=/scratch/%u/SignVerse-2M-runtime/slurm/logs/orchestrator_launcher_%j.out#SBATCH --error=/scratch/%u/SignVerse-2M-runtime/slurm/logs/orchestrator_launcher_%j.errset -euo pipefailROOT_DIR="${ROOT_DIR:-/cache/home/sf895/SignVerse-2M}"RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"RUNTIME_LOG_ROOT="${RUNTIME_LOG_ROOT:-/scratch/$USER/SignVerse-2M-runtime/slurm/logs}"ORCH_SUBMIT_SCRIPT="${ORCH_SUBMIT_SCRIPT:-$ROOT_DIR/reproduce_independently_slurm.sh}"STOP_FILE="${STOP_FILE:-$RUNTIME_ROOT/STOP_AUTORESTART}"ROTATE_SECONDS="${ROTATE_SECONDS:-43200}"CHECK_INTERVAL_SECONDS="${CHECK_INTERVAL_SECONDS:-60}"ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"LAUNCHER_SCRIPT="${LAUNCHER_SCRIPT:-$ROOT_DIR/slurm/orchestrator_autorestart.slurm}"LAUNCHER_PARTITION="${LAUNCHER_PARTITION:-main}"LAUNCHER_ACCOUNT="${LAUNCHER_ACCOUNT:-}"LAUNCHER_TIME="${LAUNCHER_TIME:-12:30:00}"LAUNCHER_CPUS_PER_TASK="${LAUNCHER_CPUS_PER_TASK:-1}"LAUNCHER_MEM="${LAUNCHER_MEM:-512M}"REAP_PENDING_ON_ROTATE="${REAP_PENDING_ON_ROTATE:-1}"REAP_JOB_NAMES="${REAP_JOB_NAMES:-dwpose download}"mkdir -p "$RUNTIME_ROOT/slurm/logs" "$RUNTIME_LOG_ROOT"now_ts() {date '+%Y-%m-%d %H:%M:%S'7 unmodified linessqueue -u "$USER" -h -o '%A|%j|%T' | awk -F'|' '$2=="sign-dwpose-orch" && ($3=="RUNNING" || $3=="PENDING" || $3=="CONFIGURING") {print $1}'}current_reapable_pending_ids() {local names_regexnames_regex="$(printf '%s\n' $REAP_JOB_NAMES | paste -sd'|' -)"squeue -u "$USER" -h -o '%A|%j|%T' | awk -F'|' -v names_re="$names_regex" '$2 ~ ("^(" names_re ")$") && $3=="PENDING" {print $1}' | sort -u}cancel_reapable_pending_jobs() {[[ "$REAP_PENDING_ON_ROTATE" == "1" ]] || return 0local idsids="$(current_reapable_pending_ids || true)"if [[ -n "$ids" ]]; thenlog "cancelling stale pending worker jobs: $(echo "$ids" | tr '\n' ' ')"scancel $ids || trueelselog "no stale pending worker jobs to cancel"fi}submit_orchestrator() {log "submitting orchestration with ORCHESTRATOR_TIME=$ORCHESTRATOR_TIME"env \-u SLURM_JOB_ID \-u SLURM_JOB_NAME \-u SLURM_JOB_NODELIST \-u SLURM_ARRAY_JOB_ID \-u SLURM_ARRAY_TASK_ID \ORCHESTRATOR_TIME="$ORCHESTRATOR_TIME" \bash "$ORCH_SUBMIT_SCRIPT"}cancel_orchestrators() {14 unmodified linesif [[ -n "$LAUNCHER_ACCOUNT" ]]; thencmd+=("--account=$LAUNCHER_ACCOUNT")ficmd+=("--export=ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,RUNTIME_LOG_ROOT=$RUNTIME_LOG_ROOT,ORCH_SUBMIT_SCRIPT=$ORCH_SUBMIT_SCRIPT,STOP_FILE=$STOP_FILE,ROTATE_SECONDS=$ROTATE_SECONDS,CHECK_INTERVAL_SECONDS=$CHECK_INTERVAL_SECONDS,ORCHESTRATOR_TIME=$ORCHESTRATOR_TIME,LAUNCHER_SCRIPT=$LAUNCHER_SCRIPT,LAUNCHER_PARTITION=$LAUNCHER_PARTITION,LAUNCHER_ACCOUNT=$LAUNCHER_ACCOUNT,LAUNCHER_TIME=$LAUNCHER_TIME,LAUNCHER_CPUS_PER_TASK=$LAUNCHER_CPUS_PER_TASK,LAUNCHER_MEM=$LAUNCHER_MEM,REAP_PENDING_ON_ROTATE=$REAP_PENDING_ON_ROTATE,REAP_JOB_NAMES=$REAP_JOB_NAMES")cmd+=("$LAUNCHER_SCRIPT")log "submitting next launcher""${cmd[@]}"6 unmodified linesfiif [[ -z "$(current_orchestrator_ids || true)" ]]; thencancel_reapable_pending_jobssubmit_orchestratorelselog "existing orchestration detected; not submitting a duplicate"5 unmodified linesexit 0fiif [[ -z "$(current_orchestrator_ids || true)" ]]; thenlog "no live orchestration detected; reaping old pending workers before replacement"cancel_reapable_pending_jobssubmit_orchestratorfisleep "$CHECK_INTERVAL_SECONDS"5 unmodified linesexit 0filog "rotation boundary reached; reaping old pending workers and restarting orchestration"cancel_reapable_pending_jobscancel_orchestratorssleep 5submit_orchestrator
17 unmodified lines1819202122232425262756 unmodified lines8485868788899091929317 unmodified linesSOURCE_METADATA_CSV="${SOURCE_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_ori.csv}"OUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PIPELINE01="${PIPELINE01:-$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py}"DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$STATE_ROOT/SignVerse-2M-metadata_processed.csv.lock}"56 unmodified lines--source-metadata-csv "$SOURCE_METADATA_CSV"--output-metadata-csv "$OUTPUT_METADATA_CSV"--raw-video-dir "$RAW_VIDEO_DIR"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--dataset-dir "$DATASET_DIR"--stats-npz "$STATS_NPZ"--csv-lock-path "$DOWNLOAD_CSV_LOCK_PATH"--limit 1--video-ids="$VIDEO_ID"17 unmodified lines181920212223242526272829303156 unmodified lines88899091929394959697989910010117 unmodified linesSOURCE_METADATA_CSV="${SOURCE_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_ori.csv}"OUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"HOME_RAW_VIDEO_LIMIT="${HOME_RAW_VIDEO_LIMIT:-180}"SCRATCH_RAW_VIDEO_LIMIT="${SCRATCH_RAW_VIDEO_LIMIT:-2800}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"STATUS_JOURNAL_PATH="${STATUS_JOURNAL_PATH:-$RUNTIME_ROOT/upload_status_journal.jsonl}"PIPELINE01="${PIPELINE01:-$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py}"DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$STATE_ROOT/SignVerse-2M-metadata_processed.csv.lock}"56 unmodified lines--source-metadata-csv "$SOURCE_METADATA_CSV"--output-metadata-csv "$OUTPUT_METADATA_CSV"--raw-video-dir "$RAW_VIDEO_DIR"--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR"--home-raw-video-limit "$HOME_RAW_VIDEO_LIMIT"--scratch-raw-video-limit "$SCRATCH_RAW_VIDEO_LIMIT"--raw-caption-dir "$RAW_CAPTION_DIR"--raw-metadata-dir "$RAW_METADATA_DIR"--dataset-dir "$DATASET_DIR"--stats-npz "$STATS_NPZ"--status-journal-path "$STATUS_JOURNAL_PATH"--csv-lock-path "$DOWNLOAD_CSV_LOCK_PATH"--limit 1--video-ids="$VIDEO_ID"
14 unmodified lines151617181920212223242 unmodified lines27282930313213 unmodified lines46474849505152535455565758596061626364656667686918 unmodified lines88899091929394959697983 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513616 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519614 unmodified linesRUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"STATE_ROOT="${STATE_ROOT:-/home/sf895/SignVerse-2M-runtime}"CONDA_SH="${CONDA_SH:-/home/sf895/miniconda3/etc/profile.d/conda.sh}"CONDA_ENV="${CONDA_ENV:-dwpose}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PIPELINE02="${PIPELINE02:-$ROOT_DIR/scripts/pipeline02_extract_dwpose_from_video.py}"FPS="${FPS:-24}"TMP_ROOT="${TMP_ROOT:-${SLURM_TMPDIR:-/tmp}}"2 unmodified linesCLAIM_DIR="${CLAIM_DIR:-$STATE_ROOT/slurm/state/claims}"RETRY_DIR="${RETRY_DIR:-$STATE_ROOT/slurm/state/gpu_init_retries}"MAX_GPU_INIT_RETRIES="${MAX_GPU_INIT_RETRIES:-3}"MANIFEST="${MANIFEST:-${1:-}}"if [[ -z "$MANIFEST" ]]; then13 unmodified linesexit 1fiVIDEO_ID="$(sed -n "$((SLURM_ARRAY_TASK_ID + 1))p" "$MANIFEST")"if [[ -z "$VIDEO_ID" ]]; thenecho "No video id found for task index ${SLURM_ARRAY_TASK_ID} in manifest $MANIFEST" >&2exit 1fimkdir -p "$CLAIM_DIR" "$RETRY_DIR"CLAIM_PATH="$CLAIM_DIR/${VIDEO_ID}.claim"RETRY_STATE_PATH="$RETRY_DIR/${VIDEO_ID}.state"cleanup_claim() {rm -f "$CLAIM_PATH"}trap cleanup_claim EXITexport OMP_NUM_THREADS="${SLURM_CPUS_PER_TASK:-1}"export MKL_NUM_THREADS="${SLURM_CPUS_PER_TASK:-1}"echo "[$(date '+%F %T')] job=${SLURM_JOB_ID:-na} task=${SLURM_ARRAY_TASK_ID} host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-unset} video_id=$VIDEO_ID"# shellcheck disable=SC1090source "$CONDA_SH"18 unmodified linesecho "Using LD_PRELOAD=$LD_PRELOAD"gpu_init_retry_state() {local attempts="$1"local host_name="$2"local gpu_id="$3"local reason="$4"cat > "$RETRY_STATE_PATH" <<STATEattempts=$attemptshost=$host_namegpu=$gpu_id3 unmodified lines}get_retry_attempts() {if [[ -f "$RETRY_STATE_PATH" ]]; thenawk -F'=' '/^attempts=/{print $2}' "$RETRY_STATE_PATH" | tail -n 1elseecho 0fi}mark_retry_exhausted() {local attempts="$1"local reason="$2"python - <<PYfrom pathlib import Pathimport sys, timeroot = Path(r"$ROOT_DIR")stats_path = Path(r"$STATS_NPZ")video_id = r"$VIDEO_ID"attempts = int(r"$attempts")reason = r'''$reason'''sys.path.insert(0, str(root))from utils.stats_npz import update_video_statsupdate_video_stats(stats_path,video_id,process_status="skipped",last_error=f"gpu_init_retry_exhausted after {attempts} attempts: {reason}",updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)PYrm -f "$RAW_VIDEO_DIR/$VIDEO_ID.mp4" "$RAW_VIDEO_DIR/$VIDEO_ID.mkv" "$RAW_VIDEO_DIR/$VIDEO_ID.webm" "$RAW_VIDEO_DIR/$VIDEO_ID.mov"}should_retry_gpu_init_failure() {16 unmodified lines"CONDA_NO_PLUGINS=true")cmd=(python -u "$PIPELINE02"--raw-video-dir "$RAW_VIDEO_DIR"--dataset-dir "$DATASET_DIR"--stats-npz "$STATS_NPZ"--fps "$FPS"--workers 1--tmp-root "$TMP_ROOT"--video-ids="$VIDEO_ID")if [[ "$FORCE_PROCESS" == "1" ]]; thencmd+=(--force)fiif [[ "$DELETE_SOURCE_ON_SUCCESS" == "1" ]]; thencmd+=(--delete-source-on-success)fiTMP_LOG="$(mktemp "${TMP_ROOT%/}/dwpose_${VIDEO_ID}_XXXX.log")"set +e"${env_cmd[@]}" conda run -n "$CONDA_ENV" "${cmd[@]}" 2>&1 | tee "$TMP_LOG"cmd_status=${PIPESTATUS[0]}set -eif [[ "$cmd_status" -ne 0 ]]; thennpz_dir="$DATASET_DIR/$VIDEO_ID/npz"if should_retry_gpu_init_failure "$TMP_LOG" "$npz_dir"; thenattempts="$(get_retry_attempts)"attempts="$((attempts + 1))"last_reason="$(tail -n 80 "$TMP_LOG" | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g' | cut -c1-1200)"gpu_init_retry_state "$attempts" "$(hostname)" "${CUDA_VISIBLE_DEVICES:-unset}" "$last_reason"if [[ "$attempts" -ge "$MAX_GPU_INIT_RETRIES" ]]; thenecho "GPU init failed on multiple GPUs; marking $VIDEO_ID as skipped after $attempts attempts." >&2mark_retry_exhausted "$attempts" "$last_reason"exit 0fiecho "GPU init failure for $VIDEO_ID on host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-unset}; retry attempt $attempts/$MAX_GPU_INIT_RETRIES will be resubmitted later." >&2exit 0fiexit "$cmd_status"firm -f "$RETRY_STATE_PATH"14 unmodified lines151617181920212223242526272 unmodified lines30313233343536373839404142434413 unmodified lines5859606162636465666768697071727374757677787980818218 unmodified lines1011021031041051061071081091101111121133 unmodified lines11711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615716 unmodified lines17417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325414 unmodified linesRUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"STATE_ROOT="${STATE_ROOT:-/home/sf895/SignVerse-2M-runtime}"CONDA_SH="${CONDA_SH:-/home/sf895/miniconda3/etc/profile.d/conda.sh}"CONDA_ENV="${CONDA_ENV:-signx2}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"STATUS_JOURNAL_PATH="${STATUS_JOURNAL_PATH:-$RUNTIME_ROOT/upload_status_journal.jsonl}"PIPELINE02="${PIPELINE02:-$ROOT_DIR/scripts/pipeline02_extract_dwpose_from_video.py}"FPS="${FPS:-24}"TMP_ROOT="${TMP_ROOT:-${SLURM_TMPDIR:-/tmp}}"2 unmodified linesCLAIM_DIR="${CLAIM_DIR:-$STATE_ROOT/slurm/state/claims}"RETRY_DIR="${RETRY_DIR:-$STATE_ROOT/slurm/state/gpu_init_retries}"MAX_GPU_INIT_RETRIES="${MAX_GPU_INIT_RETRIES:-3}"OPTIMIZED_MODE="${OPTIMIZED_MODE:-1}"OPTIMIZED_PROVIDER="${OPTIMIZED_PROVIDER:-cuda}"OPTIMIZED_FRAME_BATCH_SIZE="${OPTIMIZED_FRAME_BATCH_SIZE:-8}"OPTIMIZED_DETECT_RESOLUTION="${OPTIMIZED_DETECT_RESOLUTION:-512}"OPTIMIZED_FRAME_STRIDE="${OPTIMIZED_FRAME_STRIDE:-1}"OPTIMIZED_IO_BINDING="${OPTIMIZED_IO_BINDING:-1}"OPTIMIZED_GPU_DETECTOR_POSTPROCESS="${OPTIMIZED_GPU_DETECTOR_POSTPROCESS:-1}"OPTIMIZED_GPU_POSE_PREPROCESS="${OPTIMIZED_GPU_POSE_PREPROCESS:-0}"VIDEOS_PER_JOB="${VIDEOS_PER_JOB:-5}"MANIFEST="${MANIFEST:-${1:-}}"if [[ -z "$MANIFEST" ]]; then13 unmodified linesexit 1fimapfile -t ALL_VIDEO_IDS < <(sed -n "$((SLURM_ARRAY_TASK_ID * VIDEOS_PER_JOB + 1)),$(((SLURM_ARRAY_TASK_ID + 1) * VIDEOS_PER_JOB))p" "$MANIFEST")if [[ "${#ALL_VIDEO_IDS[@]}" -eq 0 ]]; thenecho "No video ids found for task index ${SLURM_ARRAY_TASK_ID} in manifest $MANIFEST" >&2exit 1fimkdir -p "$CLAIM_DIR" "$RETRY_DIR"cleanup_claims() {local video_idfor video_id in "${ALL_VIDEO_IDS[@]}"; dorm -f "$CLAIM_DIR/${video_id}.claim"done}trap cleanup_claims EXITexport OMP_NUM_THREADS="${SLURM_CPUS_PER_TASK:-1}"export MKL_NUM_THREADS="${SLURM_CPUS_PER_TASK:-1}"echo "[$(date '+%F %T')] job=${SLURM_JOB_ID:-na} task=${SLURM_ARRAY_TASK_ID} host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-unset} videos=${#ALL_VIDEO_IDS[@]} first_video=${ALL_VIDEO_IDS[0]}"# shellcheck disable=SC1090source "$CONDA_SH"18 unmodified linesecho "Using LD_PRELOAD=$LD_PRELOAD"gpu_init_retry_state() {local video_id="$1"local attempts="$2"local host_name="$3"local gpu_id="$4"local reason="$5"local retry_state_path="$RETRY_DIR/${video_id}.state"cat > "$retry_state_path" <<STATEattempts=$attemptshost=$host_namegpu=$gpu_id3 unmodified lines}get_retry_attempts() {local video_id="$1"local retry_state_path="$RETRY_DIR/${video_id}.state"if [[ -f "$retry_state_path" ]]; thenawk -F'=' '/^attempts=/{print $2}' "$retry_state_path" | tail -n 1elseecho 0fi}mark_retry_exhausted() {local video_id="$1"local attempts="$2"local reason="$3"python - <<PYfrom pathlib import Pathimport sys, timeroot = Path(r"$ROOT_DIR")stats_path = Path(r"$STATS_NPZ")video_id = r"$video_id"attempts = int(r"$attempts")reason = r'''$reason'''sys.path.insert(0, str(root))from utils.stats_npz import update_video_stats_best_effortjournal_path = Path(r"$STATUS_JOURNAL_PATH")update_video_stats_best_effort(stats_path,journal_path,video_id,process_status="skipped",last_error=f"gpu_init_retry_exhausted after {attempts} attempts: {reason}",updated_at=time.strftime("%Y-%m-%d %H:%M:%S"),)PYrm -f "$RAW_VIDEO_DIR/$video_id.mp4" "$RAW_VIDEO_DIR/$video_id.mkv" "$RAW_VIDEO_DIR/$video_id.webm" "$RAW_VIDEO_DIR/$video_id.mov"rm -f "$SCRATCH_RAW_VIDEO_DIR/$video_id.mp4" "$SCRATCH_RAW_VIDEO_DIR/$video_id.mkv" "$SCRATCH_RAW_VIDEO_DIR/$video_id.webm" "$SCRATCH_RAW_VIDEO_DIR/$video_id.mov"}should_retry_gpu_init_failure() {16 unmodified lines"CONDA_NO_PLUGINS=true")cmd_base=(python -u "$PIPELINE02"--raw-video-dir "$RAW_VIDEO_DIR"--scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR"--dataset-dir "$DATASET_DIR"--scratch-dataset-dir "$SCRATCH_DATASET_DIR"--stats-npz "$STATS_NPZ"--status-journal-path "$STATUS_JOURNAL_PATH"--fps "$FPS"--workers 1--tmp-root "$TMP_ROOT")if [[ "$OPTIMIZED_MODE" == "1" ]]; thencmd_base+=(--optimized-mode)cmd_base+=(--optimized-provider "$OPTIMIZED_PROVIDER")cmd_base+=(--optimized-frame-batch-size "$OPTIMIZED_FRAME_BATCH_SIZE")cmd_base+=(--optimized-detect-resolution "$OPTIMIZED_DETECT_RESOLUTION")cmd_base+=(--optimized-frame-stride "$OPTIMIZED_FRAME_STRIDE")if [[ "$OPTIMIZED_IO_BINDING" == "1" ]]; thencmd_base+=(--optimized-io-binding)fiif [[ "$OPTIMIZED_GPU_DETECTOR_POSTPROCESS" == "1" ]]; thencmd_base+=(--optimized-gpu-detector-postprocess)fiif [[ "$OPTIMIZED_GPU_POSE_PREPROCESS" == "1" ]]; thencmd_base+=(--optimized-gpu-pose-preprocess)fielsecmd_base+=(--legacy-mode)fiif [[ "$FORCE_PROCESS" == "1" ]]; thencmd_base+=(--force)fiif [[ "$DELETE_SOURCE_ON_SUCCESS" == "1" ]]; thencmd_base+=(--delete-source-on-success)fioverall_status=0for VIDEO_ID in "${ALL_VIDEO_IDS[@]}"; do[[ -z "$VIDEO_ID" ]] && continueCLAIM_PATH="$CLAIM_DIR/${VIDEO_ID}.claim"RETRY_STATE_PATH="$RETRY_DIR/${VIDEO_ID}.state"echo "[$(date '+%F %T')] job=${SLURM_JOB_ID:-na} task=${SLURM_ARRAY_TASK_ID} host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-unset} video_id=$VIDEO_ID"TMP_LOG="$(mktemp "${TMP_ROOT%/}/dwpose_${VIDEO_ID}_XXXX.log")"cmd=("${cmd_base[@]}" --video-ids="$VIDEO_ID")set +e"${env_cmd[@]}" conda run -n "$CONDA_ENV" "${cmd[@]}" 2>&1 | tee "$TMP_LOG"cmd_status=${PIPESTATUS[0]}set -eif [[ "$cmd_status" -ne 0 ]]; thennpz_dir="$DATASET_DIR/$VIDEO_ID/npz"if [[ ! -d "$npz_dir" && -d "$SCRATCH_DATASET_DIR/$VIDEO_ID/npz" ]]; thennpz_dir="$SCRATCH_DATASET_DIR/$VIDEO_ID/npz"fiif should_retry_gpu_init_failure "$TMP_LOG" "$npz_dir"; thenattempts="$(get_retry_attempts "$VIDEO_ID")"attempts="$((attempts + 1))"last_reason="$(tail -n 80 "$TMP_LOG" | tr '\n' ' ' | sed 's/[[:space:]]\+/ /g' | cut -c1-1200)"gpu_init_retry_state "$VIDEO_ID" "$attempts" "$(hostname)" "${CUDA_VISIBLE_DEVICES:-unset}" "$last_reason"if [[ "$attempts" -ge "$MAX_GPU_INIT_RETRIES" ]]; thenecho "GPU init failed on multiple GPUs; marking $VIDEO_ID as skipped after $attempts attempts." >&2mark_retry_exhausted "$VIDEO_ID" "$attempts" "$last_reason"rm -f "$CLAIM_PATH"continuefiecho "GPU init failure for $VIDEO_ID on host=$(hostname) gpu=${CUDA_VISIBLE_DEVICES:-unset}; retry attempt $attempts/$MAX_GPU_INIT_RETRIES will be resubmitted later." >&2overall_status="$cmd_status"breakfioverall_status="$cmd_status"breakfirm -f "$RETRY_STATE_PATH" "$CLAIM_PATH"doneexit "$overall_status"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899#!/usr/bin/env bash#SBATCH --job-name=upload#SBATCH --nodes=1#SBATCH --ntasks=1#SBATCH --cpus-per-task=2#SBATCH --mem=8G#SBATCH --time=24:00:00#SBATCH --output=%x_%A_%a.out#SBATCH --error=%x_%A_%a.err
set -euo pipefail
ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"CONDA_SH="${CONDA_SH:-/home/sf895/miniconda3/etc/profile.d/conda.sh}"CONDA_ENV="${CONDA_ENV:-signx2}"PIPELINE03="${PIPELINE03:-$ROOT_DIR/scripts/pipeline03_upload_to_huggingface.py}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"ARCHIVE_DIR="${ARCHIVE_DIR:-$ROOT_DIR/archives}"PROGRESS_JSON="${PROGRESS_JSON:-$RUNTIME_ROOT/archive_upload_progress.json}"STATUS_JOURNAL_PATH="${STATUS_JOURNAL_PATH:-$RUNTIME_ROOT/upload_status_journal.jsonl}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"REPO_ID="${REPO_ID:-SignerX/SignVerse-2M}"REPO_REVISION="${REPO_REVISION:-dev}"TARGET_BYTES="${TARGET_BYTES:-10737418240}"TARGET_FOLDERS="${TARGET_FOLDERS:-40}"PARALLEL_SHARDS="${PARALLEL_SHARDS:-1}"START_STAGGER_MIN="${START_STAGGER_MIN:-1}"START_STAGGER_MAX="${START_STAGGER_MAX:-3}"ALLOW_SMALL_FINAL_BATCH="${ALLOW_SMALL_FINAL_BATCH:-0}"REQUIRE_TARGET_BYTES="${REQUIRE_TARGET_BYTES:-1}"DRY_RUN_UPLOAD="${DRY_RUN_UPLOAD:-0}"UPLOAD_MODE="${UPLOAD_MODE:-api}"
if [[ ! -f "$CONDA_SH" ]]; then echo "Missing conda init script: $CONDA_SH" >&2 exit 1fi
if [[ -z "${SLURM_ARRAY_TASK_ID:-}" ]]; then echo "SLURM_ARRAY_TASK_ID is required." >&2 exit 1fi
if (( PARALLEL_SHARDS < 1 )); then echo "PARALLEL_SHARDS must be >= 1" >&2 exit 1fi
if (( SLURM_ARRAY_TASK_ID < 0 || SLURM_ARRAY_TASK_ID >= PARALLEL_SHARDS )); then echo "SLURM_ARRAY_TASK_ID=$SLURM_ARRAY_TASK_ID is out of range for PARALLEL_SHARDS=$PARALLEL_SHARDS" >&2 exit 1fi
echo "[$(date '+%F %T')] upload shard=${SLURM_ARRAY_TASK_ID}/${PARALLEL_SHARDS} host=$(hostname)"
# shellcheck disable=SC1090source "$CONDA_SH"
cmd=(python -u "$PIPELINE03" --dataset-dir "$DATASET_DIR" --scratch-dataset-dir "$SCRATCH_DATASET_DIR" --raw-video-dir "$RAW_VIDEO_DIR" --scratch-raw-video-dir "$SCRATCH_RAW_VIDEO_DIR" --raw-caption-dir "$RAW_CAPTION_DIR" --raw-metadata-dir "$RAW_METADATA_DIR" --archive-dir "$ARCHIVE_DIR" --progress-path "$PROGRESS_JSON" --stats-npz "$STATS_NPZ" --status-journal-path "$STATUS_JOURNAL_PATH" --repo-id "$REPO_ID" --repo-revision "$REPO_REVISION" --target-bytes "$TARGET_BYTES" --target-folders "$TARGET_FOLDERS" --parallel-shards "$PARALLEL_SHARDS" --shard-index "$SLURM_ARRAY_TASK_ID" --start-stagger-min "$START_STAGGER_MIN" --start-stagger-max "$START_STAGGER_MAX" --upload-mode "$UPLOAD_MODE")
if [[ "$ALLOW_SMALL_FINAL_BATCH" == "1" ]]; then cmd+=(--allow-small-final-batch)fiif [[ "$REQUIRE_TARGET_BYTES" != "1" ]]; then cmd+=(--allow-small-final-batch)fiif [[ "$DRY_RUN_UPLOAD" == "1" ]]; then cmd+=(--dry-run)fi
cmd+=(--skip-stats-write)
CONDA_NO_PLUGINS=true conda run -n "$CONDA_ENV" "${cmd[@]}"4 unmodified lines567891011124 unmodified lines#SBATCH --cpus-per-task=2#SBATCH --mem=8G#SBATCH --time=24:00:00#SBATCH --output=%x_%A.out#SBATCH --error=%x_%A.errset -euo pipefail4 unmodified lines567891011124 unmodified lines#SBATCH --cpus-per-task=2#SBATCH --mem=8G#SBATCH --time=24:00:00#SBATCH --output=/scratch/%u/SignVerse-2M-runtime/slurm/logs/%x_%A.out#SBATCH --error=/scratch/%u/SignVerse-2M-runtime/slurm/logs/%x_%A.errset -euo pipefail
6 unmodified lines789101112131415168 unmodified lines2526272829303125 unmodified lines57585960616222 unmodified lines85868788899032 unmodified lines1231241251261271281291 unmodified line13113213313413513613713813914014114214314414514647 unmodified lines19419519619719819920020120220320420520624 unmodified lines23123223323423523630 unmodified lines2672682692702712722736 unmodified linesSOURCE_METADATA_CSV="${SOURCE_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_ori.csv}"OUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"SLURM_SCRIPT="$ROOT_DIR/slurm/process_download_array.slurm"MANIFEST_DIR="${MANIFEST_DIR:-$STATE_ROOT/slurm/manifests}"LOG_DIR="${LOG_DIR:-$STATE_ROOT/slurm/logs}"8 unmodified linesMEMORY="4G"LIMIT=""ARRAY_PARALLEL=""MAX_BACKLOG_VIDEOS="180"MAX_ACTIVE_DOWNLOADS="60"DOWNLOAD_CLAIM_GRACE_SECONDS="${DOWNLOAD_CLAIM_GRACE_SECONDS:-600}"WORKERS="60"25 unmodified lines--max-backlog-videos N Max raw backlog + active download claims allowed. Default: 180--max-active-downloads N Max active download claims allowed at once. Default: 30--workers N Max download tasks to submit in one cycle. Default: 60--claim-dir DIR Download claim directory--csv-lock-path PATH CSV lock path--video-ids ID [ID ...] Restrict this cycle to specific videos22 unmodified lines--array-parallel) ARRAY_PARALLEL="$2"; shift 2 ;;--max-backlog-videos) MAX_BACKLOG_VIDEOS="$2"; shift 2 ;;--workers) WORKERS="$2"; shift 2 ;;--max-active-downloads) MAX_ACTIVE_DOWNLOADS="$2"; shift 2 ;;--claim-dir) DOWNLOAD_CLAIM_DIR="$2"; shift 2 ;;--csv-lock-path) DOWNLOAD_CSV_LOCK_PATH="$2"; shift 2 ;;32 unmodified linessqueue -h -u "$USER" -o "%A" | sed 's/_.*//' | sort -u > "$ACTIVE_JOBS_FILE"squeue -h -u "$USER" -n download -t RUNNING,PENDING,CONFIGURING -o "%i" > "$ACTIVE_DOWNLOAD_TASKS_FILE"SELECTED_COUNT="$(python - "$SOURCE_METADATA_CSV" "$OUTPUT_METADATA_CSV" "$RAW_VIDEO_DIR" "$DOWNLOAD_CLAIM_DIR" "$ACTIVE_JOBS_FILE" "$ACTIVE_DOWNLOAD_TASKS_FILE" "$MAX_BACKLOG_VIDEOS" "$MAX_ACTIVE_DOWNLOADS" "$LIMIT" "$WORKERS" "$BASE_MANIFEST" "${VIDEO_IDS[*]:-}" <<'PY'import csvimport sysfrom pathlib import Path1 unmodified linesource_csv = Path(sys.argv[1])processed_csv = Path(sys.argv[2])raw_video_dir = Path(sys.argv[3])claim_dir = Path(sys.argv[4])active_jobs_path = Path(sys.argv[5])active_download_tasks_path = Path(sys.argv[6])max_backlog = int(sys.argv[7])max_active_downloads = int(sys.argv[8])limit_arg = sys.argv[9]workers = int(sys.argv[10])manifest_path = Path(sys.argv[11])video_ids_joined = sys.argv[12].strip()limit = int(limit_arg) if limit_arg else Nonevideo_filter = set(video_ids_joined.split()) if video_ids_joined else Nonevideo_extensions = {'.mp4', '.mkv', '.webm', '.mov'}47 unmodified lineselse:claim_path.unlink(missing_ok=True)raw_backlog = 0existing_raw = set()if raw_video_dir.exists():for path in raw_video_dir.iterdir():if path.is_file() and path.suffix.lower() in video_extensions:raw_backlog += 1existing_raw.add(path.stem)effective_active_downloads = max(active_download_tasks, len(active_claims))remaining_slots = max(0, max_backlog - raw_backlog - len(active_claims))24 unmodified linescontinueif video_id in active_claims or video_id in existing_raw:continuedownload_status = (row.get('download_status') or '').strip()if download_status in {'ok', 'skipped'}:continue30 unmodified lines--array "$ARRAY_SPEC"--output "$LOG_DIR/download_%A_%a.out"--error "$LOG_DIR/download_%A_%a.err"--export "ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,CONDA_SH=/home/sf895/miniconda3/etc/profile.d/conda.sh,CONDA_ENV=signx2,SOURCE_METADATA_CSV=$SOURCE_METADATA_CSV,OUTPUT_METADATA_CSV=$OUTPUT_METADATA_CSV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,RAW_CAPTION_DIR=$RAW_CAPTION_DIR,RAW_METADATA_DIR=$RAW_METADATA_DIR,DATASET_DIR=$DATASET_DIR,STATS_NPZ=$STATS_NPZ,PIPELINE01=$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py,DOWNLOAD_CLAIM_DIR=$DOWNLOAD_CLAIM_DIR,DOWNLOAD_CSV_LOCK_PATH=$DOWNLOAD_CSV_LOCK_PATH,MANIFEST=$BASE_MANIFEST,FORCE_METADATA=$FORCE_METADATA,FORCE_SUBTITLES=$FORCE_SUBTITLES,FORCE_DOWNLOAD=$FORCE_DOWNLOAD,SKIP_VIDEO_DOWNLOAD=$SKIP_VIDEO_DOWNLOAD,SKIP_SUBTITLES=$SKIP_SUBTITLES,COOKIES_FILE=$COOKIES_FILE,COOKIES_FROM_BROWSER=$COOKIES_FROM_BROWSER,EXTRACTOR_ARGS=$EXTRACTOR_ARGS,DOWNLOAD_START_STAGGER_MIN=${DOWNLOAD_START_STAGGER_MIN:-1},DOWNLOAD_START_STAGGER_MAX=${DOWNLOAD_START_STAGGER_MAX:-3}")if [[ -n "$ACCOUNT" ]]; thencmd+=(--account "$ACCOUNT")6 unmodified lines78910111213141516171819208 unmodified lines2930313233343525 unmodified lines61626364656667686922 unmodified lines929394959697989910032 unmodified lines1331341351361371381391 unmodified line14114214314414514614714814915015115215315415515615715815916016116216316416516616716816947 unmodified lines21721821922022122222322422522622722822923023123223323423523623723823924024 unmodified lines26526626726826927027127230 unmodified lines3033043053063073083096 unmodified linesSOURCE_METADATA_CSV="${SOURCE_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_ori.csv}"OUTPUT_METADATA_CSV="${OUTPUT_METADATA_CSV:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv}"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"HOME_RAW_VIDEO_LIMIT="${HOME_RAW_VIDEO_LIMIT:-180}"SCRATCH_RAW_VIDEO_LIMIT="${SCRATCH_RAW_VIDEO_LIMIT:-2800}"RAW_CAPTION_DIR="${RAW_CAPTION_DIR:-$RUNTIME_ROOT/raw_caption}"RAW_METADATA_DIR="${RAW_METADATA_DIR:-$RUNTIME_ROOT/raw_metadata}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PROGRESS_JSON="${PROGRESS_JSON:-$RUNTIME_ROOT/archive_upload_progress.json}"SLURM_SCRIPT="$ROOT_DIR/slurm/process_download_array.slurm"MANIFEST_DIR="${MANIFEST_DIR:-$STATE_ROOT/slurm/manifests}"LOG_DIR="${LOG_DIR:-$STATE_ROOT/slurm/logs}"8 unmodified linesMEMORY="4G"LIMIT=""ARRAY_PARALLEL=""MAX_BACKLOG_VIDEOS="2980"MAX_ACTIVE_DOWNLOADS="60"DOWNLOAD_CLAIM_GRACE_SECONDS="${DOWNLOAD_CLAIM_GRACE_SECONDS:-600}"WORKERS="60"25 unmodified lines--max-backlog-videos N Max raw backlog + active download claims allowed. Default: 180--max-active-downloads N Max active download claims allowed at once. Default: 30--workers N Max download tasks to submit in one cycle. Default: 60--scratch-raw-video-dir DIR Scratch raw video pool directory--home-raw-video-limit N Home raw pool cap. Default: 180--scratch-raw-video-limit N Scratch raw pool cap. Default: 2800--claim-dir DIR Download claim directory--csv-lock-path PATH CSV lock path--video-ids ID [ID ...] Restrict this cycle to specific videos22 unmodified lines--array-parallel) ARRAY_PARALLEL="$2"; shift 2 ;;--max-backlog-videos) MAX_BACKLOG_VIDEOS="$2"; shift 2 ;;--workers) WORKERS="$2"; shift 2 ;;--scratch-raw-video-dir) SCRATCH_RAW_VIDEO_DIR="$2"; shift 2 ;;--home-raw-video-limit) HOME_RAW_VIDEO_LIMIT="$2"; shift 2 ;;--scratch-raw-video-limit) SCRATCH_RAW_VIDEO_LIMIT="$2"; shift 2 ;;--max-active-downloads) MAX_ACTIVE_DOWNLOADS="$2"; shift 2 ;;--claim-dir) DOWNLOAD_CLAIM_DIR="$2"; shift 2 ;;--csv-lock-path) DOWNLOAD_CSV_LOCK_PATH="$2"; shift 2 ;;32 unmodified linessqueue -h -u "$USER" -o "%A" | sed 's/_.*//' | sort -u > "$ACTIVE_JOBS_FILE"squeue -h -u "$USER" -n download -t RUNNING,PENDING,CONFIGURING -o "%i" > "$ACTIVE_DOWNLOAD_TASKS_FILE"SELECTED_COUNT="$(python - "$SOURCE_METADATA_CSV" "$OUTPUT_METADATA_CSV" "$RAW_VIDEO_DIR" "$SCRATCH_RAW_VIDEO_DIR" "$DOWNLOAD_CLAIM_DIR" "$ACTIVE_JOBS_FILE" "$ACTIVE_DOWNLOAD_TASKS_FILE" "$MAX_BACKLOG_VIDEOS" "$MAX_ACTIVE_DOWNLOADS" "$LIMIT" "$WORKERS" "$BASE_MANIFEST" "$HOME_RAW_VIDEO_LIMIT" "$SCRATCH_RAW_VIDEO_LIMIT" "$PROGRESS_JSON" "${VIDEO_IDS[*]:-}" <<'PY'import csvimport sysfrom pathlib import Path1 unmodified linesource_csv = Path(sys.argv[1])processed_csv = Path(sys.argv[2])raw_video_dir = Path(sys.argv[3])scratch_raw_video_dir = Path(sys.argv[4])claim_dir = Path(sys.argv[5])active_jobs_path = Path(sys.argv[6])active_download_tasks_path = Path(sys.argv[7])max_backlog = int(sys.argv[8])max_active_downloads = int(sys.argv[9])limit_arg = sys.argv[10]workers = int(sys.argv[11])manifest_path = Path(sys.argv[12])home_raw_video_limit = int(sys.argv[13])scratch_raw_video_limit = int(sys.argv[14])progress_path = Path(sys.argv[15])video_ids_joined = sys.argv[16].strip()limit = int(limit_arg) if limit_arg else Noneuploaded_ids = set()if progress_path.exists():try:import jsonprogress = json.loads(progress_path.read_text(encoding="utf-8"))uploaded_ids = set((progress.get("uploaded_folders") or {}).keys())except Exception:uploaded_ids = set()video_filter = set(video_ids_joined.split()) if video_ids_joined else Nonevideo_extensions = {'.mp4', '.mkv', '.webm', '.mov'}47 unmodified lineselse:claim_path.unlink(missing_ok=True)home_raw_count = 0scratch_raw_count = 0existing_raw = set()if raw_video_dir.exists():for path in raw_video_dir.iterdir():if path.is_file() and path.suffix.lower() in video_extensions:home_raw_count += 1existing_raw.add(path.stem)if scratch_raw_video_dir.exists():for path in scratch_raw_video_dir.iterdir():if path.is_file() and path.suffix.lower() in video_extensions:scratch_raw_count += 1existing_raw.add(path.stem)raw_backlog = home_raw_count + scratch_raw_countif home_raw_count >= home_raw_video_limit and scratch_raw_count >= scratch_raw_video_limit:manifest_path.write_text('', encoding='utf-8')print(0)raise SystemExiteffective_active_downloads = max(active_download_tasks, len(active_claims))remaining_slots = max(0, max_backlog - raw_backlog - len(active_claims))24 unmodified linescontinueif video_id in active_claims or video_id in existing_raw:continueif video_id in uploaded_ids:continuedownload_status = (row.get('download_status') or '').strip()if download_status in {'ok', 'skipped'}:continue30 unmodified lines--array "$ARRAY_SPEC"--output "$LOG_DIR/download_%A_%a.out"--error "$LOG_DIR/download_%A_%a.err"--export "ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,CONDA_SH=/home/sf895/miniconda3/etc/profile.d/conda.sh,CONDA_ENV=signx2,SOURCE_METADATA_CSV=$SOURCE_METADATA_CSV,OUTPUT_METADATA_CSV=$OUTPUT_METADATA_CSV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,SCRATCH_RAW_VIDEO_DIR=$SCRATCH_RAW_VIDEO_DIR,HOME_RAW_VIDEO_LIMIT=$HOME_RAW_VIDEO_LIMIT,SCRATCH_RAW_VIDEO_LIMIT=$SCRATCH_RAW_VIDEO_LIMIT,RAW_CAPTION_DIR=$RAW_CAPTION_DIR,RAW_METADATA_DIR=$RAW_METADATA_DIR,DATASET_DIR=$DATASET_DIR,STATS_NPZ=$STATS_NPZ,STATUS_JOURNAL_PATH=$RUNTIME_ROOT/upload_status_journal.jsonl,PIPELINE01=$ROOT_DIR/scripts/pipeline01_download_video_fix_caption.py,DOWNLOAD_CLAIM_DIR=$DOWNLOAD_CLAIM_DIR,DOWNLOAD_CSV_LOCK_PATH=$DOWNLOAD_CSV_LOCK_PATH,MANIFEST=$BASE_MANIFEST,FORCE_METADATA=$FORCE_METADATA,FORCE_SUBTITLES=$FORCE_SUBTITLES,FORCE_DOWNLOAD=$FORCE_DOWNLOAD,SKIP_VIDEO_DOWNLOAD=$SKIP_VIDEO_DOWNLOAD,SKIP_SUBTITLES=$SKIP_SUBTITLES,COOKIES_FILE=$COOKIES_FILE,COOKIES_FROM_BROWSER=$COOKIES_FROM_BROWSER,EXTRACTOR_ARGS=$EXTRACTOR_ARGS,DOWNLOAD_START_STAGGER_MIN=${DOWNLOAD_START_STAGGER_MIN:-1},DOWNLOAD_START_STAGGER_MAX=${DOWNLOAD_START_STAGGER_MAX:-3}")if [[ -n "$ACCOUNT" ]]; thencmd+=(--account "$ACCOUNT")
6 unmodified lines78910111213148 unmodified lines2324252627282930313210 unmodified lines43444546474849505113 unmodified lines6566676869707111 unmodified lines838485868788899091929394959697989910010110210310410510619 unmodified lines12612712812913013113213313413513613713813914012 unmodified lines15315415515615715815916016116216316416516616716816918 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232241 unmodified line2262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612624 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013026 unmodified linesCONDA_SH="/home/sf895/miniconda3/etc/profile.d/conda.sh"CONDA_ENV="signx2"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"SLURM_SCRIPT="$ROOT_DIR/slurm/process_dwpose_array.slurm"MANIFEST_DIR="${MANIFEST_DIR:-$STATE_ROOT/slurm/manifests}"LOG_DIR="${LOG_DIR:-$STATE_ROOT/slurm/logs}"8 unmodified linesFPS="24"LIMIT=""ARRAY_PARALLEL=""MAX_BACKLOG_VIDEOS="180"FORCE_PROCESS=0DELETE_SOURCE_ON_SUCCESS=0MAX_PER_NODE=""usage() {cat <<USAGE10 unmodified lines--mem SIZE Default: 32G--fps N Default: 24--limit N Only submit the first N pending, unclaimed videos this cycle--max-backlog-videos N Max claimed queued/running videos allowed at once. Default: 180--array-parallel N Add a %N cap to each node-local array--max-per-node N Cap submissions per node in a cycle--force-process Re-run videos even if marked complete--delete-source-on-success Delete raw videos after successful processing--help13 unmodified lines--limit) LIMIT="$2"; shift 2 ;;--max-backlog-videos) MAX_BACKLOG_VIDEOS="$2"; shift 2 ;;--array-parallel) ARRAY_PARALLEL="$2"; shift 2 ;;--max-per-node) MAX_PER_NODE="$2"; shift 2 ;;--force-process) FORCE_PROCESS=1; shift ;;--delete-source-on-success) DELETE_SOURCE_ON_SUCCESS=1; shift ;;-h|--help) usage; exit 0 ;;11 unmodified linesTIMESTAMP="$(date '+%Y%m%d_%H%M%S')"BASE_MANIFEST="$MANIFEST_DIR/pending_videos_${TIMESTAMP}.txt"ACTIVE_JOBS_FILE="$STATE_DIR/active_jobs_${TIMESTAMP}.txt"NODE_SLOTS_FILE="$STATE_DIR/node_slots_${TIMESTAMP}.txt"squeue -h -u "$USER" -o "%A" | sed 's/_.*//' | sort -u > "$ACTIVE_JOBS_FILE"PENDING_COUNT="$(python - "$RAW_VIDEO_DIR" "$DATASET_DIR" "$LIMIT" "$FORCE_PROCESS" "$BASE_MANIFEST" "$CLAIM_DIR" "$ACTIVE_JOBS_FILE" "$MAX_BACKLOG_VIDEOS" <<'PY'import sysfrom pathlib import Pathraw_video_dir = Path(sys.argv[1])dataset_dir = Path(sys.argv[2])limit_arg = sys.argv[3]force = sys.argv[4] == '1'manifest_path = Path(sys.argv[5])claim_dir = Path(sys.argv[6])active_jobs_path = Path(sys.argv[7])max_backlog = int(sys.argv[8])limit = int(limit_arg) if limit_arg else Nonevideo_extensions = {'.mp4', '.mkv', '.webm', '.mov'}claim_dir.mkdir(parents=True, exist_ok=True)active_jobs = set()19 unmodified linesremaining_slots = max(0, max_backlog - len(active_claims))selected = []if remaining_slots > 0 and raw_video_dir.exists():for path in sorted(raw_video_dir.iterdir()):if not path.is_file() or path.suffix.lower() not in video_extensions:continuevideo_id = path.stemif video_id in active_claims:continuecomplete_marker = dataset_dir / video_id / 'npz' / '.complete'if not force and complete_marker.exists():continueselected.append(video_id)if len(selected) >= remaining_slots:12 unmodified linesexit 0fiAVAILABLE_SLOTS="$(python - "$PARTITIONS" "$NODE_SLOTS_FILE" "$MAX_PER_NODE" <<'PY'import reimport subprocessimport sysfrom pathlib import Pathparts = [p for p in sys.argv[1].split(',') if p]out_path = Path(sys.argv[2])max_per_node_arg = sys.argv[3]max_per_node = int(max_per_node_arg) if max_per_node_arg else Noneslots = []for part in parts:proc = subprocess.run(['sinfo', '-h', '-N', '-p', part, '-o', '%N'], capture_output=True, text=True, check=False)if proc.returncode != 0:18 unmodified linesif max_per_node is not None:free = min(free, max_per_node)if free > 0:slots.append((part, node, free))slots.sort(key=lambda item: (-item[2], item[0], item[1]))out_path.write_text(''.join(f'{part}\t{node}\t{free}\n' for part, node, free in slots), encoding='utf-8')print(sum(free for _, _, free in slots))PY)"if [[ -z "$AVAILABLE_SLOTS" || "$AVAILABLE_SLOTS" == "0" ]]; thenecho "No free GPU slots detected across requested partitions."rm -f "$BASE_MANIFEST" "$NODE_SLOTS_FILE"exit 0fiTARGET_COUNT="$PENDING_COUNT"if [[ "$TARGET_COUNT" -gt "$AVAILABLE_SLOTS" ]]; thenTARGET_COUNT="$AVAILABLE_SLOTS"head -n "$TARGET_COUNT" "$BASE_MANIFEST" > "$BASE_MANIFEST.tmp"mv "$BASE_MANIFEST.tmp" "$BASE_MANIFEST"fiecho "Created manifest: $BASE_MANIFEST"echo "Pending videos selected this cycle: $PENDING_COUNT"echo "Available GPU slots right now: $AVAILABLE_SLOTS"echo "Submitting now: $TARGET_COUNT"write_claims() {local manifest="$1"local job_id="$2"local task_id=0while IFS= read -r video_id; do[[ -z "$video_id" ]] && continuecat > "$CLAIM_DIR/${video_id}.claim" <<CLAIMjob_id=$job_idtask_id=$task_id1 unmodified linevideo_id=$video_idsubmitted_at=$(date '+%F %T')CLAIMtask_id=$((task_id + 1))done < "$manifest"}submit_node() {local partition="$1"local node="$2"local manifest="$3"local count="$4"local array_spec="0-$((count - 1))"local job_output job_idif [[ -n "$ARRAY_PARALLEL" ]]; thenarray_spec+="%${ARRAY_PARALLEL}"filocal -a cmd=(sbatch--partition "$partition"--nodelist "$node"--array "$array_spec"--cpus-per-task "$CPUS_PER_TASK"--mem "$MEMORY"--time "$TIME_LIMIT"--output "$LOG_DIR/dwpose_${partition}_${node}_%A_%a.out"--error "$LOG_DIR/dwpose_${partition}_${node}_%A_%a.err"--export "ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,CONDA_SH=$CONDA_SH,CONDA_ENV=$CONDA_ENV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,DATASET_DIR=$DATASET_DIR,STATS_NPZ=$STATS_NPZ,FPS=$FPS,FORCE_PROCESS=$FORCE_PROCESS,DELETE_SOURCE_ON_SUCCESS=$DELETE_SOURCE_ON_SUCCESS,MANIFEST=$manifest,CLAIM_DIR=$CLAIM_DIR")if [[ -n "$ACCOUNT" ]]; thencmd+=(--account "$ACCOUNT")ficmd+=("$SLURM_SCRIPT")echo "Submitting partition=$partition node=$node array=$array_spec manifest=$manifest"job_output="$("${cmd[@]}")"echo "$job_output"job_id="$(awk '/Submitted batch job/ {print $4}' <<< "$job_output" | tail -n 1)"if [[ -z "$job_id" ]]; then4 unmodified lines}submitted_total=0failed_nodes=0line_no=1while IFS=$'\t' read -r partition node free_slots; do[[ -z "$partition" ]] && continueif [[ "$submitted_total" -ge "$TARGET_COUNT" ]]; thenbreakfiremaining=$((TARGET_COUNT - submitted_total))assign_count="$free_slots"if [[ "$assign_count" -gt "$remaining" ]]; thenassign_count="$remaining"fishard_manifest="$MANIFEST_DIR/pending_videos_${TIMESTAMP}.${partition}.${node}.txt"sed -n "${line_no},$((line_no + assign_count - 1))p" "$BASE_MANIFEST" > "$shard_manifest"shard_count="$(wc -l < "$shard_manifest" | tr -d [:space:])"if [[ "$shard_count" == "0" ]]; thenrm -f "$shard_manifest"continuefiif submit_node "$partition" "$node" "$shard_manifest" "$shard_count"; thensubmitted_total=$((submitted_total + shard_count))line_no=$((line_no + shard_count))elseecho "Node-local submit failed for partition=$partition node=$node; leaving those videos unclaimed for later nodes or the next cycle." >&2rm -f "$shard_manifest"failed_nodes=$((failed_nodes + 1))continuefidone < "$NODE_SLOTS_FILE"echo "SUBMITTED_VIDEO_COUNT=$submitted_total"echo "FAILED_NODE_SUBMITS=$failed_nodes"rm -f "$NODE_SLOTS_FILE"6 unmodified lines78910111213141516178 unmodified lines262728293031323334353637383940414210 unmodified lines5354555657585960616213 unmodified lines76777879808182838411 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313419 unmodified lines15415515615715815916016116216316416516616716816917017117217317417517617717817918012 unmodified lines19319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727818 unmodified lines2972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713721 unmodified line3743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154 unmodified lines4204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664676 unmodified linesCONDA_SH="/home/sf895/miniconda3/etc/profile.d/conda.sh"CONDA_ENV="signx2"RAW_VIDEO_DIR="${RAW_VIDEO_DIR:-$RUNTIME_ROOT/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"DATASET_DIR="${DATASET_DIR:-$RUNTIME_ROOT/dataset}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"STATS_NPZ="${STATS_NPZ:-$RUNTIME_ROOT/stats.npz}"PROGRESS_JSON="${PROGRESS_JSON:-$RUNTIME_ROOT/archive_upload_progress.json}"SLURM_SCRIPT="$ROOT_DIR/slurm/process_dwpose_array.slurm"MANIFEST_DIR="${MANIFEST_DIR:-$STATE_ROOT/slurm/manifests}"LOG_DIR="${LOG_DIR:-$STATE_ROOT/slurm/logs}"8 unmodified linesFPS="24"LIMIT=""ARRAY_PARALLEL=""MAX_BACKLOG_VIDEOS="2980"FORCE_PROCESS=0DELETE_SOURCE_ON_SUCCESS=0VIDEOS_PER_JOB="${VIDEOS_PER_JOB:-5}"MAX_PER_NODE=""PARTITION_QOS_COOLDOWN_SECONDS="${PARTITION_QOS_COOLDOWN_SECONDS:-300}"PARTITION_QOS_HEADROOM="${PARTITION_QOS_HEADROOM:-2}"PARTITION_ACTIVE_WINDOW_DEFAULT="${PARTITION_ACTIVE_WINDOW_DEFAULT:-16}"PARTITION_ACTIVE_WINDOW_GPU="${PARTITION_ACTIVE_WINDOW_GPU:-16}"PARTITION_ACTIVE_WINDOW_GPU_REDHAT="${PARTITION_ACTIVE_WINDOW_GPU_REDHAT:-16}"PARTITION_ACTIVE_WINDOW_CGPU="${PARTITION_ACTIVE_WINDOW_CGPU:-8}"usage() {cat <<USAGE10 unmodified lines--mem SIZE Default: 32G--fps N Default: 24--limit N Only submit the first N pending, unclaimed videos this cycle--max-backlog-videos N Max claimed queued/running videos allowed at once. Default: 2980--array-parallel N Add a %N cap to each partition array--max-per-node N Cap per-node free-slot contribution before partition aggregation--partition-qos-cooldown-seconds N Skip a partition for N seconds after a submit failure. Default: 300--force-process Re-run videos even if marked complete--delete-source-on-success Delete raw videos after successful processing--help13 unmodified lines--limit) LIMIT="$2"; shift 2 ;;--max-backlog-videos) MAX_BACKLOG_VIDEOS="$2"; shift 2 ;;--array-parallel) ARRAY_PARALLEL="$2"; shift 2 ;;--max-per-node) MAX_PER_NODE="$2"; shift 2 ;;&--videos-per-job) VIDEOS_PER_JOB="$2"; shift 2 ;;--partition-qos-cooldown-seconds) PARTITION_QOS_COOLDOWN_SECONDS="$2"; shift 2 ;;--force-process) FORCE_PROCESS=1; shift ;;--delete-source-on-success) DELETE_SOURCE_ON_SUCCESS=1; shift ;;-h|--help) usage; exit 0 ;;11 unmodified linesTIMESTAMP="$(date '+%Y%m%d_%H%M%S')"BASE_MANIFEST="$MANIFEST_DIR/pending_videos_${TIMESTAMP}.txt"ACTIVE_JOBS_FILE="$STATE_DIR/active_jobs_${TIMESTAMP}.txt"PARTITION_SLOTS_FILE="$STATE_DIR/partition_slots_${TIMESTAMP}.txt"PARTITION_COOLDOWN_DIR="$STATE_DIR/partition_submit_cooldowns"mkdir -p "$PARTITION_COOLDOWN_DIR"squeue -h -u "$USER" -o "%A" | sed 's/_.*//' | sort -u > "$ACTIVE_JOBS_FILE"PENDING_COUNT="$(python - "$RAW_VIDEO_DIR" "$SCRATCH_RAW_VIDEO_DIR" "$DATASET_DIR" "$SCRATCH_DATASET_DIR" "$LIMIT" "$FORCE_PROCESS" "$BASE_MANIFEST" "$CLAIM_DIR" "$ACTIVE_JOBS_FILE" "$MAX_BACKLOG_VIDEOS" "$PROGRESS_JSON" <<'PY'import sysfrom pathlib import Pathraw_video_dir = Path(sys.argv[1])scratch_raw_video_dir = Path(sys.argv[2])dataset_dir = Path(sys.argv[3])scratch_dataset_dir = Path(sys.argv[4])limit_arg = sys.argv[5]force = sys.argv[6] == '1'manifest_path = Path(sys.argv[7])claim_dir = Path(sys.argv[8])active_jobs_path = Path(sys.argv[9])max_backlog = int(sys.argv[10])progress_path = Path(sys.argv[11])limit = int(limit_arg) if limit_arg else Noneuploaded_ids = set()if progress_path.exists():try:import jsonprogress = json.loads(progress_path.read_text(encoding="utf-8"))uploaded_ids = set((progress.get("uploaded_folders") or {}).keys())except Exception:uploaded_ids = set()video_extensions = {'.mp4', '.mkv', '.webm', '.mov'}claim_dir.mkdir(parents=True, exist_ok=True)active_jobs = set()19 unmodified linesremaining_slots = max(0, max_backlog - len(active_claims))selected = []if remaining_slots > 0:raw_paths = []if raw_video_dir.exists():raw_paths.extend(sorted(raw_video_dir.iterdir()))if scratch_raw_video_dir.exists():raw_paths.extend(sorted(scratch_raw_video_dir.iterdir()))seen = set()for path in raw_paths:if not path.is_file() or path.suffix.lower() not in video_extensions:continuevideo_id = path.stemif video_id in seen:continueseen.add(video_id)if video_id in active_claims:continueif video_id in uploaded_ids:continuecomplete_marker = dataset_dir / video_id / 'npz' / '.complete'scratch_complete_marker = scratch_dataset_dir / video_id / 'npz' / '.complete'if not force and (complete_marker.exists() or scratch_complete_marker.exists()):continueselected.append(video_id)if len(selected) >= remaining_slots:12 unmodified linesexit 0fiAVAILABLE_SLOTS="$(python - "$PARTITIONS" "$PARTITION_SLOTS_FILE" "$MAX_PER_NODE" "$USER" "$PARTITION_COOLDOWN_DIR" "$PARTITION_QOS_COOLDOWN_SECONDS" "$PARTITION_QOS_HEADROOM" "$PARTITION_ACTIVE_WINDOW_DEFAULT" "$PARTITION_ACTIVE_WINDOW_GPU" "$PARTITION_ACTIVE_WINDOW_GPU_REDHAT" "$PARTITION_ACTIVE_WINDOW_CGPU" <<'PY'import reimport subprocessimport sysfrom collections import defaultdictfrom pathlib import Pathparts = [p for p in sys.argv[1].split(',') if p]out_path = Path(sys.argv[2])max_per_node_arg = sys.argv[3]user = sys.argv[4]cooldown_dir = Path(sys.argv[5])cooldown_seconds = int(sys.argv[6])qos_headroom = int(sys.argv[7])partition_active_window_default = int(sys.argv[8])partition_active_window_gpu = int(sys.argv[9])partition_active_window_gpu_redhat = int(sys.argv[10])partition_active_window_cgpu = int(sys.argv[11])partition_active_window_map = {"gpu": partition_active_window_gpu,"gpu-redhat": partition_active_window_gpu_redhat,"cgpu": partition_active_window_cgpu,}max_per_node = int(max_per_node_arg) if max_per_node_arg else Noneqos_limit_by_part = {}try:proc = subprocess.run(['sacctmgr', 'show', 'qos', 'format=Name,MaxSubmitPU', '-P'], capture_output=True, text=True, check=False)for line in (proc.stdout or '').splitlines():if not line.strip() or '|' not in line:continuename, max_submit = line.split('|', 1)name = name.strip()max_submit = max_submit.strip()if name in parts and max_submit:try:qos_limit_by_part[name] = int(max_submit)except ValueError:passexcept Exception:qos_limit_by_part = {}def expand_count(jobid_token: str) -> int:m = re.match(r'^(\d+)_\[(.+)\]$', jobid_token)if not m:return 1body = m.group(2)if '%' in body:body = body.split('%', 1)[0]total = 0for part in body.split(','):part = part.strip()if not part:continueif '-' in part:a, b = part.split('-', 1)try:total += int(b) - int(a) + 1except ValueError:total += 1else:total += 1return max(total, 1)active_tasks_by_part = defaultdict(int)try:proc = subprocess.run(['squeue', '-u', user, '-h', '-o', '%i|%P|%T'], capture_output=True, text=True, check=False)for line in (proc.stdout or '').splitlines():if not line.strip() or '|' not in line:continuejobid, partition, state = [x.strip() for x in line.split('|', 2)]if partition not in parts:continueif state not in {'RUNNING', 'PENDING', 'CONFIGURING'}:continueactive_tasks_by_part[partition] += expand_count(jobid)except Exception:active_tasks_by_part = defaultdict(int)free_gpus_by_part = defaultdict(int)for part in parts:proc = subprocess.run(['sinfo', '-h', '-N', '-p', part, '-o', '%N'], capture_output=True, text=True, check=False)if proc.returncode != 0:18 unmodified linesif max_per_node is not None:free = min(free, max_per_node)if free > 0:free_gpus_by_part[part] += freeordered = []now = __import__('time').time()for part in parts:cooldown_path = cooldown_dir / f'{part}.until'if cooldown_path.exists():try:until_ts = float(cooldown_path.read_text(encoding='utf-8').strip() or '0')except Exception:until_ts = 0.0if until_ts > now:continuecooldown_path.unlink(missing_ok=True)free_slots = free_gpus_by_part.get(part, 0)if free_slots <= 0:continueqos_limit = qos_limit_by_part.get(part)active_tasks = active_tasks_by_part.get(part, 0)submit_slots = free_slotsif qos_limit is not None:submit_slots = min(submit_slots, max(0, qos_limit - active_tasks - qos_headroom))part_window = partition_active_window_map.get(part, partition_active_window_default)submit_slots = min(submit_slots, max(0, part_window - active_tasks))if submit_slots > 0:ordered.append((part, free_slots, active_tasks, qos_limit if qos_limit is not None else 'na', submit_slots))ordered.sort(key=lambda row: (-int(row[4]), -int(row[1]), row[0]))out_path.write_text(''.join(f'{part}\t{free}\t{active}\t{qos}\t{submit}\n' for part, free, active, qos, submit in ordered), encoding='utf-8')print(sum(submit for _, _, _, _, submit in ordered))PY)"if [[ -z "$AVAILABLE_SLOTS" || "$AVAILABLE_SLOTS" == "0" ]]; thenecho "No free GPU/QoS submission slots detected across requested partitions."rm -f "$BASE_MANIFEST" "$PARTITION_SLOTS_FILE"exit 0fiAVAILABLE_JOB_SLOTS="$AVAILABLE_SLOTS"TARGET_VIDEO_COUNT="$PENDING_COUNT"MAX_VIDEO_COUNT="$((AVAILABLE_JOB_SLOTS * VIDEOS_PER_JOB))"if [[ "$TARGET_VIDEO_COUNT" -gt "$MAX_VIDEO_COUNT" ]]; thenTARGET_VIDEO_COUNT="$MAX_VIDEO_COUNT"head -n "$TARGET_VIDEO_COUNT" "$BASE_MANIFEST" > "$BASE_MANIFEST.tmp"mv "$BASE_MANIFEST.tmp" "$BASE_MANIFEST"fiTARGET_JOB_COUNT="$(((TARGET_VIDEO_COUNT + VIDEOS_PER_JOB - 1) / VIDEOS_PER_JOB))"echo "Created manifest: $BASE_MANIFEST"echo "Pending videos selected this cycle: $PENDING_COUNT"echo "Available GPU/QoS job slots right now: $AVAILABLE_JOB_SLOTS"echo "Submitting jobs now: $TARGET_JOB_COUNT"echo "Submitting videos now: $TARGET_VIDEO_COUNT"echo "Per-partition capacity snapshot:"while IFS=$'\t' read -r partition free_slots active_tasks qos_limit submit_slots; do[[ -z "$partition" ]] && continueecho " partition=$partition free_gpus=$free_slots active_tasks=$active_tasks qos_limit=${qos_limit:-na} submit_slots=$submit_slots"done < "$PARTITION_SLOTS_FILE"write_claims() {local manifest="$1"local job_id="$2"local index=0local task_id=0while IFS= read -r video_id; do[[ -z "$video_id" ]] && continuetask_id=$((index / VIDEOS_PER_JOB))cat > "$CLAIM_DIR/${video_id}.claim" <<CLAIMjob_id=$job_idtask_id=$task_id1 unmodified linevideo_id=$video_idsubmitted_at=$(date '+%F %T')CLAIMindex=$((index + 1))done < "$manifest"}mark_partition_submit_cooldown() {local partition="$1"mkdir -p "$PARTITION_COOLDOWN_DIR"printf '%s\n' "$(( $(date +%s) + PARTITION_QOS_COOLDOWN_SECONDS ))" > "$PARTITION_COOLDOWN_DIR/${partition}.until"}submit_partition() {local partition="$1"local manifest="$2"local count="$3"local task_count="$(((count + VIDEOS_PER_JOB - 1) / VIDEOS_PER_JOB))"local array_spec="0-$((task_count - 1))"local job_output job_idif [[ -n "$ARRAY_PARALLEL" ]]; thenarray_spec+="%${ARRAY_PARALLEL}"filocal -a cmd=(sbatch--partition "$partition"--array "$array_spec"--cpus-per-task "$CPUS_PER_TASK"--mem "$MEMORY"--time "$TIME_LIMIT"--output "$LOG_DIR/dwpose_${partition}_%A_%a.out"--error "$LOG_DIR/dwpose_${partition}_%A_%a.err"--export "ALL,ROOT_DIR=$ROOT_DIR,RUNTIME_ROOT=$RUNTIME_ROOT,STATE_ROOT=$STATE_ROOT,CONDA_SH=$CONDA_SH,CONDA_ENV=$CONDA_ENV,RAW_VIDEO_DIR=$RAW_VIDEO_DIR,SCRATCH_RAW_VIDEO_DIR=$SCRATCH_RAW_VIDEO_DIR,DATASET_DIR=$DATASET_DIR,STATS_NPZ=$STATS_NPZ,FPS=$FPS,FORCE_PROCESS=$FORCE_PROCESS,DELETE_SOURCE_ON_SUCCESS=$DELETE_SOURCE_ON_SUCCESS,MANIFEST=$manifest,CLAIM_DIR=$CLAIM_DIR,VIDEOS_PER_JOB=$VIDEOS_PER_JOB")if [[ -n "$ACCOUNT" ]]; thencmd+=(--account "$ACCOUNT")ficmd+=("$SLURM_SCRIPT")echo "Submitting partition=$partition array=$array_spec manifest=$manifest"job_output="$(${cmd[@]} 2>&1)"echo "$job_output"job_id="$(awk '/Submitted batch job/ {print $4}' <<< "$job_output" | tail -n 1)"if [[ -z "$job_id" ]]; then4 unmodified lines}submitted_total=0submitted_jobs=0failed_partitions=0line_no=1while IFS=$' ' read -r partition free_slots active_tasks qos_limit submit_slots; do[[ -z "$partition" ]] && continueif [[ "$submitted_total" -ge "$TARGET_VIDEO_COUNT" ]]; thenbreakfiremaining_videos=$((TARGET_VIDEO_COUNT - submitted_total))assign_jobs="$submit_slots"if [[ "$assign_jobs" -le 0 ]]; thencontinuefimax_videos_for_partition=$((assign_jobs * VIDEOS_PER_JOB))assign_count="$remaining_videos"if [[ "$assign_count" -gt "$max_videos_for_partition" ]]; thenassign_count="$max_videos_for_partition"fiif [[ "$assign_count" -le 0 ]]; thencontinuefishard_manifest="$MANIFEST_DIR/pending_videos_${TIMESTAMP}.${partition}.txt"sed -n "${line_no},$((line_no + assign_count - 1))p" "$BASE_MANIFEST" > "$shard_manifest"shard_count="$(wc -l < "$shard_manifest" | tr -d '[:space:]')"if [[ "$shard_count" == "0" ]]; thenrm -f "$shard_manifest"continuefiif submit_partition "$partition" "$shard_manifest" "$shard_count"; thensubmitted_total=$((submitted_total + shard_count))submitted_jobs=$((submitted_jobs + ((shard_count + VIDEOS_PER_JOB - 1) / VIDEOS_PER_JOB)))line_no=$((line_no + shard_count))elsemark_partition_submit_cooldown "$partition"echo "Partition-level submit failed for partition=$partition; cooling down and leaving those videos unclaimed for the next cycle." >&2rm -f "$shard_manifest"failed_partitions=$((failed_partitions + 1))continuefidone < "$PARTITION_SLOTS_FILE"echo "SUBMITTED_VIDEO_COUNT=$submitted_total"echo "SUBMITTED_JOB_COUNT=$submitted_jobs"echo "FAILED_PARTITION_SUBMITS=$failed_partitions"rm -f "$PARTITION_SLOTS_FILE"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687#!/usr/bin/env bashset -euo pipefail
ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_upload_parallel_slurm.sh}"PARALLEL_SHARDS="${PARALLEL_SHARDS:-8}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-8}"PARTITION="${PARTITION:-main}"START_STAGGER_MIN="${START_STAGGER_MIN:-1}"START_STAGGER_MAX="${START_STAGGER_MAX:-3}"TARGET_BYTES="${TARGET_BYTES:-10737418240}"TARGET_FOLDERS="${TARGET_FOLDERS:-40}"SLEEP_BETWEEN_WAVES="${SLEEP_BETWEEN_WAVES:-15}"PROGRESS_JSON="${PROGRESS_JSON:-/home/sf895/SignVerse-2M-runtime/archive_upload_progress.json}"HOME_DATASET_DIR="${HOME_DATASET_DIR:-/home/sf895/SignVerse-2M-runtime/dataset}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"
remaining_unuploaded() { python3 - <<PYimport jsonfrom pathlib import Pathimport syssys.path.insert(0, '/cache/home/sf895/SignVerse-2M')from utils.dataset_pool import list_unuploaded_folder_pathsprogress = json.loads(Path(r"$PROGRESS_JSON").read_text())folders = list_unuploaded_folder_paths(Path(r"$HOME_DATASET_DIR"), Path(r"$SCRATCH_DATASET_DIR"), progress.get('uploaded_folders', {}))print(len(folders))PY}
while true; do remaining="$(remaining_unuploaded)" echo "[drain] remaining_unuploaded=$remaining" if [[ "$remaining" == "0" ]]; then echo "[drain] backlog cleared" break fi
shards="$PARALLEL_SHARDS" array_parallel="$ARRAY_PARALLEL" extra_args=() needed_shards=$(((remaining + TARGET_FOLDERS - 1) / TARGET_FOLDERS)) if (( needed_shards < shards )); then shards="$needed_shards" fi if (( shards < 1 )); then shards=1 fi if (( shards == 1 )); then array_parallel="" extra_args+=(--allow-small-final-batch --no-require-target-bytes) echo "[drain] switching to single-shard tail mode" else if (( array_parallel > shards )); then array_parallel="$shards" fi echo "[drain] adaptive shard count=$shards" fi
submit_cmd=(bash "$SUBMIT_SCRIPT" --parallel-shards "$shards" --partition "$PARTITION" --start-stagger-min "$START_STAGGER_MIN" --start-stagger-max "$START_STAGGER_MAX" --target-bytes "$TARGET_BYTES" --target-folders "$TARGET_FOLDERS" ) if [[ -n "$array_parallel" ]]; then submit_cmd+=(--array-parallel "$array_parallel") fi if (( ${#extra_args[@]} > 0 )); then submit_cmd+=("${extra_args[@]}") fi
submit_out="$("${submit_cmd[@]}")" echo "$submit_out" job_id="$(awk '/Submitted batch job/{print $4}' <<< "$submit_out" | tail -n1)" if [[ -z "$job_id" ]]; then echo "[drain] failed to parse submitted job id" >&2 exit 1 fi
while [[ -n "$(squeue -h -j "$job_id" 2>/dev/null)" ]]; do sleep "$SLEEP_BETWEEN_WAVES" done sleep 2done1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495#!/usr/bin/env bashset -euo pipefail
ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"SLURM_SCRIPT="${SLURM_SCRIPT:-$ROOT_DIR/slurm/process_upload_parallel_array.slurm}"PARTITION="${PARTITION:-main}"TIME_LIMIT="${TIME_LIMIT:-24:00:00}"CPUS_PER_TASK="${CPUS_PER_TASK:-2}"MEMORY="${MEMORY:-8G}"PARALLEL_SHARDS="${PARALLEL_SHARDS:-4}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"START_STAGGER_MIN="${START_STAGGER_MIN:-1}"START_STAGGER_MAX="${START_STAGGER_MAX:-3}"TARGET_BYTES="${TARGET_BYTES:-10737418240}"TARGET_FOLDERS="${TARGET_FOLDERS:-40}"ALLOW_SMALL_FINAL_BATCH="${ALLOW_SMALL_FINAL_BATCH:-0}"REQUIRE_TARGET_BYTES="${REQUIRE_TARGET_BYTES:-1}"DRY_RUN_UPLOAD="${DRY_RUN_UPLOAD:-0}"UPLOAD_MODE="${UPLOAD_MODE:-api}"REPO_ID="${REPO_ID:-SignerX/SignVerse-2M}"REPO_REVISION="${REPO_REVISION:-dev}"
usage() { cat <<USAGEUsage: bash slurm/submit_upload_parallel_slurm.sh [options]
Options: --parallel-shards N Number of uploader shards. Default: 4 --array-parallel N Optional Slurm array concurrency cap --partition NAME Slurm partition for upload jobs. Default: main --time HH:MM:SS Default: 24:00:00 --cpus-per-task N Default: 2 --mem SIZE Default: 8G --target-bytes N Default: 10737418240 --target-folders N Default: 40 --start-stagger-min N Default: 1 --start-stagger-max N Default: 3 --allow-small-final-batch Permit smaller final shard upload batch --no-require-target-bytes Allow upload even below target-bytes --dry-run Dry-run uploader --upload-mode MODE api | api-stream | git-ssh. Default: api --repo-id ID Default: SignerX/SignVerse-2M --repo-revision BRANCH Default: dev --helpUSAGE}
while [[ $# -gt 0 ]]; do case "$1" in --parallel-shards) PARALLEL_SHARDS="$2"; shift 2 ;; --array-parallel) ARRAY_PARALLEL="$2"; shift 2 ;; --partition) PARTITION="$2"; shift 2 ;; --time) TIME_LIMIT="$2"; shift 2 ;; --cpus-per-task) CPUS_PER_TASK="$2"; shift 2 ;; --mem) MEMORY="$2"; shift 2 ;; --target-bytes) TARGET_BYTES="$2"; shift 2 ;; --target-folders) TARGET_FOLDERS="$2"; shift 2 ;; --start-stagger-min) START_STAGGER_MIN="$2"; shift 2 ;; --start-stagger-max) START_STAGGER_MAX="$2"; shift 2 ;; --allow-small-final-batch) ALLOW_SMALL_FINAL_BATCH=1; shift ;; --no-require-target-bytes) REQUIRE_TARGET_BYTES=0; shift ;; --dry-run) DRY_RUN_UPLOAD=1; shift ;; --upload-mode) UPLOAD_MODE="$2"; shift 2 ;; --repo-id) REPO_ID="$2"; shift 2 ;; --repo-revision) REPO_REVISION="$2"; shift 2 ;; -h|--help) usage; exit 0 ;; *) echo "Unknown argument: $1" >&2; usage >&2; exit 1 ;; esacdone
if (( PARALLEL_SHARDS < 1 )); then echo "--parallel-shards must be >= 1" >&2 exit 1fi
if (( START_STAGGER_MAX < START_STAGGER_MIN )); then echo "--start-stagger-max must be >= --start-stagger-min" >&2 exit 1fi
array_spec="0-$((PARALLEL_SHARDS - 1))"if [[ -n "$ARRAY_PARALLEL" ]]; then array_spec="${array_spec}%${ARRAY_PARALLEL}"fi
sbatch \ --partition="$PARTITION" \ --time="$TIME_LIMIT" \ --cpus-per-task="$CPUS_PER_TASK" \ --mem="$MEMORY" \ --array="$array_spec" \ --export=ALL,ROOT_DIR="$ROOT_DIR",RUNTIME_ROOT="$RUNTIME_ROOT",PARALLEL_SHARDS="$PARALLEL_SHARDS",START_STAGGER_MIN="$START_STAGGER_MIN",START_STAGGER_MAX="$START_STAGGER_MAX",TARGET_BYTES="$TARGET_BYTES",TARGET_FOLDERS="$TARGET_FOLDERS",ALLOW_SMALL_FINAL_BATCH="$ALLOW_SMALL_FINAL_BATCH",REQUIRE_TARGET_BYTES="$REQUIRE_TARGET_BYTES",DRY_RUN_UPLOAD="$DRY_RUN_UPLOAD",UPLOAD_MODE="$UPLOAD_MODE",REPO_ID="$REPO_ID",REPO_REVISION="$REPO_REVISION" \ "$SLURM_SCRIPT"14 unmodified lines15161718192021222314 unmodified linesGPU_PARTITIONS="${GPU_PARTITIONS:-gpu,gpu-redhat,cgpu}"GPU_ACCOUNT="${GPU_ACCOUNT:-}"SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-60}"SUBMIT_LIMIT="${SUBMIT_LIMIT:-180}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-180}"FPS="${FPS:-24}"MAX_ITERATIONS="${MAX_ITERATIONS:-0}"FORCE_PROCESS="${FORCE_PROCESS:-0}"14 unmodified lines15161718192021222314 unmodified linesGPU_PARTITIONS="${GPU_PARTITIONS:-gpu,gpu-redhat,cgpu}"GPU_ACCOUNT="${GPU_ACCOUNT:-}"SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-60}"SUBMIT_LIMIT="${SUBMIT_LIMIT:-2980}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-2980}"FPS="${FPS:-24}"MAX_ITERATIONS="${MAX_ITERATIONS:-0}"FORCE_PROCESS="${FORCE_PROCESS:-0}"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374from __future__ import annotations
from pathlib import Pathfrom typing import Dict, Iterator, List, Tuple
COMPLETE_MARKER_NAME = ".complete"
def dataset_dir_for_video( video_path: Path, home_raw_dir: Path, scratch_raw_dir: Path | None, home_dataset_dir: Path, scratch_dataset_dir: Path | None,) -> Path: if scratch_raw_dir is not None and scratch_dataset_dir is not None: try: if video_path.parent.resolve() == scratch_raw_dir.resolve(): return scratch_dataset_dir except FileNotFoundError: pass return home_dataset_dir
def iter_dataset_video_dirs(home_dataset_dir: Path, scratch_dataset_dir: Path | None = None) -> Iterator[Tuple[str, Path]]: seen: Dict[str, Path] = {} for dataset_dir in [home_dataset_dir, scratch_dataset_dir]: if dataset_dir is None or not dataset_dir.exists(): continue for folder_path in sorted(dataset_dir.iterdir()): if not folder_path.is_dir(): continue seen.setdefault(folder_path.name, folder_path) for video_id, folder_path in sorted(seen.items()): yield video_id, folder_path
def complete_video_ids(home_dataset_dir: Path, scratch_dataset_dir: Path | None = None) -> set[str]: complete: set[str] = set() for video_id, folder_path in iter_dataset_video_dirs(home_dataset_dir, scratch_dataset_dir): if (folder_path / "npz" / COMPLETE_MARKER_NAME).exists(): complete.add(video_id) return complete
def count_complete(home_dataset_dir: Path, scratch_dataset_dir: Path | None = None) -> int: return len(complete_video_ids(home_dataset_dir, scratch_dataset_dir))
def find_dataset_video_dir(video_id: str, home_dataset_dir: Path, scratch_dataset_dir: Path | None = None) -> Path: home_path = home_dataset_dir / video_id if home_path.exists(): return home_path if scratch_dataset_dir is not None: scratch_path = scratch_dataset_dir / video_id if scratch_path.exists(): return scratch_path return home_path
def list_unuploaded_folder_paths( home_dataset_dir: Path, scratch_dataset_dir: Path | None, uploaded_folders: Dict[str, object],) -> List[Tuple[str, Path]]: folders: List[Tuple[str, Path]] = [] for video_id, folder_path in iter_dataset_video_dirs(home_dataset_dir, scratch_dataset_dir): if video_id in uploaded_folders: continue if not (folder_path / "npz" / COMPLETE_MARKER_NAME).exists(): continue folders.append((video_id, folder_path)) return folders123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164from __future__ import annotations
import contextlibimport fcntlfrom pathlib import Pathfrom typing import Iterable, Iterator, Sequence
VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov"}
def existing_raw_dirs(*dirs: Path | None) -> list[Path]: result: list[Path] = [] seen: set[str] = set() for directory in dirs: if directory is None: continue key = str(directory) if key in seen: continue seen.add(key) result.append(directory) return result
def collect_raw_videos(*dirs: Path | None) -> dict[str, Path]: videos: dict[str, Path] = {} for directory in existing_raw_dirs(*dirs): if not directory.exists(): continue for path in sorted(directory.iterdir()): if not path.is_file() or path.suffix.lower() not in VIDEO_EXTENSIONS: continue videos.setdefault(path.stem, path) return videos
def count_raw_videos(*dirs: Path | None) -> int: return len(collect_raw_videos(*dirs))
def sum_raw_video_sizes(*dirs: Path | None) -> int: return sum(path.stat().st_size for path in collect_raw_videos(*dirs).values() if path.exists())
def iter_raw_video_files(*dirs: Path | None) -> Iterator[Path]: for path in collect_raw_videos(*dirs).values(): yield path
def find_video_file(video_id: str, *dirs: Path | None) -> Path | None: for directory in existing_raw_dirs(*dirs): if not directory.exists(): continue candidates = [] for path in directory.glob(f"{video_id}.*"): if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS: candidates.append(path) if candidates: return sorted(candidates)[0] return None
def iter_partial_download_files(video_id: str, *dirs: Path | None) -> Iterator[Path]: seen: set[Path] = set() for directory in existing_raw_dirs(*dirs): if not directory.exists(): continue for path in directory.glob(f"{video_id}*"): if not path.is_file(): continue suffixes = set(path.suffixes) if '.part' in suffixes or '.ytdl' in suffixes or path.suffix in {'.part', '.ytdl'}: resolved = path.resolve() if resolved in seen: continue seen.add(resolved) yield path
def cleanup_partial_downloads(video_id: str, *dirs: Path | None) -> None: for partial_path in iter_partial_download_files(video_id, *dirs): partial_path.unlink(missing_ok=True)
def _count_reservations(reservation_dir: Path | None, pool_name: str) -> int: if reservation_dir is None: return 0 pool_dir = reservation_dir / pool_name if not pool_dir.exists(): return 0 return sum(1 for path in pool_dir.iterdir() if path.is_file() and path.suffix == ".reserve")
def _create_reservation(reservation_dir: Path | None, pool_name: str, reservation_key: str | None) -> Path | None: if reservation_dir is None or not reservation_key: return None pool_dir = reservation_dir / pool_name pool_dir.mkdir(parents=True, exist_ok=True) reservation_path = pool_dir / f"{reservation_key}.reserve" reservation_path.write_text(f"pool={pool_name}\nkey={reservation_key}\n", encoding="utf-8") return reservation_path
def release_download_reservation(reservation_path: Path | None) -> None: if reservation_path is not None: reservation_path.unlink(missing_ok=True)
def choose_download_target( primary_dir: Path, scratch_dir: Path | None, primary_limit: int, scratch_limit: int, reservation_dir: Path | None = None, reservation_key: str | None = None,) -> tuple[Path, Path | None]: primary_dir.mkdir(parents=True, exist_ok=True) if reservation_dir is None: primary_count = count_raw_videos(primary_dir) if primary_count < primary_limit: return primary_dir, None if scratch_dir is None: raise RuntimeError( f"raw backlog full in primary pool ({primary_count}/{primary_limit}) and no scratch raw pool configured" ) scratch_dir.mkdir(parents=True, exist_ok=True) scratch_count = count_raw_videos(scratch_dir) if scratch_count < scratch_limit: return scratch_dir, None raise RuntimeError( f"raw backlog full in both pools: primary {primary_count}/{primary_limit}, scratch {scratch_count}/{scratch_limit}" )
reservation_dir.mkdir(parents=True, exist_ok=True) lock_path = reservation_dir / ".target_selection.lock" with lock_path.open("a+", encoding="utf-8") as lock_handle: fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX) try: primary_count = count_raw_videos(primary_dir) + _count_reservations(reservation_dir, "home") if primary_count < primary_limit: return primary_dir, _create_reservation(reservation_dir, "home", reservation_key) if scratch_dir is None: raise RuntimeError( f"raw backlog full in primary pool ({primary_count}/{primary_limit}) and no scratch raw pool configured" ) scratch_dir.mkdir(parents=True, exist_ok=True) scratch_count = count_raw_videos(scratch_dir) + _count_reservations(reservation_dir, "scratch") if scratch_count < scratch_limit: return scratch_dir, _create_reservation(reservation_dir, "scratch", reservation_key) raise RuntimeError( f"raw backlog full in both pools: primary {primary_count}/{primary_limit}, scratch {scratch_count}/{scratch_limit}" ) finally: with contextlib.suppress(OSError): fcntl.flock(lock_handle.fileno(), fcntl.LOCK_UN)
def remove_video_files(video_id: str, *dirs: Path | None) -> None: for directory in existing_raw_dirs(*dirs): if not directory.exists(): continue for path in directory.glob(f"{video_id}.*"): if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS: path.unlink(missing_ok=True)12345678970 unmodified lines808182838485868744 unmodified lines132133134import fcntlimport osimport timeimport zipfilefrom pathlib import Pathfrom typing import Dict, Iterableimport numpy as np70 unmodified linesfor field in STATUS_FIELDS:payload[field] = np.asarray([stats[video_id].get(field, "") for video_id in video_ids], dtype=object)tmp_path = stats_path.parent / f".{stats_path.stem}.{os.getpid()}.tmp.npz"np.savez(tmp_path, **payload)os.replace(tmp_path, stats_path)def ensure_record(stats: Dict[str, Dict[str, str]], video_id: str) -> Dict[str, str]:44 unmodified linesif last_error is not None:raise last_error1234567891070 unmodified lines81828384858687888990919244 unmodified lines137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264import fcntlimport jsonimport osimport timeimport zipfilefrom pathlib import Pathfrom typing import Dict, Iterable, Sequenceimport numpy as np70 unmodified linesfor field in STATUS_FIELDS:payload[field] = np.asarray([stats[video_id].get(field, "") for video_id in video_ids], dtype=object)tmp_path = stats_path.parent / f".{stats_path.stem}.{os.getpid()}.tmp.npz"try:np.savez(tmp_path, **payload)os.replace(tmp_path, stats_path)finally:if tmp_path.exists():tmp_path.unlink(missing_ok=True)def ensure_record(stats: Dict[str, Dict[str, str]], video_id: str) -> Dict[str, str]:44 unmodified linesif last_error is not None:raise last_errordef journal_lock_path(journal_path: Path) -> Path:return journal_path.with_suffix(journal_path.suffix + ".lock")def sidecar_status_dir(stats_path: Path) -> Path:return stats_path.parent / "video_status"def sidecar_status_path(stats_path: Path, video_id: str) -> Path:return sidecar_status_dir(stats_path) / f"{video_id}.jsonl"def append_status_journal(journal_path: Path, video_ids: Sequence[str], **updates: str) -> None:journal_path.parent.mkdir(parents=True, exist_ok=True)payload = {"video_ids": list(video_ids),"updates": {key: ("" if value is None else str(value)) for key, value in updates.items()},"recorded_at": time.strftime("%Y-%m-%d %H:%M:%S"),}lock_path = journal_lock_path(journal_path)with lock_path.open("a+", encoding="utf-8") as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:with journal_path.open("a", encoding="utf-8") as journal_handle:journal_handle.write(json.dumps(payload, ensure_ascii=False) + "\n")finally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)def append_status_sidecar(stats_path: Path, video_id: str, **updates: str) -> None:payload = {"video_ids": [video_id],"updates": {key: ("" if value is None else str(value)) for key, value in updates.items()},"recorded_at": time.strftime("%Y-%m-%d %H:%M:%S"),}sidecar_path = sidecar_status_path(stats_path, video_id)sidecar_path.parent.mkdir(parents=True, exist_ok=True)lock_path = journal_lock_path(sidecar_path)with lock_path.open("a+", encoding="utf-8") as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:with sidecar_path.open("a", encoding="utf-8") as sidecar_handle:sidecar_handle.write(json.dumps(payload, ensure_ascii=False) + "\n")finally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)def update_video_stats_best_effort(stats_path: Path, journal_path: Path, video_id: str, **updates: str) -> Dict[str, str]:append_status_sidecar(stats_path, video_id, **updates)return {key: ("" if value is None else str(value)) for key, value in updates.items() if key in STATUS_FIELDS}def update_many_video_stats_best_effort(stats_path: Path, journal_path: Path, video_ids: Sequence[str], **updates: str) -> None:try:update_many_video_stats_with_retry(stats_path, video_ids, **updates)except Exception:append_status_journal(journal_path, video_ids, **updates)def _apply_payloads_to_stats(stats_path: Path, payloads: Sequence[dict]) -> int:if not payloads:return 0update_count = 0stats_lock_path = _lock_path(stats_path)stats_lock_path.parent.mkdir(parents=True, exist_ok=True)with stats_lock_path.open("a+", encoding="utf-8") as stats_handle:fcntl.flock(stats_handle.fileno(), fcntl.LOCK_EX)try:stats = _load_stats_unlocked(stats_path)for payload in payloads:video_ids = [str(item) for item in payload.get("video_ids", []) if str(item)]updates = payload.get("updates", {})if not video_ids or not isinstance(updates, dict):continuefor video_id in video_ids:record = ensure_record(stats, video_id)for key, value in updates.items():if key in STATUS_FIELDS:record[key] = "" if value is None else str(value)update_count += 1if update_count:save_stats(stats_path, stats)finally:fcntl.flock(stats_handle.fileno(), fcntl.LOCK_UN)return update_countdef apply_status_journal_to_stats(stats_path: Path, journal_path: Path, remove_applied: bool = True) -> int:payloads = []if journal_path.exists() and journal_path.stat().st_size > 0:lock_path = journal_lock_path(journal_path)with lock_path.open("a+", encoding="utf-8") as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:if journal_path.exists() and journal_path.stat().st_size > 0:for line in journal_path.read_text(encoding="utf-8").splitlines():if line.strip():payloads.append(json.loads(line))if remove_applied:journal_path.unlink(missing_ok=True)finally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)sidecar_dir = sidecar_status_dir(stats_path)if sidecar_dir.exists():for sidecar_path in sorted(sidecar_dir.glob("*.jsonl")):lock_path = journal_lock_path(sidecar_path)with lock_path.open("a+", encoding="utf-8") as handle:fcntl.flock(handle.fileno(), fcntl.LOCK_EX)try:if sidecar_path.exists() and sidecar_path.stat().st_size > 0:for line in sidecar_path.read_text(encoding="utf-8").splitlines():if line.strip():payloads.append(json.loads(line))if remove_applied:sidecar_path.unlink(missing_ok=True)finally:fcntl.flock(handle.fileno(), fcntl.LOCK_UN)if remove_applied:lock_path.unlink(missing_ok=True)return _apply_payloads_to_stats(stats_path, payloads)
reproduce_independently.sh+4
reproduce_independently_slurm.sh+177-70
scripts/pipeline01_download_video_fix_caption.py+53-45
scripts/pipeline02_extract_dwpose_from_video.py+28-9
scripts/pipeline03_upload_to_huggingface.py+286-102
scripts/runtime_status.py+155-18
scripts/sync_processed_csv_from_runtime.py+13-2
slurm/orchestrator_autorestart.slurm+39-8
slurm/process_download_array.slurm+8
slurm/process_dwpose_array.slurm+107-49
slurm/process_upload_parallel_array.slurmAdded+99
slurm/run_reproduce_independently_slurm.slurm+2-2
slurm/submit_download_slurm.sh+50-14
slurm/submit_dwpose_slurm.sh+223-58
slurm/submit_upload_parallel_drain.shAdded+87
slurm/submit_upload_parallel_slurm.shAdded+95
slurm/watch_submit_dwpose.slurm+2-2
utils/dataset_pool.pyAdded+74
utils/raw_video_pool.pyAdded+164
utils/stats_npz.py+133-3