Download frame_extract.py from YYF111/checkpoint: direct link, hf CLI and curl.
- Browser
- Download file 31.5 kB
-
https://huggingface.co/datasets/YYF111/checkpoint/resolve/main/frame_extract.py
- Command line
-
hf download hf://datasets/YYF111/checkpoint/frame_extract.py
-
curl -L -o frame_extract.py https://huggingface.co/datasets/YYF111/checkpoint/resolve/main/frame_extract.py
31.5 kB
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """ | |
| 在 extract_frames_v3_hdfs 的基础上,补充**可视化进度**: | |
| - 默认:使用 tqdm 显示“已完成视频/总视频”的进度条(自动适配终端宽度)。 | |
| - 若未安装 tqdm 或非 TTY 环境:自动回退到单行文本进度(\r 覆盖更新)。 | |
| - 新增开关: | |
| - --plain-progress :强制使用纯文本进度(不依赖 tqdm) | |
| - --no-progress :完全关闭进度显示 | |
| - 每个视频完成后会打印一行简要结果(含后端、保存帧数、HDFS 上传/删除状态)。 | |
| 其它功能与 HDFS 上传逻辑保持一致。 | |
| """ | |
| import multiprocessing as mp | |
| import os | |
| import re | |
| import sys | |
| import csv | |
| import json | |
| import math | |
| import time | |
| import argparse | |
| import traceback | |
| import shutil | |
| import subprocess | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import List, Set, Tuple, Optional, Dict, Any | |
| from concurrent.futures import ProcessPoolExecutor, as_completed, TimeoutError | |
| # 可选依赖 | |
| try: | |
| import decord | |
| from decord import VideoReader, cpu, gpu | |
| _HAS_DECORD = True | |
| except Exception: | |
| _HAS_DECORD = False | |
| try: | |
| import cv2 | |
| _HAS_CV2 = True | |
| except Exception: | |
| _HAS_CV2 = False | |
| try: | |
| import av # PyAV | |
| _HAS_PYAV = True | |
| except Exception: | |
| _HAS_PYAV = False | |
| try: | |
| from PIL import Image | |
| _HAS_PIL = True | |
| except Exception: | |
| _HAS_PIL = False | |
| try: | |
| from tqdm import tqdm as _tqdm | |
| _HAS_TQDM = True | |
| except Exception: | |
| _HAS_TQDM = False | |
| # ========================= 路径回退解析 ========================= | |
| FALLBACK_PREFIXES = [ | |
| (Path("/mnt/bn/imagesim/yaoyifeng"), Path("/mnt/bn/chobits-wx/yyf")), | |
| ] | |
| def resolve_existing_video_path(original: Path) -> Tuple[Path, bool]: | |
| """ | |
| 若 original 存在则直接返回; | |
| 否则尝试按 FALLBACK_PREFIXES 把前缀替换为备选前缀并检查文件是否存在。 | |
| 返回:(用于打开的真实路径, 是否使用了回退路径) | |
| """ | |
| if original.exists(): | |
| return original, False | |
| for src_prefix, alt_prefix in FALLBACK_PREFIXES: | |
| try: | |
| rel = original.relative_to(src_prefix) | |
| except ValueError: | |
| continue | |
| candidate = alt_prefix / rel | |
| if candidate.exists(): | |
| print(f"[INFO] 找不到原视频,改用回退路径:{original} -> {candidate}", file=sys.stderr) | |
| return candidate, True | |
| # 未找到可用回退,仍返回 original(后续会正常报错/失败统计) | |
| return original, False | |
| # ========================= 通用工具 ========================= | |
| def read_unique_videos(jsonl_path: Path) -> List[Path]: | |
| vids: Set[Path] = set() | |
| with jsonl_path.open("r", encoding="utf-8") as f: | |
| for lineno, line in enumerate(f, 1): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| try: | |
| obj = json.loads(line) | |
| except json.JSONDecodeError as e: | |
| print(f"[WARN] 第 {lineno} 行 JSON 解析失败:{e}", file=sys.stderr) | |
| continue | |
| v = obj.get("video") | |
| if v: | |
| vids.add(Path(v)) | |
| return sorted(vids) | |
| def derive_output_dir(video_path: Path) -> Path: | |
| return video_path.parent / "images" / video_path.stem | |
| def list_existing_indices(out_dir: Path, ext: str) -> Set[int]: | |
| if not out_dir.exists(): | |
| return set() | |
| pat = re.compile(rf"^(\d+)\.{re.escape(ext)}$") | |
| indices: Set[int] = set() | |
| for p in out_dir.iterdir(): | |
| m = pat.match(p.name) | |
| if m: | |
| try: | |
| indices.add(int(m.group(1))) | |
| except ValueError: | |
| pass | |
| return indices | |
| def ensure_dir(p: Path): | |
| p.mkdir(parents=True, exist_ok=True) | |
| def save_image_array_bgr(img_bgr, out_path: Path, ext: str): | |
| if not _HAS_CV2 and not _HAS_PIL: | |
| raise RuntimeError("需要 opencv-python 或 pillow 用于保存图像") | |
| if _HAS_CV2: | |
| if ext == "jpg": | |
| cv2.imwrite(str(out_path), img_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), 95]) | |
| else: | |
| cv2.imwrite(str(out_path), img_bgr) | |
| else: | |
| import numpy as np | |
| img_rgb = img_bgr[:, :, ::-1] | |
| Image.fromarray(np.asarray(img_rgb)).save(str(out_path), quality=95 if ext == "jpg" else None) | |
| # ========================= 采样规划 ========================= | |
| def plan_indices_fixed_fps(src_fps: float, n_frames: int, fps_out: float) -> List[int]: | |
| if src_fps <= 0: | |
| src_fps = 30.0 | |
| duration = n_frames / src_fps | |
| if duration <= 0: | |
| return [] | |
| k_max = int(math.floor(duration * fps_out - 1e-9)) | |
| times = [k / fps_out for k in range(0, k_max + 1)] | |
| idxs = [min(int(round(t * src_fps)), n_frames - 1) for t in times] | |
| return sorted(set(idxs)) | |
| def plan_indices_uniform(n_frames: int, src_fps: float, fps_out: float) -> List[int]: | |
| if src_fps <= 0: | |
| src_fps = 30.0 | |
| duration = n_frames / src_fps | |
| N = max(1, int(math.floor(duration * fps_out + 1e-9))) | |
| if N == 1: | |
| return [0] | |
| return list(sorted(set(int(round(i * (n_frames - 1) / (N - 1))) for i in range(N)))) | |
| # ========================= decord 后端 ========================= | |
| def extract_with_decord(video_path: Path, out_dir: Path, ext: str, | |
| fps_out: float, mode: str, chunk: int, | |
| dev_id: Optional[int], use_gpu_decoding: bool, | |
| overwrite: bool) -> bool: | |
| if not _HAS_DECORD: | |
| print("[ERROR] 未安装 decord", file=sys.stderr) | |
| return False | |
| if not _HAS_CV2 and not _HAS_PIL: | |
| print("[ERROR] 保存图片需要 OpenCV 或 Pillow", file=sys.stderr) | |
| return False | |
| ensure_dir(out_dir) | |
| try: | |
| ctx = gpu(dev_id) if (use_gpu_decoding and dev_id is not None) else cpu(0) | |
| except Exception: | |
| ctx = cpu(0) | |
| vr = VideoReader(str(video_path), ctx=ctx) | |
| n_frames = len(vr) | |
| src_fps = float(vr.get_avg_fps()) if hasattr(vr, "get_avg_fps") else 0.0 | |
| if n_frames <= 0: | |
| print(f"[WARN] 视频无帧:{video_path}", file=sys.stderr) | |
| return False | |
| if mode == "fixed_fps": | |
| idxs = plan_indices_fixed_fps(src_fps, n_frames, fps_out) | |
| else: | |
| idxs = plan_indices_uniform(n_frames, src_fps, fps_out) | |
| existing = set() if overwrite else list_existing_indices(out_dir, ext) | |
| need_pairs: List[Tuple[int, int]] = [] | |
| for rank, fi in enumerate(idxs, start=1): | |
| if rank not in existing: | |
| need_pairs.append((rank, fi)) | |
| if not need_pairs: | |
| return True | |
| ok_any = False | |
| for i in range(0, len(need_pairs), chunk): | |
| sub = need_pairs[i:i+chunk] | |
| uniq_map = {} | |
| ordered_unique = [] | |
| for _, fi in sub: | |
| if fi not in uniq_map: | |
| uniq_map[fi] = len(uniq_map) | |
| ordered_unique.append(fi) | |
| batch = vr.get_batch(ordered_unique).asnumpy() # RGB | |
| for rank, fi in sub: | |
| bi = uniq_map[fi] | |
| frame_rgb = batch[bi] | |
| frame_bgr = frame_rgb[:, :, ::-1] | |
| out_path = out_dir / f"{rank}.{ext}" | |
| save_image_array_bgr(frame_bgr, out_path, ext) | |
| ok_any = True | |
| return ok_any | |
| # ========================= OpenCV 后端 ========================= | |
| def get_cv2_meta(cap) -> Tuple[float, int]: | |
| src_fps = float(cap.get(cv2.CAP_PROP_FPS)) if _HAS_CV2 else 30.0 | |
| if src_fps <= 0: | |
| src_fps = 30.0 | |
| n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) if _HAS_CV2 else 0 | |
| return src_fps, n_frames | |
| def read_frame_opencv(cap, frame_idx: int): | |
| cap.set(cv2.CAP_PROP_POS_FRAMES, frame_idx) | |
| ok, frame = cap.read() | |
| return frame if ok else None | |
| def stream_fixed_fps_opencv(cap, out_dir: Path, ext: str, fps_out: float, | |
| src_fps: float, overwrite: bool) -> bool: | |
| existing = set() if overwrite else list_existing_indices(out_dir, ext) | |
| ensure_dir(out_dir) | |
| next_rank = 1 if overwrite else ((max(existing) + 1) if existing else 1) | |
| next_t = (next_rank - 1) / fps_out | |
| step_t = 1.0 / fps_out | |
| frame_idx = 0 | |
| ok_any = False | |
| while True: | |
| ret, frame = cap.read() | |
| if not ret: | |
| break | |
| t = frame_idx / src_fps | |
| while t + 1e-9 >= next_t: | |
| out_path = out_dir / f"{next_rank}.{ext}" | |
| save_image_array_bgr(frame, out_path, ext) | |
| ok_any = True | |
| next_rank += 1 | |
| next_t += step_t | |
| frame_idx += 1 | |
| cap.release() | |
| return ok_any | |
| def extract_with_opencv(video_path: Path, out_dir: Path, ext: str, | |
| fps_out: float, mode: str, overwrite: bool) -> bool: | |
| if not _HAS_CV2: | |
| print("[ERROR] 未安装 OpenCV(cv2)", file=sys.stderr) | |
| return False | |
| ensure_dir(out_dir) | |
| cap = cv2.VideoCapture(str(video_path)) | |
| if not cap.isOpened(): | |
| print(f"[WARN] 无法打开视频:{video_path}", file=sys.stderr) | |
| return False | |
| src_fps, n_frames = get_cv2_meta(cap) | |
| if n_frames <= 0: | |
| if mode != "fixed_fps": | |
| print(f"[INFO] 无法读取总帧数,回退流式 fixed_fps:{video_path}") | |
| return stream_fixed_fps_opencv(cap, out_dir, ext, fps_out, src_fps, overwrite) | |
| if mode == "fixed_fps": | |
| idxs = plan_indices_fixed_fps(src_fps, n_frames, fps_out) | |
| else: | |
| idxs = plan_indices_uniform(n_frames, src_fps, fps_out) | |
| existing = set() if overwrite else list_existing_indices(out_dir, ext) | |
| ok_any = False | |
| for rank, fi in enumerate(idxs, start=1): | |
| if rank in existing: | |
| continue | |
| frame = read_frame_opencv(cap, fi) | |
| if frame is None: | |
| continue | |
| out_path = out_dir / f"{rank}.{ext}" | |
| save_image_array_bgr(frame, out_path, ext) | |
| ok_any = True | |
| cap.release() | |
| return ok_any | |
| # ========================= PyAV(av) 后端 ========================= | |
| def _pyav_guess_meta(vs) -> Tuple[float, int, float]: | |
| src_fps = 0.0 | |
| n_frames = -1 | |
| duration = -1.0 | |
| try: | |
| if vs.average_rate: | |
| src_fps = float(vs.average_rate) | |
| except Exception: | |
| pass | |
| try: | |
| nf = getattr(vs, "frames", None) | |
| if nf is None: | |
| nf = getattr(vs, "nb_frames", None) | |
| if nf is not None and int(nf) > 0: | |
| n_frames = int(nf) | |
| except Exception: | |
| pass | |
| try: | |
| if vs.duration is not None and vs.time_base is not None: | |
| duration = float(vs.duration * vs.time_base) | |
| except Exception: | |
| pass | |
| if n_frames < 0 and duration > 0 and src_fps > 0: | |
| n_frames = int(round(duration * src_fps)) | |
| return (src_fps if src_fps > 0 else 30.0, n_frames, duration) | |
| def _pyav_save_frame(frame, out_path: Path, ext: str): | |
| if _HAS_PIL: | |
| img = frame.to_image() | |
| img.save(str(out_path), quality=95 if ext == "jpg" else None) | |
| elif _HAS_CV2: | |
| arr_bgr = frame.to_ndarray(format="bgr24") | |
| save_image_array_bgr(arr_bgr, out_path, ext) | |
| else: | |
| raise RuntimeError("PyAV 保存需要 pillow 或 opencv-python 之一") | |
| def extract_with_pyav(video_path: Path, out_dir: Path, ext: str, | |
| fps_out: float, mode: str, overwrite: bool) -> bool: | |
| if not _HAS_PYAV: | |
| print("[ERROR] 未安装 PyAV(av)", file=sys.stderr) | |
| return False | |
| ensure_dir(out_dir) | |
| try: | |
| container = av.open(str(video_path), mode="r") | |
| except Exception as e: | |
| print(f"[WARN] av.open 失败:{video_path} -> {e}", file=sys.stderr) | |
| return False | |
| try: | |
| vs = next(s for s in container.streams if s.type == "video") | |
| except StopIteration: | |
| print(f"[WARN] 未找到视频流:{video_path}", file=sys.stderr) | |
| container.close() | |
| return False | |
| src_fps, n_frames, duration = _pyav_guess_meta(vs) | |
| existing = set() if overwrite else list_existing_indices(out_dir, ext) | |
| if mode == "fixed_fps": | |
| next_rank = 1 if overwrite else ((max(existing) + 1) if existing else 1) | |
| next_t = (next_rank - 1) / fps_out | |
| step_t = 1.0 / fps_out | |
| container.seek(0) | |
| ok_any = False | |
| for frame in container.decode(vs): | |
| if frame.pts is not None and vs.time_base is not None: | |
| t = float(frame.pts * vs.time_base) | |
| else: | |
| if not hasattr(extract_with_pyav, "_counter"): | |
| extract_with_pyav._counter = 0 | |
| t = extract_with_pyav._counter / src_fps | |
| extract_with_pyav._counter += 1 | |
| while t + 1e-9 >= next_t: | |
| out_path = out_dir / f"{next_rank}.{ext}" | |
| _pyav_save_frame(frame, out_path, ext) | |
| ok_any = True | |
| next_rank += 1 | |
| next_t += step_t | |
| container.close() | |
| return ok_any | |
| else: | |
| if n_frames < 0: | |
| total = 0 | |
| container.seek(0) | |
| for _ in container.decode(vs): | |
| total += 1 | |
| n_frames = total | |
| container.close() | |
| try: | |
| container = av.open(str(video_path), mode="r") | |
| vs = next(s for s in container.streams if s.type == "video") | |
| except Exception as e: | |
| print(f"[WARN] reopen after counting failed: {video_path} -> {e}", file=sys.stderr) | |
| return False | |
| if n_frames <= 0: | |
| container.close() | |
| print(f"[WARN] 不能确定总帧数:{video_path}", file=sys.stderr) | |
| return False | |
| idxs = plan_indices_uniform(n_frames, src_fps, fps_out) | |
| rank2idx = {rank: fi for rank, fi in enumerate(idxs, start=1)} | |
| todo_ranks = sorted(set(rank2idx.keys()) - existing) | |
| if not todo_ranks: | |
| container.close() | |
| return True | |
| need_indices = set(rank2idx[r] for r in todo_ranks) | |
| container.seek(0) | |
| ok_any = False | |
| for frame_idx, frame in enumerate(container.decode(vs)): | |
| if frame_idx in need_indices: | |
| for r, fi in list(rank2idx.items()): | |
| if fi == frame_idx and r in todo_ranks: | |
| out_path = out_dir / f"{r}.{ext}" | |
| _pyav_save_frame(frame, out_path, ext) | |
| ok_any = True | |
| todo_ranks.remove(r) | |
| del rank2idx[r] | |
| break | |
| if not todo_ranks: | |
| break | |
| container.close() | |
| return ok_any | |
| # ========================= HDFS 上传工具 ========================= | |
| def _run(cmd: List[str]) -> Tuple[int, str, str]: | |
| try: | |
| p = subprocess.run(cmd, capture_output=True, text=True) | |
| return p.returncode, p.stdout.strip(), p.stderr.strip() | |
| except FileNotFoundError as e: | |
| return 127, "", str(e) | |
| def _subpath_after_token(local_path: Path, token: str) -> Path: | |
| parts = list(local_path.parts) | |
| for i, seg in enumerate(parts): | |
| if seg == token: | |
| rest = parts[i+1:] | |
| return Path(*rest) if rest else Path(local_path.name) | |
| return Path(local_path.name) | |
| def upload_to_hdfs(local_video: Path, hdfs_base: str, preserve_token: str, force: bool) -> Tuple[bool, str, str]: | |
| if not hdfs_base: | |
| return False, "", "empty hdfs_base" | |
| hdfs_base_norm = hdfs_base.rstrip('/') | |
| subpath = _subpath_after_token(local_video, preserve_token) | |
| target_dir = f"{hdfs_base_norm}/{subpath.parent.as_posix()}" if subpath.parent.as_posix() != '.' else hdfs_base_norm | |
| target_full = f"{hdfs_base_norm}/{subpath.as_posix()}" | |
| rc, out, err = _run(["hdfs", "dfs", "-mkdir", "-p", target_dir]) | |
| if rc != 0: | |
| return False, target_full, f"mkdir failed: rc={rc}, err={err}" | |
| put_cmd = ["hdfs", "dfs", "-put"] + (["-f"] if force else []) + [str(local_video), target_full] | |
| rc, out, err = _run(put_cmd) | |
| if rc != 0: | |
| return False, target_full, f"put failed: rc={rc}, err={err}" | |
| rc, _, _ = _run(["hdfs", "dfs", "-test", "-e", target_full]) | |
| if rc != 0: | |
| return False, target_full, "hdfs -test not found file after put" | |
| return True, target_full, "" | |
| # ========================= 任务封装与并行 ========================= | |
| def backend_order(primary: str) -> List[str]: | |
| if primary == "decord": | |
| return ["decord", "pyav", "opencv"] | |
| if primary == "pyav": | |
| return ["pyav", "decord", "opencv"] | |
| if primary == "opencv": | |
| return ["opencv", "decord", "pyav"] | |
| return ["decord", "pyav", "opencv"] | |
| def mark_done(out_dir: Path, info: Dict[str, Any]): | |
| try: | |
| (out_dir / ".done").write_text(json.dumps(info, ensure_ascii=False, indent=2), encoding="utf-8") | |
| except Exception: | |
| pass | |
| def process_one_video(video_path: Path, fps: float, ext: str, primary_backend: str, | |
| mode: str, chunk: int, dev_id: Optional[int], use_gpu_decoding: bool, | |
| max_retries: int, overwrite: bool, clean: bool, | |
| hdfs_base: str, preserve_token: str, | |
| hdfs_force: bool, do_hdfs: bool, delete_local_after: bool) -> Dict[str, Any]: | |
| start = time.time() | |
| out_dir = derive_output_dir(video_path) | |
| if overwrite and clean and out_dir.exists(): | |
| shutil.rmtree(out_dir, ignore_errors=True) | |
| ensure_dir(out_dir) | |
| existing_before = len(list_existing_indices(out_dir, ext)) | |
| order = backend_order(primary_backend) | |
| used_backend = None | |
| error_msgs = [] | |
| tries = 0 | |
| for be in order: | |
| for attempt in range(max_retries + 1): | |
| tries += 1 | |
| try: | |
| if be == "decord": | |
| ok = extract_with_decord(video_path, out_dir, ext, fps, mode, chunk, dev_id, use_gpu_decoding, overwrite) | |
| elif be == "pyav": | |
| ok = extract_with_pyav(video_path, out_dir, ext, fps, mode, overwrite) | |
| else: | |
| ok = extract_with_opencv(video_path, out_dir, ext, fps, mode, overwrite) | |
| except Exception as e: | |
| ok = False | |
| error_msgs.append(f"{be} attempt#{attempt}: {e}\n{traceback.format_exc(limit=1)}") | |
| if ok: | |
| used_backend = be | |
| # print(video_path) | |
| break | |
| if used_backend is not None: | |
| break | |
| existing_after = len(list_existing_indices(out_dir, ext)) | |
| saved = max(0, existing_after - existing_before) | |
| info: Dict[str, Any] = { | |
| "video": str(video_path), | |
| "out_dir": str(out_dir), | |
| "saved": saved, | |
| "backend": used_backend or "", | |
| "mode": mode, | |
| "elapsed_sec": round(time.time() - start, 3), | |
| "error": "; ".join(error_msgs) if used_backend is None else "", | |
| "hdfs_base": hdfs_base, | |
| "hdfs_preserve_from": preserve_token, | |
| "hdfs_path": "", | |
| "hdfs_uploaded": False, | |
| "hdfs_error": "", | |
| "deleted_local": False, | |
| "delete_local_error": "", | |
| } | |
| if used_backend is not None: | |
| if do_hdfs and hdfs_base: | |
| uploaded, hdfs_full, err = upload_to_hdfs(video_path, hdfs_base, preserve_token, hdfs_force) | |
| # print(uploaded,err) | |
| info["hdfs_path"] = hdfs_full | |
| info["hdfs_uploaded"] = uploaded | |
| info["hdfs_error"] = err | |
| if uploaded and delete_local_after: | |
| try: | |
| os.remove(video_path) | |
| info["deleted_local"] = True | |
| mark_done(out_dir, info) | |
| except Exception as e: | |
| info["delete_local_error"] = str(e) | |
| return info | |
| class Job: | |
| idx: int | |
| video: str | |
| dev: Optional[int] | |
| def load_skiplist(path: str) -> Set[str]: | |
| if not path: | |
| return set() | |
| p = Path(path) | |
| if not p.exists(): | |
| return set() | |
| with p.open("r", encoding="utf-8") as f: | |
| return set(line.strip() for line in f if line.strip()) | |
| def append_skiplist(path: str, items: List[str]): | |
| if not path or not items: | |
| return | |
| with open(path, "a", encoding="utf-8") as f: | |
| for it in items: | |
| f.write(it + "\n") | |
| def write_report(path: str, rows: List[Dict[str, Any]]): | |
| if not path: | |
| return | |
| fields = [ | |
| "video", "out_dir", "saved", "backend", "mode", "elapsed_sec", "error", | |
| "hdfs_base", "hdfs_preserve_from", "hdfs_path", "hdfs_uploaded", "hdfs_error", | |
| "deleted_local", "delete_local_error", | |
| ] | |
| new_file = not Path(path).exists() | |
| with open(path, "a", newline="", encoding="utf-8") as f: | |
| w = csv.DictWriter(f, fieldnames=fields) | |
| if new_file: | |
| w.writeheader() | |
| for r in rows: | |
| w.writerow({k: r.get(k, "") for k in fields}) | |
| # -------- 进度封装 -------- | |
| class _PlainProgress: | |
| def __init__(self, total: int, desc: str = ""): | |
| self.total = max(1, int(total)) | |
| self.done = 0 | |
| self.desc = desc | |
| self._t0 = time.time() | |
| self._last_print = 0.0 | |
| self._print(0) | |
| def _print(self, done: int): | |
| pct = int(done * 100 / self.total) | |
| msg = f"\r{self.desc} {done}/{self.total} ({pct}%)" | |
| print(msg, end="", flush=True) | |
| def update(self, n: int = 1, postfix: str = ""): | |
| self.done += n | |
| now = time.time() | |
| if now - self._last_print >= 0.1 or self.done >= self.total: | |
| self._print(self.done) | |
| self._last_print = now | |
| def close(self): | |
| print() | |
| # ========================= 主流程 ========================= | |
| def main(): | |
| args = parse_args() | |
| jsonl_path = Path(args.jsonl) | |
| if not jsonl_path.exists(): | |
| print(f"[ERROR] 找不到 JSONL:{jsonl_path}", file=sys.stderr) | |
| sys.exit(1) | |
| if args.backend == "decord" and not _HAS_DECORD: | |
| print("[ERROR] 指定了 --backend decord 但未安装 decord", file=sys.stderr) | |
| sys.exit(2) | |
| if args.backend == "pyav" and not _HAS_PYAV and args.backend != "auto": | |
| print("[ERROR] 指定了 --backend pyav 但未安装 PyAV(av)", file=sys.stderr) | |
| sys.exit(3) | |
| if not _HAS_CV2 and not _HAS_PIL: | |
| print("[ERROR] 需要安装 opencv-python 或 pillow 以保存图片", file=sys.stderr) | |
| sys.exit(4) | |
| videos = read_unique_videos(jsonl_path) | |
| if not videos: | |
| print("[WARN] 未发现任何 video 字段。", file=sys.stderr) | |
| sys.exit(0) | |
| skip_in = load_skiplist(args.skiplist_in) | |
| if skip_in: | |
| videos = [v for v in videos if str(v) not in skip_in] | |
| filtered = [] | |
| for v in videos: | |
| out_dir = derive_output_dir(v) | |
| if (not args.overwrite) and (out_dir / ".done").exists(): | |
| continue | |
| filtered.append(v) | |
| videos = filtered | |
| if not videos: | |
| if not args.no_progress: | |
| print("[INFO] 无需处理:均已完成或在跳表中。") | |
| sys.exit(0) | |
| devices = [] | |
| if args.devices.strip(): | |
| try: | |
| devices = [int(x) for x in args.devices.split(',') if x.strip() != ''] | |
| except Exception: | |
| print("[WARN] --devices 解析失败,忽略。", file=sys.stderr) | |
| devices = [] | |
| jobs: List[Job] = [] | |
| for i, v in enumerate(videos): | |
| dev = devices[i % len(devices)] if devices else None | |
| jobs.append(Job(idx=i, video=str(v), dev=dev)) | |
| total = len(jobs) | |
| if not args.no_progress: | |
| print(f"[INFO] 去重后视频数量:{total},并发:{args.workers}") | |
| results: List[Dict[str, Any]] = [] | |
| failed_paths: List[str] = [] | |
| # 构建 futures | |
| # with ProcessPoolExecutor(max_workers=args.workers) as ex: | |
| with ProcessPoolExecutor(max_workers=args.workers, | |
| mp_context=mp.get_context("spawn")) as ex: | |
| fut2job = { | |
| ex.submit( | |
| _worker, | |
| job, | |
| args.fps, | |
| args.ext, | |
| args.backend, | |
| args.mode, | |
| args.chunk, | |
| args.use_gpu_decoding, | |
| args.max_retries, | |
| args.overwrite, | |
| args.clean, | |
| args.hdfs_base, | |
| args.preserve_from, | |
| args.hdfs_force, | |
| (not args.no_hdfs), | |
| args.delete_local_after_upload, | |
| ): job for job in jobs | |
| } | |
| if args.no_progress: | |
| iterator = as_completed(fut2job) | |
| progress = None | |
| elif (not args.plain_progress) and _HAS_TQDM and sys.stderr.isatty(): | |
| iterator = _tqdm(as_completed(fut2job), total=total, desc="并行处理中", dynamic_ncols=True) | |
| progress = None | |
| else: | |
| iterator = as_completed(fut2job) | |
| progress = _PlainProgress(total, desc="并行处理中") | |
| processed = 0 | |
| for fut in iterator: | |
| job = fut2job[fut] | |
| try: | |
| info = fut.result(timeout=args.timeout or None) | |
| except TimeoutError: | |
| info = { | |
| "video": job.video, | |
| "out_dir": str(derive_output_dir(Path(job.video))), | |
| "saved": 0, | |
| "backend": "", | |
| "mode": args.mode, | |
| "elapsed_sec": -1, | |
| "error": f"timeout>{args.timeout}s" if args.timeout else "timeout", | |
| "hdfs_base": args.hdfs_base, | |
| "hdfs_preserve_from": args.preserve_from, | |
| "hdfs_path": "", | |
| "hdfs_uploaded": False, | |
| "hdfs_error": "", | |
| "deleted_local": False, | |
| "delete_local_error": "", | |
| } | |
| except Exception as e: | |
| info = { | |
| "video": job.video, | |
| "out_dir": str(derive_output_dir(Path(job.video))), | |
| "saved": 0, | |
| "backend": "", | |
| "mode": args.mode, | |
| "elapsed_sec": -1, | |
| "error": f"exception: {e}", | |
| "hdfs_base": args.hdfs_base, | |
| "hdfs_preserve_from": args.preserve_from, | |
| "hdfs_path": "", | |
| "hdfs_uploaded": False, | |
| "hdfs_error": "", | |
| "deleted_local": False, | |
| "delete_local_error": "", | |
| } | |
| results.append(info) | |
| if not info.get("backend"): | |
| failed_paths.append(job.video) | |
| # 单行摘要(不影响进度条) | |
| if args.no_progress: | |
| pass | |
| else: | |
| summary = ( | |
| f"[DONE] idx={job.idx} saved={info['saved']} backend={info.get('backend','-')} " | |
| f"hdfs={'OK' if info.get('hdfs_uploaded') else 'NO'} " | |
| f"del={'YES' if info.get('deleted_local') else 'NO'}" | |
| ) | |
| # print(summary, file=sys.stderr, flush=True) | |
| processed += 1 | |
| if progress: | |
| progress.update(1) | |
| if progress: | |
| progress.close() | |
| append_skiplist(args.skiplist_out, failed_paths) | |
| write_report(args.report, results) | |
| ok = sum(1 for r in results if r.get("backend")) | |
| print(f"[SUMMARY] 成功 {ok} / {len(results)},失败 {len(results)-ok}") | |
| if failed_paths: | |
| print("[FAILED] 写入跳表:", args.skiplist_out or "(未指定)") | |
| # 为了复用原 worker 签名,这里在末尾定义 | |
| def _worker(job: 'Job', fps: float, ext: str, backend: str, mode: str, chunk: int, | |
| use_gpu_decoding: bool, max_retries: int, | |
| overwrite: bool, clean: bool, | |
| hdfs_base: str, preserve_token: str, | |
| hdfs_force: bool, do_hdfs: bool, delete_local_after: bool) -> Dict[str, Any]: | |
| return process_one_video( | |
| Path(job.video), fps, ext, backend, mode, chunk, | |
| job.dev, use_gpu_decoding, max_retries, | |
| overwrite, clean, | |
| hdfs_base, preserve_token, | |
| hdfs_force, do_hdfs, delete_local_after, | |
| ) | |
| # ========================= 配置与参数 ========================= | |
| def parse_args(): | |
| ap = argparse.ArgumentParser(description="从 JSONL 去重视频并按固定 FPS 抽帧(并行 + HDFS + 进度显示)") | |
| ap.add_argument("--jsonl", type=str, default="/mnt/bn/imagesim/yaoyifeng/dataset/LLaVA-Video-178K/merged_dataset.jsonl", help="JSONL 文件路径(每行含 'video' 字段)") | |
| ap.add_argument("--fps", type=float, default=4.0, help="目标采样 FPS,默认 4") | |
| ap.add_argument("--ext", choices=["jpg", "png"], default="jpg", help="输出图片格式,默认 jpg") | |
| ap.add_argument("--backend", choices=["auto", "decord", "pyav", "opencv"], default="auto", | |
| help="后端优先级:auto->decord->pyav->opencv") | |
| ap.add_argument("--mode", choices=["fixed_fps", "uniform"], default="uniform", | |
| help="fixed_fps:按时间步长;uniform:按总帧数等间距") | |
| ap.add_argument("--chunk", type=int, default=128, help="decord 批量读取块大小") | |
| # 覆盖 & 清理 | |
| ap.add_argument("--overwrite", action="store_true", help="覆盖已存在的帧并忽略 .done 标记") | |
| ap.add_argument("--clean", action="store_true", help="与 --overwrite 一起用:开跑前先删除输出目录,避免残留旧帧") | |
| # 并行 & 稳健性 | |
| ap.add_argument("--workers", type=int, default=max(1, 16), help="并发进程数") | |
| ap.add_argument("--devices", type=str, default="", help="逗号分隔的 GPU 序号,如 0,1;仅 decord 使用") | |
| ap.add_argument("--use-gpu-decoding", action="store_true", help="尝试在 decord 使用 GPU/NVDEC") | |
| ap.add_argument("--max-retries", type=int, default=3, help="单视频失败重试次数(含回退后端)") | |
| ap.add_argument("--timeout", type=int, default=0, help="单任务超时秒(0=不启用)") | |
| # 跳表 & 报告 | |
| ap.add_argument("--skiplist-in", type=str, default="", help="要跳过的视频路径列表文件(每行一个绝对路径)") | |
| ap.add_argument("--skiplist-out", type=str, default="fail_video.txt", help="将失败视频路径追加到该文件") | |
| ap.add_argument("--report", type=str, default="", help="运行结束导出报告 CSV") | |
| # HDFS 上传选项 | |
| ap.add_argument("--hdfs-base", type=str, default="dfs://harunava/home/byte_magellan_va/user/yaoyifeng/LLaVA-Video-178K", | |
| help="HDFS 目标根目录(将按子路径组织)") | |
| ap.add_argument("--preserve-from", type=str, default="LLaVA-Video-178K", | |
| help="在本地路径中找到该目录名后,其后的相对路径会被保留到 HDFS(未找到则仅用文件名)") | |
| ap.add_argument("--hdfs-force", action="store_true", default=True, help="使用 -put -f 强制覆盖(默认开启)") | |
| ap.add_argument("--no-hdfs", action="store_true", help="禁用 HDFS 上传(调试用)") | |
| ap.add_argument("--delete-local-after-upload", action="store_true", default=True, help="上传成功后删除本地原视频(默认开启)") | |
| # 进度显示选项 | |
| ap.add_argument("--plain-progress", action="store_true", help="强制使用纯文本进度而不是 tqdm") | |
| ap.add_argument("--no-progress", action="store_true", help="关闭所有进度输出") | |
| return ap.parse_args() | |
| if __name__ == "__main__": | |
| main() | |