Spaces:
Running on CPU Upgrade

File size: 12,017 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env python3
"""Analyze benchmark ground truth for hard-rule deviations.

For each benchmark case with a reference case.yaml, checks whether the
expected product codes actually pass the pipeline's hard filtering rules
(H1-H7). Records deviations into the benchmark_deviations DB table.

Deviation types:
  - corpus_gap:      Product exists but is missing a field hard rules need
  - corpus_missing:  Product code not found in corpus at all
  - rule_conflict:   Product field EXISTS but violates a hard rule vs schedule specs

Usage:
    python scripts/analyze_deviations.py [--case-id example-3] [--dry-run]
"""
from __future__ import annotations

import argparse
import json
import re
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path

import yaml

REPO_ROOT = Path(__file__).resolve().parent.parent
CORPUS_PATH = REPO_ROOT / "data" / "corpus_products.json"
CASES_DIR = REPO_ROOT / "benchmark" / "cases"

sys.path.insert(0, str(REPO_ROOT / "scripts"))
from corpus_query import (
    CCT_APPROVED_PAIRS,
    normalize_dimming,
    normalize_mounting,
    parse_ip_number,
)


def load_corpus_map() -> dict[str, dict]:
    with open(CORPUS_PATH) as f:
        products = json.load(f)
    result = {}
    for p in products:
        code = p.get("product_code", "")
        result[code] = p
        norm = code.upper().replace("-", "").replace("_", "").replace(" ", "")
        result[norm] = p
    return result


def find_product(corpus_map: dict, code: str) -> dict | None:
    if not code:
        return None
    if code in corpus_map:
        return corpus_map[code]
    norm = code.upper().replace("-", "").replace("_", "").replace(" ", "")
    return corpus_map.get(norm)


def check_product(item: dict, product: dict, case_id: str, source_file: str) -> list[dict]:
    """Check a ground truth product against hard rules. Returns deviations."""
    deviations = []
    code = item["corpus_link"].get("expected_product_code") or ""
    item_id = item["benchmark_item_id"]

    def add(rule: str, detail: str, direction: str, expected: str, actual: str):
        deviations.append({
            "case_id": case_id,
            "item_id": item_id,
            "source_file": source_file,
            "expected_product_code": code,
            "rule_violated": rule,
            "rule_detail": detail,
            "direction": direction,
            "expected_value": expected,
            "actual_value": actual,
        })

    # --- Corpus gaps: fields the hard rules need but the product doesn't have ---

    p_cct = product.get("cct")
    if p_cct is None:
        add("H2", "Corpus gap: product missing CCT", "corpus_gap", "CCT present", "null")

    p_cri = product.get("cri")
    if p_cri is None:
        add("H3", "Corpus gap: product missing CRI", "corpus_gap", "CRI present", "null")

    p_lumens = product.get("lumens")
    if p_lumens is None:
        add("H4", "Corpus gap: product missing lumens", "corpus_gap", "lumens present", "null")

    p_dim = normalize_dimming(product.get("dimming_method"))
    if p_dim is None or p_dim == "unknown":
        add("H5", "Corpus gap: product missing dimming method", "corpus_gap",
            "dimming present", str(product.get("dimming_method")))

    p_ip = parse_ip_number(product.get("ip_rating"))
    if p_ip is None:
        add("H6", "Corpus gap: product missing IP rating", "corpus_gap", "IP present", "null")

    p_mount = normalize_mounting(product.get("mounting_method"))
    if p_mount is None or p_mount == "unknown":
        add("H7", "Corpus gap: product missing mounting method", "corpus_gap",
            "mounting present", str(product.get("mounting_method")))

    # --- Rule conflicts: product field EXISTS but may violate schedule specs ---
    # We infer schedule specs from the item description and rationale where possible.

    rationale = (item.get("corpus_link", {}).get("match_rationale") or "").lower()
    desc = (item.get("expected_normalized_description") or "").lower()
    evidence_notes = " ".join(
        (ref.get("note") or "") for ref in item.get("source_evidence_refs", [])
    ).lower()
    combined = f"{desc} {rationale} {evidence_notes}"

    # Try to infer schedule CCT from evidence/description
    cct_match = re.search(r'(\d{4})\s*k\b', combined) or re.search(r'\b(2700|3000|3500|4000|5000|5700|6500)\b', combined)
    if cct_match and p_cct is not None:
        sched_cct = int(cct_match.group(1))
        if p_cct != sched_cct and (sched_cct, p_cct) not in CCT_APPROVED_PAIRS:
            add("H2", f"Rule conflict: schedule wants {sched_cct}K, product has {p_cct}K",
                "more_relaxed", str(sched_cct), str(p_cct))

    # Try to infer schedule IP from evidence
    ip_match = re.search(r'ip\s*(\d{2,})', combined)
    if ip_match and p_ip is not None:
        sched_ip = int(ip_match.group(1))
        if p_ip < sched_ip:
            add("H6", f"Rule conflict: schedule wants IP{sched_ip}, product has IP{p_ip}",
                "more_relaxed", f"IP{sched_ip}", f"IP{p_ip}")

    # Try to infer schedule mounting
    for mount_word, mount_val in [("recessed", "recessed"), ("surface", "surface"),
                                   ("suspended", "suspended"), ("pendant", "suspended"),
                                   ("wall mount", "wall"), ("wall-mount", "wall")]:
        if mount_word in combined and p_mount is not None and p_mount != "unknown":
            sched_mount = mount_val
            if p_mount != sched_mount:
                add("H7", f"Rule conflict: schedule wants {sched_mount}, product has {p_mount}",
                    "more_relaxed", sched_mount, p_mount)
            break

    # Try to infer schedule lumens
    lumen_match = re.search(r'(\d{3,5})\s*l[um]', combined)
    if lumen_match and p_lumens is not None:
        sched_lumens = int(lumen_match.group(1))
        if p_lumens < sched_lumens * 0.9:
            shortfall = round((1 - p_lumens / sched_lumens) * 100, 1)
            add("H4", f"Rule conflict: schedule wants {sched_lumens}lm, product has {p_lumens}lm ({shortfall}% shortfall)",
                "more_relaxed", str(sched_lumens), str(p_lumens))

    return deviations


def analyze_case(case_dir: Path, corpus_map: dict) -> list[dict]:
    case_yaml = case_dir / "case.yaml"
    if not case_yaml.exists():
        return []

    with open(case_yaml) as f:
        case = yaml.safe_load(f)

    case_id = case["metadata"]["case_id"]
    source_file = case_yaml.name
    all_deviations = []

    for item in case.get("items", []):
        outcome = item.get("expected_outcome", "")
        code = (item.get("corpus_link", {}).get("expected_product_code") or "").strip()

        if outcome != "matched_to_output" or not code:
            continue

        product = find_product(corpus_map, code)
        if product is None:
            all_deviations.append({
                "case_id": case_id,
                "item_id": item["benchmark_item_id"],
                "source_file": source_file,
                "expected_product_code": code,
                "rule_violated": "CORPUS",
                "rule_detail": f"Product code '{code}' not found in corpus",
                "direction": "corpus_missing",
                "expected_value": "code exists",
                "actual_value": "not found",
            })
            continue

        # Check alternative codes too
        alts = item.get("corpus_link", {}).get("acceptable_alternative_product_codes") or []
        for alt in alts:
            if alt and not find_product(corpus_map, alt):
                all_deviations.append({
                    "case_id": case_id,
                    "item_id": item["benchmark_item_id"],
                    "source_file": source_file,
                    "expected_product_code": alt,
                    "rule_violated": "CORPUS",
                    "rule_detail": f"Alternative code '{alt}' not found in corpus",
                    "direction": "corpus_missing",
                    "expected_value": "code exists",
                    "actual_value": "not found",
                })

        devs = check_product(item, product, case_id, source_file)
        all_deviations.extend(devs)

    return all_deviations


def get_db_path() -> Path:
    for candidate in [
        REPO_ROOT / "storage" / "lighting_mvp.db",
        REPO_ROOT / "lighting_mvp.db",
    ]:
        if candidate.exists():
            return candidate
    return REPO_ROOT / "storage" / "lighting_mvp.db"


def save_to_db(deviations: list[dict], db_path: Path) -> None:
    conn = sqlite3.connect(str(db_path))
    cur = conn.cursor()

    cur.execute("""
        CREATE TABLE IF NOT EXISTS benchmark_deviations (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            case_id TEXT NOT NULL,
            item_id TEXT NOT NULL,
            source_file TEXT NOT NULL,
            expected_product_code TEXT,
            rule_violated TEXT NOT NULL,
            rule_detail TEXT NOT NULL,
            direction TEXT NOT NULL,
            expected_value TEXT,
            actual_value TEXT,
            created_at TEXT NOT NULL
        )
    """)

    case_ids = set(d["case_id"] for d in deviations)
    for cid in case_ids:
        cur.execute("DELETE FROM benchmark_deviations WHERE case_id = ?", (cid,))

    now = datetime.now(timezone.utc).isoformat()
    for d in deviations:
        cur.execute(
            """INSERT INTO benchmark_deviations
               (case_id, item_id, source_file, expected_product_code,
                rule_violated, rule_detail, direction, expected_value, actual_value, created_at)
               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
            (d["case_id"], d["item_id"], d["source_file"], d["expected_product_code"],
             d["rule_violated"], d["rule_detail"], d["direction"],
             d["expected_value"], d["actual_value"], now),
        )

    conn.commit()
    conn.close()


def main():
    parser = argparse.ArgumentParser(description="Analyze benchmark ground truth for hard-rule deviations")
    parser.add_argument("--case-id", help="Analyze only this case (default: all)")
    parser.add_argument("--dry-run", action="store_true", help="Print deviations without writing to DB")
    args = parser.parse_args()

    corpus_map = load_corpus_map()
    all_deviations = []

    if args.case_id:
        case_dir = CASES_DIR / args.case_id
        if not case_dir.exists():
            print(f"Case directory not found: {case_dir}")
            sys.exit(1)
        all_deviations = analyze_case(case_dir, corpus_map)
    else:
        for case_dir in sorted(CASES_DIR.iterdir()):
            if case_dir.is_dir() and not case_dir.name.endswith("-agent-test"):
                devs = analyze_case(case_dir, corpus_map)
                all_deviations.extend(devs)

    # Group by direction (type)
    by_type = {}
    for d in all_deviations:
        by_type.setdefault(d["direction"], []).append(d)

    print(f"Total deviations: {len(all_deviations)}\n")

    for dtype in ["corpus_missing", "corpus_gap", "more_relaxed", "stricter"]:
        devs = by_type.get(dtype, [])
        if not devs:
            continue
        print(f"  [{dtype}] — {len(devs)}")

        # Sub-group by rule
        by_rule = {}
        for d in devs:
            by_rule.setdefault(d["rule_violated"], []).append(d)
        for rule, rdevs in sorted(by_rule.items()):
            print(f"    {rule}: {len(rdevs)}")
            for d in rdevs[:2]:
                print(f"      {d['case_id']}/{d['item_id']}: {d['rule_detail']}")
            if len(rdevs) > 2:
                print(f"      ... +{len(rdevs) - 2} more")
        print()

    if not args.dry_run and all_deviations:
        db_path = get_db_path()
        print(f"Writing to DB: {db_path}")
        save_to_db(all_deviations, db_path)
        print(f"Saved {len(all_deviations)} deviations.")
    elif args.dry_run:
        print("(dry run — nothing written)")


if __name__ == "__main__":
    main()