""" 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): { "消费视频主题": "", "投稿视频主题": "", "主题相似": "", "相似元素": [""], "reasoning": "", "model_error_analysis": "" }""" # ── 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()