File size: 7,212 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
#!/usr/bin/env python3
"""Pool top-20 runs, annotate unseen pairs, and export complete five-way qrels."""
import argparse
import json
from collections import defaultdict
from pathlib import Path

from utils import GRADE_ALIASES, index_pairs, pair_key, read_jsonl, read_pairs, write_jsonl


def build_pool(recall_path, run_paths, output_path, top_k=20):
    if top_k < 1 or not run_paths:
        raise ValueError("Supply retrieval runs and a positive top_k")
    pairs = {}
    for row in read_pairs(recall_path):
        key = pair_key(row)
        pairs.setdefault(key, set()).update(row.get("retrieved_by", []))
    query_ids = {qid for qid, _ in pairs}
    if not query_ids:
        raise ValueError("Initial candidate pool is empty")
    for path in run_paths:
        with open(path, encoding="utf-8") as f:
            run = json.load(f)
        qids = [str(row["qid"]) for row in run]
        if len(set(qids)) != len(qids) or set(qids) != query_ids:
            raise ValueError(f"Run query IDs must match initial pool exactly: {path}")
        source = f"model:{Path(path).parent.name}/{Path(path).name}"
        for row in run:
            hits = row["ranked"][:top_k]
            ids = [str(hit["did"]) for hit in hits]
            if len(ids) < top_k or len(set(ids)) != len(ids):
                raise ValueError(f"Run needs {top_k} unique products per query: {path}, {row['qid']}")
            for did in ids:
                pairs.setdefault((str(row["qid"]), did), set()).add(source)
    rows = [{"idx": qid, "item_id": did, "retrieved_by": sorted(sources)}
            for (qid, did), sources in sorted(pairs.items())]
    write_jsonl(output_path, rows)
    return rows


def coarse_index(paths):
    rows = index_pairs([row for path in paths for row in read_pairs(path)])
    for row in rows.values():
        if row.get("decision") not in {"keep", "discard"}:
            raise ValueError(f"Invalid coarse decision: {pair_key(row)}")
    return rows


def prepare_coarse(merged_path, coarse_path, output_path, todo_path):
    pool = index_pairs(read_pairs(merged_path))
    coarse = coarse_index([coarse_path])
    if set(coarse) - set(pool):
        raise ValueError("Existing coarse results contain pairs outside the pool")
    done, todo = [], []
    for key, row in pool.items():
        if key in coarse:
            done.append({**row, "decision": coarse[key]["decision"],
                         "reason": coarse[key].get("reason", "")})
        else:
            todo.append(row)
    write_jsonl(output_path, done)
    write_jsonl(todo_path, todo)
    return done, todo


def merge_coarse(merged_path, result_paths, output_path):
    pool = index_pairs(read_pairs(merged_path))
    results = coarse_index(result_paths)
    if set(pool) != set(results):
        raise ValueError(f"Incomplete coarse results: missing={len(set(pool)-set(results))}, "
                         f"extra={len(set(results)-set(pool))}")
    rows = [{**row, "decision": results[key]["decision"],
             "reason": results[key].get("reason", "")} for key, row in pool.items()]
    write_jsonl(output_path, rows)
    return rows


def finalize(pool_path, coarse_paths, fine_paths, queries_path, output_dir):
    """Require complete labels; filter queries only after initial and pooled labeling."""
    pool = index_pairs(read_pairs(pool_path))
    coarse = coarse_index(coarse_paths)
    fine = index_pairs([row for path in fine_paths for row in read_pairs(path)])
    if set(coarse) != set(pool):
        raise ValueError("Coarse results must cover exactly the complete pool")
    kept_pairs = {key for key, row in coarse.items() if row["decision"] == "keep"}
    if set(fine) != kept_pairs:
        raise ValueError(f"Fine results must cover all and only coarse-kept pairs: "
                         f"missing={len(kept_pairs-set(fine))}, extra={len(set(fine)-kept_pairs)}")
    queries = read_jsonl(queries_path)
    qids = [str(row["idx"]) for row in queries]
    if len(set(qids)) != len(qids) or set(qids) != {qid for qid, _ in pool}:
        raise ValueError("Query IDs must match the complete pool exactly")
    judgments = defaultdict(list)
    membership = []
    for key, pair in pool.items():
        if coarse[key]["decision"] == "discard":
            grade = "N3"
        else:
            raw_grade = fine[key].get("final_grade")
            if not isinstance(raw_grade, str) or raw_grade not in GRADE_ALIASES:
                raise ValueError(f"Missing or invalid final grade: {key}")
            grade = GRADE_ALIASES[raw_grade]
        judgments[key[0]].append({"item_id": key[1], "final_grade": grade})
        membership.append({**pair, "final_grade": grade})
    retained = {qid for qid, items in judgments.items()
                if 1 <= sum(item["final_grade"] == "L1" for item in items) <= 20}
    final_queries = [{"idx": str(row["idx"]), "query": row["query"], "image_url": row["image_url"]}
                     for row in queries if str(row["idx"]) in retained]
    out = Path(output_dir)
    # Keep IDs and corpus unchanged; only the final query set is filtered.
    write_jsonl(out / "mipr_query.jsonl", final_queries)
    write_jsonl(out / "mipr_annotation.jsonl", [
        {"idx": qid, "items": judgments[qid]} for qid in qids if qid in retained])
    write_jsonl(out / "pool_membership.jsonl", [row for row in membership if row["idx"] in retained])
    return retained


def main():
    p = argparse.ArgumentParser(description=__doc__)
    sub = p.add_subparsers(dest="command", required=True)
    build = sub.add_parser("build", help="Merge initial flat pairs and model top-20 runs")
    build.add_argument("--recall", required=True)
    build.add_argument("--runs", nargs="+", required=True)
    build.add_argument("--top-k", type=int, default=20)
    build.add_argument("--output", required=True)
    prepare = sub.add_parser("prepare", help="Reuse old coarse results and emit unseen pairs")
    prepare.add_argument("--pool", required=True)
    prepare.add_argument("--coarse", required=True)
    prepare.add_argument("--done", required=True)
    prepare.add_argument("--todo", required=True)
    merge = sub.add_parser("merge", help="Combine reused and newly screened pairs")
    merge.add_argument("--pool", required=True)
    merge.add_argument("--results", nargs="+", required=True)
    merge.add_argument("--output", required=True)
    final = sub.add_parser("finalize", help="Merge all labels, map N1/N2/N3, and filter queries")
    final.add_argument("--pool", required=True)
    final.add_argument("--coarse", nargs="+", required=True)
    final.add_argument("--fine", nargs="+", required=True)
    final.add_argument("--queries", required=True)
    final.add_argument("--output-dir", required=True)
    args = p.parse_args()
    if args.command == "build":
        build_pool(args.recall, args.runs, args.output, args.top_k)
    elif args.command == "prepare":
        prepare_coarse(args.pool, args.coarse, args.done, args.todo)
    elif args.command == "merge":
        merge_coarse(args.pool, args.results, args.output)
    else:
        finalize(args.pool, args.coarse, args.fine, args.queries, args.output_dir)


if __name__ == "__main__":
    main()