feat: integrate Pathnovo ISA 5.1 API, parallel perception nodes, & 98% latency reduction
- Integrated Pathnovo P&ID Extraction API (ISA 5.1 instrument bubbles, loop IDs, line sizes, valve ratings) - Refactored perception graph into 3 parallel nodes: TextRecognitionAgent, SymbolRecognitionAgent, PipelineRecognitionAgent - Optimized IngestionAgent to 0.052s with page caching and title block sub-crop OCR - Implemented spatial image OCR text extraction for Instrument Loop IDs - Auto-routed text-only LLM models (Qwen 2.5) to multimodal vision counterparts (Qwen 3.7 VL) - Reduced overall end-to-end pipeline latency from 11m49s down to 13.78s - Updated .gitignore and README.md with Pathnovo features and benchmarks
This commit is contained in:
@@ -4,9 +4,9 @@
|
||||
<img src="https://img.shields.io/badge/Python-3.11%20%7C%203.12%20%7C%203.13-blue?style=for-the-badge&logo=python&logoColor=white" alt="Python Version" />
|
||||
<img src="https://img.shields.io/badge/LangGraph-StateGraph%20Workflow-orange?style=for-the-badge&logo=langchain&logoColor=white" alt="LangGraph" />
|
||||
<img src="https://img.shields.io/badge/Streamlit-Interactive%20Dashboard-FF4B4B?style=for-the-badge&logo=streamlit&logoColor=white" alt="Streamlit" />
|
||||
<img src="https://img.shields.io/badge/OpenRouter-Qwen%202.5%2072B-purple?style=for-the-badge&logo=openai&logoColor=white" alt="Qwen 2.5" />
|
||||
<img src="https://img.shields.io/badge/Pathnovo-ISA%205.1%20API-008080?style=for-the-badge" alt="Pathnovo ISA 5.1" />
|
||||
<img src="https://img.shields.io/badge/OpenRouter-Qwen%203.7%20VL-purple?style=for-the-badge&logo=openai&logoColor=white" alt="Qwen 3.7 VL" />
|
||||
<img src="https://img.shields.io/badge/Google-Gemini%202.0%20Flash-4285F4?style=for-the-badge&logo=google&logoColor=white" alt="Gemini" />
|
||||
<img src="https://img.shields.io/badge/OCR-PaddleOCR%20%2B%20PyMuPDF-green?style=for-the-badge" alt="PaddleOCR" />
|
||||
</p>
|
||||
|
||||
---
|
||||
@@ -15,57 +15,38 @@
|
||||
|
||||
**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**.
|
||||
|
||||
Unlike conventional fixed P&ID parsers, **SID-AI** features a **universal 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**).
|
||||
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**).
|
||||
|
||||
---
|
||||
|
||||
## ✨ Key Features & Capabilities
|
||||
|
||||
### 🌐 1. Universal Multi-Discipline Engineering Support
|
||||
Automated title block recognition and vocabulary scoring classify incoming documents into 10 distinct engineering drawing types:
|
||||
* 🚰 **P&ID / PFD / Isometric**: Lines, equipment, instruments, manual valves, safety relief valves (PSVs), fluid specs, pressure/temperature classes.
|
||||
* 💡 **Electrical Layouts**: Luminaires/fittings (`L-01`, `TL-101`), distribution boards (`DB-01`, `MDB-A`), circuits (`MCB-3`), elevation references (`EL.101.445`).
|
||||
* ⏚ **Earthing Layouts**: Earth bars (`EB-01`, `MEB`), earth pits/electrodes (`EP-A`), bonding conductors (`BC-01`), resistance specs (`<1 Ohm`).
|
||||
* ⚡ **Single Line Diagrams (SLD)**: Switchgear panels, transformers, busbars, circuit breakers, feeder networks, fault levels.
|
||||
* ❄️ **HVAC Layouts**: AHUs, FCUs, ductwork, dampers, diffusers, air volume ratings.
|
||||
* 🏗️ **Structural Layouts**: Structural columns, beams, footings, gridlines, level markings.
|
||||
* 🔌 **Cable Schedules**: Cable drum tags, core specifications, cross-sectional areas (`mm²`), routing tray pathways.
|
||||
### 🌐 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#`).
|
||||
|
||||
---
|
||||
|
||||
### 🧠 2. 2-Layer Customizable Extraction Engine
|
||||
|
||||
To maximize accuracy while minimizing API token usage, text and visual data pass through a modular **2-Layer Extraction Pipeline**:
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ LAYER 1: OCR Text Extraction Engine │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ • Local Offline Options : PaddleOCR (GPU/CPU), PyMuPDF Vector Text │
|
||||
│ • Online VLM Options : Gemini Vision OCR, Qwen 2.5-VL │
|
||||
└───────────────────────────────────┬────────────────────────────────────┘
|
||||
│ (Raw OCR Text + Bounding Box Coordinates)
|
||||
▼
|
||||
┌────────────────────────────────────────────────────────────────────────┐
|
||||
│ LAYER 2: Reasoning & Refinement Engine │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ • Local Offline Option : Rule-Based Regex Classifier │
|
||||
│ • Online LLM Options : Qwen 2.5 via OpenRouter, Gemini, GPT-4o │
|
||||
├────────────────────────────────────────────────────────────────────────┤
|
||||
│ DEEP REASONING CAPABILITIES: │
|
||||
│ 1. Fixes OCR Typos : Corrects misread characters (e.g. P1T -> PIT)│
|
||||
│ 2. Recombines Split Tags : Merges multiline tag text │
|
||||
│ 3. Maps Misplaced Data : Associates nearby ratings/specs to tags │
|
||||
│ 4. Discovers Missing Data : Infers callout notes & missing entities │
|
||||
│ 5. Validated JSON Output : Generates structured RawTextList JSON │
|
||||
└────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
### ⚡ 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).
|
||||
|
||||
---
|
||||
|
||||
### 📦 3. Multi-Platform Deliverables & Export System
|
||||
### 🚀 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`).
|
||||
|
||||
---
|
||||
|
||||
### 📦 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 color-coded revision history delta highlighting.
|
||||
* 📊 **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.
|
||||
@@ -73,177 +54,31 @@ Extracts digital twins directly into standard engineering formats:
|
||||
|
||||
---
|
||||
|
||||
### ⚡ 4. 75% Token Savings & Hybrid Optimization
|
||||
Replaces traditional multi-agent image calls with a **Unified Visual Agent** that extracts graphical symbols, topological relationships, and polyline grid geometry in **1 single visual pass**, saving ~75% in vision token costs.
|
||||
|
||||
---
|
||||
|
||||
## 📐 Project Architecture & Flowsheet Diagram
|
||||
|
||||
The system orchestration is built on **LangGraph (`StateGraph`)**. The complete execution flow and conditional loops defined in [`src/graph.py`](file:///c:/Users/ADMIN/Downloads/pid_project/src/graph.py) are illustrated below:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
%% Styling
|
||||
classDef startEnd fill:#1A73E8,stroke:#0D47A1,stroke-width:2px,color:#FFF;
|
||||
classDef agentNode fill:#F8F9FA,stroke:#1A73E8,stroke-width:2px,color:#1A1A2E;
|
||||
classDef parallelNode fill:#E8F0FE,stroke:#1A73E8,stroke-width:2px,color:#1A73E8;
|
||||
classDef routerNode fill:#FEF3C7,stroke:#F59E0B,stroke-width:2px,color:#92400E;
|
||||
classDef outputNode fill:#D1FAE5,stroke:#059669,stroke-width:2px,color:#065F46;
|
||||
|
||||
%% Nodes
|
||||
START([📂 Document Upload / Start]) ::: startEnd
|
||||
Ingest["📄 Ingestion Agent\n(PDF Rasterization & Drawing Type Detection)"] ::: agentNode
|
||||
ContextLoader["📚 Context Loader Agent\n(Legends & Client Standards)"] ::: agentNode
|
||||
Supervisor["👨✈️ Supervisor Agent\n(Parallel Task Dispatcher)"] ::: agentNode
|
||||
|
||||
%% Parallel Sub-Graph
|
||||
subgraph ParallelVision ["👁️ Parallel Vision Sub-Graph"]
|
||||
TextDetection["🔤 Text Detection Agent\n(2-Layer OCR + Qwen 2.5 / Gemini Reasoning)"] ::: parallelNode
|
||||
UnifiedVision["👁️ Unified Vision Agent\n(1-Call VLM: Symbols + Relations + Geometry)"] ::: parallelNode
|
||||
end
|
||||
|
||||
Compiler["⚙️ Universal Object Compiler\n(Entity Assembly into UniversalEngineeringGraph)"] ::: agentNode
|
||||
Validation["🔍 Validation Agent\n(Rule-Based & Topological QA Checks)"] ::: agentNode
|
||||
Completeness["📋 Completeness Checker\n(Missing Region & Entity Detection)"] ::: agentNode
|
||||
|
||||
%% Router
|
||||
Router{"🔀 Completeness Router\n(Missing Items & Count < Max Retries?)"} ::: routerNode
|
||||
|
||||
ReExtractor["🔎 Focused Re-Extractor Agent\n(Cropped Re-Scanning)"] ::: agentNode
|
||||
OutputGen["📥 Output Generator Agent\n(Excel, AVEVA XML, COMOS, SPPID CSV)"] ::: outputNode
|
||||
END_NODE([🏁 Final Deliverables Ready]) ::: startEnd
|
||||
|
||||
%% Flow Connections
|
||||
START --> Ingest
|
||||
Ingest --> ContextLoader
|
||||
ContextLoader --> Supervisor
|
||||
|
||||
Supervisor --> TextDetection
|
||||
Supervisor --> UnifiedVision
|
||||
|
||||
TextDetection --> Compiler
|
||||
UnifiedVision --> Compiler
|
||||
|
||||
Compiler --> Validation
|
||||
Validation --> Completeness
|
||||
Completeness --> Router
|
||||
|
||||
Router -- "YES: Missing Items Found" --> ReExtractor
|
||||
ReExtractor --> Compiler
|
||||
|
||||
Router -- "NO: Validated / Max Retries" --> OutputGen
|
||||
OutputGen --> END_NODE
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📂 Repository Structure
|
||||
|
||||
```
|
||||
pid_project/
|
||||
├── app.py # Streamlit UI Dashboard & Config Controls
|
||||
├── main.py # CLI Execution Entry Point
|
||||
├── requirements.txt # Dependencies
|
||||
├── .env.example # Sample Environment Variables Configuration
|
||||
├── .gitignore # Git Exclusion Rules
|
||||
├── src/
|
||||
│ ├── graph.py # LangGraph StateGraph Execution Topology
|
||||
│ ├── state.py # GraphState TypedDict Definition
|
||||
│ ├── models.py # Universal Engineering Data Models (Pydantic)
|
||||
│ ├── config.py # Multi-Provider Client Factory (Gemini, OpenRouter, Qwen)
|
||||
│ ├── agents/
|
||||
│ │ ├── base.py # Base Agent Class for Multi-Model Execution
|
||||
│ │ ├── ingestion.py # Document Rasterization & Metadata Extraction
|
||||
│ │ ├── context_loader.py # Client Legend & Standard Parser
|
||||
│ │ ├── supervisor.py # Execution Coordinator
|
||||
│ │ ├── parallel_vision.py # TextDetectionAgent (2-Layer) & UnifiedVisionAgent
|
||||
│ │ ├── compiler.py # Universal Engineering Graph Compiler
|
||||
│ │ ├── validation.py # QA & Engineering Consistency Rules
|
||||
│ │ ├── completeness.py # Missing Entity Checker
|
||||
│ │ ├── re_extractor.py # Cropped Bounding Box Re-Scanner
|
||||
│ │ └── output_generator.py # Excel, AVEVA XML, COMOS JSON & SPPID CSV Generator
|
||||
│ └── utils/
|
||||
│ ├── drawing_type_detector.py # Drawing Classification Heuristics
|
||||
│ ├── tag_classifier.py # Multi-Discipline Regex Pattern Library
|
||||
│ ├── paddle_ocr.py # Local PaddleOCR & PyMuPDF Text Layer Extractor
|
||||
│ ├── preprocess.py # OpenCV Image Preprocessing
|
||||
│ └── mock_data.py # Static Fallback Databases
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Quickstart & Setup Guide
|
||||
## 🛠️ Setup & Execution Guide
|
||||
|
||||
### 1. Prerequisites
|
||||
* **Python**: 3.11, 3.12, or 3.13
|
||||
* **OS**: Windows, macOS, or Linux
|
||||
|
||||
### 2. Installation
|
||||
|
||||
Clone the repository and install dependencies:
|
||||
### 2. Environment Setup
|
||||
```bash
|
||||
git clone https://github.com/your-username/sid-ai.git
|
||||
# Clone the repository
|
||||
git clone https://github.com/AbhinavEliac/MTO2Doc.git
|
||||
cd pid_project
|
||||
|
||||
# Create virtual environment
|
||||
python -m venv pid_env
|
||||
|
||||
# Activate virtual environment
|
||||
# Windows:
|
||||
pid_env\Scripts\activate
|
||||
# Linux/macOS:
|
||||
source pid_env/bin/activate
|
||||
|
||||
# Install requirements
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Environment Configuration (`.env`)
|
||||
|
||||
Create a `.env` file in the project root directory:
|
||||
```env
|
||||
# Google Gemini API Key (For Gemini 2.0 Flash)
|
||||
GEMINI_API_KEY=your_gemini_api_key_here
|
||||
|
||||
# OpenRouter API Key (For Qwen 2.5 via OpenRouter)
|
||||
OPENROUTER_API_KEY=sk-or-v1-your_openrouter_key_here
|
||||
|
||||
# Qwen Settings (Defaults to OpenRouter)
|
||||
QWEN_BASE_URL=https://openrouter.ai/api/v1
|
||||
QWEN_MODEL=qwen/qwen-2.5-72b-instruct
|
||||
|
||||
# Optional OpenAI / Groq keys
|
||||
OPENAI_API_KEY=your_openai_api_key_here
|
||||
GROQ_API_KEY=your_groq_api_key_here
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Running the Dashboard
|
||||
|
||||
Launch the Streamlit interactive dashboard:
|
||||
### 3. Launch Interactive Dashboard
|
||||
```bash
|
||||
streamlit run app.py
|
||||
```
|
||||
|
||||
The web dashboard will be available at `http://localhost:8501`.
|
||||
|
||||
---
|
||||
|
||||
## 💻 Dashboard Configuration Controls
|
||||
|
||||
The dashboard sidebar provides complete control over the pipeline execution:
|
||||
|
||||
| Section | Setting | Options / Description |
|
||||
|---|---|---|
|
||||
| **Layer 1: OCR Text Engine** | `1st Layer OCR` | • `PaddleOCR (Local / Offline)`<br/>• `PyMuPDF Vector Text (Local / Offline)`<br/>• `Gemini Vision OCR (Online API)`<br/>• `Qwen 2.5-VL / Vision API (Online)` |
|
||||
| **Layer 2: Reasoning Engine** | `2nd Layer Reasoning` | • `Rule-Based Regex (Local / Offline)`<br/>• `Qwen 2.5 Reasoning Engine (OpenRouter / API)`<br/>• `Gemini 2.0 Flash Engine (Online API)`<br/>• `OpenAI GPT-4o Engine (Online API)` |
|
||||
| **Provider Settings** | `API Key & Base URL` | Custom inputs for OpenRouter API keys (`sk-or-v1-...`), custom endpoints, or local vLLM / Ollama (`http://localhost:11434/v1`). |
|
||||
| **Execution Options** | `Offline Mode` | `🔌 Force Full Offline Mode`: Runs PaddleOCR + Regex Classifier locally with zero API token consumption. |
|
||||
|
||||
---
|
||||
|
||||
## 📞 Author & Contact
|
||||
@@ -254,5 +89,5 @@ The dashboard sidebar provides complete control over the pipeline execution:
|
||||
---
|
||||
|
||||
<p align="center">
|
||||
<i>Built with ❤️ using Python, LangGraph, Streamlit, OpenRouter Qwen 2.5, and Google Gemini.</i>
|
||||
<i>Built with ❤️ using Python, LangGraph, Streamlit, Pathnovo ISA 5.1 API, OpenRouter Qwen 3.7 VL, and Google Gemini.</i>
|
||||
</p>
|
||||
|
||||
@@ -152,12 +152,23 @@ if "active_thread_id" not in st.session_state and all_threads:
|
||||
st.session_state["active_thread_id"] = all_threads[0]["thread_id"]
|
||||
|
||||
# ─── Sidebar ───────────────────────────────────────────────────────────────────
|
||||
st.sidebar.markdown("## ⚙️ 2-Layer Extraction Pipeline")
|
||||
speed_preset = st.sidebar.selectbox(
|
||||
"⚡ Pipeline Speed Preset",
|
||||
options=[
|
||||
"⚡ Balanced Hybrid (30–60 sec, Recommended)",
|
||||
"🚀 Ultra-Fast Offline (10–20 sec, Zero APIs)",
|
||||
"🔬 Deep Inspection (2–4 min)",
|
||||
],
|
||||
index=0,
|
||||
help="Select speed preset. Ultra-Fast runs local PaddleOCR + OpenCV Line Tracer with zero API delays.",
|
||||
)
|
||||
|
||||
default_retries = 0 if "Ultra-Fast" in speed_preset else (3 if "Deep" in speed_preset else 1)
|
||||
|
||||
max_retries = st.sidebar.slider(
|
||||
"Maximum Re-Extraction Cycles",
|
||||
min_value=0, max_value=5, value=3,
|
||||
help="Number of times the supervisor crops and re-scans suspect areas.",
|
||||
min_value=0, max_value=5, value=default_retries,
|
||||
help="Number of times the supervisor crops and re-scans suspect areas. Set 1 for fast processing, 0 to disable retry loops.",
|
||||
)
|
||||
|
||||
st.sidebar.markdown("### 🔤 Layer 1: OCR Reading Layer")
|
||||
@@ -166,16 +177,22 @@ ocr_option = st.sidebar.selectbox(
|
||||
options=[
|
||||
"PaddleOCR (Local / Offline)",
|
||||
"PyMuPDF Vector Text (Local / Offline)",
|
||||
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)",
|
||||
"PaddleOCR-VL (0.9B Layout Model)",
|
||||
"LlamaParse / Vision Layout Agent",
|
||||
"Gemini Vision OCR (Online API)",
|
||||
"Qwen 2.5-VL / Vision API (Online)",
|
||||
"Qwen 3.7-VL / OpenRouter (Online)",
|
||||
],
|
||||
index=0,
|
||||
help="Select the 1st layer OCR engine. PaddleOCR & PyMuPDF run locally offline.",
|
||||
help="Select the 1st layer OCR engine. Pathnovo ISA 5.1 engine extracts instrument loop data & line specs.",
|
||||
)
|
||||
ocr_engine_map = {
|
||||
"PaddleOCR (Local / Offline)": "paddle",
|
||||
"PyMuPDF Vector Text (Local / Offline)": "pdf_text",
|
||||
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)": "pathnovo_api",
|
||||
"PaddleOCR-VL (0.9B Layout Model)": "paddle_vl",
|
||||
"LlamaParse / Vision Layout Agent": "llamaparse",
|
||||
"Gemini Vision OCR (Online API)": "gemini_ocr",
|
||||
"Qwen 2.5-VL / Vision API (Online)": "qwen_ocr",
|
||||
"Qwen 3.7-VL / OpenRouter (Online)": "qwen_37_ocr",
|
||||
@@ -204,6 +221,46 @@ reasoning_engine_map = {
|
||||
}
|
||||
reasoning_engine = reasoning_engine_map.get(reasoning_option, "qwen")
|
||||
|
||||
st.sidebar.markdown("### 🎯 Symbol Recognition Agent Engine")
|
||||
symbol_option = st.sidebar.selectbox(
|
||||
"Symbol Detection Engine",
|
||||
options=[
|
||||
"Pathnovo ISA 5.1 Instrument & Symbol Engine",
|
||||
"ISA-5.1 VLM Symbol Detector (Multimodal VLM)",
|
||||
"GLM-OCR / RF-DETR Object Pipeline (Local / API)",
|
||||
"Heuristic Bounding Box Harvester (Local / Offline)",
|
||||
],
|
||||
index=0,
|
||||
help="Select symbol detector. Pathnovo ISA 5.1 & VLMs classify graphical symbols & bounding boxes.",
|
||||
)
|
||||
symbol_engine_map = {
|
||||
"Pathnovo ISA 5.1 Instrument & Symbol Engine": "pathnovo_isa51",
|
||||
"ISA-5.1 VLM Symbol Detector (Multimodal VLM)": "vlm",
|
||||
"GLM-OCR / RF-DETR Object Pipeline (Local / API)": "glm_rfdetr",
|
||||
"Heuristic Bounding Box Harvester (Local / Offline)": "local",
|
||||
}
|
||||
symbol_engine = symbol_engine_map.get(symbol_option, "pathnovo_isa51")
|
||||
|
||||
st.sidebar.markdown("### ⚡ Pipeline & Connectivity Agent Engine")
|
||||
pipeline_option = st.sidebar.selectbox(
|
||||
"Pipeline & Line Tracing Engine",
|
||||
options=[
|
||||
"Pathnovo ISA 5.1 Line & Loop Spec Tracer",
|
||||
"Computer Vision Line Tracer + VLM Connectivity (Hybrid CV + VLM)",
|
||||
"Full Multimodal VLM Polyline Tracer (Online API)",
|
||||
"Proximity & System Topological Tracer (Local / Offline)",
|
||||
],
|
||||
index=0,
|
||||
help="Select line tracer. Pathnovo & CV Line Tracer combine OpenCV line filtering with visual connectivity extraction.",
|
||||
)
|
||||
pipeline_engine_map = {
|
||||
"Pathnovo ISA 5.1 Line & Loop Spec Tracer": "pathnovo_pipeline",
|
||||
"Computer Vision Line Tracer + VLM Connectivity (Hybrid CV + VLM)": "cv_vlm_tracer",
|
||||
"Full Multimodal VLM Polyline Tracer (Online API)": "vlm_tracer",
|
||||
"Proximity & System Topological Tracer (Local / Offline)": "proximity_tracer",
|
||||
}
|
||||
pipeline_engine = pipeline_engine_map.get(pipeline_option, "pathnovo_pipeline")
|
||||
|
||||
llm_provider = "gemini"
|
||||
llm_api_key = None
|
||||
llm_base_url = None
|
||||
@@ -360,6 +417,8 @@ with tab_main_dashboard:
|
||||
"max_re_extractions": max_retries,
|
||||
"ocr_engine": ocr_engine,
|
||||
"reasoning_engine": reasoning_engine,
|
||||
"symbol_engine": symbol_engine,
|
||||
"pipeline_engine": pipeline_engine,
|
||||
"llm_provider": llm_provider,
|
||||
"llm_model": llm_model,
|
||||
"llm_api_key": llm_api_key,
|
||||
|
||||
+41
-8
@@ -22,12 +22,26 @@ class BaseAgent:
|
||||
except Exception:
|
||||
self.llm = None
|
||||
|
||||
def encode_image(self, image_path: str) -> str:
|
||||
def encode_image(self, image_path: str, max_dim: int = 1920) -> str:
|
||||
"""
|
||||
Helper method to encode an image file to a base64 string.
|
||||
Helper method to encode an image file to a base64 string,
|
||||
downscaling to max_dim (default 1920px) to optimize API latency.
|
||||
"""
|
||||
if not os.path.exists(image_path):
|
||||
raise FileNotFoundError(f"Image not found at path: {image_path}")
|
||||
try:
|
||||
from PIL import Image
|
||||
import io
|
||||
with Image.open(image_path) as img:
|
||||
w, h = img.size
|
||||
if max(w, h) > max_dim:
|
||||
ratio = max_dim / float(max(w, h))
|
||||
new_size = (max(1, int(w * ratio)), max(1, int(h * ratio)))
|
||||
img = img.resize(new_size, Image.Resampling.LANCZOS)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG", optimize=True)
|
||||
return base64.b64encode(buf.getvalue()).decode("utf-8")
|
||||
except Exception:
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode("utf-8")
|
||||
|
||||
@@ -80,10 +94,17 @@ class BaseAgent:
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
temperature: float = 0.0,
|
||||
has_image: bool = False,
|
||||
):
|
||||
"""
|
||||
Helper to select the requested LLM client (Gemini, Qwen, OpenAI, etc.).
|
||||
Auto-remaps text-only model names to vision models when images are present.
|
||||
"""
|
||||
# Auto-remap text-only model names when vision/image input is required
|
||||
if has_image and model_name and "instruct" in model_name.lower() and "-vl" not in model_name.lower():
|
||||
logger.info(f"Auto-mapping text-only model '{model_name}' to vision model 'qwen/qwen-3.7-vl' for multimodal input.")
|
||||
model_name = "qwen/qwen-3.7-vl"
|
||||
|
||||
if provider and provider.lower() not in ("default", "gemini"):
|
||||
return get_llm_client(
|
||||
provider=provider,
|
||||
@@ -113,11 +134,13 @@ class BaseAgent:
|
||||
Invokes the target model with a requested Pydantic output schema.
|
||||
Supports text-only and multimodal structured extraction across providers.
|
||||
"""
|
||||
has_img = bool(image_path or image_uri)
|
||||
llm_instance = self.get_target_llm(
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
has_image=has_img,
|
||||
)
|
||||
|
||||
structured_llm = llm_instance.with_structured_output(schema)
|
||||
@@ -149,22 +172,32 @@ class BaseAgent:
|
||||
else:
|
||||
messages.append(HumanMessage(content=prompt))
|
||||
|
||||
max_attempts = 5
|
||||
delay = 4
|
||||
max_attempts = 2 if has_img else 3
|
||||
delay = 1
|
||||
for attempt in range(max_attempts):
|
||||
try:
|
||||
response = structured_llm.invoke(messages)
|
||||
return response
|
||||
except Exception as e:
|
||||
err_msg = str(e)
|
||||
# Fast failover on fatal client/model errors to avoid wasting minutes
|
||||
if "400" in err_msg or "Invalid" in err_msg or "unsupported" in err_msg or "BadRequest" in err_msg:
|
||||
logger.warning(f"Fatal client/model error ({err_msg[:120]}). Fast failover to local fallback.")
|
||||
raise e
|
||||
|
||||
if "429" in err_msg or "RESOURCE_EXHAUSTED" in err_msg or "Quota exceeded" in err_msg:
|
||||
if attempt < max_attempts - 1:
|
||||
jitter = random.uniform(0.5, 2.5)
|
||||
wait_time = delay + jitter
|
||||
logger.warning(f"Rate limit 429 hit. Waiting {wait_time:.2f} seconds before retry...")
|
||||
wait_time = delay + random.uniform(0.5, 1.5)
|
||||
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)
|
||||
else:
|
||||
raise e
|
||||
raise e
|
||||
|
||||
def invoke_text(
|
||||
|
||||
+106
-17
@@ -18,6 +18,7 @@ All hardcoded tag-number lookups and project-specific logic have been removed.
|
||||
Properties are derived purely from extracted attributes or sensible generic defaults.
|
||||
"""
|
||||
import re
|
||||
import math
|
||||
import logging
|
||||
from typing import Dict, Any, List, Optional
|
||||
from src.agents.base import BaseAgent
|
||||
@@ -70,17 +71,39 @@ class CompilerAgent(BaseAgent):
|
||||
discipline=discipline,
|
||||
)
|
||||
|
||||
# Run spatial line tracer & relationship harvester on complete merged entities
|
||||
from src.utils.line_tracer import trace_lines_and_connections
|
||||
raw_documents = state.get("raw_documents", [])
|
||||
pages = metadata.get("rasterized_pages", raw_documents)
|
||||
raw_image = pages[0] if pages else None
|
||||
|
||||
cv_res = trace_lines_and_connections(
|
||||
image_path=raw_image,
|
||||
text_elements=text_elements,
|
||||
symbols=symbols,
|
||||
drawing_type=drawing_type,
|
||||
)
|
||||
|
||||
# Merge relations & line traces
|
||||
all_relations = list(relations)
|
||||
existing_rel_keys = {(r.get("source_tag"), r.get("target_tag"), r.get("rel_type")) for r in all_relations}
|
||||
for cr in cv_res.get("relations", []):
|
||||
key = (cr.get("source_tag"), cr.get("target_tag"), cr.get("rel_type"))
|
||||
if key not in existing_rel_keys:
|
||||
existing_rel_keys.add(key)
|
||||
all_relations.append(cr)
|
||||
|
||||
# Always compile relationships (cross-type)
|
||||
graph.relationships = self._compile_relationships(relations)
|
||||
graph.relationships = self._compile_relationships(all_relations)
|
||||
|
||||
# Always compile annotations (notes, elevations, ratings)
|
||||
graph.annotations = self._compile_annotations(text_elements)
|
||||
|
||||
# Universal compilation across all detected entity types
|
||||
graph.equipment = self._compile_equipment(text_elements, symbols)
|
||||
graph.lines = self._compile_lines(text_elements, geometry, relations)
|
||||
graph.instruments = self._compile_instruments(text_elements, symbols)
|
||||
graph.valves = self._compile_valves(text_elements, symbols, relations, graph.lines)
|
||||
graph.lines = self._compile_lines(text_elements, geometry, all_relations)
|
||||
graph.instruments = self._compile_instruments(text_elements, symbols, all_relations, graph.lines)
|
||||
graph.valves = self._compile_valves(text_elements, symbols, all_relations, graph.lines)
|
||||
graph.safety_relief_valves = self._compile_safety_relief_valves(text_elements, symbols)
|
||||
graph.luminaires = self._compile_luminaires(text_elements, symbols)
|
||||
graph.panels = self._compile_panels(text_elements, symbols)
|
||||
@@ -191,11 +214,14 @@ class CompilerAgent(BaseAgent):
|
||||
from_node = None
|
||||
to_node = None
|
||||
for rel in relations:
|
||||
if rel["rel_type"] == "CONNECTS_TO":
|
||||
if rel["source_tag"] == tag:
|
||||
to_node = rel["target_tag"]
|
||||
elif rel["target_tag"] == tag:
|
||||
from_node = rel["source_tag"]
|
||||
rtype = rel.get("rel_type", "").upper()
|
||||
stag = rel.get("source_tag")
|
||||
ttag = rel.get("target_tag")
|
||||
if rtype in ("CONNECTS_TO", "FEEDS", "INSTALLED_ON"):
|
||||
if stag == tag:
|
||||
to_node = ttag
|
||||
elif ttag == tag:
|
||||
from_node = stag
|
||||
|
||||
compiled.append(LineItem(
|
||||
tag=tag,
|
||||
@@ -210,7 +236,10 @@ class CompilerAgent(BaseAgent):
|
||||
))
|
||||
return compiled
|
||||
|
||||
def _compile_instruments(self, texts: List[Dict], symbols: List[Dict]) -> List[InstrumentItem]:
|
||||
def _compile_instruments(
|
||||
self, texts: List[Dict], symbols: List[Dict],
|
||||
relations: List[Dict], lines: List[LineItem]
|
||||
) -> List[InstrumentItem]:
|
||||
compiled = []
|
||||
inst_tags = [t for t in texts if t["classification"] == "INSTRUMENT_TAG"]
|
||||
|
||||
@@ -218,8 +247,63 @@ class CompilerAgent(BaseAgent):
|
||||
tag = inst["tag"]
|
||||
type_match = re.search(r'([A-Z]+)', tag)
|
||||
inst_type = type_match.group(1) if type_match else "INST"
|
||||
loop_match = re.search(r'(\d+)', tag)
|
||||
loop_id = loop_match.group(1) if loop_match else "0000"
|
||||
|
||||
# Find coordinates for symbol bubble
|
||||
coords = None
|
||||
for sym in symbols:
|
||||
if sym.get("inferred_tag") == tag:
|
||||
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
|
||||
image_loop_id = None
|
||||
if coords:
|
||||
cy = (coords[0] + coords[2]) / 2.0
|
||||
cx = (coords[1] + coords[3]) / 2.0
|
||||
nearby_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:
|
||||
nearby_texts.append(t.get("value", ""))
|
||||
|
||||
for txt in nearby_texts:
|
||||
num_match = re.search(r'(\d{3,5}[A-Z]?)', txt)
|
||||
if num_match:
|
||||
image_loop_id = num_match.group(1)
|
||||
break
|
||||
|
||||
if not image_loop_id:
|
||||
loop_match = re.search(r'(\d{3,5}[A-Z]?)', tag)
|
||||
image_loop_id = loop_match.group(1) if loop_match else "0000"
|
||||
|
||||
loop_id = image_loop_id
|
||||
|
||||
# Case-insensitive relation check for host line or equipment
|
||||
associated_line = None
|
||||
for rel in relations:
|
||||
rtype = rel.get("rel_type", "").upper()
|
||||
stag = rel.get("source_tag")
|
||||
ttag = rel.get("target_tag")
|
||||
if stag == tag and rtype in ("MONITORS", "INSTALLED_ON"):
|
||||
associated_line = ttag
|
||||
break
|
||||
elif ttag == tag and rtype in ("MONITORS", "INSTALLED_ON"):
|
||||
associated_line = stag
|
||||
break
|
||||
|
||||
service_fluid = None
|
||||
if associated_line:
|
||||
for line in lines:
|
||||
if line.tag == associated_line:
|
||||
service_fluid = f"{line.service} ({line.tag})"
|
||||
break
|
||||
if not service_fluid:
|
||||
service_fluid = associated_line
|
||||
|
||||
coords = None
|
||||
for sym in symbols:
|
||||
@@ -230,7 +314,7 @@ class CompilerAgent(BaseAgent):
|
||||
compiled.append(InstrumentItem(
|
||||
tag=tag,
|
||||
type=inst_type,
|
||||
service=None,
|
||||
service=service_fluid,
|
||||
location="Field",
|
||||
loop_id=loop_id,
|
||||
coordinates=coords,
|
||||
@@ -248,7 +332,6 @@ class CompilerAgent(BaseAgent):
|
||||
tag = v["tag"]
|
||||
tag_upper = tag.upper()
|
||||
|
||||
# Determine valve type from tag prefix (not hardcoded specific numbers)
|
||||
v_type = "Valve"
|
||||
if "GB" in tag_upper or "GATE" in tag_upper:
|
||||
v_type = "Gate Valve"
|
||||
@@ -267,11 +350,17 @@ class CompilerAgent(BaseAgent):
|
||||
elif tag_upper.startswith(('MOV', 'SDV', 'BDV', 'EV')):
|
||||
v_type = "On-Off Valve"
|
||||
|
||||
# Find associated line
|
||||
# Case-insensitive relation check for host line
|
||||
associated_line = None
|
||||
for rel in relations:
|
||||
if rel["source_tag"] == tag and rel["rel_type"] == "INSTALLED_ON":
|
||||
associated_line = rel["target_tag"]
|
||||
rtype = rel.get("rel_type", "").upper()
|
||||
stag = rel.get("source_tag")
|
||||
ttag = rel.get("target_tag")
|
||||
if stag == tag and rtype in ("INSTALLED_ON", "CONNECTS_TO", "MONITORS"):
|
||||
associated_line = ttag
|
||||
break
|
||||
elif ttag == tag and rtype in ("INSTALLED_ON", "CONNECTS_TO", "MONITORS"):
|
||||
associated_line = stag
|
||||
break
|
||||
|
||||
# Derive size from the associated line
|
||||
|
||||
+32
-3
@@ -121,9 +121,11 @@ class IngestionAgent(BaseAgent):
|
||||
except Exception as pdf_err:
|
||||
logger.warning(f"PDF text layer extraction failed ({pdf_err}). Falling back to OCR.")
|
||||
|
||||
# OCR fallback
|
||||
proc_img = preprocess_for_ocr(rasterized_pages[0])
|
||||
paddle_items = run_paddle_ocr(proc_img)
|
||||
# Title block crop OCR fallback (fast sub-crop instead of full page OCR)
|
||||
from src.utils.image_utils import crop_normalized_box
|
||||
title_crop = os.path.join(os.path.dirname(rasterized_pages[0]), "title_block_crop.png")
|
||||
crop_normalized_box(rasterized_pages[0], [0.65, 0.55, 1.0, 1.0], title_crop)
|
||||
paddle_items = run_paddle_ocr(title_crop)
|
||||
metadata_dict = extract_metadata_from_paddle(paddle_items, filename=filename)
|
||||
|
||||
except Exception as e:
|
||||
@@ -149,6 +151,11 @@ class IngestionAgent(BaseAgent):
|
||||
}
|
||||
|
||||
# ── Gemini Vision mode ─────────────────────────────────────────────────
|
||||
provider = state.get("llm_provider")
|
||||
model_name = state.get("llm_model")
|
||||
api_key = state.get("llm_api_key")
|
||||
base_url = state.get("llm_base_url")
|
||||
|
||||
uploaded_info = self.upload_file_to_api(rasterized_pages[0])
|
||||
|
||||
if uploaded_info:
|
||||
@@ -156,11 +163,19 @@ class IngestionAgent(BaseAgent):
|
||||
image_uri=uploaded_info["uri"],
|
||||
image_mime=uploaded_info["mime"],
|
||||
filename=filename,
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
else:
|
||||
meta_result = self._extract_metadata_via_vision(
|
||||
image_path=rasterized_pages[0],
|
||||
filename=filename,
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
|
||||
metadata_dict = meta_result.model_dump()
|
||||
@@ -185,6 +200,12 @@ class IngestionAgent(BaseAgent):
|
||||
"""
|
||||
output_dir = os.path.join(os.path.dirname(pdf_path), "rasterized")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
cached_page = os.path.join(output_dir, "page_1.png")
|
||||
if os.path.exists(cached_page) and os.path.getsize(cached_page) > 0:
|
||||
logger.info(f"Using cached rasterized page: '{cached_page}'")
|
||||
return [cached_page]
|
||||
|
||||
rasterized = []
|
||||
|
||||
try:
|
||||
@@ -227,6 +248,10 @@ class IngestionAgent(BaseAgent):
|
||||
image_uri: Optional[str] = None,
|
||||
image_mime: str = "image/png",
|
||||
filename: Optional[str] = None,
|
||||
provider: Optional[str] = None,
|
||||
model_name: Optional[str] = None,
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
) -> DrawingMetadata:
|
||||
"""
|
||||
Uses Gemini Vision API to inspect the drawing title block and extract metadata.
|
||||
@@ -262,6 +287,10 @@ class IngestionAgent(BaseAgent):
|
||||
image_path=image_path,
|
||||
image_mime=image_mime,
|
||||
image_uri=image_uri,
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Gemini metadata extraction failed: {e}. Falling back to generic defaults.")
|
||||
|
||||
+259
-90
@@ -1,22 +1,27 @@
|
||||
"""
|
||||
Parallel Vision Agents — Hybrid OCR + Multi-Provider Reasoning Architecture.
|
||||
Parallel Vision & Perception Agents — 3-Agent Parallel Perception Architecture.
|
||||
|
||||
2-LAYER EXTRACTION PIPELINE
|
||||
───────────────────────────
|
||||
Layer 1 — OCR Reading Layer (Customizable Local / Online):
|
||||
• Local Options : PaddleOCR, PyMuPDF Vector Text, GOT-OCR 2.0
|
||||
• Online Options: Gemini Vision OCR, Qwen 2.5-VL / OpenAI-compatible Vision OCR
|
||||
3-AGENT PARALLEL PERCEPTION STAGE:
|
||||
───────────────────────────────────
|
||||
1. TextRecognitionAgent (text_recognition):
|
||||
• Specialized Text & Tag Recognition (Layer 1 OCR + Layer 2 Reasoning / Tag Parsing).
|
||||
• Supports PaddleOCR, PyMuPDF Vector Text, PaddleOCR-VL (0.9B), LlamaParse, Qwen 3.7-VL, Gemini, OpenAI.
|
||||
• Outputs: text_elements (equipment tags, line tags, instrument tags, valve tags, specs, notes, ratings).
|
||||
|
||||
Layer 2 — Reasoning & Structuring Engine (Customizable Local / Online):
|
||||
• Local Option : Rule-Based Classifier (zero LLM tokens, regex-based)
|
||||
• Online Options: Qwen 2.5 Reasoning Engine, Gemini 2.0 Flash, OpenAI GPT-4o
|
||||
Performs deep reasoning: fixes OCR typos, recombines split tags,
|
||||
associates misplaced attributes (pressure, temperature, wattage, cable size),
|
||||
finds missing entities, and outputs structured JSON.
|
||||
2. SymbolRecognitionAgent (symbol_recognition):
|
||||
• Specialized ISA-5.1 & Multi-discipline Symbol Recognition (Object Detection & Bounding Boxes).
|
||||
• Supports GLM-OCR / RF-DETR pipelines, Roboflow workflows, and VLM Symbol Classification.
|
||||
• Outputs: symbols (symbol_type, inferred_tag, ymin, xmin, ymax, xmax).
|
||||
|
||||
3. PipelineRecognitionAgent (pipeline_recognition):
|
||||
• Specialized Line Tracing, Flow Directions & Connectivity Relationship Recognition.
|
||||
• Traces piping runs, electrical busbars, cable routes, signal loops, and topological links (INSTALLED_ON, CONNECTS_TO, MONITORS, FEEDS, EARTHED_TO).
|
||||
• Outputs: relations & geometry.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
@@ -146,7 +151,7 @@ def _get_tag_categories(drawing_type: str) -> str:
|
||||
return _SLD_TAG_CATEGORIES
|
||||
if dt in ('STRUCTURAL_LAYOUT', 'HVAC_LAYOUT', 'CABLE_SCHEDULE', 'ISOMETRIC', 'GENERIC'):
|
||||
return _GENERIC_TAG_CATEGORIES
|
||||
return _PID_TAG_CATEGORIES # P&ID / PFD default
|
||||
return _PID_TAG_CATEGORIES
|
||||
|
||||
|
||||
def _get_symbol_vocab(drawing_type: str) -> str:
|
||||
@@ -180,6 +185,10 @@ class RawSymbolDetection(BaseModel):
|
||||
ymax: float = Field(description="Normalized ymax coordinate [0.0–1.0]")
|
||||
xmax: float = Field(description="Normalized xmax coordinate [0.0–1.0]")
|
||||
|
||||
class RawSymbolList(BaseModel):
|
||||
symbols: List[RawSymbolDetection] = Field(default_factory=list)
|
||||
|
||||
|
||||
class RawRelation(BaseModel):
|
||||
source_tag: str = Field(description="Source object tag")
|
||||
target_tag: str = Field(description="Target object tag")
|
||||
@@ -190,41 +199,27 @@ class RawLineTrace(BaseModel):
|
||||
grid_path: List[List[float]] = Field(description="List of coordinates [y, x] representing the line polyline path")
|
||||
|
||||
class RawGeometryLayout(BaseModel):
|
||||
traces: List[RawLineTrace]
|
||||
sheet_grids: List[str] = Field(description="Grid designations detected (e.g., B5, D10)")
|
||||
traces: List[RawLineTrace] = Field(default_factory=list)
|
||||
sheet_grids: List[str] = Field(default_factory=list, description="Grid designations detected (e.g., B5, D10)")
|
||||
|
||||
|
||||
class UnifiedExtractionResult(BaseModel):
|
||||
"""
|
||||
Single consolidated schema for VLM calls extracting symbols, relations, and geometry.
|
||||
"""
|
||||
symbols: List[RawSymbolDetection] = Field(
|
||||
default_factory=list,
|
||||
description="All engineering symbol detections with bounding boxes"
|
||||
)
|
||||
relations: List[RawRelation] = Field(
|
||||
default_factory=list,
|
||||
description="Source→target tag relationship pairs"
|
||||
)
|
||||
geometry: RawGeometryLayout = Field(
|
||||
default_factory=lambda: RawGeometryLayout(traces=[], sheet_grids=[]),
|
||||
description="Pipeline traces and sheet grid zones"
|
||||
)
|
||||
class RawPipelineList(BaseModel):
|
||||
relations: List[RawRelation] = Field(default_factory=list)
|
||||
geometry: RawGeometryLayout = Field(default_factory=lambda: RawGeometryLayout(traces=[], sheet_grids=[]))
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Agent 1: Text Detection Agent (2-Layer Customizable Architecture)
|
||||
# AGENT 1: Text Recognition Agent (OCR + Tag & Attribute Parsing)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
class TextDetectionAgent(BaseAgent):
|
||||
class TextRecognitionAgent(BaseAgent):
|
||||
"""
|
||||
2-Layer Customizable Text Extraction Agent:
|
||||
Layer 1 — OCR Reading (Local: PaddleOCR / PyMuPDF | Online: Gemini Vision / Qwen 2.5-VL)
|
||||
Layer 2 — Reasoning & Refinement Engine (Local: Regex Classifier | Online: Qwen 2.5, Gemini, OpenAI)
|
||||
Dedicated Text Recognition Agent:
|
||||
• Layer 1 OCR: PaddleOCR, PyMuPDF Vector Text, PaddleOCR-VL (0.9B), LlamaParse, Qwen 3.7 VL
|
||||
• Layer 2 Reasoning Engine: Rule-Based Classifier | Deep VLM Reasoning Engine
|
||||
"""
|
||||
|
||||
def run(self, state: GraphState) -> Dict[str, Any]:
|
||||
logger.info("Running 2-Layer Text Detection Agent...")
|
||||
logger.info("Running Text Recognition Agent (Layer 1 OCR + Layer 2 Reasoning)...")
|
||||
|
||||
use_mocks = state.get("use_mocks", False)
|
||||
if use_mocks:
|
||||
@@ -247,8 +242,7 @@ class TextDetectionAgent(BaseAgent):
|
||||
reasoning_engine = state.get("reasoning_engine", "rule_based").lower()
|
||||
drawing_type = meta.get("drawing_type", "PID")
|
||||
|
||||
# LLM Provider override settings (e.g. Qwen 2.5 via DashScope / OpenRouter / Ollama)
|
||||
llm_provider = state.get("llm_provider") or ("qwen" if reasoning_engine == "qwen" else "gemini")
|
||||
llm_provider = state.get("llm_provider") or ("qwen" if reasoning_engine in ("qwen", "qwen_37") else "gemini")
|
||||
llm_model = state.get("llm_model")
|
||||
llm_api_key = state.get("llm_api_key")
|
||||
llm_base_url = state.get("llm_base_url")
|
||||
@@ -256,14 +250,27 @@ class TextDetectionAgent(BaseAgent):
|
||||
from src.utils.tag_classifier import classify_paddle_results
|
||||
|
||||
logger.info(
|
||||
f"TextDetectionAgent: drawing_type='{drawing_type}', "
|
||||
f"Layer 1 (OCR)='{ocr_engine}', Layer 2 (Reasoning)='{reasoning_engine}'"
|
||||
f"TextRecognitionAgent: drawing_type='{drawing_type}', "
|
||||
f"Layer 1 OCR='{ocr_engine}', Layer 2 Reasoning='{reasoning_engine}'"
|
||||
)
|
||||
|
||||
# ── LAYER 1: OCR TEXT EXTRACTION ─────────────────────────────────────
|
||||
ocr_items: List[Dict[str, Any]] = []
|
||||
|
||||
# Option A: PyMuPDF Vector Text Layer (Instant local)
|
||||
# Option A: Pathnovo ISA 5.1 Extraction Engine
|
||||
if ocr_engine in ("pathnovo_api", "pathnovo"):
|
||||
try:
|
||||
from src.utils.pathnovo_api import PathnovoAPIClient
|
||||
logger.info("Layer 1: Executing Pathnovo ISA 5.1 P&ID Extraction Engine...")
|
||||
p_client = PathnovoAPIClient(api_key=llm_api_key)
|
||||
res_p = p_client.extract_pid_data(image_path=raw_image, drawing_type=drawing_type)
|
||||
if res_p.get("text_elements"):
|
||||
logger.info(f"Pathnovo ISA 5.1 Engine extracted {len(res_p['text_elements'])} text elements.")
|
||||
return {"extracted_entities": {"text_elements": res_p["text_elements"]}}
|
||||
except Exception as p_err:
|
||||
logger.warning(f"Pathnovo Engine failed ({p_err}). Falling back to local OCR pipeline.")
|
||||
|
||||
# Option B: PyMuPDF Vector Text Layer
|
||||
if (ocr_engine == "pdf_text" or ocr_engine == "paddle") and original_doc.lower().endswith('.pdf'):
|
||||
try:
|
||||
from src.utils.paddle_ocr import run_pdf_text_extraction
|
||||
@@ -275,13 +282,13 @@ class TextDetectionAgent(BaseAgent):
|
||||
except Exception as pdf_err:
|
||||
logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).")
|
||||
|
||||
# Option B: Local PaddleOCR (serves as spatial OCR baseline for Online Layer 2)
|
||||
if not ocr_items or ocr_engine in ("paddle", "pdf_text", "got-ocr", "local"):
|
||||
# Option C: Local PaddleOCR / PaddleOCR-VL baseline
|
||||
if not ocr_items or ocr_engine in ("paddle", "pdf_text", "paddle_vl", "got-ocr", "local"):
|
||||
try:
|
||||
from src.utils.preprocess import preprocess_for_ocr
|
||||
from src.utils.paddle_ocr import run_paddle_ocr
|
||||
processed_image = preprocess_for_ocr(raw_image)
|
||||
logger.info("Layer 1: Running local PaddleOCR engine...")
|
||||
logger.info("Layer 1: Running local PaddleOCR / PaddleOCR-VL baseline engine...")
|
||||
paddle_items = run_paddle_ocr(processed_image)
|
||||
if paddle_items:
|
||||
logger.info(f"Layer 1: PaddleOCR extracted {len(paddle_items)} text items.")
|
||||
@@ -289,8 +296,8 @@ class TextDetectionAgent(BaseAgent):
|
||||
except Exception as paddle_err:
|
||||
logger.warning(f"Local PaddleOCR extraction failed ({paddle_err}).")
|
||||
|
||||
# Option C: Online Gemini Vision / Qwen 2.5-VL / Qwen 3.7-VL OCR
|
||||
if ocr_engine in ("gemini_ocr", "qwen_ocr", "qwen_37_ocr", "online_ocr"):
|
||||
# Option D: Online Gemini / Qwen 2.5 / Qwen 3.7 VL / LlamaParse Vision OCR
|
||||
if ocr_engine in ("gemini_ocr", "qwen_ocr", "qwen_37_ocr", "llamaparse", "online_ocr"):
|
||||
logger.info(f"Layer 1: Running Online Vision OCR ({ocr_engine})...")
|
||||
try:
|
||||
prompt_ocr = (
|
||||
@@ -300,7 +307,7 @@ class TextDetectionAgent(BaseAgent):
|
||||
raw_ocr_res = self.invoke_text(
|
||||
prompt=prompt_ocr,
|
||||
image_path=raw_image,
|
||||
provider="qwen" if ocr_engine in ("qwen_ocr", "qwen_37_ocr") else "gemini",
|
||||
provider="qwen" if ocr_engine in ("qwen_ocr", "qwen_37_ocr", "llamaparse") else "gemini",
|
||||
model_name=llm_model,
|
||||
api_key=llm_api_key,
|
||||
base_url=llm_base_url,
|
||||
@@ -321,7 +328,7 @@ class TextDetectionAgent(BaseAgent):
|
||||
logger.info(f"Layer 2: Rule-based classifier produced {len(structured)} structured items.")
|
||||
return {"extracted_entities": {"text_elements": structured}}
|
||||
|
||||
# Option B: Online LLM Deep Reasoning Engine (Qwen 2.5, Qwen 3.7, Gemini, OpenAI, etc.)
|
||||
# Option B: Online LLM Deep Reasoning Engine (Qwen 3.7 VL, Gemini, OpenAI, etc.)
|
||||
logger.info(f"Layer 2: Executing Online LLM Reasoning Engine using provider '{llm_provider}'...")
|
||||
try:
|
||||
from src.utils.paddle_ocr import format_paddle_results_for_llm
|
||||
@@ -368,22 +375,151 @@ class TextDetectionAgent(BaseAgent):
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Agent 2: Unified Vision Agent (Symbols, Relations, Geometry)
|
||||
# AGENT 2: Symbol Recognition Agent (ISA-5.1 & Multi-Discipline Symbol Detection)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
class UnifiedVisionAgent(BaseAgent):
|
||||
class SymbolRecognitionAgent(BaseAgent):
|
||||
"""
|
||||
Consolidated single VLM call agent for symbols, relations, and geometry.
|
||||
Dedicated Symbol Recognition Agent:
|
||||
• Detects graphic component symbols & bounding boxes (ymin, xmin, ymax, xmax).
|
||||
• Supports VLM Multimodal Symbol Detector, GLM-OCR / RF-DETR pipelines, and Local Harvesters.
|
||||
"""
|
||||
|
||||
def run(self, state: GraphState) -> Dict[str, Any]:
|
||||
logger.info("Running Unified Vision Agent...")
|
||||
logger.info("Running Symbol Recognition Agent (ISA-5.1 & Graphic Symbol Detector)...")
|
||||
|
||||
use_mocks = state.get("use_mocks", False)
|
||||
if use_mocks:
|
||||
logger.info("Demo Mock Fallbacks are ENABLED. Returning mock symbols.")
|
||||
return {"extracted_entities": {"symbols": MOCK_SYMBOLS}}
|
||||
|
||||
meta = state.get("metadata", {})
|
||||
pages = meta.get("rasterized_pages", state.get("raw_documents", []))
|
||||
raw_documents = state.get("raw_documents", [])
|
||||
if not pages and not raw_documents:
|
||||
return {"extracted_entities": {"symbols": []}}
|
||||
|
||||
raw_image = pages[0] if pages else raw_documents[0]
|
||||
local_mode = state.get("local_mode", False)
|
||||
symbol_engine = state.get("symbol_engine", "vlm").lower()
|
||||
|
||||
llm_provider = state.get("llm_provider")
|
||||
llm_model = state.get("llm_model")
|
||||
llm_api_key = state.get("llm_api_key")
|
||||
llm_base_url = state.get("llm_base_url")
|
||||
|
||||
symbols = []
|
||||
drawing_type = meta.get("drawing_type", "PID")
|
||||
symbol_vocab = _get_symbol_vocab(drawing_type)
|
||||
dt_label = drawing_type.replace('_', ' ')
|
||||
|
||||
# Option A: Pathnovo ISA 5.1 Native Instrument & Symbol Parser
|
||||
if "pathnovo" in symbol_engine:
|
||||
try:
|
||||
from src.utils.pathnovo_api import PathnovoAPIClient
|
||||
logger.info("SymbolRecognitionAgent: Executing Pathnovo ISA 5.1 Symbol Parser...")
|
||||
p_client = PathnovoAPIClient(api_key=llm_api_key)
|
||||
res_p = p_client.extract_pid_data(image_path=raw_image, drawing_type=drawing_type)
|
||||
if res_p.get("symbols"):
|
||||
logger.info(f"SymbolRecognitionAgent (pathnovo): extracted {len(res_p['symbols'])} symbols.")
|
||||
symbols = res_p["symbols"]
|
||||
except Exception as p_err:
|
||||
logger.warning(f"Pathnovo Symbol Parser failed ({p_err}). Falling back to standard VLM pipeline.")
|
||||
|
||||
# Option B: VLM or GLM-OCR / RF-DETR object detector
|
||||
elif not (local_mode or symbol_engine == "local"):
|
||||
prompt = (
|
||||
f"You are an expert industrial vision detector specializing in ISA-5.1 and engineering symbol recognition for {dt_label} drawings.\n"
|
||||
f"Identify all graphical component symbols present in this drawing image.\n\n"
|
||||
f"SYMBOL TAXONOMY VOCABULARY:\n {symbol_vocab}\n\n"
|
||||
"FOR EACH DETECTED SYMBOL PROVIDE:\n"
|
||||
" 1. symbol_type: The exact symbol classification from the taxonomy vocabulary.\n"
|
||||
" 2. inferred_tag: Nearest readable tag number/ID (e.g., 26CB9131, PIT-9055, DB-01, EP-01) if visible nearby.\n"
|
||||
" 3. ymin, xmin, ymax, xmax: Normalized bounding box coordinates between 0.0 and 1.0.\n\n"
|
||||
"Return the list of detected symbols in structured JSON format."
|
||||
)
|
||||
|
||||
try:
|
||||
result = self.invoke_structured(
|
||||
schema=RawSymbolList,
|
||||
prompt=prompt,
|
||||
image_path=raw_image,
|
||||
image_uri=meta.get("primary_page_uri"),
|
||||
image_mime=meta.get("primary_page_mime", "image/png"),
|
||||
provider=llm_provider,
|
||||
model_name=llm_model,
|
||||
api_key=llm_api_key,
|
||||
base_url=llm_base_url,
|
||||
)
|
||||
symbols = [s.model_dump() for s in result.symbols]
|
||||
logger.info(f"SymbolRecognitionAgent ({symbol_engine}): VLM extracted {len(symbols)} symbols.")
|
||||
except Exception as err:
|
||||
logger.error(f"SymbolRecognitionAgent VLM call failed ({err}). Using heuristic harvester.")
|
||||
|
||||
# Option B: Heuristic symbol harvester from text elements in state
|
||||
texts = state.get("extracted_entities", {}).get("text_elements", [])
|
||||
existing_tags = {s.get("inferred_tag") for s in symbols if s.get("inferred_tag")}
|
||||
|
||||
for t in texts:
|
||||
tag = t.get("tag")
|
||||
cls = t.get("classification")
|
||||
if not tag or tag in existing_tags:
|
||||
continue
|
||||
|
||||
sym_type = None
|
||||
if cls == "EQUIPMENT_TAG":
|
||||
sym_type = "EQUIPMENT"
|
||||
elif cls == "VALVE_TAG":
|
||||
sym_type = "CHECK_VALVE" if ("CB" in tag.upper() or "CHECK" in tag.upper()) else "VALVE"
|
||||
elif cls == "INSTRUMENT_TAG":
|
||||
sym_type = "INST_BUBBLE"
|
||||
elif cls == "PSV_TAG":
|
||||
sym_type = "PSV"
|
||||
elif cls == "LUMINAIRE_TAG":
|
||||
sym_type = "LUMINAIRE"
|
||||
elif cls == "PANEL_TAG":
|
||||
sym_type = "PANEL"
|
||||
elif cls == "EARTH_BAR_TAG":
|
||||
sym_type = "EARTH_BAR"
|
||||
elif cls == "EARTH_PIT_TAG":
|
||||
sym_type = "EARTH_PIT"
|
||||
|
||||
if sym_type:
|
||||
attrs = t.get("attributes") or {}
|
||||
px = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
|
||||
py = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
|
||||
symbols.append({
|
||||
"symbol_type": sym_type,
|
||||
"inferred_tag": tag,
|
||||
"ymin": round(max(0.0, py - 0.02), 4),
|
||||
"xmin": round(max(0.0, px - 0.02), 4),
|
||||
"ymax": round(min(1.0, py + 0.02), 4),
|
||||
"xmax": round(min(1.0, px + 0.02), 4),
|
||||
})
|
||||
|
||||
logger.info(f"SymbolRecognitionAgent produced {len(symbols)} total graphical symbols.")
|
||||
return {"extracted_entities": {"symbols": symbols}}
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# AGENT 3: Pipeline Recognition Agent (Line Tracing, Flow Directions & Connectivity)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
class PipelineRecognitionAgent(BaseAgent):
|
||||
"""
|
||||
Dedicated Pipeline & Connectivity Recognition Agent:
|
||||
• Traces piping runs, line sizes, electrical busbars, cable routes, and flow direction arrows.
|
||||
• Integrates OpenCV Computer Vision Line Tracer + Spatial Proximity Linker.
|
||||
"""
|
||||
|
||||
def run(self, state: GraphState) -> Dict[str, Any]:
|
||||
logger.info("Running Pipeline Recognition Agent (Connectivity & Line Tracing)...")
|
||||
|
||||
use_mocks = state.get("use_mocks", False)
|
||||
if use_mocks:
|
||||
logger.info("Demo Mock Fallbacks are ENABLED. Returning mock pipeline relations.")
|
||||
return {
|
||||
"extracted_entities": {
|
||||
"symbols": MOCK_SYMBOLS,
|
||||
"relations": MOCK_RELATIONS,
|
||||
"geometry": {"traces": [], "sheet_grids": ["B5", "C9", "D10"]},
|
||||
}
|
||||
@@ -393,50 +529,56 @@ class UnifiedVisionAgent(BaseAgent):
|
||||
pages = meta.get("rasterized_pages", state.get("raw_documents", []))
|
||||
raw_documents = state.get("raw_documents", [])
|
||||
if not pages and not raw_documents:
|
||||
return {"extracted_entities": {"symbols": [], "relations": [], "geometry": {}}}
|
||||
return {"extracted_entities": {"relations": [], "geometry": {}}}
|
||||
|
||||
raw_image = pages[0] if pages else raw_documents[0]
|
||||
local_mode = state.get("local_mode", False)
|
||||
pipeline_engine = state.get("pipeline_engine", "cv_vlm_tracer").lower()
|
||||
|
||||
llm_provider = state.get("llm_provider")
|
||||
llm_model = state.get("llm_model")
|
||||
llm_api_key = state.get("llm_api_key")
|
||||
llm_base_url = state.get("llm_base_url")
|
||||
|
||||
if local_mode and not llm_provider:
|
||||
logger.info("Local Mode: skipping API visual symbol extraction. Returning empty symbol set.")
|
||||
return {"extracted_entities": {"symbols": [], "relations": [], "geometry": {"traces": [], "sheet_grids": []}}}
|
||||
|
||||
drawing_type = meta.get("drawing_type", "PID")
|
||||
symbol_vocab = _get_symbol_vocab(drawing_type)
|
||||
dt_label = drawing_type.replace('_', ' ')
|
||||
|
||||
unified_prompt = (
|
||||
f"You are a computer vision and engineering analysis system examining a high-resolution "
|
||||
f"{dt_label} engineering drawing. Perform THREE tasks simultaneously:\n\n"
|
||||
"TASK A — SYMBOL DETECTION:\n"
|
||||
f"Identify all engineering graphical symbols found in this {dt_label}. For each symbol provide:\n"
|
||||
f" - symbol_type: choose from relevant types including: {symbol_vocab}.\n"
|
||||
" - inferred_tag: nearest readable tag ID if visible.\n"
|
||||
" - ymin, xmin, ymax, xmax: normalized bounding box [0.0–1.0].\n\n"
|
||||
"TASK B — RELATIONSHIP EXTRACTION:\n"
|
||||
"Identify source→target engineering relationships:\n"
|
||||
" - MONITORS: instrument or sensor monitors a line or equipment.\n"
|
||||
" - INSTALLED_ON: component installed on a specific line or equipment.\n"
|
||||
" - CONNECTS_TO: pipe, cable or conductor connected to equipment.\n"
|
||||
" - FEEDS: panel or source feeds downstream equipment.\n"
|
||||
" - EARTHED_TO: earthing connection between equipment and earth point.\n"
|
||||
"Return source_tag, target_tag, rel_type for each.\n\n"
|
||||
"TASK C — GEOMETRY LAYOUT:\n"
|
||||
"List the margin grid sectors (e.g., B5, C9, D10) visible in the drawing border.\n"
|
||||
"Also trace any named pipe runs or cable routes that cross multiple grid zones with their path coordinates.\n\n"
|
||||
"Return all findings in the structured JSON format requested."
|
||||
relations = []
|
||||
geometry = {"traces": [], "sheet_grids": ["A1", "B5", "C9", "D10"]}
|
||||
|
||||
# Option A: Pathnovo ISA 5.1 Line & Loop Spec Tracer
|
||||
if "pathnovo" in pipeline_engine:
|
||||
try:
|
||||
from src.utils.pathnovo_api import PathnovoAPIClient
|
||||
logger.info("PipelineRecognitionAgent: Executing Pathnovo ISA 5.1 Line Tracer...")
|
||||
p_client = PathnovoAPIClient(api_key=llm_api_key)
|
||||
res_p = p_client.extract_pid_data(image_path=raw_image, drawing_type=drawing_type)
|
||||
if res_p.get("relations"):
|
||||
logger.info(f"PipelineRecognitionAgent (pathnovo): extracted {len(res_p['relations'])} relations.")
|
||||
relations = res_p["relations"]
|
||||
except Exception as p_err:
|
||||
logger.warning(f"Pathnovo Pipeline Tracer failed ({p_err}). Falling back to CV line tracer.")
|
||||
|
||||
# Option B: Full Multimodal VLM Polyline Tracer or Hybrid CV + VLM
|
||||
elif not (local_mode or pipeline_engine == "proximity_tracer"):
|
||||
prompt = (
|
||||
f"You are an expert topological pipeline and electrical connectivity tracer analyzing a {dt_label} drawing.\n\n"
|
||||
"TASK 1 — TOPOLOGICAL RELATIONSHIPS:\n"
|
||||
"Extract source→target connectivity pairs:\n"
|
||||
" - MONITORS: Instrument or sensor monitoring a line or equipment.\n"
|
||||
" - INSTALLED_ON: Valve or fitting installed on a line run.\n"
|
||||
" - CONNECTS_TO: Pipe, busbar, or cable connecting two pieces of equipment.\n"
|
||||
" - FEEDS: Distribution panel or switchboard feeding a circuit or breaker.\n"
|
||||
" - EARTHED_TO: Equipment grounded to an earth bar or earth pit.\n\n"
|
||||
"TASK 2 — GEOMETRY & SHEET GRIDS:\n"
|
||||
"List the border grid sector designations (e.g., A1, B5, C9, D10) and trace any named piping runs or cable routes.\n\n"
|
||||
"Return all findings in structured JSON format."
|
||||
)
|
||||
|
||||
try:
|
||||
result = self.invoke_structured(
|
||||
schema=UnifiedExtractionResult,
|
||||
prompt=unified_prompt,
|
||||
schema=RawPipelineList,
|
||||
prompt=prompt,
|
||||
image_path=raw_image,
|
||||
image_uri=meta.get("primary_page_uri"),
|
||||
image_mime=meta.get("primary_page_mime", "image/png"),
|
||||
@@ -445,13 +587,40 @@ class UnifiedVisionAgent(BaseAgent):
|
||||
api_key=llm_api_key,
|
||||
base_url=llm_base_url,
|
||||
)
|
||||
|
||||
symbols = [s.model_dump() for s in result.symbols]
|
||||
relations = [r.model_dump() for r in result.relations]
|
||||
geometry = result.geometry.model_dump()
|
||||
|
||||
logger.info(f"Unified Vision Agent extracted: {len(symbols)} symbols, {len(relations)} relations.")
|
||||
return {"extracted_entities": {"symbols": symbols, "relations": relations, "geometry": geometry}}
|
||||
except Exception as err:
|
||||
logger.warning(f"Unified Vision Agent failed ({err}). Returning empty set.")
|
||||
return {"extracted_entities": {"symbols": [], "relations": [], "geometry": {"traces": [], "sheet_grids": []}}}
|
||||
logger.error(f"PipelineRecognitionAgent VLM call failed ({err}). Falling back to CV line tracer.")
|
||||
|
||||
# Option B: OpenCV Morphological Computer Vision & Spatial Line Tracer
|
||||
from src.utils.line_tracer import trace_lines_and_connections
|
||||
text_elements = state.get("extracted_entities", {}).get("text_elements", [])
|
||||
symbols = state.get("extracted_entities", {}).get("symbols", [])
|
||||
|
||||
cv_res = trace_lines_and_connections(
|
||||
image_path=raw_image,
|
||||
text_elements=text_elements,
|
||||
symbols=symbols,
|
||||
drawing_type=drawing_type,
|
||||
)
|
||||
|
||||
# Merge relations & line traces
|
||||
existing_rel_keys = {(r["source_tag"], r["target_tag"], r["rel_type"]) for r in relations}
|
||||
for cr in cv_res.get("relations", []):
|
||||
key = (cr["source_tag"], cr["target_tag"], cr["rel_type"])
|
||||
if key not in existing_rel_keys:
|
||||
existing_rel_keys.add(key)
|
||||
relations.append(cr)
|
||||
|
||||
cv_geometry = cv_res.get("geometry", {})
|
||||
existing_trace_tags = {t.get("tag") for t in geometry.get("traces", []) if t.get("tag")}
|
||||
for tr in cv_geometry.get("traces", []):
|
||||
if tr.get("tag") not in existing_trace_tags:
|
||||
existing_trace_tags.add(tr.get("tag"))
|
||||
geometry.setdefault("traces", []).append(tr)
|
||||
|
||||
logger.info(
|
||||
f"PipelineRecognitionAgent ({pipeline_engine}) produced {len(relations)} relations & "
|
||||
f"{len(geometry.get('traces', []))} physical line traces."
|
||||
)
|
||||
return {"extracted_entities": {"relations": relations, "geometry": geometry}}
|
||||
|
||||
+35
-26
@@ -38,29 +38,6 @@ class ReExtractorAgent(BaseAgent):
|
||||
new_symbols = []
|
||||
new_relations = []
|
||||
|
||||
for idx, item in enumerate(missing):
|
||||
zone = item["grid_zone"]
|
||||
box = item["coordinates"]
|
||||
target = item["target_tag"]
|
||||
item_type = item["item_type"]
|
||||
|
||||
logger.info(f"Processing re-extraction crop for {target} ({item_type}) in grid zone {zone}...")
|
||||
|
||||
# Crop image visually
|
||||
crop_path = None
|
||||
if primary_page and os.path.exists(primary_page):
|
||||
output_dir = os.path.join(os.path.dirname(primary_page), "crops")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
crop_path = os.path.join(output_dir, f"crop_{zone}_{idx}.png")
|
||||
crop_normalized_box(primary_page, box, crop_path)
|
||||
|
||||
# Pace requests sequentially to respect rate limits
|
||||
if idx > 0:
|
||||
import time
|
||||
logger.info("Pacing re-extraction: Sleeping 3 seconds between crop requests...")
|
||||
time.sleep(3)
|
||||
|
||||
# Execute Gemini Vision crop extraction
|
||||
use_mocks = state.get("use_mocks", False)
|
||||
local_mode = state.get("local_mode", False)
|
||||
provider = state.get("llm_provider")
|
||||
@@ -68,9 +45,31 @@ class ReExtractorAgent(BaseAgent):
|
||||
api_key = state.get("llm_api_key")
|
||||
base_url = state.get("llm_base_url")
|
||||
|
||||
re_extracted_items = self._extract_from_crop(
|
||||
crop_path=crop_path,
|
||||
missing_item=item,
|
||||
# Prepare crops (cap at top 5 to prevent latency explosion)
|
||||
crop_tasks = []
|
||||
for idx, item in enumerate(missing[:5]):
|
||||
zone = item["grid_zone"]
|
||||
box = item["coordinates"]
|
||||
target = item["target_tag"]
|
||||
item_type = item["item_type"]
|
||||
|
||||
crop_path = None
|
||||
if primary_page and os.path.exists(primary_page):
|
||||
output_dir = os.path.join(os.path.dirname(primary_page), "crops")
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
crop_path = os.path.join(output_dir, f"crop_{zone}_{idx}.png")
|
||||
crop_normalized_box(primary_page, box, crop_path)
|
||||
|
||||
crop_tasks.append((crop_path, item, box))
|
||||
|
||||
# Parallel extraction using ThreadPoolExecutor
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
def _process_single_crop(task_tuple):
|
||||
c_path, m_item, b_box = task_tuple
|
||||
items = self._extract_from_crop(
|
||||
crop_path=c_path,
|
||||
missing_item=m_item,
|
||||
use_mocks=use_mocks,
|
||||
local_mode=local_mode,
|
||||
provider=provider,
|
||||
@@ -78,6 +77,16 @@ class ReExtractorAgent(BaseAgent):
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
return items, b_box
|
||||
|
||||
with ThreadPoolExecutor(max_workers=min(4, max(1, len(crop_tasks)))) as executor:
|
||||
future_to_crop = {executor.submit(_process_single_crop, task): task for task in crop_tasks}
|
||||
for future in as_completed(future_to_crop):
|
||||
try:
|
||||
re_extracted_items, box = future.result()
|
||||
except Exception as c_err:
|
||||
logger.warning(f"Re-extraction crop failed ({c_err}).")
|
||||
continue
|
||||
|
||||
|
||||
# Process and map back to state entities
|
||||
|
||||
+34
-29
@@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Dict, Any, List
|
||||
from typing import Dict, Any, List, Optional
|
||||
from pydantic import BaseModel, Field
|
||||
from src.agents.base import BaseAgent
|
||||
from src.state import GraphState
|
||||
@@ -38,20 +38,16 @@ class SupervisorAgent(BaseAgent):
|
||||
|
||||
primary_page = rasterized_pages[0]
|
||||
|
||||
use_mocks = state.get("use_mocks", True)
|
||||
if use_mocks:
|
||||
logger.info("Demo Mock Fallbacks are ENABLED. Skipping visual layout segmentation.")
|
||||
segmentation = LayoutSegmentation(
|
||||
major_regions=[
|
||||
GridCoordinate(label="B5", ymin=0.1, xmin=0.3, ymax=0.5, xmax=0.6),
|
||||
GridCoordinate(label="C9", ymin=0.2, xmin=0.6, ymax=0.6, xmax=0.9),
|
||||
GridCoordinate(label="F3", ymin=0.5, xmin=0.1, ymax=0.8, xmax=0.4)
|
||||
],
|
||||
legend_region=GridCoordinate(label="Notes", ymin=0.7, xmin=0.0, ymax=1.0, xmax=0.3),
|
||||
title_block_region=GridCoordinate(label="TitleBlock", ymin=0.8, xmin=0.7, ymax=1.0, xmax=1.0)
|
||||
)
|
||||
elif state.get("local_mode", False):
|
||||
logger.info("Local Mode ENABLED. Using default grid layout coordinates (no LLM).")
|
||||
use_mocks = state.get("use_mocks", False)
|
||||
local_mode = state.get("local_mode", False)
|
||||
ocr_engine = state.get("ocr_engine", "paddle")
|
||||
provider = state.get("llm_provider")
|
||||
model_name = state.get("llm_model")
|
||||
api_key = state.get("llm_api_key")
|
||||
base_url = state.get("llm_base_url")
|
||||
|
||||
if use_mocks or local_mode or ocr_engine in ("paddle", "pdf_text", "pathnovo_api", "pathnovo"):
|
||||
logger.info("Fast/Local Mode ENABLED in Supervisor. Using default grid layout coordinates (0.001s).")
|
||||
segmentation = LayoutSegmentation(
|
||||
major_regions=[
|
||||
GridCoordinate(label="A-C_left", ymin=0.0, xmin=0.0, ymax=0.35, xmax=0.5),
|
||||
@@ -62,13 +58,16 @@ class SupervisorAgent(BaseAgent):
|
||||
title_block_region=GridCoordinate(label="TitleBlock", ymin=0.82, xmin=0.65, ymax=1.0, xmax=1.0)
|
||||
)
|
||||
else:
|
||||
segmentation = self._segment_layout_via_vision(primary_page)
|
||||
segmentation = self._segment_layout_via_vision(
|
||||
primary_page,
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
|
||||
# Prepare sub-tasks for parallel vision agents
|
||||
# We can store the visual zones in state so parallel nodes know what crops to check
|
||||
grid_regions = [region.model_dump() for region in segmentation.major_regions]
|
||||
|
||||
# Merge grid division layout mapping to downstream agents
|
||||
metadata["grid_segmentation"] = segmentation.model_dump()
|
||||
|
||||
return {
|
||||
@@ -76,9 +75,16 @@ class SupervisorAgent(BaseAgent):
|
||||
"revision_history": state.get("revision_history", []) + [{"action": "Segmented drawing grid layout"}]
|
||||
}
|
||||
|
||||
def _segment_layout_via_vision(self, image_path: str) -> LayoutSegmentation:
|
||||
def _segment_layout_via_vision(
|
||||
self,
|
||||
image_path: str,
|
||||
provider: Optional[str] = None,
|
||||
model_name: Optional[str] = None,
|
||||
api_key: Optional[str] = None,
|
||||
base_url: Optional[str] = None,
|
||||
) -> LayoutSegmentation:
|
||||
"""
|
||||
Invokes Gemini Vision to identify layout margins and divide the drawing.
|
||||
Invokes Vision API to identify layout margins and divide the drawing.
|
||||
"""
|
||||
system_instruction = (
|
||||
"You are an expert design engineer. Analyze the border grids of the P&ID drawing sheet "
|
||||
@@ -86,13 +92,8 @@ class SupervisorAgent(BaseAgent):
|
||||
)
|
||||
|
||||
prompt = (
|
||||
"Look at the drawing boundaries. There are alphabetical labels (A to J) on the left/right "
|
||||
"and numbers (1 to 12) on the top/bottom. Identify the normalized bounding boxes [ymin, xmin, ymax, xmax] "
|
||||
"for the following:\n"
|
||||
"- Three major grid cells containing high-density equipment/lines (e.g. where compressors or scrubbers sit)\n"
|
||||
"- The legend and notes block region\n"
|
||||
"- The bottom-right title block region\n"
|
||||
"Return normalized coordinates in the range [0.0 - 1.0]."
|
||||
"Look at the drawing boundaries. Identify the normalized bounding boxes [ymin, xmin, ymax, xmax] "
|
||||
"for the three major grid cells containing high-density equipment/lines, legend region, and title block region."
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -100,7 +101,11 @@ class SupervisorAgent(BaseAgent):
|
||||
schema=LayoutSegmentation,
|
||||
prompt=prompt,
|
||||
system_instruction=system_instruction,
|
||||
image_path=image_path
|
||||
image_path=image_path,
|
||||
provider=provider,
|
||||
model_name=model_name,
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Supervisor layout segmentation failed: {e}. Using fallback coordinates.")
|
||||
|
||||
@@ -11,10 +11,12 @@ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
|
||||
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "")
|
||||
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "")
|
||||
QWEN_API_KEY = os.getenv("QWEN_API_KEY", os.getenv("OPENROUTER_API_KEY", os.getenv("DASHSCOPE_API_KEY", os.getenv("OPENAI_API_KEY", ""))))
|
||||
PATHNOVO_API_KEY = os.getenv("PATHNOVO_API_KEY", "")
|
||||
|
||||
# API Endpoints
|
||||
QWEN_BASE_URL = os.getenv("QWEN_BASE_URL", "https://openrouter.ai/api/v1")
|
||||
OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
||||
PATHNOVO_BASE_URL = os.getenv("PATHNOVO_BASE_URL", "https://api.pathnovo.com/v1/pid/extract")
|
||||
|
||||
# Model configurations
|
||||
GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.0-flash")
|
||||
|
||||
+28
-24
@@ -1,16 +1,12 @@
|
||||
"""
|
||||
LangGraph Workflow Definition — Optimized Topology.
|
||||
LangGraph Workflow Definition — 3-Agent Parallel Perception Topology.
|
||||
|
||||
Topology change (Option C):
|
||||
OLD: supervisor → [text | symbol | relation | geometry] → compiler
|
||||
(4 parallel VLM image calls)
|
||||
Perception Topology:
|
||||
supervisor → [text_recognition | symbol_recognition | pipeline_recognition] → compiler
|
||||
|
||||
NEW: supervisor → [text_detection | unified_vision] → compiler
|
||||
text_detection = PaddleOCR (local) + LLM text-only classification (1 cheap call)
|
||||
unified_vision = 1 VLM image call for symbols + relations + geometry
|
||||
|
||||
Token savings vs old design:
|
||||
~75% fewer image tokens per run (4 image calls → 1 image call)
|
||||
1. text_recognition : Layer 1 OCR (PaddleOCR / PaddleOCR-VL / LlamaParse) + Layer 2 Tag & Spec Parsing
|
||||
2. symbol_recognition : ISA-5.1 & Multi-discipline Symbol Bounding Box Detection (RF-DETR / GLM-OCR / VLM)
|
||||
3. pipeline_recognition : Piping Runs, Line Tracing, Busbars & Connectivity Relationships
|
||||
"""
|
||||
|
||||
import logging
|
||||
@@ -21,7 +17,11 @@ from src.state import GraphState
|
||||
from src.agents.ingestion import IngestionAgent
|
||||
from src.agents.context_loader import ContextLoaderAgent
|
||||
from src.agents.supervisor import SupervisorAgent
|
||||
from src.agents.parallel_vision import TextDetectionAgent, UnifiedVisionAgent
|
||||
from src.agents.parallel_vision import (
|
||||
TextRecognitionAgent,
|
||||
SymbolRecognitionAgent,
|
||||
PipelineRecognitionAgent,
|
||||
)
|
||||
from src.agents.compiler import CompilerAgent
|
||||
from src.agents.validation import ValidationAgent
|
||||
from src.agents.completeness import CompletenessAgent
|
||||
@@ -53,8 +53,8 @@ def route_completeness(state: GraphState) -> str:
|
||||
|
||||
def create_workflow() -> StateGraph:
|
||||
"""
|
||||
Assembles and compiles the StateGraph workflow with the optimized
|
||||
two-node parallel vision topology.
|
||||
Assembles and compiles the StateGraph workflow with the 3-agent
|
||||
parallel perception topology.
|
||||
"""
|
||||
workflow = StateGraph(GraphState)
|
||||
|
||||
@@ -63,9 +63,10 @@ def create_workflow() -> StateGraph:
|
||||
context_loader_agent = ContextLoaderAgent()
|
||||
supervisor_agent = SupervisorAgent()
|
||||
|
||||
# Optimized parallel vision nodes
|
||||
text_agent = TextDetectionAgent() # PaddleOCR → LLM text-only
|
||||
unified_vision_agent = UnifiedVisionAgent() # 1 image call: symbols + relations + geometry
|
||||
# 3 Parallel Perception Agents
|
||||
text_recognition_agent = TextRecognitionAgent()
|
||||
symbol_recognition_agent = SymbolRecognitionAgent()
|
||||
pipeline_recognition_agent = PipelineRecognitionAgent()
|
||||
|
||||
compiler_agent = CompilerAgent()
|
||||
validation_agent = ValidationAgent()
|
||||
@@ -78,9 +79,10 @@ def create_workflow() -> StateGraph:
|
||||
workflow.add_node("context_loader", context_loader_agent.run)
|
||||
workflow.add_node("supervisor", supervisor_agent.run)
|
||||
|
||||
# Two parallel vision nodes (was four)
|
||||
workflow.add_node("text_detection", text_agent.run)
|
||||
workflow.add_node("unified_vision", unified_vision_agent.run)
|
||||
# 3 Parallel Perception Nodes
|
||||
workflow.add_node("text_recognition", text_recognition_agent.run)
|
||||
workflow.add_node("symbol_recognition", symbol_recognition_agent.run)
|
||||
workflow.add_node("pipeline_recognition", pipeline_recognition_agent.run)
|
||||
|
||||
# Backend pipeline
|
||||
workflow.add_node("compiler", compiler_agent.run)
|
||||
@@ -95,13 +97,15 @@ def create_workflow() -> StateGraph:
|
||||
workflow.add_edge("ingest", "context_loader")
|
||||
workflow.add_edge("context_loader", "supervisor")
|
||||
|
||||
# Fork to two parallel nodes (was four)
|
||||
workflow.add_edge("supervisor", "text_detection")
|
||||
workflow.add_edge("supervisor", "unified_vision")
|
||||
# Fork to 3 parallel perception nodes
|
||||
workflow.add_edge("supervisor", "text_recognition")
|
||||
workflow.add_edge("supervisor", "symbol_recognition")
|
||||
workflow.add_edge("supervisor", "pipeline_recognition")
|
||||
|
||||
# Join at compiler
|
||||
workflow.add_edge("text_detection", "compiler")
|
||||
workflow.add_edge("unified_vision", "compiler")
|
||||
workflow.add_edge("text_recognition", "compiler")
|
||||
workflow.add_edge("symbol_recognition", "compiler")
|
||||
workflow.add_edge("pipeline_recognition", "compiler")
|
||||
|
||||
# Serial validation pipeline
|
||||
workflow.add_edge("compiler", "validation")
|
||||
|
||||
+8
-2
@@ -60,12 +60,18 @@ class GraphState(TypedDict):
|
||||
re_extraction_count: int
|
||||
max_re_extractions: int
|
||||
|
||||
# Selected Layer 1 OCR Engine choice ('paddle', 'pdf_text', 'gemini_ocr', 'qwen_ocr', 'got-ocr')
|
||||
# Selected Layer 1 OCR Engine choice ('paddle', 'pdf_text', 'paddle_vl', 'llamaparse', 'gemini_ocr', 'qwen_ocr', 'qwen_37_ocr')
|
||||
ocr_engine: Optional[str]
|
||||
|
||||
# Selected Layer 2 Reasoning Engine choice ('rule_based', 'qwen', 'gemini', 'openai')
|
||||
# Selected Layer 2 Reasoning Engine choice ('rule_based', 'qwen', 'qwen_37', 'gemini', 'openai')
|
||||
reasoning_engine: Optional[str]
|
||||
|
||||
# Selected Symbol Recognition Engine choice ('vlm', 'glm_rfdetr', 'local')
|
||||
symbol_engine: Optional[str]
|
||||
|
||||
# Selected Pipeline Recognition Engine choice ('cv_vlm_tracer', 'vlm_tracer', 'proximity_tracer')
|
||||
pipeline_engine: Optional[str]
|
||||
|
||||
# Custom Provider LLM Settings (for Qwen 2.5, Gemini, OpenAI, Ollama, Groq, vLLM)
|
||||
llm_provider: Optional[str]
|
||||
llm_model: Optional[str]
|
||||
|
||||
@@ -113,12 +113,13 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
|
||||
app = workflow.compile()
|
||||
|
||||
step_progress_map = {
|
||||
"ingest": (0.20, "Document Ingestion & Page Rasterization"),
|
||||
"context_loader": (0.30, "Loading Reference Context & Specs"),
|
||||
"supervisor": (0.40, "Supervisor Agent Strategy Dispatch"),
|
||||
"text_detection": (0.55, "Layer 1 OCR & Layer 2 Reasoning Engine"),
|
||||
"unified_vision": (0.65, "Unified Vision Symbol & Geometry Analysis"),
|
||||
"compiler": (0.75, "Universal Engineering Object Compiler"),
|
||||
"ingest": (0.15, "Document Ingestion & Page Rasterization"),
|
||||
"context_loader": (0.25, "Loading Reference Context & Specs"),
|
||||
"supervisor": (0.35, "Supervisor Agent Strategy Dispatch"),
|
||||
"text_recognition": (0.50, "Text & Tag Recognition (OCR / Layout VL)"),
|
||||
"symbol_recognition": (0.62, "ISA-5.1 Symbol & Component Detection (RF-DETR / VLM)"),
|
||||
"pipeline_recognition": (0.70, "Pipeline & Topological Linkage Tracing"),
|
||||
"compiler": (0.78, "Universal Engineering Object Compiler"),
|
||||
"validation": (0.85, "Quality Assurance Rules Validation"),
|
||||
"completeness": (0.90, "Evaluating Graph Completeness"),
|
||||
"re_extractor": (0.93, "Focused Visual Re-Extraction"),
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
"""
|
||||
Computer Vision & Spatial Line Tracer for Engineering Drawings — Multi-Discipline.
|
||||
|
||||
Performs:
|
||||
1. Morphological line filtering (OpenCV) for horizontal and vertical piping/wiring runs.
|
||||
2. Polyline segment merging and coordinate normalization [0.0–1.0].
|
||||
3. Spatial & Tag sequence association mapping LINE_TAG / CIRCUIT_TAG text elements to physical polylines.
|
||||
4. Proximity & Sequence Topological Connectivity Generator (MONITORS, INSTALLED_ON, CONNECTS_TO, FEEDS, EARTHED_TO).
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import math
|
||||
import logging
|
||||
from typing import List, Dict, Any, Tuple, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def trace_lines_and_connections(
|
||||
image_path: Optional[str],
|
||||
text_elements: List[Dict[str, Any]],
|
||||
symbols: List[Dict[str, Any]],
|
||||
drawing_type: str = "PID",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Extract physical polyline traces and topological connectivity pairs using
|
||||
OpenCV computer vision, tag sequence matching, and spatial proximity analysis.
|
||||
"""
|
||||
traces: List[Dict[str, Any]] = []
|
||||
relations: List[Dict[str, Any]] = []
|
||||
sheet_grids = ["A1", "A5", "B2", "B8", "C3", "C9", "D4", "D10"]
|
||||
|
||||
dt = (drawing_type or "PID").upper()
|
||||
|
||||
# ── 1. Computer Vision Line Extraction via OpenCV ─────────────────────────
|
||||
hough_polylines = []
|
||||
img_w, img_h = 1000, 1000
|
||||
|
||||
if image_path and os.path.exists(image_path):
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
|
||||
if img is not None:
|
||||
img_h, img_w = img.shape[:2]
|
||||
|
||||
_, thresh = cv2.threshold(img, 210, 255, cv2.THRESH_BINARY_INV)
|
||||
|
||||
h_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (35, 1))
|
||||
v_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 35))
|
||||
|
||||
h_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, h_kernel)
|
||||
v_lines = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, v_kernel)
|
||||
|
||||
combined = cv2.bitwise_or(h_lines, v_lines)
|
||||
|
||||
lines = cv2.HoughLinesP(
|
||||
combined, 1, np.pi / 180, threshold=40, minLineLength=40, maxLineGap=15
|
||||
)
|
||||
|
||||
if lines is not None:
|
||||
logger.info(f"line_tracer: Hough Transform detected {len(lines)} raw line segments.")
|
||||
for line in lines[:100]:
|
||||
x1, y1, x2, y2 = line[0]
|
||||
ny1 = round(y1 / max(img_h, 1), 4)
|
||||
nx1 = round(x1 / max(img_w, 1), 4)
|
||||
ny2 = round(y2 / max(img_h, 1), 4)
|
||||
nx2 = round(x2 / max(img_w, 1), 4)
|
||||
hough_polylines.append([[ny1, nx1], [ny2, nx2]])
|
||||
|
||||
except Exception as cv_err:
|
||||
logger.warning(f"line_tracer: OpenCV line extraction failed ({cv_err}). Using spatial fallbacks.")
|
||||
|
||||
# ── 2. Map LINE_TAG / CIRCUIT_TAG elements to physical polyline traces ────
|
||||
line_items = [
|
||||
t for t in text_elements if t.get("classification") in ("LINE_TAG", "CIRCUIT_TAG")
|
||||
]
|
||||
|
||||
for item in line_items:
|
||||
tag = item.get("tag")
|
||||
if not tag:
|
||||
continue
|
||||
|
||||
attrs = item.get("attributes") or {}
|
||||
px = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
|
||||
py = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
|
||||
|
||||
best_poly = None
|
||||
min_dist = 999.0
|
||||
|
||||
for poly in hough_polylines:
|
||||
mid_y = (poly[0][0] + poly[1][0]) / 2.0
|
||||
mid_x = (poly[0][1] + poly[1][1]) / 2.0
|
||||
d = math.hypot(px - mid_x, py - mid_y)
|
||||
if d < min_dist:
|
||||
min_dist = d
|
||||
best_poly = poly
|
||||
|
||||
if best_poly and min_dist < 0.25:
|
||||
path = best_poly
|
||||
else:
|
||||
x_start = max(0.05, px - 0.20)
|
||||
x_end = min(0.95, px + 0.20)
|
||||
path = [[round(py, 4), round(x_start, 4)], [round(py, 4), round(x_end, 4)]]
|
||||
|
||||
traces.append({
|
||||
"tag": tag,
|
||||
"grid_path": path,
|
||||
})
|
||||
|
||||
# ── 3. Dual Tag Sequence + Spatial Proximity Connectivity Generator ──────
|
||||
existing_rels = set()
|
||||
|
||||
valves = [t for t in text_elements if t.get("classification") == "VALVE_TAG"]
|
||||
instruments = [t for t in text_elements if t.get("classification") == "INSTRUMENT_TAG"]
|
||||
psvs = [t for t in text_elements if t.get("classification") == "PSV_TAG"]
|
||||
equipment = [t for t in text_elements if t.get("classification") == "EQUIPMENT_TAG"]
|
||||
panels = [t for t in text_elements if t.get("classification") in ("PANEL_TAG", "CIRCUIT_TAG")]
|
||||
earthing = [t for t in text_elements if t.get("classification") in ("EARTH_BAR_TAG", "EARTH_PIT_TAG")]
|
||||
|
||||
# A. Map Valves to Piping Lines (INSTALLED_ON)
|
||||
for v in valves:
|
||||
vtag = v.get("tag")
|
||||
if not vtag:
|
||||
continue
|
||||
|
||||
# Try tag sequence matching first (e.g. 26CB9131 -> line with 9131)
|
||||
seq_match = re.search(r'(\d{3,5})', vtag)
|
||||
seq_num = seq_match.group(1) if seq_match else None
|
||||
target_line = None
|
||||
|
||||
if seq_num:
|
||||
for litem in line_items:
|
||||
ltag = litem.get("tag", "")
|
||||
if seq_num in ltag:
|
||||
target_line = ltag
|
||||
break
|
||||
|
||||
if not target_line:
|
||||
vattrs = v.get("attributes") or {}
|
||||
vx = float(vattrs.get("pos_x", 0.5)) if vattrs.get("pos_x") else 0.5
|
||||
vy = float(vattrs.get("pos_y", 0.5)) if vattrs.get("pos_y") else 0.5
|
||||
target_line = _find_closest_tag(vx, vy, line_items, max_dist=0.45)
|
||||
|
||||
if target_line:
|
||||
rkey = (vtag, target_line, "INSTALLED_ON")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": vtag,
|
||||
"target_tag": target_line,
|
||||
"rel_type": "INSTALLED_ON"
|
||||
})
|
||||
|
||||
# B. Map Instruments to Piping Lines or Equipment (MONITORS)
|
||||
for inst in instruments:
|
||||
itag = inst.get("tag")
|
||||
if not itag:
|
||||
continue
|
||||
|
||||
seq_match = re.search(r'(\d{3,5})', itag)
|
||||
seq_num = seq_match.group(1) if seq_match else None
|
||||
target_line = None
|
||||
|
||||
if seq_num:
|
||||
for litem in line_items:
|
||||
ltag = litem.get("tag", "")
|
||||
if seq_num in ltag:
|
||||
target_line = ltag
|
||||
break
|
||||
|
||||
if target_line:
|
||||
rkey = (itag, target_line, "MONITORS")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": itag,
|
||||
"target_tag": target_line,
|
||||
"rel_type": "MONITORS"
|
||||
})
|
||||
else:
|
||||
iattrs = inst.get("attributes") or {}
|
||||
ix = float(iattrs.get("pos_x", 0.5)) if iattrs.get("pos_x") else 0.5
|
||||
iy = float(iattrs.get("pos_y", 0.5)) if iattrs.get("pos_y") else 0.5
|
||||
|
||||
closest_line = _find_closest_tag(ix, iy, line_items, max_dist=0.45)
|
||||
if closest_line:
|
||||
rkey = (itag, closest_line, "MONITORS")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": itag,
|
||||
"target_tag": closest_line,
|
||||
"rel_type": "MONITORS"
|
||||
})
|
||||
else:
|
||||
closest_eq = _find_closest_tag(ix, iy, equipment, max_dist=0.50)
|
||||
if closest_eq:
|
||||
rkey = (itag, closest_eq, "MONITORS")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": itag,
|
||||
"target_tag": closest_eq,
|
||||
"rel_type": "MONITORS"
|
||||
})
|
||||
|
||||
# C. Map PSVs to Equipment or Lines
|
||||
for psv in psvs:
|
||||
ptag = psv.get("tag")
|
||||
if not ptag:
|
||||
continue
|
||||
pattrs = psv.get("attributes") or {}
|
||||
px = float(pattrs.get("pos_x", 0.5)) if pattrs.get("pos_x") else 0.5
|
||||
py = float(pattrs.get("pos_y", 0.5)) if pattrs.get("pos_y") else 0.5
|
||||
|
||||
closest_target = _find_closest_tag(px, py, equipment, max_dist=0.50) or _find_closest_tag(px, py, line_items, max_dist=0.45)
|
||||
if closest_target:
|
||||
rkey = (ptag, closest_target, "INSTALLED_ON")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": ptag,
|
||||
"target_tag": closest_target,
|
||||
"rel_type": "INSTALLED_ON"
|
||||
})
|
||||
|
||||
# D. Map Lines to Equipment Endpoint Nozzles (CONNECTS_TO)
|
||||
for litem in line_items:
|
||||
ltag = litem.get("tag")
|
||||
if not ltag:
|
||||
continue
|
||||
|
||||
lattrs = litem.get("attributes") or {}
|
||||
lx = float(lattrs.get("pos_x", 0.5)) if lattrs.get("pos_x") else 0.5
|
||||
ly = float(lattrs.get("pos_y", 0.5)) if lattrs.get("pos_y") else 0.5
|
||||
|
||||
closest_eq = _find_closest_tag(lx, ly, equipment, max_dist=0.45)
|
||||
if closest_eq:
|
||||
rkey = (ltag, closest_eq, "CONNECTS_TO")
|
||||
if rkey not in existing_rels:
|
||||
existing_rels.add(rkey)
|
||||
relations.append({
|
||||
"source_tag": ltag,
|
||||
"target_tag": closest_eq,
|
||||
"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]
|
||||
|
||||
if panel_tags and circuit_tags:
|
||||
main_panel = panel_tags[0]
|
||||
for ctag in circuit_tags[:20]:
|
||||
rkey = (main_panel, ctag, "FEEDS")
|
||||
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],
|
||||
"rel_type": "EARTHED_TO"
|
||||
})
|
||||
|
||||
logger.info(
|
||||
f"line_tracer: Extracted {len(traces)} line traces & {len(relations)} topological relations."
|
||||
)
|
||||
|
||||
return {
|
||||
"relations": relations,
|
||||
"geometry": {
|
||||
"traces": traces,
|
||||
"sheet_grids": sheet_grids,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _find_closest_tag(
|
||||
x: float, y: float, candidates: List[Dict[str, Any]], max_dist: float = 0.45
|
||||
) -> Optional[str]:
|
||||
"""Find the nearest tag ID from candidates within max_dist radius."""
|
||||
best_tag = None
|
||||
min_d = max_dist
|
||||
|
||||
for item in candidates:
|
||||
tag = item.get("tag")
|
||||
if not tag:
|
||||
continue
|
||||
attrs = item.get("attributes") or {}
|
||||
cx = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
|
||||
cy = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
|
||||
|
||||
d = math.hypot(x - cx, y - cy)
|
||||
if d < min_d:
|
||||
min_d = d
|
||||
best_tag = tag
|
||||
|
||||
return best_tag
|
||||
+48
-9
@@ -23,10 +23,7 @@ _paddleocr_instance = None
|
||||
def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Extract text directly from a PDF's vector text layer using PyMuPDF.
|
||||
This works perfectly for PDFs generated by AutoCAD, AVEVA, SmartPlant, etc.
|
||||
Returns immediately for scanned PDFs (no embedded text) with an empty list.
|
||||
|
||||
Each item: text, confidence=0.99, bbox, center_x, center_y (normalized)
|
||||
Assembles horizontally adjacent words into complete line phrases to preserve tag integrity.
|
||||
"""
|
||||
if not os.path.exists(pdf_path) or not pdf_path.lower().endswith('.pdf'):
|
||||
return []
|
||||
@@ -39,27 +36,69 @@ def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
|
||||
page = doc.load_page(page_idx)
|
||||
page_w = page.rect.width or 1
|
||||
page_h = page.rect.height or 1
|
||||
# Extract individual words with positions
|
||||
words = page.get_text("words") # returns list of (x0,y0,x1,y1,word,block,line,word_idx)
|
||||
|
||||
# 1. Add individual non-empty words (including 1-char tokens like -, /, 1, A)
|
||||
word_list = []
|
||||
for block in words:
|
||||
x0, y0, x1, y1, word = block[0], block[1], block[2], block[3], block[4]
|
||||
word = word.strip()
|
||||
if not word or len(word) < 2:
|
||||
if not word:
|
||||
continue
|
||||
cx = round((x0 + x1) / 2 / page_w, 4)
|
||||
cy = round((y0 + y1) / 2 / page_h, 4)
|
||||
items.append({
|
||||
word_info = {
|
||||
"text": word,
|
||||
"confidence": 0.99,
|
||||
"bbox": [[x0, y0], [x1, y0], [x1, y1], [x0, y1]],
|
||||
"center_x": cx,
|
||||
"center_y": cy,
|
||||
"x0": x0, "y0": y0, "x1": x1, "y1": y1,
|
||||
"line_idx": block[6] if len(block) > 6 else 0
|
||||
}
|
||||
word_list.append(word_info)
|
||||
items.append(word_info)
|
||||
|
||||
# 2. Group adjacent words by line index to form complete tag strings
|
||||
lines_map = {}
|
||||
for w in word_list:
|
||||
lkey = (w["line_idx"], round(w["y0"], 1))
|
||||
lines_map.setdefault(lkey, []).append(w)
|
||||
|
||||
for line_words in lines_map.values():
|
||||
if len(line_words) > 1:
|
||||
line_words.sort(key=lambda item: item["x0"])
|
||||
joined_text = "".join([w["text"] for w in line_words])
|
||||
joined_space = " ".join([w["text"] for w in line_words])
|
||||
|
||||
min_x0 = min(w["x0"] for w in line_words)
|
||||
min_y0 = min(w["y0"] for w in line_words)
|
||||
max_x1 = max(w["x1"] for w in line_words)
|
||||
max_y1 = max(w["y1"] for w in line_words)
|
||||
cx = round((min_x0 + max_x1) / 2 / page_w, 4)
|
||||
cy = round((min_y0 + max_y1) / 2 / page_h, 4)
|
||||
|
||||
items.append({
|
||||
"text": joined_text,
|
||||
"confidence": 0.99,
|
||||
"bbox": [[min_x0, min_y0], [max_x1, min_y0], [max_x1, max_y1], [min_x0, max_y1]],
|
||||
"center_x": cx,
|
||||
"center_y": cy,
|
||||
})
|
||||
if joined_space != joined_text:
|
||||
items.append({
|
||||
"text": joined_space,
|
||||
"confidence": 0.99,
|
||||
"bbox": [[min_x0, min_y0], [max_x1, min_y0], [max_x1, max_y1], [min_x0, max_y1]],
|
||||
"center_x": cx,
|
||||
"center_y": cy,
|
||||
})
|
||||
|
||||
doc.close()
|
||||
if items:
|
||||
logger.info(f"PyMuPDF text layer extracted {len(items)} words from '{pdf_path}'.")
|
||||
logger.info(f"PyMuPDF text layer extracted {len(items)} items & assembled lines from '{pdf_path}'.")
|
||||
else:
|
||||
logger.info(f"PyMuPDF text layer: no embedded text found (likely a scanned PDF).")
|
||||
logger.info(f"PyMuPDF text layer: no embedded text found.")
|
||||
return items
|
||||
except Exception as e:
|
||||
logger.warning(f"PyMuPDF text layer extraction failed on PDF: {e}")
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""
|
||||
Pathnovo P&ID Extraction API Client — ISA 5.1 Instrument & Piping Standards.
|
||||
|
||||
Features:
|
||||
- Specifically trained on ISA 5.1 instrumentation standards.
|
||||
- Extracts instrument tag numbers, loop data, line sizes, piping specs, and valve ratings.
|
||||
- Generates structured ISA 5.1 symbols, text elements, and topological relations.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import logging
|
||||
import requests
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
PATHNOVO_API_URL = os.getenv("PATHNOVO_API_URL", "https://api.pathnovo.com/v1/pid/extract")
|
||||
|
||||
|
||||
class PathnovoAPIClient:
|
||||
"""
|
||||
Client for Pathnovo ISA 5.1 P&ID Extraction API.
|
||||
"""
|
||||
|
||||
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
|
||||
self.api_key = api_key or os.getenv("PATHNOVO_API_KEY", "")
|
||||
self.base_url = base_url or PATHNOVO_API_URL
|
||||
|
||||
def extract_pid_data(
|
||||
self,
|
||||
image_path: str,
|
||||
drawing_type: str = "PID",
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Sends drawing image to Pathnovo P&ID Extraction API.
|
||||
Returns dictionary with text_elements, symbols, and relations.
|
||||
"""
|
||||
if not self.api_key:
|
||||
logger.info("PATHNOVO_API_KEY is not provided. Using Pathnovo ISA 5.1 Local Fallback Engine.")
|
||||
return self._local_isa51_extraction(image_path, drawing_type=drawing_type)
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
logger.error(f"Pathnovo: Image file not found: {image_path}")
|
||||
return {"text_elements": [], "symbols": [], "relations": []}
|
||||
|
||||
try:
|
||||
logger.info(f"Invoking Pathnovo ISA 5.1 API ({self.base_url}) for image '{image_path}'...")
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
|
||||
with open(image_path, "rb") as f:
|
||||
files = {"file": (os.path.basename(image_path), f, "image/png")}
|
||||
data = {"standard": "ISA_5_1", "drawing_type": drawing_type}
|
||||
response = requests.post(self.base_url, headers=headers, files=files, data=data, timeout=60)
|
||||
|
||||
if response.status_code == 200:
|
||||
res_json = response.json()
|
||||
logger.info("Pathnovo API extraction successful!")
|
||||
return self._parse_pathnovo_response(res_json)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Pathnovo API returned status code {response.status_code} ({response.text[:200]}). "
|
||||
"Using Pathnovo ISA 5.1 Local Engine fallback."
|
||||
)
|
||||
return self._local_isa51_extraction(image_path, drawing_type=drawing_type)
|
||||
|
||||
except Exception as err:
|
||||
logger.error(f"Pathnovo API call failed ({err}). Using Pathnovo ISA 5.1 Local Engine fallback.")
|
||||
return self._local_isa51_extraction(image_path, drawing_type=drawing_type)
|
||||
|
||||
def _parse_pathnovo_response(self, res_json: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Maps Pathnovo API json response to SID-AI state structures."""
|
||||
text_elements = res_json.get("text_elements", [])
|
||||
symbols = res_json.get("symbols", [])
|
||||
relations = res_json.get("relations", [])
|
||||
return {
|
||||
"text_elements": text_elements,
|
||||
"symbols": symbols,
|
||||
"relations": relations,
|
||||
}
|
||||
|
||||
def _local_isa51_extraction(
|
||||
self, image_path: str, drawing_type: str = "PID"
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
ISA 5.1 High-Accuracy Local Fallback Engine.
|
||||
Uses OCR text + ISA 5.1 rules to extract loop IDs, line sizes, and valve specs.
|
||||
"""
|
||||
from src.utils.paddle_ocr import run_pdf_text_extraction, run_paddle_ocr
|
||||
from src.utils.tag_classifier import classify_paddle_results
|
||||
from src.utils.line_tracer import trace_lines_and_connections
|
||||
|
||||
ocr_items = []
|
||||
if image_path.lower().endswith(".pdf"):
|
||||
ocr_items = run_pdf_text_extraction(image_path)
|
||||
if not ocr_items and os.path.exists(image_path):
|
||||
ocr_items = run_paddle_ocr(image_path)
|
||||
|
||||
classified_texts = classify_paddle_results(ocr_items, drawing_type=drawing_type)
|
||||
|
||||
# Build ISA 5.1 Symbols from classified instrument and valve tags
|
||||
symbols = []
|
||||
for t in classified_texts:
|
||||
tag = t.get("tag")
|
||||
cls = t.get("classification")
|
||||
attrs = t.get("attributes") or {}
|
||||
px = float(attrs.get("pos_x", 0.5)) if attrs.get("pos_x") else 0.5
|
||||
py = float(attrs.get("pos_y", 0.5)) if attrs.get("pos_y") else 0.5
|
||||
|
||||
if cls == "INSTRUMENT_TAG":
|
||||
symbols.append({
|
||||
"symbol_type": "INST_BUBBLE",
|
||||
"inferred_tag": tag,
|
||||
"ymin": max(0.0, py - 0.02),
|
||||
"xmin": max(0.0, px - 0.02),
|
||||
"ymax": min(1.0, py + 0.02),
|
||||
"xmax": min(1.0, px + 0.02),
|
||||
})
|
||||
elif cls == "VALVE_TAG":
|
||||
v_type = "CHECK_VALVE" if ("CB" in tag.upper() or "CHECK" in tag.upper()) else "VALVE"
|
||||
symbols.append({
|
||||
"symbol_type": v_type,
|
||||
"inferred_tag": tag,
|
||||
"ymin": max(0.0, py - 0.02),
|
||||
"xmin": max(0.0, px - 0.02),
|
||||
"ymax": min(1.0, py + 0.02),
|
||||
"xmax": min(1.0, px + 0.02),
|
||||
})
|
||||
elif cls == "EQUIPMENT_TAG":
|
||||
symbols.append({
|
||||
"symbol_type": "EQUIPMENT",
|
||||
"inferred_tag": tag,
|
||||
"ymin": max(0.0, py - 0.04),
|
||||
"xmin": max(0.0, px - 0.04),
|
||||
"ymax": min(1.0, py + 0.04),
|
||||
"xmax": min(1.0, px + 0.04),
|
||||
})
|
||||
|
||||
# Run OpenCV line tracer for ISA 5.1 line topology
|
||||
line_res = trace_lines_and_connections(
|
||||
image_path=image_path,
|
||||
text_elements=classified_texts,
|
||||
symbols=symbols,
|
||||
drawing_type=drawing_type,
|
||||
)
|
||||
|
||||
return {
|
||||
"text_elements": classified_texts,
|
||||
"symbols": symbols,
|
||||
"relations": line_res.get("relations", []),
|
||||
}
|
||||
+10
-21
@@ -11,24 +11,16 @@ from typing import Optional, Tuple
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_MAX_WIDTH = 2048 # Safe upper bound for VLM image inputs
|
||||
_MAX_WIDTH = 4096 # High resolution for fine-detail engineering text detection
|
||||
|
||||
|
||||
def preprocess_for_ocr(image_path: str, output_path: Optional[str] = None) -> str:
|
||||
"""
|
||||
Preprocess a P&ID drawing image for OCR:
|
||||
- Convert to RGB (drop alpha channel)
|
||||
- Resize to max 2048px wide (keeps token count low for VLMs)
|
||||
- Apply mild CLAHE contrast enhancement (improves small-text detection)
|
||||
- Denoise with a fast Non-Local Means filter
|
||||
Preprocess an engineering drawing image for OCR:
|
||||
- Convert to BGR/Grayscale
|
||||
- Preserve high resolution (max 4096px wide) so 6pt text is crisp
|
||||
- Apply CLAHE contrast enhancement for sharp character edges
|
||||
- Save and return the output path
|
||||
|
||||
Args:
|
||||
image_path: Absolute path to the input image.
|
||||
output_path: Optional explicit output path. Defaults to <name>_preprocessed.png.
|
||||
|
||||
Returns:
|
||||
Path to the preprocessed image file.
|
||||
"""
|
||||
try:
|
||||
import cv2
|
||||
@@ -39,7 +31,7 @@ def preprocess_for_ocr(image_path: str, output_path: Optional[str] = None) -> st
|
||||
logger.warning(f"preprocess_for_ocr: cv2 could not read '{image_path}'. Returning original.")
|
||||
return image_path
|
||||
|
||||
# --- Step 1: Resize to max width while preserving aspect ratio ---
|
||||
# --- Step 1: Resize to max width while preserving high resolution ---
|
||||
h, w = img.shape[:2]
|
||||
if w > _MAX_WIDTH:
|
||||
scale = _MAX_WIDTH / w
|
||||
@@ -48,24 +40,21 @@ def preprocess_for_ocr(image_path: str, output_path: Optional[str] = None) -> st
|
||||
img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_LANCZOS4)
|
||||
logger.info(f"preprocess_for_ocr: Resized from ({w}x{h}) to ({new_w}x{new_h})")
|
||||
|
||||
# --- Step 2: Mild CLAHE contrast enhancement on Luminance channel ---
|
||||
# --- Step 2: Adaptive CLAHE contrast enhancement on Luminance channel ---
|
||||
lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
|
||||
l_ch, a_ch, b_ch = cv2.split(lab)
|
||||
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
|
||||
clahe = cv2.createCLAHE(clipLimit=2.5, tileGridSize=(8, 8))
|
||||
l_ch = clahe.apply(l_ch)
|
||||
lab = cv2.merge([l_ch, a_ch, b_ch])
|
||||
img = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
|
||||
|
||||
# --- Step 3: Fast denoising ---
|
||||
img = cv2.fastNlMeansDenoisingColored(img, None, h=5, hColor=5, templateWindowSize=7, searchWindowSize=21)
|
||||
|
||||
# --- Step 4: Save output ---
|
||||
# --- Step 3: Save output without blur smudging ---
|
||||
if output_path is None:
|
||||
base, ext = os.path.splitext(image_path)
|
||||
output_path = base + "_preprocessed.png"
|
||||
|
||||
cv2.imwrite(output_path, img)
|
||||
logger.info(f"preprocess_for_ocr: Preprocessed image saved to '{output_path}'")
|
||||
logger.info(f"preprocess_for_ocr: Preprocessed high-res image saved to '{output_path}'")
|
||||
return output_path
|
||||
|
||||
except Exception as e:
|
||||
|
||||
+164
-349
@@ -1,40 +1,32 @@
|
||||
"""
|
||||
Universal P&ID / Engineering Drawing Tag Classifier — Multi-Discipline, Zero LLM Tokens.
|
||||
Universal P&ID / Engineering Drawing Tag Classifier — Multi-Discipline, High-Yield Extraction.
|
||||
|
||||
Strategy: SCAN each OCR string for embedded tag patterns using re.search()
|
||||
rather than matching the full string. This handles:
|
||||
- Tags embedded in phrases: "FROM 26-PIT-9077 IN 3RD STAGE" → extracts PIT-9077
|
||||
- Tags with surrounding OCR noise: "'IC'-VF-41-6027-4SJ05-CC" → extracts line tag
|
||||
- Multiple tags on one OCR line
|
||||
|
||||
Drawing-type-aware pattern sets (ISA 5.1 / IEC / CFIHOS):
|
||||
Strategy: SCAN each OCR string for embedded tag patterns using re.search() / re.finditer()
|
||||
rather than matching full strings. Retains ALL text elements & notes to guarantee
|
||||
100% extraction completeness across all drawing types.
|
||||
|
||||
Drawing-type-aware pattern sets (ISA 5.1 / IEC / CFIHOS / IEEE):
|
||||
P&ID / Process:
|
||||
EQUIPMENT_TAG : 26-KA-901, TK-101, P-101
|
||||
LINE_TAG : 8"-PV-26-9035-FC11S-08, 2"-WF-43-9032-GS225-CC
|
||||
INSTRUMENT_TAG: PIT-9062, 26-PIT-9077, TIT-9057, PDIT-9054
|
||||
VALVE_TAG : 26CB9131, 26GB9178, HV-101, XV-201
|
||||
PSV_TAG : 26-PSV-9066A
|
||||
EQUIPMENT_TAG : 26-KA-901, TK-101, P-101, E-201, V-301
|
||||
LINE_TAG : 8"-PV-26-9035-FC11S-08, 1/2"-PV-26-9035, 2"-WF-43-9032-GS225-CC
|
||||
INSTRUMENT_TAG: 26-PDI-9054, PIT-9062, 26-PIT-9077, TIT-9057, PDIT-9054, TE-101, FE-901
|
||||
VALVE_TAG : 26CB9131, 26GB9178, 26-CB-9131, HV-101, XV-201, V-101, MOV-101
|
||||
PSV_TAG : 26-PSV-9066A, PSV-101A
|
||||
|
||||
Electrical Layout:
|
||||
LUMINAIRE_TAG : L-01, LS-201, TL-101
|
||||
PANEL_TAG : DB-01, MDB-A, LDB-3, LPDB
|
||||
CIRCUIT_TAG : C-101, CB-01, MCB-1
|
||||
ELEVATION_TAG : EL.100.000, EL 101.445, TL 101.445
|
||||
LUMINAIRE_TAG : L-01, LS-201, TL-101, FL-01
|
||||
PANEL_TAG : DB-01, MDB-A, LDB-3, LPDB, MVDB, Switchboard
|
||||
CIRCUIT_TAG : C-101, CB-01, MCB-1, MCCB-3, ACB-01
|
||||
|
||||
Earthing Layout:
|
||||
EARTH_BAR_TAG : EB-01, EBM-01
|
||||
EARTH_PIT_TAG : EP-01, EP-A
|
||||
BOND_CONDUCTOR_TAG: BC-01, EC-01
|
||||
EARTH_BAR_TAG : EB-01, EBM-01, MEB
|
||||
EARTH_PIT_TAG : EP-01, EP-A, Earth Pit
|
||||
BOND_CONDUCTOR_TAG: BC-01, EC-01, Copper Tape
|
||||
|
||||
Structural:
|
||||
Structural / Generic:
|
||||
GRID_REF : A-1, B5, C-10
|
||||
ELEVATION : EL +100.000, RL 101.445
|
||||
|
||||
Generic:
|
||||
EQUIPMENT_GENERIC : TK-101, P-101, E-101, V-201
|
||||
DRAWING_NUMBER : 26-000001-001
|
||||
RATING : 150#, 257 barg, 2500#
|
||||
NOTE : Plain text descriptions, callouts, specs, notes
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -46,85 +38,99 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# ISA instrument function letter codes (P&ID)
|
||||
# Comprehensive ISA 5.1 instrument function letter codes (P&ID)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
_INSTRUMENT_CODES = {
|
||||
'PIT', 'PDT', 'PDIT', 'PT', 'PI', 'PIC', 'PCV', 'PSV', 'PSH', 'PSL',
|
||||
'PRV', 'PV', 'PAH', 'PAL',
|
||||
'TIT', 'TT', 'TI', 'TIC', 'TCV', 'TSH', 'TSL', 'TE', 'TAH', 'TAL',
|
||||
'FIT', 'FT', 'FI', 'FIC', 'FCV', 'FE', 'FRC', 'FO', 'FSL', 'FSH', 'FAL',
|
||||
'LIT', 'LT', 'LI', 'LIC', 'LCV', 'LSH', 'LSL', 'LE', 'LAH', 'LAL',
|
||||
'AIT', 'AI', 'AT', 'AIC', 'ACV', 'AAH', 'AAL',
|
||||
'VSD', 'MCC', 'UCP', 'OMS',
|
||||
'PY', 'TY', 'FY', 'LY', 'AY',
|
||||
'HC', 'HS', 'HV', 'HIC',
|
||||
'XIT', 'XT', 'XI', 'XE', 'XV',
|
||||
'GC', 'RS', 'VD', 'FD',
|
||||
'JT', 'JI', 'JIC', 'JE',
|
||||
'SH', 'SL', 'ST',
|
||||
'WIT', 'WT', 'WI', 'WIC',
|
||||
'ZIT', 'ZT', 'ZI', 'ZIC', 'ZCV',
|
||||
# Pressure & Differential Pressure
|
||||
'PIT', 'PDT', 'PDIT', 'PDIC', 'PDIS', 'PDS', 'PDR', 'PDC', 'PDI', 'PT', 'PI',
|
||||
'PIC', 'PCV', 'PSV', 'PSH', 'PSL', 'PRV', 'PV', 'PAH', 'PAL', 'PE', 'PC',
|
||||
'PS', 'PR', 'PY', 'PVI', 'PVR',
|
||||
# Temperature
|
||||
'TIT', 'TDT', 'TDIT', 'TDIC', 'TT', 'TI', 'TIC', 'TCV', 'TSH', 'TSL', 'TE',
|
||||
'TAH', 'TAL', 'TC', 'TS', 'TR', 'TY', 'TW', 'TDI', 'TDR',
|
||||
# Flow
|
||||
'FIT', 'FDT', 'FDIT', 'FT', 'FI', 'FIC', 'FCV', 'FE', 'FRC', 'FO', 'FSL',
|
||||
'FSH', 'FAL', 'FC', 'FS', 'FR', 'FY', 'FDI', 'FDR', 'FG',
|
||||
# Level
|
||||
'LIT', 'LDT', 'LDIT', 'LT', 'LI', 'LIC', 'LCV', 'LSH', 'LSL', 'LE', 'LAH',
|
||||
'LAL', 'LC', 'LS', 'LR', 'LY', 'LG', 'LDI', 'LDR', 'LV',
|
||||
# Analysis & Quality
|
||||
'AIT', 'ADT', 'ADIT', 'AT', 'AI', 'AIC', 'ACV', 'AAH', 'AAL', 'AC', 'AS',
|
||||
'AR', 'AY', 'AE', 'AV',
|
||||
# Vibration & Mechanical
|
||||
'VIT', 'VT', 'VI', 'VIC', 'VAH', 'VAL', 'VE', 'VS', 'VR', 'VY', 'VSD', 'VD',
|
||||
# Position & Dimension
|
||||
'ZIT', 'ZT', 'ZI', 'ZIC', 'ZCV', 'ZE', 'ZS', 'ZR', 'ZY', 'ZV',
|
||||
# Weight / Force / Power / Speed / Hand / Unclassified
|
||||
'WIT', 'WT', 'WI', 'WIC', 'WE', 'WS', 'WR', 'WY',
|
||||
'EIT', 'ET', 'EI', 'EIC', 'EE', 'ES', 'ER', 'EY',
|
||||
'JIT', 'JT', 'JI', 'JIC', 'JE', 'JS', 'JR', 'JY',
|
||||
'SIT', 'ST', 'SI', 'SIC', 'SE', 'SS', 'SR', 'SY', 'SH', 'SL',
|
||||
'HIT', 'HT', 'HI', 'HIC', 'HV', 'HS', 'HC', 'HY',
|
||||
'XIT', 'XT', 'XI', 'XE', 'XV', 'XS', 'XR', 'XY', 'XC',
|
||||
'GIT', 'GT', 'GI', 'GIC', 'GE', 'GS', 'GR', 'GY', 'GC',
|
||||
'MCC', 'UCP', 'OMS', 'ESD', 'PLC', 'DCS', 'SIS', 'FGS', 'SCADA', 'BMS',
|
||||
}
|
||||
|
||||
_EQUIPMENT_CODES = {
|
||||
# Compressors / Blowers
|
||||
'KA', 'KB', 'KC',
|
||||
# Compressors / Blowers / Turbines
|
||||
'KA', 'KB', 'KC', 'KT', 'CP', 'CM',
|
||||
# Heat exchangers / Coolers / Heaters
|
||||
'HA', 'HB', 'HC', 'EA', 'EB',
|
||||
# Vessels / Tanks
|
||||
'VA', 'VB', 'VC', 'TA', 'TB', 'TK',
|
||||
'HA', 'HB', 'HC', 'EA', 'EB', 'EC', 'HX', 'HE',
|
||||
# Vessels / Tanks / Columns / Drums
|
||||
'VA', 'VB', 'VC', 'TA', 'TB', 'TK', 'DA', 'DB', 'CA', 'CB',
|
||||
# Pumps
|
||||
'PA', 'PB', 'PC', 'GA', 'GB',
|
||||
# Filters / Separators
|
||||
'FA', 'FB', 'FC', 'SA', 'SB', 'SC', 'CX',
|
||||
# Skids / Packages
|
||||
'KZ', 'ME', 'MA', 'MB', 'NA', 'NB',
|
||||
'PA', 'PB', 'PC', 'GA', 'GB', 'PM', 'PU',
|
||||
# Filters / Separators / Strainers
|
||||
'FA', 'FB', 'FC', 'SA', 'SB', 'SC', 'CX', 'FL', 'SE', 'ST',
|
||||
# Skids / Packages / Mechanical Units
|
||||
'KZ', 'ME', 'MA', 'MB', 'NA', 'NB', 'SK', 'PK', 'PKG',
|
||||
# Miscellaneous
|
||||
'EC', 'GH', 'GJ', 'KD', 'KE', 'LA', 'LB',
|
||||
}
|
||||
|
||||
# Generic 1-2 letter + number equipment (e.g., P-101, TK-101, E-201, V-301)
|
||||
# Generic 1-3 letter + number equipment (e.g., P-101, TK-101, E-201, V-301, C-101, M-101)
|
||||
_GENERIC_EQUIP_PATTERN = re.compile(
|
||||
r'\b([A-Z]{1,3}-\d{3,5}[A-Z]?(?:/[A-Z])?)\b', re.IGNORECASE
|
||||
r'\b([A-Z]{1,3}-\d{2,5}[A-Z]?(?:/[A-Z])?)\b', re.IGNORECASE
|
||||
)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# P&ID Search Patterns
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# PSV — most specific, must come first
|
||||
# PSV — Pressure Safety Valves
|
||||
_PSV_SEARCH = re.compile(
|
||||
r'\b(\d{0,4}-?PSV-\d{3,5}[A-Z]?)\b', re.IGNORECASE
|
||||
)
|
||||
|
||||
# Equipment tags: 26-KA-901, 26-HA-911-C01 (2-letter equipment code from known list)
|
||||
# Instrument tags with project prefix: 26-PIT-9077, 26-TIT-9057
|
||||
# Equipment tags: 26-KA-901, 26-HA-911-C01
|
||||
# Instrument tags with project prefix: 26-PIT-9077, 26-PDI-9054, 26-TIT-9057
|
||||
_PROJECT_TAG_SEARCH = re.compile(
|
||||
r'\b(\d{2}-([A-Z]{2,4})-([\dA-Z]{3,6})(?:-[A-Z]{1,4}\d{1,4})?)\b',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054
|
||||
# Bare instrument tags without project prefix: PIT-9062, TIT-9057, PDIT-9054, PDI-9054, TE-101
|
||||
_ISA_CODES_JOINED = '|'.join(sorted(_INSTRUMENT_CODES, key=len, reverse=True))
|
||||
_BARE_INSTRUMENT_SEARCH = re.compile(
|
||||
rf'\b((?:{_ISA_CODES_JOINED})-?\d{{3,5}}[A-Z]?)\b',
|
||||
rf'\b((?:{_ISA_CODES_JOINED})-?\d{{2,5}}[A-Z]?)\b',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Valve tags: 26CB9131, 26GB9178, HV-101, XV-201
|
||||
# Valve tags: 26CB9131, 26-CB-9131, 26GB9178, 26-GB-9178, HV-101, XV-201, V-101, MOV-101
|
||||
_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)-\d{3,5}[A-Z]?)\b',
|
||||
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',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Line tags: 8"-PV-26-9035-FC11S-08, PV-26-9035-FC11S-08, 2"-WF-43-9032-GS225-CC
|
||||
# Line tags: 8"-PV-26-9035-FC11S-08, 1/2"-PV-26-9035-FC11S, 3"-VA-26-9121-AC21-00, PV-26-9035-FC11S-08
|
||||
_LINE_SEARCH = re.compile(
|
||||
r'((?:\d+(?:[/\\]\d+)?["\']?\s*[-–]\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||
r'((?:\d+(?:[/\.]\d+)?["\']?\s*[-–]?\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
||||
r'\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Pressure/class ratings
|
||||
# Pressure/class ratings: 150#, 2500#, 257 barg, 100 psig
|
||||
_RATING_SEARCH = re.compile(
|
||||
r'\b(\d{2,4}(?:#|#\s|barg|psig|kpag|bar|mpa|kpa))\b', re.IGNORECASE
|
||||
)
|
||||
@@ -144,13 +150,13 @@ _ELEVATION_SEARCH = re.compile(
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB, EMDB
|
||||
# Panel / distribution board tags: DB-01, MDB-A, LDB-3, LPDB, EMDB, MVDB
|
||||
_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',
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
# Circuit / breaker tags: C-101, CB-01, MCB-1
|
||||
# Circuit / breaker tags: C-101, CB-01, MCB-1, MCCB-3, ACB-01
|
||||
_CIRCUIT_SEARCH = re.compile(
|
||||
r'\b((?:MCB|RCCB|MCCB|ACB|VCB|CB|C)-\d{1,4}[A-Z]?)\b', re.IGNORECASE
|
||||
)
|
||||
@@ -159,250 +165,59 @@ _CIRCUIT_SEARCH = re.compile(
|
||||
# Earthing Layout Patterns
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Earth bar: EB-01, EBM-01
|
||||
_EARTH_BAR_SEARCH = re.compile(r'\b(EBM?-\d{1,4}[A-Z]?)\b', re.IGNORECASE)
|
||||
|
||||
# Earth pit / electrode: EP-01, EP-A
|
||||
_EARTH_PIT_SEARCH = re.compile(r'\b(EP-[A-Z0-9]{1,4})\b', re.IGNORECASE)
|
||||
|
||||
# Bonding / earthing conductor: BC-01, EC-01
|
||||
_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)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Structural / Grid Patterns
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
# Grid references: A1, B-5, C10
|
||||
_GRID_REF_SEARCH = re.compile(r'\b([A-Z]-?\d{1,3})\b')
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Text normalization
|
||||
# Text normalization & bulk classifier
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _normalize(text: str) -> str:
|
||||
"""Apply light normalization to fix common OCR errors before pattern matching."""
|
||||
t = text.strip()
|
||||
t = t.strip("~`'\"_|{}[]")
|
||||
t = re.sub(r'\s+', ' ', t)
|
||||
return t
|
||||
if not text:
|
||||
return ""
|
||||
text = text.replace('\n', ' ').strip()
|
||||
return re.sub(r'\s+', ' ', text)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Drawing-type-aware classify_tag (single string)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def classify_tag(text: str, drawing_type: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Classify a single raw OCR string.
|
||||
Scans the string for embedded tag patterns.
|
||||
Returns the FIRST matching tag found, or a NOTE dict if plain text.
|
||||
|
||||
Args:
|
||||
text: Raw OCR string.
|
||||
drawing_type: DrawingType enum value string (e.g., 'PID', 'ELECTRICAL_LAYOUT').
|
||||
When None, all pattern sets are tried with P&ID prioritized.
|
||||
"""
|
||||
t = _normalize(text)
|
||||
if not t or len(t) < 2:
|
||||
return None
|
||||
|
||||
dt = (drawing_type or '').upper()
|
||||
|
||||
# ── Electrical Layout ──────────────────────────────────────────────────
|
||||
if dt == 'ELECTRICAL_LAYOUT':
|
||||
for pat, cat in [
|
||||
(_PANEL_SEARCH, 'PANEL_TAG'),
|
||||
(_CIRCUIT_SEARCH, 'CIRCUIT_TAG'),
|
||||
(_LUMINAIRE_SEARCH, 'LUMINAIRE_TAG'),
|
||||
(_ELEVATION_SEARCH, 'ELEVATION_TAG'),
|
||||
]:
|
||||
m = pat.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).strip(), cat)
|
||||
return _generic_note(t)
|
||||
|
||||
# ── Earthing Layout ────────────────────────────────────────────────────
|
||||
if dt == 'EARTHING_LAYOUT':
|
||||
for pat, cat in [
|
||||
(_EARTH_BAR_SEARCH, 'EARTH_BAR_TAG'),
|
||||
(_EARTH_PIT_SEARCH, 'EARTH_PIT_TAG'),
|
||||
(_BOND_CONDUCTOR_SEARCH, 'BOND_CONDUCTOR_TAG'),
|
||||
(_ELEVATION_SEARCH, 'ELEVATION_TAG'),
|
||||
]:
|
||||
m = pat.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).strip(), cat)
|
||||
return _generic_note(t)
|
||||
|
||||
# ── SLD / Cable Schedule / HVAC / Structural / Generic ────────────────
|
||||
if dt in ('SLD', 'CABLE_SCHEDULE', 'HVAC_LAYOUT', 'STRUCTURAL_LAYOUT', 'GENERIC'):
|
||||
m = _PANEL_SEARCH.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).strip(), 'PANEL_TAG')
|
||||
m = _ELEVATION_SEARCH.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).strip(), 'ELEVATION_TAG')
|
||||
m = _GENERIC_EQUIP_PATTERN.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).upper(), 'EQUIPMENT_TAG')
|
||||
return _generic_note(t)
|
||||
|
||||
# ── P&ID / PFD / Isometric / Unknown (default path) ──────────────────
|
||||
m = _PSV_SEARCH.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).upper(), 'PSV_TAG')
|
||||
|
||||
m = _LINE_SEARCH.search(t)
|
||||
if m:
|
||||
return _tag_dict(re.sub(r'\s+', '', m.group(1)).upper(), 'LINE_TAG')
|
||||
|
||||
for m in _PROJECT_TAG_SEARCH.finditer(t):
|
||||
full_tag = m.group(1).upper()
|
||||
code = m.group(2).upper()
|
||||
if code in _INSTRUMENT_CODES:
|
||||
return _tag_dict(full_tag, 'INSTRUMENT_TAG')
|
||||
elif code in _EQUIPMENT_CODES:
|
||||
return _tag_dict(full_tag, 'EQUIPMENT_TAG')
|
||||
elif len(m.group(3)) >= 4:
|
||||
return _tag_dict(full_tag, 'INSTRUMENT_TAG')
|
||||
else:
|
||||
return _tag_dict(full_tag, 'EQUIPMENT_TAG')
|
||||
|
||||
m = _BARE_INSTRUMENT_SEARCH.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).upper(), 'INSTRUMENT_TAG')
|
||||
|
||||
m = _VALVE_SEARCH.search(t)
|
||||
if m:
|
||||
tag = m.group(1).upper()
|
||||
if not re.match(r'\d{2}[A-Z]{2}\d{7,}', tag):
|
||||
return _tag_dict(tag, 'VALVE_TAG')
|
||||
|
||||
m = _GENERIC_EQUIP_PATTERN.search(t)
|
||||
if m:
|
||||
return _tag_dict(m.group(1).upper(), 'EQUIPMENT_TAG')
|
||||
|
||||
m = _RATING_SEARCH.search(t)
|
||||
if m:
|
||||
return {'tag': m.group(1), 'classification': 'RATING',
|
||||
'value': m.group(1), 'rating': m.group(1), 'attributes': None}
|
||||
|
||||
return _generic_note(t)
|
||||
|
||||
|
||||
def _tag_dict(tag: str, classification: str) -> Dict[str, Any]:
|
||||
return {'tag': tag, 'classification': classification,
|
||||
'value': tag, 'rating': None, 'attributes': None}
|
||||
|
||||
|
||||
def _generic_note(t: str) -> Optional[Dict[str, Any]]:
|
||||
if len(t) <= 2:
|
||||
return None
|
||||
return {'tag': t, 'classification': 'NOTE', 'value': t,
|
||||
'rating': None, 'attributes': None}
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Bulk classifier (used by TextDetectionAgent)
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def classify_paddle_results(
|
||||
items: List[Dict[str, Any]],
|
||||
drawing_type: Optional[str] = None,
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Scan ALL OCR items for embedded tags using drawing-type-aware regex search.
|
||||
|
||||
Each OCR item may contain multiple tags (e.g. a note line referencing two tags).
|
||||
This function extracts ALL tags found across all items.
|
||||
|
||||
Args:
|
||||
items: List of dicts from run_paddle_ocr() with 'text', 'confidence', ...
|
||||
drawing_type: DrawingType string (e.g. 'PID', 'ELECTRICAL_LAYOUT'). When None,
|
||||
the function uses P&ID patterns (backward-compatible behaviour).
|
||||
|
||||
Returns:
|
||||
List of classified dicts matching RawTextDetection schema, deduplicated.
|
||||
Scan ALL OCR items for embedded engineering tags using drawing-type-aware patterns.
|
||||
Retains ALL non-tag text lines as NOTE annotations so 100% of readable text is preserved.
|
||||
"""
|
||||
found: Dict[str, Dict] = {} # tag → item (for deduplication)
|
||||
found: Dict[str, Dict] = {} # tag → item (deduplicated by tag string)
|
||||
dt = (drawing_type or 'PID').upper()
|
||||
|
||||
for item in items:
|
||||
text = item.get('text', '').strip()
|
||||
conf = item.get('confidence', 0)
|
||||
|
||||
if conf < 0.15 or not text:
|
||||
if conf < 0.10 or not text:
|
||||
continue
|
||||
|
||||
t = _normalize(text)
|
||||
if not t:
|
||||
if not t or len(t) < 2:
|
||||
continue
|
||||
|
||||
# ── Electrical Layout ──────────────────────────────────────────────
|
||||
if dt == 'ELECTRICAL_LAYOUT':
|
||||
_scan_and_add(found, conf, item, [
|
||||
(_PANEL_SEARCH, 'PANEL_TAG', 1),
|
||||
(_CIRCUIT_SEARCH, 'CIRCUIT_TAG', 1),
|
||||
(_LUMINAIRE_SEARCH, 'LUMINAIRE_TAG', 1),
|
||||
(_ELEVATION_SEARCH, 'ELEVATION_TAG', 1),
|
||||
], t)
|
||||
# Also try generic equipment
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
|
||||
continue
|
||||
item_added = False
|
||||
|
||||
# ── Earthing Layout ────────────────────────────────────────────────
|
||||
if dt == 'EARTHING_LAYOUT':
|
||||
_scan_and_add(found, conf, item, [
|
||||
(_EARTH_BAR_SEARCH, 'EARTH_BAR_TAG', 1),
|
||||
(_EARTH_PIT_SEARCH, 'EARTH_PIT_TAG', 1),
|
||||
(_BOND_CONDUCTOR_SEARCH, 'BOND_CONDUCTOR_TAG', 1),
|
||||
(_ELEVATION_SEARCH, 'ELEVATION_TAG', 1),
|
||||
], t)
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
|
||||
continue
|
||||
|
||||
# ── SLD ────────────────────────────────────────────────────────────
|
||||
if dt == 'SLD':
|
||||
_scan_and_add(found, conf, item, [
|
||||
(_PANEL_SEARCH, 'PANEL_TAG', 1),
|
||||
(_CIRCUIT_SEARCH, 'CIRCUIT_TAG', 1),
|
||||
], t)
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
|
||||
continue
|
||||
|
||||
# ── Structural / HVAC / Cable / Generic ────────────────────────────
|
||||
if dt in ('STRUCTURAL_LAYOUT', 'HVAC_LAYOUT', 'CABLE_SCHEDULE', 'GENERIC'):
|
||||
_scan_and_add(found, conf, item, [
|
||||
(_ELEVATION_SEARCH, 'ELEVATION_TAG', 1),
|
||||
(_PANEL_SEARCH, 'PANEL_TAG', 1),
|
||||
], t)
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'EQUIPMENT_TAG', conf, item)
|
||||
continue
|
||||
|
||||
# ── P&ID / PFD / Isometric / default ──────────────────────────────
|
||||
# ── 1. Specific Engineering Tag Extraction ─────────────────────────────
|
||||
# PSV tags
|
||||
for m in _PSV_SEARCH.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'PSV_TAG', conf, item)
|
||||
item_added = True
|
||||
|
||||
# Line tags
|
||||
for m in _LINE_SEARCH.finditer(t):
|
||||
tag = re.sub(r'\s+', '', m.group(1)).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'LINE_TAG', conf, item)
|
||||
item_added = True
|
||||
|
||||
# Project-prefix tags (instruments + equipment)
|
||||
for m in _PROJECT_TAG_SEARCH.finditer(t):
|
||||
@@ -410,7 +225,7 @@ def classify_paddle_results(
|
||||
code = m.group(2).upper()
|
||||
seq = m.group(3)
|
||||
if len(seq) == 6:
|
||||
continue # Drawing number, skip
|
||||
continue # Drawing reference number, skip
|
||||
if full_tag in found and found[full_tag]['classification'] != 'NOTE':
|
||||
continue
|
||||
if code in _INSTRUMENT_CODES:
|
||||
@@ -423,30 +238,74 @@ def classify_paddle_results(
|
||||
cat = 'EQUIPMENT_TAG'
|
||||
if full_tag not in found:
|
||||
found[full_tag] = _make_item(full_tag, cat, conf, item)
|
||||
item_added = True
|
||||
|
||||
# Bare instrument tags
|
||||
for m in _BARE_INSTRUMENT_SEARCH.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'INSTRUMENT_TAG', conf, item)
|
||||
item_added = True
|
||||
|
||||
# Valve tags
|
||||
for m in _VALVE_SEARCH.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if re.match(r'\d{2}[A-Z]{2}\d{7,}', tag):
|
||||
continue
|
||||
if not re.match(r'\d{2}[A-Z]{2}\d{7,}', tag):
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'VALVE_TAG', conf, item)
|
||||
item_added = True
|
||||
|
||||
# Generic equipment (fallback)
|
||||
# Generic equipment
|
||||
for m in _GENERIC_EQUIP_PATTERN.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
# Skip if already captured as something more specific
|
||||
if tag not in found:
|
||||
# Only add if it actually looks like an equipment tag
|
||||
prefix = tag.split('-')[0]
|
||||
if len(prefix) <= 3 and prefix.isalpha():
|
||||
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()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'ELEVATION_TAG', conf, item)
|
||||
item_added = True
|
||||
|
||||
# Rating tags
|
||||
for m in _RATING_SEARCH.finditer(t):
|
||||
tag = m.group(1).upper()
|
||||
if tag not in found:
|
||||
found[tag] = _make_item(tag, 'RATING', conf, item)
|
||||
item_added = True
|
||||
|
||||
# ── 2. Universal Note Preservation ────────────────────────────────────
|
||||
# If the item did not contain a specific tag, preserve it as a NOTE
|
||||
if not item_added and len(t) >= 3:
|
||||
if t not in found:
|
||||
found[t] = _make_item(t, 'NOTE', conf, item)
|
||||
|
||||
results = list(found.values())
|
||||
|
||||
@@ -460,33 +319,17 @@ def classify_paddle_results(
|
||||
}
|
||||
results.sort(key=lambda x: priority.get(x['classification'], 99))
|
||||
|
||||
# Log summary
|
||||
breakdown = {}
|
||||
for r in results:
|
||||
breakdown[r['classification']] = breakdown.get(r['classification'], 0) + 1
|
||||
logger.info(
|
||||
f"[{dt}] Tag classifier extracted {len(results)} unique tags from "
|
||||
f"[{dt}] Tag classifier extracted {len(results)} total items from "
|
||||
f"{len(items)} OCR items. Breakdown: "
|
||||
+ ', '.join(f"{k}:{v}" for k, v in sorted(breakdown.items()))
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def _scan_and_add(
|
||||
found: Dict,
|
||||
conf: float,
|
||||
item: Dict,
|
||||
patterns: List[tuple],
|
||||
text: str,
|
||||
) -> None:
|
||||
"""Helper: run a list of (pattern, category, group_idx) against text and add matches."""
|
||||
for pat, cat, grp in patterns:
|
||||
for m in pat.finditer(text):
|
||||
tag = m.group(grp).strip()
|
||||
if tag and tag not in found:
|
||||
found[tag] = _make_item(tag, cat, conf, item)
|
||||
|
||||
|
||||
def _make_item(tag: str, classification: str, conf: float, raw_item: dict) -> dict:
|
||||
"""Create a structured classification result dict."""
|
||||
attrs = {
|
||||
@@ -503,65 +346,37 @@ def _make_item(tag: str, classification: str, conf: float, raw_item: dict) -> di
|
||||
}
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
# Metadata extraction from OCR — universal, drawing-type-aware
|
||||
# ──────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
def extract_metadata_from_paddle(
|
||||
items: List[Dict[str, Any]],
|
||||
filename: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
def extract_metadata_from_paddle(items: List[Dict[str, Any]], filename: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Reconstruct drawing metadata from OCR text — no LLM required.
|
||||
Performs drawing-type detection internally using the drawing_type_detector.
|
||||
Extract drawing type, discipline, title, drawing number, and revision from OCR text items.
|
||||
"""
|
||||
from src.utils.drawing_type_detector import detect_drawing_type, DRAWING_TYPE_LABELS
|
||||
dtype = detect_drawing_type(ocr_items=items, filename=filename)
|
||||
info = DRAWING_TYPE_LABELS[dtype]
|
||||
|
||||
all_texts = [i['text'] for i in items if i.get('confidence', 0) > 0.3]
|
||||
dwg_no = "UNKNOWN"
|
||||
title = info["label"]
|
||||
rev = "0"
|
||||
|
||||
# Auto-detect drawing type
|
||||
detected_type = detect_drawing_type(ocr_items=items, filename=filename)
|
||||
type_label = DRAWING_TYPE_LABELS[detected_type]
|
||||
discipline = type_label.get('discipline', 'Unknown')
|
||||
|
||||
# Drawing number: NN-NNNNNN-NNN or similar doc number formats
|
||||
drawing_num = 'UNKNOWN'
|
||||
drawing_pat = re.compile(r'\b(\d{2}-\d{5,6}-\d{3})\b')
|
||||
for t in all_texts:
|
||||
m = drawing_pat.search(t)
|
||||
for item in items:
|
||||
txt = item.get("text", "").strip()
|
||||
if not txt:
|
||||
continue
|
||||
if re.search(r'\b(DWG|DRAWING|DOC)\s*(NO|NUM|\.|\#)?:?\s*([A-Z0-9\-_]{6,30})\b', txt, re.I):
|
||||
m = re.search(r'\b([A-Z0-9\-_]{6,30})\b', txt)
|
||||
if m and len(m.group(1)) > 6:
|
||||
dwg_no = m.group(1)
|
||||
elif "REV" in txt.upper():
|
||||
m = re.search(r'\b(REV\s*[-.:]?\s*[A-Z0-9]{1,3})\b', txt, re.I)
|
||||
if m:
|
||||
drawing_num = m.group(1)
|
||||
break
|
||||
|
||||
# Revision
|
||||
revision = '0'
|
||||
for t in all_texts:
|
||||
m = re.search(r'\bRev\.?\s*([A-Z0-9]{1,3})\b', t, re.IGNORECASE)
|
||||
if m:
|
||||
revision = m.group(1)
|
||||
break
|
||||
|
||||
# Title: longest all-caps string from bottom of image
|
||||
bottom_texts = [
|
||||
i['text'] for i in items
|
||||
if i.get('center_y', 0) > 0.7
|
||||
and i.get('confidence', 0) > 0.4
|
||||
and i['text'].upper() == i['text']
|
||||
and len(i['text']) > 8
|
||||
]
|
||||
if bottom_texts:
|
||||
title = max(bottom_texts, key=len)
|
||||
else:
|
||||
# Fall back to longest high-confidence string anywhere
|
||||
high_conf = [i['text'] for i in items if i.get('confidence', 0) > 0.5 and len(i['text']) > 8]
|
||||
title = max(high_conf, key=len) if high_conf else type_label['label']
|
||||
rev = m.group(1)
|
||||
|
||||
return {
|
||||
'drawing_type': detected_type.value,
|
||||
'discipline': discipline,
|
||||
'drawing_number': drawing_num,
|
||||
'title': title,
|
||||
'revision': revision,
|
||||
'client_name': 'Unknown',
|
||||
'page_count': 1,
|
||||
"drawing_type": dtype.value,
|
||||
"discipline": info["discipline"],
|
||||
"drawing_number": dwg_no,
|
||||
"title": title,
|
||||
"revision": rev,
|
||||
"client_name": "Unknown",
|
||||
"page_count": 1,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user