File size: 13,214 Bytes
cb5f642
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
"""
Extract frames for the 238 hard cases from the CSV.

Strategy:
1. First try to find GIDs in parquet files (fast - reuses existing base64 frames)
2. Fallback: download via yt-dlp + extract with PyAV (16 frames per video)

Output: one JSON file per pair at OUTPUT_DIR/{view_gid}_{pub_gid}.json
JSON format mirrors training data messages format:
{
  "view_gid": "...",
  "pub_gid":  "...",
  "class_name": "...",
  "pred_val": 0,
  "true_val": 1,
  "source": "parquet" | "download",
  "messages": [
    {
      "role": "user",
      "content": [
        {"type": "video", "video": ["<b64_frame>", ...]},
        {"type": "text",  "text": "<metadata_json_str>"},
        {"type": "video", "video": ["<b64_frame>", ...]},
        {"type": "text",  "text": "<metadata_json_str>"}
      ]
    },
    {
      "role": "assistant",
      "content": [{"type": "text", "text": "{\"label\": 1}"}]
    }
  ]
}
"""

import argparse
import base64
import csv
import glob
import io
import json
import os
import subprocess
import sys
import traceback
from pathlib import Path

import pyarrow.parquet as pq
from PIL import Image

# ── config ─────────────────────────────────────────────────────────────────────

CSV_PATH   = "/mnt/bn/bohanzhainas1/jiashuo/code/active_reason/4kwζ ‘ζ¨‘εž‹ζ ‡ι”™case-εž‚η±» - jiashuo_analyzed.csv"
PARQUET_DIR = "/mnt/hdfs/byte_tt_data_cu_vagcp/haogeng.liu/new_policy7w_v2_reformat"
OUTPUT_DIR  = Path("/mlx/users/jiashuo.fan/playground/inference/active_cases/frames_cache")
VIDEO_DIR   = Path("/mnt/bn/bohanzhainas1/jiashuo/tmp/active_cases_videos")
N_FRAMES    = 16   # frames per video


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

def load_csv():
    rows = []
    with open(CSV_PATH, encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append({
                "view_gid":  str(row["view_gid"]).strip(),
                "pub_gid":   str(row["pub_gid"]).strip(),
                "pred_val":  int(row["pred_val"]),
                "true_val":  int(row["true_val"]),
                "class_name": str(row["class_name"]).strip(),
            })
    return rows


def build_gid_index(parquet_dir: str) -> dict:
    """
    Build a mapping: (view_gid, pub_gid) -> (parquet_file, row_index)
    Scans all parquet files; may take a few minutes for 379 files.
    """
    print(f"Building GID index from {parquet_dir} ...")
    files = sorted(glob.glob(f"{parquet_dir}/*.parquet"))
    index = {}
    for file_idx, pf in enumerate(files):
        if file_idx % 50 == 0:
            print(f"  Scanning file {file_idx}/{len(files)} ...", flush=True)
        try:
            table = pq.read_table(pf, columns=["extra_info"])
            for row_idx in range(len(table)):
                raw = table.slice(row_idx, 1).to_pydict()["extra_info"][0]
                extra = json.loads(raw)
                v_gid = str(extra.get("video1", {}).get("gid", ""))
                p_gid = str(extra.get("video2", {}).get("gid", ""))
                key = (v_gid, p_gid)
                if key not in index:
                    index[key] = (pf, row_idx)
        except Exception as e:
            print(f"  Warning: error reading {pf}: {e}", flush=True)
    print(f"Index built: {len(index)} unique pairs", flush=True)
    return index


def load_from_parquet(pf: str, row_idx: int) -> dict:
    """Load the full row (messages + extra_info) from parquet."""
    table = pq.read_table(pf, columns=["messages", "extra_info"])
    row = table.slice(row_idx, 1).to_pydict()
    msgs  = json.loads(row["messages"][0])
    extra = json.loads(row["extra_info"][0])
    return msgs, extra


# ── video download & frame extraction ─────────────────────────────────────────

def download_video(gid: str, out_path: Path) -> bool:
    if out_path.exists() and out_path.stat().st_size > 10_000:
        return True
    out_path.parent.mkdir(parents=True, exist_ok=True)
    url = f"https://www.tiktok.com/@any/video/{gid}"
    cmd = [
        "yt-dlp", "-f", "bestvideo+bestaudio/best",
        "--merge-output-format", "mp4",
        "-o", str(out_path),
        "--no-playlist", "--quiet", "--no-warnings",
        url,
    ]
    try:
        subprocess.run(cmd, capture_output=True, text=True, timeout=120, check=False)
    except subprocess.TimeoutExpired:
        return False
    return out_path.exists() and out_path.stat().st_size > 10_000


def extract_frames_from_video(video_path: Path, n: int = N_FRAMES) -> list[str]:
    """Extract n evenly-spaced frames; return list of base64-encoded JPEG strings."""
    import av
    container = av.open(str(video_path))
    if not container.streams.video:
        container.close()
        return []
    stream = container.streams.video[0]
    total = stream.frames or 0

    if total == 0:
        for _ in container.decode(stream):
            total += 1
        container.seek(0)
        container = av.open(str(video_path))
        stream = container.streams.video[0]

    target_idxs = set(int(i * total / n) for i in range(n))
    b64_frames = []
    frame_idx  = 0
    for frame in container.decode(stream):
        if frame_idx in target_idxs:
            img = frame.to_image().convert("RGB")
            # Resize to max 512px wide to keep size reasonable
            w, h = img.size
            if w > 512:
                img = img.resize((512, int(h * 512 / w)), Image.LANCZOS)
            buf = io.BytesIO()
            img.save(buf, format="JPEG", quality=85)
            b64_frames.append(base64.b64encode(buf.getvalue()).decode())
            if len(b64_frames) >= n:
                break
        frame_idx += 1
    container.close()
    return b64_frames


def make_metadata_text(extra_video: dict) -> str:
    """Build the text metadata JSON string matching training format."""
    return json.dumps({
        "asr":                  extra_video.get("asr", "[]"),
        "key_words":            extra_video.get("key_words", "[]"),
        "mt_diversity_tier3_tags": extra_video.get("mt_diversity_tier3_tags", ""),
        "ocr":                  extra_video.get("ocr", ""),
        "sticker_texts":        extra_video.get("sticker_texts", "[]"),
        "video_caption_v2":     extra_video.get("video_caption_v2", ""),
    }, ensure_ascii=False)


def build_sample_from_parquet(msgs: list, extra: dict, csv_row: dict) -> dict:
    """Use frames from parquet directly; keep original message structure."""
    return {
        "view_gid":  csv_row["view_gid"],
        "pub_gid":   csv_row["pub_gid"],
        "class_name": csv_row["class_name"],
        "pred_val":  csv_row["pred_val"],
        "true_val":  csv_row["true_val"],
        "source":    "parquet",
        "messages":  msgs,
    }


def build_sample_from_download(
    view_b64_frames: list[str],
    pub_b64_frames:  list[str],
    csv_row:         dict,
    view_extra:      dict | None = None,
    pub_extra:       dict | None = None,
) -> dict:
    """Build messages structure from freshly downloaded frames (no metadata)."""
    view_meta_text = make_metadata_text(view_extra or {})
    pub_meta_text  = make_metadata_text(pub_extra  or {})

    msgs = [
        {
            "role": "user",
            "content": [
                {"type": "video", "video": view_b64_frames},
                {"type": "text",  "text":  view_meta_text},
                {"type": "video", "video": pub_b64_frames},
                {"type": "text",  "text":  pub_meta_text},
            ],
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": json.dumps({"label": csv_row["true_val"]})}],
        },
    ]
    return {
        "view_gid":  csv_row["view_gid"],
        "pub_gid":   csv_row["pub_gid"],
        "class_name": csv_row["class_name"],
        "pred_val":  csv_row["pred_val"],
        "true_val":  csv_row["true_val"],
        "source":    "download",
        "messages":  msgs,
    }


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

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--skip-parquet", action="store_true", default=True,
                        help="Skip parquet search (default=True; the hard-case GIDs are "
                             "likely not in the training parquet). Use --no-skip-parquet "
                             "to force a full scan of 379 parquet files.")
    parser.add_argument("--no-skip-parquet", dest="skip_parquet", action="store_false",
                        help="Force scan of all parquet files for GID matches")
    parser.add_argument("--skip-download", action="store_true",
                        help="Skip download fallback (only use parquet hits)")
    parser.add_argument("--output-dir", default=str(OUTPUT_DIR))
    args = parser.parse_args()

    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    csv_rows = load_csv()
    print(f"Loaded {len(csv_rows)} rows from CSV", flush=True)

    # Load already-done pairs
    done = set()
    for f in out_dir.glob("*.json"):
        done.add(f.stem)  # stem = "{view_gid}_{pub_gid}"
    if done:
        print(f"Resuming: {len(done)} already extracted", flush=True)

    pending = [r for r in csv_rows if f"{r['view_gid']}_{r['pub_gid']}" not in done]
    print(f"Pending: {len(pending)}", flush=True)

    if not pending:
        print("All done!", flush=True)
        return

    # Build GID index from parquet (unless --skip-parquet)
    gid_index = {}
    if not args.skip_parquet:
        gid_index = build_gid_index(PARQUET_DIR)

    stats = {"parquet": 0, "download": 0, "failed": 0}

    for i, row in enumerate(pending):
        key      = f"{row['view_gid']}_{row['pub_gid']}"
        out_path = out_dir / f"{key}.json"
        print(f"[{i+1}/{len(pending)}] {key} ({row['class_name']})", flush=True)

        sample = None

        # --- Try parquet first ---
        if not args.skip_parquet:
            parquet_key = (row["view_gid"], row["pub_gid"])
            if parquet_key in gid_index:
                pf, row_idx = gid_index[parquet_key]
                try:
                    msgs, extra = load_from_parquet(pf, row_idx)
                    sample = build_sample_from_parquet(msgs, extra, row)
                    stats["parquet"] += 1
                    print(f"  -> parquet hit: {Path(pf).name}[{row_idx}]", flush=True)
                except Exception as e:
                    print(f"  -> parquet load error: {e}", flush=True)

        # --- Fallback: download ---
        if sample is None and not args.skip_download:
            try:
                pair_dir = VIDEO_DIR / key
                pair_dir.mkdir(parents=True, exist_ok=True)
                view_mp4 = pair_dir / f"view_{row['view_gid']}.mp4"
                pub_mp4  = pair_dir / f"pub_{row['pub_gid']}.mp4"

                view_ok = download_video(row["view_gid"], view_mp4)
                pub_ok  = download_video(row["pub_gid"],  pub_mp4)

                if view_ok and pub_ok:
                    view_frames = extract_frames_from_video(view_mp4, N_FRAMES)
                    pub_frames  = extract_frames_from_video(pub_mp4,  N_FRAMES)
                    if view_frames and pub_frames:
                        sample = build_sample_from_download(
                            view_frames, pub_frames, row
                        )
                        stats["download"] += 1
                        print(f"  -> downloaded: {len(view_frames)}+{len(pub_frames)} frames",
                              flush=True)
                    else:
                        print(f"  -> frame extraction failed", flush=True)
                else:
                    print(f"  -> download failed: view={view_ok} pub={pub_ok}", flush=True)
            except Exception as e:
                print(f"  -> download/extract error: {traceback.format_exc()[:300]}", flush=True)

        if sample is None:
            # Save a stub so we know it failed
            sample = {
                "view_gid":  row["view_gid"],
                "pub_gid":   row["pub_gid"],
                "class_name": row["class_name"],
                "pred_val":  row["pred_val"],
                "true_val":  row["true_val"],
                "source":    "failed",
                "messages":  [],
            }
            stats["failed"] += 1
            print(f"  -> FAILED (no frames available)", flush=True)

        out_path.write_text(json.dumps(sample, ensure_ascii=False))

    print(f"\nDone. parquet={stats['parquet']}  download={stats['download']}  "
          f"failed={stats['failed']}")
    print(f"Output: {out_dir}")


if __name__ == "__main__":
    main()