Refactor extraction pipeline, add SQLite persistence & Qwen 3.7 VL support

- Fixed line tag regex matching & column alignment for size-less line tags

- Generalized CompilerAgent to universally compile all entity types across disciplines

- Fixed mock completeness loop injection & forwarded LLM provider params in re_extractor

- Fixed Qwen 3.7 VL vision extraction by passing multimodal image context & OCR blocks

- Added SQLite database persistence layer (src/db.py) and background ThreadManager

- Added live execution timer & duration tracking across progress bar, metadata, and history logs

- Added high-contrast text styling for Consistency Errors & Warnings cards in Dark Mode

- Moved Generation Threads to bottom of sidebar in a scrollable max-5 container with delete buttons

- Excluded *.db and extraction_history.db from Git tracking in .gitignore
This commit is contained in:
Avhinav Gupta
2026-08-05 16:42:44 +05:30
parent 27825f324a
commit f4835855ac
4 changed files with 118 additions and 62 deletions
+85 -50
View File
@@ -9,6 +9,7 @@ import time
import uuid import uuid
import logging import logging
from datetime import datetime from datetime import datetime
from typing import Dict, Any, List, Optional
import streamlit as st import streamlit as st
import pandas as pd import pandas as pd
from PIL import Image from PIL import Image
@@ -29,6 +30,16 @@ from src.thread_manager import (
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
def format_duration(seconds: Optional[float]) -> str:
if seconds is None or seconds <= 0:
return "N/A"
sec = int(seconds)
if sec < 60:
return f"{seconds:.1f}s"
m = sec // 60
s = sec % 60
return f"{m:02d}m {s:02d}s"
# Initialize SQLite Database on app load # Initialize SQLite Database on app load
init_db() init_db()
@@ -141,44 +152,6 @@ if "active_thread_id" not in st.session_state and all_threads:
st.session_state["active_thread_id"] = all_threads[0]["thread_id"] 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(
@@ -195,6 +168,7 @@ ocr_option = st.sidebar.selectbox(
"PyMuPDF Vector Text (Local / Offline)", "PyMuPDF Vector Text (Local / Offline)",
"Gemini Vision OCR (Online API)", "Gemini Vision OCR (Online API)",
"Qwen 2.5-VL / Vision API (Online)", "Qwen 2.5-VL / Vision API (Online)",
"Qwen 3.7-VL / OpenRouter (Online)",
], ],
index=0, index=0,
help="Select the 1st layer OCR engine. PaddleOCR & PyMuPDF run locally offline.", help="Select the 1st layer OCR engine. PaddleOCR & PyMuPDF run locally offline.",
@@ -204,6 +178,7 @@ ocr_engine_map = {
"PyMuPDF Vector Text (Local / Offline)": "pdf_text", "PyMuPDF Vector Text (Local / Offline)": "pdf_text",
"Gemini Vision OCR (Online API)": "gemini_ocr", "Gemini Vision OCR (Online API)": "gemini_ocr",
"Qwen 2.5-VL / Vision API (Online)": "qwen_ocr", "Qwen 2.5-VL / Vision API (Online)": "qwen_ocr",
"Qwen 3.7-VL / OpenRouter (Online)": "qwen_37_ocr",
} }
ocr_engine = ocr_engine_map.get(ocr_option, "paddle") ocr_engine = ocr_engine_map.get(ocr_option, "paddle")
@@ -213,6 +188,7 @@ reasoning_option = st.sidebar.selectbox(
options=[ options=[
"Rule-Based Regex Classifier (Local / Offline)", "Rule-Based Regex Classifier (Local / Offline)",
"Qwen 2.5 Reasoning Engine (OpenRouter / API)", "Qwen 2.5 Reasoning Engine (OpenRouter / API)",
"Qwen 3.7 Reasoning Engine (OpenRouter / API)",
"Gemini 2.0 Flash Engine (Online / API)", "Gemini 2.0 Flash Engine (Online / API)",
"OpenAI GPT-4o Engine (Online / API)", "OpenAI GPT-4o Engine (Online / API)",
], ],
@@ -222,6 +198,7 @@ reasoning_option = st.sidebar.selectbox(
reasoning_engine_map = { reasoning_engine_map = {
"Rule-Based Regex Classifier (Local / Offline)": "rule_based", "Rule-Based Regex Classifier (Local / Offline)": "rule_based",
"Qwen 2.5 Reasoning Engine (OpenRouter / API)": "qwen", "Qwen 2.5 Reasoning Engine (OpenRouter / API)": "qwen",
"Qwen 3.7 Reasoning Engine (OpenRouter / API)": "qwen_37",
"Gemini 2.0 Flash Engine (Online / API)": "gemini", "Gemini 2.0 Flash Engine (Online / API)": "gemini",
"OpenAI GPT-4o Engine (Online / API)": "openai", "OpenAI GPT-4o Engine (Online / API)": "openai",
} }
@@ -232,8 +209,8 @@ llm_api_key = None
llm_base_url = None llm_base_url = None
llm_model = None llm_model = None
if reasoning_engine in ("qwen", "openai") or ocr_engine == "qwen_ocr": if reasoning_engine in ("qwen", "qwen_37", "openai") or ocr_engine in ("qwen_ocr", "qwen_37_ocr"):
llm_provider = "qwen" if ("Qwen" in reasoning_option or ocr_engine == "qwen_ocr") else "openai" llm_provider = "qwen" if ("Qwen" in reasoning_option or "qwen" in ocr_engine) else "openai"
with st.sidebar.expander(f"🔧 {llm_provider.upper()} / OpenRouter Settings", expanded=True): with st.sidebar.expander(f"🔧 {llm_provider.upper()} / OpenRouter Settings", expanded=True):
default_key = os.getenv("OPENROUTER_API_KEY", os.getenv("QWEN_API_KEY", os.getenv("OPENAI_API_KEY", ""))) default_key = os.getenv("OPENROUTER_API_KEY", os.getenv("QWEN_API_KEY", os.getenv("OPENAI_API_KEY", "")))
llm_api_key = st.text_input( llm_api_key = st.text_input(
@@ -248,11 +225,11 @@ if reasoning_engine in ("qwen", "openai") or ocr_engine == "qwen_ocr":
value=default_endpoint, value=default_endpoint,
help="Custom endpoint URL (e.g. OpenRouter https://openrouter.ai/api/v1, DashScope, or local Ollama/vLLM)", help="Custom endpoint URL (e.g. OpenRouter https://openrouter.ai/api/v1, DashScope, or local Ollama/vLLM)",
) )
default_model = os.getenv("QWEN_MODEL", "qwen/qwen-2.5-72b-instruct") if llm_provider == "qwen" else "gpt-4o" default_model = "qwen/qwen-3.7-vl" if ("3.7" in ocr_option or "3.7" in reasoning_option) else os.getenv("QWEN_MODEL", "qwen/qwen-2.5-72b-instruct")
llm_model = st.text_input( llm_model = st.text_input(
"Model Name", "Model Name",
value=default_model, value=default_model,
help="Model identifier e.g. qwen/qwen-2.5-72b-instruct, qwen/qwen-2.5-coder-32b-instruct, qwen/qwen-2.5-vl-72b-instruct", help="Model identifier e.g. qwen/qwen-3.7-vl, qwen/qwen-2.5-72b-instruct, qwen/qwen-2.5-vl-72b-instruct",
) )
elif reasoning_engine == "gemini": elif reasoning_engine == "gemini":
llm_provider = "gemini" llm_provider = "gemini"
@@ -273,6 +250,45 @@ 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("---")
st.sidebar.markdown("## 🧵 Generation Threads")
if all_threads:
with st.sidebar.container(height=260):
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.columns([0.78, 0.22])
with col_t1:
button_label = f"{status_icon} {fname[:16]}...{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.")
# ─── Main Content Tabs: Dashboard vs History ─────────────────────────────────── # ─── Main Content Tabs: Dashboard vs History ───────────────────────────────────
tab_main_dashboard, tab_main_history = st.tabs([ tab_main_dashboard, tab_main_history = st.tabs([
"📊 Current Extraction Dashboard", "📊 Current Extraction Dashboard",
@@ -375,10 +391,22 @@ with tab_main_dashboard:
# ── Active Process & Progress Bar ───────────────────────────────── # ── Active Process & Progress Bar ─────────────────────────────────
if status == "RUNNING" or status == "QUEUED": if status == "RUNNING" or status == "QUEUED":
st.markdown("<div class='section-header'>⚡ Active Subprocess Progress</div>", unsafe_allow_html=True) st.markdown("<div class='section-header'>⚡ Active Subprocess Progress</div>", unsafe_allow_html=True)
# Compute live duration
elapsed_sec = active_thread.get("duration_sec", 0.0) or 0.0
try:
c_time = datetime.fromisoformat(active_thread.get("created_at"))
elapsed_sec = (datetime.now() - c_time).total_seconds()
except Exception:
pass
col_p1, col_p2 = st.columns([0.8, 0.2]) col_p1, col_p2 = st.columns([0.8, 0.2])
with col_p1: with col_p1:
st.progress(progress) st.progress(progress)
st.info(f"⏳ **Active Subprocess:** `{current_step}` ({int(progress*100)}%) — File: *{fname}*") st.info(
f"⏳ **Active Subprocess:** `{current_step}` ({int(progress*100)}%) — "
f"⏱️ **Timer:** `{format_duration(elapsed_sec)}` — File: *{fname}*"
)
with col_p2: with col_p2:
if st.button("🛑 Cancel Process", type="secondary", use_container_width=True): if st.button("🛑 Cancel Process", type="secondary", use_container_width=True):
cancel_extraction_thread(active_id) cancel_extraction_thread(active_id)
@@ -429,7 +457,7 @@ with tab_main_dashboard:
# 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, col_m6 = st.columns(6)
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:
@@ -440,6 +468,9 @@ with tab_main_dashboard:
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Discipline</div><div class='metric-val'>{metadata.get('discipline', 'N/A')}</div></div>", unsafe_allow_html=True) st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Discipline</div><div class='metric-val'>{metadata.get('discipline', 'N/A')}</div></div>", unsafe_allow_html=True)
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)
with col_m6:
proc_time = format_duration(active_thread.get("duration_sec"))
st.markdown(f"<div class='metric-card'><div class='metric-lbl'>Processing Time</div><div class='metric-val'>{proc_time}</div></div>", unsafe_allow_html=True)
# Extracted Data Tabs # Extracted Data Tabs
if graph: if graph:
@@ -680,13 +711,16 @@ with tab_main_dashboard:
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.get("severity") == "ERROR" else "⚠️" is_err = (r.get("severity") == "ERROR")
bg_color = "#FDF2F2" if r.get("severity") == "ERROR" else "#FEFBF0" icon = "❌" if is_err else "⚠️"
border_color = "#F05252" if r.get("severity") == "ERROR" else "#FACA15" bg_color = "#FDF2F2" if is_err else "#FEFBF0"
border_color = "#F05252" if is_err else "#FACA15"
title_color = "#7F1D1D" if is_err else "#713F12"
msg_color = "#991B1B" if is_err else "#854D0E"
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: 12px; border-left: 5px solid {border_color}; border-radius: 6px; margin-bottom: 10px; font-family: sans-serif;'>
<strong>{icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})</strong><br/> <strong style='color: {title_color}; font-size: 0.95rem;'>{icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})</strong><br/>
<span style='font-size: 0.9rem;'>{r.get('message')}</span> <span style='font-size: 0.9rem; color: {msg_color}; line-height: 1.4; display: block; margin-top: 4px;'>{r.get('message')}</span>
</div> </div>
""", unsafe_allow_html=True) """, unsafe_allow_html=True)
else: else:
@@ -783,6 +817,7 @@ with tab_main_history:
"Type": t.get("drawing_type"), "Type": t.get("drawing_type"),
"Status": t.get("status"), "Status": t.get("status"),
"Progress": f"{int(t.get('progress', 0)*100)}%", "Progress": f"{int(t.get('progress', 0)*100)}%",
"Duration": format_duration(t.get("duration_sec")),
"Step": t.get("current_step"), "Step": t.get("current_step"),
"Created At": t.get("created_at", "")[:19].replace("T", " "), "Created At": t.get("created_at", "")[:19].replace("T", " "),
}) })
+13 -10
View File
@@ -275,8 +275,8 @@ class TextDetectionAgent(BaseAgent):
except Exception as pdf_err: except Exception as pdf_err:
logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).") logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).")
# Option B: Local PaddleOCR # Option B: Local PaddleOCR (serves as spatial OCR baseline for Online Layer 2)
if not ocr_items and ocr_engine in ("paddle", "pdf_text", "got-ocr", "local"): if not ocr_items or ocr_engine in ("paddle", "pdf_text", "got-ocr", "local"):
try: try:
from src.utils.preprocess import preprocess_for_ocr from src.utils.preprocess import preprocess_for_ocr
from src.utils.paddle_ocr import run_paddle_ocr from src.utils.paddle_ocr import run_paddle_ocr
@@ -289,37 +289,39 @@ class TextDetectionAgent(BaseAgent):
except Exception as paddle_err: except Exception as paddle_err:
logger.warning(f"Local PaddleOCR extraction failed ({paddle_err}).") logger.warning(f"Local PaddleOCR extraction failed ({paddle_err}).")
# Option C: Online Gemini Vision / Qwen 2.5-VL OCR # Option C: Online Gemini Vision / Qwen 2.5-VL / Qwen 3.7-VL OCR
if not ocr_items or ocr_engine in ("gemini_ocr", "qwen_ocr", "online_ocr"): if ocr_engine in ("gemini_ocr", "qwen_ocr", "qwen_37_ocr", "online_ocr"):
logger.info(f"Layer 1: Running Online Vision OCR ({ocr_engine})...") logger.info(f"Layer 1: Running Online Vision OCR ({ocr_engine})...")
try: try:
prompt_ocr = ( prompt_ocr = (
"Extract all text labels, tag numbers, coordinates, and notes visible on this drawing.\n" "Extract all text labels, tag numbers, coordinates, and notes visible on this drawing.\n"
"Return a JSON list of items with text, confidence, and pos_x, pos_y." "Return a clean list of text items found on the drawing."
) )
raw_ocr_res = self.invoke_text( raw_ocr_res = self.invoke_text(
prompt=prompt_ocr, prompt=prompt_ocr,
image_path=raw_image, image_path=raw_image,
provider="qwen" if ocr_engine == "qwen_ocr" else "gemini", provider="qwen" if ocr_engine in ("qwen_ocr", "qwen_37_ocr") else "gemini",
model_name=llm_model, model_name=llm_model,
api_key=llm_api_key, api_key=llm_api_key,
base_url=llm_base_url, base_url=llm_base_url,
) )
# Parse fallback
logger.info("Layer 1 Online OCR response received.") logger.info("Layer 1 Online OCR response received.")
if raw_ocr_res and not ocr_items:
lines = [l.strip() for l in raw_ocr_res.splitlines() if l.strip()]
ocr_items = [{"text": line, "confidence": 0.9, "box": [0.5, 0.5, 0.5, 0.5]} for line in lines]
except Exception as online_ocr_err: except Exception as online_ocr_err:
logger.warning(f"Online OCR engine failed ({online_ocr_err}).") logger.warning(f"Online OCR engine failed ({online_ocr_err}).")
# ── LAYER 2: REASONING & STRUCTURING ENGINE ─────────────────────────── # ── LAYER 2: REASONING & STRUCTURING ENGINE ───────────────────────────
# Option A: Rule-Based Classifier (Local Offline Regex) # Option A: Rule-Based Classifier (Local Offline Regex)
if reasoning_engine == "rule_based" or (local_mode and reasoning_engine not in ("qwen", "gemini", "openai")): if reasoning_engine == "rule_based" or (local_mode and reasoning_engine not in ("qwen", "qwen_37", "gemini", "openai")):
logger.info("Layer 2: Executing Local Rule-Based Classifier (zero LLM tokens)...") logger.info("Layer 2: Executing Local Rule-Based Classifier (zero LLM tokens)...")
structured = classify_paddle_results(ocr_items, drawing_type=drawing_type) structured = classify_paddle_results(ocr_items, drawing_type=drawing_type)
logger.info(f"Layer 2: Rule-based classifier produced {len(structured)} structured items.") logger.info(f"Layer 2: Rule-based classifier produced {len(structured)} structured items.")
return {"extracted_entities": {"text_elements": structured}} return {"extracted_entities": {"text_elements": structured}}
# Option B: Online LLM Deep Reasoning Engine (Qwen 2.5, Gemini, OpenAI, etc.) # Option B: Online LLM Deep Reasoning Engine (Qwen 2.5, Qwen 3.7, Gemini, OpenAI, etc.)
logger.info(f"Layer 2: Executing Online LLM Reasoning Engine using provider '{llm_provider}'...") logger.info(f"Layer 2: Executing Online LLM Reasoning Engine using provider '{llm_provider}'...")
try: try:
from src.utils.paddle_ocr import format_paddle_results_for_llm from src.utils.paddle_ocr import format_paddle_results_for_llm
@@ -335,7 +337,7 @@ class TextDetectionAgent(BaseAgent):
"1. FIX OCR TYPOS: Correct misread letters/digits (e.g., P1T-9055 -> PIT-9055, 0B-01 -> DB-01, E8-01 -> EB-01).\n" "1. FIX OCR TYPOS: Correct misread letters/digits (e.g., P1T-9055 -> PIT-9055, 0B-01 -> DB-01, E8-01 -> EB-01).\n"
"2. RECOMBINE SPLIT TEXT: Re-assemble tags that were split across multiple OCR lines.\n" "2. RECOMBINE SPLIT TEXT: Re-assemble tags that were split across multiple OCR lines.\n"
"3. IDENTIFY MISPLACED DATA: Map nearby specifications (design pressure, design temp, wattage, rating, cable size, elevation, material, duty) into the parent tag's attributes dict.\n" "3. IDENTIFY MISPLACED DATA: Map nearby specifications (design pressure, design temp, wattage, rating, cable size, elevation, material, duty) into the parent tag's attributes dict.\n"
"4. FIND MISSING TAGS/ENTITIES: Infer missing tags or equipment referenced in callouts or note blocks.\n" "4. FIND MISSING TAGS/ENTITIES: Visually inspect the drawing image to find any missing tags or equipment referenced in callouts or note blocks.\n"
"5. CLASSIFY & STRUCTURE: Map every entity into ONE of the following categories:\n" "5. CLASSIFY & STRUCTURE: Map every entity into ONE of the following categories:\n"
+ tag_categories + "\n" + tag_categories + "\n"
"Return the cleaned, structured findings as a validated RawTextList JSON." "Return the cleaned, structured findings as a validated RawTextList JSON."
@@ -348,6 +350,7 @@ class TextDetectionAgent(BaseAgent):
"You are an AI engineering data reasoning engine. Your goal is to find missing data, " "You are an AI engineering data reasoning engine. Your goal is to find missing data, "
"correct OCR errors, map misplaced attributes, and output clean structured JSON." "correct OCR errors, map misplaced attributes, and output clean structured JSON."
), ),
image_path=raw_image,
provider=llm_provider, provider=llm_provider,
model_name=llm_model, model_name=llm_model,
api_key=llm_api_key, api_key=llm_api_key,
+9
View File
@@ -30,12 +30,17 @@ def init_db():
current_step TEXT DEFAULT 'Initialized', current_step TEXT DEFAULT 'Initialized',
created_at TEXT, created_at TEXT,
updated_at TEXT, updated_at TEXT,
duration_sec REAL DEFAULT 0.0,
error_message TEXT, error_message TEXT,
error_traceback TEXT, error_traceback TEXT,
config_json TEXT, config_json TEXT,
result_json TEXT result_json TEXT
); );
""") """)
try:
cursor.execute("ALTER TABLE threads ADD COLUMN duration_sec REAL DEFAULT 0.0")
except Exception:
pass
cursor.execute(""" cursor.execute("""
CREATE TABLE IF NOT EXISTS thread_logs ( CREATE TABLE IF NOT EXISTS thread_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT, id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -96,6 +101,7 @@ def update_thread_status(
result_dict: Optional[Dict[str, Any]] = None, result_dict: Optional[Dict[str, Any]] = None,
drawing_type: Optional[str] = None, drawing_type: Optional[str] = None,
discipline: Optional[str] = None, discipline: Optional[str] = None,
duration_sec: Optional[float] = None,
): ):
now = datetime.now().isoformat() now = datetime.now().isoformat()
fields = ["updated_at = ?"] fields = ["updated_at = ?"]
@@ -125,6 +131,9 @@ def update_thread_status(
if discipline is not None: if discipline is not None:
fields.append("discipline = ?") fields.append("discipline = ?")
params.append(discipline) params.append(discipline)
if duration_sec is not None:
fields.append("duration_sec = ?")
params.append(duration_sec)
params.append(thread_id) params.append(thread_id)
sql = f"UPDATE threads SET {', '.join(fields)} WHERE thread_id = ?" sql = f"UPDATE threads SET {', '.join(fields)} WHERE thread_id = ?"
+11 -2
View File
@@ -94,12 +94,14 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
""" """
Worker function executed in the background thread. Worker function executed in the background thread.
""" """
start_time = time.time()
logger.info(f"Background worker started for thread '{thread_id}'") logger.info(f"Background worker started for thread '{thread_id}'")
update_thread_status( update_thread_status(
thread_id=thread_id, thread_id=thread_id,
status="RUNNING", status="RUNNING",
progress=0.10, progress=0.10,
current_step="Initializing Workflow Graph", current_step="Initializing Workflow Graph",
duration_sec=0.0,
) )
add_log(thread_id, "Pipeline Started", "Initialized workflow state graph.") add_log(thread_id, "Pipeline Started", "Initialized workflow state graph.")
@@ -126,6 +128,7 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
current_state = dict(initial_state) current_state = dict(initial_state)
for output in app.stream(initial_state): for output in app.stream(initial_state):
elapsed = round(time.time() - start_time, 1)
if cancel_event.is_set(): if cancel_event.is_set():
logger.info(f"Cancellation detected for thread '{thread_id}'") logger.info(f"Cancellation detected for thread '{thread_id}'")
update_thread_status( update_thread_status(
@@ -134,6 +137,7 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
progress=1.0, progress=1.0,
current_step="Cancelled by User", current_step="Cancelled by User",
error_message="Process was manually interrupted by user.", error_message="Process was manually interrupted by user.",
duration_sec=elapsed,
) )
add_log(thread_id, "Cancellation", "Process execution cancelled by user.", log_level="WARNING") add_log(thread_id, "Cancellation", "Process execution cancelled by user.", log_level="WARNING")
return return
@@ -156,12 +160,14 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
current_step=desc, current_step=desc,
drawing_type=dt, drawing_type=dt,
discipline=disc, discipline=disc,
duration_sec=elapsed,
) )
add_log(thread_id, node_name.replace("_", " ").title(), f"Completed stage: {desc}") add_log(thread_id, node_name.replace("_", " ").title(), f"Completed stage: {desc}")
if cancel_event.is_set(): if cancel_event.is_set():
return return
final_duration = round(time.time() - start_time, 1)
final_meta = current_state.get("metadata", {}) final_meta = current_state.get("metadata", {})
final_graph = current_state.get("engineering_graph") final_graph = current_state.get("engineering_graph")
@@ -178,11 +184,13 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
result_dict=serializable_state, result_dict=serializable_state,
drawing_type=final_meta.get("drawing_type", "GENERIC"), drawing_type=final_meta.get("drawing_type", "GENERIC"),
discipline=final_meta.get("discipline", "Unknown"), discipline=final_meta.get("discipline", "Unknown"),
duration_sec=final_duration,
) )
add_log(thread_id, "Completed", "Extraction pipeline finished successfully. Deliverables generated.") add_log(thread_id, "Completed", f"Extraction finished in {final_duration}s. Deliverables generated.")
logger.info(f"Thread '{thread_id}' completed successfully.") logger.info(f"Thread '{thread_id}' completed successfully in {final_duration}s.")
except Exception as e: except Exception as e:
final_duration = round(time.time() - start_time, 1)
tb = traceback.format_exc() tb = traceback.format_exc()
logger.error(f"Thread '{thread_id}' failed: {e}\n{tb}") logger.error(f"Thread '{thread_id}' failed: {e}\n{tb}")
update_thread_status( update_thread_status(
@@ -192,6 +200,7 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
current_step="Execution Failed", current_step="Execution Failed",
error_message=str(e), error_message=str(e),
error_traceback=tb, error_traceback=tb,
duration_sec=final_duration,
) )
add_log(thread_id, "Error", f"Execution failed: {e}", log_level="ERROR") add_log(thread_id, "Error", f"Execution failed: {e}", log_level="ERROR")