Refactor extraction pipeline and add SQLite thread persistence
- Fixed line tag regex matching & column alignment for size-less line tags - Generalized CompilerAgent to universally compile all entity types across disciplines - Added SQLite database persistence layer (src/db.py) and background ThreadManager - Added Streamlit sidebar thread history with delete buttons & live progress tracking - Added Cancel Process button and dedicated Generation History & Error Logs tab - Fixed mock completeness loop injection & forwarded provider params in re_extractor
This commit is contained in:
@@ -23,6 +23,8 @@ uploads/
|
|||||||
outputs/
|
outputs/
|
||||||
rasterized/
|
rasterized/
|
||||||
*.log
|
*.log
|
||||||
|
*.db
|
||||||
|
extraction_history.db
|
||||||
install_log.txt
|
install_log.txt
|
||||||
|
|
||||||
# Scratch & debug scripts
|
# Scratch & debug scripts
|
||||||
|
|||||||
@@ -1,16 +1,36 @@
|
|||||||
"""
|
"""
|
||||||
SID-AI — Universal Engineering Drawing Intelligence Dashboard.
|
SID-AI — Universal Engineering Drawing Intelligence Dashboard.
|
||||||
|
|
||||||
Supports any drawing type: P&ID, Electrical Layout, Earthing Layout,
|
Supports thread persistence in SQLite, background extraction execution,
|
||||||
SLD, HVAC, Structural, Cable Schedule, and Generic drawings.
|
live progress tracking, cancel functionality, and historical error logs.
|
||||||
The dashboard adapts its tabs and columns based on the detected drawing type.
|
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
import streamlit as st
|
import streamlit as st
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from src.graph import create_workflow
|
|
||||||
|
from src.models import UniversalEngineeringGraph
|
||||||
from src.state import GraphState
|
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 ────────────────────────────────────────────────────────
|
# ─── Page Configuration ────────────────────────────────────────────────────────
|
||||||
st.set_page_config(
|
st.set_page_config(
|
||||||
@@ -91,7 +111,17 @@ st.markdown("""
|
|||||||
padding-bottom: 8px;
|
padding-bottom: 8px;
|
||||||
margin: 24px 0 16px 0;
|
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; }
|
||||||
</style>
|
</style>
|
||||||
""", unsafe_allow_html=True)
|
""", unsafe_allow_html=True)
|
||||||
|
|
||||||
@@ -103,7 +133,52 @@ st.markdown(
|
|||||||
unsafe_allow_html=True,
|
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 ───────────────────────────────────────────────────────────────────
|
# ─── 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")
|
st.sidebar.markdown("## ⚙️ 2-Layer Extraction Pipeline")
|
||||||
|
|
||||||
max_retries = st.sidebar.slider(
|
max_retries = st.sidebar.slider(
|
||||||
@@ -152,7 +227,6 @@ reasoning_engine_map = {
|
|||||||
}
|
}
|
||||||
reasoning_engine = reasoning_engine_map.get(reasoning_option, "qwen")
|
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_provider = "gemini"
|
||||||
llm_api_key = None
|
llm_api_key = None
|
||||||
llm_base_url = None
|
llm_base_url = None
|
||||||
@@ -199,21 +273,16 @@ local_mode = st.sidebar.checkbox(
|
|||||||
if local_mode:
|
if local_mode:
|
||||||
st.sidebar.info("🔌 Full Offline Mode forced — PaddleOCR + Regex Classifier. Zero API tokens.")
|
st.sidebar.info("🔌 Full Offline Mode forced — PaddleOCR + Regex Classifier. Zero API tokens.")
|
||||||
|
|
||||||
st.sidebar.markdown("---")
|
# ─── Main Content Tabs: Dashboard vs History ───────────────────────────────────
|
||||||
st.sidebar.markdown("### 📋 Supported Drawing Types")
|
tab_main_dashboard, tab_main_history = st.tabs([
|
||||||
st.sidebar.markdown("""
|
"📊 Current Extraction Dashboard",
|
||||||
- **P&ID** — Piping & Instrumentation
|
"📜 Generation History & Error Logs",
|
||||||
- **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
|
|
||||||
""")
|
|
||||||
|
|
||||||
# ─── File Upload ───────────────────────────────────────────────────────────────
|
# ─── TAB 1: CURRENT EXTRACTION DASHBOARD ───────────────────────────────────────
|
||||||
st.markdown("<div class='section-header'>📂 Document Upload</div>", unsafe_allow_html=True)
|
with tab_main_dashboard:
|
||||||
|
# Upload Section
|
||||||
|
st.markdown("<div class='section-header'>📂 Document Upload & Extraction Trigger</div>", unsafe_allow_html=True)
|
||||||
col1, col2 = st.columns(2)
|
col1, col2 = st.columns(2)
|
||||||
|
|
||||||
with col1:
|
with col1:
|
||||||
@@ -231,14 +300,12 @@ with col2:
|
|||||||
help="Provide symbol legends, client coding standards, or specification sheets.",
|
help="Provide symbol legends, client coding standards, or specification sheets.",
|
||||||
)
|
)
|
||||||
|
|
||||||
# ─── Run Button ────────────────────────────────────────────────────────────────
|
|
||||||
run_pipeline = st.button(
|
run_pipeline = st.button(
|
||||||
"🚀 Run Extraction Pipeline",
|
"🚀 Run Extraction Pipeline",
|
||||||
type="primary",
|
type="primary",
|
||||||
disabled=(uploaded_drawing is None),
|
disabled=(uploaded_drawing is None),
|
||||||
)
|
)
|
||||||
|
|
||||||
# ─── Pipeline Execution ────────────────────────────────────────────────────────
|
|
||||||
if run_pipeline and uploaded_drawing:
|
if run_pipeline and uploaded_drawing:
|
||||||
temp_dir = os.path.join(os.getcwd(), "uploads")
|
temp_dir = os.path.join(os.getcwd(), "uploads")
|
||||||
os.makedirs(temp_dir, exist_ok=True)
|
os.makedirs(temp_dir, exist_ok=True)
|
||||||
@@ -256,6 +323,8 @@ if run_pipeline and uploaded_drawing:
|
|||||||
|
|
||||||
raw_docs = [drawing_path] + ref_paths
|
raw_docs = [drawing_path] + ref_paths
|
||||||
|
|
||||||
|
new_thread_id = f"thread_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
|
||||||
|
|
||||||
initial_state: GraphState = {
|
initial_state: GraphState = {
|
||||||
"raw_documents": raw_docs,
|
"raw_documents": raw_docs,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
@@ -284,32 +353,67 @@ if run_pipeline and uploaded_drawing:
|
|||||||
"re_extracted_targets": [],
|
"re_extracted_targets": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
with st.spinner("🔍 Agent workflow running — ingesting, detecting drawing type, and extracting entities…"):
|
# Start asynchronous background thread
|
||||||
try:
|
start_extraction_thread(
|
||||||
workflow = create_workflow()
|
thread_id=new_thread_id,
|
||||||
app = workflow.compile()
|
initial_state=initial_state,
|
||||||
final_state = app.invoke(initial_state)
|
filename=uploaded_drawing.name,
|
||||||
st.session_state["pipeline_results"] = final_state
|
)
|
||||||
st.success("✅ Pipeline Execution Completed Successfully!")
|
st.session_state["active_thread_id"] = new_thread_id
|
||||||
except Exception as e:
|
st.rerun()
|
||||||
st.error(f"Pipeline execution error: {e}")
|
|
||||||
import traceback
|
|
||||||
st.code(traceback.format_exc())
|
|
||||||
|
|
||||||
# ─── Results Dashboard ─────────────────────────────────────────────────────────
|
# Render selected thread dashboard
|
||||||
if "pipeline_results" in st.session_state:
|
active_id = st.session_state.get("active_thread_id")
|
||||||
state = st.session_state["pipeline_results"]
|
if active_id:
|
||||||
metadata = state.get("metadata", {})
|
active_thread = get_thread(active_id)
|
||||||
graph = state.get("engineering_graph")
|
if active_thread:
|
||||||
reports = state.get("validation_reports", [])
|
status = active_thread.get("status")
|
||||||
deliverables = state.get("deliverables", {})
|
progress = active_thread.get("progress", 0.0)
|
||||||
re_runs = state.get("re_extraction_count", 0)
|
current_step = active_thread.get("current_step", "")
|
||||||
revision_history = state.get("revision_history", [])
|
fname = active_thread.get("filename", "")
|
||||||
|
|
||||||
drawing_type = metadata.get("drawing_type", "GENERIC")
|
# ── Active Process & Progress Bar ─────────────────────────────────
|
||||||
discipline = metadata.get("discipline", "Unknown")
|
if status == "RUNNING" or status == "QUEUED":
|
||||||
|
st.markdown("<div class='section-header'>⚡ Active Subprocess Progress</div>", 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()
|
||||||
|
|
||||||
|
# Auto refresh UI while processing
|
||||||
|
time.sleep(1.5)
|
||||||
|
st.rerun()
|
||||||
|
|
||||||
|
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')}")
|
||||||
|
|
||||||
|
# ── 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")
|
||||||
|
|
||||||
|
graph = None
|
||||||
|
if raw_graph_data:
|
||||||
|
if isinstance(raw_graph_data, dict):
|
||||||
|
graph = UniversalEngineeringGraph(**raw_graph_data)
|
||||||
|
else:
|
||||||
|
graph = raw_graph_data
|
||||||
|
|
||||||
|
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", [])
|
||||||
|
|
||||||
|
drawing_type = active_thread.get("drawing_type") or metadata.get("drawing_type", "GENERIC")
|
||||||
|
discipline = active_thread.get("discipline") or metadata.get("discipline", "Unknown")
|
||||||
|
|
||||||
# Drawing type badge
|
|
||||||
from src.utils.drawing_type_detector import DRAWING_TYPE_LABELS, DrawingType
|
from src.utils.drawing_type_detector import DRAWING_TYPE_LABELS, DrawingType
|
||||||
try:
|
try:
|
||||||
dtype_enum = DrawingType(drawing_type)
|
dtype_enum = DrawingType(drawing_type)
|
||||||
@@ -323,10 +427,9 @@ if "pipeline_results" in st.session_state:
|
|||||||
unsafe_allow_html=True,
|
unsafe_allow_html=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── Metadata Block ────────────────────────────────────────────────────────
|
# Metadata Block
|
||||||
st.markdown("<div class='section-header'>📋 Drawing Metadata</div>", unsafe_allow_html=True)
|
st.markdown("<div class='section-header'>📋 Drawing Metadata</div>", unsafe_allow_html=True)
|
||||||
col_m1, col_m2, col_m3, col_m4, col_m5 = st.columns(5)
|
col_m1, col_m2, col_m3, col_m4, col_m5 = st.columns(5)
|
||||||
|
|
||||||
with col_m1:
|
with col_m1:
|
||||||
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Drawing Title</div><div class='metric-val'>{metadata.get('title', 'N/A')}</div></div>", unsafe_allow_html=True)
|
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Drawing Title</div><div class='metric-val'>{metadata.get('title', 'N/A')}</div></div>", unsafe_allow_html=True)
|
||||||
with col_m2:
|
with col_m2:
|
||||||
@@ -338,13 +441,11 @@ if "pipeline_results" in st.session_state:
|
|||||||
with col_m5:
|
with col_m5:
|
||||||
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Client</div><div class='metric-val'>{metadata.get('client_name', 'N/A')}</div></div>", unsafe_allow_html=True)
|
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Client</div><div class='metric-val'>{metadata.get('client_name', 'N/A')}</div></div>", unsafe_allow_html=True)
|
||||||
|
|
||||||
# ── Extracted Deliverables — Dynamic Tabs ─────────────────────────────────
|
# Extracted Data Tabs
|
||||||
if graph:
|
if graph:
|
||||||
st.markdown("<div class='section-header'>📊 Extracted Data</div>", unsafe_allow_html=True)
|
st.markdown("<div class='section-header'>📊 Extracted Data</div>", unsafe_allow_html=True)
|
||||||
|
|
||||||
dt = drawing_type.upper()
|
dt = drawing_type.upper()
|
||||||
|
|
||||||
# ── P&ID / PFD / Isometric ─────────────────────────────────────────────
|
|
||||||
if dt in ('PID', 'PFD', 'ISOMETRIC'):
|
if dt in ('PID', 'PFD', 'ISOMETRIC'):
|
||||||
tab_line, tab_inst, tab_valve, tab_psv, tab_eq = st.tabs([
|
tab_line, tab_inst, tab_valve, tab_psv, tab_eq = st.tabs([
|
||||||
f"📏 Line List ({len(graph.lines)})",
|
f"📏 Line List ({len(graph.lines)})",
|
||||||
@@ -353,7 +454,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
f"🛡️ Safety Relief Valves ({len(graph.safety_relief_valves)})",
|
f"🛡️ Safety Relief Valves ({len(graph.safety_relief_valves)})",
|
||||||
f"⚙️ Equipment List ({len(graph.equipment)})",
|
f"⚙️ Equipment List ({len(graph.equipment)})",
|
||||||
])
|
])
|
||||||
|
|
||||||
with tab_line:
|
with tab_line:
|
||||||
st.subheader("Line List (Piping Segments)")
|
st.subheader("Line List (Piping Segments)")
|
||||||
if graph.lines:
|
if graph.lines:
|
||||||
@@ -394,7 +494,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No equipment detected.")
|
st.info("No equipment detected.")
|
||||||
|
|
||||||
# ── Electrical Layout ──────────────────────────────────────────────────
|
|
||||||
elif dt == 'ELECTRICAL_LAYOUT':
|
elif dt == 'ELECTRICAL_LAYOUT':
|
||||||
tab_lum, tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([
|
tab_lum, tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([
|
||||||
f"💡 Luminaires ({len(graph.luminaires)})",
|
f"💡 Luminaires ({len(graph.luminaires)})",
|
||||||
@@ -403,7 +502,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
f"⚙️ Equipment ({len(graph.equipment)})",
|
f"⚙️ Equipment ({len(graph.equipment)})",
|
||||||
f"📝 Annotations ({len(graph.annotations)})",
|
f"📝 Annotations ({len(graph.annotations)})",
|
||||||
])
|
])
|
||||||
|
|
||||||
with tab_lum:
|
with tab_lum:
|
||||||
st.subheader("Luminaire / Lighting Fitting List")
|
st.subheader("Luminaire / Lighting Fitting List")
|
||||||
if graph.luminaires:
|
if graph.luminaires:
|
||||||
@@ -444,14 +542,12 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No annotations detected.")
|
st.info("No annotations detected.")
|
||||||
|
|
||||||
# ── Earthing Layout ────────────────────────────────────────────────────
|
|
||||||
elif dt == 'EARTHING_LAYOUT':
|
elif dt == 'EARTHING_LAYOUT':
|
||||||
tab_earth, tab_eq, tab_ann = st.tabs([
|
tab_earth, tab_eq, tab_ann = st.tabs([
|
||||||
f"⏚ Earthing Components ({len(graph.earthing_components)})",
|
f"⏚ Earthing Components ({len(graph.earthing_components)})",
|
||||||
f"⚙️ Equipment / Structures ({len(graph.equipment)})",
|
f"⚙️ Equipment / Structures ({len(graph.equipment)})",
|
||||||
f"📝 Notes & Elevations ({len(graph.annotations)})",
|
f"📝 Notes & Elevations ({len(graph.annotations)})",
|
||||||
])
|
])
|
||||||
|
|
||||||
with tab_earth:
|
with tab_earth:
|
||||||
st.subheader("Earthing Components (Bars, Pits, Conductors)")
|
st.subheader("Earthing Components (Bars, Pits, Conductors)")
|
||||||
if graph.earthing_components:
|
if graph.earthing_components:
|
||||||
@@ -476,7 +572,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No annotations detected.")
|
st.info("No annotations detected.")
|
||||||
|
|
||||||
# ── SLD ───────────────────────────────────────────────────────────────
|
|
||||||
elif dt == 'SLD':
|
elif dt == 'SLD':
|
||||||
tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([
|
tab_panel, tab_cable, tab_eq, tab_ann = st.tabs([
|
||||||
f"🏗️ Switchgear & Panels ({len(graph.panels)})",
|
f"🏗️ Switchgear & Panels ({len(graph.panels)})",
|
||||||
@@ -484,7 +579,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
f"⚙️ Loads & Equipment ({len(graph.equipment)})",
|
f"⚙️ Loads & Equipment ({len(graph.equipment)})",
|
||||||
f"📝 Ratings & Notes ({len(graph.annotations)})",
|
f"📝 Ratings & Notes ({len(graph.annotations)})",
|
||||||
])
|
])
|
||||||
|
|
||||||
with tab_panel:
|
with tab_panel:
|
||||||
st.subheader("Switchgear, Busbars & Panels")
|
st.subheader("Switchgear, Busbars & Panels")
|
||||||
if graph.panels:
|
if graph.panels:
|
||||||
@@ -517,7 +611,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No annotations detected.")
|
st.info("No annotations detected.")
|
||||||
|
|
||||||
# ── Cable Schedule ─────────────────────────────────────────────────────
|
|
||||||
elif dt == 'CABLE_SCHEDULE':
|
elif dt == 'CABLE_SCHEDULE':
|
||||||
tab_cable, tab_panel, tab_ann = st.tabs([
|
tab_cable, tab_panel, tab_ann = st.tabs([
|
||||||
f"🔌 Cable Schedule ({len(graph.cables)})",
|
f"🔌 Cable Schedule ({len(graph.cables)})",
|
||||||
@@ -543,14 +636,12 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No annotations detected.")
|
st.info("No annotations detected.")
|
||||||
|
|
||||||
# ── HVAC / Structural / Generic ────────────────────────────────────────
|
|
||||||
else:
|
else:
|
||||||
tab_eq, tab_generic, tab_ann = st.tabs([
|
tab_eq, tab_generic, tab_ann = st.tabs([
|
||||||
f"⚙️ Equipment ({len(graph.equipment)})",
|
f"⚙️ Equipment ({len(graph.equipment)})",
|
||||||
f"🔩 Components ({len(graph.generic_components)})",
|
f"🔩 Components ({len(graph.generic_components)})",
|
||||||
f"📝 Notes & Annotations ({len(graph.annotations)})",
|
f"📝 Notes & Annotations ({len(graph.annotations)})",
|
||||||
])
|
])
|
||||||
|
|
||||||
with tab_eq:
|
with tab_eq:
|
||||||
st.subheader("Equipment List")
|
st.subheader("Equipment List")
|
||||||
if graph.equipment:
|
if graph.equipment:
|
||||||
@@ -575,46 +666,45 @@ if "pipeline_results" in st.session_state:
|
|||||||
else:
|
else:
|
||||||
st.info("No annotations detected.")
|
st.info("No annotations detected.")
|
||||||
|
|
||||||
# ── Relationships ──────────────────────────────────────────────────────
|
# Relationships
|
||||||
if graph.relationships:
|
if graph.relationships:
|
||||||
with st.expander(f"🔗 Engineering Relationships ({len(graph.relationships)})"):
|
with st.expander(f"🔗 Engineering Relationships ({len(graph.relationships)})"):
|
||||||
df = pd.DataFrame([r.model_dump() for r in graph.relationships])
|
df = pd.DataFrame([r.model_dump() for r in graph.relationships])
|
||||||
st.dataframe(df, use_container_width=True)
|
st.dataframe(df, use_container_width=True)
|
||||||
|
|
||||||
# ── QA & Validation ───────────────────────────────────────────────────────
|
# Quality Assurance & Process Log
|
||||||
st.markdown("<div class='section-header'>🔍 Quality Assurance & Validation Logs</div>", unsafe_allow_html=True)
|
st.markdown("<div class='section-header'>🔍 Quality Assurance & Process Log</div>", unsafe_allow_html=True)
|
||||||
col_v1, col_v2 = st.columns(2)
|
col_v1, col_v2 = st.columns(2)
|
||||||
|
|
||||||
with col_v1:
|
with col_v1:
|
||||||
st.subheader("Consistency Errors & Warnings")
|
st.subheader("Consistency Errors & Warnings")
|
||||||
if reports:
|
if reports:
|
||||||
for r in reports:
|
for r in reports:
|
||||||
icon = "❌" if r["severity"] == "ERROR" else "⚠️"
|
icon = "❌" if r.get("severity") == "ERROR" else "⚠️"
|
||||||
bg_color = "#FDF2F2" if r["severity"] == "ERROR" else "#FEFBF0"
|
bg_color = "#FDF2F2" if r.get("severity") == "ERROR" else "#FEFBF0"
|
||||||
border_color = "#F05252" if r["severity"] == "ERROR" else "#FACA15"
|
border_color = "#F05252" if r.get("severity") == "ERROR" else "#FACA15"
|
||||||
st.markdown(f"""
|
st.markdown(f"""
|
||||||
<div style='background-color: {bg_color}; padding: 10px; border-left: 4px solid {border_color}; border-radius: 4px; margin-bottom: 8px;'>
|
<div style='background-color: {bg_color}; padding: 10px; border-left: 4px solid {border_color}; border-radius: 4px; margin-bottom: 8px;'>
|
||||||
<strong>{icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})</strong><br/>
|
<strong>{icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})</strong><br/>
|
||||||
<span style='font-size: 0.9rem;'>{r['message']}</span>
|
<span style='font-size: 0.9rem;'>{r.get('message')}</span>
|
||||||
</div>
|
</div>
|
||||||
""", unsafe_allow_html=True)
|
""", unsafe_allow_html=True)
|
||||||
else:
|
else:
|
||||||
st.success("✓ No validation discrepancies identified.")
|
st.success("✓ No validation discrepancies identified.")
|
||||||
|
|
||||||
with col_v2:
|
with col_v2:
|
||||||
st.subheader("Extraction Process Log")
|
st.subheader("Extraction Process History")
|
||||||
st.markdown(f"**Re-extraction Loops:** `{re_runs}` / `{max_retries}`")
|
st.markdown(f"**Re-extraction Loops:** `{re_runs}` / `{max_retries}`")
|
||||||
st.markdown("**Revision History:**")
|
st.markdown("**Revision History:**")
|
||||||
for log in revision_history:
|
for log in revision_history:
|
||||||
action = log.get("action", str(log))
|
action = log.get("action", str(log))
|
||||||
st.markdown(f"- {action}")
|
st.markdown(f"- {action}")
|
||||||
|
|
||||||
# ── Download Section ───────────────────────────────────────────────────────
|
# Export & Download
|
||||||
st.markdown("<div class='section-header'>📥 Export & Download</div>", unsafe_allow_html=True)
|
st.markdown("<div class='section-header'>📥 Export & Download</div>", unsafe_allow_html=True)
|
||||||
st.markdown("Download deliverables formatted for standard engineering platforms:")
|
st.markdown("Download deliverables formatted for standard engineering platforms:")
|
||||||
|
|
||||||
col_d1, col_d2, col_d3, col_d4, col_d5 = st.columns(5)
|
col_d1, col_d2, col_d3, col_d4, col_d5 = st.columns(5)
|
||||||
|
|
||||||
if deliverables:
|
if deliverables:
|
||||||
if "excel" in deliverables and os.path.exists(deliverables["excel"]):
|
if "excel" in deliverables and os.path.exists(deliverables["excel"]):
|
||||||
with open(deliverables["excel"], "rb") as f:
|
with open(deliverables["excel"], "rb") as f:
|
||||||
@@ -625,7 +715,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
use_container_width=True,
|
use_container_width=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
if "json_graph" in deliverables and os.path.exists(deliverables["json_graph"]):
|
if "json_graph" in deliverables and os.path.exists(deliverables["json_graph"]):
|
||||||
with open(deliverables["json_graph"], "rb") as f:
|
with open(deliverables["json_graph"], "rb") as f:
|
||||||
col_d2.download_button(
|
col_d2.download_button(
|
||||||
@@ -635,7 +724,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
mime="application/json",
|
mime="application/json",
|
||||||
use_container_width=True,
|
use_container_width=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
if "aveva_xml" in deliverables and os.path.exists(deliverables["aveva_xml"]):
|
if "aveva_xml" in deliverables and os.path.exists(deliverables["aveva_xml"]):
|
||||||
with open(deliverables["aveva_xml"], "rb") as f:
|
with open(deliverables["aveva_xml"], "rb") as f:
|
||||||
col_d3.download_button(
|
col_d3.download_button(
|
||||||
@@ -645,7 +733,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
mime="application/xml",
|
mime="application/xml",
|
||||||
use_container_width=True,
|
use_container_width=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
if "comos_json" in deliverables and os.path.exists(deliverables["comos_json"]):
|
if "comos_json" in deliverables and os.path.exists(deliverables["comos_json"]):
|
||||||
with open(deliverables["comos_json"], "rb") as f:
|
with open(deliverables["comos_json"], "rb") as f:
|
||||||
col_d4.download_button(
|
col_d4.download_button(
|
||||||
@@ -655,7 +742,6 @@ if "pipeline_results" in st.session_state:
|
|||||||
mime="application/json",
|
mime="application/json",
|
||||||
use_container_width=True,
|
use_container_width=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
if "sppid_csv" in deliverables and os.path.exists(deliverables["sppid_csv"]):
|
if "sppid_csv" in deliverables and os.path.exists(deliverables["sppid_csv"]):
|
||||||
with open(deliverables["sppid_csv"], "rb") as f:
|
with open(deliverables["sppid_csv"], "rb") as f:
|
||||||
col_d5.download_button(
|
col_d5.download_button(
|
||||||
@@ -666,4 +752,73 @@ if "pipeline_results" in st.session_state:
|
|||||||
use_container_width=True,
|
use_container_width=True,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
st.info("No export files generated yet. Run the pipeline to generate deliverables.")
|
st.info("No export files generated yet for this thread.")
|
||||||
|
else:
|
||||||
|
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("<div class='section-header'>📜 Generation History & Execution Logs</div>", 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.")
|
||||||
|
|||||||
+40
-32
@@ -76,36 +76,16 @@ class CompilerAgent(BaseAgent):
|
|||||||
# Always compile annotations (notes, elevations, ratings)
|
# Always compile annotations (notes, elevations, ratings)
|
||||||
graph.annotations = self._compile_annotations(text_elements)
|
graph.annotations = self._compile_annotations(text_elements)
|
||||||
|
|
||||||
# Drawing-type dispatch
|
# Universal compilation across all detected entity types
|
||||||
if drawing_type in ('PID', 'PFD', 'ISOMETRIC'):
|
|
||||||
graph.equipment = self._compile_equipment(text_elements, symbols)
|
graph.equipment = self._compile_equipment(text_elements, symbols)
|
||||||
graph.lines = self._compile_lines(text_elements, geometry, relations)
|
graph.lines = self._compile_lines(text_elements, geometry, relations)
|
||||||
graph.instruments = self._compile_instruments(text_elements, symbols)
|
graph.instruments = self._compile_instruments(text_elements, symbols)
|
||||||
graph.valves = self._compile_valves(text_elements, symbols, relations, graph.lines)
|
graph.valves = self._compile_valves(text_elements, symbols, relations, graph.lines)
|
||||||
graph.safety_relief_valves = self._compile_safety_relief_valves(text_elements, symbols)
|
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.luminaires = self._compile_luminaires(text_elements, symbols)
|
||||||
graph.panels = self._compile_panels(text_elements, symbols)
|
graph.panels = self._compile_panels(text_elements, symbols)
|
||||||
graph.cables = self._compile_cables(text_elements, symbols, relations)
|
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.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)
|
graph.generic_components = self._compile_generic(text_elements, symbols)
|
||||||
|
|
||||||
total = graph.total_items
|
total = graph.total_items
|
||||||
@@ -160,20 +140,48 @@ class CompilerAgent(BaseAgent):
|
|||||||
|
|
||||||
for lt in line_tags:
|
for lt in line_tags:
|
||||||
tag = lt["tag"]
|
tag = lt["tag"]
|
||||||
# Parse line tag components (e.g. 8"-PV-26-9035-FC11S-08)
|
# Intelligently split tag and detect whether size prefix is present
|
||||||
pattern = r'^(\d+(?:\.\d+)?\"?)-([A-Z]+)-(\d+)-(\d+)-([A-Z0-9]+)(?:-([A-Z0-9]+))?'
|
parts = [p.strip() for p in tag.split('-') if p.strip()]
|
||||||
match = re.match(pattern, tag)
|
|
||||||
|
|
||||||
if match:
|
is_size = False
|
||||||
size, service, system, sequence, spec, insulation = match.groups()
|
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:
|
else:
|
||||||
parts = tag.split('-')
|
size = ""
|
||||||
size = parts[0] if parts else '1"'
|
rem = parts
|
||||||
service = parts[1] if len(parts) > 1 else 'UNK'
|
|
||||||
spec = parts[-2] if len(parts) > 3 else 'UNSPEC'
|
service = rem[0] if len(rem) > 0 else "UNK"
|
||||||
sequence = parts[-1] if len(parts) > 2 else '0000'
|
system = None
|
||||||
|
sequence = "0000"
|
||||||
|
spec = "UNSPEC"
|
||||||
insulation = None
|
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
|
path_coords = None
|
||||||
for trace in geom.get("traces", []):
|
for trace in geom.get("traces", []):
|
||||||
if trace["tag"] == tag:
|
if trace["tag"] == tag:
|
||||||
@@ -401,7 +409,7 @@ class CompilerAgent(BaseAgent):
|
|||||||
self, texts: List[Dict], symbols: List[Dict], relations: List[Dict]
|
self, texts: List[Dict], symbols: List[Dict], relations: List[Dict]
|
||||||
) -> List[CableItem]:
|
) -> List[CableItem]:
|
||||||
compiled = []
|
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:
|
for item in items:
|
||||||
tag = item["tag"]
|
tag = item["tag"]
|
||||||
|
|||||||
@@ -56,14 +56,13 @@ class CompletenessAgent(BaseAgent):
|
|||||||
# 2. Heuristic check: Check if there's a high pressure valve near PIT-9055 (loop 9055)
|
# 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).
|
# 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.
|
# 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)
|
re_extraction_count = state.get("re_extraction_count", 0)
|
||||||
|
|
||||||
if re_extraction_count == 0:
|
if use_mocks and re_extraction_count == 0:
|
||||||
target = "26CB9131"
|
target = "26CB9131"
|
||||||
if target not in re_extracted_targets:
|
if target not in re_extracted_targets:
|
||||||
# Let's intentionally inject a missing check valve "26CB9131" in grid B9
|
logger.info("Demo Mock mode: Flagging check valve 26CB9131 in grid B9 as missing for re-extraction demo.")
|
||||||
# to demonstrate the Focused Re-Extraction and Merge Loop!
|
|
||||||
logger.info("First run: Flagging check valve 26CB9131 in grid B9 as missing.")
|
|
||||||
missing.append({
|
missing.append({
|
||||||
"item_type": "CHECK_VALVE",
|
"item_type": "CHECK_VALVE",
|
||||||
"target_tag": target,
|
"target_tag": target,
|
||||||
|
|||||||
@@ -61,9 +61,23 @@ class ReExtractorAgent(BaseAgent):
|
|||||||
time.sleep(3)
|
time.sleep(3)
|
||||||
|
|
||||||
# Execute Gemini Vision crop extraction
|
# 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)
|
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
|
# 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.
|
Calls Gemini Vision (or local PaddleOCR in local_mode) on the cropped image file.
|
||||||
"""
|
"""
|
||||||
@@ -163,7 +187,11 @@ class ReExtractorAgent(BaseAgent):
|
|||||||
schema=ReExtractionPayload,
|
schema=ReExtractionPayload,
|
||||||
prompt=prompt,
|
prompt=prompt,
|
||||||
system_instruction=system_instruction,
|
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
|
return result.items
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -81,14 +81,16 @@ class ValidationAgent(BaseAgent):
|
|||||||
"message": f"Orphan instrument: Instrument '{inst.tag}' has no logical connections to lines or equipment."
|
"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:
|
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({
|
reports.append({
|
||||||
"rule_id": "VAL-005",
|
"rule_id": "VAL-005",
|
||||||
"severity": "WARNING",
|
"severity": "WARNING",
|
||||||
"target_tag": eq.tag,
|
"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.")
|
logger.info(f"Validation complete. Identified {len(reports)} inconsistencies.")
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -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)
|
||||||
@@ -117,10 +117,10 @@ _VALVE_SEARCH = re.compile(
|
|||||||
re.IGNORECASE
|
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(
|
_LINE_SEARCH = re.compile(
|
||||||
r'(\d+(?:[/\\]\d+)?["\']?\s*[-–]\s*[A-Z]{2,4}\s*[-–]\s*\d{2}\s*[-–]\s*\d{4,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}){1,2})',
|
r'\s*[-–]\s*[A-Z0-9]{2,8}(?:\s*[-–]\s*[A-Z0-9]{1,8})?)',
|
||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user