File size: 7,721 Bytes
f0d6538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Visualize 100 samples from new_policy7w_v2_reformat dataset.
Output: /mnt/bn/bohanzhainas1/jiashuo/viz/
  - samples/sample_NNN/  -> video frames + info.json
  - index.html           -> browsable HTML overview
"""

import os, json, base64, glob
import pandas as pd
from pathlib import Path

DATA_DIR = "/mnt/hdfs/byte_tt_data_cu_vagcp/haogeng.liu/new_policy7w_v2_reformat"
OUT_DIR   = Path("/mnt/bn/bohanzhainas1/jiashuo/viz")
N_SAMPLES = 100
PREVIEW_FRAMES = [0, 4, 8, 12, 15]  # frames shown in HTML (out of 16)

# ── helpers ──────────────────────────────────────────────────────────────────

def save_frames(frames_b64: list, out_dir: Path, prefix: str) -> list[str]:
    """Save all frames to disk, return relative paths."""
    paths = []
    for i, b64 in enumerate(frames_b64):
        raw = base64.b64decode(b64)
        rel = f"{prefix}_frame_{i:02d}.jpg"
        (out_dir / rel).write_bytes(raw)
        paths.append(rel)
    return paths


def parse_row(row) -> dict:
    msgs    = json.loads(row["messages"])
    extra   = json.loads(row["extra_info"])

    user_content = msgs[0]["content"]   # list of {type, video/text, ...}
    asst_content = msgs[1]["content"]   # list of {type, text}

    # extract videos and texts from user turn
    videos, user_texts = [], []
    for item in user_content:
        if item["type"] == "video":
            videos.append(item["video"])       # list of 16 base64 strings
        elif item["type"] == "text":
            user_texts.append(item["text"])
        elif item["type"] == "image":
            videos.append([item["image"]])     # treat single-image as 1-frame video

    assistant_text = " ".join(
        c["text"] for c in asst_content if c.get("type") == "text"
    )

    return {
        "videos": videos,
        "user_texts": user_texts,
        "assistant_text": assistant_text,
        "extra_info": extra,
    }


def build_sample_dir(idx: int, parsed: dict) -> dict:
    """Save frames + info.json, return metadata for HTML."""
    sdir = OUT_DIR / "samples" / f"sample_{idx:03d}"
    sdir.mkdir(parents=True, exist_ok=True)

    frame_paths = {}   # video_idx -> [relative paths]
    for vi, frames in enumerate(parsed["videos"]):
        paths = save_frames(frames, sdir, f"video{vi+1}")
        frame_paths[vi] = paths

    info = {
        "user_texts":      parsed["user_texts"],
        "assistant":       parsed["assistant_text"],
        "extra_info":      parsed["extra_info"],
        "num_videos":      len(parsed["videos"]),
        "frames_per_video": [len(v) for v in parsed["videos"]],
    }
    (sdir / "info.json").write_text(json.dumps(info, ensure_ascii=False, indent=2))

    return {"sdir": sdir, "frame_paths": frame_paths, "info": info}


# ── HTML generation ───────────────────────────────────────────────────────────

def img_tag(sdir: Path, rel_path: str, width=160) -> str:
    abs_path = sdir / rel_path
    b64 = base64.b64encode(abs_path.read_bytes()).decode()
    return f'<img src="data:image/jpeg;base64,{b64}" width="{width}" style="border-radius:4px;margin:2px">'


def json_block(obj) -> str:
    if isinstance(obj, str):
        try:
            obj = json.loads(obj)
        except Exception:
            pass
    text = json.dumps(obj, ensure_ascii=False, indent=2) if not isinstance(obj, str) else obj
    return f'<pre style="white-space:pre-wrap;word-break:break-word;font-size:12px;background:#f5f5f5;padding:8px;border-radius:4px;max-height:300px;overflow-y:auto">{text}</pre>'


def render_sample_html(idx: int, meta: dict) -> str:
    sdir        = meta["sdir"]
    frame_paths = meta["frame_paths"]
    info        = meta["info"]

    # video strips (only PREVIEW_FRAMES)
    video_html = ""
    for vi, paths in frame_paths.items():
        preview = [paths[i] for i in PREVIEW_FRAMES if i < len(paths)]
        imgs    = "".join(img_tag(sdir, p) for p in preview)
        video_html += f"""
        <div style="margin-bottom:8px">
          <b>Video {vi+1}</b> ({len(paths)} frames, showing {len(preview)}):
          <div>{imgs}</div>
        </div>"""

    # user texts
    user_text_html = ""
    for i, t in enumerate(info["user_texts"]):
        label = f"Video {i+1} metadata" if i < len(frame_paths) else f"Text {i+1}"
        user_text_html += f"<b>{label}:</b>{json_block(t)}"

    # assistant
    asst_html = json_block(info["assistant_text"])

    # extra_info
    extra = info["extra_info"]
    extra_sections = ""
    for key in ["video1", "video2"]:
        if key in extra:
            v = extra[key]
            extra_sections += f"<b>extra_info.{key}:</b>{json_block(v)}"
    for key in [k for k in extra if k not in ("video1", "video2")]:
        extra_sections += f"<b>extra_info.{key}:</b> <code>{extra[key]}</code><br>"

    return f"""
  <div id="s{idx}" style="border:1px solid #ddd;border-radius:8px;padding:16px;margin-bottom:24px;background:#fff">
    <h3 style="margin:0 0 12px 0;color:#333">Sample {idx:03d}
      <a href="samples/sample_{idx:03d}/info.json" target="_blank"
         style="font-size:12px;margin-left:8px;color:#888">[info.json]</a>
    </h3>
    <div style="display:flex;gap:24px;flex-wrap:wrap">
      <div style="flex:1;min-width:340px">
        <b>Videos:</b>
        {video_html}
      </div>
      <div style="flex:2;min-width:340px">
        <b>User texts:</b>
        {user_text_html}
        <b>Assistant:</b>
        {asst_html}
        {extra_sections}
      </div>
    </div>
  </div>"""


# ── main ─────────────────────────────────────────────────────────────────────

def main():
    parquet_files = sorted(glob.glob(f"{DATA_DIR}/*.parquet"))
    print(f"Found {len(parquet_files)} parquet files")

    samples_html = []
    count = 0

    for pf in parquet_files:
        if count >= N_SAMPLES:
            break
        df = pd.read_parquet(pf)
        for _, row in df.iterrows():
            if count >= N_SAMPLES:
                break
            print(f"  Processing sample {count:03d} ...", end="\r")
            try:
                parsed = parse_row(row)
                meta   = build_sample_dir(count, parsed)
                html   = render_sample_html(count, meta)
                samples_html.append(html)
            except Exception as e:
                samples_html.append(f'<div style="color:red">Sample {count}: ERROR - {e}</div>')
            count += 1

    print(f"\nProcessed {count} samples")

    page = f"""<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>new_policy7w_v2_reformat β€” {count} samples</title>
  <style>
    body {{ font-family: sans-serif; max-width: 1400px; margin: 0 auto; padding: 24px; background: #f9f9f9; }}
    h1   {{ color: #222; }}
    code {{ background: #eee; padding: 2px 4px; border-radius: 3px; font-size: 12px; }}
  </style>
</head>
<body>
  <h1>Dataset: new_policy7w_v2_reformat</h1>
  <p>Showing <b>{count}</b> samples &nbsp;|&nbsp;
     Each sample: 2 videos (16 frames each) + metadata texts + assistant label<br>
     Full frames + info.json saved under <code>samples/sample_NNN/</code></p>
  {"".join(samples_html)}
</body>
</html>"""

    out_html = OUT_DIR / "index.html"
    out_html.write_text(page, encoding="utf-8")
    print(f"Saved: {out_html}")
    print(f"Samples dir: {OUT_DIR / 'samples'}")


if __name__ == "__main__":
    main()