#!/usr/bin/env python3 """多源多进程并行下载与高吞吐流式解压官方帧包:预建目录+多线程异步直写+移除逐帧rename/statvfs/JSON重写风暴。""" import argparse import collections from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed import fcntl import hashlib import io import json import os from pathlib import Path import re import shutil import subprocess import tarfile from download_assets import ROOT, atomic, download, safe_flock from prepare_eval_media import Concatenated def _write_jpeg_fast(dest: Path, data: bytes, need_sha: bool, archive_member: str): with dest.open('wb') as out: out.write(data) if need_sha: return dict( path=str(dest.relative_to(ROOT)), bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), archive_member=archive_member, ) return None def process_one_source(source: str, items: list, selected: dict, io_threads: int = 32, dl_threads: int = 4, delete_tar: bool = True): marker = ROOT / 'provenance' / ('training_media_extracted_' + source + '.json') source_inv_path = ROOT / 'provenance' / f'training_media_inventory.{source}.json' if marker.exists(): status = json.loads(marker.read_text()) if not status.get('missing') and status['found_videos'] == status['selected_videos']: inv = json.loads(source_inv_path.read_text()) if source_inv_path.exists() else {} return source, status, inv print(json.dumps({'source': source, 'stage': 'downloading_archives', 'parts': len(items)}), flush=True) with ThreadPoolExecutor(max_workers=min(dl_threads, max(1, len(items)))) as dl_pool: paths = list(dl_pool.map(lambda it: Path(download(it)), items)) # 一次性预先创建该source下所有目标视频目录,并扫描已存在的帧,彻底消除逐张JPEG的mkdir与exists()系统调用风暴 existing_frames = {} for video, meta in selected.items(): vdir = ROOT / 'data/training_frames' / video vdir.mkdir(parents=True, exist_ok=True) try: existing = { int(entry.name.split('.', 1)[0]): entry.stat().st_size for entry in os.scandir(vdir) if entry.is_file() and entry.name.lower().endswith(('.jpg', '.jpeg', '.png')) and entry.name.split('.', 1)[0].isdigit() } except OSError: existing = {} existing_frames[video] = existing seen = collections.Counter() local_inventory = {} for video, ex in existing_frames.items(): valid_ex = {idx: sz for idx, sz in ex.items() if idx <= selected[video]['max_query_time']} if valid_ex: seen[video] = len(valid_ex) local_inventory[video] = dict( files=len(valid_ex), storage_bytes=sum(valid_ex.values()), min_index=min(valid_ex), max_index=max(valid_ex), source=source, samples=[], ) start_members = [] pending_futures = collections.deque() max_in_flight = io_threads * 4 # 优先使用系统多核 pigz 或 gzip 子进程管道解压,把解压与Python tar解析解耦到不同CPU核 decomp_prog = 'pigz' if shutil.which('pigz') else ('gzip' if shutil.which('gzip') else None) def _consume_archive(archive): with ThreadPoolExecutor(max_workers=io_threads) as writer_pool: total_written = 0 for member in archive: if not member.isfile(): continue if len(start_members) < 10: start_members.append(member.name) if not member.name.lower().endswith(('.jpg', '.jpeg', '.png')): continue name = Path(member.name) parts = name.parts exact = '/'.join(parts[-3:-1]) if len(parts) >= 3 else '' if exact in selected: video = exact else: candidate = source + '/' + name.parent.name if candidate in selected: video = candidate else: continue stem = name.stem if not stem.isdigit(): continue index = int(stem) if index > selected[video]['max_query_time']: continue if index in existing_frames[video]: continue fobj = archive.extractfile(member) if fobj is None: continue data = fobj.read() dest = ROOT / 'data/training_frames' / video / name.name value = local_inventory.setdefault( video, dict(files=0, storage_bytes=0, min_index=index, max_index=index, source=source, samples=[]), ) value['files'] += 1 value['storage_bytes'] += len(data) value['min_index'] = min(value['min_index'], index) value['max_index'] = max(value['max_index'], index) need_sha = len(value['samples']) < 3 fut = writer_pool.submit(_write_jpeg_fast, dest, data, need_sha, member.name) pending_futures.append((video, fut)) seen[video] += 1 total_written += 1 while len(pending_futures) >= max_in_flight: v_done, f_done = pending_futures.popleft() sample_info = f_done.result() if sample_info is not None and len(local_inventory[v_done]['samples']) < 3: local_inventory[v_done]['samples'].append(sample_info) if total_written % 10000 == 0: print( json.dumps({'source': source, 'written_frames': total_written, 'videos_seen': len(seen)}, ensure_ascii=False), flush=True, ) while pending_futures: v_done, f_done = pending_futures.popleft() sample_info = f_done.result() if sample_info is not None and len(local_inventory[v_done]['samples']) < 3: local_inventory[v_done]['samples'].append(sample_info) if decomp_prog is not None: cat_proc = subprocess.Popen(['cat', *[str(p) for p in paths]], stdout=subprocess.PIPE, bufsize=16 * 1024**2) dec_cmd = [decomp_prog, '-dc'] if decomp_prog == 'gzip' else [decomp_prog, '-dc', '-p', '4'] dec_proc = subprocess.Popen(dec_cmd, stdin=cat_proc.stdout, stdout=subprocess.PIPE, bufsize=16 * 1024**2) cat_proc.stdout.close() with tarfile.open(fileobj=dec_proc.stdout, mode='r|') as archive: _consume_archive(archive) dec_proc.stdout.close() dec_proc.wait() cat_proc.wait() else: with io.BufferedReader(Concatenated(paths), buffer_size=16 * 1024**2) as stream: with tarfile.open(fileobj=stream, mode='r|gz') as archive: _consume_archive(archive) missing = sorted(set(selected) - set(seen)) atomic(source_inv_path, local_inventory) audit_path = ROOT / 'provenance/training_selection_audit.json' cand_sha = json.loads(audit_path.read_text())['candidate_sha256'] if audit_path.exists() else '' status = dict( source=source, selected_videos=len(selected), found_videos=len(seen), complete=not missing, missing=missing, first_archive_members=start_members, matched_frames=sum(seen.values()), archives=[i['file'] for i in items], candidate_manifest_sha256=cand_sha, ) if missing: atomic(marker.with_name(marker.name + '.failed'), status) raise RuntimeError('冻结候选视频在官方包中缺失,保留压缩包以供诊断:' + str(missing)) atomic(marker, status) if delete_tar: for path in paths: path.unlink(missing_ok=True) print(json.dumps({'source': source, 'status': 'extracted', 'videos': len(seen), 'frames': sum(seen.values())}), flush=True) return source, status, local_inventory def main(): parser = argparse.ArgumentParser() parser.add_argument('--source', default=None, help='仅处理指定source;默认多进程并行处理全部7个source') parser.add_argument('--parallel-sources', type=int, default=int(os.environ.get('CGVM_EXTRACT_SOURCES', '7')), help='同时并行解压的source进程数(配合pigz与多线程I/O吃满24核CPU)') parser.add_argument('--io-threads', type=int, default=int(os.environ.get('CGVM_EXTRACT_IO_THREADS', '32')), help='每个source内部并发写小JPEG文件的I/O线程数,隐藏Bucket/云盘高延迟') parser.add_argument('--scratch-dir', default=os.environ.get('CGVM_SCRATCH_DIR', ''), help='可选本地高速盘路径(如 /dev/shm/cgvm_frames 或 /tmp/cgvm_frames),自动软链 data/training_frames 避免向远程Bucket写百万小JPEG') parser.add_argument('--keep-tar', action='store_true') args = parser.parse_args() frames_root = ROOT / 'data/training_frames' if args.scratch_dir: scratch_path = Path(args.scratch_dir).resolve() scratch_path.mkdir(parents=True, exist_ok=True) if not frames_root.exists(): frames_root.parent.mkdir(parents=True, exist_ok=True) frames_root.symlink_to(scratch_path) print(json.dumps({'stage': 'symlinked_training_frames_to_fast_scratch', 'target': str(scratch_path)}), flush=True) videos = json.loads((ROOT / 'manifests/training_videos.candidate.json').read_text()) plan = json.loads((ROOT / 'manifests/download_training_media.json').read_text()) inventory_path = ROOT / 'provenance/training_media_inventory.json' inventory = json.loads(inventory_path.read_text()) if inventory_path.exists() else {} grouped = collections.defaultdict(list) for item in plan: if args.source and item['training_source'] != args.source: continue grouped[item['training_source']].append(item) tasks = [] for source, items in sorted(grouped.items(), key=lambda pair: sum(i['size'] for i in pair[1])): selected = {video: meta for video, meta in videos.items() if video.startswith(source + '/')} tasks.append((source, items, selected)) if len(tasks) <= 1 or args.parallel_sources <= 1: for source, items, selected in tasks: _, _, local_inv = process_one_source( source, items, selected, io_threads=args.io_threads, delete_tar=not args.keep_tar ) inventory.update(local_inv) atomic(inventory_path, inventory) else: with ProcessPoolExecutor(max_workers=min(args.parallel_sources, len(tasks))) as pool: futures = { pool.submit( process_one_source, source, items, selected, args.io_threads, 4, not args.keep_tar ): source for source, items, selected in tasks } for fut in as_completed(futures): source, _, local_inv = fut.result() inventory.update(local_inv) atomic(inventory_path, inventory) if __name__ == '__main__': (ROOT / 'coordination').mkdir(parents=True, exist_ok=True) with (ROOT / 'coordination/training_media.lock').open('w') as lock: safe_flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) lock.write(str(os.getpid())) lock.flush() main()