File size: 4,687 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
"""商品词走三路检索,意图走文本融合和多模态两路;每源默认 top-5。

search(mode, queries, top_k) 由调用方提供,不在本文件实现检索后端。
queries 为 {query_id: text},返回 {query_id: [(item_id, score), ...]},按分数降序。
mode: bm25(jieba 分词);embedding(Qwen3-Embedding-0.6B 与
BGE-small-zh-v1.5 的 RRF 融合);qwen3_vl(Qwen3-VL-Embedding-2B)。
"""
import argparse
import json
from pathlib import Path

from utils import deduplicate, load_embeddings, read_jsonl, write_jsonl

MODES = ("bm25", "embedding", "qwen3_vl")


def retrieve_candidates(input_path, output_path, search, top_k=5):
    with open(input_path, encoding="utf-8") as f:
        entries = [json.loads(line) for line in f if line.strip()]
    keywords = dict.fromkeys(kw for row in entries for kw in row["product_keywords"])
    intents = dict.fromkeys(row["scene"]["intent"] for row in entries if row["scene"]["intent"])
    kw_to_qid = {kw: f"kw_{i}" for i, kw in enumerate(keywords)}
    intent_to_qid = {intent: f"int_{i}" for i, intent in enumerate(intents)}
    kw_queries = {qid: kw for kw, qid in kw_to_qid.items()}
    intent_queries = {qid: intent for intent, qid in intent_to_qid.items()}
    mode_results = {}
    for mode in MODES:
        queries = kw_queries if mode == "bm25" else {**kw_queries, **intent_queries}
        mode_results[mode] = search(mode, queries, top_k=top_k)
    output = [assemble_sources(row, mode_results, kw_to_qid, intent_to_qid, top_k)
              for row in entries]
    Path(output_path).parent.mkdir(parents=True, exist_ok=True)
    with open(output_path, "w", encoding="utf-8") as f:
        for row in output:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")
    return output


def assemble_sources(row, mode_results, kw_to_qid, intent_to_qid, top_k=5):
    searches = [(kw, kw_to_qid[kw], "keyword") for kw in row["product_keywords"]]
    intent = row["scene"]["intent"]
    if intent:
        searches.append((intent, intent_to_qid[intent], "intent"))
    sources = []
    for text, qid, kind in searches:
        for mode in MODES:
            if kind == "intent" and mode == "bm25":
                continue
            hits = mode_results[mode].get(qid, [])[:top_k]
            sources.append({
                "source": f"{mode}:{text if kind == 'keyword' else 'intent'}",
                "mode": mode, "query_text": text, "query_type": kind,
                "items": [{"item_id": did, "score": score, "rank": rank}
                          for rank, (did, score) in enumerate(hits, 1)],
            })
    return {"idx": row["idx"], "query": row["query"], "image_url": row["image_url"],
            "scene": row["scene"], "product_keywords": row["product_keywords"],
            "source_results": sources}


# 叶类目内去重,随后合并并重定向各 query 的候选。


def redirect_candidates(entries, product_mapping):
    """将检索源结果合并为 query-product 对,重定向商品并合并来源。"""
    pairs = {}
    for row in entries:
        for source in row["source_results"]:
            for hit in source["items"]:
                item_id = product_mapping[str(hit["item_id"])]
                key = (str(row["idx"]), item_id)
                pair = pairs.setdefault(key, {"idx": key[0], "item_id": item_id, "retrieved_by": []})
                if source["source"] not in pair["retrieved_by"]:
                    pair["retrieved_by"].append(source["source"])
    return list(pairs.values())


def run_product_dedup(args):
    items = read_jsonl(args.input)
    emb = load_embeddings(args.emb_path, [row["item_id"] for row in items])
    kept, mapping = deduplicate(items, emb, "product", args.threshold)
    pairs = redirect_candidates(read_jsonl(args.sources), mapping)
    out = Path(args.output_dir)
    write_jsonl(out / "deduplicated.jsonl", kept)
    write_jsonl(out / "pairs.jsonl", pairs)
    (out / "id_mapping.json").write_text(json.dumps(mapping, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"商品去重:{len(items)} → {len(kept)}")


def main():
    p = argparse.ArgumentParser(description="候选商品去重及 query-product 对重定向")
    p.add_argument("--input", required=True, help="召回商品并集 JSONL")
    p.add_argument("--emb-path", required=True, help="Qwen3-VL-Embedding-8B 图文 NPZ: emb, ids")
    p.add_argument("--sources", required=True, help="retrieve_candidates 输出的 source_results")
    p.add_argument("--output-dir", required=True)
    p.add_argument("--threshold", type=float, default=0.60)
    run_product_dedup(p.parse_args())


if __name__ == "__main__":
    main()