FaustDerLegende's picture
Upload folder using huggingface_hub (part 61)
11a414e verified
Raw History Blame Contribute Delete
2.9 kB
"""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