AGT / code /agt /prepare /video_clip.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
7.99 kB
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
SCHEMA = "clip_inputs_v1"
FRAMES = 20
STEP_S = 0.1
CONTEXT_POSITIONS = [0, 5, 10, 15]
RENDERED = list(range(16))
NATIVE = (1280, 720)
IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png")
def crop_16_9(w: int, h: int) -> tuple:
if w * 9 == h * 16:
return 0, 0, w, h
if w * 9 > h * 16:
cw = round(h * 16 / 9)
left = (w - cw) // 2
return left, 0, left + cw, h
ch = round(w * 9 / 16)
top = (h - ch) // 2
return 0, top, w, top + ch
def pick_nearest(times, start_s: float, period: float, what: str):
targets = start_s + STEP_S * np.arange(FRAMES)
times = np.asarray(times, np.float64)
pick = [int(np.abs(times - t).argmin()) for t in targets]
error = np.abs(times[pick] - targets)
if error.max() > period / 2 + 1e-6:
raise ValueError(f'{what}: target {targets[int(error.argmax())]:.3f} s has no frame within half a period '
f'(nearest {error.max() * 1e3:.1f} ms, period {period * 1e3:.1f} ms)')
if len(set(pick)) != FRAMES:
raise ValueError(f'{what}: two samples map to the same frame (frame rate below 10 Hz?)')
return pick, float(error.max() * 1e3)
def decode_window(video: Path, start_s: float) -> dict:
import av
with av.open(str(video)) as container:
stream = container.streams.video[0]
rate = stream.average_rate or stream.guessed_rate
period = 1.0 / float(rate)
container.seek(max(0, int((start_s - 1.0) / stream.time_base)), stream=stream, backward=True)
times, images, index, rotations = [], [], [], set()
last = start_s + STEP_S * (FRAMES - 1)
for frame in container.decode(stream):
t = frame.time
if t is None:
raise ValueError(f'{video}: frame without pts')
if t < start_s - 0.5:
continue
if t > last + 0.5:
break
image = frame.to_image()
rotation = int(round(getattr(frame, 'rotation', 0) or 0))
if rotation % 90:
raise ValueError(f'{video}: display rotation {rotation} is not a multiple of 90')
if rotation % 360:
image = image.rotate(rotation, expand=True)
rotations.add(rotation % 360)
times.append(t); images.append(image); index.append(frame.pts)
if len(rotations) > 1:
raise ValueError(f'{video}: display rotation changes inside the window {sorted(rotations)}')
(w, h), = {im.size for im in images} or {(0, 0)}
info = {'width': w, 'height': h, 'coded_size': [stream.codec_context.width, stream.codec_context.height],
'display_rotation_ccw': next(iter(rotations), 0),
'average_rate': str(stream.average_rate), 'codec': stream.codec_context.name}
if len(times) < FRAMES:
raise ValueError(f'{video}: only {len(times)} frames near [{start_s}, {last}]')
times = np.asarray(times)
gaps = np.diff(np.sort(times))
if gaps.size and np.median(gaps) > 0:
period = float(np.median(gaps))
pick, err = pick_nearest(times, start_s, period, str(video))
return {'images': [images[i] for i in pick], 'times': times[pick], 'pts': [index[i] for i in pick],
'max_time_error_ms': err, 'frame_period_ms': period * 1e3, **info}
def read_sequence(frames_dir: Path, fps: float, start_s: float) -> dict:
from PIL import Image
files = sorted(x for x in Path(frames_dir).iterdir() if x.suffix.lower() in IMAGE_SUFFIXES)
pick, err = pick_nearest(np.arange(len(files)) / fps, start_s, 1 / fps, str(frames_dir))
images = [Image.open(files[i]) for i in pick]
sizes = {im.size for im in images}
if len(sizes) != 1:
raise ValueError(f'{frames_dir}: mixed frame sizes {sizes}')
(w, h), = sizes
return {'images': images, 'times': np.asarray(pick, np.float64) / fps, 'pts': [files[i].name for i in pick],
'max_time_error_ms': err, 'frame_period_ms': 1e3 / fps, 'width': w, 'height': h,
'average_rate': f'{fps:g}', 'codec': 'image sequence'}
def default_clip_id(source: Path, start_s: float) -> str:
return f'{Path(source).stem}_s{int(round(start_s * 1000)):05d}'
def export_clip(out: Path, clip_id: str, *, video: Path | None = None, frames_dir: Path | None = None,
fps: float | None = None, start_s: float = 0.0, dataset: str = 'user', group: str | None = None) -> dict:
from PIL import Image
if frames_dir is not None:
source = Path(frames_dir)
w = read_sequence(source, float(fps), start_s)
else:
source = Path(video)
w = decode_window(source, start_s)
box = crop_16_9(w['width'], w['height'])
d = Path(out) / clip_id
d.mkdir()
names = []
for k, image in enumerate(w['images']):
if image.size != (w['width'], w['height']):
raise ValueError(f'frame {k} size {image.size}')
image = image.convert('RGB').crop(box).resize(NATIVE, Image.Resampling.BICUBIC)
names.append(f'frame_{k:02d}.png')
image.save(d / names[-1])
t = w['times']
t_norm = ((t - t[0]) / (t[CONTEXT_POSITIONS[-1]] - t[0])).tolist()
us = [int(round(x * 1e6)) for x in t]
clip = {'schema': SCHEMA, 'clip_id': clip_id, 'sample_id': clip_id, 'scene_id': clip_id,
'dataset': dataset, 'group': group, 'context_positions': CONTEXT_POSITIONS,
'roles': ['context' if k in CONTEXT_POSITIONS else 'interp' if k < 16 else 'extrap' for k in range(FRAMES)],
'frame_files': names, 'frame_size': list(NATIVE), 't_norm': t_norm,
'timestamps_start_us': us, 'timestamps_us': us,
'pose': None, 'c2w': None, 'camera_native': None, 'camera_grid': None,
'frame_time': 'decoded frame pts (no exposure information); timestamps relative to the video start',
'source': {'name': source.name, 'window_start_s': float(start_s), 'sample_times_s': t.tolist(),
'pts': w['pts'], 'max_time_error_ms': w['max_time_error_ms'],
'frame_period_ms': w['frame_period_ms'], 'native_size': [w['width'], w['height']],
'average_rate': w['average_rate'], 'codec': w['codec'], 'crop_box': list(box),
'coded_size': w.get('coded_size'), 'display_rotation_ccw': w.get('display_rotation_ccw'),
'resize': 'PIL bicubic to 1280x720'}}
(d / 'clip.json').write_text(json.dumps(clip, indent=1) + '\n')
return clip
def export_clips(out: Path, entries: list[dict], allow_failures: bool = False) -> dict:
out = Path(out)
out.mkdir(parents=True, exist_ok=False)
clips, failures = [], []
for e in entries:
start = float(e.get('window_start_s', 0.0))
source = e.get('frames_dir') or e['video_path']
cid = e.get('clip_id') or default_clip_id(source, start)
try:
export_clip(out, cid, video=e.get('video_path'), frames_dir=e.get('frames_dir'), fps=e.get('fps'),
start_s=start, dataset=e.get('dataset', 'user'), group=e.get('group'))
clips.append(cid)
print(json.dumps({'clip_id': cid, 'ok': True}), flush=True)
except Exception as error:
failures.append({'clip_id': cid, 'error': f'{type(error).__name__}: {error}'})
print(json.dumps(failures[-1]), flush=True)
manifest = {'schema': SCHEMA, 'clips': clips, 'failures': failures,
'layout': {'frames': FRAMES, 'step_s': STEP_S, 'context_positions': CONTEXT_POSITIONS,
'rendered_positions': RENDERED, 'native_size': list(NATIVE)}}
(out / 'manifest.json').write_text(json.dumps(manifest, indent=1) + '\n')
if failures and not allow_failures:
raise SystemExit(f'{len(failures)} clip(s) failed (see manifest.json failures)')
return manifest