Spaces:
Running on CPU Upgrade

File size: 10,911 Bytes
427634d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Corpus query tool for the benchmark authoring agent.

Filters the EXO product corpus using the same hard rules as the pipeline's
matching service. Returns compact JSON results.

Usage:
    python scripts/corpus_query.py --category downlight --wattage 15 --cct 4000
    python scripts/corpus_query.py --code "ALN-U68*"
    python scripts/corpus_query.py --search "suspended LED extrusion" --cct 4000
    python scripts/corpus_query.py --code-exact "PLB-1230-24W-4K-9-MP-DA"
"""
from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path

CORPUS_PATH = Path(__file__).resolve().parent.parent / "data" / "corpus_products.json"

# Hard rule approved CCT pairs
CCT_APPROVED_PAIRS = [(2700, 3000), (3000, 2700), (3500, 4000), (4000, 3500)]

# Mounting normalization
MOUNTING_MAP = {
    "recess": "recessed", "recessed": "recessed",
    "surface": "surface",
    "pendant": "suspended", "suspend": "suspended", "suspended": "suspended",
    "wall": "wall",
}

# Dimming normalization
DIMMING_MAP = {
    "dali": "dali", "dali-2": "dali", "dali2": "dali",
    "triac": "phase_dimmable", "phase": "phase_dimmable",
    "leading edge": "phase_dimmable", "trailing edge": "phase_dimmable",
    "1-10v": "1_10v", "1-10": "1_10v", "0-10v": "1_10v",
    "non_dimmable": "non_dimmable", "non-dimmable": "non_dimmable",
}

# DALI fallback sources
DALI_FALLBACK_SOURCES = {"phase_dimmable", "1_10v"}


def normalize_mounting(val: str | None) -> str | None:
    if not val:
        return None
    return MOUNTING_MAP.get(val.lower().strip(), val.lower().strip())


def normalize_dimming(val: str | None) -> str | None:
    if not val:
        return None
    return DIMMING_MAP.get(val.lower().strip(), val.lower().strip())


def parse_ip_number(val: str | None) -> int | None:
    if not val:
        return None
    m = re.search(r"(\d{2,})", str(val))
    return int(m.group(1)) if m else None


def load_corpus() -> list[dict]:
    with open(CORPUS_PATH, encoding="utf-8") as f:
        return json.load(f)


def filter_corpus(
    products: list[dict],
    *,
    category: str | None = None,
    wattage: float | None = None,
    wattage_tolerance: float = 0.2,
    cct: int | None = None,
    cri_min: int | None = None,
    lumens_min: int | None = None,
    lumens_max: int | None = None,
    ip_min: str | None = None,
    dimming: str | None = None,
    mounting: str | None = None,
    item_type: str | None = None,
    code_pattern: str | None = None,
    code_exact: str | None = None,
    search_text: str | None = None,
    limit: int = 50,
) -> list[dict]:
    results = []

    norm_mounting = normalize_mounting(mounting)
    norm_dimming = normalize_dimming(dimming)
    ip_min_num = parse_ip_number(ip_min)

    code_re = None
    if code_pattern:
        pattern = code_pattern.replace("*", ".*").replace("?", ".")
        code_re = re.compile(pattern, re.IGNORECASE)

    search_tokens = None
    if search_text:
        search_tokens = set(search_text.lower().split())

    for p in products:
        # Code exact match
        if code_exact:
            pc = (p.get("product_code") or "").upper().replace("-", "").replace("_", "").replace(" ", "")
            target = code_exact.upper().replace("-", "").replace("_", "").replace(" ", "")
            if pc != target:
                continue

        # Code pattern match
        if code_re and not code_re.search(p.get("product_code", "")):
            continue

        # Category filter (H1) β€” require field present
        if category:
            p_cat = p.get("product_category")
            if not p_cat:
                continue
            if p_cat.lower() != category.lower():
                equiv = {("wall_light", "bollard"), ("bollard", "wall_light"), ("linear", "strip"), ("strip", "linear")}
                if (category.lower(), p_cat.lower()) not in equiv:
                    continue

        # Item type filter
        if item_type:
            if (p.get("item_type") or "").lower() != item_type.lower():
                continue

        # Wattage filter β€” require field present
        if wattage is not None:
            p_watt = p.get("wattage")
            if p_watt is None:
                continue
            low = wattage * (1 - wattage_tolerance)
            high = wattage * (1 + wattage_tolerance)
            if not (low <= p_watt <= high):
                continue

        # CCT filter (H2) β€” require field present, with approved pairs
        if cct is not None:
            p_cct = p.get("cct")
            if p_cct is None:
                continue
            if p_cct != cct and (cct, p_cct) not in CCT_APPROVED_PAIRS:
                continue

        # CRI filter (H3) β€” require field present, product must meet or exceed
        if cri_min is not None:
            p_cri = p.get("cri")
            if p_cri is None:
                continue
            if p_cri < cri_min:
                continue

        # Lumens filter (H4) β€” require field present, with 10% shortfall tolerance
        if lumens_min is not None:
            p_lumens = p.get("lumens")
            if p_lumens is None:
                continue
            if p_lumens < lumens_min * 0.9:
                continue
        if lumens_max is not None:
            p_lumens = p.get("lumens")
            if p_lumens is None:
                continue
            if p_lumens > lumens_max:
                continue

        # Dimming filter (H5) β€” require field present, with DALI fallback
        if norm_dimming is not None:
            p_dim = normalize_dimming(p.get("dimming_method"))
            if p_dim is None or p_dim == "unknown":
                continue
            if p_dim != norm_dimming:
                if not (norm_dimming in DALI_FALLBACK_SOURCES and p_dim == "dali"):
                    continue

        # IP filter (H6) β€” require field present, product must meet or exceed
        if ip_min_num is not None:
            p_ip = parse_ip_number(p.get("ip_rating"))
            if p_ip is None:
                continue
            if p_ip < ip_min_num:
                continue

        # Mounting filter (H7) β€” require field present, exact match
        if norm_mounting is not None:
            p_mount = normalize_mounting(p.get("mounting_method"))
            if p_mount is None or p_mount == "unknown":
                continue
            if p_mount != norm_mounting:
                continue

        # Text search (description overlap)
        if search_tokens:
            desc_lower = (p.get("description") or "").lower()
            code_lower = (p.get("product_code") or "").lower()
            combined = desc_lower + " " + code_lower
            matches = sum(1 for t in search_tokens if t in combined)
            if matches < len(search_tokens) * 0.3:
                continue

        results.append(p)
        if len(results) >= limit:
            break

    return results


def format_compact(products: list[dict]) -> str:
    compact = []
    for p in products:
        entry = {"code": p["product_code"], "desc": p["description"]}
        for field in ["product_category", "wattage", "lumens", "cct", "cri",
                       "ip_rating", "dimming_method", "mounting_method",
                       "colour", "finish", "item_type",
                       "length_mm", "width_mm", "height_mm", "diameter_mm"]:
            v = p.get(field)
            if v is not None and v != "" and v != "null":
                entry[field] = v
        compact.append(entry)
    return json.dumps(compact, indent=2)


def format_brief(products: list[dict]) -> str:
    """One-line-per-product format to minimize context usage."""
    lines = []
    for p in products:
        parts = [p["product_code"]]
        for field, label in [("wattage", "W"), ("cct", "K"), ("cri", "CRI"),
                             ("lumens", "lm"), ("ip_rating", ""), ("dimming_method", ""),
                             ("mounting_method", "")]:
            v = p.get(field)
            if v is not None and v != "" and v != "null":
                parts.append(f"{v}{label}" if label else str(v))
        parts.append(f'"{p["description"]}"')
        lines.append(" | ".join(parts))
    return "\n".join(lines)


def main():
    parser = argparse.ArgumentParser(description="Query the EXO product corpus with hard-rule filters")
    parser.add_argument("--category", help="Product category: downlight, linear, panel, batten, wall_light, exit_sign, emergency_light")
    parser.add_argument("--wattage", type=float, help="Target wattage (Β±20%% tolerance)")
    parser.add_argument("--wattage-tolerance", type=float, default=0.2, help="Wattage tolerance fraction (default: 0.2)")
    parser.add_argument("--cct", type=int, help="Target CCT in Kelvin (with approved pair fallback)")
    parser.add_argument("--cri-min", type=int, help="Minimum CRI")
    parser.add_argument("--lumens-min", type=int, help="Minimum lumens (with 10%% shortfall tolerance)")
    parser.add_argument("--lumens-max", type=int, help="Maximum lumens")
    parser.add_argument("--ip-min", help="Minimum IP rating (e.g. IP54)")
    parser.add_argument("--dimming", help="Dimming method: dali, phase_dimmable, 1_10v, non_dimmable")
    parser.add_argument("--mounting", help="Mounting method: recessed, surface, suspended, wall")
    parser.add_argument("--item-type", help="Item type: general_luminaire, emergency, exit, combined_general_emergency")
    parser.add_argument("--code", help="Product code pattern (wildcards: * ?)")
    parser.add_argument("--code-exact", help="Exact product code lookup")
    parser.add_argument("--search", help="Free text search in description")
    parser.add_argument("--limit", type=int, default=15, help="Max results (default: 15)")
    parser.add_argument("--count-only", action="store_true", help="Only print count of matches")
    parser.add_argument("--brief", action="store_true", help="One-line-per-product output (saves context)")

    args = parser.parse_args()
    products = load_corpus()

    results = filter_corpus(
        products,
        category=args.category,
        wattage=args.wattage,
        wattage_tolerance=args.wattage_tolerance,
        cct=args.cct,
        cri_min=args.cri_min,
        lumens_min=args.lumens_min,
        lumens_max=args.lumens_max,
        ip_min=args.ip_min,
        dimming=args.dimming,
        mounting=args.mounting,
        item_type=args.item_type,
        code_pattern=args.code,
        code_exact=args.code_exact,
        search_text=args.search,
        limit=args.limit,
    )

    if args.count_only:
        print(len(results))
    elif args.brief:
        print(f"# {len(results)} results")
        print(format_brief(results))
    else:
        print(f"# {len(results)} results")
        print(format_compact(results))


if __name__ == "__main__":
    main()