Download code/agt/data/clips.py from MRBSTUDIO/AGT: direct link, hf CLI and curl.
- Browser
- Download file 5.77 kB
-
https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/data/clips.py
- Command line
-
hf download hf://MRBSTUDIO/AGT/code/agt/data/clips.py
-
curl -L -o clips.py https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/data/clips.py
5.77 kB
| from __future__ import annotations | |
| import numpy as np | |
| from .protocol import ClipProtocol, ROLE_CONTEXT, ROLE_EXTRAP, ROLE_INTERP, US | |
| RULE_NO_FRAME = 'no_frame_within_tolerance' | |
| RULE_SAME_FRAME = 'same_frame_picked_twice' | |
| class FrameSelectionError(ValueError): | |
| def __init__(self, message, *, rules=(), max_error_us=float('nan'), tolerance_us=float('nan')): | |
| super().__init__(message) | |
| self.rules, self.max_error_us, self.tolerance_us = tuple(rules), float(max_error_us), float(tolerance_us) | |
| def frame_times(frames_meta) -> dict: | |
| start = np.asarray([row['timestamp_start_us'] for row in frames_meta], dtype=np.int64) | |
| end = np.asarray([row['timestamp_end_us'] for row in frames_meta], dtype=np.int64) | |
| if len(start) < 2 or not np.all(np.diff(start) > 0) or np.any(end < start): | |
| raise ValueError('Frame timestamps must be strictly increasing with end >= start') | |
| mid = (start.astype(np.float64) + end) / 2 | |
| elapsed = mid - mid[0] | |
| period = float(elapsed[-1] / (len(elapsed) - 1)) | |
| return {'start_us': start, 'end_us': end, 'mid_us': mid, 'elapsed_us': elapsed, 'period_us': period, | |
| 'duration_us': period * len(elapsed)} | |
| def nearest_frames(elapsed_us: np.ndarray, targets_us) -> tuple: | |
| targets = np.asarray(targets_us, dtype=np.float64) | |
| right = np.clip(np.searchsorted(elapsed_us, targets), 1, len(elapsed_us) - 1) | |
| left = right - 1 | |
| pick = np.where(np.abs(elapsed_us[left] - targets) <= np.abs(elapsed_us[right] - targets), left, right) | |
| return pick.astype(np.int64), np.abs(elapsed_us[pick] - targets) | |
| def selection_tolerance_us(period_us: float, tolerance_us: float | None = None) -> float: | |
| return float(period_us) / 2 if tolerance_us is None else float(tolerance_us) | |
| def select_frames(elapsed_us: np.ndarray, targets_us, period_us: float, tolerance_us: float | None = None) -> tuple: | |
| tol = selection_tolerance_us(period_us, tolerance_us) | |
| targets = np.asarray(targets_us, dtype=np.float64) | |
| pick, error = nearest_frames(elapsed_us, targets) | |
| far = error > tol | |
| rules = ([RULE_NO_FRAME] if np.any(far) else []) + ([RULE_SAME_FRAME] if np.any(np.diff(pick) <= 0) else []) | |
| if rules: | |
| if far.any(): | |
| where = 'half a period' if tolerance_us is None else f'the declared tolerance {tol / 1e3:g} ms' | |
| message = f'No frame within {where} of {targets[far] / US} s' | |
| if RULE_SAME_FRAME in rules: | |
| message += '; two samples map to one frame' | |
| else: | |
| message = 'Sampling rate exceeds the frame rate: two samples map to one frame' | |
| raise FrameSelectionError(message, rules=rules, max_error_us=float(error.max()), tolerance_us=tol) | |
| return pick, float(error.max()) | |
| def build_clips(protocol: ClipProtocol, record, frames_meta, *, sample_id: str | None = None, | |
| skipped: list | None = None, tolerance_us: float | None = None) -> list: | |
| T = int(record.frame_count) | |
| if len(frames_meta) != T: | |
| raise ValueError(f'{record.scene_id}: frames.jsonl has {len(frames_meta)} rows, record says {T}') | |
| times = frame_times(frames_meta) | |
| sample_id = sample_id or record.scene_id | |
| offsets, roles = np.asarray(protocol.offsets_us()), list(protocol.roles()) | |
| ctx_pos = [i for i, r in enumerate(roles) if r == ROLE_CONTEXT] | |
| clips = [] | |
| for start_us in protocol.window_starts_us(times['duration_us'], times['period_us']): | |
| try: | |
| idx, error = select_frames(times['elapsed_us'], start_us + offsets, times['period_us'], tolerance_us) | |
| except FrameSelectionError as exc: | |
| if skipped is None: | |
| raise | |
| skipped.append({'sample_id': sample_id, 'scene_id': record.scene_id, | |
| 'source_id': getattr(record, 'source_id', None), 'window_start_s': start_us / US, | |
| 'reason': str(exc), 'rules': list(exc.rules), 'max_error_us': exc.max_error_us, | |
| 'tolerance_us': exc.tolerance_us}) | |
| continue | |
| mid = times['mid_us'][idx] | |
| t0, t1 = mid[ctx_pos[0]], mid[ctx_pos[-1]] | |
| if t1 <= t0: | |
| raise ValueError('Context span must be positive') | |
| idx_list = idx.tolist() | |
| clips.append({ | |
| 'clip_id': f'{sample_id}__w{idx_list[0]}', | |
| 'sample_id': sample_id, | |
| 'sample_key': dict(zip(('dataset_id', 'scene_id', 'camera_id', 'variant_id'), record.sample_key)), | |
| 'scene_id': record.scene_id, | |
| 'protocol_id': protocol.protocol_id, | |
| 'protocol_name': protocol.name, | |
| 'window_mode': protocol.window_mode, | |
| 'group': record.group, 'time_of_day': record.time_of_day, 'template_id': record.template_id, | |
| 'source_id': record.source_id, 'map_version': record.map_version, | |
| 'window_start_s': start_us / US, | |
| 'window_start_frame': idx_list[0], | |
| 'frame_indices': idx_list, | |
| 'roles': roles, | |
| 'is_keyframe': [r == ROLE_CONTEXT for r in roles], | |
| 'context_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_CONTEXT], | |
| 'interp_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_INTERP], | |
| 'extrap_frames': [i for i, r in zip(idx_list, roles) if r == ROLE_EXTRAP], | |
| 'heldout_frames': [i for i, r in zip(idx_list, roles) if r in (ROLE_INTERP, ROLE_EXTRAP)], | |
| 'timestamps_us': mid.tolist(), | |
| 'timestamps_start_us': times['start_us'][idx].tolist(), | |
| 't_norm': ((mid - t0) / (t1 - t0)).tolist(), | |
| 'selection_max_error_us': error, | |
| }) | |
| if len({c['clip_id'] for c in clips}) != len(clips): | |
| raise ValueError('Duplicate clip ids') | |
| return clips | |