File size: 10,998 Bytes
6351be7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/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()