File size: 24,392 Bytes
49654fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
#!/usr/bin/env python3
"""商品标注:粗筛 → 三模型精标 → 多数投票与 Sonnet 仲裁。"""
import argparse
import json
import re
import subprocess
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path

from utils import parse_grade as parse_result


SYSTEM_PROMPT = "你是一个商品相关性精评助手。只输出 JSON 对象,不要输出任何解释或其他内容。"


VALID_GRADES = {"L1", "L2", "hard_neg_lookalike", "hard_neg_constraint", "irrelevant"}


_write_lock = threading.Lock()


def log(msg):
    print(msg, flush=True)


def load_jsonl(path):
    rows = []
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                rows.append(json.loads(line))
    return rows


def cand_key(rec):
    return f'{rec["idx"]}|{rec["item_id"]}'


def load_done(path):
    done = set()
    if not path.exists():
        return done
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                r = json.loads(line)
                done.add(cand_key(r))
            except (json.JSONDecodeError, KeyError):
                continue
    return done


def append_jsonl(path, obj):
    with _write_lock:
        with open(path, "a", encoding="utf-8") as f:
            f.write(json.dumps(obj, ensure_ascii=False) + "\n")
            f.flush()


def load_scenes(path):
    return {str(row["idx"]): {"question": row["query"], **row["scene"]}
            for row in load_jsonl(path)}


def load_corpus(path):
    return {str(row["item_id"]): row for row in load_jsonl(path)}


def load_captions(path):
    return {str(row["item_id"]): row["caption"] for row in load_jsonl(path)}


# 1. 粗筛。
COARSE_FILTER_PROMPT = """用户拍了一张图并提出需求,想买商品来解决。给你一个候选商品,只做宽松粗筛,区分“完全不沾边”和“沾边或可能有用”。

# 判断标准
- keep:商品与需求涉及的对象、用途或场景有联系,或可能有用。
- discard:商品与需求完全不沾边,明显没有关联(如:要保养玉石 → 却是厨房模具)。

# 注意
- 只排除完全无关的商品。商品可能有用、或你无法确定是否有关联时,一律 keep。
- 综合参考商品标题和类目;不要仅因类目不同就 discard,不同类目的商品也可能与需求有关联。

# 示例1
【用户】
图像内容:翡翠(或玉石)圆形平安扣吊坠,颜色为淡绿色,成色较浅,配有18K金扣头,整体品相较新
用户意图:寻找适合保养玉石/翡翠吊坠的养护用品
【商品】
标题:家用烘焙硅胶蛋糕模具 六连马芬杯
商品类目:厨房用品-烘焙用具-蛋糕模具
【输出】
{{"decision": "discard", "reason": "商品为烘焙蛋糕模具,与玉石保养完全无关"}}

# 示例2
【用户】
图像内容:翡翠(或玉石)圆形平安扣吊坠,颜色为淡绿色,成色较浅,配有18K金扣头,整体品相较新
用户意图:寻找适合保养玉石/翡翠吊坠的养护用品
【商品】
标题:铸固黄白抛光布轮首饰珠宝抛光布轮金属打磨不锈钢镜面抛光白色布
商品类目:五金-磨具-抛光轮
【输出】
{{"decision": "keep", "reason": "与珠宝养护沾边,是否适用玉石无法确定,保留"}}

# 本次输入
【用户】
图像内容:{content}
用户意图:{intent}
【商品】
标题:{title}
商品类目:{category}
【输出】
"""


def parse_decision(raw):
    match = re.search(r"\{.*?\}", raw, re.DOTALL)
    if match:
        try:
            obj = json.loads(match.group())
            decision = obj.get("decision", "").lower()
            if decision in ("keep", "discard"):
                return decision, obj.get("reason", "")
        except json.JSONDecodeError:
            pass
    raw_lower = raw.lower()
    if "discard" in raw_lower:
        return "discard", raw[:100]
    return "keep", raw[:100]


def run_coarse(args):
    from utils import load_model_and_processor, run_text_only_batch
    pairs = load_jsonl(args.input)
    scenes, corpus = load_scenes(args.queries), load_corpus(args.corpus)
    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)
    done = load_done(out)
    out.touch(exist_ok=True)
    pairs = [pair for pair in pairs if cand_key(pair) not in done]
    if not pairs:
        return
    model, processor = load_model_and_processor(args.model_path)
    for start in range(0, len(pairs), 32):
        chunk = pairs[start:start + 32]
        prompts = []
        for pair in chunk:
            sc, product = scenes[str(pair["idx"])], corpus[str(pair["item_id"])]
            prompts.append(COARSE_FILTER_PROMPT.format(
                content=sc["content"], intent=sc["intent"],
                title=product["title"], category=product["treecate_full_path"]))
        responses = run_text_only_batch(model, processor, prompts, batch_size=32,
                                        max_new_tokens=256, do_sample=False, show_progress=False)
        for pair, response in zip(chunk, responses):
            decision, reason = parse_decision(response)
            append_jsonl(out, {**pair, "decision": decision, "reason": reason})
    log(f"粗筛完成:{out}")


# 2. 五级精标。
FINE_FILTER_PROMPT_WITH_IMG = """用户拍了一张图并提出需求,想买商品来解决。给你一个候选商品,请对它做细致的相关性分级。

# 背景信息
- 图像内容:用户所拍图片的文字描述(即用户手上待解决问题的物品或场景)。
- 用户意图:用户真正想解决的问题。
- 商品标题 / 商品图描述 / 商品类目:候选商品的三项信息,含义见下方"信息使用原则"。

# 信息使用原则
- 商品标题:主要依据。商家会写明核心品名与主打场景,用它判断"这个商品是什么、干什么用的"。
- 商品图描述:商品实拍图的文字描述,反映商品的真实形态/外观(是膏状、喷雾、刷子还是别的)。用它佐证和补充标题——尤其当标题含糊或夸大时,以图描述看清商品实际是什么。若标题措辞夸张(如"神器""万能"),而图描述显示其真实形态与所需品类不符,应以图描述反映的实际商品为准。
- 商品类目:平台对商品的结构化归类,反映商品的品类归属,是重要的佐证依据。当标题堆砌关键词、图描述较泛时,类目能帮助锁定商品到底属于哪一类。注意类目有时会挂错或挂粗,因此当类目与标题、图描述明显矛盾时,以标题和图描述反映的实际商品为准。
- 三者相互印证,综合判断"商品实际是什么、能不能解决用户痛点":多数情况下三者一致;若不一致,优先信任标题与图描述共同反映的实际商品,类目作为品类归属的参考。

# 分级标准(按顺序判断,命中即停)

## 第一步:这个商品能不能解决用户的核心需求?
关键问自己:"用户拿到这个商品,能不能解决他最想解决的那个痛点?"
结合标题、图描述与类目,读懂商品整体是干什么用的、能不能解决用户真正的痛点,而不是看到标题里有个和需求相同的词就算能解决。
- 完全无关,和需求扯不上关系、毫无关联 → **irrelevant**
  (例:要清洗鞋面,商品是"冰箱除味盒"——和洗鞋毫无关系)
- 解决不了核心需求:商品和需求沾边(同领域或名称相似、看着像能解决),但商品的实际用途干的不是解决用户痛点这件事 → **hard_neg_lookalike**
  (例:要清洗鞋面,商品是"鞋撑/鞋盒"——它的用途是定型/收纳,不是清洗,解决不了洗鞋这个痛点)
- 能解决核心需求 → 进入第二步

## 第二步:能解决,但用了会不会损坏物品 / 造成伤害?
请结合用户图像中物品的材质/属性,凭常识判断:这个商品用于本需求,会不会损坏用户的物品、或造成安全/健康伤害?
- 商品能解决需求,但用于本需求会造成损坏或伤害 → **hard_neg_constraint**
  (例:清洗深蓝色网面鞋,商品是"强漂白洗鞋剂"——能洗鞋(能解决),但会导致深色鞋面褪色,造成损坏)
- 不会造成损坏或伤害 → 进入第三步

## 第三步:专门对口(L1) 还是 通用凑合(L2)?
- 专门为这类需求设计、或标题主打了本需求场景的对口商品 → **L1**
  (例:清洗网面鞋,商品是"运动鞋网面专用清洁剂")
- 通用商品能解决、但不够对口(不专用,但能用、无损坏)→ **L2**
  (例:清洗网面鞋,商品是"洗衣香皂"——能洗、不含漂白无损坏风险,但非鞋面专用、不够对口)

# 判断原则(重要)
- 一切以【用户核心需求能否被解决】为准:完全不沾边→irrelevant;沾边但解决不了核心痛点→hard_neg_lookalike;能解决但会损坏/伤害→hard_neg_constraint;能解决且无损坏→正例(L1/L2)。
- 区分 irrelevant 与 lookalike:完全不沾边、和需求毫无关联的商品判 irrelevant(如洗鞋需求下的"冰箱除味盒");只有当商品和需求同领域/名称相似、看着像能解决但实际用途不对时,才判 hard_neg_lookalike(如洗鞋需求下的"鞋撑")。二者区别在于"沾不沾边"。
- 读懂商品整体是做什么的,抓住核心痛点:综合标题、图描述与类目理解商品的实际用途,看它到底能不能解决用户真正要解决的问题。例如需求是"清洗鞋面"、标题是"擦鞋神器"但图描述显示是"一把软毛刷子"、类目为"鞋刷",则实际是鞋刷、并非清洗剂,应判 hard_neg_lookalike。
- 损坏/伤害的判断要基于确实存在的风险,不要过度联想:普通商品用于常规用途一般不构成损坏(如用普通胶水补掉钻,只是不够牢固→仍属能解决,判L2),只有确实会毁坏物品或危害安全健康时才判 hard_neg_constraint。

# 以下示例均基于同一个需求:清洗网面运动鞋

【共同输入】
图像内容:一双斯凯奇运动休闲鞋,鞋面为深蓝色网布/飞织材质,白色厚底
用户意图:寻找清洗运动鞋网面(飞织/网布鞋面)的清洗剂

# 示例1(L1:专门对口)
【商品】
标题:多用去污膏去除顽固污渍网面鞋家用去污多功能清洁膏擦鞋神器
图描述:一盒白色膏状清洁产品,配有海绵,包装标注"网面鞋去污"
类目:家清-环境清洁-清洁剂-多用途清洁剂
【输出】
{{"grade": "L1", "reason": "标题、图描述、类目三者一致——是膏状去污清洁品、能清洗鞋面顽固污渍解决核心需求,标题主打'网面鞋去污'、图描述确认为清洁膏、类目为清洁剂,锚定洗鞋场景,专门对口"}}

# 示例2(L2:通用凑合)
【商品】
标题:千里臣洗衣液温和不伤手婴幼儿新生儿童宝宝母婴专用洗衣液
图描述:一瓶蓝色包装的洗衣液,瓶身标注"婴幼儿专用"
类目:家清-衣物洗护-洗衣液-普通洗衣液
【输出】
{{"grade": "L2", "reason": "标题、图描述、类目均指向婴幼儿洗衣液,能清洗织物污渍、可用于清洗网布鞋面、解决核心需求,温和不含漂白无损坏风险,但是无场景锚定的通用洗涤品、非鞋面专用,不够对口"}}

# 示例3(hard_neg_constraint:能解决但会损坏)
【商品】
标题:立白漂白水600g
图描述:一瓶白色漂白水,瓶身标注"漂白"字样
类目:家清-衣物洗护-漂白剂
【输出】
{{"grade": "hard_neg_constraint", "reason": "标题、图描述、类目一致确认为漂白水,能清洗鞋面污渍(能解决核心需求),但用户鞋面为深蓝色、漂白会导致褪色,用于本需求会损坏鞋子,属会造成损坏的红线"}}

# 示例4(hard_neg_lookalike:解决不了核心需求)
【商品】
标题:家用鞋子除臭喷雾剂银离子清新剂学生宿舍去异味持久清香防臭杀菌
图描述:一瓶喷雾式除味剂,标注"鞋类除臭、持久清香"
类目:家清-衣物洗护-鞋袜除臭剂
【输出】
{{"grade": "hard_neg_lookalike", "reason": "标题、图描述、类目均显示是鞋类除臭剂,虽同为鞋类护理、词面都含'鞋',但实际用途是去除鞋内异味,用户核心需求是清洗鞋面污渍,除臭剂解决不了'洗干净'这个痛点,无法解决需求"}}

# 示例5(hard_neg_lookalike:标题夸大,图描述与类目揭示实为工具)
【商品】
标题:擦鞋神器网面鞋清洁去污一擦即净家用清洁好帮手
图描述:一把带手柄的软毛刷子
类目:日用百货-刷子-鞋刷
【输出】
{{"grade": "hard_neg_lookalike", "reason": "标题措辞夸张称'擦鞋神器/清洁去污'、看似清洁剂,但图描述显示实为一把软毛刷子、类目也归为'鞋刷',可判定实际是鞋刷工具而非清洗剂;用户核心需求是找清洗剂,鞋刷不属于该品类,解决不了需求"}}

# 示例6(irrelevant:完全无关)
【商品】
标题:冰箱除味盒活性炭去异味保鲜盒厨房家用除味剂
图描述:一个白色塑料盒,内含活性炭,用于冰箱内除味
类目:家清-空气清新-除味剂
【输出】
{{"grade": "irrelevant", "reason": "标题、图描述、类目均指向冰箱除味盒,用于冰箱内除味保鲜,和清洗鞋面这个需求毫无关联、完全不沾边,判 irrelevant"}}

# 本次输入
【用户】
图像内容:{content}
原始问题:{question}
用户意图:{intent}
【商品】
标题:{title}
图描述:{product_caption}
类目:{category}
【输出】
"""


MODEL_NAMES = {
    "ds": "deepseek-v4-pro",
    "qw": "qwen3.7-max",
    "glm": "GLM-5.2",
}


def call_claude(prompt, model, timeout_seconds):
    result = subprocess.run(
        [
            "claude", "-p", prompt,
            "--system-prompt", SYSTEM_PROMPT,
            "--model", model,
            "--output-format", "text",
            "--no-session-persistence",
            "--bare",
        ],
        stdin=subprocess.DEVNULL,
        capture_output=True,
        text=True,
        timeout=timeout_seconds,
    )
    if result.returncode != 0:
        stderr = (result.stderr or "").strip()
        raise RuntimeError(f"claude -p exit {result.returncode}: {stderr}")
    return result.stdout.strip()


def call_claude_with_retry(prompt, model, max_retries, timeout_seconds):
    for attempt in range(1, max_retries + 1):
        try:
            raw = call_claude(prompt, model, timeout_seconds)
            parse_result(raw)  # Invalid responses are retried, never converted to L2.
            return raw, None
        except Exception as exc:
            if attempt == max_retries:
                return None, str(exc)
            time.sleep(min(2 ** attempt, 10))
    return None, "max retries exceeded"


def build_prompt(pair, scenes, corpus, captions):
    idx = str(pair["idx"])
    item_id = str(pair["item_id"])
    sc = scenes.get(idx, {})
    corp = corpus.get(item_id, {})
    cap = captions.get(item_id, "")
    return FINE_FILTER_PROMPT_WITH_IMG.format(
        question=sc["question"],
        content=sc.get("content", ""),
        intent=sc.get("intent", ""),
        title=corp.get("title", ""),
        product_caption=cap,
        category=corp.get("treecate_full_path", ""),
    )


def run_fine(args):
    pairs = load_jsonl(args.input)
    if any("decision" in pair and pair["decision"] not in {"keep", "discard"} for pair in pairs):
        raise ValueError("Invalid coarse decision")
    pairs = [pair for pair in pairs if pair.get("decision", "keep") == "keep"]
    scenes, corpus = load_scenes(args.queries), load_corpus(args.corpus)
    captions = load_captions(args.captions)
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)
    done = load_done(output_path)
    output_path.touch(exist_ok=True)

    def process_one(pair):
        idx, item_id = str(pair["idx"]), str(pair["item_id"])
        sc, product = scenes[idx], corpus[item_id]
        prompt = build_prompt(pair, scenes, corpus, captions)
        raw, error = call_claude_with_retry(prompt, args.model, args.max_retries, args.timeout)
        if error:
            raise RuntimeError(f"{cand_key(pair)}: {error}")
        append_jsonl(output_path, {
            "idx": idx, "item_id": item_id, "retrieved_by": pair.get("retrieved_by", []),
            "question": sc["question"], "content": sc["content"], "intent": sc["intent"],
            "title": product["title"], "treecate_full_path": product["treecate_full_path"],
            "product_caption": captions[item_id], **parse_result(raw), "raw_response": raw,
        })

    with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
        futures = [pool.submit(process_one, pair) for pair in pairs if cand_key(pair) not in done]
        for future in as_completed(futures):
            future.result()
    log(f"精标完成:{output_path}")
    return output_path


# 3. 投票与分歧仲裁:共用精标标准及示例。


SONNET_JUDGE_PROMPT = FINE_FILTER_PROMPT_WITH_IMG.rsplit("【输出】", 1)[0] + """
# 三个模型的评估结果(仅供参考)

以下是三个模型对本商品的独立评估结果。它们产生了分歧,请参考它们的判断和理由,独立思考后给出你的最终判断。

模型A ({name_a}):
- 评级:{grade_a}
- 理由:{reason_a}

模型B ({name_b}):
- 评级:{grade_b}
- 理由:{reason_b}

模型C ({name_c}):
- 评级:{grade_c}
- 理由:{reason_c}

请综合以上信息,给出你的最终评级和理由。
【输出】
"""


def merge_votes(votes):
    grades = list(votes.values())
    if len(grades) != 3 or any(grade not in VALID_GRADES for grade in grades):
        raise ValueError("需要三个有效的五级标签")
    positive = {grade in {"L1", "L2"} for grade in grades}
    if len(positive) > 1 or len(set(grades)) == 3:
        return "disagree", None
    return "agree", max(grades, key=grades.count)


def do_merge(model_paths, merged_path):
    model_data = {}
    for model, path in model_paths.items():
        with open(path, encoding="utf-8") as f:
            rows = [json.loads(line) for line in f if line.strip()]
        model_data[model] = {cand_key(row): row for row in rows}
        if len(model_data[model]) != len(rows):
            raise ValueError(f"Duplicate model votes: {model}")
    keys = set(model_data["ds"])
    if any(set(rows) != keys for rows in model_data.values()):
        raise ValueError("三个模型的 pair 集合必须一致,不能丢弃缺票样本")
    disagree_items = []
    with open(merged_path, "w", encoding="utf-8") as f:
        for key in sorted(keys):
            records = {model: rows[key] for model, rows in model_data.items()}
            votes = {model: row["grade"] for model, row in records.items()}
            status, grade = merge_votes(votes)
            row = records["ds"]
            out = {field: row[field] for field in [
                "idx", "item_id", "question", "content", "intent", "title",
                "treecate_full_path", "product_caption"]}
            out.update(retrieved_by=row.get("retrieved_by", []), votes=votes,
                       status=status, final_grade=grade)
            for model, record in records.items():
                out[f"{model}_grade"] = record["grade"]
                out[f"{model}_reason"] = record.get("reason", "")
            f.write(json.dumps(out, ensure_ascii=False) + "\n")
            if status == "disagree":
                disagree_items.append(out)
    return merged_path, disagree_items


def build_judge_prompt(item):
    return SONNET_JUDGE_PROMPT.format(
        question=item["question"],
        content=item.get("content", ""),
        intent=item.get("intent", ""),
        title=item.get("title", ""),
        product_caption=item.get("product_caption", ""),
        category=item.get("treecate_full_path", ""),
        name_a=MODEL_NAMES["ds"],
        grade_a=item.get("ds_grade", ""),
        reason_a=item.get("ds_reason", ""),
        name_b=MODEL_NAMES["qw"],
        grade_b=item.get("qw_grade", ""),
        reason_b=item.get("qw_reason", ""),
        name_c=MODEL_NAMES["glm"],
        grade_c=item.get("glm_grade", ""),
        reason_c=item.get("glm_reason", ""),
    )


def run_judge(judge_path, disagree_items, args):
    done = load_done(judge_path)

    def process_one(item):
        raw, error = call_claude_with_retry(
            build_judge_prompt(item), "claude-sonnet-4-6", args.max_retries, args.timeout)
        if error:
            raise RuntimeError(f"{cand_key(item)}: {error}")
        append_jsonl(judge_path, {"idx": item["idx"], "item_id": item["item_id"],
                                 "votes": item["votes"], **parse_result(raw), "raw_response": raw})

    with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
        futures = [pool.submit(process_one, item) for item in disagree_items if cand_key(item) not in done]
        for future in as_completed(futures):
            future.result()
    return judge_path


def final_merge(merged_path, judge_path, final_path):
    judge_results = {}
    if judge_path.exists():
        with open(judge_path, encoding="utf-8") as f:
            for line in f:
                if line.strip():
                    row = json.loads(line)
                    judge_results[cand_key(row)] = row["grade"]
    with open(merged_path, encoding="utf-8") as fin:
        rows = [json.loads(line) for line in fin if line.strip()]
    for row in rows:
        grade = row["final_grade"] if row["status"] == "agree" else judge_results.get(cand_key(row))
        if grade not in VALID_GRADES:
            raise ValueError(f"Missing or invalid adjudication: {cand_key(row)}")
    with open(final_path, "w", encoding="utf-8") as fout:
        for row in rows:
            if row["status"] == "agree":
                grade, source = row["final_grade"], "model_consensus"
            else:
                grade = judge_results.get(cand_key(row))
                source = "sonnet_judge" if grade else "unresolved"
            out = {"idx": row["idx"], "item_id": row["item_id"],
                   "retrieved_by": row["retrieved_by"], "final_grade": grade, "source": source}
            fout.write(json.dumps(out, ensure_ascii=False) + "\n")
    return final_path


def run_adjudication(args):
    out = Path(args.output_dir)
    out.mkdir(parents=True, exist_ok=True)
    merged, disagree = do_merge({"ds": args.ds, "qw": args.qw, "glm": args.glm}, out / "merged.jsonl")
    judged = run_judge(out / "judged.jsonl", disagree, args)
    final_merge(merged, judged, out / "final.jsonl")
    log(f"合并完成;需裁决 {len(disagree)} 条,输出 {out / 'final.jsonl'}")


def main():
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest="stage", required=True)
    for stage in ("coarse", "fine", "adjudicate"):
        command = sub.add_parser(stage)
        if stage == "adjudicate":
            for name in ("ds", "qw", "glm"):
                command.add_argument(f"--{name}", required=True)
            command.add_argument("--output-dir", required=True)
        else:
            for name in ("input", "queries", "corpus", "output"):
                command.add_argument(f"--{name}", required=True)
        if stage == "coarse":
            command.add_argument("--model-path", required=True)
        else:
            command.add_argument("--concurrency", type=int, default=8)
            command.add_argument("--max-retries", type=int, default=3)
            command.add_argument("--timeout", type=int, default=120)
        if stage == "fine":
            command.add_argument("--captions", required=True)
            command.add_argument("--model", required=True, choices=list(MODEL_NAMES.values()))
    args = p.parse_args()
    {"coarse": run_coarse, "fine": run_fine, "adjudicate": run_adjudication}[args.stage](args)


if __name__ == "__main__":
    main()