File size: 8,834 Bytes
966b234
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Uniform FFmpeg frame extraction for gameplay-video references."""

from __future__ import annotations

import json
import math
from pathlib import Path
import re
import shutil
from typing import Any, Mapping

from bench_builder import reference_frames
from bench_builder.video_plugin_options import PluginOptionSpec
from bench_builder.video_reference_processors.base import (
    VideoReferenceArtifacts,
    VideoReferenceProcessorDescriptor,
    VideoReferenceProcessorError,
)
from bench_builder.video_source_plugins import VideoClipArtifact


DEFAULT_OPTIONS: dict[str, Any] = {
    "recommended_clip_seconds": 30,
    "frame_interval_seconds": 0.5,
    "frame_width": 640,
    "frame_height": 360,
    "sampling_strategy": "uniform",
    "generate_gameplay_md": True,
    "gameplay_language": "auto",
}


def _write_json(path: Path, payload: Mapping[str, Any]) -> Path:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    return path


def _language(value: str, title: str) -> str:
    if value in {"chinese", "english"}:
        return value
    return "chinese" if re.search(r"[\u3400-\u9fff]", title) else "english"


def _initial_brief(title: str, language: str) -> str:
    if language == "chinese":
        return (
            f"复刻参考视频《{title}》中可见的游戏体验。\n\n"
            "- 对齐角色、场景、镜头、UI、运动节奏和可见状态变化。\n"
            "- 按时间轴检查开头、中段和结尾的截图。\n"
            "- 视频没有明确展示的按键只能作为建议控制,不要声称它来自录制轨迹。\n"
        )
    return (
        f'Recreate the visible game experience in the reference video "{title}".\n\n'
        "- Match the characters, environment, camera, UI, motion, and visible state changes.\n"
        "- Inspect frames from the beginning, middle, and end of the timeline.\n"
        "- Treat controls not visibly demonstrated by the video as suggested controls, not a recorded input trace.\n"
    )


class FfmpegFramesProcessor:
    descriptor = VideoReferenceProcessorDescriptor(
        plugin_id="ffmpeg_frames_v1",
        display_name="FFmpeg frames",
        sampling_strategies=("uniform",),
        options=(
            PluginOptionSpec(
                "frame_interval_seconds",
                "Screenshot interval",
                "number",
                0.5,
                minimum=0.1,
                maximum=10.0,
                step=0.1,
            ),
            PluginOptionSpec(
                "frame_width",
                "Frame width",
                "select",
                640,
                choices=(640, 960, 1280),
            ),
            PluginOptionSpec(
                "frame_height",
                "Frame height",
                "select",
                360,
                choices=(360, 540, 720),
            ),
        ),
    )

    def validate_options(self, options: Mapping[str, Any] | None) -> dict[str, Any]:
        settings = {**DEFAULT_OPTIONS, **dict(options or {})}
        try:
            interval = float(settings["frame_interval_seconds"])
            width = int(settings["frame_width"])
            height = int(settings["frame_height"])
            recommended = int(settings["recommended_clip_seconds"])
        except (TypeError, ValueError) as exc:
            raise VideoReferenceProcessorError("reference settings must be numeric") from exc
        if not math.isfinite(interval) or not 0.1 <= interval <= 10.0:
            raise VideoReferenceProcessorError("screenshot interval must be between 0.1 and 10 seconds")
        if (width, height) not in {(640, 360), (960, 540), (1280, 720)}:
            raise VideoReferenceProcessorError("frame resolution is unsupported")
        if str(settings["sampling_strategy"]) not in self.descriptor.sampling_strategies:
            raise VideoReferenceProcessorError("sampling strategy is unsupported")
        language = str(settings["gameplay_language"]).casefold()
        if language not in {"auto", "chinese", "english"}:
            raise VideoReferenceProcessorError("gameplay language is unsupported")
        if not 5 <= recommended <= 300:
            raise VideoReferenceProcessorError("suggested clip length must be between 5 and 300 seconds")
        return {
            "recommended_clip_seconds": recommended,
            "frame_interval_seconds": interval,
            "frame_width": width,
            "frame_height": height,
            "sampling_strategy": str(settings["sampling_strategy"]),
            "generate_gameplay_md": bool(settings["generate_gameplay_md"]),
            "gameplay_language": language,
            "source_title": str(settings.get("source_title") or "Gameplay video"),
        }

    def prepare(
        self,
        clip: VideoClipArtifact,
        destination: Path,
        options: Mapping[str, Any],
    ) -> VideoReferenceArtifacts:
        settings = self.validate_options(options)
        package = destination.resolve()
        frame_dir = package / "public" / "reference" / "frames"
        try:
            sequence = reference_frames.export_reference_frame_sequence(
                session_id=package.name,
                video_path=clip.path,
                trajectory_path=None,
                metadata_path=None,
                output_dir=frame_dir,
                interval_seconds=settings["frame_interval_seconds"],
                max_frames=1800,
                width=settings["frame_width"],
                height=settings["frame_height"],
                overlay_inputs=False,
                trim_start_seconds=0.0,
                trim_end_seconds=0.0,
                still_width=settings["frame_width"],
                still_height=settings["frame_height"],
            )
        except (OSError, ValueError, reference_frames.ReferenceFrameError) as exc:
            raise VideoReferenceProcessorError(str(exc)) from exc
        frames = [
            {
                "path": (frame_dir / frame.name).relative_to(package).as_posix(),
                "timestamp_seconds": frame.timestamp_seconds,
                "held_keys": [],
            }
            for frame in sequence.frames
        ]
        reference_root = package / "public" / "reference"
        timeline_path = reference_root / "timeline.jsonl"
        timeline_path.write_text(
            "".join(
                json.dumps(item, ensure_ascii=False, sort_keys=True) + "\n"
                for item in frames
            ),
            encoding="utf-8",
        )
        reference_manifest_path = _write_json(
            reference_root / "reference-manifest.json",
            {
                "schema": "gameplay-video.reference.v1",
                "clip": "reference_video/clip.mp4",
                "sequences": [{"frames": frames}],
            },
        )
        design_still_path = package / "public" / "screenshots" / "design-still.png"
        design_still_path.parent.mkdir(parents=True, exist_ok=True)
        source_still = frame_dir / reference_frames.DESIGN_STILL_NAME
        shutil.copy2(source_still, design_still_path)
        language = _language(settings["gameplay_language"], settings["source_title"])
        gameplay_path = package / "reference_video" / "GAMEPLAY.md"
        if not gameplay_path.is_file():
            gameplay_path.parent.mkdir(parents=True, exist_ok=True)
            gameplay_path.write_text(
                _initial_brief(settings["source_title"], language)
                if settings["generate_gameplay_md"]
                else "",
                encoding="utf-8",
            )
        brief = gameplay_path.read_text(encoding="utf-8")
        design_path = _write_json(
            package / "public" / "design.json",
            {
                "schema": "gameplay-video.design.v1",
                "brief": brief,
                "screenshots": [design_still_path.relative_to(package).as_posix()],
            },
        )
        settings_path = _write_json(
            package / "reference_video" / "reference-settings.json",
            {"processor_id": self.descriptor.plugin_id, **settings},
        )
        return VideoReferenceArtifacts(
            processor_id=self.descriptor.plugin_id,
            frame_dir=frame_dir,
            timeline_path=timeline_path,
            reference_manifest_path=reference_manifest_path,
            design_path=design_path,
            design_still_path=design_still_path,
            gameplay_path=gameplay_path,
            settings_path=settings_path,
            frame_count=sequence.frame_count,
        )


PLUGIN = FfmpegFramesProcessor()


__all__ = ["DEFAULT_OPTIONS", "FfmpegFramesProcessor", "PLUGIN"]