Codex commited on
Commit ·
cd27dad
1
Parent(s): 1d7e5b8
Revert "Sync latest local production code"
Browse filesThis reverts commit 1d7e5b8e79c6190f880cd74fe7fde7e55081f86d.
Files changed (14)
- README.md+336-3
- reproduce_independently_slurm.sh+4-4
- scripts/pipeline01_backfill_subtitles.pyDeleted-254
- scripts/pipeline01_download_video_fix_caption.py+117-184
- scripts/pipeline02_extract_dwpose_from_video.py+4-39
- scripts/pipeline03_upload_to_huggingface.py+22-40
- slurm/orchestrator_autorestart.slurm+2-2
- slurm/submit_download_slurm.sh+2-2
- slurm/submit_dwpose_slurm.sh+2-2
- slurm/submit_upload_parallel_drain.sh+11-45
- slurm/submit_upload_parallel_slurm.sh+2-2
- slurm/watch_submit_dwpose.slurm+1-1
- utils/draw_dw_lib.py+204-31
- utils/raw_video_pool.py+7-34
123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336---
license: mit
------license: cc-by-nc-4.0language: - ase - bfi - gsg - sgd - fsl - lsf - lse - lis - lgp - ngt - asf - jsl - kvk - csl - aed - tsm - pjm - rsl - swl - dsl - fse - nsl - lsc - lsm - bzstask_categories: - othertags: - sign-language - pose-estimation - dwpose - multilingual - keypoint - video-understanding - sign-language-generation - sign-language-recognition - pose-nativesize_categories: - 1M<n<10Mpretty_name: "SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages"---
<div align="center" style="position: relative; width: 100%; max-width: 1400px; margin: 0 auto 24px auto;"> <img src="https://signerx.github.io/SignVerse-2M/static/images/background_gallery_big.gif" alt="SignVerse-2M cover" style="width: 100%; display: block; border-radius: 18px;" /> <div style=" position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; background: linear-gradient(to bottom, rgba(0,0,0,0.18), rgba(0,0,0,0.28)); border-radius: 18px; " > <div style=" color: white; font-size: 3.4rem; font-weight: 800; letter-spacing: 0.04em; text-shadow: 0 4px 20px rgba(0,0,0,0.45); " > SignVerse-2M </div> </div></div>
## SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages
Links: [[Paper]](https://arxiv.org/abs/2605.01720) | [[Data Files]](https://huggingface.co/datasets/SignerX/SignVerse-2M/tree/main/dataset) | [[Project Page]](https://signerx.github.io/SignVerse-2M)
**SignVerse-2M** is a large-scale multilingual pose-native dataset for sign language research. The dataset reorganizes publicly available sign language videos into a unified DWPose-based representation and releases the result as approximately **2 million clips** from **39,196 videos** covering **55+ sign languages**. Rather than distributing raw RGB video, SignVerse-2M provides per-frame body, hand, and face keypoints together with structured subtitle supervision, making the corpus directly usable for pose-conditioned sign language generation, recognition, and translation research.
## Overview
Existing large-scale sign language resources are typically organized as video-text corpora. That format is appropriate for RGB-based recognition or translation, but it is not the most natural interface for modern pose-driven generation pipelines, which increasingly operate on standardized human keypoint controls such as DWPose. SignVerse-2M addresses this mismatch by converting multilingual public sign language videos into a common pose space.
The release is intended to support research questions such as:
- multilingual sign language generation in pose space- pose-based sign language recognition and translation- cross-lingual transfer across heterogeneous sign language sources- benchmarking of sign language motion representations under open-world conditions
## Key Characteristics
| Property | Value || --- | --- || Dataset name | SignVerse-2M || Core representation | DWPose keypoint sequences || Videos | 39,196 || Clips / subtitle segments | Approximately 2 million || Sign languages | 55+ || Frame rate | 24 FPS || Per-frame keypoints | 18 body + 21 left hand + 21 right hand + 68 face = 128 || Source type | Public multilingual sign language videos || Raw RGB frames released | No || Released supervision | Structured subtitle text and document-level text |
## Why A Pose-Native Release
SignVerse-2M should not be understood as merely a larger multilingual video-text corpus. Its main contribution is the release of a unified pose-native interface for sign language research.
Compared with raw-video releases, the pose-native representation offers three practical advantages:
1. It reduces nuisance variation from background, clothing, and appearance, allowing models to focus more directly on motion.2. It aligns naturally with contemporary pose-conditioned generation pipelines that already consume DWPose-like controls.3. It provides a common representation for multilingual benchmarking, making comparisons across methods more interpretable.
## Data Source And Processing
The corpus is built from publicly available multilingual sign language videos ([YouTube-SL-25](https://arxiv.org/abs/2407.11144)), including resources inherited from large public sign language collections such as YouTube-SL-55 and related open web sources. Each video is processed through a unified pipeline that:
1. retrieves metadata and available subtitles,2. structures subtitle tracks into segment-level and document-level text,3. decodes the video at 24 FPS,4. applies DWPose to extract body, hand, and face keypoints frame by frame,5. packages the outputs into per-video artifacts for public release.
No manual keypoint annotation is provided. The keypoints and subtitles are produced automatically through the preprocessing pipeline.
## Languages
The corpus covers more than 55 sign languages. Major language codes in the current release include:
| Code | Language | Code | Language || --- | --- | --- | --- || `ase` | American Sign Language | `lsf` | French Sign Language || `bfi` | British Sign Language | `lse` | Spanish Sign Language || `gsg` | German Sign Language | `lis` | Italian Sign Language || `sgd` | Swiss German Sign Language | `lgp` | Portuguese Sign Language || `asf` | Australian Sign Language | `ngt` | Sign Language of the Netherlands || `jsl` | Japanese Sign Language | `kvk` | Korean Sign Language || `csl` | Chinese Sign Language | `bzs` | Brazilian Sign Language || `lsm` | Mexican Sign Language | `pjm` | Polish Sign Language |
The language distribution is long-tailed rather than balanced. High-resource languages account for a disproportionate share of the total data volume.
## Repository Structure
The public release is organized around `.tar` shards stored under `dataset/`. Each shard contains per-video directories:
```textdataset/ Sign_DWPose_NPZ_000001.tar Sign_DWPose_NPZ_000002.tar ...```
Within each shard:
```text{video_id}/ poses.npz caption.json {video_id}.complete```
The main files are:
- `poses.npz`: per-video DWPose payload with frame-wise keypoints- `caption.json`: structured subtitle and supervision metadata- `.complete`: completion marker produced by the processing pipeline
## Data Schema
### `poses.npz`
Each `poses.npz` file stores a person-centric per-frame representation. A simplified schema is shown below:
```python{ "video_id": str, "fps": float, "num_frames": int, "frame_ids": int[T], "width": int, "height": int, "frames": [ { "num_people": int, "frame_id": int, "width": int, "height": int, "person_0": { "body": float[18, 3], "face": float[68, 3], "left_hand": float[21, 3], "right_hand": float[21, 3], }, # optional additional people: # "person_1": { ... } }, ... ]}```
Keypoint coordinates are stored in pixel space as `(x, y, score)`, where confidence scores lie in `[0, 1]`.
### `caption.json`
```json{ "video_id": "...", "sign_language": "ase", "title": "...", "duration_s": 312.4, "segments": [ { "start": 0.0, "end": 4.2, "text": "..." } ], "document_text": "...", "english_source": "native"}```
The field `english_source` records whether the English supervision is native or automatically selected from an available translated subtitle track.
## Loading Example
```pythonimport jsonimport tarfileimport numpy as np
with tarfile.open("dataset/Sign_DWPose_NPZ_000001.tar") as tar: tar.extractall("./tmp_signverse")
npz = np.load("./tmp_signverse/{video_id}/poses.npz", allow_pickle=True)frames = npz["frames"].tolist()body = frames[0]["person_0"]["body"]
with open("./tmp_signverse/{video_id}/caption.json", "r", encoding="utf-8") as f: caption = json.load(f)
print(body.shape)print(caption["segments"][0]["text"])```
## Visualization And Reproduction
The repository includes scripts for inspecting the released pose files and for reproducing the processing pipeline.
### Visualize one pose file
```bashpython scripts/visualize_dwpose_npz.py \ --npz extracted/{video_id}/poses.npz \ --style openpose \ --out viz/```
### Reproduce the pipeline
```bash# Single machinebash reproduce_independently.sh
# SLURM clusterbash reproduce_independently_slurm.sh```
The pipeline is organized into acquisition, subtitle structuring, pose extraction, and upload/publication stages.
## Benchmark Setting
The accompanying paper introduces a multilingual **text-to-pose** benchmark for sign language generation. A generated DWPose sequence is evaluated through back-translation into spoken text, and standard text metrics such as BLEU and ROUGE are reported against the source input. The benchmark repository also provides a **SignDW Transformer** baseline in both small and large model configurations.
For model code and experimental setup, refer to the benchmark repository:
- [https://github.com/SignerX/SignVerse-2M](https://github.com/SignerX/SignVerse-2M)
## Intended Use
The release is intended for research use, including:
- sign language generation from text via pose space- pose-based sign language translation and recognition- cross-lingual transfer, adaptation, and benchmarking- comparison of pose-native motion representations under open-world distributions
The release is not intended for:
- safety-critical interpretation in medical, legal, or emergency settings- re-identification of individual signers- claims of full linguistic coverage for any specific sign language
<!--## Limitations
Users should account for the following limitations when interpreting results:
- Keypoints are extracted automatically and may be noisy under fast motion, occlusion, or multi-person scenes.- Fine-grained handshape distinctions are only partially captured by the released 21-keypoint hand representation.- Non-manual linguistic signals such as facial expression and mouthing are only partially represented by 68 face landmarks.- Subtitle timing and translations are automatically processed and may contain alignment or semantic errors.- The corpus is language-imbalanced and inherits the long-tail distribution of public web video sources.- `person_0` is treated as the primary signer, which may be imperfect in multi-signer videos.-->
## Responsible Use
SignVerse-2M is derived from publicly posted sign language videos. This repository does **not** redistribute raw RGB videos; it releases pose keypoints and structured subtitle text only. Even so, pose sequences may still carry information that can contribute to signer identification when combined with external metadata. Users should treat the corpus as human-subject-derived data and use it responsibly.
The data distribution is also shaped by what is publicly available online. Educational or interpreter-style content may be overrepresented, while conversational, regional, or community-specific signing practices may be underrepresented.
## Citation
If you use SignVerse-2M in academic work, please cite:
```bibtex@misc{fang2026signverse2mtwomillionclipposenativeuniverse, title={SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages}, author={Sen Fang and Hongbin Zhong and Yanxin Zhang and Dimitris N. Metaxas}, year={2026}, eprint={2605.01720}, archivePrefix={arXiv}, primaryClass={cs.CV}, url={https://arxiv.org/abs/2605.01720}, }```
## License
The released dataset annotations, pose keypoints, and accompanying metadata are distributed under **CC BY-NC 4.0**.
Source videos are **not** redistributed in this repository and remain subject to the original platform terms and the rights of their respective creators.40 unmodified lines414243444445464714 unmodified lines6263646565666768697071717273744 unmodified lines798081828283848540 unmodified linesTARGET_FOLDERS="${TARGET_FOLDERS:-40}"UPLOAD_PARALLEL_SHARDS="${UPLOAD_PARALLEL_SHARDS:-8}"UPLOAD_ARRAY_PARALLEL="${UPLOAD_ARRAY_PARALLEL:-8}"UPLOAD_PARTITION="${UPLOAD_PARTITION:-main-redhat}"UPLOAD_PARTITION="${UPLOAD_PARTITION:-main}"UPLOAD_START_STAGGER_MIN="${UPLOAD_START_STAGGER_MIN:-1}"UPLOAD_START_STAGGER_MAX="${UPLOAD_START_STAGGER_MAX:-3}"DOWNLOAD_BATCH_SIZE="${DOWNLOAD_BATCH_SIZE:-1}"14 unmodified linesEXTRACTOR_ARGS="${EXTRACTOR_ARGS:-}"SLURM_PROCESS_SUBMIT_SCRIPT="${SLURM_PROCESS_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"SLURM_DOWNLOAD_SUBMIT_SCRIPT="${SLURM_DOWNLOAD_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_download_slurm.sh}"GPU_PARTITIONS="gpu-redhat,gpu,cgpu"GPU_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-redhat}"DOWNLOAD_PARTITIONS="${DOWNLOAD_PARTITIONS:-main}"DOWNLOAD_ACCOUNT="${DOWNLOAD_ACCOUNT:-}"DOWNLOAD_TIME="${DOWNLOAD_TIME:-04:00:00}"DOWNLOAD_CPUS_PER_TASK="${DOWNLOAD_CPUS_PER_TASK:-1}"4 unmodified linesDOWNLOAD_START_STAGGER_MAX="${DOWNLOAD_START_STAGGER_MAX:-3}"DOWNLOAD_CLAIM_GRACE_SECONDS="${DOWNLOAD_CLAIM_GRACE_SECONDS:-600}"DOWNLOAD_PARTIAL_TIMEOUT_SECONDS="${DOWNLOAD_PARTIAL_TIMEOUT_SECONDS:-1800}"ORCHESTRATOR_PARTITION="${ORCHESTRATOR_PARTITION:-main-redhat}"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}"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254#!/usr/bin/env python3
import argparseimport jsonimport sysimport timefrom pathlib import Pathfrom typing import Dict, List, Sequence, Tuple
REPO_ROOT = Path(__file__).resolve().parents[1]if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT))
from scripts.pipeline01_download_video_fix_caption import ( DEFAULT_DATASET_DIR, DEFAULT_OUTPUT_METADATA_CSV, DEFAULT_SOURCE_METADATA_CSV, DEFAULT_STATUS_JOURNAL_PATH, DEFAULT_YT_DLP_EXTRACTOR_ARGS, DEFAULT_COLUMNS, DEFAULT_RAW_METADATA_DIR, build_subtitle_json_payload, fetch_metadata, filter_caption_languages, load_subtitle_payloads, lock_path_for_manifest, merge_row_values, persist_raw_metadata, read_state_manifest, repo_relative_or_absolute, sanitize_cookie_file, select_english_subtitle, subtitle_dir_for_video, update_video_stats_best_effort, with_manifest_lock, write_manifest, write_subtitle_json, download_subtitles,)
EXTRA_COLUMNS = [ "subtitle_texts_json", "subtitle_en", "subtitle_json_path", "raw_caption_dir",]
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Backfill subtitles only for SignVerse videos, without downloading video payloads." ) parser.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("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR) parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR) parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH) parser.add_argument("--stats-npz", type=Path, default=REPO_ROOT / '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") parser.add_argument("--force-subtitles", action="store_true") parser.add_argument("--sleep-seconds", type=float, default=0.0) parser.add_argument("--cookies", type=Path, default=None) parser.add_argument("--cookies-from-browser", default=None) parser.add_argument("--extractor-args", default=DEFAULT_YT_DLP_EXTRACTOR_ARGS) parser.add_argument("--csv-lock-path", type=Path, default=None) return parser.parse_args()
def ordered_fieldnames(fieldnames: Sequence[str]) -> List[str]: ordered: List[str] = [] for column in list(DEFAULT_COLUMNS) + EXTRA_COLUMNS + list(fieldnames): if column and column not in ordered: ordered.append(column) return ordered
def row_needs_subtitle_backfill(row: Dict[str, str], args: argparse.Namespace) -> bool: if args.force_metadata or args.force_subtitles: return True return (row.get("subtitle_status") or "").strip() != "ok"
def selected_rows(rows: Sequence[Dict[str, str]], args: argparse.Namespace) -> List[Dict[str, str]]: selected: List[Dict[str, str]] = [] video_id_filter = set(args.video_ids or []) for row in rows: video_id = (row.get("video_id") or "").strip() if not video_id: continue if video_id_filter and video_id not in video_id_filter: continue if not row_needs_subtitle_backfill(row, args): continue selected.append(dict(row)) if args.limit is not None and len(selected) >= args.limit: break return selected
def persist_row_update(args: argparse.Namespace, video_id: str, updated_row: Dict[str, str], fieldnames: Sequence[str]) -> None: lock_path = lock_path_for_manifest(args.output_metadata_csv, args.csv_lock_path) handle = with_manifest_lock(lock_path) try: rows, current_fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv) merged_fieldnames = ordered_fieldnames(list(current_fieldnames) + list(fieldnames)) found = False for row in rows: if (row.get("video_id") or "").strip() == video_id: merge_row_values(row, updated_row, merged_fieldnames) found = True break if not found: new_row = {column: updated_row.get(column, "") for column in merged_fieldnames} rows.append(new_row) write_manifest(args.output_metadata_csv, rows, merged_fieldnames) finally: import fcntl fcntl.flock(handle.fileno(), fcntl.LOCK_UN) handle.close()
def main() -> None: args = parse_args() temp_cookie_path: Path | None = None if args.cookies: temp_cookie_path = sanitize_cookie_file(args.cookies) args._effective_cookies = temp_cookie_path else: args._effective_cookies = None
try: rows, fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv) fields = ordered_fieldnames(fieldnames) pending = selected_rows(rows, args) args.dataset_dir.mkdir(parents=True, exist_ok=True) args.raw_metadata_dir.mkdir(parents=True, exist_ok=True)
print(f"subtitle_backfill_selected={len(pending)}")
ok_count = 0 missing_count = 0 failed_count = 0 partial_count = 0
for index, row in enumerate(pending, start=1): video_id = (row.get("video_id") or "").strip() print(f"[{index}/{len(pending)}] subtitle backfill {video_id}", flush=True) subtitle_error = "" metadata_error = "" stats_record: Dict[str, object] = {} try: metadata_path = args.raw_metadata_dir / f"{video_id}.json" if metadata_path.exists() and not args.force_metadata: metadata = json.loads(metadata_path.read_text(encoding="utf-8")) else: metadata, metadata_error = fetch_metadata(video_id, args) persist_raw_metadata(args.raw_metadata_dir, video_id, metadata) row["metadata_status"] = "ok" row["raw_metadata_path"] = repo_relative_or_absolute(metadata_path) row["title"] = str(metadata.get("title") or row.get("title") or "") row["duration_sec"] = str(metadata.get("duration") or row.get("duration_sec") or "") row["start_sec"] = row.get("start_sec") or "0" row["end_sec"] = str(metadata.get("duration") or row.get("end_sec") or "")
manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata) preferred_manual = manual_langs[:1] preferred_native_auto = [] if preferred_manual else native_automatic_langs[:1] subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id) need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt")) if need_subtitles: subtitle_error = download_subtitles( video_id, subtitle_dir, preferred_manual, preferred_native_auto, english_translation_lang, args, ) subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id) row["subtitle_status"] = "ok" if subtitle_payloads else "missing" row["subtitle_languages"] = "|".join(sorted(subtitle_payloads)) row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else "" subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads) row["subtitle_en"] = subtitle_en row["subtitle_en_source"] = subtitle_en_source subtitle_json_path = write_subtitle_json(subtitle_dir, video_id, subtitle_payloads, subtitle_en, subtitle_en_source) row["subtitle_json_path"] = repo_relative_or_absolute(subtitle_json_path) if subtitle_json_path else "" row["subtitle_texts_json"] = json.dumps( build_subtitle_json_payload(video_id, subtitle_payloads, subtitle_en, subtitle_en_source).get("subtitle_texts", {}), ensure_ascii=False, ) if subtitle_payloads else "" row["raw_caption_dir"] = row["subtitle_dir_path"] row["download_status"] = row.get("download_status") or "" row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S") row["error"] = subtitle_error or metadata_error
stats_record.update({ "title": row["title"], "duration_sec": row["duration_sec"], "start_sec": row["start_sec"], "end_sec": row["end_sec"], "subtitle_languages": row["subtitle_languages"], "subtitle_dir_path": row["subtitle_dir_path"], "subtitle_en_source": row["subtitle_en_source"], "raw_metadata_path": row["raw_metadata_path"], "metadata_status": row["metadata_status"], "subtitle_status": row["subtitle_status"], "download_status": row["download_status"], "updated_at": row["processed_at"], "last_error": row["error"], }) persist_row_update(args, video_id, row, fields) update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
status = row["subtitle_status"] if status == "ok": ok_count += 1 elif status == "missing": missing_count += 1 elif status == "partial": partial_count += 1 else: failed_count += 1 print(f" subtitle_status={status} langs={row['subtitle_languages']}", flush=True) except Exception as exc: row["subtitle_status"] = "failed" row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S") row["error"] = str(exc) stats_record.update({ "subtitle_status": row["subtitle_status"], "updated_at": row["processed_at"], "last_error": row["error"], }) persist_row_update(args, video_id, row, fields) update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record) failed_count += 1 print(f" subtitle_status=failed error={exc}", flush=True) if args.sleep_seconds > 0: time.sleep(args.sleep_seconds)
print( f"subtitle_backfill_done ok={ok_count} missing={missing_count} partial={partial_count} failed={failed_count}", flush=True, ) finally: if temp_cookie_path is not None: temp_cookie_path.unlink(missing_ok=True)
if __name__ == '__main__': main()175 unmodified lines176177178179180181182183184185186187188179180181182183184193185186187593 unmodified lines78178278379379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183278483483583683778578678723 unmodified lines81181281386786886987087181481581681725 unmodified lines8438448459039049059069078468478488499089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429438509459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989998518528538548558568578581001100210031004100510061007100810091010101110121013101410151016101710181019102085986086186286386410241025102610271028865866867103186886910341035870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971175 unmodified lines
def write_manifest(csv_path: Path, rows: Sequence[Dict[str, str]], fieldnames: Sequence[str]) -> None: csv_path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", newline="", suffix=csv_path.suffix + ".tmp", prefix=csv_path.stem + ".", dir=csv_path.parent, delete=False, ) as handle: tmp_path = csv_path.with_suffix(csv_path.suffix + ".tmp") with tmp_path.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow({column: row.get(column, "") for column in fieldnames}) tmp_path = Path(handle.name) tmp_path.replace(csv_path)
593 unmodified lines return 0
def is_terminal_source_error(error_text: str) -> bool: normalized = (error_text or "").strip().lower() if not normalized: return False
non_terminal_markers = ( "sign in", "cookies", "cookie", "429", "too many requests", "timed out", "timeout", "connection reset", "temporary failure", "network is unreachable", "http error 5", "unable to download", "requested format is not available", "filenotfounderror", "no such file or directory", ) if any(marker in normalized for marker in non_terminal_markers): return False
terminal_markers = ( "video unavailable", "this video is private", "private video", "this video has been removed", "video has been removed", "account associated with this video has been terminated", "the playlist does not exist", "not a valid url", "copyright claim", "410 gone", ) return any(marker in normalized for marker in terminal_markers)
def record_row_failure(row: Dict[str, str], stats_record: Dict[str, object], error_text: str, max_failures_before_skip: int) -> tuple[int, bool]: if not is_terminal_source_error(error_text): stats_record["failure_count"] = row.get("failure_count", "0") return row_failure_count(row), False
failure_count = row_failure_count(row) + 1 row["failure_count"] = str(failure_count) stats_record["failure_count"] = row["failure_count"]23 unmodified lines needs_metadata = metadata_status != "ok" # Treat missing subtitles as a terminal state so videos without captions are not retried forever. needs_subtitles = (not args.skip_subtitles) and subtitle_status not in {"ok", "missing", "skipped"} needs_download = ( (not args.skip_video_download) and subtitle_status == "ok" and download_status not in {"ok", "skipped"} ) needs_download = (not args.skip_video_download) and download_status != "ok" return needs_metadata or needs_subtitles or needs_download
25 unmodified lines metadata: Dict[str, object] | None = None
try: try: metadata_path = args.raw_metadata_dir / f"{video_id}.json" if metadata_path.exists() and not args.force_metadata: with metadata_path.open("r", encoding="utf-8") as handle: metadata = json.load(handle) metadata_path = args.raw_metadata_dir / f"{video_id}.json" if metadata_path.exists() and not args.force_metadata: with metadata_path.open("r", encoding="utf-8") as handle: metadata = json.load(handle) else: metadata, metadata_error = fetch_metadata(video_id, args) row["raw_metadata_path"] = persist_raw_metadata(args.raw_metadata_dir, video_id, metadata) row["metadata_status"] = "ok" except Exception as exc: metadata_error = str(exc) row["metadata_status"] = "failed" row["error"] = metadata_error row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S") stats_record["metadata_status"] = "failed" stats_record["updated_at"] = row["processed_at"] failure_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") if args.sleep_seconds > 0: time.sleep(args.sleep_seconds) continue
assert metadata is not None row["raw_metadata_path"] = row.get("raw_metadata_path") or persist_raw_metadata(args.raw_metadata_dir, video_id, metadata) row["title"] = str(metadata.get("title") or "") duration = metadata.get("duration") row["duration_sec"] = str(duration or "") row["start_sec"] = "0" row["end_sec"] = str(duration or "")
manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata) subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id) subtitle_payloads: Dict[str, Dict[str, object]] = {}
if args.skip_subtitles: row["subtitle_status"] = "skipped" else: try: need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt")) if need_subtitles: subtitle_error = download_subtitles( video_id, subtitle_dir, manual_langs, native_automatic_langs, english_translation_lang, args, ) subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id) row["subtitle_status"] = "ok" if subtitle_payloads else "missing" except Exception as exc: subtitle_error = str(exc) subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id) row["subtitle_status"] = "partial" if subtitle_payloads else "failed"
row["subtitle_languages"] = "|".join(sorted(subtitle_payloads)) row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else "" subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads) row["subtitle_en_source"] = subtitle_en_source if "subtitle_texts_json" in row: row["subtitle_texts_json"] = "" if "subtitle_en" in row: row["subtitle_en"] = "" if "subtitle_json_path" in row: row["subtitle_json_path"] = "" if "raw_caption_dir" in row: row["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 "" elif row["subtitle_status"] != "ok": if existing_video is not None: existing_video.unlink(missing_ok=True) row["raw_video_path"] = "" row["download_status"] = "skipped" if not download_error: download_error = "subtitle required before video download" else: if existing_video is None or args.force_download: row["raw_video_path"], download_error = download_video(video_id, args.raw_video_dir, args) else: row["raw_video_path"] = repo_relative_or_absolute(existing_video) row["download_status"] = "ok" if row["raw_video_path"] else "failed" except Exception as exc: download_error = str(exc) row["download_status"] = "failed"
errors = [value for value in [metadata_error, subtitle_error, download_error] if value] row["error"] = " | ".join(errors) metadata, metadata_error = fetch_metadata(video_id, args) row["raw_metadata_path"] = persist_raw_metadata(args.raw_metadata_dir, video_id, metadata) row["metadata_status"] = "ok" except Exception as exc: metadata_error = str(exc) row["metadata_status"] = "failed" row["error"] = metadata_error row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S") stats_record["sign_language"] = row.get("sign_language", "") stats_record["title"] = row["title"] stats_record["duration_sec"] = row["duration_sec"] stats_record["start_sec"] = row["start_sec"] stats_record["end_sec"] = row["end_sec"] stats_record["subtitle_languages"] = row["subtitle_languages"] stats_record["subtitle_dir_path"] = row["subtitle_dir_path"] stats_record["subtitle_en_source"] = row["subtitle_en_source"] stats_record["raw_video_path"] = row["raw_video_path"] stats_record["raw_metadata_path"] = row["raw_metadata_path"] stats_record["metadata_status"] = row["metadata_status"] stats_record["subtitle_status"] = row["subtitle_status"] stats_record["download_status"] = row["download_status"] if errors: failure_count, should_skip = record_row_failure(row, stats_record, row["error"], args.max_failures_before_skip) else: reset_row_failures(row, stats_record) failure_count, should_skip = 0, False stats_record["download_status"] = row["download_status"] stats_record["last_error"] = row["error"] stats_record["metadata_status"] = "failed" stats_record["updated_at"] = row["processed_at"] failure_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)
if row["download_status"] == "failed": print(f" video download failed: {download_error}") if row["subtitle_status"] in {"failed", "partial"}: print(f" subtitle status: {row['subtitle_status']} {subtitle_error}") print(f" metadata failed: {metadata_error}") if should_skip: print(f" skipping after {failure_count} failures")
if args.sleep_seconds > 0: time.sleep(args.sleep_seconds) finally: release_claim(args, video_id) continue
assert metadata is not None row["raw_metadata_path"] = row.get("raw_metadata_path") or persist_raw_metadata(args.raw_metadata_dir, video_id, metadata) row["title"] = str(metadata.get("title") or "") duration = metadata.get("duration") row["duration_sec"] = str(duration or "") row["start_sec"] = "0" row["end_sec"] = str(duration or "")
manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata) subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id) subtitle_payloads: Dict[str, Dict[str, object]] = {}
if args.skip_subtitles: row["subtitle_status"] = "skipped" else: try: need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt")) if need_subtitles: subtitle_error = download_subtitles( video_id, subtitle_dir, manual_langs, native_automatic_langs, english_translation_lang, args, ) subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id) row["subtitle_status"] = "ok" if subtitle_payloads else "missing" except Exception as exc: subtitle_error = str(exc) subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id) row["subtitle_status"] = "partial" if subtitle_payloads else "failed"
row["subtitle_languages"] = "|".join(sorted(subtitle_payloads)) row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else "" subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads) row["subtitle_en_source"] = subtitle_en_source if "subtitle_texts_json" in row: row["subtitle_texts_json"] = "" if "subtitle_en" in row: row["subtitle_en"] = "" if "subtitle_json_path" in row: row["subtitle_json_path"] = "" if "raw_caption_dir" in row: row["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 "" else: if existing_video is None or args.force_download: row["raw_video_path"], download_error = download_video(video_id, args.raw_video_dir, args) else: row["raw_video_path"] = repo_relative_or_absolute(existing_video) row["download_status"] = "ok" if row["raw_video_path"] else "failed" except Exception as exc: download_error = str(exc) row["download_status"] = "failed"
errors = [value for value in [metadata_error, subtitle_error, download_error] if value] row["error"] = " | ".join(errors) row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S") stats_record["sign_language"] = row.get("sign_language", "") stats_record["title"] = row["title"] stats_record["duration_sec"] = row["duration_sec"] stats_record["start_sec"] = row["start_sec"] stats_record["end_sec"] = row["end_sec"] stats_record["subtitle_languages"] = row["subtitle_languages"] stats_record["subtitle_dir_path"] = row["subtitle_dir_path"] stats_record["subtitle_en_source"] = row["subtitle_en_source"] stats_record["raw_video_path"] = row["raw_video_path"] stats_record["raw_metadata_path"] = row["raw_metadata_path"] stats_record["metadata_status"] = row["metadata_status"] stats_record["subtitle_status"] = row["subtitle_status"] stats_record["download_status"] = row["download_status"] if errors: failure_count, should_skip = record_row_failure(row, stats_record, row["error"], args.max_failures_before_skip) else: reset_row_failures(row, stats_record) failure_count, should_skip = 0, False stats_record["download_status"] = row["download_status"] stats_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}") if row["subtitle_status"] in {"failed", "partial"}: print(f" subtitle status: {row['subtitle_status']} {subtitle_error}") if should_skip: print(f" skipping after {failure_count} failures")
if args.sleep_seconds > 0: time.sleep(args.sleep_seconds) finally: if temp_cookie_path is not None: temp_cookie_path.unlink(missing_ok=True)34 unmodified lines35363738383940415 unmodified lines47484950515253545556575859606162636465666768505152152 unmodified lines205206207227228229230231232233234235236237238239208209210211243244245246247212213214215216393 unmodified lines61061161264761361461534 unmodified lines processed_complete_counter_path, update_video_stats_best_effort,)from utils.raw_video_pool import find_video_file, iter_raw_video_filesfrom utils.raw_video_pool import iter_raw_video_filesfrom utils.dataset_pool import dataset_dir_for_video, find_dataset_video_dir
5 unmodified linesCOMPLETE_MARKER_NAME = ".complete"
def sync_caption_dir(video_id: str, output_dataset_dir: Path, home_dataset_dir: Path, scratch_dataset_dir: Path | None) -> None: output_caption_dir = output_dataset_dir / video_id / "captions" if any(output_caption_dir.glob("*.vtt")): return source_dirs = [home_dataset_dir / video_id / "captions"] if scratch_dataset_dir is not None: source_dirs.append(scratch_dataset_dir / video_id / "captions") for source_dir in source_dirs: if not source_dir.exists(): continue vtts = sorted(source_dir.glob("*.vtt")) if not vtts: continue output_caption_dir.mkdir(parents=True, exist_ok=True) for source_path in vtts: shutil.copy2(source_path, output_caption_dir / source_path.name) break
def build_optimized_providers(device: str, optimized_provider: str, cache_dir: Path): device = str(device) gpu_id = 0152 unmodified lines stats = load_stats(args.stats_npz)
selected = [] if video_id_filter: candidate_paths = [] for video_id in sorted(video_id_filter): path = find_video_file(video_id, args.raw_video_dir, args.scratch_raw_video_dir) if path is not None: candidate_paths.append(path) else: candidate_paths = sorted( iter_raw_video_files(args.raw_video_dir, args.scratch_raw_video_dir), key=lambda p: (p.stem, str(p)), )
for path in candidate_paths: 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.stem if video_id_filter and video_id not in video_id_filter: continue dataset_video_dir = find_dataset_video_dir(video_id, args.dataset_dir, args.scratch_dataset_dir) caption_dir = dataset_video_dir / "captions" if not any(caption_dir.glob("*.vtt")): continue npz_dir = dataset_video_dir / "npz" dataset_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_NAME if ( not args.force393 unmodified lines if output_npz_dir.exists() and (force or not complete_marker.exists()): shutil.rmtree(output_npz_dir) output_npz_dir.mkdir(parents=True, exist_ok=True) sync_caption_dir(video_id, output_dataset_dir, dataset_dir, scratch_dataset_dir)
aggregated_payloads = [] frame_widths = []427 unmodified lines4284294304314314324334344354354364374384394404414374424434444394454464474484499 unmodified lines459460461455462463464465466467457468469470459471472473474462475476477478479480467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498481482483427 unmodified lines for video_id in video_ids: dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir) had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists() safe_remove_tree(dataset_video_dir, context=f"cleanup uploaded dataset {video_id}") if dataset_video_dir.exists(): shutil.rmtree(dataset_video_dir, ignore_errors=True) if had_complete: adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1) for raw_dir in [raw_video_dir, scratch_raw_video_dir]: safe_remove_matching_files(raw_dir, f"{video_id}.*", context=f"cleanup uploaded raw video {video_id}") if raw_dir is None: continue for path in raw_dir.glob(f"{video_id}.*"): if path.is_file(): path.unlink() caption_dir = raw_caption_dir / video_id safe_remove_tree(caption_dir, context=f"cleanup uploaded caption {video_id}") if caption_dir.exists(): shutil.rmtree(caption_dir, ignore_errors=True) metadata_path = raw_metadata_dir / f"{video_id}.json" safe_remove_file(metadata_path, context=f"cleanup uploaded metadata {video_id}") if metadata_path.exists(): metadata_path.unlink(missing_ok=True)
def prune_uploaded_runtime_residue(9 unmodified lines uploaded = set(progress.get("uploaded_folders", {})) for video_id in uploaded: for raw_dir in [raw_video_dir, scratch_raw_video_dir]: safe_remove_matching_files(raw_dir, f"{video_id}.*", context=f"prune uploaded raw video {video_id}") if raw_dir is None: continue for path in raw_dir.glob(f"{video_id}.*"): if path.is_file(): path.unlink(missing_ok=True) caption_dir = raw_caption_dir / video_id safe_remove_tree(caption_dir, context=f"prune uploaded caption {video_id}") if caption_dir.exists(): shutil.rmtree(caption_dir, ignore_errors=True) metadata_path = raw_metadata_dir / f"{video_id}.json" safe_remove_file(metadata_path, context=f"prune uploaded metadata {video_id}") if metadata_path.exists(): metadata_path.unlink(missing_ok=True) dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir) had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists() safe_remove_tree(dataset_video_dir, context=f"prune uploaded dataset {video_id}") if dataset_video_dir.exists(): shutil.rmtree(dataset_video_dir, ignore_errors=True) if had_complete and stats_npz is not None: adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1)
def safe_remove_matching_files(parent_dir: Path | None, pattern: str, *, context: str) -> None: if parent_dir is None: return try: matches = list(parent_dir.glob(pattern)) except OSError as exc: print(f"[pipeline03] warning: failed to scan {parent_dir} for {pattern} during {context}: {exc}", flush=True) return for path in matches: try: if path.is_file(): path.unlink(missing_ok=True) except OSError as exc: print(f"[pipeline03] warning: failed to remove {path} during {context}: {exc}", flush=True)
def safe_remove_tree(path: Path, *, context: str) -> None: try: if path.exists(): shutil.rmtree(path, ignore_errors=True) except OSError as exc: print(f"[pipeline03] warning: failed to remove directory {path} during {context}: {exc}", flush=True)
def safe_remove_file(path: Path, *, context: str) -> None: try: if path.exists(): path.unlink(missing_ok=True) except OSError as exc: print(f"[pipeline03] warning: failed to remove file {path} during {context}: {exc}", flush=True)
def format_size(num_bytes: int) -> str: size = float(num_bytes) for unit in ["B", "KB", "MB", "GB", "TB"]:12234514 unmodified lines2021222323242526#!/usr/bin/env bash#SBATCH --partition=main-redhat#SBATCH --partition=main#SBATCH --job-name=sign-dwpose-launcher#SBATCH --nodes=1#SBATCH --ntasks=114 unmodified linesCHECK_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-redhat}"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}"21 unmodified lines222324252526272820 unmodified lines495051525253545521 unmodified linesDOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_DIR/download_claims}"LOCK_FILE="$STATE_DIR/submit_download.lock"DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$STATE_ROOT/SignVerse-2M-metadata_processed.csv.lock}"PARTITIONS="main-redhat"PARTITIONS="main"ACCOUNT=""TIME_LIMIT="04:00:00"CPUS_PER_TASK="1"20 unmodified lines bash slurm/submit_download_slurm.sh [options]
Options: --partitions P1[,P2,...] Comma-separated CPU partitions. Default: main-redhat --partitions P1[,P2,...] Comma-separated CPU partitions. Default: main --runtime-root DIR Shared runtime root --state-root DIR Shared state/log root --account NAME Optional Slurm account17 unmodified lines181920212122232419 unmodified lines444546474748495017 unmodified linesSTATE_DIR="${STATE_DIR:-$STATE_ROOT/slurm/state}"CLAIM_DIR="${CLAIM_DIR:-$STATE_DIR/claims}"LOCK_FILE="$STATE_DIR/submit.lock"PARTITIONS="gpu-redhat,gpu,cgpu"PARTITIONS="gpu,gpu-redhat,cgpu"ACCOUNT=""TIME_LIMIT="24:00:00"CPUS_PER_TASK="8"19 unmodified lines bash slurm/submit_dwpose_slurm.sh [options]
Options: --partitions P1[,P2,...] Comma-separated partitions. Default: gpu-redhat,gpu,cgpu --partitions P1[,P2,...] Comma-separated partitions. Default: gpu,gpu-redhat,cgpu --runtime-root DIR Shared runtime root for data/state --state-root DIR Shared state/log root (default: runtime root) --account NAME Optional Slurm account4 unmodified lines5678891011121314151516181917212218192021221 unmodified line24252630313233343536373839404142434445464748495051522728293031565732333435362 unmodified lines39404166676842697071434445464748787980818283495086515253545516 unmodified lines727374109757677784 unmodified linesSUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_upload_parallel_slurm.sh}"PARALLEL_SHARDS="${PARALLEL_SHARDS:-8}"ARRAY_PARALLEL="${ARRAY_PARALLEL:-8}"PARTITION="${PARTITION:-main-redhat}"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}"STATE_ROOT="${STATE_ROOT:-/home/sf895/SignVerse-2M-runtime}"HOME_DATASET_DIR="${HOME_DATASET_DIR:-/home/sf895/SignVerse-2M-runtime/dataset}"SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"HOME_RAW_VIDEO_DIR="${HOME_RAW_VIDEO_DIR:-/home/sf895/SignVerse-2M-runtime/raw_video}"SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"
remaining_stats() { python3 - <<PY2remaining_unuploaded() { python3 - <<PYimport jsonfrom pathlib import Pathimport sys1 unmodified linefrom 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', {}))size_bytes = 0for item in folders: path = item[1] if isinstance(item, tuple) else item try: for child in path.rglob('*'): if child.is_file(): size_bytes += child.stat().st_size except FileNotFoundError: continueprint(f"remaining={len(folders)}")print(f"bytes={size_bytes}")PY2}
upstream_busy() { local download_claims process_claims raw_count download_claims=$(find "$STATE_ROOT/slurm/state/download_claims" -maxdepth 1 -type f -name '*.claim' 2>/dev/null | wc -l) process_claims=$(find "$STATE_ROOT/slurm/state/claims" -maxdepth 1 -type f -name '*.claim' 2>/dev/null | wc -l) raw_count=$(find "$HOME_RAW_VIDEO_DIR" "$SCRATCH_RAW_VIDEO_DIR" -maxdepth 1 -type f \( -name '*.mp4' -o -name '*.mkv' -o -name '*.webm' -o -name '*.mov' \) 2>/dev/null | wc -l) if [[ "$download_claims" -gt 0 || "$process_claims" -gt 0 || "$raw_count" -gt 0 ]]; then return 0 fi return 1print(len(folders))PY}
while true; do eval "$(remaining_stats)" echo "[drain] remaining_unuploaded=$remaining remaining_bytes=$bytes" remaining="$(remaining_unuploaded)" echo "[drain] remaining_unuploaded=$remaining" if [[ "$remaining" == "0" ]]; then echo "[drain] backlog cleared" break2 unmodified lines shards="$PARALLEL_SHARDS" array_parallel="$ARRAY_PARALLEL" extra_args=() # Keep each normal shard at or above TARGET_FOLDERS when possible. # For example, 311 folders should use 7 shards, not 8, so each shard still has >=40 folders. needed_shards=$(( remaining / TARGET_FOLDERS )) needed_shards=$(((remaining + TARGET_FOLDERS - 1) / TARGET_FOLDERS)) if (( needed_shards < 1 )); then needed_shards=1 fi if (( needed_shards < shards )); then shards="$needed_shards" fi if (( shards < 1 )); then shards=1 fi
if (( remaining < TARGET_FOLDERS && bytes < TARGET_BYTES )); then echo "[drain] below upload thresholds; skip upload wave" break fi
if (( shards == 1 )); then array_parallel="" echo "[drain] single-shard strict mode" 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"16 unmodified lines submit_cmd+=("${extra_args[@]}") fi
submit_out="$(${submit_cmd[@]})" submit_out="$("${submit_cmd[@]}")" echo "$submit_out" job_id="$(awk '/Submitted batch job/{print $4}' <<< "$submit_out" | tail -n1)" if [[ -z "$job_id" ]]; then3 unmodified lines45677891018 unmodified lines29303132323334353 unmodified linesROOT_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-redhat}"PARTITION="${PARTITION:-main}"TIME_LIMIT="${TIME_LIMIT:-24:00:00}"CPUS_PER_TASK="${CPUS_PER_TASK:-2}"MEMORY="${MEMORY:-8G}"18 unmodified linesOptions: --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-redhat --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: 8G11 unmodified lines121314151516171811 unmodified lines
ROOT_DIR="${ROOT_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"GPU_PARTITIONS="${GPU_PARTITIONS:-gpu-redhat,gpu,cgpu}"GPU_PARTITIONS="${GPU_PARTITIONS:-gpu,gpu-redhat,cgpu}"GPU_ACCOUNT="${GPU_ACCOUNT:-}"SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-60}"SUBMIT_LIMIT="${SUBMIT_LIMIT:-2980}"13 unmodified lines1415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123221241251261278 unmodified lines1361371383713914014114241 unmodified lines184185186851871881891908919119219319412 unmodified lines2072082091082102111101112122132142152161 unmodified line2182192201192212221211222232242252261252272282292307 unmodified lines23823924013924124224314224424524624724824925025125225325425525625725829 unmodified lines28828929017829129229329429529629729829930030118130230330430530630730830931031118431231331431531631731831932032132218919019132332432532632732832933019633133233333433533633733833934034119934234334434534634734834935035120235235335435535635735835936036164 unmodified lines4264274282732742752762772782792804294304314324334344354364374384394404414424434444454464474484494504514524534544554567 unmodified lines46446546629446713 unmodified lines
eps = 0.01
RENDER_STYLES = { "bold": {"line_scale": 3.0, "point_scale": 2.0}, "thin": {"line_scale": 1.0, "point_scale": 1.0},}
def get_render_style(style: str = "bold") -> Dict[str, float]: """Return named DWPose rendering style parameters.""" if style not in RENDER_STYLES: raise ValueError(f"Unknown render style '{style}'. Choose from: {sorted(RENDER_STYLES)}") return RENDER_STYLES[style]
def filter_pose_by_confidence( pose_data: Dict[str, Any], conf_threshold: float = 0.6,) -> Dict[str, Any]: """Filter low-confidence joints before rendering.""" filtered = {} for key, value in pose_data.items(): if isinstance(value, np.ndarray): filtered[key] = value.copy() else: filtered[key] = value
bodies = filtered.get("bodies") body_scores = filtered.get("body_scores") if bodies is not None: bodies = np.array(bodies, copy=True) min_valid = 1e-6 coord_mask = (bodies[:, 0] > min_valid) & (bodies[:, 1] > min_valid)
conf_mask = None if body_scores is not None: score_vec = np.asarray(body_scores).reshape(-1).astype(float) conf_mask = score_vec < conf_threshold if conf_mask.shape[0] < bodies.shape[0]: conf_mask = np.pad( conf_mask, (0, bodies.shape[0] - conf_mask.shape[0]), constant_values=False, ) elif conf_mask.shape[0] > bodies.shape[0]: conf_mask = conf_mask[: bodies.shape[0]]
valid_mask = coord_mask if conf_mask is None else coord_mask & (~conf_mask) bodies[~valid_mask, :] = 0 filtered["bodies"] = bodies
if body_scores is not None: subset = np.array(body_scores, copy=True) if subset.ndim == 1: subset = subset.reshape(1, -1) else: subset = np.arange(bodies.shape[0], dtype=float).reshape(1, -1)
if subset.shape[1] < bodies.shape[0]: subset = np.pad( subset, ((0, 0), (0, bodies.shape[0] - subset.shape[1])), constant_values=-1, ) elif subset.shape[1] > bodies.shape[0]: subset = subset[:, : bodies.shape[0]]
subset[:, ~valid_mask] = -1 filtered["body_scores"] = subset
hands = filtered.get("hands") hand_scores = filtered.get("hands_scores") if hands is not None and hand_scores is not None: hands = np.array(hands, copy=True) scores = np.array(hand_scores) if hands.ndim == 3 and scores.ndim in (2, 3): for h in range(hands.shape[0]): cur_scores = scores[h] if scores.ndim == 2 else scores[h] mask = (cur_scores < conf_threshold) | (cur_scores <= 0) hands[h][mask, :] = 0 elif hands.ndim == 2 and scores.ndim in (1, 2): cur_scores = scores if scores.ndim == 1 else scores.reshape(-1) mask = (cur_scores < conf_threshold) | (cur_scores <= 0) hands[mask, :] = 0 filtered["hands"] = hands
faces = filtered.get("faces") face_scores = filtered.get("faces_scores") if faces is not None and face_scores is not None: faces = np.array(faces, copy=True) scores = np.array(face_scores) if faces.ndim == 3 and scores.ndim in (2, 3): for f in range(faces.shape[0]): cur_scores = scores[f] if scores.ndim == 2 else scores[f] mask = (cur_scores < conf_threshold) | (cur_scores <= 0) faces[f][mask, :] = 0 elif faces.ndim == 2 and scores.ndim in (1, 2): cur_scores = scores if scores.ndim == 1 else scores.reshape(-1) mask = (cur_scores < conf_threshold) | (cur_scores <= 0) faces[mask, :] = 0 filtered["faces"] = faces
return filtered
def alpha_blend_color(color, alpha): """blend color according to point conf """ return [int(c * alpha) for c in color]
def draw_bodypose(canvas, candidate, subset, score, transparent=False):def draw_bodypose(canvas, candidate, subset, score, transparent=False, line_scale=1.0, point_scale=1.0): """Draw body pose on canvas Args: canvas: numpy array canvas to draw on8 unmodified lines candidate = np.array(candidate) subset = np.array(subset)
stickwidth = 4 stickwidth = max(1, int(round(4 * line_scale)))
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],41 unmodified lines color = colors[i][:-1] + [int(255 * conf)] # Adjust alpha based on confidence else: color = colors[i] cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1) cv2.circle(canvas, (int(x), int(y)), max(1, int(round(4 * point_scale))), color, thickness=-1)
return canvas
def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False, line_scale=1.0, point_scale=1.0): """Draw hand pose on canvas""" H, W, C = canvas.shape
12 unmodified lines if x1 > eps and y1 > eps and x2 > eps and y2 > eps: color = matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) if transparent: color = np.append(color, score) # Add alpha channel color = tuple(int(c * 255) for c in color) + (int(score * 255),) else: color = color * score cv2.line(canvas, (x1, y1), (x2, y2), color * 255, thickness=2) color = tuple(int(c * score * 255) for c in color) cv2.line(canvas, (x1, y1), (x2, y2), color, thickness=max(1, int(round(2 * line_scale))))
for i, keypoint in enumerate(peaks): x, y = keypoint1 unmodified line y = int(y * H) if x > eps and y > eps: if transparent: color = (0, 0, 0, scores[i]) # Black with alpha color = (0, 0, 0, int(scores[i] * 255)) else: color = (0, 0, int(scores[i] * 255)) # Original color cv2.circle(canvas, (x, y), 4, color, thickness=-1) color = (0, 0, int(scores[i] * 255)) cv2.circle(canvas, (x, y), max(1, int(round(4 * point_scale))), color, thickness=-1) return canvas
def draw_facepose(canvas, all_lmks, all_scores, transparent=False):def draw_facepose(canvas, all_lmks, all_scores, transparent=False, point_scale=1.0): """Draw face pose on canvas""" H, W, C = canvas.shape for lmks, scores in zip(all_lmks, all_scores):7 unmodified lines else: conf = int(score * 255) color = (conf, conf, conf) # Original grayscale cv2.circle(canvas, (x, y), 3, color, thickness=-1) cv2.circle(canvas, (x, y), max(1, int(round(3 * point_scale))), color, thickness=-1) return canvas
def draw_pose(pose, H, W, include_body=True, include_hand=True, include_face=True, ref_w=2160, transparent=False):def draw_pose( pose, H, W, include_body=True, include_hand=True, include_face=True, ref_w=2160, transparent=False, line_scale=1.0, point_scale=1.0,): """vis dwpose outputs with optional transparent background
Args:29 unmodified lines subset = bodies['subset'] if include_body: canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent) canvas = draw_bodypose( canvas, candidate, subset, score=bodies['score'], transparent=transparent, line_scale=line_scale, point_scale=point_scale, )
if include_hand: canvas = draw_handpose(canvas, hands, processed_data['hands_score'], transparent=transparent) canvas = draw_handpose( canvas, hands, processed_data['hands_score'], transparent=transparent, line_scale=line_scale, point_scale=point_scale, )
if include_face: canvas = draw_facepose(canvas, faces, processed_data['faces_score'], transparent=transparent) canvas = draw_facepose( canvas, faces, processed_data['faces_score'], transparent=transparent, point_scale=point_scale, ) else: # 兼容旧的数据格式 - 作为备选方案 try: bodies = pose['bodies'] faces = pose['faces'] hands = pose['hands'] processed_data = process_pose_data(pose, H, W) bodies = processed_data['bodies'] faces = processed_data['faces'] hands = processed_data['hands'] candidate = bodies['candidate'] subset = bodies['subset']
if include_body: canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent) canvas = draw_bodypose( canvas, candidate, subset, score=bodies['score'], transparent=transparent, line_scale=line_scale, point_scale=point_scale, )
if include_hand: canvas = draw_handpose(canvas, hands, pose['hands_score'], transparent=transparent) canvas = draw_handpose( canvas, hands, processed_data['hands_score'], transparent=transparent, line_scale=line_scale, point_scale=point_scale, )
if include_face: canvas = draw_facepose(canvas, faces, pose['faces_score'], transparent=transparent) canvas = draw_facepose( canvas, faces, processed_data['faces_score'], transparent=transparent, point_scale=point_scale, ) except Exception as e: print(f"绘制旧格式数据失败: {str(e)}") # 返回空画布64 unmodified lines face_scores = np.array(all_face_scores) if all_face_scores else np.array([]) else: # 兼容性处理 - 如果不是新格式,返回空数据 bodies = np.array([]) subset = np.array([[]]) scores = np.array([[]]) hands = np.array([]) hand_scores = np.array([]) faces = np.array([]) face_scores = np.array([]) # 兼容旧的单人数据格式 raw_bodies = np.array(pose_data.get('bodies', []), dtype=np.float32) raw_body_scores = np.array(pose_data.get('body_scores', []), dtype=np.float32) raw_hands = np.array(pose_data.get('hands', []), dtype=np.float32) raw_hand_scores = np.array(pose_data.get('hands_scores', []), dtype=np.float32) raw_faces = np.array(pose_data.get('faces', []), dtype=np.float32) raw_face_scores = np.array(pose_data.get('faces_scores', []), dtype=np.float32)
if raw_bodies.size > 0: bodies = raw_bodies.reshape(-1, 2) subset = np.arange(bodies.shape[0], dtype=np.int32)[None, :]
if raw_body_scores.size > 0: scores = raw_body_scores.reshape(1, -1) else: scores = np.ones((1, bodies.shape[0]), dtype=np.float32) else: bodies = np.array([]) subset = np.array([[]]) scores = np.array([[]])
hands = raw_hands if raw_hands.size > 0 else np.array([]) hand_scores = raw_hand_scores if raw_hand_scores.size > 0 else np.array([]) faces = raw_faces if raw_faces.size > 0 else np.array([]) face_scores = raw_face_scores if raw_face_scores.size > 0 else np.array([]) processed_data['bodies'] = { 'candidate': bodies,7 unmodified lines processed_data['faces'] = faces processed_data['faces_score'] = face_scores return processed_data return processed_data27 unmodified lines2829303132333435313233344 unmodified lines3940414647484950515253424344457 unmodified lines5354556768697071565758596 unmodified lines666768848586878869707172929373949574757683 unmodified lines16016116218518618718818919019116316427 unmodified lines if not directory.exists(): continue for path in sorted(directory.iterdir()): try: is_file = path.is_file() except OSError: continue if not is_file or path.suffix.lower() not in VIDEO_EXTENSIONS: if not path.is_file() or path.suffix.lower() not in VIDEO_EXTENSIONS: continue videos.setdefault(path.stem, path) return videos4 unmodified lines
def sum_raw_video_sizes(*dirs: Path | None) -> int: total = 0 for path in collect_raw_videos(*dirs).values(): try: if path.exists(): total += path.stat().st_size except OSError: continue return total 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]:7 unmodified lines continue candidates = [] for path in directory.glob(f"{video_id}.*"): try: is_file = path.is_file() except OSError: continue if is_file and path.suffix.lower() in VIDEO_EXTENSIONS: if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS: candidates.append(path) if candidates: return sorted(candidates)[0]6 unmodified lines if not directory.exists(): continue for path in directory.glob(f"{video_id}*"): try: is_file = path.is_file() except OSError: continue if not is_file: if not path.is_file(): continue suffixes = set(path.suffixes) if '.part' in suffixes or '.ytdl' in suffixes or path.suffix in {'.part', '.ytdl'}: try: resolved = path.resolve() resolved = path.resolve() except OSError: continue if resolved in seen: continue seen.add(resolved)83 unmodified lines if not directory.exists(): continue for path in directory.glob(f"{video_id}.*"): try: is_file = path.is_file() except OSError: continue if is_file and path.suffix.lower() in VIDEO_EXTENSIONS: with contextlib.suppress(OSError): path.unlink(missing_ok=True) if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS: path.unlink(missing_ok=True)README.md+336-3
reproduce_independently_slurm.sh+4-4
scripts/pipeline01_backfill_subtitles.pyDeleted-254
scripts/pipeline01_download_video_fix_caption.py+117-184
scripts/pipeline02_extract_dwpose_from_video.py+4-39
scripts/pipeline03_upload_to_huggingface.py+22-40
slurm/orchestrator_autorestart.slurm+2-2
slurm/submit_download_slurm.sh+2-2
slurm/submit_dwpose_slurm.sh+2-2
slurm/submit_upload_parallel_drain.sh+11-45
slurm/submit_upload_parallel_slurm.sh+2-2
slurm/watch_submit_dwpose.slurm+1-1
utils/draw_dw_lib.py+204-31
utils/raw_video_pool.py+7-34