Spaces:
Runtime error
Runtime error
Download app.py from dwaynefernandes05/MajorProject: direct link, hf CLI and curl.
- Browser
- Download file 20 kB
-
https://huggingface.co/spaces/dwaynefernandes05/MajorProject/resolve/main/app.py
- Command line
-
hf download hf://spaces/dwaynefernandes05/MajorProject/app.py
-
curl -L -o app.py https://huggingface.co/spaces/dwaynefernandes05/MajorProject/resolve/main/app.py
20 kB
| """ | |
| 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 | Structured (50%) + Semantic (30%) + Standards (20%) | |
| | 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 | Major Project Prototype | | |
| Hybrid Retrieval: Structured + Semantic + Standards | |
| </div> | |
| """) | |
| if __name__ == "__main__": | |
| demo.launch(share=False, server_name="0.0.0.0", server_port=7860) |