| |
| """ |
| Lab 自建数据集预处理:将 features/lab 下的 mp4 + text.json 转为 QVHighlights 风格标注, |
| 并提取 CLIP 视频特征与 LLaMA 文本特征,便于用 FlashVTG 做实验。 |
| |
| 目录约定: |
| - features/lab/*.mp4 原始视频(如 1.mp4, 2.mp4, 3.mp4) |
| - features/lab/text.json 每行一个样本:{"textN": "query", "gt:s1,s2,..."},gt 单位为秒 |
| - data/lab_val.jsonl 输出:QV 风格标注(qid, query, duration, vid, relevant_windows 等) |
| - features/lab/clip_features CLIP 视频特征({vid}.npz, key "features", shape (T, 768)) |
| - features/lab/llama_text_feature LLaMA 文本特征(qid{qid}.npz, key "last_hidden_state") |
| |
| 用法: |
| # 仅生成标注(并获取视频时长) |
| python scripts/prepare_lab_dataset.py --lab_dir features/lab --out_jsonl data/lab_val.jsonl |
| |
| # 生成标注 + 提取 CLIP + 提取 LLaMA(需 GPU) |
| python scripts/prepare_lab_dataset.py --lab_dir features/lab --out_jsonl data/lab_val.jsonl --extract_clip --extract_llama |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import re |
| from pathlib import Path |
|
|
| import numpy as np |
|
|
|
|
| def get_video_duration_sec(video_path: str) -> float: |
| """获取视频时长(秒)。优先 decord,否则 opencv。""" |
| try: |
| from decord import VideoReader, cpu |
| vr = VideoReader(video_path, ctx=cpu(0)) |
| n = len(vr) |
| fps = vr.get_avg_fps() |
| if fps and fps > 0: |
| return n / fps |
| return max(0.0, n / 30.0) |
| except Exception: |
| pass |
| try: |
| import cv2 |
| cap = cv2.VideoCapture(video_path) |
| n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 |
| cap.release() |
| return n / fps if fps > 0 else 0.0 |
| except Exception: |
| return 0.0 |
|
|
|
|
| def parse_text_json(lab_dir: str) -> list[dict]: |
| """ |
| 解析 features/lab/text.json。 |
| 每行格式:{"text1": "query text", "gt:9,10,11"} 或 {"text1": "query", "gt": "9,10,11"} |
| 返回:[{"vid": "1", "query": "...", "gt_seconds": [9,10,11]}, ...] |
| """ |
| path = Path(lab_dir) / "text.json" |
| if not path.exists(): |
| raise FileNotFoundError(f"Not found: {path}") |
|
|
| samples = [] |
| with open(path, "r", encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| |
| if '"gt:' in line: |
| line = re.sub(r'"gt:([^"]*?)"\s*}', r'"gt": "\1"}', line) |
| try: |
| d = json.loads(line) |
| except json.JSONDecodeError: |
| continue |
| |
| query = None |
| vid = None |
| for k, v in d.items(): |
| if k.startswith("text") and isinstance(v, str): |
| num = k.replace("text", "").strip() |
| vid = num if num else "1" |
| query = v |
| break |
| if query is None: |
| continue |
| |
| gt_raw = d.get("gt", "") |
| if isinstance(gt_raw, list): |
| gt_seconds = [float(x) for x in gt_raw] |
| else: |
| gt_seconds = [float(x.strip()) for x in str(gt_raw).split(",") if x.strip()] |
| if not gt_seconds: |
| continue |
| samples.append({"vid": vid, "query": query, "gt_seconds": gt_seconds}) |
| return samples |
|
|
|
|
| def seconds_to_relevant_windows(gt_seconds: list[float]) -> list[list[float]]: |
| """将 gt 秒数列表转为 QV 的 relevant_windows [[start, end], ...]。""" |
| if not gt_seconds: |
| return [] |
| gt_seconds = sorted(gt_seconds) |
| return [[min(gt_seconds), max(gt_seconds)]] |
|
|
|
|
| def seconds_to_clip_ids(gt_seconds: list[float], clip_length: float = 2.0) -> list[int]: |
| """与 QV 一致:每 clip_length 秒一个 clip,返回与 gt 重叠的 clip 索引。""" |
| if not gt_seconds: |
| return [] |
| t_min, t_max = min(gt_seconds), max(gt_seconds) |
| id_min = max(0, int(t_min / clip_length)) |
| id_max = int(t_max / clip_length) |
| return list(range(id_min, id_max + 1)) |
|
|
|
|
| def build_lab_jsonl( |
| lab_dir: str, |
| out_jsonl: str, |
| clip_length: float = 2.0, |
| ) -> list[dict]: |
| """ |
| 根据 text.json 和 lab 下 mp4 生成 QV 风格 jsonl。 |
| 返回写入的每条记录列表(便于后续提取特征时用)。 |
| """ |
| lab_path = Path(lab_dir) |
| samples = parse_text_json(lab_dir) |
| if not samples: |
| raise ValueError("text.json 中未解析到有效样本") |
|
|
| records = [] |
| for idx, s in enumerate(samples): |
| vid = s["vid"] |
| mp4 = lab_path / f"{vid}.mp4" |
| if not mp4.exists(): |
| |
| if not (lab_path / f"{vid}.mp4").exists(): |
| raise FileNotFoundError(f"Video not found: {mp4}") |
| duration = get_video_duration_sec(str(mp4)) |
| if duration <= 0: |
| duration = 30.0 |
|
|
| relevant_windows = seconds_to_relevant_windows(s["gt_seconds"]) |
| relevant_clip_ids = seconds_to_clip_ids(s["gt_seconds"], clip_length) |
| |
| saliency_scores = [[1, 1, 1]] * len(relevant_clip_ids) if relevant_clip_ids else [[1, 1, 1]] |
|
|
| qid = idx + 1 |
| rec = { |
| "qid": qid, |
| "query": s["query"], |
| "duration": round(duration, 2), |
| "vid": vid, |
| "relevant_clip_ids": relevant_clip_ids, |
| "saliency_scores": saliency_scores, |
| "relevant_windows": relevant_windows, |
| } |
| records.append(rec) |
|
|
| os.makedirs(os.path.dirname(os.path.abspath(out_jsonl)) or ".", exist_ok=True) |
| with open(out_jsonl, "w", encoding="utf-8") as f: |
| for rec in records: |
| f.write(json.dumps(rec, ensure_ascii=False) + "\n") |
| print(f"Wrote {len(records)} samples to {out_jsonl}") |
| return records |
|
|
|
|
| def main(): |
| import sys |
| import importlib.util |
|
|
| parser = argparse.ArgumentParser(description="Lab dataset: build QV-style jsonl + optional CLIP/LLaMA extraction") |
| parser.add_argument("--lab_dir", default="features/lab", help="Directory with mp4 and text.json") |
| parser.add_argument("--out_jsonl", default="data/lab_val.jsonl", help="Output QV-style jsonl path") |
| parser.add_argument("--clip_length", type=float, default=2.0, help="Seconds per clip (QV default 2)") |
| parser.add_argument("--extract_clip", action="store_true", help="Extract CLIP video features into features/lab/clip_features") |
| parser.add_argument("--extract_llama", action="store_true", help="Extract LLaMA text features into features/lab/llama_text_feature") |
| try: |
| import torch |
| device_default = "cuda" if torch.cuda.is_available() else "cpu" |
| except Exception: |
| device_default = "cpu" |
| parser.add_argument("--device", default=device_default) |
| args = parser.parse_args() |
|
|
| lab_dir = os.path.abspath(args.lab_dir) |
| out_jsonl = os.path.abspath(args.out_jsonl) |
| script_dir = os.path.dirname(os.path.abspath(__file__)) |
| project_root = os.path.dirname(script_dir) |
| if project_root not in sys.path: |
| sys.path.insert(0, project_root) |
|
|
| |
| build_lab_jsonl(lab_dir, out_jsonl, clip_length=args.clip_length) |
|
|
| |
| if args.extract_clip: |
| clip_out = os.path.join(lab_dir, "clip_features") |
| try: |
| spec = importlib.util.spec_from_file_location( |
| "extract_clip_mod", |
| os.path.join(script_dir, "extract_vidstg_clip_features.py"), |
| ) |
| mod = importlib.util.module_from_spec(spec) |
| spec.loader.exec_module(mod) |
| extract_clip_features = mod.extract_clip_features |
| import open_clip |
| lab_path = Path(lab_dir) |
| mp4s = sorted(lab_path.glob("*.mp4")) |
| model, _, preprocess = open_clip.create_model_and_transforms("ViT-L-14", pretrained="openai") |
| model = model.to(args.device).eval() |
| os.makedirs(clip_out, exist_ok=True) |
| for mp4 in mp4s: |
| vid = mp4.stem |
| out_path = os.path.join(clip_out, f"{vid}.npz") |
| if os.path.exists(out_path): |
| print(f"Skip CLIP {vid} (exists)") |
| continue |
| feats = extract_clip_features(str(mp4), model, preprocess, args.device, sample_fps=0.5, batch_size=8) |
| if feats.ndim == 1: |
| feats = feats[None, :] |
| np.savez_compressed(out_path, features=feats.astype(np.float32)) |
| print(f"CLIP {vid} -> {feats.shape[0]} frames") |
| except Exception as e: |
| print("CLIP extraction failed:", e) |
|
|
| |
| if args.extract_llama: |
| llama_out = os.path.join(lab_dir, "llama_text_feature") |
| try: |
| spec = importlib.util.spec_from_file_location( |
| "extract_llama_mod", |
| os.path.join(script_dir, "extract_vidstg_llama_features.py"), |
| ) |
| mod = importlib.util.module_from_spec(spec) |
| spec.loader.exec_module(mod) |
| extract_llama_features = mod.extract_llama_features |
| from transformers import AutoModelForCausalLM, AutoTokenizer |
| import torch |
| qid2query = {} |
| with open(out_jsonl) as f: |
| for line in f: |
| d = json.loads(line) |
| qid2query[d["qid"]] = d["query"] |
| tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b", trust_remote_code=True) |
| model = AutoModelForCausalLM.from_pretrained( |
| "openlm-research/open_llama_7b", |
| torch_dtype=torch.float32, |
| device_map="auto" if args.device == "cuda" else None, |
| trust_remote_code=True, |
| ) |
| model.eval() |
| os.makedirs(llama_out, exist_ok=True) |
| for qid, query in qid2query.items(): |
| out_path = os.path.join(llama_out, f"qid{qid}.npz") |
| if os.path.exists(out_path): |
| print(f"Skip LLaMA qid{qid} (exists)") |
| continue |
| feats = extract_llama_features(model, tokenizer, query, args.device, max_length=40) |
| np.savez_compressed(out_path, last_hidden_state=feats.astype(np.float32)) |
| print(f"LLaMA qid{qid} -> {feats.shape}") |
| except Exception as e: |
| print("LLaMA extraction failed:", e) |
|
|
| print("Done. Use data/lab_val.jsonl and features/lab/clip_features, features/lab/llama_text_feature for inference.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|