Codex commited on
Commit
cd27dad
·
1 Parent(s): 1d7e5b8

Revert "Sync latest local production code"

Browse files

This reverts commit 1d7e5b8e79c6190f880cd74fe7fde7e55081f86d.

README.md CHANGED
@@ -1,3 +1,336 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-nc-4.0
3
+ language:
4
+ - ase
5
+ - bfi
6
+ - gsg
7
+ - sgd
8
+ - fsl
9
+ - lsf
10
+ - lse
11
+ - lis
12
+ - lgp
13
+ - ngt
14
+ - asf
15
+ - jsl
16
+ - kvk
17
+ - csl
18
+ - aed
19
+ - tsm
20
+ - pjm
21
+ - rsl
22
+ - swl
23
+ - dsl
24
+ - fse
25
+ - nsl
26
+ - lsc
27
+ - lsm
28
+ - bzs
29
+ task_categories:
30
+ - other
31
+ tags:
32
+ - sign-language
33
+ - pose-estimation
34
+ - dwpose
35
+ - multilingual
36
+ - keypoint
37
+ - video-understanding
38
+ - sign-language-generation
39
+ - sign-language-recognition
40
+ - pose-native
41
+ size_categories:
42
+ - 1M<n<10M
43
+ pretty_name: "SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages"
44
+ ---
45
+
46
+ <div align="center" style="position: relative; width: 100%; max-width: 1400px; margin: 0 auto 24px auto;">
47
+ <img
48
+ src="https://signerx.github.io/SignVerse-2M/static/images/background_gallery_big.gif"
49
+ alt="SignVerse-2M cover"
50
+ style="width: 100%; display: block; border-radius: 18px;"
51
+ />
52
+ <div
53
+ style="
54
+ position: absolute;
55
+ inset: 0;
56
+ display: flex;
57
+ align-items: center;
58
+ justify-content: center;
59
+ background: linear-gradient(to bottom, rgba(0,0,0,0.18), rgba(0,0,0,0.28));
60
+ border-radius: 18px;
61
+ "
62
+ >
63
+ <div
64
+ style="
65
+ color: white;
66
+ font-size: 3.4rem;
67
+ font-weight: 800;
68
+ letter-spacing: 0.04em;
69
+ text-shadow: 0 4px 20px rgba(0,0,0,0.45);
70
+ "
71
+ >
72
+ SignVerse-2M
73
+ </div>
74
+ </div>
75
+ </div>
76
+
77
+ ## SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages
78
+
79
+ 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)
80
+
81
+ **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.
82
+
83
+ ## Overview
84
+
85
+ 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.
86
+
87
+ The release is intended to support research questions such as:
88
+
89
+ - multilingual sign language generation in pose space
90
+ - pose-based sign language recognition and translation
91
+ - cross-lingual transfer across heterogeneous sign language sources
92
+ - benchmarking of sign language motion representations under open-world conditions
93
+
94
+ ## Key Characteristics
95
+
96
+ | Property | Value |
97
+ | --- | --- |
98
+ | Dataset name | SignVerse-2M |
99
+ | Core representation | DWPose keypoint sequences |
100
+ | Videos | 39,196 |
101
+ | Clips / subtitle segments | Approximately 2 million |
102
+ | Sign languages | 55+ |
103
+ | Frame rate | 24 FPS |
104
+ | Per-frame keypoints | 18 body + 21 left hand + 21 right hand + 68 face = 128 |
105
+ | Source type | Public multilingual sign language videos |
106
+ | Raw RGB frames released | No |
107
+ | Released supervision | Structured subtitle text and document-level text |
108
+
109
+ ## Why A Pose-Native Release
110
+
111
+ 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.
112
+
113
+ Compared with raw-video releases, the pose-native representation offers three practical advantages:
114
+
115
+ 1. It reduces nuisance variation from background, clothing, and appearance, allowing models to focus more directly on motion.
116
+ 2. It aligns naturally with contemporary pose-conditioned generation pipelines that already consume DWPose-like controls.
117
+ 3. It provides a common representation for multilingual benchmarking, making comparisons across methods more interpretable.
118
+
119
+ ## Data Source And Processing
120
+
121
+ 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:
122
+
123
+ 1. retrieves metadata and available subtitles,
124
+ 2. structures subtitle tracks into segment-level and document-level text,
125
+ 3. decodes the video at 24 FPS,
126
+ 4. applies DWPose to extract body, hand, and face keypoints frame by frame,
127
+ 5. packages the outputs into per-video artifacts for public release.
128
+
129
+ No manual keypoint annotation is provided. The keypoints and subtitles are produced automatically through the preprocessing pipeline.
130
+
131
+ ## Languages
132
+
133
+ The corpus covers more than 55 sign languages. Major language codes in the current release include:
134
+
135
+ | Code | Language | Code | Language |
136
+ | --- | --- | --- | --- |
137
+ | `ase` | American Sign Language | `lsf` | French Sign Language |
138
+ | `bfi` | British Sign Language | `lse` | Spanish Sign Language |
139
+ | `gsg` | German Sign Language | `lis` | Italian Sign Language |
140
+ | `sgd` | Swiss German Sign Language | `lgp` | Portuguese Sign Language |
141
+ | `asf` | Australian Sign Language | `ngt` | Sign Language of the Netherlands |
142
+ | `jsl` | Japanese Sign Language | `kvk` | Korean Sign Language |
143
+ | `csl` | Chinese Sign Language | `bzs` | Brazilian Sign Language |
144
+ | `lsm` | Mexican Sign Language | `pjm` | Polish Sign Language |
145
+
146
+ The language distribution is long-tailed rather than balanced. High-resource languages account for a disproportionate share of the total data volume.
147
+
148
+ ## Repository Structure
149
+
150
+ The public release is organized around `.tar` shards stored under `dataset/`. Each shard contains per-video directories:
151
+
152
+ ```text
153
+ dataset/
154
+ Sign_DWPose_NPZ_000001.tar
155
+ Sign_DWPose_NPZ_000002.tar
156
+ ...
157
+ ```
158
+
159
+ Within each shard:
160
+
161
+ ```text
162
+ {video_id}/
163
+ poses.npz
164
+ caption.json
165
+ {video_id}.complete
166
+ ```
167
+
168
+ The main files are:
169
+
170
+ - `poses.npz`: per-video DWPose payload with frame-wise keypoints
171
+ - `caption.json`: structured subtitle and supervision metadata
172
+ - `.complete`: completion marker produced by the processing pipeline
173
+
174
+ ## Data Schema
175
+
176
+ ### `poses.npz`
177
+
178
+ Each `poses.npz` file stores a person-centric per-frame representation. A simplified schema is shown below:
179
+
180
+ ```python
181
+ {
182
+ "video_id": str,
183
+ "fps": float,
184
+ "num_frames": int,
185
+ "frame_ids": int[T],
186
+ "width": int,
187
+ "height": int,
188
+ "frames": [
189
+ {
190
+ "num_people": int,
191
+ "frame_id": int,
192
+ "width": int,
193
+ "height": int,
194
+ "person_0": {
195
+ "body": float[18, 3],
196
+ "face": float[68, 3],
197
+ "left_hand": float[21, 3],
198
+ "right_hand": float[21, 3],
199
+ },
200
+ # optional additional people:
201
+ # "person_1": { ... }
202
+ },
203
+ ...
204
+ ]
205
+ }
206
+ ```
207
+
208
+ Keypoint coordinates are stored in pixel space as `(x, y, score)`, where confidence scores lie in `[0, 1]`.
209
+
210
+ ### `caption.json`
211
+
212
+ ```json
213
+ {
214
+ "video_id": "...",
215
+ "sign_language": "ase",
216
+ "title": "...",
217
+ "duration_s": 312.4,
218
+ "segments": [
219
+ { "start": 0.0, "end": 4.2, "text": "..." }
220
+ ],
221
+ "document_text": "...",
222
+ "english_source": "native"
223
+ }
224
+ ```
225
+
226
+ The field `english_source` records whether the English supervision is native or automatically selected from an available translated subtitle track.
227
+
228
+ ## Loading Example
229
+
230
+ ```python
231
+ import json
232
+ import tarfile
233
+ import numpy as np
234
+
235
+ with tarfile.open("dataset/Sign_DWPose_NPZ_000001.tar") as tar:
236
+ tar.extractall("./tmp_signverse")
237
+
238
+ npz = np.load("./tmp_signverse/{video_id}/poses.npz", allow_pickle=True)
239
+ frames = npz["frames"].tolist()
240
+ body = frames[0]["person_0"]["body"]
241
+
242
+ with open("./tmp_signverse/{video_id}/caption.json", "r", encoding="utf-8") as f:
243
+ caption = json.load(f)
244
+
245
+ print(body.shape)
246
+ print(caption["segments"][0]["text"])
247
+ ```
248
+
249
+ ## Visualization And Reproduction
250
+
251
+ The repository includes scripts for inspecting the released pose files and for reproducing the processing pipeline.
252
+
253
+ ### Visualize one pose file
254
+
255
+ ```bash
256
+ python scripts/visualize_dwpose_npz.py \
257
+ --npz extracted/{video_id}/poses.npz \
258
+ --style openpose \
259
+ --out viz/
260
+ ```
261
+
262
+ ### Reproduce the pipeline
263
+
264
+ ```bash
265
+ # Single machine
266
+ bash reproduce_independently.sh
267
+
268
+ # SLURM cluster
269
+ bash reproduce_independently_slurm.sh
270
+ ```
271
+
272
+ The pipeline is organized into acquisition, subtitle structuring, pose extraction, and upload/publication stages.
273
+
274
+ ## Benchmark Setting
275
+
276
+ 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.
277
+
278
+ For model code and experimental setup, refer to the benchmark repository:
279
+
280
+ - [https://github.com/SignerX/SignVerse-2M](https://github.com/SignerX/SignVerse-2M)
281
+
282
+ ## Intended Use
283
+
284
+ The release is intended for research use, including:
285
+
286
+ - sign language generation from text via pose space
287
+ - pose-based sign language translation and recognition
288
+ - cross-lingual transfer, adaptation, and benchmarking
289
+ - comparison of pose-native motion representations under open-world distributions
290
+
291
+ The release is not intended for:
292
+
293
+ - safety-critical interpretation in medical, legal, or emergency settings
294
+ - re-identification of individual signers
295
+ - claims of full linguistic coverage for any specific sign language
296
+
297
+ <!--
298
+ ## Limitations
299
+
300
+ Users should account for the following limitations when interpreting results:
301
+
302
+ - Keypoints are extracted automatically and may be noisy under fast motion, occlusion, or multi-person scenes.
303
+ - Fine-grained handshape distinctions are only partially captured by the released 21-keypoint hand representation.
304
+ - Non-manual linguistic signals such as facial expression and mouthing are only partially represented by 68 face landmarks.
305
+ - Subtitle timing and translations are automatically processed and may contain alignment or semantic errors.
306
+ - The corpus is language-imbalanced and inherits the long-tail distribution of public web video sources.
307
+ - `person_0` is treated as the primary signer, which may be imperfect in multi-signer videos.
308
+ -->
309
+
310
+ ## Responsible Use
311
+
312
+ 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.
313
+
314
+ 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.
315
+
316
+ ## Citation
317
+
318
+ If you use SignVerse-2M in academic work, please cite:
319
+
320
+ ```bibtex
321
+ @misc{fang2026signverse2mtwomillionclipposenativeuniverse,
322
+ title={SignVerse-2M: A Two-Million-Clip Pose-Native Universe of 55+ Sign Languages},
323
+ author={Sen Fang and Hongbin Zhong and Yanxin Zhang and Dimitris N. Metaxas},
324
+ year={2026},
325
+ eprint={2605.01720},
326
+ archivePrefix={arXiv},
327
+ primaryClass={cs.CV},
328
+ url={https://arxiv.org/abs/2605.01720},
329
+ }
330
+ ```
331
+
332
+ ## License
333
+
334
+ The released dataset annotations, pose keypoints, and accompanying metadata are distributed under **CC BY-NC 4.0**.
335
+
336
+ Source videos are **not** redistributed in this repository and remain subject to the original platform terms and the rights of their respective creators.
reproduce_independently_slurm.sh CHANGED
@@ -41,7 +41,7 @@ TARGET_BYTES="${TARGET_BYTES:-$((10 * 1024 * 1024 * 1024))}"
41
  TARGET_FOLDERS="${TARGET_FOLDERS:-40}"
42
  UPLOAD_PARALLEL_SHARDS="${UPLOAD_PARALLEL_SHARDS:-8}"
43
  UPLOAD_ARRAY_PARALLEL="${UPLOAD_ARRAY_PARALLEL:-8}"
44
- UPLOAD_PARTITION="${UPLOAD_PARTITION:-main-redhat}"
45
  UPLOAD_START_STAGGER_MIN="${UPLOAD_START_STAGGER_MIN:-1}"
46
  UPLOAD_START_STAGGER_MAX="${UPLOAD_START_STAGGER_MAX:-3}"
47
  DOWNLOAD_BATCH_SIZE="${DOWNLOAD_BATCH_SIZE:-1}"
@@ -62,13 +62,13 @@ COOKIES_FROM_BROWSER="${COOKIES_FROM_BROWSER:-}"
62
  EXTRACTOR_ARGS="${EXTRACTOR_ARGS:-}"
63
  SLURM_PROCESS_SUBMIT_SCRIPT="${SLURM_PROCESS_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"
64
  SLURM_DOWNLOAD_SUBMIT_SCRIPT="${SLURM_DOWNLOAD_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_download_slurm.sh}"
65
- GPU_PARTITIONS="gpu-redhat,gpu,cgpu"
66
  GPU_ACCOUNT="${GPU_ACCOUNT:-}"
67
  ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"
68
  MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-$DEFAULT_TOTAL_RAW_VIDEO_LIMIT}"
69
  DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"
70
  DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv.lock}"
71
- DOWNLOAD_PARTITIONS="${DOWNLOAD_PARTITIONS:-main-redhat}"
72
  DOWNLOAD_ACCOUNT="${DOWNLOAD_ACCOUNT:-}"
73
  DOWNLOAD_TIME="${DOWNLOAD_TIME:-04:00:00}"
74
  DOWNLOAD_CPUS_PER_TASK="${DOWNLOAD_CPUS_PER_TASK:-1}"
@@ -79,7 +79,7 @@ DOWNLOAD_START_STAGGER_MIN="${DOWNLOAD_START_STAGGER_MIN:-1}"
79
  DOWNLOAD_START_STAGGER_MAX="${DOWNLOAD_START_STAGGER_MAX:-3}"
80
  DOWNLOAD_CLAIM_GRACE_SECONDS="${DOWNLOAD_CLAIM_GRACE_SECONDS:-600}"
81
  DOWNLOAD_PARTIAL_TIMEOUT_SECONDS="${DOWNLOAD_PARTIAL_TIMEOUT_SECONDS:-1800}"
82
- ORCHESTRATOR_PARTITION="${ORCHESTRATOR_PARTITION:-main-redhat}"
83
  ORCHESTRATOR_ACCOUNT="${ORCHESTRATOR_ACCOUNT:-}"
84
  ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"
85
  ORCHESTRATOR_CPUS_PER_TASK="${ORCHESTRATOR_CPUS_PER_TASK:-4}"
 
41
  TARGET_FOLDERS="${TARGET_FOLDERS:-40}"
42
  UPLOAD_PARALLEL_SHARDS="${UPLOAD_PARALLEL_SHARDS:-8}"
43
  UPLOAD_ARRAY_PARALLEL="${UPLOAD_ARRAY_PARALLEL:-8}"
44
+ UPLOAD_PARTITION="${UPLOAD_PARTITION:-main}"
45
  UPLOAD_START_STAGGER_MIN="${UPLOAD_START_STAGGER_MIN:-1}"
46
  UPLOAD_START_STAGGER_MAX="${UPLOAD_START_STAGGER_MAX:-3}"
47
  DOWNLOAD_BATCH_SIZE="${DOWNLOAD_BATCH_SIZE:-1}"
 
62
  EXTRACTOR_ARGS="${EXTRACTOR_ARGS:-}"
63
  SLURM_PROCESS_SUBMIT_SCRIPT="${SLURM_PROCESS_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"
64
  SLURM_DOWNLOAD_SUBMIT_SCRIPT="${SLURM_DOWNLOAD_SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_download_slurm.sh}"
65
+ GPU_PARTITIONS="gpu,gpu-redhat,cgpu"
66
  GPU_ACCOUNT="${GPU_ACCOUNT:-}"
67
  ARRAY_PARALLEL="${ARRAY_PARALLEL:-}"
68
  MAX_BACKLOG_VIDEOS="${MAX_BACKLOG_VIDEOS:-$DEFAULT_TOTAL_RAW_VIDEO_LIMIT}"
69
  DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_ROOT/slurm/state/download_claims}"
70
  DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$RUNTIME_ROOT/SignVerse-2M-metadata_processed.csv.lock}"
71
+ DOWNLOAD_PARTITIONS="${DOWNLOAD_PARTITIONS:-main}"
72
  DOWNLOAD_ACCOUNT="${DOWNLOAD_ACCOUNT:-}"
73
  DOWNLOAD_TIME="${DOWNLOAD_TIME:-04:00:00}"
74
  DOWNLOAD_CPUS_PER_TASK="${DOWNLOAD_CPUS_PER_TASK:-1}"
 
79
  DOWNLOAD_START_STAGGER_MAX="${DOWNLOAD_START_STAGGER_MAX:-3}"
80
  DOWNLOAD_CLAIM_GRACE_SECONDS="${DOWNLOAD_CLAIM_GRACE_SECONDS:-600}"
81
  DOWNLOAD_PARTIAL_TIMEOUT_SECONDS="${DOWNLOAD_PARTIAL_TIMEOUT_SECONDS:-1800}"
82
+ ORCHESTRATOR_PARTITION="${ORCHESTRATOR_PARTITION:-main}"
83
  ORCHESTRATOR_ACCOUNT="${ORCHESTRATOR_ACCOUNT:-}"
84
  ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"
85
  ORCHESTRATOR_CPUS_PER_TASK="${ORCHESTRATOR_CPUS_PER_TASK:-4}"
scripts/pipeline01_backfill_subtitles.py DELETED
@@ -1,254 +0,0 @@
1
- #!/usr/bin/env python3
2
-
3
- import argparse
4
- import json
5
- import sys
6
- import time
7
- from pathlib import Path
8
- from typing import Dict, List, Sequence, Tuple
9
-
10
- REPO_ROOT = Path(__file__).resolve().parents[1]
11
- if str(REPO_ROOT) not in sys.path:
12
- sys.path.insert(0, str(REPO_ROOT))
13
-
14
- from scripts.pipeline01_download_video_fix_caption import (
15
- DEFAULT_DATASET_DIR,
16
- DEFAULT_OUTPUT_METADATA_CSV,
17
- DEFAULT_SOURCE_METADATA_CSV,
18
- DEFAULT_STATUS_JOURNAL_PATH,
19
- DEFAULT_YT_DLP_EXTRACTOR_ARGS,
20
- DEFAULT_COLUMNS,
21
- DEFAULT_RAW_METADATA_DIR,
22
- build_subtitle_json_payload,
23
- fetch_metadata,
24
- filter_caption_languages,
25
- load_subtitle_payloads,
26
- lock_path_for_manifest,
27
- merge_row_values,
28
- persist_raw_metadata,
29
- read_state_manifest,
30
- repo_relative_or_absolute,
31
- sanitize_cookie_file,
32
- select_english_subtitle,
33
- subtitle_dir_for_video,
34
- update_video_stats_best_effort,
35
- with_manifest_lock,
36
- write_manifest,
37
- write_subtitle_json,
38
- download_subtitles,
39
- )
40
-
41
-
42
- EXTRA_COLUMNS = [
43
- "subtitle_texts_json",
44
- "subtitle_en",
45
- "subtitle_json_path",
46
- "raw_caption_dir",
47
- ]
48
-
49
-
50
- def parse_args() -> argparse.Namespace:
51
- parser = argparse.ArgumentParser(
52
- description="Backfill subtitles only for SignVerse videos, without downloading video payloads."
53
- )
54
- parser.add_argument("--source-metadata-csv", type=Path, default=DEFAULT_SOURCE_METADATA_CSV)
55
- parser.add_argument("--output-metadata-csv", type=Path, default=DEFAULT_OUTPUT_METADATA_CSV)
56
- parser.add_argument("--dataset-dir", type=Path, default=DEFAULT_DATASET_DIR)
57
- parser.add_argument("--raw-metadata-dir", type=Path, default=DEFAULT_RAW_METADATA_DIR)
58
- parser.add_argument("--status-journal-path", type=Path, default=DEFAULT_STATUS_JOURNAL_PATH)
59
- parser.add_argument("--stats-npz", type=Path, default=REPO_ROOT / 'stats.npz')
60
- parser.add_argument("--limit", type=int, default=None)
61
- parser.add_argument("--video-ids", nargs="*", default=None)
62
- parser.add_argument("--force-metadata", action="store_true")
63
- parser.add_argument("--force-subtitles", action="store_true")
64
- parser.add_argument("--sleep-seconds", type=float, default=0.0)
65
- parser.add_argument("--cookies", type=Path, default=None)
66
- parser.add_argument("--cookies-from-browser", default=None)
67
- parser.add_argument("--extractor-args", default=DEFAULT_YT_DLP_EXTRACTOR_ARGS)
68
- parser.add_argument("--csv-lock-path", type=Path, default=None)
69
- return parser.parse_args()
70
-
71
-
72
- def ordered_fieldnames(fieldnames: Sequence[str]) -> List[str]:
73
- ordered: List[str] = []
74
- for column in list(DEFAULT_COLUMNS) + EXTRA_COLUMNS + list(fieldnames):
75
- if column and column not in ordered:
76
- ordered.append(column)
77
- return ordered
78
-
79
-
80
- def row_needs_subtitle_backfill(row: Dict[str, str], args: argparse.Namespace) -> bool:
81
- if args.force_metadata or args.force_subtitles:
82
- return True
83
- return (row.get("subtitle_status") or "").strip() != "ok"
84
-
85
-
86
- def selected_rows(rows: Sequence[Dict[str, str]], args: argparse.Namespace) -> List[Dict[str, str]]:
87
- selected: List[Dict[str, str]] = []
88
- video_id_filter = set(args.video_ids or [])
89
- for row in rows:
90
- video_id = (row.get("video_id") or "").strip()
91
- if not video_id:
92
- continue
93
- if video_id_filter and video_id not in video_id_filter:
94
- continue
95
- if not row_needs_subtitle_backfill(row, args):
96
- continue
97
- selected.append(dict(row))
98
- if args.limit is not None and len(selected) >= args.limit:
99
- break
100
- return selected
101
-
102
-
103
- def persist_row_update(args: argparse.Namespace, video_id: str, updated_row: Dict[str, str], fieldnames: Sequence[str]) -> None:
104
- lock_path = lock_path_for_manifest(args.output_metadata_csv, args.csv_lock_path)
105
- handle = with_manifest_lock(lock_path)
106
- try:
107
- rows, current_fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv)
108
- merged_fieldnames = ordered_fieldnames(list(current_fieldnames) + list(fieldnames))
109
- found = False
110
- for row in rows:
111
- if (row.get("video_id") or "").strip() == video_id:
112
- merge_row_values(row, updated_row, merged_fieldnames)
113
- found = True
114
- break
115
- if not found:
116
- new_row = {column: updated_row.get(column, "") for column in merged_fieldnames}
117
- rows.append(new_row)
118
- write_manifest(args.output_metadata_csv, rows, merged_fieldnames)
119
- finally:
120
- import fcntl
121
- fcntl.flock(handle.fileno(), fcntl.LOCK_UN)
122
- handle.close()
123
-
124
-
125
- def main() -> None:
126
- args = parse_args()
127
- temp_cookie_path: Path | None = None
128
- if args.cookies:
129
- temp_cookie_path = sanitize_cookie_file(args.cookies)
130
- args._effective_cookies = temp_cookie_path
131
- else:
132
- args._effective_cookies = None
133
-
134
- try:
135
- rows, fieldnames = read_state_manifest(args.source_metadata_csv, args.output_metadata_csv)
136
- fields = ordered_fieldnames(fieldnames)
137
- pending = selected_rows(rows, args)
138
- args.dataset_dir.mkdir(parents=True, exist_ok=True)
139
- args.raw_metadata_dir.mkdir(parents=True, exist_ok=True)
140
-
141
- print(f"subtitle_backfill_selected={len(pending)}")
142
-
143
- ok_count = 0
144
- missing_count = 0
145
- failed_count = 0
146
- partial_count = 0
147
-
148
- for index, row in enumerate(pending, start=1):
149
- video_id = (row.get("video_id") or "").strip()
150
- print(f"[{index}/{len(pending)}] subtitle backfill {video_id}", flush=True)
151
- subtitle_error = ""
152
- metadata_error = ""
153
- stats_record: Dict[str, object] = {}
154
- try:
155
- metadata_path = args.raw_metadata_dir / f"{video_id}.json"
156
- if metadata_path.exists() and not args.force_metadata:
157
- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
158
- else:
159
- metadata, metadata_error = fetch_metadata(video_id, args)
160
- persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
161
- row["metadata_status"] = "ok"
162
- row["raw_metadata_path"] = repo_relative_or_absolute(metadata_path)
163
- row["title"] = str(metadata.get("title") or row.get("title") or "")
164
- row["duration_sec"] = str(metadata.get("duration") or row.get("duration_sec") or "")
165
- row["start_sec"] = row.get("start_sec") or "0"
166
- row["end_sec"] = str(metadata.get("duration") or row.get("end_sec") or "")
167
-
168
- manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata)
169
- preferred_manual = manual_langs[:1]
170
- preferred_native_auto = [] if preferred_manual else native_automatic_langs[:1]
171
- subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id)
172
- need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt"))
173
- if need_subtitles:
174
- subtitle_error = download_subtitles(
175
- video_id,
176
- subtitle_dir,
177
- preferred_manual,
178
- preferred_native_auto,
179
- english_translation_lang,
180
- args,
181
- )
182
- subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
183
- row["subtitle_status"] = "ok" if subtitle_payloads else "missing"
184
- row["subtitle_languages"] = "|".join(sorted(subtitle_payloads))
185
- row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else ""
186
- subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads)
187
- row["subtitle_en"] = subtitle_en
188
- row["subtitle_en_source"] = subtitle_en_source
189
- subtitle_json_path = write_subtitle_json(subtitle_dir, video_id, subtitle_payloads, subtitle_en, subtitle_en_source)
190
- row["subtitle_json_path"] = repo_relative_or_absolute(subtitle_json_path) if subtitle_json_path else ""
191
- row["subtitle_texts_json"] = json.dumps(
192
- build_subtitle_json_payload(video_id, subtitle_payloads, subtitle_en, subtitle_en_source).get("subtitle_texts", {}),
193
- ensure_ascii=False,
194
- ) if subtitle_payloads else ""
195
- row["raw_caption_dir"] = row["subtitle_dir_path"]
196
- row["download_status"] = row.get("download_status") or ""
197
- row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
198
- row["error"] = subtitle_error or metadata_error
199
-
200
- stats_record.update({
201
- "title": row["title"],
202
- "duration_sec": row["duration_sec"],
203
- "start_sec": row["start_sec"],
204
- "end_sec": row["end_sec"],
205
- "subtitle_languages": row["subtitle_languages"],
206
- "subtitle_dir_path": row["subtitle_dir_path"],
207
- "subtitle_en_source": row["subtitle_en_source"],
208
- "raw_metadata_path": row["raw_metadata_path"],
209
- "metadata_status": row["metadata_status"],
210
- "subtitle_status": row["subtitle_status"],
211
- "download_status": row["download_status"],
212
- "updated_at": row["processed_at"],
213
- "last_error": row["error"],
214
- })
215
- persist_row_update(args, video_id, row, fields)
216
- update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
217
-
218
- status = row["subtitle_status"]
219
- if status == "ok":
220
- ok_count += 1
221
- elif status == "missing":
222
- missing_count += 1
223
- elif status == "partial":
224
- partial_count += 1
225
- else:
226
- failed_count += 1
227
- print(f" subtitle_status={status} langs={row['subtitle_languages']}", flush=True)
228
- except Exception as exc:
229
- row["subtitle_status"] = "failed"
230
- row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
231
- row["error"] = str(exc)
232
- stats_record.update({
233
- "subtitle_status": row["subtitle_status"],
234
- "updated_at": row["processed_at"],
235
- "last_error": row["error"],
236
- })
237
- persist_row_update(args, video_id, row, fields)
238
- update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
239
- failed_count += 1
240
- print(f" subtitle_status=failed error={exc}", flush=True)
241
- if args.sleep_seconds > 0:
242
- time.sleep(args.sleep_seconds)
243
-
244
- print(
245
- f"subtitle_backfill_done ok={ok_count} missing={missing_count} partial={partial_count} failed={failed_count}",
246
- flush=True,
247
- )
248
- finally:
249
- if temp_cookie_path is not None:
250
- temp_cookie_path.unlink(missing_ok=True)
251
-
252
-
253
- if __name__ == '__main__':
254
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
scripts/pipeline01_download_video_fix_caption.py CHANGED
@@ -176,21 +176,12 @@ def read_state_manifest(source_csv: Path, output_csv: Path) -> Tuple[List[Dict[s
176
 
177
 
178
  def write_manifest(csv_path: Path, rows: Sequence[Dict[str, str]], fieldnames: Sequence[str]) -> None:
179
- csv_path.parent.mkdir(parents=True, exist_ok=True)
180
- with tempfile.NamedTemporaryFile(
181
- mode="w",
182
- encoding="utf-8",
183
- newline="",
184
- suffix=csv_path.suffix + ".tmp",
185
- prefix=csv_path.stem + ".",
186
- dir=csv_path.parent,
187
- delete=False,
188
- ) as handle:
189
  writer = csv.DictWriter(handle, fieldnames=fieldnames)
190
  writer.writeheader()
191
  for row in rows:
192
  writer.writerow({column: row.get(column, "") for column in fieldnames})
193
- tmp_path = Path(handle.name)
194
  tmp_path.replace(csv_path)
195
 
196
 
@@ -790,51 +781,7 @@ def row_failure_count(row: Dict[str, str]) -> int:
790
  return 0
791
 
792
 
793
- def is_terminal_source_error(error_text: str) -> bool:
794
- normalized = (error_text or "").strip().lower()
795
- if not normalized:
796
- return False
797
-
798
- non_terminal_markers = (
799
- "sign in",
800
- "cookies",
801
- "cookie",
802
- "429",
803
- "too many requests",
804
- "timed out",
805
- "timeout",
806
- "connection reset",
807
- "temporary failure",
808
- "network is unreachable",
809
- "http error 5",
810
- "unable to download",
811
- "requested format is not available",
812
- "filenotfounderror",
813
- "no such file or directory",
814
- )
815
- if any(marker in normalized for marker in non_terminal_markers):
816
- return False
817
-
818
- terminal_markers = (
819
- "video unavailable",
820
- "this video is private",
821
- "private video",
822
- "this video has been removed",
823
- "video has been removed",
824
- "account associated with this video has been terminated",
825
- "the playlist does not exist",
826
- "not a valid url",
827
- "copyright claim",
828
- "410 gone",
829
- )
830
- return any(marker in normalized for marker in terminal_markers)
831
-
832
-
833
  def record_row_failure(row: Dict[str, str], stats_record: Dict[str, object], error_text: str, max_failures_before_skip: int) -> tuple[int, bool]:
834
- if not is_terminal_source_error(error_text):
835
- stats_record["failure_count"] = row.get("failure_count", "0")
836
- return row_failure_count(row), False
837
-
838
  failure_count = row_failure_count(row) + 1
839
  row["failure_count"] = str(failure_count)
840
  stats_record["failure_count"] = row["failure_count"]
@@ -864,11 +811,7 @@ def row_needs_processing(row: Dict[str, str], args: argparse.Namespace) -> bool:
864
  needs_metadata = metadata_status != "ok"
865
  # Treat missing subtitles as a terminal state so videos without captions are not retried forever.
866
  needs_subtitles = (not args.skip_subtitles) and subtitle_status not in {"ok", "missing", "skipped"}
867
- needs_download = (
868
- (not args.skip_video_download)
869
- and subtitle_status == "ok"
870
- and download_status not in {"ok", "skipped"}
871
- )
872
  return needs_metadata or needs_subtitles or needs_download
873
 
874
 
@@ -900,139 +843,129 @@ def main() -> None:
900
  metadata: Dict[str, object] | None = None
901
 
902
  try:
903
- try:
904
- metadata_path = args.raw_metadata_dir / f"{video_id}.json"
905
- if metadata_path.exists() and not args.force_metadata:
906
- with metadata_path.open("r", encoding="utf-8") as handle:
907
- metadata = json.load(handle)
908
- else:
909
- metadata, metadata_error = fetch_metadata(video_id, args)
910
- row["raw_metadata_path"] = persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
911
- row["metadata_status"] = "ok"
912
- except Exception as exc:
913
- metadata_error = str(exc)
914
- row["metadata_status"] = "failed"
915
- row["error"] = metadata_error
916
- row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
917
- stats_record["metadata_status"] = "failed"
918
- stats_record["updated_at"] = row["processed_at"]
919
- failure_count, should_skip = record_row_failure(row, stats_record, metadata_error, args.max_failures_before_skip)
920
- stats_record["last_error"] = row["error"]
921
- persist_row_update(args, video_id, row, fieldnames)
922
- update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
923
- print(f" metadata failed: {metadata_error}")
924
- if should_skip:
925
- print(f" skipping after {failure_count} failures")
926
- if args.sleep_seconds > 0:
927
- time.sleep(args.sleep_seconds)
928
- continue
929
-
930
- assert metadata is not None
931
- row["raw_metadata_path"] = row.get("raw_metadata_path") or persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
932
- row["title"] = str(metadata.get("title") or "")
933
- duration = metadata.get("duration")
934
- row["duration_sec"] = str(duration or "")
935
- row["start_sec"] = "0"
936
- row["end_sec"] = str(duration or "")
937
-
938
- manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata)
939
- subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id)
940
- subtitle_payloads: Dict[str, Dict[str, object]] = {}
941
-
942
- if args.skip_subtitles:
943
- row["subtitle_status"] = "skipped"
944
  else:
945
- try:
946
- need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt"))
947
- if need_subtitles:
948
- subtitle_error = download_subtitles(
949
- video_id,
950
- subtitle_dir,
951
- manual_langs,
952
- native_automatic_langs,
953
- english_translation_lang,
954
- args,
955
- )
956
- subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
957
- row["subtitle_status"] = "ok" if subtitle_payloads else "missing"
958
- except Exception as exc:
959
- subtitle_error = str(exc)
960
- subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
961
- row["subtitle_status"] = "partial" if subtitle_payloads else "failed"
962
-
963
- row["subtitle_languages"] = "|".join(sorted(subtitle_payloads))
964
- row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else ""
965
- subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads)
966
- row["subtitle_en_source"] = subtitle_en_source
967
- if "subtitle_texts_json" in row:
968
- row["subtitle_texts_json"] = ""
969
- if "subtitle_en" in row:
970
- row["subtitle_en"] = ""
971
- if "subtitle_json_path" in row:
972
- row["subtitle_json_path"] = ""
973
- if "raw_caption_dir" in row:
974
- row["raw_caption_dir"] = ""
975
-
976
- try:
977
- existing_video = find_video_file(args.raw_video_dir, video_id, args.scratch_raw_video_dir)
978
- if args.skip_video_download:
979
- row["download_status"] = "skipped"
980
- row["raw_video_path"] = repo_relative_or_absolute(existing_video) if existing_video else ""
981
- elif row["subtitle_status"] != "ok":
982
- if existing_video is not None:
983
- existing_video.unlink(missing_ok=True)
984
- row["raw_video_path"] = ""
985
- row["download_status"] = "skipped"
986
- if not download_error:
987
- download_error = "subtitle required before video download"
988
- else:
989
- if existing_video is None or args.force_download:
990
- row["raw_video_path"], download_error = download_video(video_id, args.raw_video_dir, args)
991
- else:
992
- row["raw_video_path"] = repo_relative_or_absolute(existing_video)
993
- row["download_status"] = "ok" if row["raw_video_path"] else "failed"
994
- except Exception as exc:
995
- download_error = str(exc)
996
- row["download_status"] = "failed"
997
-
998
- errors = [value for value in [metadata_error, subtitle_error, download_error] if value]
999
- row["error"] = " | ".join(errors)
1000
  row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
1001
- stats_record["sign_language"] = row.get("sign_language", "")
1002
- stats_record["title"] = row["title"]
1003
- stats_record["duration_sec"] = row["duration_sec"]
1004
- stats_record["start_sec"] = row["start_sec"]
1005
- stats_record["end_sec"] = row["end_sec"]
1006
- stats_record["subtitle_languages"] = row["subtitle_languages"]
1007
- stats_record["subtitle_dir_path"] = row["subtitle_dir_path"]
1008
- stats_record["subtitle_en_source"] = row["subtitle_en_source"]
1009
- stats_record["raw_video_path"] = row["raw_video_path"]
1010
- stats_record["raw_metadata_path"] = row["raw_metadata_path"]
1011
- stats_record["metadata_status"] = row["metadata_status"]
1012
- stats_record["subtitle_status"] = row["subtitle_status"]
1013
- stats_record["download_status"] = row["download_status"]
1014
- if errors:
1015
- failure_count, should_skip = record_row_failure(row, stats_record, row["error"], args.max_failures_before_skip)
1016
- else:
1017
- reset_row_failures(row, stats_record)
1018
- failure_count, should_skip = 0, False
1019
- stats_record["download_status"] = row["download_status"]
1020
- stats_record["last_error"] = row["error"]
1021
  stats_record["updated_at"] = row["processed_at"]
 
 
1022
  persist_row_update(args, video_id, row, fieldnames)
1023
  update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
1024
-
1025
- if row["download_status"] == "failed":
1026
- print(f" video download failed: {download_error}")
1027
- if row["subtitle_status"] in {"failed", "partial"}:
1028
- print(f" subtitle status: {row['subtitle_status']} {subtitle_error}")
1029
  if should_skip:
1030
  print(f" skipping after {failure_count} failures")
1031
-
1032
  if args.sleep_seconds > 0:
1033
  time.sleep(args.sleep_seconds)
1034
- finally:
1035
- release_claim(args, video_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1036
  finally:
1037
  if temp_cookie_path is not None:
1038
  temp_cookie_path.unlink(missing_ok=True)
 
176
 
177
 
178
  def write_manifest(csv_path: Path, rows: Sequence[Dict[str, str]], fieldnames: Sequence[str]) -> None:
179
+ tmp_path = csv_path.with_suffix(csv_path.suffix + ".tmp")
180
+ with tmp_path.open("w", encoding="utf-8", newline="") as handle:
 
 
 
 
 
 
 
 
181
  writer = csv.DictWriter(handle, fieldnames=fieldnames)
182
  writer.writeheader()
183
  for row in rows:
184
  writer.writerow({column: row.get(column, "") for column in fieldnames})
 
185
  tmp_path.replace(csv_path)
186
 
187
 
 
781
  return 0
782
 
783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
784
  def record_row_failure(row: Dict[str, str], stats_record: Dict[str, object], error_text: str, max_failures_before_skip: int) -> tuple[int, bool]:
 
 
 
 
785
  failure_count = row_failure_count(row) + 1
786
  row["failure_count"] = str(failure_count)
787
  stats_record["failure_count"] = row["failure_count"]
 
811
  needs_metadata = metadata_status != "ok"
812
  # Treat missing subtitles as a terminal state so videos without captions are not retried forever.
813
  needs_subtitles = (not args.skip_subtitles) and subtitle_status not in {"ok", "missing", "skipped"}
814
+ needs_download = (not args.skip_video_download) and download_status != "ok"
 
 
 
 
815
  return needs_metadata or needs_subtitles or needs_download
816
 
817
 
 
843
  metadata: Dict[str, object] | None = None
844
 
845
  try:
846
+ metadata_path = args.raw_metadata_dir / f"{video_id}.json"
847
+ if metadata_path.exists() and not args.force_metadata:
848
+ with metadata_path.open("r", encoding="utf-8") as handle:
849
+ metadata = json.load(handle)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
850
  else:
851
+ metadata, metadata_error = fetch_metadata(video_id, args)
852
+ row["raw_metadata_path"] = persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
853
+ row["metadata_status"] = "ok"
854
+ except Exception as exc:
855
+ metadata_error = str(exc)
856
+ row["metadata_status"] = "failed"
857
+ row["error"] = metadata_error
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
858
  row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
859
+ stats_record["metadata_status"] = "failed"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
860
  stats_record["updated_at"] = row["processed_at"]
861
+ failure_count, should_skip = record_row_failure(row, stats_record, metadata_error, args.max_failures_before_skip)
862
+ stats_record["last_error"] = row["error"]
863
  persist_row_update(args, video_id, row, fieldnames)
864
  update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
865
+ print(f" metadata failed: {metadata_error}")
 
 
 
 
866
  if should_skip:
867
  print(f" skipping after {failure_count} failures")
 
868
  if args.sleep_seconds > 0:
869
  time.sleep(args.sleep_seconds)
870
+ continue
871
+
872
+ assert metadata is not None
873
+ row["raw_metadata_path"] = row.get("raw_metadata_path") or persist_raw_metadata(args.raw_metadata_dir, video_id, metadata)
874
+ row["title"] = str(metadata.get("title") or "")
875
+ duration = metadata.get("duration")
876
+ row["duration_sec"] = str(duration or "")
877
+ row["start_sec"] = "0"
878
+ row["end_sec"] = str(duration or "")
879
+
880
+ manual_langs, native_automatic_langs, english_translation_lang = filter_caption_languages(metadata)
881
+ subtitle_dir = subtitle_dir_for_video(args.dataset_dir, video_id)
882
+ subtitle_payloads: Dict[str, Dict[str, object]] = {}
883
+
884
+ if args.skip_subtitles:
885
+ row["subtitle_status"] = "skipped"
886
+ else:
887
+ try:
888
+ need_subtitles = args.force_subtitles or not any(subtitle_dir.glob(f"{video_id}.*.vtt"))
889
+ if need_subtitles:
890
+ subtitle_error = download_subtitles(
891
+ video_id,
892
+ subtitle_dir,
893
+ manual_langs,
894
+ native_automatic_langs,
895
+ english_translation_lang,
896
+ args,
897
+ )
898
+ subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
899
+ row["subtitle_status"] = "ok" if subtitle_payloads else "missing"
900
+ except Exception as exc:
901
+ subtitle_error = str(exc)
902
+ subtitle_payloads = load_subtitle_payloads(subtitle_dir, video_id)
903
+ row["subtitle_status"] = "partial" if subtitle_payloads else "failed"
904
+
905
+ row["subtitle_languages"] = "|".join(sorted(subtitle_payloads))
906
+ row["subtitle_dir_path"] = repo_relative_or_absolute(subtitle_dir) if subtitle_payloads else ""
907
+ subtitle_en, subtitle_en_source = select_english_subtitle(subtitle_payloads)
908
+ row["subtitle_en_source"] = subtitle_en_source
909
+ if "subtitle_texts_json" in row:
910
+ row["subtitle_texts_json"] = ""
911
+ if "subtitle_en" in row:
912
+ row["subtitle_en"] = ""
913
+ if "subtitle_json_path" in row:
914
+ row["subtitle_json_path"] = ""
915
+ if "raw_caption_dir" in row:
916
+ row["raw_caption_dir"] = ""
917
+
918
+ try:
919
+ existing_video = find_video_file(args.raw_video_dir, video_id, args.scratch_raw_video_dir)
920
+ if args.skip_video_download:
921
+ row["download_status"] = "skipped"
922
+ row["raw_video_path"] = repo_relative_or_absolute(existing_video) if existing_video else ""
923
+ else:
924
+ if existing_video is None or args.force_download:
925
+ row["raw_video_path"], download_error = download_video(video_id, args.raw_video_dir, args)
926
+ else:
927
+ row["raw_video_path"] = repo_relative_or_absolute(existing_video)
928
+ row["download_status"] = "ok" if row["raw_video_path"] else "failed"
929
+ except Exception as exc:
930
+ download_error = str(exc)
931
+ row["download_status"] = "failed"
932
+
933
+ errors = [value for value in [metadata_error, subtitle_error, download_error] if value]
934
+ row["error"] = " | ".join(errors)
935
+ row["processed_at"] = time.strftime("%Y-%m-%d %H:%M:%S")
936
+ stats_record["sign_language"] = row.get("sign_language", "")
937
+ stats_record["title"] = row["title"]
938
+ stats_record["duration_sec"] = row["duration_sec"]
939
+ stats_record["start_sec"] = row["start_sec"]
940
+ stats_record["end_sec"] = row["end_sec"]
941
+ stats_record["subtitle_languages"] = row["subtitle_languages"]
942
+ stats_record["subtitle_dir_path"] = row["subtitle_dir_path"]
943
+ stats_record["subtitle_en_source"] = row["subtitle_en_source"]
944
+ stats_record["raw_video_path"] = row["raw_video_path"]
945
+ stats_record["raw_metadata_path"] = row["raw_metadata_path"]
946
+ stats_record["metadata_status"] = row["metadata_status"]
947
+ stats_record["subtitle_status"] = row["subtitle_status"]
948
+ stats_record["download_status"] = row["download_status"]
949
+ if errors:
950
+ failure_count, should_skip = record_row_failure(row, stats_record, row["error"], args.max_failures_before_skip)
951
+ else:
952
+ reset_row_failures(row, stats_record)
953
+ failure_count, should_skip = 0, False
954
+ stats_record["download_status"] = row["download_status"]
955
+ stats_record["last_error"] = row["error"]
956
+ stats_record["updated_at"] = row["processed_at"]
957
+ persist_row_update(args, video_id, row, fieldnames)
958
+ update_video_stats_best_effort(args.stats_npz, args.status_journal_path, video_id, **stats_record)
959
+
960
+ if row["download_status"] == "failed":
961
+ print(f" video download failed: {download_error}")
962
+ if row["subtitle_status"] in {"failed", "partial"}:
963
+ print(f" subtitle status: {row['subtitle_status']} {subtitle_error}")
964
+ if should_skip:
965
+ print(f" skipping after {failure_count} failures")
966
+
967
+ if args.sleep_seconds > 0:
968
+ time.sleep(args.sleep_seconds)
969
  finally:
970
  if temp_cookie_path is not None:
971
  temp_cookie_path.unlink(missing_ok=True)
scripts/pipeline02_extract_dwpose_from_video.py CHANGED
@@ -35,7 +35,7 @@ from utils.stats_npz import (
35
  processed_complete_counter_path,
36
  update_video_stats_best_effort,
37
  )
38
- from utils.raw_video_pool import find_video_file, iter_raw_video_files
39
  from utils.dataset_pool import dataset_dir_for_video, find_dataset_video_dir
40
 
41
 
@@ -47,25 +47,6 @@ VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov"}
47
  COMPLETE_MARKER_NAME = ".complete"
48
 
49
 
50
- def sync_caption_dir(video_id: str, output_dataset_dir: Path, home_dataset_dir: Path, scratch_dataset_dir: Path | None) -> None:
51
- output_caption_dir = output_dataset_dir / video_id / "captions"
52
- if any(output_caption_dir.glob("*.vtt")):
53
- return
54
- source_dirs = [home_dataset_dir / video_id / "captions"]
55
- if scratch_dataset_dir is not None:
56
- source_dirs.append(scratch_dataset_dir / video_id / "captions")
57
- for source_dir in source_dirs:
58
- if not source_dir.exists():
59
- continue
60
- vtts = sorted(source_dir.glob("*.vtt"))
61
- if not vtts:
62
- continue
63
- output_caption_dir.mkdir(parents=True, exist_ok=True)
64
- for source_path in vtts:
65
- shutil.copy2(source_path, output_caption_dir / source_path.name)
66
- break
67
-
68
-
69
  def build_optimized_providers(device: str, optimized_provider: str, cache_dir: Path):
70
  device = str(device)
71
  gpu_id = 0
@@ -224,27 +205,12 @@ def select_video_paths(args: argparse.Namespace) -> List[Path]:
224
  stats = load_stats(args.stats_npz)
225
 
226
  selected = []
227
- if video_id_filter:
228
- candidate_paths = []
229
- for video_id in sorted(video_id_filter):
230
- path = find_video_file(video_id, args.raw_video_dir, args.scratch_raw_video_dir)
231
- if path is not None:
232
- candidate_paths.append(path)
233
- else:
234
- candidate_paths = sorted(
235
- iter_raw_video_files(args.raw_video_dir, args.scratch_raw_video_dir),
236
- key=lambda p: (p.stem, str(p)),
237
- )
238
-
239
- for path in candidate_paths:
240
  video_id = path.stem
241
  if video_id_filter and video_id not in video_id_filter:
242
  continue
243
- dataset_video_dir = find_dataset_video_dir(video_id, args.dataset_dir, args.scratch_dataset_dir)
244
- caption_dir = dataset_video_dir / "captions"
245
- if not any(caption_dir.glob("*.vtt")):
246
- continue
247
- npz_dir = dataset_video_dir / "npz"
248
  complete_marker = npz_dir / COMPLETE_MARKER_NAME
249
  if (
250
  not args.force
@@ -644,7 +610,6 @@ def process_video(
644
  if output_npz_dir.exists() and (force or not complete_marker.exists()):
645
  shutil.rmtree(output_npz_dir)
646
  output_npz_dir.mkdir(parents=True, exist_ok=True)
647
- sync_caption_dir(video_id, output_dataset_dir, dataset_dir, scratch_dataset_dir)
648
 
649
  aggregated_payloads = []
650
  frame_widths = []
 
35
  processed_complete_counter_path,
36
  update_video_stats_best_effort,
37
  )
38
+ from utils.raw_video_pool import iter_raw_video_files
39
  from utils.dataset_pool import dataset_dir_for_video, find_dataset_video_dir
40
 
41
 
 
47
  COMPLETE_MARKER_NAME = ".complete"
48
 
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  def build_optimized_providers(device: str, optimized_provider: str, cache_dir: Path):
51
  device = str(device)
52
  gpu_id = 0
 
205
  stats = load_stats(args.stats_npz)
206
 
207
  selected = []
208
+ for path in sorted(iter_raw_video_files(args.raw_video_dir, args.scratch_raw_video_dir), key=lambda p: (p.stem, str(p))):
 
 
 
 
 
 
 
 
 
 
 
 
209
  video_id = path.stem
210
  if video_id_filter and video_id not in video_id_filter:
211
  continue
212
+ dataset_root = find_dataset_video_dir(video_id, args.dataset_dir, args.scratch_dataset_dir)
213
+ npz_dir = dataset_root / video_id / "npz"
 
 
 
214
  complete_marker = npz_dir / COMPLETE_MARKER_NAME
215
  if (
216
  not args.force
 
610
  if output_npz_dir.exists() and (force or not complete_marker.exists()):
611
  shutil.rmtree(output_npz_dir)
612
  output_npz_dir.mkdir(parents=True, exist_ok=True)
 
613
 
614
  aggregated_payloads = []
615
  frame_widths = []
scripts/pipeline03_upload_to_huggingface.py CHANGED
@@ -428,15 +428,22 @@ def cleanup_local_assets(
428
  for video_id in video_ids:
429
  dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)
430
  had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists()
431
- safe_remove_tree(dataset_video_dir, context=f"cleanup uploaded dataset {video_id}")
 
432
  if had_complete:
433
  adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1)
434
  for raw_dir in [raw_video_dir, scratch_raw_video_dir]:
435
- safe_remove_matching_files(raw_dir, f"{video_id}.*", context=f"cleanup uploaded raw video {video_id}")
 
 
 
 
436
  caption_dir = raw_caption_dir / video_id
437
- safe_remove_tree(caption_dir, context=f"cleanup uploaded caption {video_id}")
 
438
  metadata_path = raw_metadata_dir / f"{video_id}.json"
439
- safe_remove_file(metadata_path, context=f"cleanup uploaded metadata {video_id}")
 
440
 
441
 
442
  def prune_uploaded_runtime_residue(
@@ -452,50 +459,25 @@ def prune_uploaded_runtime_residue(
452
  uploaded = set(progress.get("uploaded_folders", {}))
453
  for video_id in uploaded:
454
  for raw_dir in [raw_video_dir, scratch_raw_video_dir]:
455
- safe_remove_matching_files(raw_dir, f"{video_id}.*", context=f"prune uploaded raw video {video_id}")
 
 
 
 
456
  caption_dir = raw_caption_dir / video_id
457
- safe_remove_tree(caption_dir, context=f"prune uploaded caption {video_id}")
 
458
  metadata_path = raw_metadata_dir / f"{video_id}.json"
459
- safe_remove_file(metadata_path, context=f"prune uploaded metadata {video_id}")
 
460
  dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)
461
  had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists()
462
- safe_remove_tree(dataset_video_dir, context=f"prune uploaded dataset {video_id}")
 
463
  if had_complete and stats_npz is not None:
464
  adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1)
465
 
466
 
467
- def safe_remove_matching_files(parent_dir: Path | None, pattern: str, *, context: str) -> None:
468
- if parent_dir is None:
469
- return
470
- try:
471
- matches = list(parent_dir.glob(pattern))
472
- except OSError as exc:
473
- print(f"[pipeline03] warning: failed to scan {parent_dir} for {pattern} during {context}: {exc}", flush=True)
474
- return
475
- for path in matches:
476
- try:
477
- if path.is_file():
478
- path.unlink(missing_ok=True)
479
- except OSError as exc:
480
- print(f"[pipeline03] warning: failed to remove {path} during {context}: {exc}", flush=True)
481
-
482
-
483
- def safe_remove_tree(path: Path, *, context: str) -> None:
484
- try:
485
- if path.exists():
486
- shutil.rmtree(path, ignore_errors=True)
487
- except OSError as exc:
488
- print(f"[pipeline03] warning: failed to remove directory {path} during {context}: {exc}", flush=True)
489
-
490
-
491
- def safe_remove_file(path: Path, *, context: str) -> None:
492
- try:
493
- if path.exists():
494
- path.unlink(missing_ok=True)
495
- except OSError as exc:
496
- print(f"[pipeline03] warning: failed to remove file {path} during {context}: {exc}", flush=True)
497
-
498
-
499
  def format_size(num_bytes: int) -> str:
500
  size = float(num_bytes)
501
  for unit in ["B", "KB", "MB", "GB", "TB"]:
 
428
  for video_id in video_ids:
429
  dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)
430
  had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists()
431
+ if dataset_video_dir.exists():
432
+ shutil.rmtree(dataset_video_dir, ignore_errors=True)
433
  if had_complete:
434
  adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1)
435
  for raw_dir in [raw_video_dir, scratch_raw_video_dir]:
436
+ if raw_dir is None:
437
+ continue
438
+ for path in raw_dir.glob(f"{video_id}.*"):
439
+ if path.is_file():
440
+ path.unlink()
441
  caption_dir = raw_caption_dir / video_id
442
+ if caption_dir.exists():
443
+ shutil.rmtree(caption_dir, ignore_errors=True)
444
  metadata_path = raw_metadata_dir / f"{video_id}.json"
445
+ if metadata_path.exists():
446
+ metadata_path.unlink(missing_ok=True)
447
 
448
 
449
  def prune_uploaded_runtime_residue(
 
459
  uploaded = set(progress.get("uploaded_folders", {}))
460
  for video_id in uploaded:
461
  for raw_dir in [raw_video_dir, scratch_raw_video_dir]:
462
+ if raw_dir is None:
463
+ continue
464
+ for path in raw_dir.glob(f"{video_id}.*"):
465
+ if path.is_file():
466
+ path.unlink(missing_ok=True)
467
  caption_dir = raw_caption_dir / video_id
468
+ if caption_dir.exists():
469
+ shutil.rmtree(caption_dir, ignore_errors=True)
470
  metadata_path = raw_metadata_dir / f"{video_id}.json"
471
+ if metadata_path.exists():
472
+ metadata_path.unlink(missing_ok=True)
473
  dataset_video_dir = find_dataset_video_dir(video_id, dataset_dir, scratch_dataset_dir)
474
  had_complete = (dataset_video_dir / "npz" / COMPLETE_MARKER_NAME).exists()
475
+ if dataset_video_dir.exists():
476
+ shutil.rmtree(dataset_video_dir, ignore_errors=True)
477
  if had_complete and stats_npz is not None:
478
  adjust_processed_complete_counter(processed_complete_counter_path(stats_npz), -1)
479
 
480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  def format_size(num_bytes: int) -> str:
482
  size = float(num_bytes)
483
  for unit in ["B", "KB", "MB", "GB", "TB"]:
slurm/orchestrator_autorestart.slurm CHANGED
@@ -1,5 +1,5 @@
1
  #!/usr/bin/env bash
2
- #SBATCH --partition=main-redhat
3
  #SBATCH --job-name=sign-dwpose-launcher
4
  #SBATCH --nodes=1
5
  #SBATCH --ntasks=1
@@ -20,7 +20,7 @@ ROTATE_SECONDS="${ROTATE_SECONDS:-43200}"
20
  CHECK_INTERVAL_SECONDS="${CHECK_INTERVAL_SECONDS:-60}"
21
  ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"
22
  LAUNCHER_SCRIPT="${LAUNCHER_SCRIPT:-$ROOT_DIR/slurm/orchestrator_autorestart.slurm}"
23
- LAUNCHER_PARTITION="${LAUNCHER_PARTITION:-main-redhat}"
24
  LAUNCHER_ACCOUNT="${LAUNCHER_ACCOUNT:-}"
25
  LAUNCHER_TIME="${LAUNCHER_TIME:-12:30:00}"
26
  LAUNCHER_CPUS_PER_TASK="${LAUNCHER_CPUS_PER_TASK:-1}"
 
1
  #!/usr/bin/env bash
2
+ #SBATCH --partition=main
3
  #SBATCH --job-name=sign-dwpose-launcher
4
  #SBATCH --nodes=1
5
  #SBATCH --ntasks=1
 
20
  CHECK_INTERVAL_SECONDS="${CHECK_INTERVAL_SECONDS:-60}"
21
  ORCHESTRATOR_TIME="${ORCHESTRATOR_TIME:-12:00:00}"
22
  LAUNCHER_SCRIPT="${LAUNCHER_SCRIPT:-$ROOT_DIR/slurm/orchestrator_autorestart.slurm}"
23
+ LAUNCHER_PARTITION="${LAUNCHER_PARTITION:-main}"
24
  LAUNCHER_ACCOUNT="${LAUNCHER_ACCOUNT:-}"
25
  LAUNCHER_TIME="${LAUNCHER_TIME:-12:30:00}"
26
  LAUNCHER_CPUS_PER_TASK="${LAUNCHER_CPUS_PER_TASK:-1}"
slurm/submit_download_slurm.sh CHANGED
@@ -22,7 +22,7 @@ STATE_DIR="${STATE_DIR:-$STATE_ROOT/slurm/state}"
22
  DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_DIR/download_claims}"
23
  LOCK_FILE="$STATE_DIR/submit_download.lock"
24
  DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$STATE_ROOT/SignVerse-2M-metadata_processed.csv.lock}"
25
- PARTITIONS="main-redhat"
26
  ACCOUNT=""
27
  TIME_LIMIT="04:00:00"
28
  CPUS_PER_TASK="1"
@@ -49,7 +49,7 @@ Usage:
49
  bash slurm/submit_download_slurm.sh [options]
50
 
51
  Options:
52
- --partitions P1[,P2,...] Comma-separated CPU partitions. Default: main-redhat
53
  --runtime-root DIR Shared runtime root
54
  --state-root DIR Shared state/log root
55
  --account NAME Optional Slurm account
 
22
  DOWNLOAD_CLAIM_DIR="${DOWNLOAD_CLAIM_DIR:-$STATE_DIR/download_claims}"
23
  LOCK_FILE="$STATE_DIR/submit_download.lock"
24
  DOWNLOAD_CSV_LOCK_PATH="${DOWNLOAD_CSV_LOCK_PATH:-$STATE_ROOT/SignVerse-2M-metadata_processed.csv.lock}"
25
+ PARTITIONS="main"
26
  ACCOUNT=""
27
  TIME_LIMIT="04:00:00"
28
  CPUS_PER_TASK="1"
 
49
  bash slurm/submit_download_slurm.sh [options]
50
 
51
  Options:
52
+ --partitions P1[,P2,...] Comma-separated CPU partitions. Default: main
53
  --runtime-root DIR Shared runtime root
54
  --state-root DIR Shared state/log root
55
  --account NAME Optional Slurm account
slurm/submit_dwpose_slurm.sh CHANGED
@@ -18,7 +18,7 @@ LOG_DIR="${LOG_DIR:-$STATE_ROOT/slurm/logs}"
18
  STATE_DIR="${STATE_DIR:-$STATE_ROOT/slurm/state}"
19
  CLAIM_DIR="${CLAIM_DIR:-$STATE_DIR/claims}"
20
  LOCK_FILE="$STATE_DIR/submit.lock"
21
- PARTITIONS="gpu-redhat,gpu,cgpu"
22
  ACCOUNT=""
23
  TIME_LIMIT="24:00:00"
24
  CPUS_PER_TASK="8"
@@ -44,7 +44,7 @@ Usage:
44
  bash slurm/submit_dwpose_slurm.sh [options]
45
 
46
  Options:
47
- --partitions P1[,P2,...] Comma-separated partitions. Default: gpu-redhat,gpu,cgpu
48
  --runtime-root DIR Shared runtime root for data/state
49
  --state-root DIR Shared state/log root (default: runtime root)
50
  --account NAME Optional Slurm account
 
18
  STATE_DIR="${STATE_DIR:-$STATE_ROOT/slurm/state}"
19
  CLAIM_DIR="${CLAIM_DIR:-$STATE_DIR/claims}"
20
  LOCK_FILE="$STATE_DIR/submit.lock"
21
+ PARTITIONS="gpu,gpu-redhat,cgpu"
22
  ACCOUNT=""
23
  TIME_LIMIT="24:00:00"
24
  CPUS_PER_TASK="8"
 
44
  bash slurm/submit_dwpose_slurm.sh [options]
45
 
46
  Options:
47
+ --partitions P1[,P2,...] Comma-separated partitions. Default: gpu,gpu-redhat,cgpu
48
  --runtime-root DIR Shared runtime root for data/state
49
  --state-root DIR Shared state/log root (default: runtime root)
50
  --account NAME Optional Slurm account
slurm/submit_upload_parallel_drain.sh CHANGED
@@ -5,21 +5,18 @@ ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"
5
  SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_upload_parallel_slurm.sh}"
6
  PARALLEL_SHARDS="${PARALLEL_SHARDS:-8}"
7
  ARRAY_PARALLEL="${ARRAY_PARALLEL:-8}"
8
- PARTITION="${PARTITION:-main-redhat}"
9
  START_STAGGER_MIN="${START_STAGGER_MIN:-1}"
10
  START_STAGGER_MAX="${START_STAGGER_MAX:-3}"
11
  TARGET_BYTES="${TARGET_BYTES:-10737418240}"
12
  TARGET_FOLDERS="${TARGET_FOLDERS:-40}"
13
  SLEEP_BETWEEN_WAVES="${SLEEP_BETWEEN_WAVES:-15}"
14
  PROGRESS_JSON="${PROGRESS_JSON:-/home/sf895/SignVerse-2M-runtime/archive_upload_progress.json}"
15
- STATE_ROOT="${STATE_ROOT:-/home/sf895/SignVerse-2M-runtime}"
16
  HOME_DATASET_DIR="${HOME_DATASET_DIR:-/home/sf895/SignVerse-2M-runtime/dataset}"
17
  SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"
18
- HOME_RAW_VIDEO_DIR="${HOME_RAW_VIDEO_DIR:-/home/sf895/SignVerse-2M-runtime/raw_video}"
19
- SCRATCH_RAW_VIDEO_DIR="${SCRATCH_RAW_VIDEO_DIR:-/scratch/$USER/SignVerse-2M-runtime/raw_video}"
20
 
21
- remaining_stats() {
22
- python3 - <<PY2
23
  import json
24
  from pathlib import Path
25
  import sys
@@ -27,34 +24,13 @@ sys.path.insert(0, '/cache/home/sf895/SignVerse-2M')
27
  from utils.dataset_pool import list_unuploaded_folder_paths
28
  progress = json.loads(Path(r"$PROGRESS_JSON").read_text())
29
  folders = list_unuploaded_folder_paths(Path(r"$HOME_DATASET_DIR"), Path(r"$SCRATCH_DATASET_DIR"), progress.get('uploaded_folders', {}))
30
- size_bytes = 0
31
- for item in folders:
32
- path = item[1] if isinstance(item, tuple) else item
33
- try:
34
- for child in path.rglob('*'):
35
- if child.is_file():
36
- size_bytes += child.stat().st_size
37
- except FileNotFoundError:
38
- continue
39
- print(f"remaining={len(folders)}")
40
- print(f"bytes={size_bytes}")
41
- PY2
42
- }
43
-
44
- upstream_busy() {
45
- local download_claims process_claims raw_count
46
- download_claims=$(find "$STATE_ROOT/slurm/state/download_claims" -maxdepth 1 -type f -name '*.claim' 2>/dev/null | wc -l)
47
- process_claims=$(find "$STATE_ROOT/slurm/state/claims" -maxdepth 1 -type f -name '*.claim' 2>/dev/null | wc -l)
48
- 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)
49
- if [[ "$download_claims" -gt 0 || "$process_claims" -gt 0 || "$raw_count" -gt 0 ]]; then
50
- return 0
51
- fi
52
- return 1
53
  }
54
 
55
  while true; do
56
- eval "$(remaining_stats)"
57
- echo "[drain] remaining_unuploaded=$remaining remaining_bytes=$bytes"
58
  if [[ "$remaining" == "0" ]]; then
59
  echo "[drain] backlog cleared"
60
  break
@@ -63,27 +39,17 @@ while true; do
63
  shards="$PARALLEL_SHARDS"
64
  array_parallel="$ARRAY_PARALLEL"
65
  extra_args=()
66
- # Keep each normal shard at or above TARGET_FOLDERS when possible.
67
- # For example, 311 folders should use 7 shards, not 8, so each shard still has >=40 folders.
68
- needed_shards=$(( remaining / TARGET_FOLDERS ))
69
- if (( needed_shards < 1 )); then
70
- needed_shards=1
71
- fi
72
  if (( needed_shards < shards )); then
73
  shards="$needed_shards"
74
  fi
75
  if (( shards < 1 )); then
76
  shards=1
77
  fi
78
-
79
- if (( remaining < TARGET_FOLDERS && bytes < TARGET_BYTES )); then
80
- echo "[drain] below upload thresholds; skip upload wave"
81
- break
82
- fi
83
-
84
  if (( shards == 1 )); then
85
  array_parallel=""
86
- echo "[drain] single-shard strict mode"
 
87
  else
88
  if (( array_parallel > shards )); then
89
  array_parallel="$shards"
@@ -106,7 +72,7 @@ while true; do
106
  submit_cmd+=("${extra_args[@]}")
107
  fi
108
 
109
- submit_out="$(${submit_cmd[@]})"
110
  echo "$submit_out"
111
  job_id="$(awk '/Submitted batch job/{print $4}' <<< "$submit_out" | tail -n1)"
112
  if [[ -z "$job_id" ]]; then
 
5
  SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_upload_parallel_slurm.sh}"
6
  PARALLEL_SHARDS="${PARALLEL_SHARDS:-8}"
7
  ARRAY_PARALLEL="${ARRAY_PARALLEL:-8}"
8
+ PARTITION="${PARTITION:-main}"
9
  START_STAGGER_MIN="${START_STAGGER_MIN:-1}"
10
  START_STAGGER_MAX="${START_STAGGER_MAX:-3}"
11
  TARGET_BYTES="${TARGET_BYTES:-10737418240}"
12
  TARGET_FOLDERS="${TARGET_FOLDERS:-40}"
13
  SLEEP_BETWEEN_WAVES="${SLEEP_BETWEEN_WAVES:-15}"
14
  PROGRESS_JSON="${PROGRESS_JSON:-/home/sf895/SignVerse-2M-runtime/archive_upload_progress.json}"
 
15
  HOME_DATASET_DIR="${HOME_DATASET_DIR:-/home/sf895/SignVerse-2M-runtime/dataset}"
16
  SCRATCH_DATASET_DIR="${SCRATCH_DATASET_DIR:-/scratch/$USER/SignVerse-2M-runtime/dataset}"
 
 
17
 
18
+ remaining_unuploaded() {
19
+ python3 - <<PY
20
  import json
21
  from pathlib import Path
22
  import sys
 
24
  from utils.dataset_pool import list_unuploaded_folder_paths
25
  progress = json.loads(Path(r"$PROGRESS_JSON").read_text())
26
  folders = list_unuploaded_folder_paths(Path(r"$HOME_DATASET_DIR"), Path(r"$SCRATCH_DATASET_DIR"), progress.get('uploaded_folders', {}))
27
+ print(len(folders))
28
+ PY
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
 
31
  while true; do
32
+ remaining="$(remaining_unuploaded)"
33
+ echo "[drain] remaining_unuploaded=$remaining"
34
  if [[ "$remaining" == "0" ]]; then
35
  echo "[drain] backlog cleared"
36
  break
 
39
  shards="$PARALLEL_SHARDS"
40
  array_parallel="$ARRAY_PARALLEL"
41
  extra_args=()
42
+ needed_shards=$(((remaining + TARGET_FOLDERS - 1) / TARGET_FOLDERS))
 
 
 
 
 
43
  if (( needed_shards < shards )); then
44
  shards="$needed_shards"
45
  fi
46
  if (( shards < 1 )); then
47
  shards=1
48
  fi
 
 
 
 
 
 
49
  if (( shards == 1 )); then
50
  array_parallel=""
51
+ extra_args+=(--allow-small-final-batch --no-require-target-bytes)
52
+ echo "[drain] switching to single-shard tail mode"
53
  else
54
  if (( array_parallel > shards )); then
55
  array_parallel="$shards"
 
72
  submit_cmd+=("${extra_args[@]}")
73
  fi
74
 
75
+ submit_out="$("${submit_cmd[@]}")"
76
  echo "$submit_out"
77
  job_id="$(awk '/Submitted batch job/{print $4}' <<< "$submit_out" | tail -n1)"
78
  if [[ -z "$job_id" ]]; then
slurm/submit_upload_parallel_slurm.sh CHANGED
@@ -4,7 +4,7 @@ set -euo pipefail
4
  ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"
5
  RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"
6
  SLURM_SCRIPT="${SLURM_SCRIPT:-$ROOT_DIR/slurm/process_upload_parallel_array.slurm}"
7
- PARTITION="${PARTITION:-main-redhat}"
8
  TIME_LIMIT="${TIME_LIMIT:-24:00:00}"
9
  CPUS_PER_TASK="${CPUS_PER_TASK:-2}"
10
  MEMORY="${MEMORY:-8G}"
@@ -29,7 +29,7 @@ Usage:
29
  Options:
30
  --parallel-shards N Number of uploader shards. Default: 4
31
  --array-parallel N Optional Slurm array concurrency cap
32
- --partition NAME Slurm partition for upload jobs. Default: main-redhat
33
  --time HH:MM:SS Default: 24:00:00
34
  --cpus-per-task N Default: 2
35
  --mem SIZE Default: 8G
 
4
  ROOT_DIR="${ROOT_DIR:-/home/sf895/SignVerse-2M}"
5
  RUNTIME_ROOT="${RUNTIME_ROOT:-/home/sf895/SignVerse-2M-runtime}"
6
  SLURM_SCRIPT="${SLURM_SCRIPT:-$ROOT_DIR/slurm/process_upload_parallel_array.slurm}"
7
+ PARTITION="${PARTITION:-main}"
8
  TIME_LIMIT="${TIME_LIMIT:-24:00:00}"
9
  CPUS_PER_TASK="${CPUS_PER_TASK:-2}"
10
  MEMORY="${MEMORY:-8G}"
 
29
  Options:
30
  --parallel-shards N Number of uploader shards. Default: 4
31
  --array-parallel N Optional Slurm array concurrency cap
32
+ --partition NAME Slurm partition for upload jobs. Default: main
33
  --time HH:MM:SS Default: 24:00:00
34
  --cpus-per-task N Default: 2
35
  --mem SIZE Default: 8G
slurm/watch_submit_dwpose.slurm CHANGED
@@ -12,7 +12,7 @@ set -euo pipefail
12
 
13
  ROOT_DIR="${ROOT_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
14
  SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"
15
- GPU_PARTITIONS="${GPU_PARTITIONS:-gpu-redhat,gpu,cgpu}"
16
  GPU_ACCOUNT="${GPU_ACCOUNT:-}"
17
  SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-60}"
18
  SUBMIT_LIMIT="${SUBMIT_LIMIT:-2980}"
 
12
 
13
  ROOT_DIR="${ROOT_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
14
  SUBMIT_SCRIPT="${SUBMIT_SCRIPT:-$ROOT_DIR/slurm/submit_dwpose_slurm.sh}"
15
+ GPU_PARTITIONS="${GPU_PARTITIONS:-gpu,gpu-redhat,cgpu}"
16
  GPU_ACCOUNT="${GPU_ACCOUNT:-}"
17
  SCAN_INTERVAL_SECONDS="${SCAN_INTERVAL_SECONDS:-60}"
18
  SUBMIT_LIMIT="${SUBMIT_LIMIT:-2980}"
utils/draw_dw_lib.py CHANGED
@@ -14,12 +14,114 @@ from typing import List, Dict, Any, Optional, Tuple
14
 
15
  eps = 0.01
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def alpha_blend_color(color, alpha):
18
  """blend color according to point conf
19
  """
20
  return [int(c * alpha) for c in color]
21
 
22
- def draw_bodypose(canvas, candidate, subset, score, transparent=False):
23
  """Draw body pose on canvas
24
  Args:
25
  canvas: numpy array canvas to draw on
@@ -34,7 +136,7 @@ def draw_bodypose(canvas, candidate, subset, score, transparent=False):
34
  candidate = np.array(candidate)
35
  subset = np.array(subset)
36
 
37
- stickwidth = 4
38
 
39
  limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
40
  [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
@@ -82,11 +184,11 @@ def draw_bodypose(canvas, candidate, subset, score, transparent=False):
82
  color = colors[i][:-1] + [int(255 * conf)] # Adjust alpha based on confidence
83
  else:
84
  color = colors[i]
85
- cv2.circle(canvas, (int(x), int(y)), 4, color, thickness=-1)
86
 
87
  return canvas
88
 
89
- def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
90
  """Draw hand pose on canvas"""
91
  H, W, C = canvas.shape
92
 
@@ -105,10 +207,10 @@ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
105
  if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
106
  color = matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0])
107
  if transparent:
108
- color = np.append(color, score) # Add alpha channel
109
  else:
110
- color = color * score
111
- cv2.line(canvas, (x1, y1), (x2, y2), color * 255, thickness=2)
112
 
113
  for i, keypoint in enumerate(peaks):
114
  x, y = keypoint
@@ -116,13 +218,13 @@ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False):
116
  y = int(y * H)
117
  if x > eps and y > eps:
118
  if transparent:
119
- color = (0, 0, 0, scores[i]) # Black with alpha
120
  else:
121
- color = (0, 0, int(scores[i] * 255)) # Original color
122
- cv2.circle(canvas, (x, y), 4, color, thickness=-1)
123
  return canvas
124
 
125
- def draw_facepose(canvas, all_lmks, all_scores, transparent=False):
126
  """Draw face pose on canvas"""
127
  H, W, C = canvas.shape
128
  for lmks, scores in zip(all_lmks, all_scores):
@@ -136,10 +238,21 @@ def draw_facepose(canvas, all_lmks, all_scores, transparent=False):
136
  else:
137
  conf = int(score * 255)
138
  color = (conf, conf, conf) # Original grayscale
139
- cv2.circle(canvas, (x, y), 3, color, thickness=-1)
140
  return canvas
141
 
142
- def draw_pose(pose, H, W, include_body=True, include_hand=True, include_face=True, ref_w=2160, transparent=False):
 
 
 
 
 
 
 
 
 
 
 
143
  """vis dwpose outputs with optional transparent background
144
 
145
  Args:
@@ -175,31 +288,74 @@ def draw_pose(pose, H, W, include_body=True, include_hand=True, include_face=Tru
175
  subset = bodies['subset']
176
 
177
  if include_body:
178
- canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent)
 
 
 
 
 
 
 
 
179
 
180
  if include_hand:
181
- canvas = draw_handpose(canvas, hands, processed_data['hands_score'], transparent=transparent)
 
 
 
 
 
 
 
182
 
183
  if include_face:
184
- canvas = draw_facepose(canvas, faces, processed_data['faces_score'], transparent=transparent)
 
 
 
 
 
 
185
 
186
  else:
187
  # 兼容旧的数据格式 - 作为备选方案
188
  try:
189
- bodies = pose['bodies']
190
- faces = pose['faces']
191
- hands = pose['hands']
 
192
  candidate = bodies['candidate']
193
  subset = bodies['subset']
194
 
195
  if include_body:
196
- canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'], transparent=transparent)
 
 
 
 
 
 
 
 
197
 
198
  if include_hand:
199
- canvas = draw_handpose(canvas, hands, pose['hands_score'], transparent=transparent)
 
 
 
 
 
 
 
200
 
201
  if include_face:
202
- canvas = draw_facepose(canvas, faces, pose['faces_score'], transparent=transparent)
 
 
 
 
 
 
203
  except Exception as e:
204
  print(f"绘制旧格式数据失败: {str(e)}")
205
  # 返回空画布
@@ -270,14 +426,31 @@ def process_pose_data(pose_data: Dict[str, Any], height: int, width: int) -> Dic
270
  face_scores = np.array(all_face_scores) if all_face_scores else np.array([])
271
 
272
  else:
273
- # 兼容性处理 - 如果不是新格式,返回空数据
274
- bodies = np.array([])
275
- subset = np.array([[]])
276
- scores = np.array([[]])
277
- hands = np.array([])
278
- hand_scores = np.array([])
279
- faces = np.array([])
280
- face_scores = np.array([])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
  processed_data['bodies'] = {
283
  'candidate': bodies,
@@ -291,4 +464,4 @@ def process_pose_data(pose_data: Dict[str, Any], height: int, width: int) -> Dic
291
  processed_data['faces'] = faces
292
  processed_data['faces_score'] = face_scores
293
 
294
- return processed_data
 
14
 
15
  eps = 0.01
16
 
17
+ RENDER_STYLES = {
18
+ "bold": {"line_scale": 3.0, "point_scale": 2.0},
19
+ "thin": {"line_scale": 1.0, "point_scale": 1.0},
20
+ }
21
+
22
+
23
+ def get_render_style(style: str = "bold") -> Dict[str, float]:
24
+ """Return named DWPose rendering style parameters."""
25
+ if style not in RENDER_STYLES:
26
+ raise ValueError(f"Unknown render style '{style}'. Choose from: {sorted(RENDER_STYLES)}")
27
+ return RENDER_STYLES[style]
28
+
29
+
30
+ def filter_pose_by_confidence(
31
+ pose_data: Dict[str, Any],
32
+ conf_threshold: float = 0.6,
33
+ ) -> Dict[str, Any]:
34
+ """Filter low-confidence joints before rendering."""
35
+ filtered = {}
36
+ for key, value in pose_data.items():
37
+ if isinstance(value, np.ndarray):
38
+ filtered[key] = value.copy()
39
+ else:
40
+ filtered[key] = value
41
+
42
+ bodies = filtered.get("bodies")
43
+ body_scores = filtered.get("body_scores")
44
+ if bodies is not None:
45
+ bodies = np.array(bodies, copy=True)
46
+ min_valid = 1e-6
47
+ coord_mask = (bodies[:, 0] > min_valid) & (bodies[:, 1] > min_valid)
48
+
49
+ conf_mask = None
50
+ if body_scores is not None:
51
+ score_vec = np.asarray(body_scores).reshape(-1).astype(float)
52
+ conf_mask = score_vec < conf_threshold
53
+ if conf_mask.shape[0] < bodies.shape[0]:
54
+ conf_mask = np.pad(
55
+ conf_mask,
56
+ (0, bodies.shape[0] - conf_mask.shape[0]),
57
+ constant_values=False,
58
+ )
59
+ elif conf_mask.shape[0] > bodies.shape[0]:
60
+ conf_mask = conf_mask[: bodies.shape[0]]
61
+
62
+ valid_mask = coord_mask if conf_mask is None else coord_mask & (~conf_mask)
63
+ bodies[~valid_mask, :] = 0
64
+ filtered["bodies"] = bodies
65
+
66
+ if body_scores is not None:
67
+ subset = np.array(body_scores, copy=True)
68
+ if subset.ndim == 1:
69
+ subset = subset.reshape(1, -1)
70
+ else:
71
+ subset = np.arange(bodies.shape[0], dtype=float).reshape(1, -1)
72
+
73
+ if subset.shape[1] < bodies.shape[0]:
74
+ subset = np.pad(
75
+ subset,
76
+ ((0, 0), (0, bodies.shape[0] - subset.shape[1])),
77
+ constant_values=-1,
78
+ )
79
+ elif subset.shape[1] > bodies.shape[0]:
80
+ subset = subset[:, : bodies.shape[0]]
81
+
82
+ subset[:, ~valid_mask] = -1
83
+ filtered["body_scores"] = subset
84
+
85
+ hands = filtered.get("hands")
86
+ hand_scores = filtered.get("hands_scores")
87
+ if hands is not None and hand_scores is not None:
88
+ hands = np.array(hands, copy=True)
89
+ scores = np.array(hand_scores)
90
+ if hands.ndim == 3 and scores.ndim in (2, 3):
91
+ for h in range(hands.shape[0]):
92
+ cur_scores = scores[h] if scores.ndim == 2 else scores[h]
93
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
94
+ hands[h][mask, :] = 0
95
+ elif hands.ndim == 2 and scores.ndim in (1, 2):
96
+ cur_scores = scores if scores.ndim == 1 else scores.reshape(-1)
97
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
98
+ hands[mask, :] = 0
99
+ filtered["hands"] = hands
100
+
101
+ faces = filtered.get("faces")
102
+ face_scores = filtered.get("faces_scores")
103
+ if faces is not None and face_scores is not None:
104
+ faces = np.array(faces, copy=True)
105
+ scores = np.array(face_scores)
106
+ if faces.ndim == 3 and scores.ndim in (2, 3):
107
+ for f in range(faces.shape[0]):
108
+ cur_scores = scores[f] if scores.ndim == 2 else scores[f]
109
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
110
+ faces[f][mask, :] = 0
111
+ elif faces.ndim == 2 and scores.ndim in (1, 2):
112
+ cur_scores = scores if scores.ndim == 1 else scores.reshape(-1)
113
+ mask = (cur_scores < conf_threshold) | (cur_scores <= 0)
114
+ faces[mask, :] = 0
115
+ filtered["faces"] = faces
116
+
117
+ return filtered
118
+
119
  def alpha_blend_color(color, alpha):
120
  """blend color according to point conf
121
  """
122
  return [int(c * alpha) for c in color]
123
 
124
+ def draw_bodypose(canvas, candidate, subset, score, transparent=False, line_scale=1.0, point_scale=1.0):
125
  """Draw body pose on canvas
126
  Args:
127
  canvas: numpy array canvas to draw on
 
136
  candidate = np.array(candidate)
137
  subset = np.array(subset)
138
 
139
+ stickwidth = max(1, int(round(4 * line_scale)))
140
 
141
  limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10],
142
  [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17],
 
184
  color = colors[i][:-1] + [int(255 * conf)] # Adjust alpha based on confidence
185
  else:
186
  color = colors[i]
187
+ cv2.circle(canvas, (int(x), int(y)), max(1, int(round(4 * point_scale))), color, thickness=-1)
188
 
189
  return canvas
190
 
191
+ def draw_handpose(canvas, all_hand_peaks, all_hand_scores, transparent=False, line_scale=1.0, point_scale=1.0):
192
  """Draw hand pose on canvas"""
193
  H, W, C = canvas.shape
194
 
 
207
  if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
208
  color = matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0])
209
  if transparent:
210
+ color = tuple(int(c * 255) for c in color) + (int(score * 255),)
211
  else:
212
+ color = tuple(int(c * score * 255) for c in color)
213
+ cv2.line(canvas, (x1, y1), (x2, y2), color, thickness=max(1, int(round(2 * line_scale))))
214
 
215
  for i, keypoint in enumerate(peaks):
216
  x, y = keypoint
 
218
  y = int(y * H)
219
  if x > eps and y > eps:
220
  if transparent:
221
+ color = (0, 0, 0, int(scores[i] * 255))
222
  else:
223
+ color = (0, 0, int(scores[i] * 255))
224
+ cv2.circle(canvas, (x, y), max(1, int(round(4 * point_scale))), color, thickness=-1)
225
  return canvas
226
 
227
+ def draw_facepose(canvas, all_lmks, all_scores, transparent=False, point_scale=1.0):
228
  """Draw face pose on canvas"""
229
  H, W, C = canvas.shape
230
  for lmks, scores in zip(all_lmks, all_scores):
 
238
  else:
239
  conf = int(score * 255)
240
  color = (conf, conf, conf) # Original grayscale
241
+ cv2.circle(canvas, (x, y), max(1, int(round(3 * point_scale))), color, thickness=-1)
242
  return canvas
243
 
244
+ def draw_pose(
245
+ pose,
246
+ H,
247
+ W,
248
+ include_body=True,
249
+ include_hand=True,
250
+ include_face=True,
251
+ ref_w=2160,
252
+ transparent=False,
253
+ line_scale=1.0,
254
+ point_scale=1.0,
255
+ ):
256
  """vis dwpose outputs with optional transparent background
257
 
258
  Args:
 
288
  subset = bodies['subset']
289
 
290
  if include_body:
291
+ canvas = draw_bodypose(
292
+ canvas,
293
+ candidate,
294
+ subset,
295
+ score=bodies['score'],
296
+ transparent=transparent,
297
+ line_scale=line_scale,
298
+ point_scale=point_scale,
299
+ )
300
 
301
  if include_hand:
302
+ canvas = draw_handpose(
303
+ canvas,
304
+ hands,
305
+ processed_data['hands_score'],
306
+ transparent=transparent,
307
+ line_scale=line_scale,
308
+ point_scale=point_scale,
309
+ )
310
 
311
  if include_face:
312
+ canvas = draw_facepose(
313
+ canvas,
314
+ faces,
315
+ processed_data['faces_score'],
316
+ transparent=transparent,
317
+ point_scale=point_scale,
318
+ )
319
 
320
  else:
321
  # 兼容旧的数据格式 - 作为备选方案
322
  try:
323
+ processed_data = process_pose_data(pose, H, W)
324
+ bodies = processed_data['bodies']
325
+ faces = processed_data['faces']
326
+ hands = processed_data['hands']
327
  candidate = bodies['candidate']
328
  subset = bodies['subset']
329
 
330
  if include_body:
331
+ canvas = draw_bodypose(
332
+ canvas,
333
+ candidate,
334
+ subset,
335
+ score=bodies['score'],
336
+ transparent=transparent,
337
+ line_scale=line_scale,
338
+ point_scale=point_scale,
339
+ )
340
 
341
  if include_hand:
342
+ canvas = draw_handpose(
343
+ canvas,
344
+ hands,
345
+ processed_data['hands_score'],
346
+ transparent=transparent,
347
+ line_scale=line_scale,
348
+ point_scale=point_scale,
349
+ )
350
 
351
  if include_face:
352
+ canvas = draw_facepose(
353
+ canvas,
354
+ faces,
355
+ processed_data['faces_score'],
356
+ transparent=transparent,
357
+ point_scale=point_scale,
358
+ )
359
  except Exception as e:
360
  print(f"绘制旧格式数据失败: {str(e)}")
361
  # 返回空画布
 
426
  face_scores = np.array(all_face_scores) if all_face_scores else np.array([])
427
 
428
  else:
429
+ # 兼容旧的单人数据格式
430
+ raw_bodies = np.array(pose_data.get('bodies', []), dtype=np.float32)
431
+ raw_body_scores = np.array(pose_data.get('body_scores', []), dtype=np.float32)
432
+ raw_hands = np.array(pose_data.get('hands', []), dtype=np.float32)
433
+ raw_hand_scores = np.array(pose_data.get('hands_scores', []), dtype=np.float32)
434
+ raw_faces = np.array(pose_data.get('faces', []), dtype=np.float32)
435
+ raw_face_scores = np.array(pose_data.get('faces_scores', []), dtype=np.float32)
436
+
437
+ if raw_bodies.size > 0:
438
+ bodies = raw_bodies.reshape(-1, 2)
439
+ subset = np.arange(bodies.shape[0], dtype=np.int32)[None, :]
440
+
441
+ if raw_body_scores.size > 0:
442
+ scores = raw_body_scores.reshape(1, -1)
443
+ else:
444
+ scores = np.ones((1, bodies.shape[0]), dtype=np.float32)
445
+ else:
446
+ bodies = np.array([])
447
+ subset = np.array([[]])
448
+ scores = np.array([[]])
449
+
450
+ hands = raw_hands if raw_hands.size > 0 else np.array([])
451
+ hand_scores = raw_hand_scores if raw_hand_scores.size > 0 else np.array([])
452
+ faces = raw_faces if raw_faces.size > 0 else np.array([])
453
+ face_scores = raw_face_scores if raw_face_scores.size > 0 else np.array([])
454
 
455
  processed_data['bodies'] = {
456
  'candidate': bodies,
 
464
  processed_data['faces'] = faces
465
  processed_data['faces_score'] = face_scores
466
 
467
+ return processed_data
utils/raw_video_pool.py CHANGED
@@ -28,11 +28,7 @@ def collect_raw_videos(*dirs: Path | None) -> dict[str, Path]:
28
  if not directory.exists():
29
  continue
30
  for path in sorted(directory.iterdir()):
31
- try:
32
- is_file = path.is_file()
33
- except OSError:
34
- continue
35
- if not is_file or path.suffix.lower() not in VIDEO_EXTENSIONS:
36
  continue
37
  videos.setdefault(path.stem, path)
38
  return videos
@@ -43,14 +39,7 @@ def count_raw_videos(*dirs: Path | None) -> int:
43
 
44
 
45
  def sum_raw_video_sizes(*dirs: Path | None) -> int:
46
- total = 0
47
- for path in collect_raw_videos(*dirs).values():
48
- try:
49
- if path.exists():
50
- total += path.stat().st_size
51
- except OSError:
52
- continue
53
- return total
54
 
55
 
56
  def iter_raw_video_files(*dirs: Path | None) -> Iterator[Path]:
@@ -64,11 +53,7 @@ def find_video_file(video_id: str, *dirs: Path | None) -> Path | None:
64
  continue
65
  candidates = []
66
  for path in directory.glob(f"{video_id}.*"):
67
- try:
68
- is_file = path.is_file()
69
- except OSError:
70
- continue
71
- if is_file and path.suffix.lower() in VIDEO_EXTENSIONS:
72
  candidates.append(path)
73
  if candidates:
74
  return sorted(candidates)[0]
@@ -81,18 +66,11 @@ def iter_partial_download_files(video_id: str, *dirs: Path | None) -> Iterator[P
81
  if not directory.exists():
82
  continue
83
  for path in directory.glob(f"{video_id}*"):
84
- try:
85
- is_file = path.is_file()
86
- except OSError:
87
- continue
88
- if not is_file:
89
  continue
90
  suffixes = set(path.suffixes)
91
  if '.part' in suffixes or '.ytdl' in suffixes or path.suffix in {'.part', '.ytdl'}:
92
- try:
93
- resolved = path.resolve()
94
- except OSError:
95
- continue
96
  if resolved in seen:
97
  continue
98
  seen.add(resolved)
@@ -182,10 +160,5 @@ def remove_video_files(video_id: str, *dirs: Path | None) -> None:
182
  if not directory.exists():
183
  continue
184
  for path in directory.glob(f"{video_id}.*"):
185
- try:
186
- is_file = path.is_file()
187
- except OSError:
188
- continue
189
- if is_file and path.suffix.lower() in VIDEO_EXTENSIONS:
190
- with contextlib.suppress(OSError):
191
- path.unlink(missing_ok=True)
 
28
  if not directory.exists():
29
  continue
30
  for path in sorted(directory.iterdir()):
31
+ if not path.is_file() or path.suffix.lower() not in VIDEO_EXTENSIONS:
 
 
 
 
32
  continue
33
  videos.setdefault(path.stem, path)
34
  return videos
 
39
 
40
 
41
  def sum_raw_video_sizes(*dirs: Path | None) -> int:
42
+ return sum(path.stat().st_size for path in collect_raw_videos(*dirs).values() if path.exists())
 
 
 
 
 
 
 
43
 
44
 
45
  def iter_raw_video_files(*dirs: Path | None) -> Iterator[Path]:
 
53
  continue
54
  candidates = []
55
  for path in directory.glob(f"{video_id}.*"):
56
+ if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
 
 
 
 
57
  candidates.append(path)
58
  if candidates:
59
  return sorted(candidates)[0]
 
66
  if not directory.exists():
67
  continue
68
  for path in directory.glob(f"{video_id}*"):
69
+ if not path.is_file():
 
 
 
 
70
  continue
71
  suffixes = set(path.suffixes)
72
  if '.part' in suffixes or '.ytdl' in suffixes or path.suffix in {'.part', '.ytdl'}:
73
+ resolved = path.resolve()
 
 
 
74
  if resolved in seen:
75
  continue
76
  seen.add(resolved)
 
160
  if not directory.exists():
161
  continue
162
  for path in directory.glob(f"{video_id}.*"):
163
+ if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
164
+ path.unlink(missing_ok=True)