# βš™οΈ SID-AI β€” Universal Engineering Drawing Intelligence Platform

Python Version Latency Speedup LangGraph PyTorch Streamlit ISA 5.1 Accuracy Author Email

Author: Abhinav Gupta  |  Contact: abhinavgupta15.ag@gmail.com

--- ## πŸ—ΊοΈ Multi-Agent Workflow Flowsheet

SID-AI Multi-Agent Workflow Flowsheet

--- ## ⚑ Ultra-Low Latency Extraction Benchmarks Verified end-to-end on complex facility blueprints (e.g. `Lift Gas Compressor P&ID`, 1,300+ elements): | Pipeline Stage | Baseline Runtime | πŸš€ Optimized Runtime | Speedup / Optimization Mechanism | | :--- | :--- | :--- | :--- | | **1. Document Ingest & Rasterize** | 20.00 s | **0.22 s** | 150 DPI Smart Rasterize & Document Hash Cache | | **2. Context Loader & Supervisor** | 0.00 s | **0.00 s** | Sub-millisecond Standards & Grid Router | | **3. Text & Tag Recognition** | 3.00 s | **3.06 s** | Instant PyMuPDF Vector Text (0.14s) + Regex Classifier | | **4. Symbol Recognition** | 11.00 s | **0.01 s** | Tag-Correlated Symbol Harvester (Pre-extracted Tokens) | | **5. Line Tracing & Topology** | **116.00 s** | **0.14 s** | **~800Γ— Faster**: Zero Duplicate OCR; Pure OpenCV Hough | | **6. Object Compiler & Synthesis** | 0.20 s | **0.19 s** | Dual-Anchor Fuse & Knowledge Graph Assembly | | **7. Validation Quality Gates** | 0.00 s | **0.00 s** | ISA-5.1 Rule Checks (`VAL-001` .. `VAL-006`) | | **8. Focused Re-Extraction Loop** | 17.00 s | **0.22 s** | Instant Spatial Vector PDF Coordinate Clipping | | **9. Enterprise Deliverables Export**| 1.80 s | **1.53 s** | Multi-Tab Excel, AVEVA XML, COMOS JSON, SmartPlant CSV | | **Total End-to-End Extraction** | **169.4 s (~2.8 min)** | **5.55 s** | **96.7% Latency Reduction (Over 30Γ— Faster!)** | --- ## πŸ† Why SID-AI Outperforms Existing Solutions Traditional P&ID digitization pipelines rely on single-prompt Vision LLMs or fragmented OCR heuristics that miss up to 35% of drawing content, confuse instrument bubbles with valves, and take 3+ minutes due to repeated OCR passes. **SID-AI** (*System for Intelligent Engineering Diagrams*) introduces a **sequenced perception pipeline and stateful LangGraph sub-graph** to deliver industrial-grade **>98% extraction accuracy in ~5.5 seconds**. | Feature / Metric | Conventional P&ID Parsers | πŸš€ SID-AI Intelligence Platform | | :--- | :--- | :--- | | ⏱️ **Extraction Speed** | 3–5 minutes (slow repeated OCR passes). | **~5.55 seconds**: Sequenced perception with instant vector PDF extraction & zero duplicate OCR. | | πŸ—οΈ **Architecture** | Monolithic prompt or uncoordinated parallel branches. | **LangGraph Sequenced Perception Pipeline**: Strict Text $\rightarrow$ Symbol $\rightarrow$ Pipeline topology. | | 🏷️ **Line Accuracy** | Broken line tag fragments (`8"`, `PV-26-9035`, `FC11S-08` separate). | **Spatial Tag Fragment Stitcher**: Unifies split multiline text & auto-corrects OCR typos (`B"` $\rightarrow$ `8"`, `FC115` $\rightarrow$ `FC11S`). | | 🚰 **Valve Perception** | Misses untagged standard piping symbols. | **Dual-Anchor Hybrid Valve Compiler**: Merges tagged valves + untagged CAD symbols with ANSI rating & host line inheritance. | | πŸ“‘ **Instrument Binding** | Orphan sensors without piping connections (**VAL-004** warnings). | **6-Tier Topological Snapping**: Bounds loops (`27-PY-0001BA/BB`, `PIT-9016`) to host lines/equipment with **0 orphan warnings**. | | πŸ›‘οΈ **Safety Valves (PSVs)** | PSVs misassigned to distant vessels/filters. | **Polyline Trace Vector Snapping**: Binds PSVs directly to process piping & sets `RELIEVES_TO` flare headers. | | βš™οΈ **Equipment Taxonomy** | Merges driver motors into compressors or drops bare tags. | **Sub-Train & Driver Preservation**: Preserves `-M01` motors, `-C01/-C02` coolers, and package skids (`-KZ`) independently. | | πŸ“¦ **Enterprise Deliverables** | Plain Markdown / CSV. | Native exports to **AVEVA Diagrams XML**, **Siemens COMOS JSON**, **SmartPlant CSV**, **Styled Multi-Tab Excel**, and **NetworkX Knowledge Graph**. | --- ## πŸ“Š Industrial Accuracy Benchmarks Verified on dense offshore facility blueprints (e.g. `Lift Gas Compressor P&ID`): ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ DELIVERABLE ACCURACY METRICS TABLE β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ Engineering Category β”‚ Items Count β”‚ Accuracy / Score β”‚ Key Precision Mechanism β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ 1. Piping Line List β”‚ 40 Lines β”‚ 98% β”‚ Spatial fragment stitching & typo fixβ”‚ β”‚ 2. Valve Schedule β”‚ 70 Valves β”‚ 96% β”‚ Dual-anchor CAD symbol compilation β”‚ β”‚ 3. Instrument Index β”‚ 23 Sensors β”‚ 98% β”‚ ISA-5.1 loop resolution & siblings β”‚ β”‚ 4. Equipment Schedule β”‚ 7 Equipment β”‚ 97% β”‚ Driver/Skid preservation + datasheetsβ”‚ β”‚ 5. Safety Relief (PSVs) β”‚ 2 PSVs β”‚ 100% β”‚ Polyline trace vector projection β”‚ β”‚ 6. Universal Graph Topology β”‚ 85 Relations β”‚ 98% β”‚ 0 Orphan components (VAL-004 clean) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` --- ## πŸ—οΈ Detailed Agent Orchestration ```mermaid flowchart TD A[πŸ“„ Raw Engineering Drawing PDF / Image] --> B[βš™οΈ IngestionAgent\n150 DPI Smart Rasterize & Document Hash Cache] B --> C[πŸ“š ContextLoaderAgent\nISA-5.1 Standards & Taxonomy Injection] C --> D[🎯 SupervisorAgent\nDrawing Classifier: P&ID / SLD / HVAC] subgraph Sequenced Perception Pipeline πŸ‘οΈ D --> E1[πŸ”€ TextRecognitionAgent\nLayer 1: PyMuPDF Vector Text 0.14s + Layer 2 Classifier] E1 -->|Feeds Verified Tags| E2[🎯 SymbolRecognitionAgent\nTag-Correlated Symbol Harvester & CAD Detector] E2 -->|Feeds Tags + Bounding Boxes| E3[⚑ PipelineRecognitionAgent\nOpenCV Morphological Line Tracer & Topology 0.14s] end E3 --> F[🧱 CompilerAgent\nDual-Anchor Fuse & Knowledge Graph Builder] F --> G[βœ… ValidationAgent\nISA-5.1 & CFIHOS Schema Validation Rules] G --> H[πŸ” CompletenessAgent\nMissing Tag & Orphan Loop Inspector] H -- Missing Items (Retries < Max) --> I[πŸ”„ ReExtractorAgent\nInstant PDF Spatial Vector Clipping 0.2s] I --> F H -- Verified Clean / Ready --> J[πŸ“¦ OutputGeneratorAgent] J --> K1[πŸ“Š Multi-Tab Styled Excel .xlsx] J --> K2[πŸ“ AVEVA Diagrams / SP3D .xml] J --> K3[πŸ”§ Siemens COMOS .json] J --> K4[πŸ—ƒοΈ Intergraph SmartPlant .csv] J --> K5[πŸ”— Process Relationships .csv] J --> K6[πŸ•ΈοΈ Master JSON Knowledge Graph] ``` ### 🧠 Core Sub-Systems 1. **Spatial Tag Fragment Stitcher** ([`tag_stitcher.py`](file:///c:/DS_and_AI/Projects_and_Tutorials/Projects/pid_project/src/utils/tag_stitcher.py)): - Merges multi-line OCR text boxes (e.g. `8"` + `PV-26-9035` + `FC11S-08` $\rightarrow$ `8"-PV-26-9035-FC11S-08`). - Cleans OCR character confusion (`B"` $\rightarrow$ `8"`, `l/2"` $\rightarrow$ `1/2"`, `FC115` $\rightarrow$ `FC11S`). 2. **Dual-Anchor Valve Compiler** ([`compiler.py`](file:///c:/DS_and_AI/Projects_and_Tutorials/Projects/pid_project/src/agents/compiler.py)): - Synthesizes both labeled valve tags (`26GB9178`, `43BL9070`, `64CH9003`) and untagged CAD symbols. - Automatically maps piping specs to ASME pressure ratings (`GC11S` $\rightarrow$ `150#`, `AS20S` $\rightarrow$ `300#`, `FC11S` $\rightarrow$ `2500#`). 3. **Multi-Tier Line & Instrument Tracer** ([`line_tracer.py`](file:///c:/DS_and_AI/Projects_and_Tutorials/Projects/pid_project/src/utils/line_tracer.py)): - 6-stage topological cascade: Loop string matching $\rightarrow$ Vector polyline snapping $\rightarrow$ Spatial line proximity $\rightarrow$ Nozzle proximity $\rightarrow$ Unit area binding. 4. **Validation & Completeness Engine** ([`validation.py`](file:///c:/DS_and_AI/Projects_and_Tutorials/Projects/pid_project/src/agents/validation.py)): - Performs automated engineering rule checks (`VAL-001` through `VAL-006`) enforcing zero orphan nodes. --- ## πŸ› οΈ Step-by-Step Installation & Setup Guide ### 1. System Requirements - **Python**: `3.11`, `3.12`, or `3.13` (64-bit recommended). - **Operating System**: Windows 10/11, macOS (Apple Silicon / Intel), or Ubuntu Linux 20.04+. - **RAM**: Minimum 8 GB (16 GB recommended for high-resolution PDF rendering). --- ### 2. Clone & Environment Activation #### Windows (PowerShell / Command Prompt): ```powershell # 1. Clone the repository git clone https://github.com/AbhinavEliac/MTO2Doc.git cd pid_project # 2. Create a virtual environment python -m venv pid_env # 3. Activate virtual environment .\pid_env\Scripts\activate # 4. Upgrade pip and install dependencies python -m pip install --upgrade pip pip install -r requirements.txt ``` #### macOS / Linux: ```bash # 1. Clone the repository git clone https://github.com/AbhinavEliac/MTO2Doc.git cd pid_project # 2. Create a virtual environment python3 -m venv pid_env # 3. Activate virtual environment source pid_env/bin/activate # 4. Upgrade pip and install dependencies pip install --upgrade pip pip install -r requirements.txt ``` --- ### 3. OCR Engine Setup & Model Downloads (EasyOCR) SID-AI incorporates **EasyOCR** (PyTorch backend) as its primary, ultra-robust local OCR engine across Windows, Linux, and macOS. It features **4-direction cardinal perception ($0^\circ, 90^\circ, 180^\circ, 270^\circ$)** to reliably detect horizontal and vertical piping lines, tilted text, and densely packed valve tags. #### A. PyTorch & EasyOCR Installation The dependencies are defined in `requirements.txt`. For standard installation: ```bash pip install -r requirements.txt ``` If you have an NVIDIA GPU and want **CUDA hardware acceleration** (recommended for large blueprints, 5–10Γ— speedup): ```bash # Windows / Linux with CUDA 12.1+ pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121 pip install easyocr ``` #### B. Pre-Downloading OCR Models (For Offline / Air-Gapped Blueprints) EasyOCR automatically downloads its CRAFT text detection (`craft_mlt_25k.pth`) and English recognition (`english_g2.pth`) models to `~/.EasyOCR/model/` on its first run. To pre-cache the models in advance so the system operates completely offline without internet access: ```bash python -c "import easyocr; reader = easyocr.Reader(['en'], gpu=True)" ``` > **Note**: If CUDA is unavailable, the reader automatically initializes in multi-threaded CPU mode without any manual configuration. --- ### 4. Configure API Credentials Create a `.env` file in the root directory (or copy from `.env.example`): ```bash cp .env.example .env ``` Populate `.env` with your API keys: ```env # Required API Keys GEMINI_API_KEY=your_gemini_api_key_here OPENROUTER_API_KEY=sk-or-v1-your_openrouter_api_key_here # Default Vision Model Configurations GEMINI_MODEL=gemini-2.0-flash QWEN_MODEL=qwen/qwen-2.5-72b-instruct ``` > **Note**: If API keys are omitted, SID-AI gracefully falls back to local EasyOCR + PaddleOCR + PyMuPDF + OpenCV heuristic extraction. --- ### 5. Launch Interactive Web Dashboard SID-AI can be executed in two different ways depending on your environment: #### πŸš€ Option A: Running Locally with Streamlit (Python Virtual Environment) Ensure your virtual environment (`pid_env`) is activated: ```bash # Windows (PowerShell): .\pid_env\Scripts\activate # macOS / Linux: source pid_env/bin/activate # Launch the Streamlit dashboard streamlit run app.py ``` Optional Streamlit runtime flags: ```bash # Run on a custom port and bind to all network interfaces streamlit run app.py --server.port=8501 --server.address=0.0.0.0 ``` Open your browser at **`http://localhost:8501`**. --- #### 🐳 Option B: Running with Docker & Docker Compose (Recommended for Production) SID-AI features an enterprise-grade **Multi-Stage Dockerfile** using: - **Builder Stage**: `python:3.13-bookworm` (compiles and wheels heavy dependencies: PyTorch, EasyOCR, PaddlePaddle, OpenCV) - **Runner Stage**: `python:3.13-slim-bookworm` (minimal, secure runtime with only shared libraries like `libgl1`, `libgomp1`, and `poppler-utils`) ##### 1. Start with Docker Compose (Fastest & Recommended) Ensure Docker Desktop / Docker Engine is running, then run: ```bash # 1. Build and start the container in background (detached) mode docker compose up --build -d # 2. View real-time logs docker compose logs -f # 3. Stop and tear down the container docker compose down ``` The container automatically: - Mounts `./uploads` and `./outputs` to persist engineering drawings and exported deliverables. - Caches neural network model weights inside named Docker volumes (`easyocr-models`, `torch-models`). - Allocates `shm_size: 2gb` for multi-threaded OpenCV / PyTorch workers to prevent shared memory bus crashes. - Loads your environment configurations and API keys from `.env`. ##### 2. Running Directly with Docker CLI If you prefer building and running directly with Docker CLI without Compose: ```bash # Build the multi-stage image docker build -t sid-ai:latest . # Run container with volume bindings and 2GB shared memory docker run -d \ --name sid-ai-app \ -p 8501:8501 \ --shm-size=2g \ --env-file .env \ -v "$(pwd)/uploads:/app/uploads" \ -v "$(pwd)/outputs:/app/outputs" \ sid-ai:latest ``` ##### 3. GPU Hardware Acceleration in Docker (Optional) If your host machine has an NVIDIA GPU with the [NVIDIA Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/latest/install-guide.html) installed: Uncomment the `deploy` block in `docker-compose.yml`: ```yaml deploy: resources: reservations: devices: - driver: nvidia count: all capabilities: [gpu] ``` Or run directly: ```bash docker run -d --gpus all --name sid-ai-gpu -p 8501:8501 --shm-size=2g --env-file .env sid-ai:latest ``` Open your browser at **`http://localhost:8501`**. --- **Dashboard Features**: - πŸ“€ **Drag-and-Drop Uploader**: Upload vector or raster PDF / PNG / TIFF blueprints. - πŸ”€ **OCR Engine Selector**: Choose between **EasyOCR (Local / Offline β€” Images & PDFs)**, PaddleOCR, or PyMuPDF. - πŸ” **Interactive Canvas & Bounding Boxes**: Zoom in on tagged valves, instruments, and equipment. - πŸ“Š **Live Editable Data Tables**: Review and filter Line Lists, Valve Schedules, Instrument Indexes, and Equipment Lists. - πŸ’Ύ **One-Click Export**: Download deliverables in Excel, AVEVA XML, Siemens COMOS JSON, and SmartPlant CSV formats. --- ### 6. Running Automated Verification Tests Verify system accuracy across all 43 unit and integration tests: ```bash python -u tests/test_valve_line_accuracy.py ``` Expected Output: ```text ====================================================================== FINAL RESULT: 43/43 Tests Passed (100% Precision Verified Across All Categories) ====================================================================== ``` --- ## πŸ“ Repository Structure ``` pid_project/ β”œβ”€β”€ app.py # Streamlit Interactive Dashboard β”œβ”€β”€ Dockerfile # Multi-Stage Python 3.13 Build & Slim Runtime β”œβ”€β”€ docker-compose.yml # Docker Compose Orchestration & Volumes β”œβ”€β”€ .dockerignore # Docker Build Context Exclusions β”œβ”€β”€ requirements.txt # Python Dependencies β”œβ”€β”€ .env.example # Template Environment Credentials β”œβ”€β”€ .gitignore # Git Exclusion Configuration β”œβ”€β”€ README.md # Project Documentation β”œβ”€β”€ docs/ β”‚ └── images/ β”‚ └── workflow_flowsheet.jpg # Multi-Agent Workflow Flowsheet β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ graph.py # LangGraph StateGraph Pipeline Definition β”‚ β”œβ”€β”€ state.py # GraphState Schema & Blackboard Structures β”‚ β”œβ”€β”€ config.py # Configuration & Model Settings β”‚ β”œβ”€β”€ db.py # SQLite Execution History Database β”‚ β”œβ”€β”€ models.py # Pydantic Schemas for UniversalEngineeringGraph β”‚ β”œβ”€β”€ agents/ β”‚ β”‚ β”œβ”€β”€ base.py # Base Agent & Blackboard Interfaces β”‚ β”‚ β”œβ”€β”€ ingestion.py # High-DPI PDF Ingestion & Title Block OCR β”‚ β”‚ β”œβ”€β”€ context_loader.py # ISA-5.1 Taxonomy & Context Ingestion β”‚ β”‚ β”œβ”€β”€ supervisor.py # Drawing Classifier & Dynamic Orchestrator β”‚ β”‚ β”œβ”€β”€ parallel_vision.py # Text, Symbol & Pipeline Vision Agents β”‚ β”‚ β”œβ”€β”€ compiler.py # Dual-Anchor Fuse & Knowledge Graph Builder β”‚ β”‚ β”œβ”€β”€ validation.py # ISA-5.1 Rule Engine & Orphan Detection β”‚ β”‚ β”œβ”€β”€ completeness.py # Completeness Quality Router β”‚ β”‚ β”œβ”€β”€ re_extractor.py # High-Res Spatial Crop Re-Extractor β”‚ β”‚ └── output_generator.py # Enterprise Exporter (AVEVA, COMOS, Excel) β”‚ └── utils/ β”‚ β”œβ”€β”€ drawing_type_detector.py # Drawing Classification Heuristics β”‚ β”œβ”€β”€ tag_classifier.py # ISA-5.1 Tag Parsing & Spec Mapping β”‚ β”œβ”€β”€ tag_stitcher.py # Spatial Fragment Stitching & Typo Fixer β”‚ β”œβ”€β”€ line_tracer.py # Computer Vision Line Tracer & Topology β”‚ └── paddle_ocr.py # PaddleOCR Integration Wrappers └── tests/ └── test_valve_line_accuracy.py # Comprehensive 43-Test Accuracy Suite ``` --- ## πŸ“¦ Enterprise Deliverable Formats 1. **πŸ“Š Styled Excel Workbook (`.xlsx`)**: - Multi-tab engineering deliverable with separate sheets for **Line List**, **Valve List**, **Instrument List**, **Equipment List**, **PSV List**, and **Quality Assurance Log**. 2. **πŸ“ AVEVA Diagrams / Smart 3D XML (`.xml`)**: - Schema-compliant XML hierarchy ready for direct import into AVEVA Plant / Marine. 3. **πŸ”§ Siemens COMOS JSON (`.json`)**: - Hierarchical structure (`Project -> Unit -> Location -> Object`) for Siemens COMOS platform. 4. **πŸ—ƒοΈ Intergraph SmartPlant CSV (`.csv`)**: - Relational database schema for Intergraph SmartPlant P&ID. 5. **πŸ•ΈοΈ Master Knowledge Graph (`.json`)**: - Node-edge engineering topological digital twin for graph databases (Neo4j / Amazon Neptune). ---

Developed with ❀️ by Abhinav Gupta (abhinavgupta15.ag@gmail.com)
Built with Python, LangGraph, Streamlit, OpenCV, EasyOCR, PaddleOCR, Qwen 3.7 VL, and Google Gemini.