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:
Avhinav Gupta
2026-08-05 15:44:14 +05:30
parent bc02c9e357
commit 27825f324a
9 changed files with 1107 additions and 505 deletions
+2
View File
@@ -23,6 +23,8 @@ uploads/
outputs/
rasterized/
*.log
*.db
extraction_history.db
install_log.txt
# Scratch & debug scripts
+603 -448
View File
File diff suppressed because it is too large Load Diff
+51 -43
View File
@@ -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"]
+3 -4
View File
@@ -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,
+32 -4
View File
@@ -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:
+5 -3
View File
@@ -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.")
+208
View File
@@ -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()
+200
View File
@@ -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)
+3 -3
View File
@@ -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
)