""" 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("""
Hybrid Retrieval System | Structured (50%) + Semantic (30%) + Standards (20%) | Experiments EXP1–EXP7