|
| 1 | +from typing import List, Dict, Union |
| 2 | +import numpy as np |
| 3 | +import json |
| 4 | +import cv2 |
| 5 | + |
| 6 | +from ns_vfs.dataloader._base import DatasetLoader |
| 7 | + |
| 8 | +class LongVideoBench(DatasetLoader): |
| 9 | + def _parse_timestamp(self, ts: str) -> float: |
| 10 | + """ |
| 11 | + Parse a timestamp like "HH:MM:SS.mmm" into total seconds as float. |
| 12 | + """ |
| 13 | + h, m, s = ts.split(':') |
| 14 | + return int(h) * 3600 + int(m) * 60 + float(s) |
| 15 | + |
| 16 | + def load_all(self, sample_fps: int = 2, chunk_size: int = 10) -> List[Dict[str, Union[List[np.ndarray], None]]]: |
| 17 | + """ |
| 18 | + Load a video and subtitles, sample at `sample_fps` frames/sec, group every |
| 19 | + `chunk_size` frames into one dict, and attach subtitles overlapping each chunk. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + List of dicts of the form: |
| 23 | + [ |
| 24 | + {'frames': [f1, f2, ..., f10], 'subtitle': None}, |
| 25 | + {'frames': [f11, ..., f20], 'subtitle': "some text"}, |
| 26 | + ... |
| 27 | + ] |
| 28 | + """ |
| 29 | + # --- 1) Load and parse subtitles --- |
| 30 | + with open(self.subtitle_path, 'r', encoding='utf-8') as f: |
| 31 | + subs = json.load(f) |
| 32 | + # convert each to (start_sec, line) |
| 33 | + subtitles = [ |
| 34 | + (self._parse_timestamp(entry['start']), entry['line']) |
| 35 | + for entry in subs |
| 36 | + ] |
| 37 | + |
| 38 | + # --- 2) Open video and get duration --- |
| 39 | + cap = cv2.VideoCapture(self.video_path) |
| 40 | + if not cap.isOpened(): |
| 41 | + raise IOError(f"Cannot open video: {self.video_path}") |
| 42 | + total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) |
| 43 | + vid_fps = cap.get(cv2.CAP_PROP_FPS) |
| 44 | + duration_sec = total_frames / vid_fps |
| 45 | + |
| 46 | + # --- 3) Sample frames at regular intervals --- |
| 47 | + interval = 1.0 / sample_fps |
| 48 | + timestamps = np.arange(0, duration_sec, interval) |
| 49 | + |
| 50 | + sampled = [] |
| 51 | + for t in timestamps: |
| 52 | + cap.set(cv2.CAP_PROP_POS_MSEC, t * 1000) |
| 53 | + ret, frame = cap.read() |
| 54 | + if not ret: |
| 55 | + break |
| 56 | + sampled.append((t, frame.copy())) |
| 57 | + cap.release() |
| 58 | + |
| 59 | + chunks: List[Dict[str, Union[List[np.ndarray], None]]] = [] |
| 60 | + for i in range(0, len(sampled), chunk_size): |
| 61 | + chunk = sampled[i:i + chunk_size] |
| 62 | + if not chunk: |
| 63 | + continue |
| 64 | + |
| 65 | + frames = [f for (_, f) in chunk] |
| 66 | + |
| 67 | + t_start = chunk[0][0] |
| 68 | + t_end = chunk[-1][0] |
| 69 | + |
| 70 | + lines = [line for (ts, line) in subtitles if t_start <= ts <= t_end] |
| 71 | + subtitle_text = " ".join(lines) if lines else None |
| 72 | + |
| 73 | + chunks.append({ |
| 74 | + 'frames': frames, |
| 75 | + 'subtitle': subtitle_text |
| 76 | + }) |
| 77 | + |
| 78 | + return chunks |
0 commit comments