File size: 10,201 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
"""
Label video pairs using Claude CLI in parallel.

Usage:
  # Test 20 samples with 10 workers
  python3 label_parallel.py --test 20 --workers 10

  # Full run
  python3 label_parallel.py --max-samples 0 --workers 15
"""

import argparse
import json
import os
import subprocess
import time
import glob
import re
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed

import pyarrow.parquet as pq

# ── Config ──
SAVE_INTERVAL = 100
MAX_RETRIES = 3
MODEL = "claude-haiku-4-5-20251001"

SYSTEM_PROMPT = """You are an expert at determining whether two TikTok videos are thematically similar.
Given metadata for two videos (video captions, keywords, category tags), determine:
1. Whether they are similar (label: 1) or not (label: 0)
2. The type of thematic similarity
3. Which elements are similar

Respond ONLY with a JSON object:
{"similar_theme": "<theme_type>", "similar_elements": <elements_list>, "label": <0_or_1>}

similar_theme values:
- "Fine-grained thematic similarity": Very specific thematic overlap (label=1)
- "General thematic similarity": Broad category overlap, label=1 only if meaningful shared elements
- "Irrelevant": Not similar (label=0)

similar_elements (pick from):
- "Subject of shooting", "How the subject acts", "Art style presentation", "Music", "Sentence and copywriting", "None of the above are similar"

If label=0, similar_elements=["None of the above are similar"].
Output ONLY the JSON."""


def build_user_prompt(msgs):
    texts = []
    for item in msgs[0]["content"]:
        if item["type"] == "text":
            texts.append(item["text"])
    if len(texts) == 2:
        return f"Video 1 metadata:\n{texts[0]}\n\nVideo 2 metadata:\n{texts[1]}"
    elif len(texts) == 1:
        return f"Video pair metadata:\n{texts[0]}"
    return "\n\n".join(f"Metadata {i+1}:\n{t}" for i, t in enumerate(texts))


def call_claude_single(args_tuple):
    """Worker function for ProcessPoolExecutor. Takes (key, prompt, gt) tuple."""
    key, prompt, gt = args_tuple
    full_prompt = f"{SYSTEM_PROMPT}\n\n{prompt}"

    for attempt in range(MAX_RETRIES):
        try:
            result = subprocess.run(
                ["claude", "-p", "--model", MODEL, "--max-turns", "1"],
                input=full_prompt,
                capture_output=True,
                text=True,
                timeout=90,
            )
            text = result.stdout.strip()
            if not text:
                if attempt < MAX_RETRIES - 1:
                    time.sleep(2)
                    continue
                return {"key": key, "error": f"empty response", "gt": gt, "est_tokens": 0}

            # Parse JSON
            clean = text
            if "```" in clean:
                m = re.search(r"```(?:json)?\s*([\s\S]+?)```", clean)
                if m:
                    clean = m.group(1).strip()

            # Find JSON object
            for s in range(len(clean)):
                if clean[s] == '{':
                    for e in range(len(clean), s, -1):
                        if clean[e-1] == '}':
                            try:
                                parsed = json.loads(clean[s:e])
                                est_tokens = (len(full_prompt) + len(text)) // 4
                                pred_label = parsed.get("label")
                                gt_label = gt.get("label") if gt else None
                                match = (pred_label == gt_label) if (pred_label is not None and gt_label is not None) else None
                                return {
                                    "key": key, "pred": parsed, "gt": gt,
                                    "match": match, "est_tokens": est_tokens,
                                }
                            except json.JSONDecodeError:
                                continue

            return {"key": key, "error": f"no JSON: {text[:150]}", "gt": gt, "est_tokens": 0}

        except subprocess.TimeoutExpired:
            if attempt < MAX_RETRIES - 1:
                time.sleep(2)
                continue
            return {"key": key, "error": "timeout", "gt": gt, "est_tokens": 0}
        except Exception as e:
            if attempt < MAX_RETRIES - 1:
                time.sleep(1)
                continue
            return {"key": key, "error": str(e), "gt": gt, "est_tokens": 0}

    return {"key": key, "error": "max retries", "gt": gt, "est_tokens": 0}


def load_samples(data_dir, max_samples=0):
    all_files = sorted(glob.glob(f"{data_dir}/*.parquet"))
    if not all_files:
        raise FileNotFoundError(f"No parquet files in {data_dir}")
    samples = []
    for pf in all_files:
        table = pq.read_table(pf, columns=["messages", "extra_info"])
        fname = Path(pf).stem
        for i in range(len(table)):
            row = table.slice(i, 1).to_pydict()
            msgs = json.loads(row["messages"][0])
            key = f"{fname}:{i}"
            samples.append((key, msgs))
            if max_samples > 0 and len(samples) >= max_samples:
                return samples
    return samples


def extract_gt(msgs):
    try:
        return json.loads(msgs[1]["content"][0]["text"])
    except:
        return None


def save_results(path, results, stats):
    path.write_text(json.dumps({
        "model": MODEL,
        "total_samples": len(results),
        "stats": stats,
        "results": results,
    }, ensure_ascii=False, indent=2))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--data-dir", default="/mnt/hdfs/byte_tt_data_cu_vagcp/haogeng.liu/new_policy7w_v2_reformat")
    parser.add_argument("--output", default="/mnt/bn/bohanzhainas1/jiashuo/playground/claude_label/results.json")
    parser.add_argument("--test", type=int, default=0)
    parser.add_argument("--max-samples", type=int, default=0)
    parser.add_argument("--workers", type=int, default=15)
    args = parser.parse_args()

    n = args.test if args.test > 0 else args.max_samples

    print(f"Loading samples from {args.data_dir}...")
    samples = load_samples(args.data_dir, max_samples=n if n > 0 else 0)
    print(f"Loaded {len(samples)} samples")

    out_path = Path(args.output)
    out_path.parent.mkdir(parents=True, exist_ok=True)

    # Resume
    done_keys = set()
    results = []
    if out_path.exists():
        try:
            saved = json.loads(out_path.read_text())
            results = saved.get("results", [])
            done_keys = {r["key"] for r in results if "key" in r}
            print(f"Resuming: {len(done_keys)} already done")
        except:
            pass

    # Build work items
    work = []
    for key, msgs in samples:
        if key not in done_keys:
            prompt = build_user_prompt(msgs)
            gt = extract_gt(msgs)
            work.append((key, prompt, gt))

    print(f"To process: {len(work)} with {args.workers} workers")
    if not work:
        print("Nothing to do!")
        return

    correct = sum(1 for r in results if r.get("match") is True)
    evaluated = sum(1 for r in results if r.get("match") is not None)
    total_est_tokens = sum(r.get("est_tokens", 0) for r in results)
    errors = 0
    t0 = time.time()
    processed = 0
    last_save = time.time()

    with ProcessPoolExecutor(max_workers=args.workers) as executor:
        futures = {executor.submit(call_claude_single, w): w[0] for w in work}

        for future in as_completed(futures):
            result = future.result()
            results.append(result)
            done_keys.add(result["key"])
            processed += 1
            total_est_tokens += result.get("est_tokens", 0)

            if result.get("match") is not None:
                evaluated += 1
                if result["match"]:
                    correct += 1
            if "error" in result:
                errors += 1

            # Progress every 10
            if processed % 10 == 0 or processed == len(work):
                elapsed = time.time() - t0
                speed = processed / elapsed
                acc = correct / evaluated if evaluated > 0 else 0
                remaining = len(work) - processed
                eta_h = remaining / speed / 3600 if speed > 0 else 0
                print(
                    f"[{processed}/{len(work)}] acc={acc:.3f} "
                    f"{speed:.1f}/s err={errors} "
                    f"~{total_est_tokens//1000}k tok "
                    f"ETA={eta_h:.1f}h"
                )

            # Save periodically
            if time.time() - last_save > 60 or processed % SAVE_INTERVAL == 0:
                acc = correct / evaluated if evaluated > 0 else 0
                stats = {
                    "accuracy": acc, "correct": correct, "evaluated": evaluated,
                    "errors": errors, "est_total_tokens": total_est_tokens,
                    "processed": len(results),
                }
                save_results(out_path, results, stats)
                last_save = time.time()

    # Final save
    elapsed = time.time() - t0
    acc = correct / evaluated if evaluated > 0 else 0
    stats = {
        "accuracy": acc, "correct": correct, "evaluated": evaluated,
        "errors": errors, "est_total_tokens": total_est_tokens,
        "processed": len(results), "elapsed_s": elapsed,
        "speed": processed / elapsed if elapsed > 0 else 0,
    }
    save_results(out_path, results, stats)

    print(f"\n{'='*60}")
    print(f"DONE: {len(results)} samples")
    print(f"Accuracy: {acc:.4f} ({correct}/{evaluated}), errors: {errors}")
    print(f"Est tokens: ~{total_est_tokens:,}")
    print(f"Time: {elapsed/3600:.1f}h ({processed/elapsed:.1f} samples/s)")
    print(f"Saved: {out_path}")

    if args.test > 0 and processed > 0:
        avg_tok = total_est_tokens / processed
        total_all = 48512
        speed = processed / elapsed
        print(f"\n--- Extrapolation for {total_all} samples ---")
        print(f"Avg ~{avg_tok:.0f} tokens/sample")
        print(f"Est total: ~{avg_tok * total_all / 1e6:.1f}M tokens")
        print(f"Est time @ {speed:.1f}/s with {args.workers} workers: {total_all / speed / 3600:.1f}h")


if __name__ == "__main__":
    main()