dwaynefernandes05 commited on
Commit
95b7e07
·
0 Parent(s):

initial commit

Browse files
__pycache__/engine.cpython-312.pyc ADDED
Binary file (28.7 kB). View file
 
app.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RFP Cable Spec Matching — Gradio Prototype
3
+ Demonstrates Hybrid Retrieval across EXP1-EXP7 stress tests.
4
+ """
5
+
6
+ import gradio as gr
7
+ import pandas as pd
8
+ import numpy as np
9
+ import json
10
+ import time
11
+ import re
12
+ from engine import (
13
+ HybridRetrievalEngine,
14
+ parse_spec_text,
15
+ extract_noise,
16
+ apply_numeric_perturbation,
17
+ apply_unit_variation,
18
+ apply_noise_injection,
19
+ apply_missing_params,
20
+ apply_partial_spec,
21
+ apply_positional_shift,
22
+ EXPERIMENT_DESCRIPTIONS,
23
+ build_product_catalog,
24
+ )
25
+
26
+ # ── Global engine (loaded once) ────────────────────────────────
27
+ print("Initialising retrieval engine...")
28
+ ENGINE = HybridRetrievalEngine(model_name='all-mpnet-base-v2')
29
+ print("Engine ready.")
30
+
31
+ # ── Sample RFP specs for demo button ───────────────────────────
32
+ SAMPLE_SPECS = [
33
+ {
34
+ "spec_text": "FRLS 11kV 3C 240sqmm Cu XLPE armoured cable as per IS 7098-2",
35
+ "voltage_rating": "11kV",
36
+ "core_count": "3",
37
+ "size_sqmm": "240.0",
38
+ "conductor": "Cu",
39
+ "insulation": "XLPE",
40
+ "armouring": "armoured",
41
+ "fire_rating": "FRLS",
42
+ "standards": "IS 7098-2",
43
+ "mandatory_specs": "voltage_rating;core_count;size_sqmm",
44
+ "label": "11kV 3C 240sqmm Cu XLPE FRLS Armoured",
45
+ },
46
+ {
47
+ "spec_text": "FR 1.1kV 4C 6sqmm Cu PVC unarmoured cable as per IS 694",
48
+ "voltage_rating": "1.1kV",
49
+ "core_count": "4",
50
+ "size_sqmm": "6.0",
51
+ "conductor": "Cu",
52
+ "insulation": "PVC",
53
+ "armouring": "unarmoured",
54
+ "fire_rating": "FR",
55
+ "standards": "IS 694",
56
+ "mandatory_specs": "voltage_rating",
57
+ "label": "1.1kV 4C 6sqmm Cu PVC FR Unarmoured",
58
+ },
59
+ {
60
+ "spec_text": "33kV 1C 300sqmm Al XLPE armoured cable as per IEC 60502-2",
61
+ "voltage_rating": "33kV",
62
+ "core_count": "1",
63
+ "size_sqmm": "300.0",
64
+ "conductor": "Al",
65
+ "insulation": "XLPE",
66
+ "armouring": "armoured",
67
+ "fire_rating": "",
68
+ "standards": "IEC 60502-2",
69
+ "mandatory_specs": "voltage_rating;size_sqmm",
70
+ "label": "33kV 1C 300sqmm Al XLPE Armoured",
71
+ },
72
+ ]
73
+
74
+ EXPERIMENT_MODES = [
75
+ ("🟢 Clean Baseline", "clean"),
76
+ ("🔴 EXP1 — Numeric Perturbation", "numeric_perturbation"),
77
+ ("🟡 EXP2 — Unit Variation", "unit_variation"),
78
+ ("🟠 EXP3 — Missing Parameters", "missing_params"),
79
+ ("🔵 EXP4 — In-Domain Noise", "noise_indomain"),
80
+ ("🟣 EXP4 — Out-of-Domain Noise", "noise_outdomain"),
81
+ ("⚫ EXP6 — Partial Spec", "partial_spec"),
82
+ ("🔶 EXP7 — Positional Bias", "positional_end"),
83
+ ]
84
+ EXP_CHOICES = [label for label, _ in EXPERIMENT_MODES]
85
+ EXP_KEY_MAP = {label: key for label, key in EXPERIMENT_MODES}
86
+
87
+
88
+ def build_rfp_dict(spec_text, voltage, cores, size, conductor,
89
+ insulation, armouring, fire_rating, standards, mandatory):
90
+ """Assemble RFP dict from UI fields."""
91
+ # Parse from text if structured fields are empty
92
+ if not voltage and not cores and not size:
93
+ parsed = parse_spec_text(spec_text)
94
+ voltage = parsed['voltage_rating'] or voltage
95
+ cores = str(parsed['core_count']) or cores
96
+ size = str(parsed['size_sqmm']) or size
97
+ conductor = parsed['conductor_material'] or conductor
98
+ insulation = parsed['insulation_type'] or insulation
99
+ armouring = parsed['armouring_type'] or armouring
100
+ fire_rating= parsed['fire_rating'] or fire_rating
101
+ standards = parsed['standards_required'] or standards
102
+
103
+ return {
104
+ 'spec_text_raw': spec_text,
105
+ 'voltage_rating': voltage.strip(),
106
+ 'core_count': cores.strip(),
107
+ 'size_sqmm': size.strip(),
108
+ 'conductor_material': conductor.strip(),
109
+ 'insulation_type': insulation.strip(),
110
+ 'armouring_type': armouring.strip(),
111
+ 'fire_rating': fire_rating.strip(),
112
+ 'sheath_material': '',
113
+ 'standards_required': standards.strip(),
114
+ 'mandatory_specs': mandatory.strip(),
115
+ }
116
+
117
+
118
+ def run_retrieval(spec_text, voltage, cores, size, conductor,
119
+ insulation, armouring, fire_rating, standards,
120
+ mandatory, experiment_mode, top_k):
121
+ """Main inference function called by Gradio."""
122
+
123
+ if not spec_text.strip():
124
+ return "⚠️ Please enter a spec text.", "", "", pd.DataFrame()
125
+
126
+ rfp = build_rfp_dict(spec_text, voltage, cores, size, conductor,
127
+ insulation, armouring, fire_rating, standards, mandatory)
128
+
129
+ exp_key = EXP_KEY_MAP.get(experiment_mode, 'clean')
130
+
131
+ # Apply experiment transformation
132
+ if exp_key == 'numeric_perturbation':
133
+ rfp_exp = apply_numeric_perturbation(rfp)
134
+ elif exp_key == 'unit_variation':
135
+ rfp_exp = apply_unit_variation(rfp)
136
+ elif exp_key == 'missing_params':
137
+ rfp_exp = apply_missing_params(rfp, n_drop=2)
138
+ elif exp_key == 'noise_indomain':
139
+ rfp_exp = apply_noise_injection(rfp, 'in_domain')
140
+ elif exp_key == 'noise_outdomain':
141
+ rfp_exp = apply_noise_injection(rfp, 'out_of_domain')
142
+ elif exp_key == 'partial_spec':
143
+ rfp_exp = apply_partial_spec(rfp, level=2)
144
+ elif exp_key == 'positional_end':
145
+ rfp_exp = apply_positional_shift(rfp, position='end')
146
+ else:
147
+ rfp_exp = rfp
148
+
149
+ top_k = int(top_k)
150
+ results = ENGINE.retrieve(rfp_exp, top_k=top_k)
151
+
152
+ # Experiment info panel
153
+ exp_info = EXPERIMENT_DESCRIPTIONS[exp_key]
154
+ info_md = f"""### {exp_info['title']}
155
+ **What this tests:** {exp_info['description']}
156
+
157
+ **What changed in the spec:** `{exp_info['what_changes']}`
158
+
159
+ **Hybrid advantage:** _{exp_info['hybrid_advantage']}_
160
+
161
+ ---
162
+ **Effective spec text sent to model:**
163
+ ```
164
+ {rfp_exp['spec_text_raw'][:300]}{'...' if len(rfp_exp['spec_text_raw']) > 300 else ''}
165
+ ```
166
+ """
167
+
168
+ # Score breakdown (top result)
169
+ if results:
170
+ top = results[0]
171
+ latency = top['latency_ms']
172
+ score_md = f"""### Top Match: `{top['sku_id']}` — {top['product_name']}
173
+
174
+ | Score Component | Value | Weight |
175
+ |---|---|---|
176
+ | 🏗️ Structured | **{top['structured_score']:.3f}** | 50% |
177
+ | 🧠 Semantic (MiniLM) | **{top['semantic_score']:.3f}** | 30% |
178
+ | 📋 Standards | **{top['standards_score']:.3f}** | 20% |
179
+ | **🎯 Hybrid Total** | **{top['hybrid_score']:.3f}** | 100% |
180
+
181
+ ⚡ **Latency:** {latency} ms
182
+ """
183
+ else:
184
+ score_md = "No results found."
185
+
186
+ # Results table
187
+ rows = []
188
+ for r in results:
189
+ rows.append({
190
+ 'Rank': r['rank'],
191
+ 'SKU ID': r['sku_id'],
192
+ 'Product': r['product_name'],
193
+ 'Voltage': r['voltage_rating'],
194
+ 'Cores': r['core_count'],
195
+ 'Size (sqmm)': r['size_sqmm'],
196
+ 'Conductor': r['conductor_material'],
197
+ 'Insulation': r['insulation_type'],
198
+ 'Armouring': r['armouring_type'],
199
+ 'Fire Rating': r['fire_rating'],
200
+ 'Standards': r['standards_complied'],
201
+ '🎯 Hybrid': f"{r['hybrid_score']:.3f}",
202
+ '🏗️ Struct': f"{r['structured_score']:.3f}",
203
+ '🧠 Semantic': f"{r['semantic_score']:.3f}",
204
+ '📋 Std': f"{r['standards_score']:.3f}",
205
+ })
206
+
207
+ df_results = pd.DataFrame(rows)
208
+ return info_md, score_md, df_results
209
+
210
+
211
+ def fill_sample(sample_idx):
212
+ """Fill all form fields from a sample spec."""
213
+ s = SAMPLE_SPECS[int(sample_idx)]
214
+ return (
215
+ s["spec_text"],
216
+ s["voltage_rating"],
217
+ s["core_count"],
218
+ s["size_sqmm"],
219
+ s["conductor"],
220
+ s["insulation"],
221
+ s["armouring"],
222
+ s["fire_rating"],
223
+ s["standards"],
224
+ s["mandatory_specs"],
225
+ )
226
+
227
+
228
+ def auto_parse(spec_text):
229
+ """Auto-fill structured fields from free text."""
230
+ parsed = parse_spec_text(spec_text)
231
+ return (
232
+ parsed['voltage_rating'],
233
+ str(parsed['core_count']) if parsed['core_count'] else '',
234
+ str(parsed['size_sqmm']) if parsed['size_sqmm'] else '',
235
+ parsed['conductor_material'],
236
+ parsed['insulation_type'],
237
+ parsed['armouring_type'],
238
+ parsed['fire_rating'],
239
+ parsed['standards_required'],
240
+ )
241
+
242
+
243
+ # ── Compare all experiments for one spec ──────────────────────
244
+ def compare_all_experiments(spec_text, voltage, cores, size, conductor,
245
+ insulation, armouring, fire_rating, standards, mandatory):
246
+ """Run all 8 experiment modes and return a comparison table."""
247
+ if not spec_text.strip():
248
+ return pd.DataFrame(), "⚠️ Enter a spec first."
249
+
250
+ rfp_base = build_rfp_dict(spec_text, voltage, cores, size, conductor,
251
+ insulation, armouring, fire_rating, standards, mandatory)
252
+
253
+ experiments = {
254
+ 'Clean Baseline': rfp_base,
255
+ 'EXP1 Numeric Perturb': apply_numeric_perturbation(rfp_base),
256
+ 'EXP2 Unit Variation': apply_unit_variation(rfp_base),
257
+ 'EXP3 Missing Params': apply_missing_params(rfp_base),
258
+ 'EXP4 In-Domain Noise': apply_noise_injection(rfp_base, 'in_domain'),
259
+ 'EXP4 Out-Domain Noise': apply_noise_injection(rfp_base, 'out_of_domain'),
260
+ 'EXP6 Partial Spec': apply_partial_spec(rfp_base),
261
+ 'EXP7 Positional Bias': apply_positional_shift(rfp_base, 'end'),
262
+ }
263
+
264
+ rows = []
265
+ for exp_name, rfp_exp in experiments.items():
266
+ results = ENGINE.retrieve(rfp_exp, top_k=1)
267
+ if results:
268
+ r = results[0]
269
+ rows.append({
270
+ 'Experiment': exp_name,
271
+ 'Top-1 SKU': r['sku_id'],
272
+ 'Top-1 Product': r['product_name'][:50],
273
+ '🎯 Hybrid': f"{r['hybrid_score']:.3f}",
274
+ '🏗️ Struct': f"{r['structured_score']:.3f}",
275
+ '🧠 Semantic': f"{r['semantic_score']:.3f}",
276
+ '📋 Std': f"{r['standards_score']:.3f}",
277
+ '⚡ ms': r['latency_ms'],
278
+ })
279
+
280
+ df = pd.DataFrame(rows)
281
+ summary = f"""### Comparison Summary
282
+ **Key Insight:** The 🏗️ Struct score stays stable across EXP1–EXP7 because it reads
283
+ structured columns (voltage_rating, core_count, size_sqmm etc.) — NOT the raw spec text.
284
+
285
+ The 🧠 Semantic score fluctuates when text is perturbed/noisy/partial — this is the SBERT
286
+ failure mode that the Hybrid model compensates for via the 50% structural weight.
287
+ """
288
+ return df, summary
289
+
290
+
291
+ # ──────────────────────────────────────────────────────────────
292
+ # GRADIO UI
293
+ # ──────────────────────────────────────────────────────────────
294
+ CSS = """
295
+ .gradio-container { font-family: 'Inter', sans-serif; }
296
+ .tab-nav button { font-weight: 600; }
297
+ #title-block { text-align: center; padding: 10px 0 5px 0; }
298
+ .score-box { border-radius: 8px; }
299
+ """
300
+
301
+ with gr.Blocks(css=CSS, title="RFP Cable Spec Matcher", theme=gr.themes.Soft()) as demo:
302
+
303
+ gr.HTML("""
304
+ <div id="title-block">
305
+ <h1>⚡ RFP Cable Specification Matcher</h1>
306
+ <p style="color:#555; font-size:0.95em;">
307
+ Hybrid Retrieval System &nbsp;|&nbsp; Structured (50%) + Semantic (30%) + Standards (20%)
308
+ &nbsp;|&nbsp; Experiments EXP1–EXP7
309
+ </p>
310
+ </div>
311
+ """)
312
+
313
+ with gr.Tabs():
314
+
315
+ # ── TAB 1: Single Query ──────────────────────────────
316
+ with gr.Tab("🔍 Single Query"):
317
+ with gr.Row():
318
+ with gr.Column(scale=2):
319
+ gr.Markdown("### 📋 RFP Specification Input")
320
+
321
+ spec_text = gr.Textbox(
322
+ label="Free-text Spec (spec_text_raw)",
323
+ placeholder="e.g. FRLS 11kV 3C 240sqmm Cu XLPE armoured cable as per IS 7098-2",
324
+ lines=3,
325
+ )
326
+
327
+ with gr.Row():
328
+ auto_parse_btn = gr.Button("🔄 Auto-Parse Fields", variant="secondary", size="sm")
329
+ gr.Markdown("")
330
+
331
+ gr.Markdown("#### Structured Fields *(used by Hybrid for stress-test immunity)*")
332
+
333
+ with gr.Row():
334
+ voltage = gr.Textbox(label="Voltage Rating", placeholder="e.g. 11kV")
335
+ cores = gr.Textbox(label="Core Count", placeholder="e.g. 3")
336
+ size = gr.Textbox(label="Size (sqmm)", placeholder="e.g. 240.0")
337
+
338
+ with gr.Row():
339
+ conductor = gr.Dropdown(["Cu", "Al", ""], label="Conductor", value="Cu")
340
+ insulation = gr.Dropdown(["XLPE", "PVC", "EPR", ""], label="Insulation", value="XLPE")
341
+ armouring = gr.Dropdown(["armoured", "unarmoured", ""], label="Armouring", value="armoured")
342
+
343
+ with gr.Row():
344
+ fire_rating = gr.Dropdown(["FRLS", "FR", "LSZH", ""], label="Fire Rating", value="FRLS")
345
+ standards = gr.Textbox(label="Standards Required", placeholder="e.g. IS 7098-2")
346
+ mandatory = gr.Textbox(
347
+ label="Mandatory Fields (semicolon-separated)",
348
+ placeholder="e.g. voltage_rating;core_count;size_sqmm",
349
+ value="voltage_rating;core_count"
350
+ )
351
+
352
+ gr.Markdown("#### Experiment Mode")
353
+ experiment_mode = gr.Radio(
354
+ choices=EXP_CHOICES,
355
+ value=EXP_CHOICES[0],
356
+ label="Select stress test to apply",
357
+ )
358
+
359
+ with gr.Row():
360
+ top_k_slider = gr.Slider(1, 10, value=5, step=1, label="Top-K results")
361
+ run_btn = gr.Button("🚀 Run Retrieval", variant="primary", size="lg")
362
+
363
+ gr.Markdown("---\n#### 📦 Load Sample Spec")
364
+ with gr.Row():
365
+ for i, s in enumerate(SAMPLE_SPECS):
366
+ gr.Button(f"Sample {i+1}: {s['label']}", size="sm").click(
367
+ fn=lambda idx=i: fill_sample(idx),
368
+ inputs=[],
369
+ outputs=[spec_text, voltage, cores, size, conductor,
370
+ insulation, armouring, fire_rating, standards, mandatory]
371
+ )
372
+
373
+ with gr.Column(scale=3):
374
+ gr.Markdown("### 📊 Results")
375
+ exp_info_md = gr.Markdown("*Run a query to see experiment info.*")
376
+ score_info_md = gr.Markdown("")
377
+ results_table = gr.DataFrame(label="Ranked Matches", wrap=True)
378
+
379
+ run_btn.click(
380
+ fn=run_retrieval,
381
+ inputs=[spec_text, voltage, cores, size, conductor,
382
+ insulation, armouring, fire_rating, standards,
383
+ mandatory, experiment_mode, top_k_slider],
384
+ outputs=[exp_info_md, score_info_md, results_table]
385
+ )
386
+
387
+ auto_parse_btn.click(
388
+ fn=auto_parse,
389
+ inputs=[spec_text],
390
+ outputs=[voltage, cores, size, conductor,
391
+ insulation, armouring, fire_rating, standards]
392
+ )
393
+
394
+ # ── TAB 2: Compare All Experiments ──────────────────
395
+ with gr.Tab("📊 Compare All Experiments"):
396
+ gr.Markdown("""
397
+ ### Run One Spec Across All 8 Experiment Modes
398
+ This shows exactly how Hybrid retrieval stays robust while SBERT-only would degrade.
399
+ Fill in a spec above (or load a sample) then click **Run Comparison**.
400
+ """)
401
+
402
+ compare_btn = gr.Button("▶️ Run All 8 Experiments", variant="primary")
403
+ compare_summary = gr.Markdown("")
404
+ compare_table = gr.DataFrame(label="Experiment Comparison", wrap=True)
405
+
406
+ compare_btn.click(
407
+ fn=compare_all_experiments,
408
+ inputs=[spec_text, voltage, cores, size, conductor,
409
+ insulation, armouring, fire_rating, standards, mandatory],
410
+ outputs=[compare_table, compare_summary]
411
+ )
412
+
413
+ # ── TAB 3: Experiment Reference ──────────────────────
414
+ with gr.Tab("📖 Experiment Reference"):
415
+ gr.Markdown("""
416
+ # Experiment Reference Guide
417
+
418
+ ## System Architecture
419
+ **Hybrid Score = 0.50 × Structured + 0.30 × Semantic + 0.20 × Standards**
420
+
421
+ The structured score reads **structured columns** (`voltage_rating`, `core_count`, `size_sqmm`, etc.)
422
+ NOT the raw spec text — this is the core innovation.
423
+
424
+ ---
425
+
426
+ ## EXP1 — Numeric Sensitivity
427
+ **Dataset:** `rfp_specs_numeric_perturbation.csv`
428
+ Numbers in `spec_text_raw` are WRONG (11kV → 33kV, 240sqmm → 185sqmm, 3C → 4C).
429
+ Structured columns remain correct.
430
+ **Finding:** Hybrid Top-1 barely drops; SBERT drops >30 pts because it reads the text.
431
+
432
+ ---
433
+
434
+ ## EXP2 — Unit Variation
435
+ **Dataset:** `rfp_specs_unit_variation.csv`
436
+ Same meaning, different notation: `11kV` vs `11000V`, `sqmm` vs `mm²`, `3C` vs `3 Core`.
437
+ **Finding:** Hybrid is unit-aware by construction. SBERT is confused by token differences.
438
+
439
+ ---
440
+
441
+ ## EXP3 — Missing Parameters
442
+ **Dataset:** `rfp_specs_missing_specs.csv`
443
+ 1–4 token types randomly dropped from `spec_text_raw`. Structured columns intact.
444
+ 40.1% of rows drop at least one mandatory field.
445
+ **Finding:** Hybrid degrades minimally. SBERT loses critical embedding signal.
446
+
447
+ ---
448
+
449
+ ## EXP4 — Noise Injection
450
+ **Datasets:** In-domain (engineering boilerplate) + Out-of-domain (Bollywood/cricket)
451
+ ~10 words prepended to spec text.
452
+ **Finding:** Out-of-domain noise hurts SBERT more; Hybrid unchanged (structured immune).
453
+
454
+ ---
455
+
456
+ ## EXP5 — Long Document Bias
457
+ **Dataset:** `rfp_specs_long_doc_noise.csv`
458
+ 500–1300 word documents with spec buried inside (early/middle/late positions).
459
+ **Finding:** SBERT 512-token limit truncates long docs. Hybrid unaffected.
460
+
461
+ ---
462
+
463
+ ## EXP6 — Partial Specification
464
+ **Synthetic:** Generated in-notebook at 4/2/1 token completeness levels.
465
+ **Finding:** Hybrid maintains performance until Level 3 (1 token). SBERT drops at Level 2.
466
+
467
+ ---
468
+
469
+ ## EXP7 — Positional Bias
470
+ **Dataset:** `rfp_specs_positional_shift.csv`
471
+ Spec text placed at START, MIDDLE, or END of 22-31 word document.
472
+ **Finding:** SBERT has primacy bias. Hybrid structured score is position-invariant.
473
+
474
+ ---
475
+
476
+ ## Models Compared
477
+ | Model | Type | Notes |
478
+ |---|---|---|
479
+ | **Hybrid (MPNet)** | Structured + Semantic + Standards | Best overall across all 7 EXPs |
480
+ | MiniLM | SBERT only | Fast but sensitive to perturbations |
481
+ | TF-IDF | Lexical | Good for exact-match tokens |
482
+ | BM25 | Lexical | Probabilistic; better than TF-IDF on short queries |
483
+
484
+ *This prototype uses MiniLM for speed; the full system uses all-mpnet-base-v2.*
485
+ """)
486
+
487
+ # ── Footer ───────────────────────────────────────────────
488
+ gr.HTML("""
489
+ <div style="text-align:center; margin-top:20px; color:#888; font-size:0.85em;">
490
+ RFP Cable Spec Matcher &nbsp;|&nbsp; Major Project Prototype &nbsp;|&nbsp;
491
+ Hybrid Retrieval: Structured + Semantic + Standards
492
+ </div>
493
+ """)
494
+
495
+ if __name__ == "__main__":
496
+ demo.launch(share=False, server_name="0.0.0.0", server_port=7860)
engine.py ADDED
@@ -0,0 +1,635 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RFP Cable Spec Matching Engine
3
+ Implements Hybrid Retrieval: Structured + Semantic (MPNet) + Standards scoring
4
+ Based on Experiments 1-7 from the major project.
5
+
6
+ Key findings encoded here:
7
+ - EXP1: Structured score is numeric-perturbation-immune (uses structured columns, not raw text)
8
+ - EXP2: Unit-aware via structured columns (11kV == 11000V handled by normalization)
9
+ - EXP3: Missing params → structured score compensates for text gaps
10
+ - EXP4: Noise-immune via structured scoring (50% weight)
11
+ - EXP5: Long-doc robust → structured score is position/length invariant
12
+ - EXP6: Partial spec → minimum viable spec handled via structured fallback
13
+ - EXP7: Positional bias → structured score is position-invariant by design
14
+ """
15
+
16
+ import re
17
+ import time
18
+ import numpy as np
19
+ import pandas as pd
20
+ from sklearn.feature_extraction.text import TfidfVectorizer
21
+ from sentence_transformers import SentenceTransformer
22
+ from rank_bm25 import BM25Okapi
23
+ from typing import List, Dict, Tuple, Optional
24
+ import warnings
25
+ warnings.filterwarnings('ignore')
26
+
27
+ # ──────────────────────────────────────────────────────────────
28
+ # CONSTANTS (from obj1_model_artifacts/model_config.json)
29
+ # ──────────────────────────────────────────────────────────────
30
+ HYBRID_WEIGHTS = (0.75, 0.15, 0.10) # structured, semantic, standards
31
+ K = 5
32
+ EXACT_FIELDS = [
33
+ 'voltage_rating', 'insulation_type', 'conductor_material',
34
+ 'armouring_type', 'fire_rating', 'sheath_material'
35
+ ]
36
+
37
+ _SIZE_LADDER = [
38
+ 0.5, 0.75, 1.0, 1.5, 2.5, 4.0, 6.0, 10.0, 16.0, 25.0, 35.0,
39
+ 50.0, 70.0, 95.0, 120.0, 150.0, 185.0, 240.0, 300.0, 400.0,
40
+ 500.0, 630.0, 800.0, 1000.0
41
+ ]
42
+ _SIZE_SET = set(_SIZE_LADDER)
43
+
44
+ # ──────────────────────────────────────────────────────────────
45
+ # UNIT NORMALISATION (EXP 2 insight: 11kV == 11000V)
46
+ # ──────────────────────────────────────────────────────────────
47
+ def normalise_voltage(text: str) -> str:
48
+ """Convert kV notation to V and vice-versa for canonical form."""
49
+ def _kv_to_v(m):
50
+ val = float(m.group(1))
51
+ return f"{int(val * 1000)}V"
52
+ text = re.sub(r'(\d+(?:\.\d+)?)kV', _kv_to_v, text)
53
+ text = re.sub(r'(\d+) Core', r'\1C', text)
54
+ text = re.sub(r'(\d+(?:\.\d+)?) mm²', r'\1sqmm', text)
55
+ text = re.sub(r'\bCopper\b', 'Cu', text)
56
+ text = re.sub(r'\bAluminium\b|\bAluminum\b', 'Al', text)
57
+ return text
58
+
59
+
60
+ def _adjacent_sizes(val: float):
61
+ if val not in _SIZE_SET:
62
+ val = min(_SIZE_LADDER, key=lambda x: abs(x - val))
63
+ idx = _SIZE_LADDER.index(val)
64
+ nbrs = {val}
65
+ if idx > 0:
66
+ nbrs.add(_SIZE_LADDER[idx - 1])
67
+ if idx < len(_SIZE_LADDER) - 1:
68
+ nbrs.add(_SIZE_LADDER[idx + 1])
69
+ return nbrs
70
+
71
+
72
+ # ──────────────────────────────────────────────────────────────
73
+ # SCORING FUNCTIONS (identical to all 7 notebooks)
74
+ # ──────────────────────────────────────────────────────────────
75
+ def structured_score(rfp: dict, sku: dict, mandatory: set = None) -> float:
76
+ if mandatory is None:
77
+ mandatory = set()
78
+ score = total = 0.0
79
+ for field in EXACT_FIELDS:
80
+ w = 2.0 if field in mandatory else 1.0
81
+ total += w
82
+ r_val = str(rfp.get(field, '')).strip().lower()
83
+ s_val = str(sku.get(field, '')).strip().lower()
84
+ if r_val and r_val != 'nan' and r_val == s_val:
85
+ score += w
86
+
87
+ # Core count
88
+ w_cc = 4.0 if 'core_count' in mandatory else 2.0
89
+ total += w_cc
90
+ try:
91
+ if int(float(rfp['core_count'])) == int(float(sku['core_count'])):
92
+ score += w_cc
93
+ except Exception:
94
+ pass
95
+
96
+ # Size (adjacent-size tolerance — EXP1 insight)
97
+ w_sz = 2.0 if 'size_sqmm' in mandatory else 1.0
98
+ total += w_sz
99
+ try:
100
+ if float(rfp['size_sqmm']) == float(sku['size_sqmm']):
101
+ score += w_sz
102
+ except Exception:
103
+ pass
104
+
105
+ return score / total if total > 0 else 0.0
106
+
107
+
108
+ def standards_score(rfp: dict, sku: dict) -> float:
109
+ r = str(rfp.get('standards_required', '')).strip().lower()
110
+ s = str(sku.get('standards_complied', '')).strip().lower()
111
+ if not r or r == 'nan':
112
+ return 0.0
113
+ return 1.0 if (r in s or s in r) else 0.0
114
+
115
+
116
+ def hybrid_score(s_struct: float, s_sem: float, s_std: float,
117
+ ws: float = 0.50, we: float = 0.30, wt: float = 0.20) -> float:
118
+ return ws * s_struct + we * s_sem + wt * s_std
119
+
120
+
121
+ # ──────────────────────────────────────────────────────────────
122
+ # INPUT PARSING (handles unit variants from EXP2)
123
+ # ──────────────────────────────────────────────────────────────
124
+ def parse_spec_text(text: str) -> dict:
125
+ """
126
+ Parse free-text RFP spec into structured fields.
127
+ Handles unit variants, missing params, noise (EXP 2,3,4 robustness).
128
+ """
129
+ text_norm = normalise_voltage(text)
130
+
131
+ # Voltage
132
+ voltage = None
133
+ v_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:kV|KV|kv)', text)
134
+ if v_match:
135
+ voltage = f"{v_match.group(1)}kV"
136
+ else:
137
+ v_match2 = re.search(r'(\d{3,6})\s*V\b', text_norm)
138
+ if v_match2:
139
+ voltage = f"{int(int(v_match2.group(1))/1000)}kV" if int(v_match2.group(1)) >= 1000 else f"0.{v_match2.group(1)}kV"
140
+
141
+ # Core count
142
+ core = None
143
+ c_match = re.search(r'(\d+)\s*(?:C\b|[Cc]ore)', text)
144
+ if c_match:
145
+ core = int(c_match.group(1))
146
+
147
+ # Size
148
+ size = None
149
+ s_match = re.search(r'(\d+(?:\.\d+)?)\s*(?:sqmm|mm²|sq\.mm|sq mm)', text, re.IGNORECASE)
150
+ if s_match:
151
+ size = float(s_match.group(1))
152
+
153
+ # Conductor
154
+ conductor = None
155
+ if re.search(r'\bCu\b|\bCopper\b', text, re.IGNORECASE):
156
+ conductor = 'Cu'
157
+ elif re.search(r'\bAl\b|\bAlumini?um\b', text, re.IGNORECASE):
158
+ conductor = 'Al'
159
+
160
+ # Insulation
161
+ insulation = None
162
+ for ins in ['XLPE', 'PVC', 'EPR']:
163
+ if re.search(rf'\b{ins}\b', text, re.IGNORECASE):
164
+ insulation = ins
165
+ break
166
+
167
+ # Fire rating
168
+ fire_rating = None
169
+ for fr in ['FRLS', 'LSZH', 'ZH', 'FR']:
170
+ if re.search(rf'\b{fr}\b', text, re.IGNORECASE):
171
+ fire_rating = fr
172
+ break
173
+
174
+ # Armouring
175
+ armouring = None
176
+ if re.search(r'\barmoure?d\b', text, re.IGNORECASE):
177
+ armouring = 'armoured'
178
+ elif re.search(r'\bunarm', text, re.IGNORECASE):
179
+ armouring = 'unarmoured'
180
+
181
+ # Standards
182
+ std_match = re.search(r'((?:IS|IEC|BS|IEEE)\s*[\d\-]+(?:[\:\-]\d+)?)', text, re.IGNORECASE)
183
+ standards = std_match.group(1).upper() if std_match else None
184
+
185
+ return {
186
+ 'voltage_rating': voltage or '',
187
+ 'core_count': core or '',
188
+ 'size_sqmm': size or '',
189
+ 'conductor_material': conductor or '',
190
+ 'insulation_type': insulation or '',
191
+ 'fire_rating': fire_rating or '',
192
+ 'armouring_type': armouring or '',
193
+ 'sheath_material': '',
194
+ 'standards_required': standards or '',
195
+ 'spec_text_raw': text,
196
+ 'mandatory_specs': '',
197
+ }
198
+
199
+
200
+ def extract_noise(text: str) -> Tuple[str, str]:
201
+ """
202
+ Detect and strip noise from spec text (EXP4 + EXP5 insight).
203
+ Returns (clean_spec, detected_noise_description).
204
+ """
205
+ # Try to find the cable spec core
206
+ cable_pattern = r'(?:FRLS\s+|FR\s+|LSZH\s+)?(?:\d+(?:\.\d+)?kV\s+)?(?:\d+C?\s+)?(?:\d+(?:\.\d+)?\s*sqmm\s+)?(?:Cu|Al\s+)?(?:XLPE|PVC|EPR\s+)?(?:armou?red\s+)?cable(?:\s+as\s+per\s+\w+\s*[\d\-]+)?'
207
+ match = re.search(cable_pattern, text, re.IGNORECASE)
208
+ if match and len(match.group(0)) > 5:
209
+ core = match.group(0).strip()
210
+ noise_len = len(text) - len(core)
211
+ if noise_len > 20:
212
+ return core, f"~{noise_len} chars of context/noise stripped"
213
+ return text, "no noise detected"
214
+
215
+
216
+ # ──────────────────────────────────────────────────────────────
217
+ # SYNTHETIC PRODUCT CATALOG (mirrors obj1_model_artifacts)
218
+ # ──────────────────────────────────────────────────────────────
219
+ def build_product_catalog() -> pd.DataFrame:
220
+ """
221
+ Synthetic product catalog with realistic cable SKUs.
222
+ In production this would be loaded from product_df.parquet.
223
+ """
224
+ voltages = ['1.1kV', '3.3kV', '6.6kV', '11kV', '33kV', '66kV', '132kV']
225
+ cores = [1, 2, 3, 4]
226
+ sizes = [1.5, 2.5, 4.0, 6.0, 10.0, 16.0, 25.0, 35.0, 50.0, 70.0, 95.0,
227
+ 120.0, 150.0, 185.0, 240.0, 300.0, 400.0]
228
+ conductors = ['Cu', 'Al']
229
+ insulations= ['XLPE', 'PVC']
230
+ armourings = ['armoured', 'unarmoured']
231
+ fire_ratings = ['FRLS', 'FR', '']
232
+ standards_map = {
233
+ '1.1kV': 'IS 694', '3.3kV': 'IS 7098-1', '6.6kV': 'IS 7098-1',
234
+ '11kV': 'IS 7098-2', '33kV': 'IS 7098-2', '66kV': 'IEC 60502-2',
235
+ '132kV': 'IEC 60502-2'
236
+ }
237
+
238
+ rows = []
239
+ sku_id = 1000
240
+
241
+ for v in voltages:
242
+ for c in cores:
243
+ for sz in sizes:
244
+ for cond in conductors:
245
+ for ins in insulations:
246
+ for arm in armourings:
247
+ for fr in fire_ratings[:2]:
248
+
249
+ name_parts = []
250
+
251
+ if fr:
252
+ name_parts.append(fr)
253
+
254
+ name_parts += [
255
+ v,
256
+ f'{c}C',
257
+ f'{sz}sqmm',
258
+ cond,
259
+ ins
260
+ ]
261
+
262
+ if arm == 'armoured':
263
+ name_parts.append('armoured')
264
+
265
+ name_parts.append('cable')
266
+
267
+ rows.append({
268
+ 'sku_id': f'SKU-{sku_id}',
269
+ 'product_name': ' '.join(name_parts),
270
+ 'voltage_rating': v,
271
+ 'core_count': c,
272
+ 'size_sqmm': sz,
273
+ 'conductor_material': cond,
274
+ 'insulation_type': ins,
275
+ 'armouring_type': arm,
276
+ 'fire_rating': fr,
277
+ 'sheath_material': 'PVC',
278
+ 'standards_complied': standards_map.get(v, 'IS 694'),
279
+ })
280
+
281
+ sku_id += 1
282
+
283
+ return pd.DataFrame(rows)
284
+
285
+
286
+ # ──────────────────────────────────────────────────────────────
287
+ # MAIN RETRIEVAL ENGINE
288
+ # ──────────────────────────────────────────────────────────────
289
+ class HybridRetrievalEngine:
290
+ """
291
+ Hybrid Retrieval: Structured (50%) + Semantic/MPNet (30%) + Standards (20%).
292
+ Weights proven optimal across EXP1-EXP7.
293
+ """
294
+
295
+ def __init__(self, product_df: pd.DataFrame = None, model_name: str = 'all-MiniLM-L6-v2'):
296
+ if product_df is not None:
297
+ self.product_df = product_df
298
+ else:
299
+ self.product_df = pd.read_parquet("product_df.parquet")
300
+ self.product_df = self.product_df.reset_index(drop=True)
301
+
302
+ print(f"[Engine] Loading semantic model: {model_name} ...")
303
+ t0 = time.time()
304
+ self.model = SentenceTransformer(model_name)
305
+ self.model_name = model_name
306
+
307
+ # Pre-encode product catalog
308
+ self.product_emb = np.load("product_embeddings_mpnet.npy")
309
+
310
+ self.product_emb = self.product_emb.astype(np.float32)
311
+ print(f"[Engine] Product embeddings ready ({len(prod_texts)} SKUs) in {time.time()-t0:.1f}s")
312
+
313
+ # Pre-build BM25 and TF-IDF on catalog
314
+ tokenized = [t.lower().split() for t in prod_texts]
315
+ self.bm25 = BM25Okapi(tokenized)
316
+
317
+ self.tfidf_vec = TfidfVectorizer(ngram_range=(1, 2), min_df=1, sublinear_tf=True)
318
+ self.tfidf_prod = self.tfidf_vec.fit_transform(prod_texts)
319
+
320
+ print("[Engine] Ready.")
321
+
322
+ def encode_query(self, text: str) -> np.ndarray:
323
+ return self.model.encode(
324
+ [text], normalize_embeddings=True, show_progress_bar=False
325
+ ).astype(np.float32)[0]
326
+
327
+ def apply_hard_filters(self, rfp_input):
328
+
329
+ mask = np.ones(len(self.product_df), dtype=bool)
330
+
331
+ # Voltage
332
+ if rfp_input.get('voltage_rating'):
333
+ mask &= (
334
+ self.product_df['voltage_rating']
335
+ .astype(str)
336
+ .str.lower()
337
+ ==
338
+ str(rfp_input['voltage_rating']).lower()
339
+ )
340
+
341
+ # Core Count
342
+ if rfp_input.get('core_count'):
343
+ mask &= (
344
+ self.product_df['core_count']
345
+ .astype(str)
346
+ ==
347
+ str(rfp_input['core_count'])
348
+ )
349
+
350
+ # Conductor
351
+ if rfp_input.get('conductor_material'):
352
+ mask &= (
353
+ self.product_df['conductor_material']
354
+ .astype(str)
355
+ .str.lower()
356
+ ==
357
+ str(rfp_input['conductor_material']).lower()
358
+ )
359
+
360
+ # Insulation
361
+ if rfp_input.get('insulation_type'):
362
+ mask &= (
363
+ self.product_df['insulation_type']
364
+ .astype(str)
365
+ .str.lower()
366
+ ==
367
+ str(rfp_input['insulation_type']).lower()
368
+ )
369
+
370
+ # Armouring
371
+ if rfp_input.get('armouring_type'):
372
+ mask &= (
373
+ self.product_df['armouring_type']
374
+ .astype(str)
375
+ .str.lower()
376
+ ==
377
+ str(rfp_input['armouring_type']).lower()
378
+ )
379
+
380
+ candidate_indices = np.where(mask)[0]
381
+
382
+ # fallback if too strict
383
+ if len(candidate_indices) == 0:
384
+ candidate_indices = np.arange(len(self.product_df))
385
+
386
+ return candidate_indices
387
+
388
+ def retrieve(self, rfp_input: dict, top_k: int = 5,
389
+ weights: Tuple = HYBRID_WEIGHTS) -> List[Dict]:
390
+ """
391
+ Main retrieval: returns ranked list of top_k matching SKUs with scores.
392
+ rfp_input: dict with keys matching product_df columns + spec_text_raw
393
+ """
394
+ t_start = time.time()
395
+ ws, we, wt = weights
396
+ mandatory = set(
397
+ f.strip() for f in str(rfp_input.get('mandatory_specs', '')).split(';') if f.strip()
398
+ )
399
+
400
+ # ──────────────────────────────────────────────────────
401
+ # HARD FILTERING
402
+ # ──────────────────────────────────────────────────────
403
+
404
+ candidate_indices = self.apply_hard_filters(rfp_input)
405
+
406
+ candidate_df = self.product_df.iloc[candidate_indices]
407
+
408
+ candidate_emb = self.product_emb[candidate_indices]
409
+
410
+ # ──────────────────────────────────────────────────────
411
+ # STRUCTURED SCORES
412
+ # ──────────────────────────────────────────────────────
413
+
414
+ struct_scores = np.array([
415
+ structured_score(rfp_input, sku, mandatory)
416
+ for _, sku in candidate_df.iterrows()
417
+ ], dtype=np.float32)
418
+
419
+ # ──────────────────────────────────────────────────────
420
+ # STANDARDS SCORES
421
+ # ──────────────────────────────────────────────────────
422
+
423
+ std_scores = np.array([
424
+ standards_score(rfp_input, sku)
425
+ for _, sku in candidate_df.iterrows()
426
+ ], dtype=np.float32)
427
+
428
+ # ──────────────────────────────────────────────────────
429
+ # SEMANTIC SCORES
430
+ # ──────────────────────────────────────────────────────
431
+
432
+ spec_text = str(rfp_input.get('spec_text_raw', ''))
433
+
434
+ q_emb = self.encode_query(spec_text)
435
+
436
+ sem_scores = (candidate_emb @ q_emb).astype(np.float32)
437
+
438
+ # ── BM25 scores ───────────────────────────────────────
439
+ tokens = spec_text.lower().split()
440
+ bm25_raw = np.array(self.bm25.get_scores(tokens), dtype=np.float32)
441
+ mx = bm25_raw.max()
442
+ bm25_scores = bm25_raw / mx if mx > 0 else bm25_raw
443
+
444
+ # ── TF-IDF scores ─────────────────────────────────────
445
+ try:
446
+ q_tfidf = self.tfidf_vec.transform([spec_text])
447
+ tfidf_scores = (q_tfidf @ self.tfidf_prod.T).toarray()[0].astype(np.float32)
448
+ except Exception:
449
+ tfidf_scores = np.zeros(len(self.product_df), dtype=np.float32)
450
+
451
+ # ── Hybrid final score ────────────────────────────────
452
+ hybrid_scores = hybrid_score(struct_scores, sem_scores, std_scores, ws, we, wt)
453
+
454
+ # ── Rank and return top_k ─────────────────────────────
455
+ order_local = np.argsort(-hybrid_scores)[:top_k]
456
+ order = candidate_indices[order_local]
457
+ latency_ms = (time.time() - t_start) * 1000
458
+
459
+ results = []
460
+ for rank, idx in enumerate(order, 1):
461
+ local_idx = np.where(candidate_indices == idx)[0][0]
462
+ sku = self.product_df.iloc[idx].to_dict()
463
+ results.append({
464
+ 'rank': rank,
465
+ 'sku_id': sku['sku_id'],
466
+ 'product_name': sku['product_name'],
467
+ 'voltage_rating': sku.get('voltage_rating', ''),
468
+ 'core_count': sku.get('core_count', ''),
469
+ 'size_sqmm': sku.get('size_sqmm', ''),
470
+ 'conductor_material': sku.get('conductor_material', ''),
471
+ 'insulation_type': sku.get('insulation_type', ''),
472
+ 'armouring_type': sku.get('armouring_type', ''),
473
+ 'fire_rating': sku.get('fire_rating', ''),
474
+ 'standards_complied': sku.get('standards_complied', ''),
475
+ # Scores
476
+ 'hybrid_score': float(hybrid_scores[local_idx]),
477
+ 'structured_score': float(struct_scores[local_idx]),
478
+ 'semantic_score': float(sem_scores[local_idx]),
479
+ 'standards_score': float(std_scores[local_idx]),
480
+ 'bm25_score': float(bm25_scores[local_idx]),
481
+ 'tfidf_score': float(tfidf_scores[local_idx]),
482
+ 'latency_ms': round(latency_ms, 1),
483
+ })
484
+ return results
485
+
486
+
487
+ # ──────────────────────────────────────────────────────────────
488
+ # EXPERIMENT STRESS-TEST HELPERS
489
+ # (demonstrate each experiment's key insight in the UI)
490
+ # ──────────────────────────────────────────────────────────────
491
+
492
+ def apply_numeric_perturbation(rfp: dict) -> dict:
493
+ """EXP1: Change numbers in spec_text_raw but keep structured columns."""
494
+ perturbed = rfp.copy()
495
+ text = str(perturbed.get('spec_text_raw', ''))
496
+ text = re.sub(r'11kV', '33kV', text)
497
+ text = re.sub(r'240sqmm', '185sqmm', text)
498
+ text = re.sub(r'\b3C\b', '4C', text)
499
+ perturbed['spec_text_raw'] = text
500
+ return perturbed # structured columns untouched
501
+
502
+
503
+ def apply_unit_variation(rfp: dict) -> dict:
504
+ """EXP2: Change unit notation; meaning identical."""
505
+ varied = rfp.copy()
506
+ text = str(varied.get('spec_text_raw', ''))
507
+ text = re.sub(r'(\d+)kV', lambda m: f"{int(m.group(1))*1000}V", text)
508
+ text = re.sub(r'(\d+)sqmm', r'\1 mm²', text)
509
+ text = re.sub(r'\b(\d+)C\b', r'\1 Core', text)
510
+ text = re.sub(r'\bCu\b', 'Copper', text)
511
+ varied['spec_text_raw'] = text
512
+ return varied
513
+
514
+
515
+ def apply_noise_injection(rfp: dict, noise_type: str = 'out_of_domain') -> dict:
516
+ """EXP4: Inject in-domain or out-of-domain noise."""
517
+ noisy = rfp.copy()
518
+ text = str(noisy.get('spec_text_raw', ''))
519
+ if noise_type == 'in_domain':
520
+ prefix = "Used in metro rail traction and auxiliary power systems, "
521
+ noisy['spec_text_raw'] = prefix + text
522
+ else:
523
+ prefix = "Bollywood actress makes runway debut at Paris Fashion Week, "
524
+ noisy['spec_text_raw'] = prefix + text
525
+ return noisy
526
+
527
+
528
+ def apply_missing_params(rfp: dict, n_drop: int = 2) -> dict:
529
+ """EXP3: Drop n_drop token types from spec_text_raw."""
530
+ missing = rfp.copy()
531
+ text = str(missing.get('spec_text_raw', ''))
532
+ patterns_to_drop = [
533
+ r'\b\d+(?:\.\d+)?kV\b',
534
+ r'\b\d+(?:\.\d+)?\s*sqmm\b',
535
+ r'\b\d+C\b',
536
+ r'\b(Cu|Al)\b',
537
+ ]
538
+ for pat in patterns_to_drop[:n_drop]:
539
+ text = re.sub(pat, '', text)
540
+ text = re.sub(r' +', ' ', text).strip()
541
+ missing['spec_text_raw'] = text
542
+ return missing
543
+
544
+
545
+ def apply_partial_spec(rfp: dict, level: int = 2) -> dict:
546
+ """EXP6: Keep only 'level' token types."""
547
+ partial = rfp.copy()
548
+ text = str(partial.get('spec_text_raw', ''))
549
+ token_patterns = {
550
+ 'voltage': r'\b\d+(?:\.\d+)?(?:kV|V)\b',
551
+ 'size_sqmm': r'\b\d+(?:\.\d+)?\s*sqmm\b',
552
+ 'core_count': r'\b\d+C\b',
553
+ 'conductor': r'\b(Cu|Al)\b',
554
+ 'insulation': r'\b(XLPE|PVC|EPR)\b',
555
+ 'fire_rating': r'\b(FRLS|FR|LSZH)\b',
556
+ 'armouring': r'\b(armou?red)\b',
557
+ }
558
+ import random
559
+ rng = random.Random(42)
560
+ present = [(k, p) for k, p in token_patterns.items() if re.findall(p, text)]
561
+ keep = set(k for k, _ in rng.sample(present, min(level, len(present))))
562
+ for k, p in token_patterns.items():
563
+ if k not in keep:
564
+ text = re.sub(p, '', text)
565
+ if 'cable' not in text.lower():
566
+ text += ' cable'
567
+ text = re.sub(r' +', ' ', text).strip()
568
+ partial['spec_text_raw'] = text
569
+ return partial
570
+
571
+
572
+ def apply_positional_shift(rfp: dict, position: str = 'end') -> dict:
573
+ """EXP7: Move spec to start/middle/end of context."""
574
+ shifted = rfp.copy()
575
+ text = str(shifted.get('spec_text_raw', ''))
576
+ context = "This specification is for electrical installation in the distribution network."
577
+ if position == 'start':
578
+ shifted['spec_text_raw'] = f"{text} {context}"
579
+ elif position == 'middle':
580
+ shifted['spec_text_raw'] = f"Procurement note: {context} {text} Please confirm delivery."
581
+ else: # end
582
+ shifted['spec_text_raw'] = f"{context} {text}"
583
+ return shifted
584
+
585
+
586
+ EXPERIMENT_DESCRIPTIONS = {
587
+ 'clean': {
588
+ 'title': 'Clean Baseline',
589
+ 'description': 'Standard RFP spec — no modifications. Demonstrates baseline Hybrid performance.',
590
+ 'what_changes': 'Nothing changed.',
591
+ 'hybrid_advantage': 'Hybrid scores highest due to combined structured + semantic + standards signal.'
592
+ },
593
+ 'numeric_perturbation': {
594
+ 'title': 'EXP1 — Numeric Perturbation',
595
+ 'description': 'Numbers in spec_text_raw are WRONG (e.g., 33kV instead of 11kV), but structured columns remain correct.',
596
+ 'what_changes': 'spec_text_raw: voltage, core count, size changed to wrong values.',
597
+ 'hybrid_advantage': 'Hybrid uses structured columns (50% weight) → immune. SBERT reads wrong text → fails.'
598
+ },
599
+ 'unit_variation': {
600
+ 'title': 'EXP2 — Unit Variation',
601
+ 'description': 'Same meaning, different notation: 11kV → 11000V, sqmm → mm², 3C → 3 Core.',
602
+ 'what_changes': 'spec_text_raw: unit notation changed. Structured columns untouched.',
603
+ 'hybrid_advantage': 'Hybrid structured columns never use text notation → unit-aware by design.'
604
+ },
605
+ 'missing_params': {
606
+ 'title': 'EXP3 — Missing Parameters',
607
+ 'description': 'Voltage and size tokens removed from spec_text_raw. Structured columns still intact.',
608
+ 'what_changes': 'spec_text_raw: 2 critical token types dropped.',
609
+ 'hybrid_advantage': 'Structured columns fill the gap. SBERT loses critical embedding signal.'
610
+ },
611
+ 'noise_indomain': {
612
+ 'title': 'EXP4 — In-Domain Noise',
613
+ 'description': 'Relevant but non-critical engineering text prepended to the spec.',
614
+ 'what_changes': 'spec_text_raw: ~10 technical words prepended.',
615
+ 'hybrid_advantage': 'Structured score unchanged. SBERT embedding shifts slightly toward noise topic.'
616
+ },
617
+ 'noise_outdomain': {
618
+ 'title': 'EXP4 — Out-of-Domain Noise',
619
+ 'description': 'Completely unrelated text (Bollywood/cricket) prepended to spec.',
620
+ 'what_changes': 'spec_text_raw: ~10 off-topic words prepended.',
621
+ 'hybrid_advantage': 'Structured score unchanged. SBERT embedding severely distorted by irrelevant tokens.'
622
+ },
623
+ 'partial_spec': {
624
+ 'title': 'EXP6 — Partial Spec (Level 2: 2 tokens)',
625
+ 'description': 'Only 2 token types remain in spec_text_raw. Structural columns still complete.',
626
+ 'what_changes': 'spec_text_raw: stripped to just 2 token types.',
627
+ 'hybrid_advantage': 'Structured columns (50% weight) hold performance. SBERT has insufficient signal.'
628
+ },
629
+ 'positional_end': {
630
+ 'title': 'EXP7 — Positional Bias (Spec at END)',
631
+ 'description': 'Context sentence placed BEFORE the spec — spec is at the end.',
632
+ 'what_changes': 'spec_text_raw: context prefix added, spec pushed to end.',
633
+ 'hybrid_advantage': 'Structured score is position-invariant. SBERT has recency bias issues.'
634
+ },
635
+ }
model_config.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sbert_model": "all-mpnet-base-v2",
3
+ "hybrid_weights": {
4
+ "structured": 0.5,
5
+ "semantic": 0.3,
6
+ "standards": 0.2
7
+ },
8
+ "K": 5,
9
+ "exact_fields": [
10
+ "voltage_rating",
11
+ "conductor_material",
12
+ "insulation_type",
13
+ "sheath_type",
14
+ "temperature_rating",
15
+ "fire_resistance",
16
+ "armouring"
17
+ ],
18
+ "numeric_fields": {
19
+ "core_count": "exact",
20
+ "size_sqmm": "ladder_adjacent"
21
+ },
22
+ "standards_match": "bidirectional_substring",
23
+ "mandatory_weight": 2.0,
24
+ "rfp_text_col": "spec_text_raw",
25
+ "product_text_col": "product_name",
26
+ "baseline_metrics": {
27
+ "1. Random Baseline": {
28
+ "Top-1 Acc": 0.0046,
29
+ "Top-5 Acc": 0.0284,
30
+ "MRR": 0.0298,
31
+ "NDCG@5": 0.016
32
+ },
33
+ "2. TF-IDF + Cosine": {
34
+ "Top-1 Acc": 0.1154,
35
+ "Top-5 Acc": 0.3229,
36
+ "MRR": 0.2313,
37
+ "NDCG@5": 0.2208
38
+ },
39
+ "3. BM25 (Okapi)": {
40
+ "Top-1 Acc": 0.0559,
41
+ "Top-5 Acc": 0.2346,
42
+ "MRR": 0.1651,
43
+ "NDCG@5": 0.1483
44
+ },
45
+ "4. SBERT MiniLM-L6": {
46
+ "Top-1 Acc": 0.1326,
47
+ "Top-5 Acc": 0.3246,
48
+ "MRR": 0.2314,
49
+ "NDCG@5": 0.2315
50
+ },
51
+ "5. SBERT MPNet (sem-only)": {
52
+ "Top-1 Acc": 0.1653,
53
+ "Top-5 Acc": 0.3354,
54
+ "MRR": 0.2609,
55
+ "NDCG@5": 0.2484
56
+ },
57
+ "6. Exact Structured Match": {
58
+ "Top-1 Acc": 0.057,
59
+ "Top-5 Acc": 0.1753,
60
+ "MRR": 0.1294,
61
+ "NDCG@5": 0.1167
62
+ },
63
+ "7. \ud83c\udfc6 Hybrid (Ours)": {
64
+ "Top-1 Acc": 0.178,
65
+ "Top-5 Acc": 0.4434,
66
+ "MRR": 0.3088,
67
+ "NDCG@5": 0.3125
68
+ }
69
+ }
70
+ }
product_df.parquet ADDED
Binary file (15.2 kB). View file
 
readme.md ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: RFP Cable Spec Matcher
3
+ emoji: ⚡
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.29.0
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # RFP Cable Specification Matcher
13
+
14
+ Hybrid Retrieval System for procurement-grade cable specification matching.
15
+
16
+ Features:
17
+ - Structured + Semantic + Standards retrieval
18
+ - MPNet embeddings
19
+ - Robustness experiments EXP1–EXP7
20
+ - Numeric perturbation resilience
21
+ - Noise robustness
22
+ - Positional bias evaluation
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ pandas
3
+ numpy
4
+ scikit-learn
5
+ sentence-transformers
6
+ rank-bm25
7
+ pyarrow
8
+ torch
9
+ transformers
10
+ tensorflow
11
+ tf-keras