File size: 2,904 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Query registry: expand seed terms along diversity axes (deterministically)."""
from __future__ import annotations

import random
from dataclasses import dataclass


@dataclass(frozen=True)
class QuerySpec:
    class_hint: str
    query: str
    lang: str = "en"
    kind: str = "seed"  # seed | expanded | lang


def _overlap(phrase: str, words: set[str]) -> float:
    toks = phrase.lower().split()
    return sum(t in words for t in toks) / len(toks) if toks else 1.0


def build_queries(
    qcfg: dict,
    classes: list[str] | None = None,
    langs: list[str] | None = None,
) -> list[QuerySpec]:
    """Build the full query list.

    For every seed term: the seed itself plus up to ``max_variants_per_seed`` variants that
    append one or two randomly chosen axis values (board type, condition, view/setting).
    A class may override any axis (e.g. ``desoldered_zone`` never pairs with "intact").
    Multilingual terms are hand-written per class and appended as-is.

    Output order and content are fully determined by ``expansion.seed``.
    """
    exp = qcfg.get("expansion", {}) or {}
    rng = random.Random(exp.get("seed", 7))
    per_seed = int(exp.get("max_variants_per_seed", 8))
    global_axes = qcfg.get("axes", {}) or {}

    out: list[QuerySpec] = []
    seen: set[tuple[str, str]] = set()

    def add(spec: QuerySpec) -> None:
        key = (spec.class_hint, spec.query.strip().lower())
        if key not in seen and spec.query.strip():
            seen.add(key)
            out.append(spec)

    for cls, body in (qcfg.get("classes") or {}).items():
        if classes and cls not in classes:
            continue
        body = body or {}
        axes = {**global_axes, **(body.get("axes") or {})}
        axis_names = sorted(a for a, vals in axes.items() if vals)

        for seed in body.get("seeds", []) or []:
            add(QuerySpec(cls, seed, "en", "seed"))
            seed_words = set(seed.lower().split())
            variants: set[str] = set()
            attempts = 0
            while axis_names and len(variants) < per_seed and attempts < per_seed * 10:
                attempts += 1
                chosen = rng.sample(axis_names, min(rng.choice([1, 2]), len(axis_names)))
                parts = [rng.choice(axes[a]) for a in sorted(chosen)]
                # Skip axis values the seed already (mostly) says, e.g. "close up" + "close up macro".
                parts = [p for p in parts if _overlap(p, seed_words) < 0.5]
                if parts:
                    variants.add(f"{seed} {' '.join(parts)}")
            for v in sorted(variants):
                add(QuerySpec(cls, v, "en", "expanded"))

        for lang, terms in (body.get("multilingual") or {}).items():
            if langs and lang not in langs:
                continue
            for term in terms or []:
                add(QuerySpec(cls, term, lang, "lang"))
    return out