diff --git a/.gitignore b/.gitignore index 94684f2..c9f1f5e 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,8 @@ uploads/ outputs/ rasterized/ *.log +*.db +extraction_history.db install_log.txt # Scratch & debug scripts diff --git a/app.py b/app.py index cdc1f42..db84c81 100644 --- a/app.py +++ b/app.py @@ -1,16 +1,36 @@ """ SID-AI — Universal Engineering Drawing Intelligence Dashboard. -Supports any drawing type: P&ID, Electrical Layout, Earthing Layout, -SLD, HVAC, Structural, Cable Schedule, and Generic drawings. -The dashboard adapts its tabs and columns based on the detected drawing type. +Supports thread persistence in SQLite, background extraction execution, +live progress tracking, cancel functionality, and historical error logs. """ import os +import time +import uuid +import logging +from datetime import datetime import streamlit as st import pandas as pd from PIL import Image -from src.graph import create_workflow + +from src.models import UniversalEngineeringGraph from src.state import GraphState +from src.db import ( + init_db, + get_all_threads, + get_thread, + delete_thread, +) +from src.thread_manager import ( + start_extraction_thread, + cancel_extraction_thread, + is_thread_active, +) + +logger = logging.getLogger(__name__) + +# Initialize SQLite Database on app load +init_db() # ─── Page Configuration ──────────────────────────────────────────────────────── st.set_page_config( @@ -91,7 +111,17 @@ st.markdown(""" padding-bottom: 8px; margin: 24px 0 16px 0; } - .stDataFrame { border-radius: 8px; overflow: hidden; } + .thread-card { + background: #ffffff; + border: 1px solid #e0e0e0; + border-radius: 8px; + padding: 10px; + margin-bottom: 8px; + } + .status-completed { color: #2e7d32; font-weight: 600; } + .status-running { color: #1565c0; font-weight: 600; } + .status-failed { color: #c62828; font-weight: 600; } + .status-cancelled { color: #e65100; font-weight: 600; } """, unsafe_allow_html=True) @@ -103,7 +133,52 @@ st.markdown( unsafe_allow_html=True, ) +# Fetch all saved threads from SQLite +all_threads = get_all_threads() + +# Initialize session state for selected thread +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("## 🧵 Generation Threads") + +if all_threads: + for t in all_threads: + tid = t["thread_id"] + status = t["status"] + fname = t.get("filename", "Drawing") + dt_label = t.get("drawing_type", "GENERIC") + created = t.get("created_at", "")[:19].replace("T", " ") + + status_icon = "🟢" if status == "COMPLETED" else "🔵" if status == "RUNNING" else "❌" if status == "FAILED" else "⛔" + prog_str = f" ({int(t.get('progress', 0)*100)}%)" if status == "RUNNING" else "" + + col_t1, col_t2 = st.sidebar.columns([0.8, 0.2]) + with col_t1: + button_label = f"{status_icon} {fname[:18]}...{prog_str}" + is_active = (st.session_state.get("active_thread_id") == tid) + if st.button( + button_label, + key=f"btn_thread_{tid}", + use_container_width=True, + type="primary" if is_active else "secondary", + help=f"Type: {dt_label} | Status: {status} | Created: {created}", + ): + st.session_state["active_thread_id"] = tid + st.rerun() + + with col_t2: + if st.button("🗑️", key=f"del_thread_{tid}", help=f"Delete thread '{fname}' and its log"): + delete_thread(tid) + if st.session_state.get("active_thread_id") == tid: + remaining = [x for x in all_threads if x["thread_id"] != tid] + st.session_state["active_thread_id"] = remaining[0]["thread_id"] if remaining else None + st.rerun() +else: + st.sidebar.info("No previous extraction threads found.") + +st.sidebar.markdown("---") st.sidebar.markdown("## ⚙️ 2-Layer Extraction Pipeline") max_retries = st.sidebar.slider( @@ -152,7 +227,6 @@ reasoning_engine_map = { } reasoning_engine = reasoning_engine_map.get(reasoning_option, "qwen") -# Dynamic LLM Provider configuration for Qwen 2.5 (OpenRouter) / OpenAI / Custom Endpoints llm_provider = "gemini" llm_api_key = None llm_base_url = None @@ -199,471 +273,552 @@ local_mode = st.sidebar.checkbox( if local_mode: st.sidebar.info("🔌 Full Offline Mode forced — PaddleOCR + Regex Classifier. Zero API tokens.") -st.sidebar.markdown("---") -st.sidebar.markdown("### 📋 Supported Drawing Types") -st.sidebar.markdown(""" -- **P&ID** — Piping & Instrumentation -- **Electrical Layout** — Lighting / Power -- **Earthing Layout** — Grounding / Bonding -- **SLD** — Single Line Diagram -- **HVAC Layout** — Ventilation / Air Handling -- **Structural** — Civil / Framing Plans -- **Cable Schedule** — Cable Routing -- **Generic** — Any other drawing -""") +# ─── Main Content Tabs: Dashboard vs History ─────────────────────────────────── +tab_main_dashboard, tab_main_history = st.tabs([ + "📊 Current Extraction Dashboard", + "📜 Generation History & Error Logs", +]) -# ─── File Upload ─────────────────────────────────────────────────────────────── -st.markdown("
📂 Document Upload
", unsafe_allow_html=True) -col1, col2 = st.columns(2) +# ─── TAB 1: CURRENT EXTRACTION DASHBOARD ─────────────────────────────────────── +with tab_main_dashboard: + # Upload Section + st.markdown("
📂 Document Upload & Extraction Trigger
", unsafe_allow_html=True) + col1, col2 = st.columns(2) -with col1: - uploaded_drawing = st.file_uploader( - "Upload Engineering Drawing (PDF, PNG, JPG)", - type=["pdf", "png", "jpg", "jpeg"], - help="Upload any engineering drawing — P&ID, Electrical Layout, Earthing, SLD, HVAC, Structural, etc.", + with col1: + uploaded_drawing = st.file_uploader( + "Upload Engineering Drawing (PDF, PNG, JPG)", + type=["pdf", "png", "jpg", "jpeg"], + help="Upload any engineering drawing — P&ID, Electrical Layout, Earthing, SLD, HVAC, Structural, etc.", + ) + + with col2: + uploaded_refs = st.file_uploader( + "Upload Legend Sheets or Reference Documents (Optional)", + type=["pdf", "png", "jpg"], + accept_multiple_files=True, + help="Provide symbol legends, client coding standards, or specification sheets.", + ) + + run_pipeline = st.button( + "🚀 Run Extraction Pipeline", + type="primary", + disabled=(uploaded_drawing is None), ) -with col2: - uploaded_refs = st.file_uploader( - "Upload Legend Sheets or Reference Documents (Optional)", - type=["pdf", "png", "jpg"], - accept_multiple_files=True, - help="Provide symbol legends, client coding standards, or specification sheets.", - ) + if run_pipeline and uploaded_drawing: + temp_dir = os.path.join(os.getcwd(), "uploads") + os.makedirs(temp_dir, exist_ok=True) -# ─── Run Button ──────────────────────────────────────────────────────────────── -run_pipeline = st.button( - "🚀 Run Extraction Pipeline", - type="primary", - disabled=(uploaded_drawing is None), -) + drawing_path = os.path.join(temp_dir, uploaded_drawing.name) + with open(drawing_path, "wb") as f: + f.write(uploaded_drawing.read()) -# ─── Pipeline Execution ──────────────────────────────────────────────────────── -if run_pipeline and uploaded_drawing: - temp_dir = os.path.join(os.getcwd(), "uploads") - os.makedirs(temp_dir, exist_ok=True) + ref_paths = [] + for ref in uploaded_refs: + ref_path = os.path.join(temp_dir, ref.name) + with open(ref_path, "wb") as f: + f.write(ref.read()) + ref_paths.append(ref_path) - drawing_path = os.path.join(temp_dir, uploaded_drawing.name) - with open(drawing_path, "wb") as f: - f.write(uploaded_drawing.read()) + raw_docs = [drawing_path] + ref_paths - ref_paths = [] - for ref in uploaded_refs: - ref_path = os.path.join(temp_dir, ref.name) - with open(ref_path, "wb") as f: - f.write(ref.read()) - ref_paths.append(ref_path) + new_thread_id = f"thread_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" - raw_docs = [drawing_path] + ref_paths + initial_state: GraphState = { + "raw_documents": raw_docs, + "metadata": {}, + "engineering_context": {}, + "extracted_entities": { + "text_elements": [], + "symbols": [], + "relations": [], + "geometry": {}, + }, + "engineering_graph": None, + "validation_reports": [], + "missing_entities": [], + "revision_history": [], + "deliverables": {}, + "re_extraction_count": 0, + "max_re_extractions": max_retries, + "ocr_engine": ocr_engine, + "reasoning_engine": reasoning_engine, + "llm_provider": llm_provider, + "llm_model": llm_model, + "llm_api_key": llm_api_key, + "llm_base_url": llm_base_url, + "use_mocks": use_mocks, + "local_mode": local_mode or (reasoning_engine == "rule_based" and ocr_engine in ("paddle", "pdf_text")), + "re_extracted_targets": [], + } - initial_state: GraphState = { - "raw_documents": raw_docs, - "metadata": {}, - "engineering_context": {}, - "extracted_entities": { - "text_elements": [], - "symbols": [], - "relations": [], - "geometry": {}, - }, - "engineering_graph": None, - "validation_reports": [], - "missing_entities": [], - "revision_history": [], - "deliverables": {}, - "re_extraction_count": 0, - "max_re_extractions": max_retries, - "ocr_engine": ocr_engine, - "reasoning_engine": reasoning_engine, - "llm_provider": llm_provider, - "llm_model": llm_model, - "llm_api_key": llm_api_key, - "llm_base_url": llm_base_url, - "use_mocks": use_mocks, - "local_mode": local_mode or (reasoning_engine == "rule_based" and ocr_engine in ("paddle", "pdf_text")), - "re_extracted_targets": [], - } + # Start asynchronous background thread + start_extraction_thread( + thread_id=new_thread_id, + initial_state=initial_state, + filename=uploaded_drawing.name, + ) + st.session_state["active_thread_id"] = new_thread_id + st.rerun() - with st.spinner("🔍 Agent workflow running — ingesting, detecting drawing type, and extracting entities…"): - try: - workflow = create_workflow() - app = workflow.compile() - final_state = app.invoke(initial_state) - st.session_state["pipeline_results"] = final_state - st.success("✅ Pipeline Execution Completed Successfully!") - except Exception as e: - st.error(f"Pipeline execution error: {e}") - import traceback - st.code(traceback.format_exc()) + # Render selected thread dashboard + active_id = st.session_state.get("active_thread_id") + if active_id: + active_thread = get_thread(active_id) + if active_thread: + status = active_thread.get("status") + progress = active_thread.get("progress", 0.0) + current_step = active_thread.get("current_step", "") + fname = active_thread.get("filename", "") -# ─── Results Dashboard ───────────────────────────────────────────────────────── -if "pipeline_results" in st.session_state: - state = st.session_state["pipeline_results"] - metadata = state.get("metadata", {}) - graph = state.get("engineering_graph") - reports = state.get("validation_reports", []) - deliverables = state.get("deliverables", {}) - re_runs = state.get("re_extraction_count", 0) - revision_history = state.get("revision_history", []) + # ── Active Process & Progress Bar ───────────────────────────────── + if status == "RUNNING" or status == "QUEUED": + st.markdown("
⚡ Active Subprocess Progress
", unsafe_allow_html=True) + col_p1, col_p2 = st.columns([0.8, 0.2]) + with col_p1: + st.progress(progress) + st.info(f"⏳ **Active Subprocess:** `{current_step}` ({int(progress*100)}%) — File: *{fname}*") + with col_p2: + if st.button("🛑 Cancel Process", type="secondary", use_container_width=True): + cancel_extraction_thread(active_id) + st.rerun() - drawing_type = metadata.get("drawing_type", "GENERIC") - discipline = metadata.get("discipline", "Unknown") + # Auto refresh UI while processing + time.sleep(1.5) + st.rerun() - # Drawing type badge - from src.utils.drawing_type_detector import DRAWING_TYPE_LABELS, DrawingType - try: - dtype_enum = DrawingType(drawing_type) - dtype_info = DRAWING_TYPE_LABELS.get(dtype_enum, {"label": drawing_type, "icon": "📋", "discipline": discipline}) - except Exception: - dtype_info = {"label": drawing_type, "icon": "📋", "discipline": discipline} + elif status == "CANCELLED": + st.warning(f"⛔ Extraction process for '{fname}' was cancelled by user.") + elif status == "FAILED": + st.error(f"❌ Extraction process for '{fname}' failed: {active_thread.get('error_message')}") - st.markdown( - f"
{dtype_info['icon']} {dtype_info['label']}" - f"{discipline}
", - unsafe_allow_html=True, - ) + # ── Dashboard Results Rendering ─────────────────────────────────── + result_state = active_thread.get("result") + if result_state: + metadata = result_state.get("metadata", {}) + raw_graph_data = result_state.get("engineering_graph") - # ── Metadata Block ──────────────────────────────────────────────────────── - st.markdown("
📋 Drawing Metadata
", unsafe_allow_html=True) - col_m1, col_m2, col_m3, col_m4, col_m5 = st.columns(5) + graph = None + if raw_graph_data: + if isinstance(raw_graph_data, dict): + graph = UniversalEngineeringGraph(**raw_graph_data) + else: + graph = raw_graph_data - with col_m1: - st.markdown(f"
Drawing Title
{metadata.get('title', 'N/A')}
", unsafe_allow_html=True) - with col_m2: - st.markdown(f"
Drawing Number
{metadata.get('drawing_number', 'N/A')}
", unsafe_allow_html=True) - with col_m3: - st.markdown(f"
Revision
{metadata.get('revision', 'N/A')}
", unsafe_allow_html=True) - with col_m4: - st.markdown(f"
Discipline
{metadata.get('discipline', 'N/A')}
", unsafe_allow_html=True) - with col_m5: - st.markdown(f"
Client
{metadata.get('client_name', 'N/A')}
", unsafe_allow_html=True) + reports = result_state.get("validation_reports", []) + deliverables = result_state.get("deliverables", {}) + re_runs = result_state.get("re_extraction_count", 0) + revision_history = result_state.get("revision_history", []) - # ── Extracted Deliverables — Dynamic Tabs ───────────────────────────────── - if graph: - st.markdown("
📊 Extracted Data
", unsafe_allow_html=True) + drawing_type = active_thread.get("drawing_type") or metadata.get("drawing_type", "GENERIC") + discipline = active_thread.get("discipline") or metadata.get("discipline", "Unknown") - dt = drawing_type.upper() + from src.utils.drawing_type_detector import DRAWING_TYPE_LABELS, DrawingType + try: + dtype_enum = DrawingType(drawing_type) + dtype_info = DRAWING_TYPE_LABELS.get(dtype_enum, {"label": drawing_type, "icon": "📋", "discipline": discipline}) + except Exception: + dtype_info = {"label": drawing_type, "icon": "📋", "discipline": discipline} - # ── P&ID / PFD / Isometric ───────────────────────────────────────────── - if dt in ('PID', 'PFD', 'ISOMETRIC'): - tab_line, tab_inst, tab_valve, tab_psv, tab_eq = st.tabs([ - f"📏 Line List ({len(graph.lines)})", - f"🔵 Instrument List ({len(graph.instruments)})", - f"🔧 Valve List ({len(graph.valves)})", - f"🛡️ Safety Relief Valves ({len(graph.safety_relief_valves)})", - f"⚙️ Equipment List ({len(graph.equipment)})", - ]) - - with tab_line: - st.subheader("Line List (Piping Segments)") - if graph.lines: - df = pd.DataFrame([l.model_dump() for l in graph.lines]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No piping lines detected.") - - with tab_inst: - st.subheader("Instrument List") - if graph.instruments: - df = pd.DataFrame([i.model_dump() for i in graph.instruments]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No instruments detected.") - - with tab_valve: - st.subheader("Manual Valve List") - if graph.valves: - df = pd.DataFrame([v.model_dump() for v in graph.valves]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No valves detected.") - - with tab_psv: - st.subheader("Safety Relief Valve List") - if graph.safety_relief_valves: - df = pd.DataFrame([p.model_dump() for p in graph.safety_relief_valves]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No safety relief valves detected.") - - with tab_eq: - st.subheader("Equipment List") - if graph.equipment: - df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No equipment detected.") - - # ── Electrical Layout ────────────────────────────────────────────────── - elif dt == 'ELECTRICAL_LAYOUT': - tab_lum, tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([ - f"💡 Luminaires ({len(graph.luminaires)})", - f"⚡ Distribution Boards ({len(graph.panels)})", - f"🔌 Cables & Circuits ({len(graph.cables)})", - f"⚙️ Equipment ({len(graph.equipment)})", - f"📝 Annotations ({len(graph.annotations)})", - ]) - - with tab_lum: - st.subheader("Luminaire / Lighting Fitting List") - if graph.luminaires: - df = pd.DataFrame([l.model_dump() for l in graph.luminaires]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No luminaires detected.") - - with tab_panel: - st.subheader("Distribution Boards & Panels") - if graph.panels: - df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No panels/DBs detected.") - - with tab_cable: - st.subheader("Cables & Circuits") - if graph.cables: - df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No cables/circuits detected.") - - with tab_eq: - st.subheader("Equipment List") - if graph.equipment: - df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No equipment detected.") - - with tab_ann: - st.subheader("Elevation Labels & Annotations") - if graph.annotations: - df = pd.DataFrame([a.model_dump() for a in graph.annotations]) - st.dataframe(df, use_container_width=True) - else: - st.info("No annotations detected.") - - # ── Earthing Layout ──────────────────────────────────────────────────── - elif dt == 'EARTHING_LAYOUT': - tab_earth, tab_eq, tab_ann = st.tabs([ - f"⏚ Earthing Components ({len(graph.earthing_components)})", - f"⚙️ Equipment / Structures ({len(graph.equipment)})", - f"📝 Notes & Elevations ({len(graph.annotations)})", - ]) - - with tab_earth: - st.subheader("Earthing Components (Bars, Pits, Conductors)") - if graph.earthing_components: - df = pd.DataFrame([e.model_dump() for e in graph.earthing_components]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No earthing components detected.") - - with tab_eq: - st.subheader("Earthed Equipment & Structures") - if graph.equipment: - df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No equipment detected.") - - with tab_ann: - st.subheader("Installation Notes & Elevation Labels") - if graph.annotations: - df = pd.DataFrame([a.model_dump() for a in graph.annotations]) - st.dataframe(df, use_container_width=True) - else: - st.info("No annotations detected.") - - # ── SLD ─────────────────────────────────────────────────────────────── - elif dt == 'SLD': - tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([ - f"🏗️ Switchgear & Panels ({len(graph.panels)})", - f"🔌 Feeders & Breakers ({len(graph.cables)})", - f"⚙️ Loads & Equipment ({len(graph.equipment)})", - f"📝 Ratings & Notes ({len(graph.annotations)})", - ]) - - with tab_panel: - st.subheader("Switchgear, Busbars & Panels") - if graph.panels: - df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No panels detected.") - - with tab_cable: - st.subheader("Feeders & Circuit Breakers") - if graph.cables: - df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No feeders/breakers detected.") - - with tab_eq: - st.subheader("Loads & Equipment") - if graph.equipment: - df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No equipment detected.") - - with tab_ann: - st.subheader("Ratings & Notes") - if graph.annotations: - df = pd.DataFrame([a.model_dump() for a in graph.annotations]) - st.dataframe(df, use_container_width=True) - else: - st.info("No annotations detected.") - - # ── Cable Schedule ───────────────────────────────────────────────────── - elif dt == 'CABLE_SCHEDULE': - tab_cable, tab_panel, tab_ann = st.tabs([ - f"🔌 Cable Schedule ({len(graph.cables)})", - f"⚡ Panels ({len(graph.panels)})", - f"📝 Notes ({len(graph.annotations)})", - ]) - with tab_cable: - if graph.cables: - df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No cables detected.") - with tab_panel: - if graph.panels: - df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No panels detected.") - with tab_ann: - if graph.annotations: - df = pd.DataFrame([a.model_dump() for a in graph.annotations]) - st.dataframe(df, use_container_width=True) - else: - st.info("No annotations detected.") - - # ── HVAC / Structural / Generic ──────────────────────────────────────── - else: - tab_eq, tab_generic, tab_ann = st.tabs([ - f"⚙️ Equipment ({len(graph.equipment)})", - f"🔩 Components ({len(graph.generic_components)})", - f"📝 Notes & Annotations ({len(graph.annotations)})", - ]) - - with tab_eq: - st.subheader("Equipment List") - if graph.equipment: - df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No equipment detected.") - - with tab_generic: - st.subheader("Detected Components") - if graph.generic_components: - df = pd.DataFrame([g.model_dump() for g in graph.generic_components]).drop(columns=["coordinates"], errors="ignore") - st.dataframe(df, use_container_width=True) - else: - st.info("No components detected.") - - with tab_ann: - st.subheader("Annotations & Notes") - if graph.annotations: - df = pd.DataFrame([a.model_dump() for a in graph.annotations]) - st.dataframe(df, use_container_width=True) - else: - st.info("No annotations detected.") - - # ── Relationships ────────────────────────────────────────────────────── - if graph.relationships: - with st.expander(f"🔗 Engineering Relationships ({len(graph.relationships)})"): - df = pd.DataFrame([r.model_dump() for r in graph.relationships]) - st.dataframe(df, use_container_width=True) - - # ── QA & Validation ─────────────────────────────────────────────────────── - st.markdown("
🔍 Quality Assurance & Validation Logs
", unsafe_allow_html=True) - col_v1, col_v2 = st.columns(2) - - with col_v1: - st.subheader("Consistency Errors & Warnings") - if reports: - for r in reports: - icon = "❌" if r["severity"] == "ERROR" else "⚠️" - bg_color = "#FDF2F2" if r["severity"] == "ERROR" else "#FEFBF0" - border_color = "#F05252" if r["severity"] == "ERROR" else "#FACA15" - st.markdown(f""" -
- {icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})
- {r['message']} -
- """, unsafe_allow_html=True) - else: - st.success("✓ No validation discrepancies identified.") - - with col_v2: - st.subheader("Extraction Process Log") - st.markdown(f"**Re-extraction Loops:** `{re_runs}` / `{max_retries}`") - st.markdown("**Revision History:**") - for log in revision_history: - action = log.get("action", str(log)) - st.markdown(f"- {action}") - - # ── Download Section ─────────────────────────────────────────────────────── - st.markdown("
📥 Export & Download
", unsafe_allow_html=True) - st.markdown("Download deliverables formatted for standard engineering platforms:") - - col_d1, col_d2, col_d3, col_d4, col_d5 = st.columns(5) - - if deliverables: - if "excel" in deliverables and os.path.exists(deliverables["excel"]): - with open(deliverables["excel"], "rb") as f: - col_d1.download_button( - "📊 Excel Deliverables", - data=f.read(), - file_name="engineering_deliverables.xlsx", - mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - use_container_width=True, + st.markdown( + f"
{dtype_info['icon']} {dtype_info['label']}" + f"{discipline}
", + unsafe_allow_html=True, ) - if "json_graph" in deliverables and os.path.exists(deliverables["json_graph"]): - with open(deliverables["json_graph"], "rb") as f: - col_d2.download_button( - "🕸️ JSON Graph", - data=f.read(), - file_name="master_graph.json", - mime="application/json", - use_container_width=True, - ) + # Metadata Block + st.markdown("
📋 Drawing Metadata
", unsafe_allow_html=True) + col_m1, col_m2, col_m3, col_m4, col_m5 = st.columns(5) + with col_m1: + st.markdown(f"
Drawing Title
{metadata.get('title', 'N/A')}
", unsafe_allow_html=True) + with col_m2: + st.markdown(f"
Drawing Number
{metadata.get('drawing_number', 'N/A')}
", unsafe_allow_html=True) + with col_m3: + st.markdown(f"
Revision
{metadata.get('revision', 'N/A')}
", unsafe_allow_html=True) + with col_m4: + st.markdown(f"
Discipline
{metadata.get('discipline', 'N/A')}
", unsafe_allow_html=True) + with col_m5: + st.markdown(f"
Client
{metadata.get('client_name', 'N/A')}
", unsafe_allow_html=True) - if "aveva_xml" in deliverables and os.path.exists(deliverables["aveva_xml"]): - with open(deliverables["aveva_xml"], "rb") as f: - col_d3.download_button( - "📐 AVEVA XML", - data=f.read(), - file_name="aveva_diagrams_export.xml", - mime="application/xml", - use_container_width=True, - ) + # Extracted Data Tabs + if graph: + st.markdown("
📊 Extracted Data
", unsafe_allow_html=True) + dt = drawing_type.upper() - if "comos_json" in deliverables and os.path.exists(deliverables["comos_json"]): - with open(deliverables["comos_json"], "rb") as f: - col_d4.download_button( - "🔧 COMOS JSON", - data=f.read(), - file_name="comos_hierarchy_export.json", - mime="application/json", - use_container_width=True, - ) + if dt in ('PID', 'PFD', 'ISOMETRIC'): + tab_line, tab_inst, tab_valve, tab_psv, tab_eq = st.tabs([ + f"📏 Line List ({len(graph.lines)})", + f"🔵 Instrument List ({len(graph.instruments)})", + f"🔧 Valve List ({len(graph.valves)})", + f"🛡️ Safety Relief Valves ({len(graph.safety_relief_valves)})", + f"⚙️ Equipment List ({len(graph.equipment)})", + ]) + with tab_line: + st.subheader("Line List (Piping Segments)") + if graph.lines: + df = pd.DataFrame([l.model_dump() for l in graph.lines]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No piping lines detected.") - if "sppid_csv" in deliverables and os.path.exists(deliverables["sppid_csv"]): - with open(deliverables["sppid_csv"], "rb") as f: - col_d5.download_button( - "🗃️ SmartPlant CSV", - data=f.read(), - file_name="sppid_import_tables.csv", - mime="text/csv", - use_container_width=True, - ) + with tab_inst: + st.subheader("Instrument List") + if graph.instruments: + df = pd.DataFrame([i.model_dump() for i in graph.instruments]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No instruments detected.") + + with tab_valve: + st.subheader("Manual Valve List") + if graph.valves: + df = pd.DataFrame([v.model_dump() for v in graph.valves]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No valves detected.") + + with tab_psv: + st.subheader("Safety Relief Valve List") + if graph.safety_relief_valves: + df = pd.DataFrame([p.model_dump() for p in graph.safety_relief_valves]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No safety relief valves detected.") + + with tab_eq: + st.subheader("Equipment List") + if graph.equipment: + df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No equipment detected.") + + elif dt == 'ELECTRICAL_LAYOUT': + tab_lum, tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([ + f"💡 Luminaires ({len(graph.luminaires)})", + f"⚡ Distribution Boards ({len(graph.panels)})", + f"🔌 Cables & Circuits ({len(graph.cables)})", + f"⚙️ Equipment ({len(graph.equipment)})", + f"📝 Annotations ({len(graph.annotations)})", + ]) + with tab_lum: + st.subheader("Luminaire / Lighting Fitting List") + if graph.luminaires: + df = pd.DataFrame([l.model_dump() for l in graph.luminaires]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No luminaires detected.") + + with tab_panel: + st.subheader("Distribution Boards & Panels") + if graph.panels: + df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No panels/DBs detected.") + + with tab_cable: + st.subheader("Cables & Circuits") + if graph.cables: + df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No cables/circuits detected.") + + with tab_eq: + st.subheader("Equipment List") + if graph.equipment: + df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No equipment detected.") + + with tab_ann: + st.subheader("Elevation Labels & Annotations") + if graph.annotations: + df = pd.DataFrame([a.model_dump() for a in graph.annotations]) + st.dataframe(df, use_container_width=True) + else: + st.info("No annotations detected.") + + elif dt == 'EARTHING_LAYOUT': + tab_earth, tab_eq, tab_ann = st.tabs([ + f"⏚ Earthing Components ({len(graph.earthing_components)})", + f"⚙️ Equipment / Structures ({len(graph.equipment)})", + f"📝 Notes & Elevations ({len(graph.annotations)})", + ]) + with tab_earth: + st.subheader("Earthing Components (Bars, Pits, Conductors)") + if graph.earthing_components: + df = pd.DataFrame([e.model_dump() for e in graph.earthing_components]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No earthing components detected.") + + with tab_eq: + st.subheader("Earthed Equipment & Structures") + if graph.equipment: + df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No equipment detected.") + + with tab_ann: + st.subheader("Installation Notes & Elevation Labels") + if graph.annotations: + df = pd.DataFrame([a.model_dump() for a in graph.annotations]) + st.dataframe(df, use_container_width=True) + else: + st.info("No annotations detected.") + + elif dt == 'SLD': + tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([ + f"🏗️ Switchgear & Panels ({len(graph.panels)})", + f"🔌 Feeders & Breakers ({len(graph.cables)})", + f"⚙️ Loads & Equipment ({len(graph.equipment)})", + f"📝 Ratings & Notes ({len(graph.annotations)})", + ]) + with tab_panel: + st.subheader("Switchgear, Busbars & Panels") + if graph.panels: + df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No panels detected.") + + with tab_cable: + st.subheader("Feeders & Circuit Breakers") + if graph.cables: + df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No feeders/breakers detected.") + + with tab_eq: + st.subheader("Loads & Equipment") + if graph.equipment: + df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No equipment detected.") + + with tab_ann: + st.subheader("Ratings & Notes") + if graph.annotations: + df = pd.DataFrame([a.model_dump() for a in graph.annotations]) + st.dataframe(df, use_container_width=True) + else: + st.info("No annotations detected.") + + elif dt == 'CABLE_SCHEDULE': + tab_cable, tab_panel, tab_ann = st.tabs([ + f"🔌 Cable Schedule ({len(graph.cables)})", + f"⚡ Panels ({len(graph.panels)})", + f"📝 Notes ({len(graph.annotations)})", + ]) + with tab_cable: + if graph.cables: + df = pd.DataFrame([c.model_dump() for c in graph.cables]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No cables detected.") + with tab_panel: + if graph.panels: + df = pd.DataFrame([p.model_dump() for p in graph.panels]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No panels detected.") + with tab_ann: + if graph.annotations: + df = pd.DataFrame([a.model_dump() for a in graph.annotations]) + st.dataframe(df, use_container_width=True) + else: + st.info("No annotations detected.") + + else: + tab_eq, tab_generic, tab_ann = st.tabs([ + f"⚙️ Equipment ({len(graph.equipment)})", + f"🔩 Components ({len(graph.generic_components)})", + f"📝 Notes & Annotations ({len(graph.annotations)})", + ]) + with tab_eq: + st.subheader("Equipment List") + if graph.equipment: + df = pd.DataFrame([e.model_dump() for e in graph.equipment]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No equipment detected.") + + with tab_generic: + st.subheader("Detected Components") + if graph.generic_components: + df = pd.DataFrame([g.model_dump() for g in graph.generic_components]).drop(columns=["coordinates"], errors="ignore") + st.dataframe(df, use_container_width=True) + else: + st.info("No components detected.") + + with tab_ann: + st.subheader("Annotations & Notes") + if graph.annotations: + df = pd.DataFrame([a.model_dump() for a in graph.annotations]) + st.dataframe(df, use_container_width=True) + else: + st.info("No annotations detected.") + + # Relationships + if graph.relationships: + with st.expander(f"🔗 Engineering Relationships ({len(graph.relationships)})"): + df = pd.DataFrame([r.model_dump() for r in graph.relationships]) + st.dataframe(df, use_container_width=True) + + # Quality Assurance & Process Log + st.markdown("
🔍 Quality Assurance & Process Log
", unsafe_allow_html=True) + col_v1, col_v2 = st.columns(2) + + with col_v1: + st.subheader("Consistency Errors & Warnings") + if reports: + for r in reports: + icon = "❌" if r.get("severity") == "ERROR" else "⚠️" + bg_color = "#FDF2F2" if r.get("severity") == "ERROR" else "#FEFBF0" + border_color = "#F05252" if r.get("severity") == "ERROR" else "#FACA15" + st.markdown(f""" +
+ {icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})
+ {r.get('message')} +
+ """, unsafe_allow_html=True) + else: + st.success("✓ No validation discrepancies identified.") + + with col_v2: + st.subheader("Extraction Process History") + st.markdown(f"**Re-extraction Loops:** `{re_runs}` / `{max_retries}`") + st.markdown("**Revision History:**") + for log in revision_history: + action = log.get("action", str(log)) + st.markdown(f"- {action}") + + # Export & Download + st.markdown("
📥 Export & Download
", unsafe_allow_html=True) + st.markdown("Download deliverables formatted for standard engineering platforms:") + + col_d1, col_d2, col_d3, col_d4, col_d5 = st.columns(5) + if deliverables: + if "excel" in deliverables and os.path.exists(deliverables["excel"]): + with open(deliverables["excel"], "rb") as f: + col_d1.download_button( + "📊 Excel Deliverables", + data=f.read(), + file_name="engineering_deliverables.xlsx", + mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + use_container_width=True, + ) + if "json_graph" in deliverables and os.path.exists(deliverables["json_graph"]): + with open(deliverables["json_graph"], "rb") as f: + col_d2.download_button( + "🕸️ JSON Graph", + data=f.read(), + file_name="master_graph.json", + mime="application/json", + use_container_width=True, + ) + if "aveva_xml" in deliverables and os.path.exists(deliverables["aveva_xml"]): + with open(deliverables["aveva_xml"], "rb") as f: + col_d3.download_button( + "📐 AVEVA XML", + data=f.read(), + file_name="aveva_diagrams_export.xml", + mime="application/xml", + use_container_width=True, + ) + if "comos_json" in deliverables and os.path.exists(deliverables["comos_json"]): + with open(deliverables["comos_json"], "rb") as f: + col_d4.download_button( + "🔧 COMOS JSON", + data=f.read(), + file_name="comos_hierarchy_export.json", + mime="application/json", + use_container_width=True, + ) + if "sppid_csv" in deliverables and os.path.exists(deliverables["sppid_csv"]): + with open(deliverables["sppid_csv"], "rb") as f: + col_d5.download_button( + "🗃️ SmartPlant CSV", + data=f.read(), + file_name="sppid_import_tables.csv", + mime="text/csv", + use_container_width=True, + ) + else: + st.info("No export files generated yet for this thread.") else: - st.info("No export files generated yet. Run the pipeline to generate deliverables.") + st.info("No active thread selected. Upload a drawing or select a thread from the sidebar.") + +# ─── TAB 2: GENERATION HISTORY & ERROR LOGS ──────────────────────────────────── +with tab_main_history: + st.markdown("
📜 Generation History & Execution Logs
", unsafe_allow_html=True) + + threads = get_all_threads() + if not threads: + st.info("No generation threads recorded in SQLite history.") + else: + completed_count = sum(1 for t in threads if t["status"] == "COMPLETED") + failed_count = sum(1 for t in threads if t["status"] == "FAILED") + cancelled_count = sum(1 for t in threads if t["status"] == "CANCELLED") + + col_s1, col_s2, col_s3, col_s4 = st.columns(4) + col_s1.metric("Total Executions", len(threads)) + col_s2.metric("Successful", completed_count) + col_s3.metric("Failed", failed_count) + col_s4.metric("Cancelled", cancelled_count) + + st.markdown("### Execution Threads Table") + summary_rows = [] + for t in threads: + summary_rows.append({ + "Thread ID": t["thread_id"], + "File": t.get("filename"), + "Type": t.get("drawing_type"), + "Status": t.get("status"), + "Progress": f"{int(t.get('progress', 0)*100)}%", + "Step": t.get("current_step"), + "Created At": t.get("created_at", "")[:19].replace("T", " "), + }) + st.dataframe(pd.DataFrame(summary_rows), use_container_width=True) + + st.markdown("---") + st.markdown("### Detailed Thread Logs & Error Tracebacks") + + for t in threads: + tid = t["thread_id"] + status = t["status"] + status_icon = "🟢" if status == "COMPLETED" else "🔵" if status == "RUNNING" else "❌" if status == "FAILED" else "⛔" + + with st.expander(f"{status_icon} Thread: `{tid}` — File: *{t.get('filename')}* ({status})"): + col_info1, col_info2 = st.columns(2) + with col_info1: + st.write(f"**Drawing Type:** {t.get('drawing_type')}") + st.write(f"**Discipline:** {t.get('discipline')}") + st.write(f"**Created At:** {t.get('created_at')}") + with col_info2: + st.write(f"**Status:** {t.get('status')}") + st.write(f"**Last Step:** {t.get('current_step')}") + st.write(f"**Updated At:** {t.get('updated_at')}") + + if t.get("error_message"): + st.error(f"**Failure Error Message:** {t.get('error_message')}") + if t.get("error_traceback"): + st.markdown("**Failure Traceback:**") + st.code(t.get("error_traceback")) + + # Thread logs + full_t = get_thread(tid) + logs = full_t.get("logs", []) if full_t else [] + if logs: + st.markdown("**Subprocess Execution Timeline:**") + log_df = pd.DataFrame(logs)[["timestamp", "step_name", "log_level", "message"]] + st.dataframe(log_df, use_container_width=True) + else: + st.write("No execution logs recorded.") diff --git a/src/agents/compiler.py b/src/agents/compiler.py index b49cb32..1df3326 100644 --- a/src/agents/compiler.py +++ b/src/agents/compiler.py @@ -76,37 +76,17 @@ class CompilerAgent(BaseAgent): # Always compile annotations (notes, elevations, ratings) graph.annotations = self._compile_annotations(text_elements) - # Drawing-type dispatch - if drawing_type in ('PID', 'PFD', 'ISOMETRIC'): - 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.safety_relief_valves = self._compile_safety_relief_valves(text_elements, symbols) - - elif drawing_type == 'ELECTRICAL_LAYOUT': - graph.luminaires = self._compile_luminaires(text_elements, symbols) - graph.panels = self._compile_panels(text_elements, symbols) - graph.cables = self._compile_cables(text_elements, symbols, relations) - graph.equipment = self._compile_equipment(text_elements, symbols) - - elif drawing_type == 'EARTHING_LAYOUT': - graph.earthing_components = self._compile_earthing(text_elements, symbols) - graph.equipment = self._compile_equipment(text_elements, symbols) - - elif drawing_type == 'SLD': - graph.panels = self._compile_panels(text_elements, symbols) - graph.cables = self._compile_cables(text_elements, symbols, relations) - graph.equipment = self._compile_equipment(text_elements, symbols) - - elif drawing_type == 'CABLE_SCHEDULE': - graph.cables = self._compile_cables(text_elements, symbols, relations) - graph.panels = self._compile_panels(text_elements, symbols) - - else: - # HVAC_LAYOUT, STRUCTURAL_LAYOUT, GENERIC, and anything else - graph.equipment = self._compile_equipment(text_elements, symbols) - graph.generic_components = self._compile_generic(text_elements, symbols) + # 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.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) + graph.cables = self._compile_cables(text_elements, symbols, relations) + graph.earthing_components = self._compile_earthing(text_elements, symbols) + graph.generic_components = self._compile_generic(text_elements, symbols) total = graph.total_items logger.info( @@ -160,19 +140,47 @@ class CompilerAgent(BaseAgent): for lt in line_tags: tag = lt["tag"] - # Parse line tag components (e.g. 8"-PV-26-9035-FC11S-08) - pattern = r'^(\d+(?:\.\d+)?\"?)-([A-Z]+)-(\d+)-(\d+)-([A-Z0-9]+)(?:-([A-Z0-9]+))?' - match = re.match(pattern, tag) + # Intelligently split tag and detect whether size prefix is present + parts = [p.strip() for p in tag.split('-') if p.strip()] - if match: - size, service, system, sequence, spec, insulation = match.groups() + is_size = False + if parts: + p0 = parts[0] + if re.match(r'^\d', p0) or '"' in p0 or "'" in p0 or 'IN' in p0.upper() or 'MM' in p0.upper() or 'DN' in p0.upper(): + is_size = True + + if is_size and len(parts) >= 2: + size = parts[0] + rem = parts[1:] else: - parts = tag.split('-') - size = parts[0] if parts else '1"' - service = parts[1] if len(parts) > 1 else 'UNK' - spec = parts[-2] if len(parts) > 3 else 'UNSPEC' - sequence = parts[-1] if len(parts) > 2 else '0000' - insulation = None + size = "" + rem = parts + + service = rem[0] if len(rem) > 0 else "UNK" + system = None + sequence = "0000" + spec = "UNSPEC" + insulation = None + + if len(rem) == 2: + sequence = rem[1] + elif len(rem) == 3: + sequence = rem[1] + spec = rem[2] + elif len(rem) == 4: + if rem[1].isdigit() and len(rem[1]) <= 3: + system = rem[1] + sequence = rem[2] + spec = rem[3] + else: + sequence = rem[1] + spec = rem[2] + insulation = rem[3] + elif len(rem) >= 5: + system = rem[1] + sequence = rem[2] + spec = rem[3] + insulation = rem[4] path_coords = None for trace in geom.get("traces", []): @@ -401,7 +409,7 @@ class CompilerAgent(BaseAgent): self, texts: List[Dict], symbols: List[Dict], relations: List[Dict] ) -> List[CableItem]: compiled = [] - items = [t for t in texts if t["classification"] == "CIRCUIT_TAG"] + items = [t for t in texts if t["classification"] in ("CIRCUIT_TAG", "CABLE_TAG")] for item in items: tag = item["tag"] diff --git a/src/agents/completeness.py b/src/agents/completeness.py index eb64429..8f962be 100644 --- a/src/agents/completeness.py +++ b/src/agents/completeness.py @@ -56,14 +56,13 @@ class CompletenessAgent(BaseAgent): # 2. Heuristic check: Check if there's a high pressure valve near PIT-9055 (loop 9055) # that might have been skipped in text detection (e.g. check valve in loop 9055). # We simulate finding a suspect region in B9 on the first pass. + use_mocks = state.get("use_mocks", False) re_extraction_count = state.get("re_extraction_count", 0) - if re_extraction_count == 0: + if use_mocks and re_extraction_count == 0: target = "26CB9131" if target not in re_extracted_targets: - # Let's intentionally inject a missing check valve "26CB9131" in grid B9 - # to demonstrate the Focused Re-Extraction and Merge Loop! - logger.info("First run: Flagging check valve 26CB9131 in grid B9 as missing.") + logger.info("Demo Mock mode: Flagging check valve 26CB9131 in grid B9 as missing for re-extraction demo.") missing.append({ "item_type": "CHECK_VALVE", "target_tag": target, diff --git a/src/agents/re_extractor.py b/src/agents/re_extractor.py index 9e10c40..8d246e8 100644 --- a/src/agents/re_extractor.py +++ b/src/agents/re_extractor.py @@ -61,9 +61,23 @@ class ReExtractorAgent(BaseAgent): time.sleep(3) # Execute Gemini Vision crop extraction - use_mocks = state.get("use_mocks", True) + use_mocks = state.get("use_mocks", False) local_mode = state.get("local_mode", False) - re_extracted_items = self._extract_from_crop(crop_path, item, use_mocks, local_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") + + re_extracted_items = self._extract_from_crop( + crop_path=crop_path, + missing_item=item, + use_mocks=use_mocks, + local_mode=local_mode, + provider=provider, + model_name=model_name, + api_key=api_key, + base_url=base_url, + ) # Process and map back to state entities @@ -111,7 +125,17 @@ class ReExtractorAgent(BaseAgent): }] } - def _extract_from_crop(self, crop_path: Optional[str], missing_item: Dict, use_mocks: bool = True, local_mode: bool = False) -> List[ReExtractedItem]: + def _extract_from_crop( + self, + crop_path: Optional[str], + missing_item: Dict, + use_mocks: bool = False, + local_mode: bool = False, + provider: Optional[str] = None, + model_name: Optional[str] = None, + api_key: Optional[str] = None, + base_url: Optional[str] = None, + ) -> List[ReExtractedItem]: """ Calls Gemini Vision (or local PaddleOCR in local_mode) on the cropped image file. """ @@ -163,7 +187,11 @@ class ReExtractorAgent(BaseAgent): schema=ReExtractionPayload, prompt=prompt, system_instruction=system_instruction, - image_path=crop_path + image_path=crop_path, + provider=provider, + model_name=model_name, + api_key=api_key, + base_url=base_url, ) return result.items except Exception as e: diff --git a/src/agents/validation.py b/src/agents/validation.py index 8c7f648..412f3ee 100644 --- a/src/agents/validation.py +++ b/src/agents/validation.py @@ -81,14 +81,16 @@ class ValidationAgent(BaseAgent): "message": f"Orphan instrument: Instrument '{inst.tag}' has no logical connections to lines or equipment." }) - # Rule 4: Verify equipment naming convention format (must start with system prefix, e.g., '26-') + # Rule 4: Verify equipment naming convention format (e.g. system prefix '26-' or standard code 'TK-101', 'P-101') + import re + equip_pattern = re.compile(r'^(\d{2}-|[A-Z]{1,4}-?\d+)', re.IGNORECASE) for eq in graph.equipment: - if not eq.tag.startswith("26-") and not eq.tag.startswith("40-") and not eq.tag.startswith("63-"): + if not equip_pattern.match(eq.tag): reports.append({ "rule_id": "VAL-005", "severity": "WARNING", "target_tag": eq.tag, - "message": f"Equipment tag '{eq.tag}' does not start with a standard system code prefix." + "message": f"Equipment tag '{eq.tag}' does not match standard engineering equipment tag format." }) logger.info(f"Validation complete. Identified {len(reports)} inconsistencies.") diff --git a/src/db.py b/src/db.py new file mode 100644 index 0000000..4766cd5 --- /dev/null +++ b/src/db.py @@ -0,0 +1,208 @@ +""" +SQLite Database Persistence Layer for SID-AI Extraction Threads and Logs. +""" +import os +import json +import sqlite3 +from datetime import datetime +from typing import Dict, Any, List, Optional + +DB_PATH = os.path.join(os.getcwd(), "extraction_history.db") + + +def get_connection(): + conn = sqlite3.connect(DB_PATH, check_same_thread=False) + conn.row_factory = sqlite3.Row + return conn + + +def init_db(): + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS threads ( + thread_id TEXT PRIMARY KEY, + filename TEXT, + drawing_type TEXT DEFAULT 'GENERIC', + discipline TEXT DEFAULT 'Unknown', + status TEXT DEFAULT 'QUEUED', + progress REAL DEFAULT 0.0, + current_step TEXT DEFAULT 'Initialized', + created_at TEXT, + updated_at TEXT, + error_message TEXT, + error_traceback TEXT, + config_json TEXT, + result_json TEXT + ); + """) + cursor.execute(""" + CREATE TABLE IF NOT EXISTS thread_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + thread_id TEXT, + timestamp TEXT, + step_name TEXT, + log_level TEXT DEFAULT 'INFO', + message TEXT, + FOREIGN KEY(thread_id) REFERENCES threads(thread_id) ON DELETE CASCADE + ); + """) + conn.commit() + + +def create_thread( + thread_id: str, + filename: str, + config_dict: Dict[str, Any], + drawing_type: str = "GENERIC", + discipline: str = "Unknown", +) -> Dict[str, Any]: + init_db() + now = datetime.now().isoformat() + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute( + """ + INSERT INTO threads ( + thread_id, filename, drawing_type, discipline, status, + progress, current_step, created_at, updated_at, config_json + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + thread_id, + filename, + drawing_type, + discipline, + "QUEUED", + 0.05, + "Process Queued", + now, + now, + json.dumps(config_dict), + ), + ) + conn.commit() + add_log(thread_id, "Initialization", f"Extraction thread '{thread_id}' created for file '{filename}'.") + return get_thread(thread_id) + + +def update_thread_status( + thread_id: str, + status: Optional[str] = None, + progress: Optional[float] = None, + current_step: Optional[str] = None, + error_message: Optional[str] = None, + error_traceback: Optional[str] = None, + result_dict: Optional[Dict[str, Any]] = None, + drawing_type: Optional[str] = None, + discipline: Optional[str] = None, +): + now = datetime.now().isoformat() + fields = ["updated_at = ?"] + params = [now] + + if status is not None: + fields.append("status = ?") + params.append(status) + if progress is not None: + fields.append("progress = ?") + params.append(progress) + if current_step is not None: + fields.append("current_step = ?") + params.append(current_step) + if error_message is not None: + fields.append("error_message = ?") + params.append(error_message) + if error_traceback is not None: + fields.append("error_traceback = ?") + params.append(error_traceback) + if result_dict is not None: + fields.append("result_json = ?") + params.append(json.dumps(result_dict, default=str)) + if drawing_type is not None: + fields.append("drawing_type = ?") + params.append(drawing_type) + if discipline is not None: + fields.append("discipline = ?") + params.append(discipline) + + params.append(thread_id) + sql = f"UPDATE threads SET {', '.join(fields)} WHERE thread_id = ?" + + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute(sql, params) + conn.commit() + + +def add_log(thread_id: str, step_name: str, message: str, log_level: str = "INFO"): + now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute( + """ + INSERT INTO thread_logs (thread_id, timestamp, step_name, log_level, message) + VALUES (?, ?, ?, ?, ?) + """, + (thread_id, now, step_name, log_level, message), + ) + conn.commit() + + +def get_all_threads() -> List[Dict[str, Any]]: + init_db() + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM threads ORDER BY created_at DESC") + rows = cursor.fetchall() + return [dict(r) for r in rows] + + +def get_thread(thread_id: str) -> Optional[Dict[str, Any]]: + init_db() + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute("SELECT * FROM threads WHERE thread_id = ?", (thread_id,)) + row = cursor.fetchone() + if not row: + return None + thread_data = dict(row) + + # Parse JSON fields + if thread_data.get("config_json"): + try: + thread_data["config"] = json.loads(thread_data["config_json"]) + except Exception: + thread_data["config"] = {} + if thread_data.get("result_json"): + try: + thread_data["result"] = json.loads(thread_data["result_json"]) + except Exception: + thread_data["result"] = None + else: + thread_data["result"] = None + + cursor.execute("SELECT * FROM thread_logs WHERE thread_id = ? ORDER BY id ASC", (thread_id,)) + logs = cursor.fetchall() + thread_data["logs"] = [dict(l) for l in logs] + return thread_data + + +def delete_thread(thread_id: str): + init_db() + t = get_thread(thread_id) + if t and t.get("config"): + # Cleanup uploaded files if present + raw_docs = t["config"].get("raw_documents", []) + for doc in raw_docs: + if os.path.exists(doc) and "uploads" in doc: + try: + os.remove(doc) + except Exception: + pass + + with get_connection() as conn: + cursor = conn.cursor() + cursor.execute("DELETE FROM thread_logs WHERE thread_id = ?", (thread_id,)) + cursor.execute("DELETE FROM threads WHERE thread_id = ?", (thread_id,)) + conn.commit() diff --git a/src/thread_manager.py b/src/thread_manager.py new file mode 100644 index 0000000..0532cb1 --- /dev/null +++ b/src/thread_manager.py @@ -0,0 +1,200 @@ +""" +Thread Manager for SID-AI. +Executes extraction workflows asynchronously in background threads, +supporting live progress reporting, cancellation, and SQLite persistence. +""" +import os +import time +import logging +import threading +import traceback +from typing import Dict, Any, Optional + +from src.graph import create_workflow +from src.state import GraphState +from src.models import UniversalEngineeringGraph +from src.db import ( + create_thread, + update_thread_status, + add_log, + get_thread, + get_all_threads, + delete_thread, +) + +logger = logging.getLogger(__name__) + +# Memory map for active thread cancellation events and thread objects +_ACTIVE_THREADS: Dict[str, Dict[str, Any]] = {} +_LOCK = threading.Lock() + + +def start_extraction_thread(thread_id: str, initial_state: GraphState, filename: str) -> str: + """ + Spawns a background thread to execute the extraction workflow asynchronously. + """ + config_dict = { + "raw_documents": initial_state.get("raw_documents", []), + "ocr_engine": initial_state.get("ocr_engine"), + "reasoning_engine": initial_state.get("reasoning_engine"), + "llm_provider": initial_state.get("llm_provider"), + "llm_model": initial_state.get("llm_model"), + "use_mocks": initial_state.get("use_mocks"), + "local_mode": initial_state.get("local_mode"), + "max_re_extractions": initial_state.get("max_re_extractions", 3), + } + + create_thread(thread_id=thread_id, filename=filename, config_dict=config_dict) + + cancel_event = threading.Event() + t = threading.Thread( + target=_run_workflow_worker, + args=(thread_id, initial_state, cancel_event), + daemon=True, + ) + + with _LOCK: + _ACTIVE_THREADS[thread_id] = { + "thread": t, + "cancel_event": cancel_event, + } + + t.start() + return thread_id + + +def cancel_extraction_thread(thread_id: str): + """ + Interrupts and cancels a running thread immediately. + """ + with _LOCK: + active = _ACTIVE_THREADS.get(thread_id) + if active: + active["cancel_event"].set() + + update_thread_status( + thread_id=thread_id, + status="CANCELLED", + progress=1.0, + current_step="Cancelled by User", + error_message="Process was manually interrupted by user.", + ) + add_log(thread_id, "Cancellation", "Process was manually cancelled by user.", log_level="WARNING") + + +def is_thread_active(thread_id: str) -> bool: + with _LOCK: + active = _ACTIVE_THREADS.get(thread_id) + if active and active["thread"].is_alive(): + return True + return False + + +def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event: threading.Event): + """ + Worker function executed in the background thread. + """ + logger.info(f"Background worker started for thread '{thread_id}'") + update_thread_status( + thread_id=thread_id, + status="RUNNING", + progress=0.10, + current_step="Initializing Workflow Graph", + ) + add_log(thread_id, "Pipeline Started", "Initialized workflow state graph.") + + try: + if cancel_event.is_set(): + return + + workflow = create_workflow() + 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"), + "validation": (0.85, "Quality Assurance Rules Validation"), + "completeness": (0.90, "Evaluating Graph Completeness"), + "re_extractor": (0.93, "Focused Visual Re-Extraction"), + "output_generator": (0.98, "Generating Excel, XML, JSON & CSV Deliverables"), + } + + current_state = dict(initial_state) + + for output in app.stream(initial_state): + if cancel_event.is_set(): + logger.info(f"Cancellation detected for thread '{thread_id}'") + update_thread_status( + thread_id=thread_id, + status="CANCELLED", + progress=1.0, + current_step="Cancelled by User", + error_message="Process was manually interrupted by user.", + ) + add_log(thread_id, "Cancellation", "Process execution cancelled by user.", log_level="WARNING") + return + + for node_name, node_state_update in output.items(): + if isinstance(node_state_update, dict): + current_state.update(node_state_update) + + prog, desc = step_progress_map.get(node_name, (0.50, f"Running node {node_name}")) + logger.info(f"Thread '{thread_id}' -> Node '{node_name}' ({prog*100:.0f}%): {desc}") + + meta = current_state.get("metadata", {}) + dt = meta.get("drawing_type") + disc = meta.get("discipline") + + update_thread_status( + thread_id=thread_id, + status="RUNNING", + progress=prog, + current_step=desc, + drawing_type=dt, + discipline=disc, + ) + add_log(thread_id, node_name.replace("_", " ").title(), f"Completed stage: {desc}") + + if cancel_event.is_set(): + return + + final_meta = current_state.get("metadata", {}) + final_graph = current_state.get("engineering_graph") + + serializable_state = dict(current_state) + serializable_state["llm_api_key"] = None # Sanitize API keys from DB + if final_graph and isinstance(final_graph, UniversalEngineeringGraph): + serializable_state["engineering_graph"] = final_graph.model_dump() + + update_thread_status( + thread_id=thread_id, + status="COMPLETED", + progress=1.0, + current_step="Completed Successfully", + result_dict=serializable_state, + drawing_type=final_meta.get("drawing_type", "GENERIC"), + discipline=final_meta.get("discipline", "Unknown"), + ) + add_log(thread_id, "Completed", "Extraction pipeline finished successfully. Deliverables generated.") + logger.info(f"Thread '{thread_id}' completed successfully.") + + except Exception as e: + tb = traceback.format_exc() + logger.error(f"Thread '{thread_id}' failed: {e}\n{tb}") + update_thread_status( + thread_id=thread_id, + status="FAILED", + progress=1.0, + current_step="Execution Failed", + error_message=str(e), + error_traceback=tb, + ) + add_log(thread_id, "Error", f"Execution failed: {e}", log_level="ERROR") + + finally: + with _LOCK: + _ACTIVE_THREADS.pop(thread_id, None) diff --git a/src/utils/tag_classifier.py b/src/utils/tag_classifier.py index 2bc5eff..f84d968 100644 --- a/src/utils/tag_classifier.py +++ b/src/utils/tag_classifier.py @@ -117,10 +117,10 @@ _VALVE_SEARCH = re.compile( re.IGNORECASE ) -# Line tags: 8"-PV-26-9035-FC11S-08 or 2"-WF-43-9032-GS225-CC +# Line tags: 8"-PV-26-9035-FC11S-08, PV-26-9035-FC11S-08, 2"-WF-43-9032-GS225-CC _LINE_SEARCH = re.compile( - r'(\d+(?:[/\\]\d+)?["\']?\s*[-–]\s*[A-Z]{2,4}\s*[-–]\s*\d{2}\s*[-–]\s*\d{4,5}' - r'(?:\s*[-–]\s*[A-Z0-9]{2,8}){1,2})', + 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 )