File size: 10,382 Bytes
7677a5d
 
 
 
 
 
 
 
 
d2b06b9
 
 
7677a5d
 
 
 
 
d2b06b9
7677a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b06b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7677a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b06b9
7677a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b06b9
7677a5d
 
 
 
 
 
 
 
 
 
d2b06b9
7677a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b06b9
7677a5d
 
 
 
d2b06b9
7677a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Package the existing public files into typed, self-contained HF tables.

Run from any directory: python scripts/build_release.py
No inference, network access, uploads, or changes to source data are performed.
"""
import hashlib
import io
import json
import re
import math
import subprocess
import tempfile
from collections import Counter
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Features, Image as HFImage, List, Value, Video
from PIL import Image, ImageDraw


ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
OUT = ROOT / "release"
REVISION = "177436de2edfc620065134530409e1394d8672fd"
BASE_URL = f"https://huggingface.co/datasets/sprited/sprite-dx-data/resolve/{REVISION}/"


def image_bytes(path):
    return {"bytes": path.read_bytes(), "path": path.name}


def png_bytes(image, name):
    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    return {"bytes": buffer.getvalue(), "path": name}


def strip(path, start=0, end=None):
    """Static, indexed filmstrip so every HF client can display motion samples."""
    with Image.open(path) as animation:
        n = animation.n_frames
        end = n if end is None else end
        if not 0 <= start < end <= n:
            raise ValueError(f"Invalid range for {path}: {start}:{end} / {n}")
        indices = sorted({start + (end - start - 1) * i // 3 for i in range(4)})
        preview = Image.new("RGB", (160 * len(indices), 184), "#f1f3f5")
        draw = ImageDraw.Draw(preview)
        for column, index in enumerate(indices):
            animation.seek(index)
            frame = animation.convert("RGBA")
            frame.thumbnail((160, 160))
            preview.paste(frame, (column * 160 + (160 - frame.width) // 2, 0), frame)
            draw.text((column * 160 + 8, 166), f"frame {index}", fill="#20242a")
        return png_bytes(preview, path.stem + "-preview.png"), n


def video_bytes(path, start=0, end=None):
    """Browser-compatible viewing copy; original WebP and timing stay available.

    Repeat frames at the greatest common divisor of durations to preserve the
    source's millisecond timing, including variable-duration WebP frames.
    """
    frames, durations = [], []
    with Image.open(path) as animation:
        end = animation.n_frames if end is None else end
        if not 0 <= start < end <= animation.n_frames:
            raise ValueError(f"Invalid video range: {path}, {start}:{end}")
        for index in range(start, end):
            animation.seek(index)
            animation.load()
            duration = animation.info.get("duration")
            if not isinstance(duration, int) or duration <= 0:
                raise ValueError(f"Missing or invalid frame duration: {path}, {index}")
            frame = animation.convert("RGBA")
            frame.thumbnail((320, 320))
            # MP4/H.264 has no alpha: previews use a neutral background.
            background = Image.new("RGBA", frame.size, (241, 243, 245, 255))
            background.alpha_composite(frame)
            frames.append(background.convert("RGB").tobytes())
            durations.append(duration)
        width, height = frame.size
    tick = math.gcd(*durations)
    raw = b"".join(frame * (duration // tick) for frame, duration in zip(frames, durations))
    with tempfile.TemporaryDirectory(prefix="sprited-video-") as directory:
        output = Path(directory) / (path.stem + ".mp4")
        subprocess.run([
            "ffmpeg", "-v", "error", "-f", "rawvideo", "-pix_fmt", "rgb24",
            "-s", f"{width}x{height}", "-r", f"1000/{tick}", "-i", "pipe:0",
            "-an", "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2",
            "-c:v", "libx264", "-preset", "fast", "-crf", "20",
            "-threads", "1", "-pix_fmt", "yuv420p", "-movflags", "+faststart",
            str(output),
        ], input=raw, check=True, capture_output=True)
        return {"bytes": output.read_bytes(), "path": output.name}


def matting_rows():
    for path in sorted((DATA / "expanded").rglob("*.png")):
        relative = path.relative_to(DATA / "expanded")
        match = re.fullmatch(r"(sample-\d+)-(\d+)-f(\d+)", path.stem)
        if not match:
            raise ValueError(f"Unexpected frame name: {path}")
        source, shot, frame = match.groups()
        paired = {key: DATA / folder / relative for key, folder in (
            ("image", "expanded"), ("matte", "automatte"),
            ("foreground", "fgr"), ("cutout", "masked"),
        )}
        sizes = set()
        for key, image_path in paired.items():
            with Image.open(image_path) as image:
                image.load()
                sizes.add(image.size)
                if key == "cutout" and image.mode != "RGBA":
                    raise ValueError(f"Missing alpha: {image_path}")
        if len(sizes) != 1:
            raise ValueError(f"Unaligned image sizes: {relative}")
        width, height = sizes.pop()
        yield {
            **{key: image_bytes(p) for key, p in paired.items()},
            "id": str(relative.with_suffix("")), "frame_id": path.stem,
            "source_id": source, "shot_index": int(shot), "frame_index": int(frame),
            "collection": relative.parts[0], "width": width, "height": height,
            "source_path": str(path.relative_to(ROOT)),
        }


def loop_rows():
    for path in sorted((DATA / "loops").glob("*.loop.hf.json")):
        shot_id = path.name.split(".")[0]
        annotation = json.loads(path.read_text())
        start, end_inclusive = annotation["best_cut"]
        end = end_inclusive + 1
        source, shot = shot_id.rsplit("-", 1)
        shot_path = DATA / "shots" / (shot_id + ".webp")
        preview, n = strip(shot_path, start, end)
        with Image.open(shot_path) as image:
            width, height = image.size
        yield {
            "video": video_bytes(shot_path, start, end),
            "preview": preview, "id": shot_id, "source_id": source,
            "shot_index": int(shot), "is_loop": annotation["loop"],
            "start_frame": start, "end_frame_exclusive": end,
            "num_frames": n, "width": width, "height": height,
            "animation_url": BASE_URL + str(shot_path.relative_to(ROOT)),
            "annotation_path": str(path.relative_to(ROOT)),
        }


def scene_rows():
    for path in sorted((DATA / "animations").glob("*.hf.json")):
        source = path.name.split(".")[0]
        animation_path = DATA / "animations" / (source + ".webp")
        cuts = json.loads(path.read_text())["scene_change_indices"]
        preview, n = strip(animation_path)
        if cuts != sorted(set(cuts)) or any(c < 0 or c >= n - 1 for c in cuts):
            raise ValueError(f"Invalid scene boundaries: {path}")
        with Image.open(animation_path) as image:
            width, height = image.size
        yield {
            "video": video_bytes(animation_path),
            "preview": preview, "id": source, "source_id": source,
            "num_frames": n, "width": width, "height": height,
            "scene_end_frames": cuts, "num_shots": len(cuts) + 1,
            "animation_url": BASE_URL + str(animation_path.relative_to(ROOT)),
            "annotation_path": str(path.relative_to(ROOT)),
        }


def features(images, strings, integers, extra=None):
    return Features({
        **({"video": extra["video"]} if extra and "video" in extra else {}),
        **{key: HFImage() for key in images},
        **{key: Value("string") for key in strings},
        **{key: Value("int32") for key in integers},
        **(extra or {}),
    })


SCHEMAS = {
    "matting": features(
        ["image", "matte", "foreground", "cutout"],
        ["id", "frame_id", "source_id", "collection", "source_path"],
        ["shot_index", "frame_index", "width", "height"],
    ),
    "loops": features(
        ["preview"], ["id", "source_id", "animation_url", "annotation_path"],
        ["shot_index", "start_frame", "end_frame_exclusive", "num_frames", "width", "height"],
        {"video": Video(), "is_loop": Value("bool")},
    ),
    "scene_boundaries": features(
        ["preview"], ["id", "source_id", "animation_url", "annotation_path"],
        ["num_frames", "width", "height", "num_shots"],
        {"video": Video(), "scene_end_frames": List(Value("int32"))},
    ),
}


def write_subset(name, rows):
    destination = OUT / name
    destination.mkdir(parents=True, exist_ok=True)
    if list(destination.glob("*.parquet")):
        raise RuntimeError(f"{destination} already contains a release; use a fresh output directory")
    schema = SCHEMAS[name].arrow_schema
    ids, sources, frames, labels = set(), set(), set(), Counter()
    batch, shards, count = [], [], 0

    def write_batch():
        output = destination / f"train-{len(shards):04d}.parquet"
        table = pa.Table.from_pylist(batch, schema=schema)
        pq.write_table(table, output, compression="zstd", row_group_size=32, write_page_index=True)
        shards.append({"path": str(output.relative_to(ROOT)), "rows": len(batch),
                       "bytes": output.stat().st_size,
                       "sha256": hashlib.sha256(output.read_bytes()).hexdigest()})
        batch.clear()

    for row in rows:
        if row["id"] in ids:
            raise ValueError(f"Duplicate row: {row['id']}")
        ids.add(row["id"])
        sources.add(row["source_id"])
        if "frame_id" in row:
            frames.add(row["frame_id"])
        if "is_loop" in row:
            labels[str(row["is_loop"]).lower()] += 1
        batch.append(row)
        count += 1
        if len(batch) == 200:
            write_batch()
    if batch:
        write_batch()
    print(f"{name}: {count} rows, {len(shards)} shards", flush=True)
    return {"rows": count, "source_animations": len(sources),
            "unique_frame_ids": len(frames) if frames else None,
            "loop_labels": dict(labels) if labels else None, "shards": shards}


def main():
    OUT.mkdir(exist_ok=True)
    report = {"source_revision": REVISION, "subsets": {}}
    for name, rows in (("matting", matting_rows()), ("loops", loop_rows()),
                       ("scene_boundaries", scene_rows())):
        report["subsets"][name] = write_subset(name, rows)
    (OUT / "manifest.json").write_text(json.dumps(report, indent=2) + "\n")


if __name__ == "__main__":
    main()