|
|
import os |
|
|
import json |
|
|
from pathlib import Path |
|
|
from PIL import Image |
|
|
|
|
|
data_dir = Path("data/animations") |
|
|
output_dir = Path("data/shots") |
|
|
|
|
|
|
|
|
output_dir.mkdir(parents=True, exist_ok=True) |
|
|
|
|
|
|
|
|
webp_files = sorted(data_dir.glob("sample-*.webp")) |
|
|
|
|
|
for webp_file in webp_files: |
|
|
|
|
|
base_name = webp_file.stem |
|
|
nnn = base_name.split("-")[1] |
|
|
hf_json_path = data_dir / f"sample-{nnn}.hf.json" |
|
|
if not hf_json_path.exists(): |
|
|
print(f"Missing {hf_json_path}, skipping {webp_file}") |
|
|
continue |
|
|
|
|
|
|
|
|
with open(hf_json_path, "r") as f: |
|
|
hf_data = json.load(f) |
|
|
|
|
|
|
|
|
img = Image.open(webp_file) |
|
|
|
|
|
|
|
|
indices = hf_data.get("scene_change_indices", []) |
|
|
if not indices: |
|
|
print(f"No scene_change_indices in {hf_json_path}, skipping.") |
|
|
continue |
|
|
|
|
|
|
|
|
ranges = [] |
|
|
prev = 0 |
|
|
for idx in indices: |
|
|
ranges.append((prev, idx)) |
|
|
prev = idx + 1 |
|
|
|
|
|
total_frames = getattr(img, 'n_frames', 1) |
|
|
ranges.append((prev, total_frames - 1)) |
|
|
|
|
|
for i, (start, end) in enumerate(ranges): |
|
|
frames = [] |
|
|
durations = [] |
|
|
for frame_idx in range(start, end + 1): |
|
|
img.seek(frame_idx) |
|
|
frames.append(img.copy()) |
|
|
|
|
|
duration = img.info.get('duration', 40) |
|
|
durations.append(duration) |
|
|
if frames: |
|
|
out_path = output_dir / f"sample-{nnn}-{i}.webp" |
|
|
if len(frames) == 1: |
|
|
frames[0].save(out_path, format="WEBP", duration=durations[0]) |
|
|
else: |
|
|
frames[0].save(out_path, format="WEBP", save_all=True, append_images=frames[1:], duration=durations) |
|
|
print(f"Saved {out_path} ({len(frames)} frames)") |
|
|
|