File size: 13,345 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
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
"""
Download TikTok video pairs from jiashuo.csv, extract frames,
analyze with Claude (vision), and write results to new CSV.

Output:
  /mnt/bn/bohanzhainas1/jiashuo/tmp/proactive_publish_20260313/
    {view_gid}_{pub_gid}/
      view_{view_gid}.mp4
      pub_{pub_gid}.mp4
      view_frames/frame_00..15.jpg
      pub_frames/frame_00..15.jpg
      analysis.json
  result_jiashuo.csv   (same dir as input CSV)
"""

import os, io, json, base64, subprocess, traceback
from pathlib import Path
from datetime import datetime
import pandas as pd
from PIL import Image
import google.genai as genai
from google.genai import types

# ── config ────────────────────────────────────────────────────────────────────
GEMINI_API_KEY = "AIzaSyD9VmJvG__n5xCJELIUtCK343w_pQUZjXc"
INPUT_CSV  = "/mnt/bn/bohanzhainas1/jiashuo/code/active_reason/4kwζ ‘ζ¨‘εž‹ζ ‡ι”™case-εž‚η±» - jiashuo.csv"
OUTPUT_CSV = "/mnt/bn/bohanzhainas1/jiashuo/code/active_reason/4kwζ ‘ζ¨‘εž‹ζ ‡ι”™case-εž‚η±» - jiashuo_analyzed.csv"
WORK_DIR   = Path("/mnt/bn/bohanzhainas1/jiashuo/tmp/proactive_publish_20260313")
N_FRAMES   = 8   # frames per video sent to Claude

POLICY_PROMPT = """You are analyzing a pair of TikTok videos to determine their similarity relationship for a "Proactive Publish" attribution task. The goal is to judge whether the "consumption video" (video 1, what a user watched) likely CAUSED or INSPIRED the user to create the "publish video" (video 2, what they then posted).

## Theme Similarity Options (pick exactly one):
1. **ζœ€ε…·ε› ζžœζ€§** (Most causal) - strongest evidence of causation. Applies when:
   - Same song lipsync or dance/fingerdance
   - Same game challenge / randomizer / special effect
   - Same meme or viral format/ηŽ©ζ³• (recognizable challenge or template)

2. **η»†η²’εΊ¦δΈ»ι’˜η›ΈδΌΌ** (Fine-grained thematic similarity) - same specific interest vertical but causation is uncertain. Examples: pet cats/dogs, cars, FPS gaming, cooking, home decoration, concerts, football, fitness, cosplay, health tips, music/instrument performance

3. **ζŠ½θ±‘δΈ»ι’˜η›ΈδΌΌ** (Abstract thematic similarity) - broad category match or same vertical with different attributes. Examples: OOTD, dancing, lipsync (generic), vlog, scenery, travel, emotions/romance, family, music videos, makeup; OR same vertical but different sub-type (different game genres, different food preparations, different sports)

4. **ιƒ½ζ˜―θ‡ͺ拍/他拍/ιšζ‹** (Both are casual/selfie/random shoots) - similar casual format

5. **δΈ»ι’˜δΈη›Έε…³** (Irrelevant) - no meaningful thematic connection

6. **δΈε―ηœ‹** (Cannot assess) - video unavailable or unviewable

## Similar Elements (select ALL that apply, can be empty):
- **η”»ι£Žε‘ˆηŽ°** (Visual style/presentation): same transition type, same template/filter/sticker, same split-screen layout
- **音乐** (Music): same background music or song
- **θ―­ε₯ζ–‡ζ‘ˆ** (Text/copywriting): same or highly similar text overlays, titles (non-hashtag), or spoken phrases (β‰₯70% match, or same fill-in-the-blank format)
- **拍摄对豑** (Subject of shooting): same IP (game/film/celebrity/sports team), same identity type (couple/nurse/footballer), same specific object (specific car model, cat breed, etc.) β€” judged by scene/environment/costume, NOT by action
- **δΈ»δ½“θ‘ŒδΈΊ/归态** (How the subject acts): same specific creative action/behavior that is non-trivial and independent of subject identity

## Important rules:
- Causal relationship vs correlation: if two videos share the same meme/challenge/song, that's causal. If they're just in the same broad category, that's correlational.
- For 拍摄对豑 vs δΈ»δ½“θ‘ŒδΈΊ: if the behavior is a natural/expected part of the subject's identity (couple being affectionate, Cristiano Ronaldo playing football), only mark 拍摄对豑. If the behavior is a specific creative act independent of identity, mark δΈ»δ½“θ‘ŒδΈΊ.

## Output format (JSON only, no other text, no comments):
{
  "ζΆˆθ΄Ήθ§†ι’‘δΈ»ι’˜": "<one sentence describing video 1 content>",
  "ζŠ•η¨Ώθ§†ι’‘δΈ»ι’˜": "<one sentence describing video 2 content>",
  "δΈ»ι’˜η›ΈδΌΌ": "<one of: ζœ€ε…·ε› ζžœζ€§ | η»†η²’εΊ¦δΈ»ι’˜η›ΈδΌΌ | ζŠ½θ±‘δΈ»ι’˜η›ΈδΌΌ | ιƒ½ζ˜―θ‡ͺ拍/他拍/ιšζ‹ | δΈ»ι’˜δΈη›Έε…³ | δΈε―ηœ‹>",
  "η›ΈδΌΌε…ƒη΄ ": ["<element1>"],
  "reasoning": "<brief explanation of your similarity judgment>",
  "model_error_analysis": "<why did the ML model get this wrong? What features signal similarity that a model might miss? e.g. same niche meme/audio that requires cultural knowledge, subtle visual template reuse, same specific challenge that looks superficially different, etc. Be specific about the failure mode.>"
}"""


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

def download_video(gid: int, out_path: Path) -> bool:
    if out_path.exists() and out_path.stat().st_size > 10_000:
        return 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
    ]
    result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
    return out_path.exists() and out_path.stat().st_size > 10_000


def extract_frames(video_path: Path, frames_dir: Path, n: int = N_FRAMES) -> list[Path]:
    frames_dir.mkdir(parents=True, exist_ok=True)
    existing = sorted(frames_dir.glob("frame_*.jpg"))
    if len(existing) >= n:
        return existing[:n]

    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:
        # fallback: count by decoding (only pts)
        for f in container.decode(stream):
            total += 1
        container.seek(0)

    # Pick target frame indices
    target_idxs = set(int(i * total / n) for i in range(n))

    frames_out = []
    frame_idx = 0
    saved = 0
    for frame in container.decode(stream):
        if frame_idx in target_idxs:
            out_path = frames_dir / f"frame_{saved:02d}.jpg"
            frame.to_image().convert("RGB").save(out_path, "JPEG", quality=85)
            frames_out.append(out_path)
            saved += 1
            if saved >= n:
                break
        frame_idx += 1
    container.close()

    return frames_out


def frames_to_b64(frame_paths: list[Path]) -> list[str]:
    result = []
    for p in frame_paths:
        img = Image.open(p).convert("RGB")
        # Resize to max 512px wide to save tokens
        w, h = img.size
        if w > 512:
            img = img.resize((512, int(h * 512 / w)), Image.LANCZOS)
        import io
        buf = io.BytesIO()
        img.save(buf, format="JPEG", quality=80)
        result.append(base64.standard_b64encode(buf.getvalue()).decode())
    return result


def analyze_with_gemini(view_mp4: Path, pub_mp4: Path, class_name: str) -> dict:
    client = genai.Client(api_key=GEMINI_API_KEY)

    def upload_video(path: Path):
        with open(path, "rb") as f:
            data = f.read()
        return types.Part.from_bytes(data=data, mime_type="video/mp4")

    view_part = upload_video(view_mp4)
    pub_part  = upload_video(pub_mp4)

    prompt = (
        f"Video 1 is the **consumption video** (class: {class_name}), "
        f"Video 2 is the **publish video**.\n\n"
        "The ML model predicted these two videos are NOT causally related (pred=0), "
        "but human annotators labeled them as related (true=1). "
        "Analyze their similarity according to the policy, and specifically explain "
        "why the model might have failed to detect the relationship. "
        "Output JSON only, no markdown fences."
    )

    response = client.models.generate_content(
        model="gemini-2.5-flash",
        contents=[
            view_part,
            pub_part,
            prompt,
        ],
        config=types.GenerateContentConfig(
            system_instruction=POLICY_PROMPT,
            max_output_tokens=2048,
            temperature=0.1,
            response_mime_type="application/json",
        ),
    )

    raw = response.text.strip()
    # Strip markdown code fences
    if "```" in raw:
        import re
        m = re.search(r"```(?:json)?\s*([\s\S]+?)```", raw)
        if m:
            raw = m.group(1).strip()
    return json.loads(raw)


def make_holmes_link(view_gid: int, pub_gid: int) -> str:
    return (
        f"https://holmes.tiktok-row.net/tiktok-debug/tiktok/video/batch"
        f"?model=Full&video_ids={view_gid}_v1,{pub_gid}_v1"
    )


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

def main():
    WORK_DIR.mkdir(parents=True, exist_ok=True)

    df = pd.read_csv(INPUT_CSV)
    df = df[['view_gid', 'pub_gid', 'pred_val', 'true_val', 'class_name']].copy()
    df['view_gid'] = df['view_gid'].astype(str).str.strip()
    df['pub_gid']  = df['pub_gid'].astype(str).str.strip()

    # Load existing results to resume
    results = []
    done_pairs = set()
    if Path(OUTPUT_CSV).exists():
        existing = pd.read_csv(OUTPUT_CSV)
        for _, r in existing.iterrows():
            key = (str(r['view_gid']), str(r['pub_gid']))
            done_pairs.add(key)
            results.append(r.to_dict())
        print(f"Resuming: {len(done_pairs)} already done")

    total = len(df)
    for i, row in df.iterrows():
        view_gid   = str(row['view_gid'])
        pub_gid    = str(row['pub_gid'])
        class_name = str(row['class_name'])
        key = (view_gid, pub_gid)

        if key in done_pairs:
            continue

        print(f"[{i+1}/{total}] {view_gid} / {pub_gid} ({class_name})")

        pair_dir = WORK_DIR / f"{view_gid}_{pub_gid}"
        pair_dir.mkdir(parents=True, exist_ok=True)

        result_row = {
            'view_gid':   view_gid,
            'pub_gid':    pub_gid,
            'pred_val':   row['pred_val'],
            'true_val':   row['true_val'],
            'class_name': class_name,
            'Holmesι“ΎζŽ₯': make_holmes_link(view_gid, pub_gid),
            'ζΆˆθ΄Ήθ§†ι’‘δΈ»ι’˜': '',
            'ζŠ•η¨Ώθ§†ι’‘δΈ»ι’˜': '',
            'δΈ»ι’˜η›ΈδΌΌ':   '',
            'η›ΈδΌΌε…ƒη΄ ':   '',
            'ε…Άδ»–':       '',
            'ζ ‡ι”™εŽŸε› εˆ†ζž': '',
        }

        try:
            # 1. Download videos
            view_mp4 = pair_dir / f"view_{view_gid}.mp4"
            pub_mp4  = pair_dir / f"pub_{pub_gid}.mp4"
            view_ok  = download_video(int(view_gid), view_mp4)
            pub_ok   = download_video(int(pub_gid),  pub_mp4)

            if not view_ok or not pub_ok:
                result_row['ε…Άδ»–'] = f'download_failed: view={view_ok} pub={pub_ok}'
                result_row['δΈ»ι’˜η›ΈδΌΌ'] = 'δΈε―ηœ‹'
                print(f"  ⚠ download failed")
                results.append(result_row)
                done_pairs.add(key)
                _save(results, OUTPUT_CSV)
                continue

            # 2. Extract frames
            view_frames = extract_frames(view_mp4, pair_dir / "view_frames")
            pub_frames  = extract_frames(pub_mp4,  pair_dir / "pub_frames")

            if not view_frames or not pub_frames:
                result_row['ε…Άδ»–'] = 'frame_extraction_failed'
                result_row['δΈ»ι’˜η›ΈδΌΌ'] = 'δΈε―ηœ‹'
                print(f"  ⚠ frame extraction failed")
                results.append(result_row)
                done_pairs.add(key)
                _save(results, OUTPUT_CSV)
                continue

            # 3. Analyze with Gemini (native video)
            analysis = analyze_with_gemini(view_mp4, pub_mp4, class_name)

            result_row['ζΆˆθ΄Ήθ§†ι’‘δΈ»ι’˜'] = analysis.get('ζΆˆθ΄Ήθ§†ι’‘δΈ»ι’˜', '')
            result_row['ζŠ•η¨Ώθ§†ι’‘δΈ»ι’˜'] = analysis.get('ζŠ•η¨Ώθ§†ι’‘δΈ»ι’˜', '')
            result_row['δΈ»ι’˜η›ΈδΌΌ']     = analysis.get('δΈ»ι’˜η›ΈδΌΌ', '')
            result_row['η›ΈδΌΌε…ƒη΄ ']     = ', '.join(analysis.get('η›ΈδΌΌε…ƒη΄ ', []))
            result_row['ε…Άδ»–']         = analysis.get('reasoning', '')
            result_row['ζ ‡ι”™εŽŸε› εˆ†ζž'] = analysis.get('model_error_analysis', '')

            # Save analysis json
            (pair_dir / "analysis.json").write_text(
                json.dumps(analysis, ensure_ascii=False, indent=2)
            )
            print(f"  βœ“ {result_row['δΈ»ι’˜η›ΈδΌΌ']} | {result_row['η›ΈδΌΌε…ƒη΄ ']}")

        except Exception as e:
            result_row['ε…Άδ»–'] = f'error: {traceback.format_exc()[:300]}'
            print(f"  βœ— {e}")

        results.append(result_row)
        done_pairs.add(key)
        _save(results, OUTPUT_CSV)

    print(f"\nDone. Results: {OUTPUT_CSV}")


def _save(results: list, path: str):
    pd.DataFrame(results).to_csv(path, index=False)


if __name__ == "__main__":
    main()