File size: 8,986 Bytes
17982ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python3
"""
从 frames 目录 + CSV(index,value,critic,done)生成左右拼接视频:
左侧当前帧;右侧与 output_2_with_plots 风格一致:顶栏
「Critic: … | Value: … | Done: …」(四位小数),其下三个纵向子图
(Value 绿 0–50、Critic 红 0–50、Done 蓝 0–1),折线 + 圆点,当前帧圆点更大。
"""
from __future__ import annotations

import argparse
import csv
import re
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
from PIL import Image


def natural_sort_key(p: Path) -> tuple[int, ...]:
    m = re.search(r"(\d+)", p.stem)
    return (int(m.group(1)),) if m else (0,)


def load_frames_dir(frames_dir: Path) -> list[Path]:
    paths = sorted(frames_dir.glob("frame_*.png"), key=natural_sort_key)
    if not paths:
        paths = sorted(frames_dir.glob("*.png"), key=natural_sort_key)
    if not paths:
        raise FileNotFoundError(f"No PNG frames under {frames_dir}")
    return paths


def load_metrics_csv(csv_path: Path) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """返回 value, critic, done — 每行对应一个 frame(按 CSV 行顺序)。"""
    with csv_path.open(newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        if not reader.fieldnames:
            raise ValueError(f"Empty CSV: {csv_path}")
        rows = list(reader)

    def col(row: dict, name: str) -> str:
        for k, v in row.items():
            if k and k.strip().lower() == name.lower():
                return v
        raise KeyError(f"Missing column {name!r} in row {row}")

    values: list[float] = []
    critics: list[float] = []
    dones: list[float] = []

    for row in rows:
        row = {k.strip(): v for k, v in row.items() if k is not None}
        values.append(float(col(row, "value")))
        critics.append(float(col(row, "critic")))
        dones.append(float(col(row, "done")))

    return (
        np.asarray(values, dtype=np.float64),
        np.asarray(critics, dtype=np.float64),
        np.asarray(dones, dtype=np.float64),
    )


def align_metrics_to_frame_count(
    n_frames: int,
    value: np.ndarray,
    critic: np.ndarray,
    done: np.ndarray,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """将 CSV 中的序列对齐到 n_frames 条(不足则重复最后一行,过多则截断)。"""
    if len(value) == n_frames:
        return value, critic, done
    if len(value) > n_frames:
        return value[:n_frames], critic[:n_frames], done[:n_frames]
    pad = n_frames - len(value)
    value = np.concatenate([value, np.full(pad, value[-1])])
    critic = np.concatenate([critic, np.full(pad, critic[-1])])
    done = np.concatenate([done, np.full(pad, done[-1])])
    return value, critic, done


def _plot_metric_subplot(
    ax,
    x: np.ndarray,
    y: np.ndarray,
    line_color: str,
    ylabel: str,
    ylabel_color: str,
    ylim: tuple[float, float],
    *,
    show_xlabel: bool,
) -> None:
    """折线 + 小圆点;最后一个点更大(当前帧)。x/y 长度一致。"""
    ax.set_facecolor("#f0f0f0")
    if len(x) > 1:
        ax.plot(x, y, color=line_color, linewidth=2.0, zorder=2, solid_capstyle="round")
        ax.scatter(
            x[:-1],
            y[:-1],
            s=45,
            color=line_color,
            zorder=3,
            edgecolors="white",
            linewidths=0.9,
        )
    ax.scatter(
        x[-1],
        y[-1],
        s=140,
        color=line_color,
        zorder=4,
        edgecolors="white",
        linewidths=1.2,
    )
    ax.set_ylim(ylim[0], ylim[1])
    ax.set_ylabel(ylabel, fontsize=10, color=ylabel_color)
    ax.tick_params(axis="y", labelcolor=ylabel_color)
    ax.grid(True, alpha=0.35, color="#bbbbbb")
    if show_xlabel:
        ax.set_xlabel("frame index", fontsize=10)


def render_frame(
    img_path: Path,
    t: int,
    n_frames: int,
    value: np.ndarray,
    critic: np.ndarray,
    done: np.ndarray,
    figsize: tuple[float, float],
    dpi: int,
) -> np.ndarray:
    """返回 RGB uint8 拼接图 (H, W, 3),右侧布局对齐 output_2_with_plots 风格。"""
    img = np.asarray(Image.open(img_path).convert("RGB"))

    fig = plt.figure(figsize=figsize, dpi=dpi)
    gs = GridSpec(
        4,
        2,
        figure=fig,
        width_ratios=[1.0, 1.15],
        height_ratios=[0.14, 1.0, 1.0, 1.0],
        wspace=0.08,
        hspace=0.30,
        left=0.04,
        right=0.98,
        top=0.94,
        bottom=0.08,
    )

    ax_l = fig.add_subplot(gs[1:4, 0])
    ax_l.imshow(img)
    ax_l.set_axis_off()

    ax_hdr = fig.add_subplot(gs[0, 1])
    ax_hdr.set_facecolor("#f0f0f0")
    ax_hdr.axis("off")
    header = (
        f"Critic: {float(critic[t]):.4f} | "
        f"Value: {float(value[t]):.4f} | "
        f"Done: {float(done[t]):.4f}"
    )
    ax_hdr.text(0.5, 0.45, header, ha="center", va="center", fontsize=10, color="black")

    ax_v = fig.add_subplot(gs[1, 1])
    ax_c = fig.add_subplot(gs[2, 1], sharex=ax_v)
    ax_d = fig.add_subplot(gs[3, 1], sharex=ax_v)

    xs = np.arange(0, t + 1, dtype=np.float64)
    x_hi = float(max(n_frames - 1, 1))
    for ax in (ax_v, ax_c, ax_d):
        ax.set_xlim(0.0, x_hi)

    _plot_metric_subplot(
        ax_v,
        xs,
        value[: t + 1],
        "#2ca02c",
        "Value",
        "#2ca02c",
        (0.0, 50.0),
        show_xlabel=False,
    )
    _plot_metric_subplot(
        ax_c,
        xs,
        critic[: t + 1],
        "#d62728",
        "Critic",
        "#d62728",
        (0.0, 50.0),
        show_xlabel=False,
    )
    _plot_metric_subplot(
        ax_d,
        xs,
        done[: t + 1],
        "#1f77b4",
        "Done",
        "black",
        (0.0, 1.0),
        show_xlabel=True,
    )

    plt.setp(ax_v.get_xticklabels(), visible=False)
    plt.setp(ax_c.get_xticklabels(), visible=False)

    fig.patch.set_facecolor("white")
    fig.canvas.draw()
    w_px, h_px = fig.canvas.get_width_height()
    buf = np.asarray(fig.canvas.buffer_rgba())
    buf = buf.reshape(h_px, w_px, 4)[..., :3].copy()
    plt.close(fig)
    # 部分编码器要求宽高为 16 的倍数,避免 imageio 拉伸告警
    h, w = buf.shape[:2]
    nh = (h + 15) // 16 * 16
    nw = (w + 15) // 16 * 16
    if nh != h or nw != w:
        buf = np.pad(buf, ((0, nh - h), (0, nw - w), (0, 0)), mode="edge")
    return buf


def build_video(
    frames_dir: Path,
    csv_path: Path,
    out_mp4: Path,
    fps: float = 8.0,
    figsize: tuple[float, float] = (12.0, 5.5),
    dpi: int = 120,
) -> Path:
    frame_paths = load_frames_dir(frames_dir)
    n = len(frame_paths)

    value, critic, done = load_metrics_csv(csv_path)
    value, critic, done = align_metrics_to_frame_count(n, value, critic, done)

    out_mp4.parent.mkdir(parents=True, exist_ok=True)
    try:
        import imageio.v2 as imageio

        writer = imageio.get_writer(out_mp4, fps=fps, codec="libx264", quality=8)
        for t in range(n):
            rgb = render_frame(
                frame_paths[t],
                t,
                n,
                value,
                critic,
                done,
                figsize=figsize,
                dpi=dpi,
            )
            writer.append_data(rgb)
        writer.close()
    except Exception:
        import cv2

        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        first = render_frame(frame_paths[0], 0, n, value, critic, done, figsize, dpi)
        h, w = first.shape[:2]
        vw = cv2.VideoWriter(str(out_mp4), fourcc, fps, (w, h))
        for t in range(n):
            rgb = render_frame(frame_paths[t], t, n, value, critic, done, figsize, dpi)
            vw.write(cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR))
        vw.release()

    print(f"[ok] wrote {out_mp4} ({n} frames @ {fps} fps)")
    return out_mp4


def main():
    p = argparse.ArgumentParser(description="Frames + metrics -> side-by-side video (frame | plots).")
    p.add_argument(
        "--frames",
        type=Path,
        default=Path("/scratch1/home/zhicao/VLAC/evo_vlac/examples/images/test"),
        help="Directory with PNG frames (frame_*.png or numbered *.png, natural sort)",
    )
    p.add_argument(
        "--csv",
        type=Path,
        default=Path("/scratch1/home/zhicao/VLAC/2.txt"),
        help="CSV with header: index,value,critic,done",
    )
    p.add_argument(
        "-o",
        "--output",
        type=Path,
        default=Path("/scratch1/home/zhicao/VLAC/output_test_with_plots.mp4"),
        help="Output mp4 path",
    )
    p.add_argument(
        "--fps",
        type=float,
        default=5.0,
        help="Output video frame rate (lower = slower playback)",
    )
    p.add_argument("--dpi", type=int, default=120)
    args = p.parse_args()

    build_video(args.frames, args.csv, args.output, fps=args.fps, dpi=args.dpi)


if __name__ == "__main__":
    main()