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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
"""
RFP Cable Spec Matching — Gradio Prototype
Demonstrates Hybrid Retrieval across EXP1-EXP7 stress tests.
"""

import gradio as gr
import pandas as pd
import numpy as np
import json
import time
import re
from engine import (
    HybridRetrievalEngine,
    parse_spec_text,
    extract_noise,
    apply_numeric_perturbation,
    apply_unit_variation,
    apply_noise_injection,
    apply_missing_params,
    apply_partial_spec,
    apply_positional_shift,
    EXPERIMENT_DESCRIPTIONS,
    build_product_catalog,
)

# ── Global engine (loaded once) ────────────────────────────────
print("Initialising retrieval engine...")
ENGINE = HybridRetrievalEngine(model_name='all-mpnet-base-v2')
print("Engine ready.")

# ── Sample RFP specs for demo button ───────────────────────────
SAMPLE_SPECS = [
    {
        "spec_text":       "FRLS 11kV 3C 240sqmm Cu XLPE armoured cable as per IS 7098-2",
        "voltage_rating":  "11kV",
        "core_count":      "3",
        "size_sqmm":       "240.0",
        "conductor":       "Cu",
        "insulation":      "XLPE",
        "armouring":       "armoured",
        "fire_rating":     "FRLS",
        "standards":       "IS 7098-2",
        "mandatory_specs": "voltage_rating;core_count;size_sqmm",
        "label":           "11kV 3C 240sqmm Cu XLPE FRLS Armoured",
    },
    {
        "spec_text":       "FR 1.1kV 4C 6sqmm Cu PVC unarmoured cable as per IS 694",
        "voltage_rating":  "1.1kV",
        "core_count":      "4",
        "size_sqmm":       "6.0",
        "conductor":       "Cu",
        "insulation":      "PVC",
        "armouring":       "unarmoured",
        "fire_rating":     "FR",
        "standards":       "IS 694",
        "mandatory_specs": "voltage_rating",
        "label":           "1.1kV 4C 6sqmm Cu PVC FR Unarmoured",
    },
    {
        "spec_text":       "33kV 1C 300sqmm Al XLPE armoured cable as per IEC 60502-2",
        "voltage_rating":  "33kV",
        "core_count":      "1",
        "size_sqmm":       "300.0",
        "conductor":       "Al",
        "insulation":      "XLPE",
        "armouring":       "armoured",
        "fire_rating":     "",
        "standards":       "IEC 60502-2",
        "mandatory_specs": "voltage_rating;size_sqmm",
        "label":           "33kV 1C 300sqmm Al XLPE Armoured",
    },
]

EXPERIMENT_MODES = [
    ("🟢 Clean Baseline",              "clean"),
    ("🔴 EXP1 — Numeric Perturbation", "numeric_perturbation"),
    ("🟡 EXP2 — Unit Variation",       "unit_variation"),
    ("🟠 EXP3 — Missing Parameters",   "missing_params"),
    ("🔵 EXP4 — In-Domain Noise",      "noise_indomain"),
    ("🟣 EXP4 — Out-of-Domain Noise",  "noise_outdomain"),
    ("⚫ EXP6 — Partial Spec",         "partial_spec"),
    ("🔶 EXP7 — Positional Bias",      "positional_end"),
]
EXP_CHOICES = [label for label, _ in EXPERIMENT_MODES]
EXP_KEY_MAP = {label: key for label, key in EXPERIMENT_MODES}


def build_rfp_dict(spec_text, voltage, cores, size, conductor,
                   insulation, armouring, fire_rating, standards, mandatory):
    """Assemble RFP dict from UI fields."""
    # Parse from text if structured fields are empty
    if not voltage and not cores and not size:
        parsed = parse_spec_text(spec_text)
        voltage    = parsed['voltage_rating']   or voltage
        cores      = str(parsed['core_count'])  or cores
        size       = str(parsed['size_sqmm'])   or size
        conductor  = parsed['conductor_material'] or conductor
        insulation = parsed['insulation_type']  or insulation
        armouring  = parsed['armouring_type']   or armouring
        fire_rating= parsed['fire_rating']      or fire_rating
        standards  = parsed['standards_required'] or standards

    return {
        'spec_text_raw':      spec_text,
        'voltage_rating':     voltage.strip(),
        'core_count':         cores.strip(),
        'size_sqmm':          size.strip(),
        'conductor_material': conductor.strip(),
        'insulation_type':    insulation.strip(),
        'armouring_type':     armouring.strip(),
        'fire_rating':        fire_rating.strip(),
        'sheath_material':    '',
        'standards_required': standards.strip(),
        'mandatory_specs':    mandatory.strip(),
    }


def run_retrieval(spec_text, voltage, cores, size, conductor,
                  insulation, armouring, fire_rating, standards,
                  mandatory, experiment_mode, top_k):
    """Main inference function called by Gradio."""

    if not spec_text.strip():
        return "⚠️ Please enter a spec text.", "", "", pd.DataFrame()

    rfp = build_rfp_dict(spec_text, voltage, cores, size, conductor,
                         insulation, armouring, fire_rating, standards, mandatory)

    exp_key = EXP_KEY_MAP.get(experiment_mode, 'clean')

    # Apply experiment transformation
    if exp_key == 'numeric_perturbation':
        rfp_exp = apply_numeric_perturbation(rfp)
    elif exp_key == 'unit_variation':
        rfp_exp = apply_unit_variation(rfp)
    elif exp_key == 'missing_params':
        rfp_exp = apply_missing_params(rfp, n_drop=2)
    elif exp_key == 'noise_indomain':
        rfp_exp = apply_noise_injection(rfp, 'in_domain')
    elif exp_key == 'noise_outdomain':
        rfp_exp = apply_noise_injection(rfp, 'out_of_domain')
    elif exp_key == 'partial_spec':
        rfp_exp = apply_partial_spec(rfp, level=2)
    elif exp_key == 'positional_end':
        rfp_exp = apply_positional_shift(rfp, position='end')
    else:
        rfp_exp = rfp

    top_k = int(top_k)
    results = ENGINE.retrieve(rfp_exp, top_k=top_k)

    # Experiment info panel
    exp_info = EXPERIMENT_DESCRIPTIONS[exp_key]
    info_md = f"""### {exp_info['title']}
**What this tests:** {exp_info['description']}

**What changed in the spec:** `{exp_info['what_changes']}`

**Hybrid advantage:** _{exp_info['hybrid_advantage']}_

---
**Effective spec text sent to model:**
```
{rfp_exp['spec_text_raw'][:300]}{'...' if len(rfp_exp['spec_text_raw']) > 300 else ''}
```
"""

    # Score breakdown (top result)
    if results:
        top = results[0]
        latency = top['latency_ms']
        score_md = f"""### Top Match: `{top['sku_id']}` — {top['product_name']}

| Score Component | Value | Weight |
|---|---|---|
| 🏗️ Structured | **{top['structured_score']:.3f}** | 50% |
| 🧠 Semantic (MiniLM) | **{top['semantic_score']:.3f}** | 30% |
| 📋 Standards | **{top['standards_score']:.3f}** | 20% |
| **🎯 Hybrid Total** | **{top['hybrid_score']:.3f}** | 100% |

⚡ **Latency:** {latency} ms
"""
    else:
        score_md = "No results found."

    # Results table
    rows = []
    for r in results:
        rows.append({
            'Rank': r['rank'],
            'SKU ID': r['sku_id'],
            'Product': r['product_name'],
            'Voltage': r['voltage_rating'],
            'Cores': r['core_count'],
            'Size (sqmm)': r['size_sqmm'],
            'Conductor': r['conductor_material'],
            'Insulation': r['insulation_type'],
            'Armouring': r['armouring_type'],
            'Fire Rating': r['fire_rating'],
            'Standards': r['standards_complied'],
            '🎯 Hybrid': f"{r['hybrid_score']:.3f}",
            '🏗️ Struct': f"{r['structured_score']:.3f}",
            '🧠 Semantic': f"{r['semantic_score']:.3f}",
            '📋 Std': f"{r['standards_score']:.3f}",
        })

    df_results = pd.DataFrame(rows)
    return info_md, score_md, df_results


def fill_sample(sample_idx):
    """Fill all form fields from a sample spec."""
    s = SAMPLE_SPECS[int(sample_idx)]
    return (
        s["spec_text"],
        s["voltage_rating"],
        s["core_count"],
        s["size_sqmm"],
        s["conductor"],
        s["insulation"],
        s["armouring"],
        s["fire_rating"],
        s["standards"],
        s["mandatory_specs"],
    )


def auto_parse(spec_text):
    """Auto-fill structured fields from free text."""
    parsed = parse_spec_text(spec_text)
    return (
        parsed['voltage_rating'],
        str(parsed['core_count']) if parsed['core_count'] else '',
        str(parsed['size_sqmm']) if parsed['size_sqmm'] else '',
        parsed['conductor_material'],
        parsed['insulation_type'],
        parsed['armouring_type'],
        parsed['fire_rating'],
        parsed['standards_required'],
    )


# ── Compare all experiments for one spec ──────────────────────
def compare_all_experiments(spec_text, voltage, cores, size, conductor,
                             insulation, armouring, fire_rating, standards, mandatory):
    """Run all 8 experiment modes and return a comparison table."""
    if not spec_text.strip():
        return pd.DataFrame(), "⚠️ Enter a spec first."

    rfp_base = build_rfp_dict(spec_text, voltage, cores, size, conductor,
                               insulation, armouring, fire_rating, standards, mandatory)

    experiments = {
        'Clean Baseline':        rfp_base,
        'EXP1 Numeric Perturb':  apply_numeric_perturbation(rfp_base),
        'EXP2 Unit Variation':   apply_unit_variation(rfp_base),
        'EXP3 Missing Params':   apply_missing_params(rfp_base),
        'EXP4 In-Domain Noise':  apply_noise_injection(rfp_base, 'in_domain'),
        'EXP4 Out-Domain Noise': apply_noise_injection(rfp_base, 'out_of_domain'),
        'EXP6 Partial Spec':     apply_partial_spec(rfp_base),
        'EXP7 Positional Bias':  apply_positional_shift(rfp_base, 'end'),
    }

    rows = []
    for exp_name, rfp_exp in experiments.items():
        results = ENGINE.retrieve(rfp_exp, top_k=1)
        if results:
            r = results[0]
            rows.append({
                'Experiment': exp_name,
                'Top-1 SKU': r['sku_id'],
                'Top-1 Product': r['product_name'][:50],
                '🎯 Hybrid': f"{r['hybrid_score']:.3f}",
                '🏗️ Struct': f"{r['structured_score']:.3f}",
                '🧠 Semantic': f"{r['semantic_score']:.3f}",
                '📋 Std': f"{r['standards_score']:.3f}",
                '⚡ ms': r['latency_ms'],
            })

    df = pd.DataFrame(rows)
    summary = f"""### Comparison Summary
**Key Insight:** The 🏗️ Struct score stays stable across EXP1–EXP7 because it reads
structured columns (voltage_rating, core_count, size_sqmm etc.) — NOT the raw spec text.

The 🧠 Semantic score fluctuates when text is perturbed/noisy/partial — this is the SBERT
failure mode that the Hybrid model compensates for via the 50% structural weight.
"""
    return df, summary


# ──────────────────────────────────────────────────────────────
# GRADIO UI
# ──────────────────────────────────────────────────────────────
CSS = """
.gradio-container { font-family: 'Inter', sans-serif; }
.tab-nav button { font-weight: 600; }
#title-block { text-align: center; padding: 10px 0 5px 0; }
.score-box { border-radius: 8px; }
"""

with gr.Blocks(css=CSS, title="RFP Cable Spec Matcher", theme=gr.themes.Soft()) as demo:

    gr.HTML("""
    <div id="title-block">
        <h1>⚡ RFP Cable Specification Matcher</h1>
        <p style="color:#555; font-size:0.95em;">
            Hybrid Retrieval System &nbsp;|&nbsp; Structured (50%) + Semantic (30%) + Standards (20%)
            &nbsp;|&nbsp; Experiments EXP1–EXP7
        </p>
    </div>
    """)

    with gr.Tabs():

        # ── TAB 1: Single Query ──────────────────────────────
        with gr.Tab("🔍 Single Query"):
            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("### 📋 RFP Specification Input")

                    spec_text = gr.Textbox(
                        label="Free-text Spec (spec_text_raw)",
                        placeholder="e.g. FRLS 11kV 3C 240sqmm Cu XLPE armoured cable as per IS 7098-2",
                        lines=3,
                    )

                    with gr.Row():
                        auto_parse_btn = gr.Button("🔄 Auto-Parse Fields", variant="secondary", size="sm")
                        gr.Markdown("")

                    gr.Markdown("#### Structured Fields *(used by Hybrid for stress-test immunity)*")

                    with gr.Row():
                        voltage   = gr.Textbox(label="Voltage Rating", placeholder="e.g. 11kV")
                        cores     = gr.Textbox(label="Core Count", placeholder="e.g. 3")
                        size      = gr.Textbox(label="Size (sqmm)", placeholder="e.g. 240.0")

                    with gr.Row():
                        conductor   = gr.Dropdown(["Cu", "Al", ""], label="Conductor", value="Cu")
                        insulation  = gr.Dropdown(["XLPE", "PVC", "EPR", ""], label="Insulation", value="XLPE")
                        armouring   = gr.Dropdown(["armoured", "unarmoured", ""], label="Armouring", value="armoured")

                    with gr.Row():
                        fire_rating = gr.Dropdown(["FRLS", "FR", "LSZH", ""], label="Fire Rating", value="FRLS")
                        standards   = gr.Textbox(label="Standards Required", placeholder="e.g. IS 7098-2")
                        mandatory   = gr.Textbox(
                            label="Mandatory Fields (semicolon-separated)",
                            placeholder="e.g. voltage_rating;core_count;size_sqmm",
                            value="voltage_rating;core_count"
                        )

                    gr.Markdown("#### Experiment Mode")
                    experiment_mode = gr.Radio(
                        choices=EXP_CHOICES,
                        value=EXP_CHOICES[0],
                        label="Select stress test to apply",
                    )

                    with gr.Row():
                        top_k_slider = gr.Slider(1, 10, value=5, step=1, label="Top-K results")
                        run_btn = gr.Button("🚀 Run Retrieval", variant="primary", size="lg")

                    gr.Markdown("---\n#### 📦 Load Sample Spec")
                    with gr.Row():
                        for i, s in enumerate(SAMPLE_SPECS):
                            gr.Button(f"Sample {i+1}: {s['label']}", size="sm").click(
                                fn=lambda idx=i: fill_sample(idx),
                                inputs=[],
                                outputs=[spec_text, voltage, cores, size, conductor,
                                         insulation, armouring, fire_rating, standards, mandatory]
                            )

                with gr.Column(scale=3):
                    gr.Markdown("### 📊 Results")
                    exp_info_md   = gr.Markdown("*Run a query to see experiment info.*")
                    score_info_md = gr.Markdown("")
                    results_table = gr.DataFrame(label="Ranked Matches", wrap=True)

            run_btn.click(
                fn=run_retrieval,
                inputs=[spec_text, voltage, cores, size, conductor,
                        insulation, armouring, fire_rating, standards,
                        mandatory, experiment_mode, top_k_slider],
                outputs=[exp_info_md, score_info_md, results_table]
            )

            auto_parse_btn.click(
                fn=auto_parse,
                inputs=[spec_text],
                outputs=[voltage, cores, size, conductor,
                         insulation, armouring, fire_rating, standards]
            )

        # ── TAB 2: Compare All Experiments ──────────────────
        with gr.Tab("📊 Compare All Experiments"):
            gr.Markdown("""
### Run One Spec Across All 8 Experiment Modes
This shows exactly how Hybrid retrieval stays robust while SBERT-only would degrade.
Fill in a spec above (or load a sample) then click **Run Comparison**.
""")

            compare_btn = gr.Button("▶️ Run All 8 Experiments", variant="primary")
            compare_summary = gr.Markdown("")
            compare_table   = gr.DataFrame(label="Experiment Comparison", wrap=True)

            compare_btn.click(
                fn=compare_all_experiments,
                inputs=[spec_text, voltage, cores, size, conductor,
                        insulation, armouring, fire_rating, standards, mandatory],
                outputs=[compare_table, compare_summary]
            )

        # ── TAB 3: Experiment Reference ──────────────────────
        with gr.Tab("📖 Experiment Reference"):
            gr.Markdown("""
# Experiment Reference Guide

## System Architecture
**Hybrid Score = 0.50 × Structured + 0.30 × Semantic + 0.20 × Standards**

The structured score reads **structured columns** (`voltage_rating`, `core_count`, `size_sqmm`, etc.)
NOT the raw spec text — this is the core innovation.

---

## EXP1 — Numeric Sensitivity
**Dataset:** `rfp_specs_numeric_perturbation.csv`
Numbers in `spec_text_raw` are WRONG (11kV → 33kV, 240sqmm → 185sqmm, 3C → 4C).
Structured columns remain correct.
**Finding:** Hybrid Top-1 barely drops; SBERT drops >30 pts because it reads the text.

---

## EXP2 — Unit Variation
**Dataset:** `rfp_specs_unit_variation.csv`
Same meaning, different notation: `11kV` vs `11000V`, `sqmm` vs `mm²`, `3C` vs `3 Core`.
**Finding:** Hybrid is unit-aware by construction. SBERT is confused by token differences.

---

## EXP3 — Missing Parameters
**Dataset:** `rfp_specs_missing_specs.csv`
1–4 token types randomly dropped from `spec_text_raw`. Structured columns intact.
40.1% of rows drop at least one mandatory field.
**Finding:** Hybrid degrades minimally. SBERT loses critical embedding signal.

---

## EXP4 — Noise Injection
**Datasets:** In-domain (engineering boilerplate) + Out-of-domain (Bollywood/cricket)
~10 words prepended to spec text.
**Finding:** Out-of-domain noise hurts SBERT more; Hybrid unchanged (structured immune).

---

## EXP5 — Long Document Bias
**Dataset:** `rfp_specs_long_doc_noise.csv`
500–1300 word documents with spec buried inside (early/middle/late positions).
**Finding:** SBERT 512-token limit truncates long docs. Hybrid unaffected.

---

## EXP6 — Partial Specification
**Synthetic:** Generated in-notebook at 4/2/1 token completeness levels.
**Finding:** Hybrid maintains performance until Level 3 (1 token). SBERT drops at Level 2.

---

## EXP7 — Positional Bias
**Dataset:** `rfp_specs_positional_shift.csv`
Spec text placed at START, MIDDLE, or END of 22-31 word document.
**Finding:** SBERT has primacy bias. Hybrid structured score is position-invariant.

---

## Models Compared
| Model | Type | Notes |
|---|---|---|
| **Hybrid (MPNet)** | Structured + Semantic + Standards | Best overall across all 7 EXPs |
| MiniLM | SBERT only | Fast but sensitive to perturbations |
| TF-IDF | Lexical | Good for exact-match tokens |
| BM25 | Lexical | Probabilistic; better than TF-IDF on short queries |

*This prototype uses MiniLM for speed; the full system uses all-mpnet-base-v2.*
""")

    # ── Footer ───────────────────────────────────────────────
    gr.HTML("""
    <div style="text-align:center; margin-top:20px; color:#888; font-size:0.85em;">
        RFP Cable Spec Matcher &nbsp;|&nbsp; Major Project Prototype &nbsp;|&nbsp;
        Hybrid Retrieval: Structured + Semantic + Standards
    </div>
    """)

if __name__ == "__main__":
    demo.launch(share=False, server_name="0.0.0.0", server_port=7860)