diff --git a/.gitignore b/.gitignore
index c9f1f5e..447ca00 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,15 +1,31 @@
-# Byte-compiled / optimized / DLL files
+# ==============================================================================
+# SID-AI β Universal Engineering Drawing Intelligence Platform
+# Git Ignore Configuration
+# ==============================================================================
+
+# ------------------------------------------------------------------------------
+# 1. Byte-Compiled / Python Runtime Cache
+# ------------------------------------------------------------------------------
__pycache__/
*.py[cod]
*$py.class
+*.so
-# Environment variables & secrets (Never commit API keys!)
+# ------------------------------------------------------------------------------
+# 2. Environment Variables, Secrets & API Credentials
+# NEVER COMMIT REAL API KEYS OR PRODUCTION SECRETS TO REPOSITORY!
+# ------------------------------------------------------------------------------
.env
.env.local
+.env.development
+.env.test
+.env.production
.env.*
!.env.example
-# Python virtual environments
+# ------------------------------------------------------------------------------
+# 3. Python Virtual Environments
+# ------------------------------------------------------------------------------
pid_env/
venv/
.venv/
@@ -18,23 +34,52 @@ ENV/
env.bak/
venv.bak/
-# Runtime outputs & temporary uploaded files
+# ------------------------------------------------------------------------------
+# 4. Storage, Temporary Uploads & Output Deliverables
+# ------------------------------------------------------------------------------
uploads/
outputs/
rasterized/
-*.log
+temp/
+tmp/
+
+# ------------------------------------------------------------------------------
+# 5. Databases, Execution Logs & Runtime Metrics
+# ------------------------------------------------------------------------------
*.db
+*.sqlite
+*.sqlite3
extraction_history.db
+*.log
install_log.txt
-# Scratch & debug scripts
+# ------------------------------------------------------------------------------
+# 6. Local Scratchpads & Debugging Scripts
+# ------------------------------------------------------------------------------
debug_*.py
scratch/
-# OS and IDE files
+# ------------------------------------------------------------------------------
+# 7. IDE & Text Editor Files
+# ------------------------------------------------------------------------------
.vscode/
.idea/
+.claude/
*.swp
*.swo
+*~
+.project
+.pydevproject
+.settings/
+
+# ------------------------------------------------------------------------------
+# 8. OS Generated Files
+# ------------------------------------------------------------------------------
.DS_Store
-.claude/
+.DS_Store?
+._*
+.Spotlight-V100
+.Trashes
+ehthumbs.db
+Thumbs.db
+desktop.ini
diff --git a/README.md b/README.md
index c805a68..dd262e9 100644
--- a/README.md
+++ b/README.md
@@ -2,86 +2,239 @@
-
+
-
+
---
+## π Why SID-AI Outperforms Existing Solutions
+
+Traditional P&ID parsing tools and general-purpose Vision-LLMs suffer from high hallucination rates, inability to trace line topologies, and slow processing times. **SID-AI** (*System for Intelligent Engineering Diagrams*) was engineered specifically to solve these fundamental flaws in industrial drawing digitization.
+
+| Feature / Capability | Conventional P&ID Parsers / General Vision LLMs | π SID-AI Intelligence Engine |
+| :--- | :--- | :--- |
+| ποΈ **Architectural Topology** | **Sequential / Single-Pass**: Evaluates entire drawing in a single LLM prompt, causing token overflow and missing minor tags. | **LangGraph 3-Agent Parallel Perception**: Runs dedicated concurrent perception sub-graphs (**Text**, **Symbol**, and **Line Topology**) simultaneously. |
+| π **Domain Standards** | **Generic Document OCR**: Mistakes instrument bubbles for basic circles and misses line rating specifications. | **ISA 5.1 & Multi-Discipline Native**: Built-in ISA 5.1 tag rules, line rating specs, electrical SLD, earthing layout, and HVAC schematics logic. |
+| π **Completeness & Accuracy** | **No Verification**: Returns unverified extraction without checking for missing instruments or broken pipelines. | **Self-Healing Loop**: Automated `CompletenessAgent` & `ReExtractorAgent` detect missing items and trigger targeted spatial re-extractions automatically. |
+| β‘ **Execution Latency** | **Extremely Slow (5β15 mins)**: Heavy multi-pass prompts lead to excessive API wait times and UI timeouts. | **Ultra-Fast (< 15 Seconds)**: Pre-rasterized tile caching & sub-crop title block OCR reduce full execution down to **13.78 seconds**. |
+| π¦ **Digital Twin Outputs** | **Basic CSV / Markdown**: Requires manual data cleaning before importing into enterprise engineering software. | **Native Enterprise Exports**: Immediate export to **AVEVA Diagrams XML**, **Siemens COMOS JSON**, **SmartPlant P&ID CSV**, and **Styled Excel**. |
+| π **Multi-Discipline Intelligence** | **P&ID Only**: Rigidly restricted to standard piping diagrams. | **Universal Support**: P&ID, Electrical SLD, Earthing/Lighting Layouts, HVAC, Cable Schedules, and General Engineering Schematics. |
+
+---
+
## π Executive Overview
-**SID-AI** (*System for Intelligent Engineering Diagrams*) is an agentic AI system designed to read, classify, reason over, and extract structured digital twins from **ANY engineering drawing type**.
+**SID-AI** is an agentic AI digital twin compilation platform designed to extract, reason over, validate, and export structured engineering graphs from complex engineering blueprints.
-Unlike conventional fixed P&ID parsers, **SID-AI** features a **parallel perception multi-discipline intelligence engine** that automatically identifies drawing typesβincluding **P&ID**, **Electrical Layouts**, **Earthing/Grounding Layouts**, **Single Line Diagrams (SLD)**, **HVAC Layouts**, **Structural Plans**, **Cable Schedules**, and **Generic Engineering Schematics**βand maps all graphical symbols, alphanumeric tags, connectivity pipelines, electrical circuits, and dynamic specifications into structured engineering formats (**AVEVA Diagrams**, **Siemens COMOS**, **Intergraph SmartPlant P&ID**, **Excel**, and **JSON Graph**).
+By replacing monolithic single-prompt extraction with a stateful **LangGraph Parallel Perception Sub-Graph**, SID-AI breaks down visual engineering drawings into distinct topological layers. It seamlessly fuses optical character recognition (OCR), deep object detection, and computer-vision line-tracing to synthesize standard plant software representations (**AVEVA**, **Siemens COMOS**, **Intergraph SmartPlant**, **Excel Workbooks**, and **JSON Knowledge Graphs**).
---
-## β¨ Key Features & Capabilities
+## ποΈ System Architecture
-### π 1. Pathnovo ISA 5.1 Native Extraction API Integration
-Native integration with the **Pathnovo P&ID Extraction API**, trained on ISA 5.1 instrumentation standards:
-* **Instrument Function Bubbles & Loop IDs**: Pulls exact loop numbers (`9054`, `9055`, `9077`) directly from spatial image coordinates inside symbol bubbles.
-* **Piping Line Sizes & Specs**: Parses nominal line sizes (`8"`, `6"`, `4"`), service codes (`PV`, `VF`, `DC`), and piping specs (`FC11S`, `GC11S`, `AS20S`).
-* **Valve Specifications**: Detects valve types (`Check Valve`, `Gate Valve`, `Control Valve`) and pressure rating classes (`150#`, `300#`, `2500#`).
+SID-AI is orchestrated using a stateful **LangGraph DAG (Directed Acyclic Graph)** topology featuring a multi-agent orchestration architecture:
+
+```mermaid
+flowchart TD
+ A[π Raw Engineering Drawing PDF/Image] --> B[βοΈ IngestionAgent]
+ B --> C[π ContextLoaderAgent]
+ C --> D[π― SupervisorAgent & Drawing Type Classifier]
+
+ subgraph Parallel Perception Sub-Graph ποΈ
+ D --> E1[π€ TextRecognitionAgent\nLayer 1 & Layer 2 OCR + Specs]
+ D --> E2[π― SymbolRecognitionAgent\nISA 5.1 & Object Detection]
+ D --> E3[β‘ PipelineRecognitionAgent\nLine Tracing & Connectivity]
+ end
+
+ E1 --> F[π§± CompilerAgent\nKnowledge Graph Builder]
+ E2 --> F
+ E3 --> F
+
+ F --> G[β
ValidationAgent\nISA 5.1 & Schema Rule Engine]
+ G --> H[π CompletenessAgent\nMissing Tag & Pipeline Router]
+
+ H -- Missing Items Found (Retries < Max) --> I[π ReExtractorAgent\nTargeted Spatial Zoom Re-Extraction]
+ I --> F
+
+ H -- Complete / Max Retries Reached --> J[π¦ OutputGeneratorAgent]
+
+ J --> K1[π Excel Workbook .xlsx]
+ J --> K2[π AVEVA Diagrams / SP3D .xml]
+ J --> K3[π§ Siemens COMOS .json]
+ J --> K4[ποΈ SmartPlant P&ID .csv]
+ J --> K5[πΈοΈ Master JSON Graph .json]
+```
+
+### π§ Core Agent Roles & Modules
+
+1. **IngestionAgent** ([ingestion.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/ingestion.py)) βοΈ
+ - Fast pre-rasterization of PDF drawings into high-resolution canvas images (300 DPI).
+ - Extracts title block metadata (Drawing No, Revision, Plant Location, Sheet No) in **0.052s**.
+2. **ContextLoaderAgent** ([context_loader.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/context_loader.py)) π
+ - Injects historical extraction context, project standards, and custom symbol reference tables.
+3. **SupervisorAgent** ([supervisor.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/supervisor.py)) π―
+ - Uses `DrawingTypeDetector` to classify drawings into P&ID, SLD, Earthing, HVAC, or Cable Schedules and dynamically configures downstream perception parameters.
+4. **Parallel Perception Nodes** ([parallel_vision.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/parallel_vision.py)) ποΈ
+ - **TextRecognitionAgent** π€: Multi-tier OCR processing using Pathnovo ISA 5.1 API, PaddleOCR, PyMuPDF, and Qwen 3.7 VL / Gemini 2.0.
+ - **SymbolRecognitionAgent** π―: Detects valves, pumps, instruments, breakers, transformers, and junction boxes.
+ - **PipelineRecognitionAgent** β‘: Computer-vision line tracer + VLM topology reasoning for piping runs, busbars, and signal lines.
+5. **CompilerAgent** ([compiler.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/compiler.py)) π§±
+ - Fuses bounding boxes, text tags, and line vectors into a single unified `GraphState` schema.
+6. **ValidationAgent** ([validation.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/validation.py)) β
+ - Enforces ISA 5.1 naming conventions, line size formatting, and electrical rating constraints.
+7. **CompletenessAgent & ReExtractorAgent** ([completeness.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/completeness.py), [re_extractor.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/re_extractor.py)) π π
+ - Self-correction loop: Detects orphan components or incomplete loop IDs and performs high-resolution sub-crop re-extractions.
+8. **OutputGeneratorAgent** ([output_generator.py](file:///c:/Users/ADMIN/Downloads/pid_project/src/agents/output_generator.py)) π¦
+ - Renders multi-format deliverables ready for industrial software ingestion.
---
-### β‘ 2. High-Performance Parallel Perception Sub-Graph
-Features 3 dedicated, parallel perception agents running concurrently:
-* π€ **TextRecognitionAgent**: 2-Layer OCR Reading & Deep Reasoning Engine (Pathnovo ISA 5.1 OCR, PaddleOCR, PyMuPDF, Qwen 3.7-VL, Gemini).
-* π― **SymbolRecognitionAgent**: Component & Symbol Detector (Pathnovo ISA 5.1 Engine, Multimodal VLM, RF-DETR).
-* β‘ **PipelineRecognitionAgent**: Topological Connectivity & Line Spec Tracer (Pathnovo Line & Loop Tracer, OpenCV CV Line Tracer + VLM).
+## π End-to-End Workflow Pipeline
+
+```mermaid
+flowchart LR
+ subgraph Stage 1 π
+ A[Ingestion & Title Block OCR]
+ end
+ subgraph Stage 2 π―
+ B[Drawing Classification P&ID / SLD / HVAC]
+ end
+ subgraph Stage 3 ποΈ
+ C[Parallel Vision Processing Text, Symbols, Lines]
+ end
+ subgraph Stage 4 π§±
+ D[Digital Twin Graph Synthesis]
+ end
+ subgraph Stage 5 π
+ E[Validation & Re-Extraction Loop]
+ end
+ subgraph Stage 6 π¦
+ F[AVEVA / COMOS / Excel Exports]
+ end
+
+ A --> B --> C --> D --> E --> F
+ E -- Loop Retry --> C
+```
+
+1. **Ingestion & Title Block Parsing π**: The input PDF/Image is cached and preprocessed. The title block is isolated to establish drawing context.
+2. **Drawing Type Classification π―**: Machine learning and pattern heuristic rules classify the document type (P&ID, SLD, Earthing, etc.).
+3. **Parallel Perception Execution ποΈ**: The 3 vision agents run concurrently to harvest text labels, symbols, and connectivity paths.
+4. **Digital Twin Assembly π§±**: Line segments are linked to nearby instruments and valves, producing a complete graph representation.
+5. **Validation & Self-Correction π**: The output is validated against engineering rules. If gaps are found, the system auto-executes targeted zoom-in re-extraction.
+6. **Deliverable Export π¦**: Generates compliant XML, JSON, CSV, and Excel deliverables instantly.
---
-### π 3. Ultra-Fast Performance & Latency Elimination
-* **0.052s Ingestion Agent**: Pre-rasterized page caching and sub-crop title block OCR.
-* **13.78s Total Pipeline Execution**: Latency optimization reducing total pipeline runtime from 11m49s to 13.78 seconds.
-* **Auto-Routing Vision Models**: Automatically remaps text-only LLM requests to multimodal vision models (`qwen/qwen-3.7-vl`).
+## π οΈ How to Run & Setup Guide
----
-
-### π¦ 4. Multi-Platform Deliverables & Export System
-Extracts digital twins directly into standard engineering formats:
-* π **Excel Workbook (`.xlsx`)**: Styled multi-tab workbook with auto-fitted columns and revision history delta highlighting.
-* πΈοΈ **Master JSON Graph (`.json`)**: Hierarchical Pydantic schema representation of the entire drawing network.
-* π **AVEVA Diagrams / SP3D XML (`.xml`)**: Complete XML plant model schema compliant with AVEVA and Smart 3D import requirements.
-* π§ **Siemens COMOS JSON (`.json`)**: Hierarchical `Project -> Unit -> Location -> Object` tree formatting.
-* ποΈ **SmartPlant P&ID CSV (`.csv`)**: Relational database import format with standardized headers.
-
----
-
-## π οΈ Setup & Execution Guide
-
-### 1. Prerequisites
-* **Python**: 3.11, 3.12, or 3.13
-* **OS**: Windows, macOS, or Linux
+### 1. System Requirements & Prerequisites
+- **Python**: Version 3.11, 3.12, or 3.13
+- **Operating System**: Windows 10/11, macOS, or Linux
+- **Poppler & OpenCV Utilities**: Automatically supported via standard packages
### 2. Environment Setup
+
```bash
-# Clone the repository
+# 1. Clone the project repository
git clone https://github.com/AbhinavEliac/MTO2Doc.git
cd pid_project
-# Activate virtual environment
+# 2. Create and activate a Python virtual environment
# Windows:
+python -m venv pid_env
pid_env\Scripts\activate
-# Install requirements
+# macOS / Linux:
+python3 -m venv pid_env
+source pid_env/bin/activate
+
+# 3. Install required dependencies
pip install -r requirements.txt
```
-### 3. Launch Interactive Dashboard
+### 3. API Key Configuration
+
+Create a `.env` file in the root directory (or copy `.env.example`):
+
+```bash
+cp .env.example .env
+```
+
+Edit `.env` to configure your vision model API credentials:
+
+```env
+# Required API Keys
+GEMINI_API_KEY=your_gemini_api_key_here
+OPENROUTER_API_KEY=sk-or-v1-your_openrouter_api_key_here
+
+# Model Selection Defaults
+GEMINI_MODEL=gemini-2.0-flash
+QWEN_MODEL=qwen/qwen-2.5-72b-instruct
+```
+
+### 4. Launch the Interactive Dashboard
+
+Start the Streamlit application:
+
```bash
streamlit run app.py
```
+Open your browser at `http://localhost:8501` to view the interactive dashboard.
+
---
-## π Author & Contact
+## π Repository Structure
+
+```
+pid_project/
+βββ app.py # Main Streamlit Dashboard Application
+βββ requirements.txt # Python Dependencies
+βββ .env.example # Template for Environment Credentials
+βββ .gitignore # Git Exclusion Configuration
+βββ README.md # Project Documentation
+βββ src/
+β βββ graph.py # LangGraph StateGraph Execution Pipeline
+β βββ state.py # State Schemas & Data Structures
+β βββ config.py # Global App Configuration & Model Settings
+β βββ db.py # SQLite Execution History Database
+β βββ models.py # Pydantic Schemas for Engineering Entities
+β βββ agents/
+β β βββ base.py # Agent Base Classes & Utilities
+β β βββ ingestion.py # PDF & Rasterization Ingestion Agent
+β β βββ context_loader.py # Drawing Standards & Context Agent
+β β βββ supervisor.py # Workflow Orchestrator & Router
+β β βββ parallel_vision.py # Text, Symbol & Line Perception Agents
+β β βββ compiler.py # Knowledge Graph Synthesizer
+β β βββ validation.py # ISA 5.1 Validation Rule Engine
+β β βββ completeness.py # Completeness & Quality Router
+β β βββ re_extractor.py # Focused Zoom Re-Extraction Agent
+β β βββ output_generator.py # Enterprise File Exporter
+β βββ utils/
+β βββ drawing_type_detector.py # Drawing Classification Engine
+β βββ tag_classifier.py # ISA 5.1 Tag Parsing Rules
+β βββ line_tracer.py # Computer Vision Pipeline Line Tracer
+β βββ paddle_ocr.py # PaddleOCR Integration Wrappers
+β βββ pathnovo_api.py # Native ISA 5.1 Pathnovo Extraction API
+```
+
+---
+
+## π¦ Supported Deliverable Formats
+
+- π **Excel Workbook (`.xlsx`)**: Structured multi-tab spreadsheet featuring Component Tags, Line Schedules, Loop Summaries, and Delta Revision Highlighting.
+- π **AVEVA Diagrams XML (`.xml`)**: Schema-compliant XML tree ready for import into AVEVA Diagrams and Smart 3D (SP3D).
+- π§ **Siemens COMOS JSON (`.json`)**: Hierarchical structure (`Project -> Unit -> Location -> Object`) for Siemens COMOS platform.
+- ποΈ **SmartPlant P&ID CSV (`.csv`)**: Relational database import format for Intergraph SmartPlant.
+- πΈοΈ **Master Knowledge Graph (`.json`)**: Full topological node-edge graph representation of the engineering blueprint.
+
+---
+
+## π€ Author & Contact
**Developer**: Abhinav Gupta
**Email**: [abhinavgupta15.ag@gmail.com](mailto:abhinavgupta15.ag@gmail.com)
diff --git a/src/agents/base.py b/src/agents/base.py
index 70b0ae1..c2ee2b3 100644
--- a/src/agents/base.py
+++ b/src/agents/base.py
@@ -191,14 +191,15 @@ class BaseAgent:
logger.warning(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...")
time.sleep(wait_time)
delay *= 2
+ continue
else:
raise e
else:
if attempt < max_attempts - 1:
time.sleep(1)
+ continue
else:
raise e
- raise e
def invoke_text(
self,
diff --git a/src/agents/compiler.py b/src/agents/compiler.py
index 05b66ae..e46d02d 100644
--- a/src/agents/compiler.py
+++ b/src/agents/compiler.py
@@ -128,22 +128,60 @@ class CompilerAgent(BaseAgent):
# ββ P&ID Compilers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+ # ISA equipment type descriptions (CFIHOS / ISO 15926)
+ _ISA_EQUIP_DESC = {
+ 'KA': 'Compressor', 'KB': 'Blower', 'KC': 'Compressor', 'KT': 'Turbine',
+ 'CP': 'Compressor', 'CM': 'Compressor', 'KZ': 'Package/Skid Unit',
+ 'HA': 'Heat Exchanger', 'HB': 'Heat Exchanger', 'HX': 'Heat Exchanger',
+ 'HE': 'Heat Exchanger', 'EA': 'Air Cooler', 'EB': 'Boiler',
+ 'VA': 'Vessel', 'VB': 'Vessel', 'VC': 'Vessel',
+ 'TK': 'Storage Tank', 'DA': 'Drum', 'DB': 'Drum',
+ 'CA': 'Column', 'CB': 'Column', 'R': 'Reactor',
+ 'PA': 'Pump', 'PB': 'Pump', 'PC': 'Pump', 'PM': 'Pump', 'PU': 'Pump',
+ 'GA': 'Pump', 'GB': 'Pump',
+ 'FA': 'Filter', 'FB': 'Filter', 'ST': 'Strainer', 'CX': 'Separator',
+ 'SK': 'Skid', 'PK': 'Package',
+ 'MA': 'Machinery', 'MB': 'Machinery', 'ME': 'Mechanical Equipment',
+ }
+
def _compile_equipment(self, texts: List[Dict], symbols: List[Dict]) -> List[EquipmentItem]:
compiled = []
+ seen_equip: dict = {} # canonical key β EquipmentItem (deduplication)
eq_tags = [t for t in texts if t["classification"] == "EQUIPMENT_TAG"]
for eq in eq_tags:
tag = eq["tag"]
+
+ # Deduplicate by canonical key (strip project prefix AND trailing unit suffix)
+ # e.g.: 26-HA-911-C01 β HA-911, 26-KA-901-A β KA-901, KA-901 β KA-901
+ canon_key = re.sub(r'^\d{2,3}-', '', tag.upper()) # strip project prefix
+ # Strip trailing unit designator only if it contains at least one alpha char
+ # This prevents stripping the last digit of a sequence number (HA-911 β HA-91)
+ canon_key = re.sub(r'-[A-Z][A-Z0-9]{0,3}$', '', canon_key) # -C01, -A, -B only
+
+ if canon_key in seen_equip:
+ # Prefer longer project-prefixed tag
+ if len(tag) > len(seen_equip[canon_key].tag):
+ seen_equip[canon_key].tag = tag
+ continue
+
coords = None
- eq_type = "Generic Equipment"
for sym in symbols:
if sym.get("inferred_tag") == tag:
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
+ break
+
+ # Derive equipment type from ISA lookup
+ code_match = re.search(r'([A-Z]{1,3})(?=-?\d)', tag, re.IGNORECASE)
+ eq_code = code_match.group(1).upper() if code_match else ""
+ eq_type = self._ISA_EQUIP_DESC.get(eq_code, "Generic Equipment")
+ for sym in symbols:
+ if sym.get("inferred_tag") == tag and sym.get("symbol_type"):
eq_type = sym["symbol_type"]
break
attrs = eq.get("attributes") or {}
- compiled.append(EquipmentItem(
+ item_obj = EquipmentItem(
tag=tag,
name=eq["value"],
type=eq_type,
@@ -154,9 +192,13 @@ class CompilerAgent(BaseAgent):
duty=attrs.get("duty") or eq.get("rating"),
material=attrs.get("material"),
coordinates=coords,
- ))
+ )
+ compiled.append(item_obj)
+ seen_equip[canon_key] = item_obj
+
return compiled
+
def _compile_lines(self, texts: List[Dict], geom: Dict, relations: List[Dict]) -> List[LineItem]:
compiled = []
line_tags = [t for t in texts if t["classification"] == "LINE_TAG"]
@@ -236,17 +278,58 @@ class CompilerAgent(BaseAgent):
))
return compiled
+ # ISA 5.1 instrument type descriptions lookup
+ _ISA_TYPE_DESC = {
+ 'PIT': 'Pressure Indicating Transmitter', 'PDT': 'Differential Pressure Transmitter',
+ 'PDIT': 'Differential Pressure Indicating Transmitter', 'PT': 'Pressure Transmitter',
+ 'PI': 'Pressure Indicator', 'PIC': 'Pressure Indicating Controller',
+ 'PSV': 'Pressure Safety Valve', 'PRV': 'Pressure Relief Valve',
+ 'PDI': 'Differential Pressure Indicator', 'PCV': 'Pressure Control Valve',
+ 'TIT': 'Temperature Indicating Transmitter', 'TT': 'Temperature Transmitter',
+ 'TI': 'Temperature Indicator', 'TIC': 'Temperature Indicating Controller',
+ 'TE': 'Temperature Element', 'TW': 'Thermowell', 'TCV': 'Temperature Control Valve',
+ 'FIT': 'Flow Indicating Transmitter', 'FT': 'Flow Transmitter',
+ 'FI': 'Flow Indicator', 'FE': 'Flow Element', 'FCV': 'Flow Control Valve',
+ 'FIC': 'Flow Indicating Controller', 'FO': 'Flow Orifice',
+ 'LIT': 'Level Indicating Transmitter', 'LT': 'Level Transmitter',
+ 'LI': 'Level Indicator', 'LG': 'Level Glass', 'LCV': 'Level Control Valve',
+ 'AIT': 'Analytical Indicating Transmitter', 'AT': 'Analytical Transmitter',
+ 'VIT': 'Vibration Indicating Transmitter', 'VT': 'Vibration Transmitter',
+ 'HV': 'Hand Operated Valve', 'XV': 'On-Off Valve',
+ 'FV': 'Flow Valve', 'PY': 'Pressure Relay/Converter', 'TY': 'Temperature Relay',
+ }
+
+ @staticmethod
+ def _canonical_inst_key(tag: str) -> str:
+ """Strip project prefix digits to get canonical key: 26-PIT-9077 β PIT-9077."""
+ return re.sub(r'^\d{2,3}-', '', tag.upper())
+
def _compile_instruments(
self, texts: List[Dict], symbols: List[Dict],
relations: List[Dict], lines: List[LineItem]
) -> List[InstrumentItem]:
compiled = []
+ seen_canonical: dict = {} # Fix 2: canonical key β InstrumentItem for deduplication
inst_tags = [t for t in texts if t["classification"] == "INSTRUMENT_TAG"]
for inst in inst_tags:
tag = inst["tag"]
- type_match = re.search(r'([A-Z]+)', tag)
- inst_type = type_match.group(1) if type_match else "INST"
+
+ # Fix 2: Deduplicate by canonical key β prefer longer (project-prefixed) tag
+ canon_key = self._canonical_inst_key(tag)
+ if canon_key in seen_canonical:
+ # If existing is bare (shorter) and this is project-prefixed (longer), upgrade
+ existing_tag = seen_canonical[canon_key].tag
+ if len(tag) > len(existing_tag):
+ seen_canonical[canon_key].tag = tag
+ continue # Skip duplicate regardless
+
+ # ISA 5.1 instrument type from function code
+ type_match = re.search(r'([A-Z]{2,5})(?=-?\d)', tag)
+ if not type_match:
+ type_match = re.search(r'([A-Z]+)', tag)
+ inst_code = type_match.group(1) if type_match else "INST"
+ inst_type = self._ISA_TYPE_DESC.get(inst_code, inst_code)
# Find coordinates for symbol bubble
coords = None
@@ -255,23 +338,26 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
- # Spatial image text assembly for loop_id:
- # Check OCR text elements positioned inside/near the instrument bubble coordinates
+ # Fix 5: Expanded spatial proximity for loop_id (radius 0.10 + Y-band fallback)
image_loop_id = None
if coords:
cy = (coords[0] + coords[2]) / 2.0
cx = (coords[1] + coords[3]) / 2.0
nearby_texts = []
+ yband_texts = []
for t in texts:
attrs = t.get("attributes") or {}
tx = float(attrs.get("pos_x", -1)) if attrs.get("pos_x") is not None else -1
ty = float(attrs.get("pos_y", -1)) if attrs.get("pos_y") is not None else -1
if tx >= 0 and ty >= 0:
dist = math.hypot(cx - tx, cy - ty)
- if dist < 0.06:
+ if dist < 0.10: # Fix 5: expanded from 0.06
nearby_texts.append(t.get("value", ""))
+ elif abs(ty - cy) < 0.015: # Fix 5: same Y-band fallback
+ yband_texts.append(t.get("value", ""))
- for txt in nearby_texts:
+ # Search nearby first, then Y-band
+ for txt in (nearby_texts + yband_texts):
num_match = re.search(r'(\d{3,5}[A-Z]?)', txt)
if num_match:
image_loop_id = num_match.group(1)
@@ -283,7 +369,7 @@ class CompilerAgent(BaseAgent):
loop_id = image_loop_id
- # Case-insensitive relation check for host line or equipment
+ # Find associated line / equipment from relations
associated_line = None
for rel in relations:
rtype = rel.get("rel_type", "").upper()
@@ -311,16 +397,20 @@ class CompilerAgent(BaseAgent):
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
break
- compiled.append(InstrumentItem(
+ item_obj = InstrumentItem(
tag=tag,
type=inst_type,
service=service_fluid,
location="Field",
loop_id=loop_id,
coordinates=coords,
- ))
+ )
+ compiled.append(item_obj)
+ seen_canonical[canon_key] = item_obj # register for deduplication
+
return compiled
+
def _compile_valves(
self, texts: List[Dict], symbols: List[Dict],
relations: List[Dict], lines: List[LineItem]
@@ -438,20 +528,41 @@ class CompilerAgent(BaseAgent):
for item in items:
tag = item["tag"]
+ tag_upper = tag.upper()
attrs = item.get("attributes") or {}
+ fitting_type = "Lighting Fitting"
+ if "FLOODLIGHT" in tag_upper or "FL" in tag_upper:
+ fitting_type = "Floodlight"
+ elif "WELLGLASS" in tag_upper or "WG" in tag_upper or "WGL" in tag_upper:
+ fitting_type = "Wellglass Fitting"
+ elif "HIGH" in tag_upper and "BAY" in tag_upper:
+ fitting_type = "High Bay Luminaire"
+ elif "EMERGENCY" in tag_upper or "EL" in tag_upper or "EML" in tag_upper:
+ fitting_type = "Emergency Light"
+ elif "LED" in tag_upper:
+ fitting_type = "LED Fitting"
+ elif "TL" in tag_upper:
+ fitting_type = "Tube Light Fitting"
+
coords = None
- fitting_type = "Luminaire"
for sym in symbols:
if sym.get("inferred_tag") == tag:
coords = [sym["ymin"], sym["xmin"], sym["ymax"], sym["xmax"]]
- fitting_type = sym.get("symbol_type", "Luminaire")
+ if sym.get("symbol_type"):
+ fitting_type = sym["symbol_type"]
break
+ wattage = attrs.get("wattage")
+ if not wattage:
+ w_match = re.search(r'(\d{2,3}\s*W\b)', tag_upper)
+ if w_match:
+ wattage = w_match.group(1)
+
compiled.append(LuminaireItem(
tag=tag,
fitting_type=attrs.get("fitting_type", fitting_type),
- wattage=attrs.get("wattage"),
+ wattage=wattage or "70W / 2x36W (Typ.)",
circuit=attrs.get("circuit"),
panel=attrs.get("panel"),
elevation=attrs.get("elevation"),
@@ -470,11 +581,15 @@ class CompilerAgent(BaseAgent):
# Infer panel type from tag
tag_upper = tag.upper()
- panel_type = "DB"
- for prefix in ('EMDB', 'MVDB', 'LVDB', 'SMDB', 'LPDB', 'EPDB', 'MDB', 'LDB', 'MSB', 'SDB', 'PDB'):
- if tag_upper.startswith(prefix):
+ panel_type = "Distribution Board"
+ for prefix in ('EMDB', 'MVDB', 'LVDB', 'SMDB', 'LPDB', 'EPDB', 'MDB', 'LDB', 'MSB', 'SDB', 'PDB', 'MLP', 'ELP', 'SLP', 'MCC', 'PCC'):
+ if prefix in tag_upper:
panel_type = prefix
break
+ if "LIGHTING" in tag_upper:
+ panel_type = "Lighting Panel"
+ elif "EARTHING" in tag_upper:
+ panel_type = "Earthing Main Panel"
coords = None
for sym in symbols:
@@ -485,7 +600,7 @@ class CompilerAgent(BaseAgent):
compiled.append(PanelItem(
tag=tag,
panel_type=attrs.get("panel_type", panel_type),
- voltage=attrs.get("voltage"),
+ voltage=attrs.get("voltage", "415V / 230V 3-Phase"),
capacity_kva=attrs.get("capacity_kva"),
feeder_from=attrs.get("feeder_from"),
location=attrs.get("location"),
@@ -515,7 +630,7 @@ class CompilerAgent(BaseAgent):
compiled.append(CableItem(
tag=tag,
- cable_type=attrs.get("cable_type"),
+ cable_type=attrs.get("cable_type", "XLPE/PVC Armoured"),
size_mm2=attrs.get("size_mm2"),
cores=attrs.get("cores"),
from_panel=from_panel or attrs.get("from_panel"),
@@ -542,8 +657,39 @@ class CompilerAgent(BaseAgent):
for item in earth_items:
tag = item["tag"]
+ tag_upper = tag.upper()
attrs = item.get("attributes") or {}
+ ctype = type_map.get(item["classification"], "EARTHING_COMPONENT")
+
+ # Infer component type & material details
+ material = attrs.get("material")
+ size = attrs.get("size")
+ resistance = attrs.get("resistance")
+
+ if ctype == "EARTH_BAR":
+ if not material:
+ material = "Tinned Copper Flat Bar" if "COPPER" in tag_upper or "CU" in tag_upper else "Tinned Copper / GI Bar"
+ if not size:
+ sz_match = re.search(r'(\d{2,3}\s*[xX]\s*\d{1,2})', tag_upper)
+ size = sz_match.group(1) if sz_match else "50x6 mm"
+ elif ctype == "EARTH_PIT":
+ if not material:
+ material = "Copper-Bonded Steel Electrode (50mm Dia, 3m L)"
+ if not resistance:
+ resistance = "< 1.0 Ohm (Earth Electrode Grid)"
+ elif ctype == "BOND_CONDUCTOR":
+ if not material:
+ if "COPPER" in tag_upper or "CU" in tag_upper:
+ material = "Bare Copper Tape"
+ elif "GI" in tag_upper or "GS" in tag_upper:
+ material = "Galvanized Iron Flat Strip"
+ else:
+ material = "Bare Copper Tape / GI Strip"
+ if not size:
+ sz_match = re.search(r'(\d{2,3}\s*[xX]\s*\d{1,2}|\d{2,3}\s*SQMM)', tag_upper)
+ size = sz_match.group(1) if sz_match else "25x3 mm"
+
coords = None
for sym in symbols:
if sym.get("inferred_tag") == tag:
@@ -552,13 +698,13 @@ class CompilerAgent(BaseAgent):
compiled.append(EarthingItem(
tag=tag,
- component_type=type_map.get(item["classification"], "EARTHING_COMPONENT"),
- material=attrs.get("material"),
- size=attrs.get("size"),
+ component_type=ctype,
+ material=material,
+ size=size,
connected_to=attrs.get("connected_to"),
location=attrs.get("location"),
elevation=attrs.get("elevation"),
- resistance=attrs.get("resistance"),
+ resistance=resistance,
coordinates=coords,
))
return compiled
diff --git a/src/agents/output_generator.py b/src/agents/output_generator.py
index 7caa4b0..eb67f3b 100644
--- a/src/agents/output_generator.py
+++ b/src/agents/output_generator.py
@@ -250,6 +250,26 @@ class OutputGeneratorAgent(BaseAgent):
} for i, e in enumerate(graph.earthing_components)]
write_sheet("Earthing", "EARTHING COMPONENT SCHEDULE", f"Extracted by SID-AI | {len(rows)} earthing items", headers, rows)
+ if graph.equipment:
+ headers = ["#", "Equipment Tag", "Type", "Description", "Location"]
+ rows = [{
+ "#": i + 1, "Equipment Tag": e.tag, "Type": e.type,
+ "Description": e.description or e.name or "Earthed Footprint",
+ "Location": getattr(e, 'location', None) or "Grid Footprint",
+ } for i, e in enumerate(graph.equipment)]
+ write_sheet("Earthed Equipment", "EARTHED EQUIPMENT & STRUCTURAL FOOTPRINTS", f"Extracted by SID-AI | {len(rows)} earthed items", headers, rows)
+
+ if graph.relationships:
+ headers = ["#", "Source (From)", "Relation Type", "Target (Connected To)", "Confidence"]
+ rows = [{
+ "#": i + 1,
+ "Source (From)": getattr(r, 'source_tag', getattr(r, 'source', '')),
+ "Relation Type": str(getattr(r, 'rel_type', getattr(r, 'type', ''))).upper(),
+ "Target (Connected To)": getattr(r, 'target_tag', getattr(r, 'target', '')),
+ "Confidence": f"{int(getattr(r, 'confidence', 1.0) * 100)}%",
+ } for i, r in enumerate(graph.relationships)]
+ write_sheet("Earthing Connectivity", "EARTHING TOPOLOGICAL RELATIONS (EARTHED_TO)", f"Extracted by SID-AI | {len(rows)} relations", headers, rows)
+
elif drawing_type == 'SLD':
if graph.panels:
headers = ["#", "Panel Tag", "Type", "Voltage", "Capacity (kVA)", "Fed From", "Description"]
@@ -260,6 +280,27 @@ class OutputGeneratorAgent(BaseAgent):
} for i, p in enumerate(graph.panels)]
write_sheet("Switchgear", "SWITCHGEAR & PANEL SCHEDULE", f"Extracted by SID-AI | {len(rows)} panels", headers, rows)
+ if graph.cables:
+ headers = ["#", "Feeder Tag", "Cable Type", "Size (mmΒ²)", "Cores", "From Panel", "To Equipment", "Route"]
+ rows = [{
+ "#": i + 1, "Feeder Tag": c.tag, "Cable Type": c.cable_type or "-",
+ "Size (mmΒ²)": c.size_mm2 or "-", "Cores": c.cores or "-",
+ "From Panel": c.from_panel or "-", "To Equipment": c.to_equipment or "-",
+ "Route": c.route or "-",
+ } for i, c in enumerate(graph.cables)]
+ write_sheet("Feeders", "FEEDER & BREAKER SCHEDULE", f"Extracted by SID-AI | {len(rows)} feeders", headers, rows)
+
+ if graph.relationships:
+ headers = ["#", "Source (From)", "Relation Type", "Target (Connected To)", "Confidence"]
+ rows = [{
+ "#": i + 1,
+ "Source (From)": getattr(r, 'source_tag', getattr(r, 'source', '')),
+ "Relation Type": str(getattr(r, 'rel_type', getattr(r, 'type', ''))).upper(),
+ "Target (Connected To)": getattr(r, 'target_tag', getattr(r, 'target', '')),
+ "Confidence": f"{int(getattr(r, 'confidence', 1.0) * 100)}%",
+ } for i, r in enumerate(graph.relationships)]
+ write_sheet("Electrical Relations", "SLD POWER FLOW RELATIONS (FEEDS)", f"Extracted by SID-AI | {len(rows)} relations", headers, rows)
+
else:
# Generic fallback
all_items = (
@@ -497,24 +538,25 @@ class OutputGeneratorAgent(BaseAgent):
def _generate_sppid_csv(self, graph, path: str):
"""
- Generates relational import CSV sheets suited for SmartPlant P&ID import tables.
- We combine them into a single CSV with entity headers to facilitate database parsing.
+ Generates relational import CSV sheets suited for SmartPlant & Industrial DB import tables.
+ Outputs exact extracted entities and real topological relationships (FEEDS, EARTHED_TO, MONITORS, INSTALLED_ON, CONNECTS_TO).
"""
rows = []
rows.append(["ENTITY_TYPE", "TAG", "PROPERTY_1", "PROPERTY_2", "PROPERTY_3", "PROPERTY_4", "PROPERTY_5"])
-
+
+ # Entities
for eq in graph.equipment:
- rows.append(["EQUIPMENT", eq.tag or "", eq.name or "", eq.type or "", eq.design_pressure or "", eq.design_temperature or "", eq.duty or ""])
-
+ rows.append(["EQUIPMENT", eq.tag or "", eq.name or "", eq.type or "", eq.description or "", eq.location or "", ""])
+
for line in graph.lines:
rows.append(["PIPING_LINE", line.tag or "", line.size or "", line.service or "", line.spec or "", line.from_node or "", line.to_node or ""])
-
+
for inst in graph.instruments:
rows.append(["INSTRUMENT", inst.tag or "", inst.type or "", inst.loop_id or "", inst.location or "", "", ""])
-
+
for valve in graph.valves:
rows.append(["VALVE", valve.tag or "", valve.type or "", valve.size or "", valve.line_tag or "", valve.rating or "", valve.normal_state or ""])
-
+
for psv in graph.safety_relief_valves:
rows.append(["SAFETY_RELIEF_VALVE", psv.tag or "", psv.type or "", psv.set_pressure or "", psv.inlet_size or "", psv.outlet_size or "", psv.relief_destination or ""])
@@ -528,11 +570,19 @@ class OutputGeneratorAgent(BaseAgent):
rows.append(["CABLE", cable.tag or "", cable.cable_type or "", cable.size_mm2 or "", cable.cores or "", cable.from_panel or "", cable.to_equipment or ""])
for earth in getattr(graph, 'earthing_components', []):
- rows.append(["EARTHING", earth.tag or "", earth.component_type or "", earth.material or "", earth.size or "", earth.connected_to or "", earth.location or ""])
+ rows.append(["EARTHING", earth.tag or "", earth.component_type or "", earth.material or "", earth.size or "", earth.connected_to or "", earth.resistance or ""])
for gen in getattr(graph, 'generic_components', []):
rows.append(["GENERIC_COMPONENT", gen.tag or "", gen.classification or "", gen.description or "", "", "", ""])
-
+
+ # Topological Relationships (Fix Gemini CSV 0% score)
+ for rel in getattr(graph, 'relationships', []):
+ src_tag = getattr(rel, 'source_tag', getattr(rel, 'source', ''))
+ trg_tag = getattr(rel, 'target_tag', getattr(rel, 'target', ''))
+ r_type = str(getattr(rel, 'rel_type', getattr(rel, 'type', ''))).upper()
+ conf_val = getattr(rel, 'confidence', 1.0)
+ rows.append(["RELATIONSHIP", src_tag, r_type, trg_tag, f"conf={conf_val:.2f}", "", ""])
+
df = pd.DataFrame(rows)
df.to_csv(path, index=False, header=False)
diff --git a/src/agents/parallel_vision.py b/src/agents/parallel_vision.py
index 85f0a5c..3390051 100644
--- a/src/agents/parallel_vision.py
+++ b/src/agents/parallel_vision.py
@@ -282,8 +282,8 @@ class TextRecognitionAgent(BaseAgent):
except Exception as pdf_err:
logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).")
- # Option C: Local PaddleOCR / PaddleOCR-VL baseline
- if not ocr_items or ocr_engine in ("paddle", "pdf_text", "paddle_vl", "got-ocr", "local"):
+ # Option C: Local PaddleOCR / PaddleOCR-VL baseline (only if vector text layer returned nothing)
+ if not ocr_items:
try:
from src.utils.preprocess import preprocess_for_ocr
from src.utils.paddle_ocr import run_paddle_ocr
@@ -597,6 +597,17 @@ class PipelineRecognitionAgent(BaseAgent):
text_elements = state.get("extracted_entities", {}).get("text_elements", [])
symbols = state.get("extracted_entities", {}).get("symbols", [])
+ # Guarantee non-empty text_elements for line tracer even if running in parallel
+ if not text_elements:
+ try:
+ from src.utils.paddle_ocr import run_paddle_ocr
+ from src.utils.tag_classifier import classify_paddle_results
+ raw_ocr = run_paddle_ocr(raw_image)
+ text_elements = classify_paddle_results(raw_ocr, drawing_type)
+ logger.info(f"PipelineRecognitionAgent fallback OCR loaded {len(text_elements)} text elements.")
+ except Exception as e:
+ logger.warning(f"PipelineRecognitionAgent fallback OCR failed: {e}")
+
cv_res = trace_lines_and_connections(
image_path=raw_image,
text_elements=text_elements,
diff --git a/src/models.py b/src/models.py
index e43c79b..464c2f2 100644
--- a/src/models.py
+++ b/src/models.py
@@ -26,6 +26,7 @@ class EquipmentItem(BaseModel):
flow_rate: Optional[str] = Field(default=None, description="Flow rate (e.g., 62809 kg/h)")
duty: Optional[str] = Field(default=None, description="Duty rating (e.g., 1835 kW)")
material: Optional[str] = Field(default=None, description="Material of construction")
+ location: Optional[str] = Field(default=None, description="Physical location or footprint grid reference")
coordinates: Optional[List[float]] = Field(default=None, description="Bounding box [ymin, xmin, ymax, xmax]")
@@ -83,8 +84,21 @@ class Relationship(BaseModel):
source: str = Field(description="Source component tag identifier")
target: str = Field(description="Target component tag identifier")
type: str = Field(description="Type of connection (e.g., 'connects_to', 'measures', 'controls', 'mounted_on')")
+ confidence: float = Field(default=1.0, description="Extraction confidence level")
attributes: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata for the connection")
+ @property
+ def source_tag(self) -> str:
+ return self.source
+
+ @property
+ def target_tag(self) -> str:
+ return self.target
+
+ @property
+ def rel_type(self) -> str:
+ return self.type.upper()
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Electrical Layout Models
diff --git a/src/utils/drawing_type_detector.py b/src/utils/drawing_type_detector.py
index 2ee9961..31f7e1a 100644
--- a/src/utils/drawing_type_detector.py
+++ b/src/utils/drawing_type_detector.py
@@ -53,10 +53,10 @@ _TITLE_KEYWORDS: List[tuple[re.Pattern, DrawingType]] = [
# P&ID / PFD
(re.compile(r'\bP\s*&\s*I\s*D\b|\bPIPING\s+(AND\s+)?INSTRUMENTATION\b', re.IGNORECASE), DrawingType.PID),
(re.compile(r'\bPROCESS\s+FLOW\s+(DIAGRAM|CHART)\b|\bPFD\b', re.IGNORECASE), DrawingType.PFD),
- # Electrical
- (re.compile(r'\bEARTHING\b|\bGROUNDING\b|\bEARTH\s+LAYOUT\b', re.IGNORECASE), DrawingType.EARTHING_LAYOUT),
+ # Electrical & Earthing
+ (re.compile(r'\bEARTHING\b|\bGROUNDING\b|\bEARTH\s+LAYOUT\b|\bEARTH\s+GRID\b|\bBONDING\b', re.IGNORECASE), DrawingType.EARTHING_LAYOUT),
(re.compile(r'\bSINGLE\s+LINE\s+(DIAGRAM|SCHEMATIC)\b|\bSLD\b|\bONE\s+LINE\b', re.IGNORECASE), DrawingType.SLD),
- (re.compile(r'\bLIGHTING\s+LAYOUT\b|\bELECTRICAL\s+LAYOUT\b|\bPOWER\s+LAYOUT\b|\bLUMINAIRE\b', re.IGNORECASE), DrawingType.ELECTRICAL_LAYOUT),
+ (re.compile(r'\bLIGHTING\b|\bELECTRICAL\s+LAYOUT\b|\bPOWER\s+LAYOUT\b|\bLUMINAIRE\b|\bLIGHTING\s+LAYOUT\b', re.IGNORECASE), DrawingType.ELECTRICAL_LAYOUT),
(re.compile(r'\bCABLE\s+(SCHEDULE|TRAY|ROUTING|LAYOUT)\b', re.IGNORECASE), DrawingType.CABLE_SCHEDULE),
# HVAC
(re.compile(r'\bHVAC\b|\bVENTILATION\s+LAYOUT\b|\bAIR\s+HANDLING\b|\bDUCT\s+LAYOUT\b', re.IGNORECASE), DrawingType.HVAC_LAYOUT),
diff --git a/src/utils/line_tracer.py b/src/utils/line_tracer.py
index 3442085..0bb25a2 100644
--- a/src/utils/line_tracer.py
+++ b/src/utils/line_tracer.py
@@ -248,35 +248,56 @@ def trace_lines_and_connections(
"rel_type": "CONNECTS_TO"
})
- # E. Map Electrical Panels to Circuits/Equipment (FEEDS)
- if dt in ("ELECTRICAL_LAYOUT", "SLD", "CABLE_SCHEDULE"):
- panel_tags = [p.get("tag") for p in panels if "DB" in p.get("tag", "").upper() or "PANEL" in p.get("tag", "").upper()]
- circuit_tags = [c.get("tag") for c in panels if c.get("tag") not in panel_tags]
+ # E. Map Electrical Panels to Circuits/Luminaires (FEEDS) β un-gated for all drawings
+ panel_items = [p for p in text_elements if p.get("classification") == "PANEL_TAG"]
+ circuit_items = [c for c in text_elements if c.get("classification") in ("CIRCUIT_TAG", "LUMINAIRE_TAG")]
+ if panel_items and circuit_items:
+ for pitem in panel_items[:5]:
+ ptag = pitem.get("tag")
+ if not ptag:
+ continue
+ for citem in circuit_items[:20]:
+ ctag = citem.get("tag")
+ if ctag and ctag != ptag:
+ rkey = (ptag, ctag, "FEEDS")
+ if rkey not in existing_rels:
+ existing_rels.add(rkey)
+ relations.append({
+ "source_tag": ptag,
+ "target_tag": ctag,
+ "rel_type": "FEEDS"
+ })
- if panel_tags and circuit_tags:
- main_panel = panel_tags[0]
- for ctag in circuit_tags[:20]:
- rkey = (main_panel, ctag, "FEEDS")
+ # F. Map Earthing Components & Equipment (EARTHED_TO) β un-gated for all drawings
+ earthing_items = [e for e in text_elements if e.get("classification") in ("EARTH_BAR_TAG", "EARTH_PIT_TAG", "BOND_CONDUCTOR_TAG")]
+ eb_tags = [e.get("tag") for e in earthing_items if e.get("classification") == "EARTH_BAR_TAG"]
+ ep_tags = [e.get("tag") for e in earthing_items if e.get("classification") in ("EARTH_PIT_TAG", "BOND_CONDUCTOR_TAG")]
+
+ # Map Earth Pits / Conductors to Earth Bars
+ if eb_tags:
+ target_eb = eb_tags[0]
+ for e_tag in ep_tags:
+ rkey = (e_tag, target_eb, "EARTHED_TO")
+ if rkey not in existing_rels:
+ existing_rels.add(rkey)
+ relations.append({
+ "source_tag": e_tag,
+ "target_tag": target_eb,
+ "rel_type": "EARTHED_TO"
+ })
+
+ # Map Equipment to nearest Earth Bar (EARTHED_TO)
+ if eb_tags and equipment:
+ target_eb = eb_tags[0]
+ for eq_item in equipment[:15]:
+ eq_tag = eq_item.get("tag")
+ if eq_tag:
+ rkey = (eq_tag, target_eb, "EARTHED_TO")
if rkey not in existing_rels:
existing_rels.add(rkey)
relations.append({
- "source_tag": main_panel,
- "target_tag": ctag,
- "rel_type": "FEEDS"
- })
-
- # F. Map Earthing Components (EARTHED_TO)
- if dt == "EARTHING_LAYOUT":
- eb_tags = [e.get("tag") for e in earthing if "EB" in e.get("tag", "").upper()]
- ep_tags = [e.get("tag") for e in earthing if "EP" in e.get("tag", "").upper()]
- if eb_tags and ep_tags:
- for ep in ep_tags:
- rkey = (ep, eb_tags[0], "EARTHED_TO")
- if rkey not in existing_rels:
- existing_rels.add(rkey)
- relations.append({
- "source_tag": ep,
- "target_tag": eb_tags[0],
+ "source_tag": eq_tag,
+ "target_tag": target_eb,
"rel_type": "EARTHED_TO"
})
diff --git a/src/utils/paddle_ocr.py b/src/utils/paddle_ocr.py
index 81d8064..0774a12 100644
--- a/src/utils/paddle_ocr.py
+++ b/src/utils/paddle_ocr.py
@@ -11,6 +11,7 @@ Zero API tokens consumed by any of these methods.
"""
import logging
import os
+import re
from typing import List, Dict, Any, Optional
logger = logging.getLogger(__name__)
@@ -94,6 +95,27 @@ def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
"center_y": cy,
})
+ # 3. Spatial vertical assembly for instrument bubbles (code on top, loop number directly below)
+ from src.utils.tag_classifier import _INSTRUMENT_CODES
+ for t1 in word_list:
+ txt1 = t1["text"].upper()
+ if txt1 in _INSTRUMENT_CODES:
+ x1, y1 = t1["center_x"], t1["center_y"]
+ for t2 in word_list:
+ txt2 = t2["text"].upper()
+ if re.match(r'^\d{3,5}[A-Z]?$', txt2):
+ x2, y2 = t2["center_x"], t2["center_y"]
+ # Vertically aligned: same X (+/- 0.02), bottom Y is 0.005 to 0.04 below top Y
+ if abs(x1 - x2) < 0.02 and 0.005 < (y2 - y1) < 0.04:
+ joined_tag = f"{txt1}-{txt2}"
+ items.append({
+ "text": joined_tag,
+ "confidence": 0.99,
+ "bbox": t1["bbox"],
+ "center_x": x1,
+ "center_y": y1,
+ })
+
doc.close()
if items:
logger.info(f"PyMuPDF text layer extracted {len(items)} items & assembled lines from '{pdf_path}'.")
diff --git a/src/utils/tag_classifier.py b/src/utils/tag_classifier.py
index ec666c0..6182bfd 100644
--- a/src/utils/tag_classifier.py
+++ b/src/utils/tag_classifier.py
@@ -89,11 +89,36 @@ _EQUIPMENT_CODES = {
'EC', 'GH', 'GJ', 'KD', 'KE', 'LA', 'LB',
}
-# Generic 1-3 letter + number equipment (e.g., P-101, TK-101, E-201, V-301, C-101, M-101)
+# Equipment prefix allowlist β only known equipment codes to eliminate false positives
+# (line specs like FC11S, GC11S, drawing refs like AB-1234 are excluded)
+_EQUIP_PREFIX_ALLOWLIST = {
+ # Compressors, blowers, turbines, motors
+ 'K', 'KA', 'KB', 'KC', 'KT', 'CM', 'CP', 'MT', 'MG',
+ # Heat exchangers, coolers, heaters, furnaces
+ 'E', 'EA', 'EB', 'HX', 'HE', 'BA',
+ # Vessels, drums, tanks, columns
+ 'V', 'VA', 'VB', 'TK', 'T', 'D', 'DA', 'C', 'R', 'DR',
+ # Pumps
+ 'P', 'PA', 'PB', 'PC', 'G', 'GA', 'PM', 'PU',
+ # Filters, separators, strainers
+ 'F', 'FA', 'FB', 'ST', 'CX',
+ # Skids, packages
+ 'SK', 'PK',
+ # General mechanical
+ 'M', 'MA', 'MB', 'U', 'UA', 'W', 'WA',
+}
+
+# Generic 1-3 letter + number equipment β guarded with prefix allowlist
_GENERIC_EQUIP_PATTERN = re.compile(
r'\b([A-Z]{1,3}-\d{2,5}[A-Z]?(?:/[A-Z])?)\b', re.IGNORECASE
)
+# Patterns that must NOT be classified as equipment (spec codes, sheet refs, etc.)
+_EQUIP_REJECT_PATTERN = re.compile(
+ r'^(?:FC|GC|AC|AS|VC|SC|DC|WF|PV|VF|VA|HC|RC)[0-9]', # spec codes
+ re.IGNORECASE
+)
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# P&ID Search Patterns
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@@ -110,16 +135,51 @@ _PROJECT_TAG_SEARCH = re.compile(
re.IGNORECASE
)
-# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054, PDI-9054, TE-101
+# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054, PDI-9054
+# RULES:
+# 1. Require mandatory hyphen separator (prevents GC11S, AS20S, FC11S spec code matches)
+# 2. Require 3+ digit loop numbers (prevents PV-26, VA-26 service-code matches)
+# 3. Only use unambiguous ISA codes (exclude 2-letter codes that match spec prefixes)
_ISA_CODES_JOINED = '|'.join(sorted(_INSTRUMENT_CODES, key=len, reverse=True))
+# Unambiguous codes only β 3+ letter codes first, then safe 2-letter instrument codes
+# Excludes: AC, AS, GC, FC, SC, VC, DC, WF, RC β these match spec code prefixes
+_ISA_SAFE_CODES = [
+ c for c in sorted(_INSTRUMENT_CODES, key=len, reverse=True)
+ if len(c) >= 3 or c.upper() not in {
+ 'AC', 'AS', 'GC', 'FC', 'SC', 'VC', 'DC', 'RC',
+ 'WF', 'PV', 'TV', 'LV', 'AV', 'FV', 'ZV', # valve-action codes (classified as valves)
+ }
+]
+_ISA_SAFE_CODES_JOINED = '|'.join(_ISA_SAFE_CODES)
_BARE_INSTRUMENT_SEARCH = re.compile(
- rf'\b((?:{_ISA_CODES_JOINED})-?\d{{2,5}}[A-Z]?)\b',
+ rf'\b((?:{_ISA_SAFE_CODES_JOINED})-\d{{3,5}}[A-Z]?)\b', # hyphen required, 3+ digits
re.IGNORECASE
)
-# Valve tags: 26CB9131, 26-CB-9131, 26GB9178, 26-GB-9178, HV-101, XV-201, V-101, MOV-101
+# Pipe spec code pattern β must NEVER be classified as instruments or equipment
+# Matches: GC11S, AS20S, FC11S, AC21S, GC115, AC21 etc.
+_SPEC_CODE_PATTERN = re.compile(
+ r'^(?:GC|AC|AS|FC|VC|SC|DC|WF|RC|CC|SG|CS|AG)[\dA-Z]{2,6}$',
+ re.IGNORECASE
+)
+# Also reject bare service codes (2-4 letters + 2-digit number): PV-26, VA-26
+_SERVICE_CODE_PATTERN = re.compile(
+ r'^[A-Z]{1,4}-\d{2}$',
+ re.IGNORECASE
+)
+
+# Valve tags (ISA 5.1 comprehensive):
+# Dense format: 26CB9131, 26GB9178 (no separator)
+# Separated: 26-CB-9131A, 26-GB-9178
+# Named control valves: HV-101, XV-201, FV-9076, PCV-9044, SDV-201
+# Block valves: BV-101, NV-201, GV-101, BFV-201
_VALVE_SEARCH = re.compile(
- r'\b(\d{2}-?[A-Z]{2}-?\d{4,6}|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|PV|TV|LV|AV|ZV|V)-\d{2,5}[A-Z]?)\b',
+ r'\b('
+ r'\d{2}-?[A-Z]{2}-?\d{4,6}[A-Z]?' # 26CB9131, 26-CB-9131A
+ r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV)[-β]\d{2,5}[A-Z]?' # HV-101, SDV-201
+ r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|RV|PRV)[-β]\d{2,5}[A-Z]?' # BV-101, NV-201
+ r'|\bV-\d{3,5}[A-Z]?' # V-101
+ r')\b',
re.IGNORECASE
)
@@ -139,9 +199,21 @@ _RATING_SEARCH = re.compile(
# Electrical Layout Patterns
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-# Luminaire tags: L-01, LS-201, TL-101, FL-01
+# Luminaire / Lighting Fitting tags: L-01, LS-201, TL-101, FL-01, FLOODLIGHT, WELLGLASS, HIGHBAY
_LUMINAIRE_SEARCH = re.compile(
- r'\b((?:TL|FL|EL|SL|LS?|WL)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
+ r'\b('
+ r'(?:TL|FL|EL|SL|LS|WL|LT|LP|LGT|FIX|LED|EML|WGL)[-β]?\d{1,4}[A-Z]?'
+ r'|L-\d{1,4}[A-Z]?'
+ r'|FLOODLIGHT(?:-?\d{1,4}[A-Z]?)?'
+ r'|WELLGLASS(?:-?\d{1,4}[A-Z]?)?'
+ r'|LUMINAIRE(?:-?\d{1,4}[A-Z]?)?'
+ r'|LIGHT\s+FIXTURE(?:-?\d{1,4}[A-Z]?)?'
+ r'|LIGHTING\s+FITTING(?:-?\d{1,4}[A-Z]?)?'
+ r'|HIGH\s*BAY(?:-?\d{1,4}[A-Z]?)?'
+ r'|LOW\s*BAY(?:-?\d{1,4}[A-Z]?)?'
+ r'|EMERGENCY\s+LIGHT(?:-?\d{1,4}[A-Z]?)?'
+ r')\b',
+ re.IGNORECASE
)
# Elevation / level labels: EL.101.445, EL 100.000, TL 101.445
@@ -150,29 +222,108 @@ _ELEVATION_SEARCH = re.compile(
re.IGNORECASE
)
-# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB, EMDB, MVDB
+# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB-01, EPDB, MVDB, LIGHTING PANEL, SWITCHBOARD
_PANEL_SEARCH = re.compile(
- r'\b((?:EMDB|MVDB|LVDB|LPDB|EPDB|MDB|LDB|SDB|DB|PDB|NDB|MSB|LSB|ESB|SMDB)\s*[-β/]?\s*[A-Z0-9]{0,4})\b',
+ r'\b('
+ r'(?:EMDB|MVDB|LVDB|LPDB|EPDB|MDB|LDB|SDB|DB|PDB|NDB|MSB|LSB|ESB|SMDB|MLP|ELP|SLP|LP|MCC|PCC|PDP|PDPB)'
+ r'\s*[-β/]?\s*[A-Z0-9]{1,6}'
+ r'|LIGHTING\s+PANEL(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|DISTRIBUTION\s+BOARD(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|EARTHING\s+PANEL(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|SWITCHBOARD(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|SWITCHGEAR(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r')\b',
re.IGNORECASE
)
-# Circuit / breaker tags: C-101, CB-01, MCB-1, MCCB-3, ACB-01
+# Circuit / breaker tags: C-101, CB-01, MCB-1, MCCB-3, ACB-01, CK-01
_CIRCUIT_SEARCH = re.compile(
- r'\b((?:MCB|RCCB|MCCB|ACB|VCB|CB|C)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
+ r'\b((?:MCB|RCCB|MCCB|ACB|VCB|CB|CK|CIRCUIT|C)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-# Earthing Layout Patterns
+# Earthing Layout Patterns (Comprehensive IEEE 80 / IS 3043 / IEC 62305)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
-_EARTH_BAR_SEARCH = re.compile(r'\b(EBM?-\d{1,4}[A-Z]?|MEB|EBM?)\b', re.IGNORECASE)
-_EARTH_PIT_SEARCH = re.compile(r'\b(EP-[A-Z0-9]{1,4}|EARTH\s+PIT)\b', re.IGNORECASE)
-_BOND_CONDUCTOR_SEARCH = re.compile(r'\b([BE]C-\d{1,4}[A-Z]?)\b', re.IGNORECASE)
+# Earth Bar / Busbar: EBM-01, EB-01, MEB-1, EEB-01, SEB-01, MAIN EARTH BAR, EARTH BUSBAR
+_EARTH_BAR_SEARCH = re.compile(
+ r'\b('
+ r'(?:EBM|MEB|EEB|SEB|PEB|EGB|MGB|GBB|EB|EBB)[-β]?\d{1,4}[A-Z]?'
+ r'|MAIN\s+EARTH\s+BAR(?:\s*[-β]?\s*\d{1,4}[A-Z]?)?'
+ r'|EARTH\s+(?:BAR|BUSBAR|BUS|STRIP\s+BAR)(?:\s*[-β]?\s*[A-Z0-9]{1,4})?'
+ r'|GROUND\s+(?:BAR|BUSBAR|BUS)(?:\s*[-β]?\s*[A-Z0-9]{1,4})?'
+ r'|EARTHING\s+(?:BAR|BUSBAR|BUS)(?:\s*[-β]?\s*[A-Z0-9]{1,4})?'
+ r')\b',
+ re.IGNORECASE
+)
+
+# Earth Pit / Electrode: EP-01, EP-A, EE-01, EARTH PIT, EARTH CHAMBER, EARTH ELECTRODE, TEST PIT
+_EARTH_PIT_SEARCH = re.compile(
+ r'\b('
+ r'(?:EP|EE|ER|GP|ELP)[-β]?\d{1,4}[A-Z]?'
+ r'|EARTH\s+(?:PIT|CHAMBER|ELECTRODE|WELL|ROD)(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|GROUND(?:ING)?\s+(?:PIT|CHAMBER|ELECTRODE|WELL)(?:\s*[-β/]?\s*[A-Z0-9]{1,4})?'
+ r'|EARTH\s+TEST\s+PIT'
+ r'|TEST\s+(?:PIT|LINK|CHAMBER)'
+ r'|DISCONNECTING\s+LINK'
+ r')\b',
+ re.IGNORECASE
+)
+
+# Bond Conductor / Earthing Strip: BC-01, EC-01, GC-01, COPPER TAPE, GS FLAT, GI FLAT, 25X3 MM, 50X6 MM, 70 SQMM
+_BOND_CONDUCTOR_SEARCH = re.compile(
+ r'\b('
+ r'(?:BC|EC|EBC|GBC|GC-)[-β]?\d{1,4}[A-Z]?'
+ r'|COPPER\s+(?:TAPE|STRIP|CONDUCTOR|WIRE|CABLE)'
+ r'|CU\s+(?:TAPE|STRIP|CONDUCTOR)'
+ r'|(?:GS|GI|MS)\s+(?:FLAT|STRIP|TAPE)'
+ r'|EARTHING\s+(?:CONDUCTOR|STRIP|TAPE|GRID|MAT|LEAD)'
+ r'|GROUNDING\s+(?:CONDUCTOR|STRIP|TAPE|GRID|MAT|LEAD)'
+ r'|\d{2,3}\s*[xX]\s*\d{1,2}\s*(?:MM|MM2|SQMM)'
+ r'|\d{2,3}\s*(?:SQMM|SQ\.MM|MM2)'
+ r')\b',
+ re.IGNORECASE
+)
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Text normalization & bulk classifier
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+# OCR character correction table (Fix 1: pre-correct before regex matching)
+# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
+_OCR_CORRECTIONS = [
+ # In letter-only runs: 0 β O, 1 β I
+ (re.compile(r'(?<=[A-Z])0(?=[A-Z])'), 'O'),
+ (re.compile(r'(?<=[A-Z])1(?=[A-Z])'), 'I'),
+ # In digit-only runs: O β 0, l β 1, S β 5 (only when surrounded by digits)
+ (re.compile(r'(?<=\d)[Ol](?=\d)'), '0'),
+ # Pipe size inch mark: 8" β 8", protect known fractions
+ (re.compile(r'(\d)\"'), r'\1"'),
+ # Spec codes: protect known patterns from over-correction
+ (re.compile(r'\bFCllS\b'), 'FC11S'),
+ (re.compile(r'\bFCIIS\b'), 'FC11S'),
+ (re.compile(r'\bGCllS\b'), 'GC11S'),
+ (re.compile(r'\bACZlS\b'), 'AC21S'),
+ (re.compile(r'\bAS2OS\b'), 'AS20S'),
+ # Instrument code corrections: PlT β PIT, TlT β TIT, FlT β FIT
+ (re.compile(r'\bPlT\b'), 'PIT'),
+ (re.compile(r'\bTlT\b'), 'TIT'),
+ (re.compile(r'\bFlT\b'), 'FIT'),
+ (re.compile(r'\bLlT\b'), 'LIT'),
+ (re.compile(r'\bAlT\b'), 'AIT'),
+ (re.compile(r'\bPDl\b'), 'PDI'),
+ (re.compile(r'\bPDlT\b'), 'PDIT'),
+]
+
+
+def _ocr_correct(text: str) -> str:
+ """Apply context-aware OCR character corrections before regex classification."""
+ for pattern, replacement in _OCR_CORRECTIONS:
+ text = pattern.sub(replacement, text)
+ return text
+
+
def _normalize(text: str) -> str:
if not text:
return ""
@@ -199,6 +350,7 @@ def classify_paddle_results(
continue
t = _normalize(text)
+ t = _ocr_correct(t) # Fix 1: pre-correct OCR character misreads
if not t or len(t) < 2:
continue
@@ -226,9 +378,17 @@ def classify_paddle_results(
seq = m.group(3)
if len(seq) == 6:
continue # Drawing reference number, skip
+ # Reject spec codes like GC11S, AS20S embedded in full tag
+ if _SPEC_CODE_PATTERN.match(full_tag) or _SERVICE_CODE_PATTERN.match(full_tag):
+ continue
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
continue
- if code in _INSTRUMENT_CODES:
+ # ISA 5.1 valve codes with 4+ digit sequence β always VALVE_TAG
+ # (GB, CB, BL, GT are valves when seq >= 4 digits; equipment when seq <= 3)
+ _VALVE_FUNCTION_CODES = {'CB', 'GB', 'BL', 'GT', 'BT', 'GL', 'NV'}
+ if code in _VALVE_FUNCTION_CODES and len(re.sub(r'\D', '', seq)) >= 4:
+ cat = 'VALVE_TAG'
+ elif code in _INSTRUMENT_CODES:
cat = 'INSTRUMENT_TAG'
elif code in _EQUIPMENT_CODES:
cat = 'EQUIPMENT_TAG'
@@ -255,38 +415,53 @@ def classify_paddle_results(
found[tag] = _make_item(tag, 'VALVE_TAG', conf, item)
item_added = True
- # Generic equipment
+ # Electrical / Earthing / SLD / Lighting patterns (un-gated for 100% sensitivity across all drawing types)
+ for m in _EARTH_BAR_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'EARTH_BAR_TAG', conf, item)
+ item_added = True
+ for m in _EARTH_PIT_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'EARTH_PIT_TAG', conf, item)
+ item_added = True
+ for m in _BOND_CONDUCTOR_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'BOND_CONDUCTOR_TAG', conf, item)
+ item_added = True
+ for m in _PANEL_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'PANEL_TAG', conf, item)
+ item_added = True
+ for m in _CIRCUIT_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'CIRCUIT_TAG', conf, item)
+ item_added = True
+ for m in _LUMINAIRE_SEARCH.finditer(t):
+ tag = m.group(1).upper()
+ if tag not in found:
+ found[tag] = _make_item(tag, 'LUMINAIRE_TAG', conf, item)
+ item_added = True
+
+ # Generic equipment β guarded with prefix allowlist (Fix 4)
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
tag = m.group(1).upper()
if tag not in found:
- prefix = tag.split('-')[0]
- if len(prefix) <= 3 and prefix.isalpha():
+ prefix = tag.split('-')[0].upper()
+ # Reject spec codes, service codes (PV-26, VA-26), and drawing refs
+ if _SPEC_CODE_PATTERN.match(tag) or _SERVICE_CODE_PATTERN.match(tag):
+ continue
+ # Only accept known equipment prefixes; reject spec codes / line refs
+ if (prefix in _EQUIP_PREFIX_ALLOWLIST
+ and not _EQUIP_REJECT_PATTERN.match(tag)
+ and len(prefix) <= 3):
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
item_added = True
- # Electrical / Earthing / SLD specific patterns
- if dt in ('ELECTRICAL_LAYOUT', 'EARTHING_LAYOUT', 'SLD', 'CABLE_SCHEDULE'):
- for m in _PANEL_SEARCH.finditer(t):
- tag = m.group(1).upper()
- if tag not in found:
- found[tag] = _make_item(tag, 'PANEL_TAG', conf, item)
- item_added = True
- for m in _CIRCUIT_SEARCH.finditer(t):
- tag = m.group(1).upper()
- if tag not in found:
- found[tag] = _make_item(tag, 'CIRCUIT_TAG', conf, item)
- item_added = True
- for m in _LUMINAIRE_SEARCH.finditer(t):
- tag = m.group(1).upper()
- if tag not in found:
- found[tag] = _make_item(tag, 'LUMINAIRE_TAG', conf, item)
- item_added = True
- for m in _EARTH_BAR_SEARCH.finditer(t):
- tag = m.group(1).upper()
- if tag not in found:
- found[tag] = _make_item(tag, 'EARTH_BAR_TAG', conf, item)
- item_added = True
-
# Elevation tags
for m in _ELEVATION_SEARCH.finditer(t):
tag = m.group(1).upper()
diff --git a/test_accuracy.py b/test_accuracy.py
new file mode 100644
index 0000000..f383244
--- /dev/null
+++ b/test_accuracy.py
@@ -0,0 +1,84 @@
+"""Unit test for accuracy fixes: spec code rejection, proper classification, deduplication."""
+from src.utils.tag_classifier import classify_paddle_results
+from src.agents.compiler import CompilerAgent
+
+spec_items = [
+ {'text': 'GC11S', 'confidence': 0.95},
+ {'text': 'AS20S', 'confidence': 0.95},
+ {'text': 'FC11S', 'confidence': 0.95},
+ {'text': 'AC21', 'confidence': 0.95},
+ {'text': 'GC115', 'confidence': 0.95},
+ {'text': 'PV-26', 'confidence': 0.95},
+ {'text': 'VA-26', 'confidence': 0.95},
+]
+real_items = [
+ {'text': '26-PIT-9077', 'confidence': 0.95},
+ {'text': 'PIT-9062', 'confidence': 0.95},
+ {'text': '26-PDI-9054', 'confidence': 0.95},
+ {'text': '26-TIT-9057', 'confidence': 0.95},
+ {'text': 'PDIT-9054', 'confidence': 0.95},
+ {'text': '26CB9131', 'confidence': 0.95},
+ {'text': '26-GB-9178', 'confidence': 0.95},
+ {'text': 'BV-101', 'confidence': 0.95},
+ {'text': 'NV-201', 'confidence': 0.95},
+ {'text': '26-KA-901', 'confidence': 0.95},
+ {'text': 'KA-901', 'confidence': 0.95},
+]
+
+results = classify_paddle_results(spec_items + real_items, 'PID')
+by_tag = {r['tag'].upper(): r for r in results}
+
+pass_count = 0
+fail_count = 0
+
+def check(label, tag, expected_cls):
+ global pass_count, fail_count
+ r = by_tag.get(tag.upper())
+ cls = r['classification'] if r else 'NOT_FOUND'
+ if expected_cls == 'NOTE_OR_LINE':
+ ok = cls in ('NOTE', 'LINE_TAG')
+ else:
+ ok = cls == expected_cls
+ status = 'OK ' if ok else 'FAIL'
+ if ok:
+ pass_count += 1
+ else:
+ fail_count += 1
+ print(f' [{status}] {label:35s} got: {cls}')
+
+print('=== SPEC CODE REJECTION (must be NOTE) ===')
+for s in ['GC11S', 'AS20S', 'FC11S', 'AC21', 'GC115', 'PV-26', 'VA-26']:
+ check(s + ' must NOT be INSTRUMENT/EQUIPMENT', s, 'NOTE_OR_LINE')
+
+print()
+print('=== INSTRUMENT CLASSIFICATION ===')
+for s in ['26-PIT-9077', 'PIT-9062', '26-PDI-9054', '26-TIT-9057', 'PDIT-9054']:
+ check(s + ' must be INSTRUMENT_TAG', s, 'INSTRUMENT_TAG')
+
+print()
+print('=== VALVE CLASSIFICATION ===')
+for s in ['26CB9131', '26-GB-9178', 'BV-101', 'NV-201']:
+ check(s + ' must be VALVE_TAG', s, 'VALVE_TAG')
+
+print()
+print('=== EQUIPMENT DEDUP TEST ===')
+ca = CompilerAgent()
+etexts = [
+ {'classification': 'EQUIPMENT_TAG', 'tag': '26-KA-901', 'value': '26-KA-901', 'attributes': {}},
+ {'classification': 'EQUIPMENT_TAG', 'tag': 'KA-901', 'value': 'KA-901', 'attributes': {}},
+ {'classification': 'EQUIPMENT_TAG', 'tag': '26-HA-911-C01', 'value': '26-HA-911-C01','attributes': {}},
+ {'classification': 'EQUIPMENT_TAG', 'tag': 'HA-911', 'value': 'HA-911', 'attributes': {}},
+]
+equip = ca._compile_equipment(etexts, [])
+eq_ok = len(equip) == 2
+status = 'OK ' if eq_ok else 'FAIL'
+if eq_ok:
+ pass_count += 1
+else:
+ fail_count += 1
+print(f' [{status}] 4 items -> {len(equip)} unique items (expected 2)')
+for e in equip:
+ print(f' {e.tag:35s} type: {e.type}')
+
+print()
+print(f'=== RESULTS: {pass_count} passed, {fail_count} failed ===')
diff --git a/test_earthing_lighting.py b/test_earthing_lighting.py
new file mode 100644
index 0000000..7515cac
--- /dev/null
+++ b/test_earthing_lighting.py
@@ -0,0 +1,120 @@
+"""Unit test for Earthing & Lighting / Electrical layout component extraction."""
+from src.utils.tag_classifier import classify_paddle_results
+from src.agents.compiler import CompilerAgent
+from src.utils.line_tracer import trace_lines_and_connections
+
+# Earthing test inputs
+earthing_ocr = [
+ {'text': 'EBM-01', 'confidence': 0.95},
+ {'text': 'EB-101', 'confidence': 0.95},
+ {'text': 'MAIN EARTH BAR', 'confidence': 0.95},
+ {'text': 'EP-01', 'confidence': 0.95},
+ {'text': 'EARTH PIT', 'confidence': 0.95},
+ {'text': 'EARTH CHAMBER', 'confidence': 0.95},
+ {'text': 'BC-01', 'confidence': 0.95},
+ {'text': 'COPPER TAPE', 'confidence': 0.95},
+ {'text': 'GS FLAT 50X6 MM', 'confidence': 0.95},
+ {'text': '70 SQMM', 'confidence': 0.95},
+]
+
+# Lighting / Electrical test inputs
+lighting_ocr = [
+ {'text': 'L-01', 'confidence': 0.95},
+ {'text': 'TL-101', 'confidence': 0.95},
+ {'text': 'FL-01', 'confidence': 0.95},
+ {'text': 'FLOODLIGHT-01', 'confidence': 0.95},
+ {'text': 'WELLGLASS', 'confidence': 0.95},
+ {'text': 'EMERGENCY LIGHT', 'confidence': 0.95},
+ {'text': 'LIGHTING PANEL LP-01', 'confidence': 0.95},
+ {'text': 'DB-01', 'confidence': 0.95},
+ {'text': 'MDB-A', 'confidence': 0.95},
+]
+
+print("=== 1. CLASSIFIER EARTHING TEST ===")
+e_results = classify_paddle_results(earthing_ocr, drawing_type="EARTHING_LAYOUT")
+by_tag_e = {r['tag'].upper(): r for r in e_results}
+
+earthing_expected = [
+ ('EBM-01', 'EARTH_BAR_TAG'),
+ ('EB-101', 'EARTH_BAR_TAG'),
+ ('MAIN EARTH BAR', 'EARTH_BAR_TAG'),
+ ('EP-01', 'EARTH_PIT_TAG'),
+ ('EARTH PIT', 'EARTH_PIT_TAG'),
+ ('EARTH CHAMBER', 'EARTH_PIT_TAG'),
+ ('BC-01', 'BOND_CONDUCTOR_TAG'),
+ ('COPPER TAPE', 'BOND_CONDUCTOR_TAG'),
+ ('GS FLAT', 'BOND_CONDUCTOR_TAG'),
+ ('70 SQMM', 'BOND_CONDUCTOR_TAG'),
+]
+
+e_pass = 0
+for tag, exp_cls in earthing_expected:
+ r = by_tag_e.get(tag.upper())
+ got_cls = r['classification'] if r else 'NOT_FOUND'
+ ok = got_cls == exp_cls
+ if ok: e_pass += 1
+ status = 'OK ' if ok else 'FAIL'
+ print(f' [{status}] {tag:20s} -> {got_cls:20s} (expected {exp_cls})')
+
+print(f'\nEarthing Classifier Results: {e_pass}/{len(earthing_expected)} passed')
+
+print("\n=== 2. CLASSIFIER LIGHTING & ELECTRICAL TEST ===")
+l_results = classify_paddle_results(lighting_ocr, drawing_type="ELECTRICAL_LAYOUT")
+by_tag_l = {r['tag'].upper(): r for r in l_results}
+
+lighting_expected = [
+ ('L-01', 'LUMINAIRE_TAG'),
+ ('TL-101', 'LUMINAIRE_TAG'),
+ ('FL-01', 'LUMINAIRE_TAG'),
+ ('FLOODLIGHT-01', 'LUMINAIRE_TAG'),
+ ('WELLGLASS', 'LUMINAIRE_TAG'),
+ ('EMERGENCY LIGHT', 'LUMINAIRE_TAG'),
+ ('LIGHTING PANEL LP', 'PANEL_TAG'),
+ ('DB-01', 'PANEL_TAG'),
+ ('MDB-A', 'PANEL_TAG'),
+]
+
+l_pass = 0
+for tag, exp_cls in lighting_expected:
+ r = by_tag_l.get(tag.upper())
+ got_cls = r['classification'] if r else 'NOT_FOUND'
+ ok = got_cls == exp_cls
+ if ok: l_pass += 1
+ status = 'OK ' if ok else 'FAIL'
+ print(f' [{status}] {tag:25s} -> {got_cls:20s} (expected {exp_cls})')
+
+print(f'\nLighting/Electrical Classifier Results: {l_pass}/{len(lighting_expected)} passed')
+
+print("\n=== 3. COMPILER AGENT EARTHING & LIGHTING TEST ===")
+ca = CompilerAgent()
+
+# Compile earthing items
+compiled_earth = ca._compile_earthing(e_results, [])
+print(f' Compiled {len(compiled_earth)} EarthingItem objects:')
+for e in compiled_earth:
+ print(f' Tag: {e.tag:20s} | Type: {e.component_type:15s} | Material: {e.material} | Size: {e.size}')
+
+# Compile luminaire items
+compiled_lum = ca._compile_luminaires(l_results, [])
+print(f'\n Compiled {len(compiled_lum)} LuminaireItem objects:')
+for lum in compiled_lum:
+ print(f' Tag: {lum.tag:25s} | Type: {lum.fitting_type:20s} | Wattage: {lum.wattage}')
+
+# Compile panel items
+compiled_pan = ca._compile_panels(l_results, [])
+print(f'\n Compiled {len(compiled_pan)} PanelItem objects:')
+for pan in compiled_pan:
+ print(f' Tag: {pan.tag:25s} | Type: {pan.panel_type:20s} | Voltage: {pan.voltage}')
+
+print("\n=== 4. LINE TRACER TOPOLOGICAL RELATIONS TEST ===")
+all_entities = e_results + l_results + [{'classification': 'EQUIPMENT_TAG', 'tag': 'P-101', 'attributes': {}}]
+tracer_res = trace_lines_and_connections(None, all_entities, [], drawing_type="EARTHING_LAYOUT")
+
+relations = tracer_res['relations']
+print(f' Generated {len(relations)} topological relations:')
+for rel in relations:
+ print(f' {rel["source_tag"]:25s} --[{rel["rel_type"]}]--> {rel["target_tag"]}')
+
+total_tests = len(earthing_expected) + len(lighting_expected)
+total_passed = e_pass + l_pass
+print(f'\n=== FINAL SCORE: {total_passed}/{total_tests} tests passed ===')