#!/usr/bin/env python3 # SPDX-License-Identifier: Apache-2.0 """Recreate the candidate single-exercise clips used by FitAQA. This standalone implementation follows the public QEVD annotation layout and the preprocessing procedure described by FitAQA. The official Qualcomm FitCoach loader was consulted to understand the source annotation format: https://github.com/Qualcomm-AI-research/FitCoach """ from __future__ import annotations import argparse import json import shutil import subprocess from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Sequence import numpy as np DEFAULT_SPLITS = ( "QEVD-FIT-COACH", "QEVD-FIT-COACH-Benchmark", "QEVD-FIT-COACH-Competition", ) @dataclass(frozen=True) class FeedbackSpan: text: str start_frame: int end_frame: int @dataclass(frozen=True) class Segment: dataset: str output_name: str source_video: str source_timestamps: str exercise_name: str start_frame: int end_frame: int start_seconds: float end_seconds: float fps: float feedback_count: int def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--input-root", type=Path, required=True, help="Directory containing the extracted QEVD split directories.", ) parser.add_argument( "--output-root", type=Path, required=True, help="Directory in which split-specific clips and manifests are written.", ) parser.add_argument( "--splits", nargs="+", choices=DEFAULT_SPLITS, default=list(DEFAULT_SPLITS), help="QEVD splits to process (defaults to all three long-video sources).", ) parser.add_argument( "--ffmpeg", default="ffmpeg", help="ffmpeg executable name or path (default: ffmpeg).", ) parser.add_argument( "--dry-run", action="store_true", help="Create segment manifests without reading or encoding the videos.", ) parser.add_argument( "--overwrite", action="store_true", help="Replace output clips that already exist.", ) return parser.parse_args(argv) def feedback_spans(dense_feedbacks: Sequence[Any]) -> list[FeedbackSpan]: """Collapse frame-aligned feedback strings into non-empty contiguous runs.""" spans: list[FeedbackSpan] = [] active_text: str | None = None active_start = 0 for frame_index, raw_feedback in enumerate(dense_feedbacks): text = str(raw_feedback or "") if active_text is not None and text != active_text: spans.append(FeedbackSpan(active_text, active_start, frame_index - 1)) active_text = None if text and active_text is None: active_text = text active_start = frame_index if active_text is not None: spans.append( FeedbackSpan(active_text, active_start, len(dense_feedbacks) - 1) ) return spans def load_frame_timestamps(path: Path) -> np.ndarray: """Load the official per-frame UNIX timestamps and convert ns to seconds.""" raw = np.asarray(np.load(path), dtype=np.float64) if raw.ndim != 1 or len(raw) < 2: raise ValueError(f"Expected a one-dimensional timestamp array: {path}") seconds = raw / 1_000_000_000.0 if not np.all(np.diff(seconds) > 0): raise ValueError(f"Frame timestamps must be strictly increasing: {path}") return seconds def effective_fps(timestamps: np.ndarray) -> float: duration = float(timestamps[-1] - timestamps[0]) if duration <= 0: raise ValueError("Timestamp duration must be positive") return float(len(timestamps) / duration) def exercise_from_transition(text: str) -> str: for prefix in ("First up are ", "Moving on to "): if text.startswith(prefix): text = text[len(prefix) :] break return text.rstrip("!").strip() def segments_for_record( *, dataset: str, record: dict[str, Any], timestamps: np.ndarray, ) -> list[Segment]: dense_feedbacks = record.get("feedbacks") sparse_timestamps = record.get("feedback_timestamps") transition_flags = record.get("is_transition") if not isinstance(dense_feedbacks, list): raise ValueError("feedbacks must be a list") if not isinstance(sparse_timestamps, list): raise ValueError("feedback_timestamps must be a list") if not isinstance(transition_flags, list): raise ValueError("is_transition must be a list") if len(dense_feedbacks) != len(timestamps): raise ValueError( "The dense feedback sequence and frame timestamp array must have equal length" ) spans = feedback_spans(dense_feedbacks) if len(spans) != len(sparse_timestamps): raise ValueError( f"Recovered {len(spans)} feedback spans but found " f"{len(sparse_timestamps)} feedback timestamps" ) if len(transition_flags) != len(spans): raise ValueError( f"Found {len(transition_flags)} transition flags for {len(spans)} spans" ) transition_positions = [ index for index, is_transition in enumerate(transition_flags) if is_transition ] if len(transition_positions) < 2: raise ValueError("At least two transition annotations are required") source_video = str(record.get("long_range_video_file") or "") source_timestamps = str(record.get("video_timestamps") or "") if not source_video or not source_timestamps: raise ValueError("The record must reference a video and timestamp file") video_stem = Path(source_video).stem fps = effective_fps(timestamps) segments: list[Segment] = [] for current_position, next_position in zip( transition_positions, transition_positions[1:] ): feedback_count = next_position - current_position - 1 if feedback_count < 1: continue current_transition = spans[current_position] next_transition = spans[next_position] start_frame = current_transition.start_frame end_frame = next_transition.start_frame + ( next_transition.end_frame - next_transition.start_frame ) // 2 if not 0 <= start_frame <= end_frame < len(timestamps): raise ValueError( f"Invalid inclusive frame range [{start_frame}, {end_frame}]" ) segment_index = len(segments) segments.append( Segment( dataset=dataset, output_name=f"{video_stem}_{segment_index:02d}.mp4", source_video=source_video, source_timestamps=source_timestamps, exercise_name=exercise_from_transition(current_transition.text), start_frame=start_frame, end_frame=end_frame, start_seconds=float(timestamps[start_frame] - timestamps[0]), end_seconds=float(timestamps[end_frame] - timestamps[0]), fps=fps, feedback_count=feedback_count, ) ) return segments def ffmpeg_command( *, executable: str, source: Path, output: Path, segment: Segment ) -> list[str]: frame_filter = ( f"select=between(n\\,{segment.start_frame}\\,{segment.end_frame})," f"setpts=N/({segment.fps:.12f}*TB)" ) return [ executable, "-hide_banner", "-loglevel", "error", "-i", str(source), "-vf", frame_filter, "-an", "-c:v", "libx264", "-preset", "slower", "-crf", "17", "-profile:v", "high", "-pix_fmt", "yuv420p", "-movflags", "+faststart", "-fps_mode", "cfr", "-r", f"{segment.fps:.12f}", "-y", str(output), ] def load_records(path: Path) -> list[dict[str, Any]]: with path.open("r", encoding="utf-8") as handle: records = json.load(handle) if not isinstance(records, list) or not all( isinstance(record, dict) for record in records ): raise ValueError(f"Expected a JSON array of objects: {path}") return records def process_split(args: argparse.Namespace, split: str) -> int: split_root = args.input_root / split records_path = split_root / "feedbacks_long_range.json" records = load_records(records_path) output_dir = args.output_root / split output_dir.mkdir(parents=True, exist_ok=True) manifest_rows: list[dict[str, Any]] = [] for record_index, record in enumerate(records): try: timestamp_path = split_root / str(record["video_timestamps"]) timestamps = load_frame_timestamps(timestamp_path) segments = segments_for_record( dataset=split, record=record, timestamps=timestamps ) for segment in segments: output_path = output_dir / segment.output_name manifest_row = asdict(segment) manifest_row["output_path"] = str( Path(split) / segment.output_name ) manifest_rows.append(manifest_row) if args.dry_run or (output_path.exists() and not args.overwrite): continue source_path = split_root / segment.source_video if not source_path.is_file(): raise FileNotFoundError(source_path) subprocess.run( ffmpeg_command( executable=args.ffmpeg, source=source_path, output=output_path, segment=segment, ), check=True, ) except Exception as exc: source = record.get("long_range_video_file", f"record {record_index}") raise RuntimeError(f"{split}: failed to process {source}") from exc manifest_path = output_dir / "segments.jsonl" with manifest_path.open("w", encoding="utf-8") as handle: for row in manifest_rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") print(f"{split}: described {len(manifest_rows):,} candidate segments") return len(manifest_rows) def main(argv: Sequence[str] | None = None) -> None: args = parse_args(argv) args.input_root = args.input_root.resolve() args.output_root = args.output_root.resolve() if not args.dry_run and shutil.which(args.ffmpeg) is None: raise RuntimeError(f"ffmpeg executable not found: {args.ffmpeg}") total = sum(process_split(args, split) for split in args.splits) print(f"Done: described {total:,} candidate single-exercise segments") if __name__ == "__main__": main()