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:
@@ -275,8 +275,8 @@ class TextDetectionAgent(BaseAgent):
|
||||
except Exception as pdf_err:
|
||||
logger.warning(f"PyMuPDF vector text extraction failed ({pdf_err}).")
|
||||
|
||||
# Option B: Local PaddleOCR
|
||||
if not ocr_items and ocr_engine in ("paddle", "pdf_text", "got-ocr", "local"):
|
||||
# Option B: Local PaddleOCR (serves as spatial OCR baseline for Online Layer 2)
|
||||
if not ocr_items or ocr_engine in ("paddle", "pdf_text", "got-ocr", "local"):
|
||||
try:
|
||||
from src.utils.preprocess import preprocess_for_ocr
|
||||
from src.utils.paddle_ocr import run_paddle_ocr
|
||||
@@ -289,37 +289,39 @@ class TextDetectionAgent(BaseAgent):
|
||||
except Exception as paddle_err:
|
||||
logger.warning(f"Local PaddleOCR extraction failed ({paddle_err}).")
|
||||
|
||||
# Option C: Online Gemini Vision / Qwen 2.5-VL OCR
|
||||
if not ocr_items or ocr_engine in ("gemini_ocr", "qwen_ocr", "online_ocr"):
|
||||
# Option C: Online Gemini Vision / Qwen 2.5-VL / Qwen 3.7-VL 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})...")
|
||||
try:
|
||||
prompt_ocr = (
|
||||
"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(
|
||||
prompt=prompt_ocr,
|
||||
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,
|
||||
api_key=llm_api_key,
|
||||
base_url=llm_base_url,
|
||||
)
|
||||
# Parse fallback
|
||||
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:
|
||||
logger.warning(f"Online OCR engine failed ({online_ocr_err}).")
|
||||
|
||||
# ── LAYER 2: REASONING & STRUCTURING ENGINE ───────────────────────────
|
||||
|
||||
# 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)...")
|
||||
structured = classify_paddle_results(ocr_items, drawing_type=drawing_type)
|
||||
logger.info(f"Layer 2: Rule-based classifier produced {len(structured)} structured items.")
|
||||
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}'...")
|
||||
try:
|
||||
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"
|
||||
"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"
|
||||
"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"
|
||||
+ tag_categories + "\n"
|
||||
"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, "
|
||||
"correct OCR errors, map misplaced attributes, and output clean structured JSON."
|
||||
),
|
||||
image_path=raw_image,
|
||||
provider=llm_provider,
|
||||
model_name=llm_model,
|
||||
api_key=llm_api_key,
|
||||
|
||||
@@ -30,12 +30,17 @@ def init_db():
|
||||
current_step TEXT DEFAULT 'Initialized',
|
||||
created_at TEXT,
|
||||
updated_at TEXT,
|
||||
duration_sec REAL DEFAULT 0.0,
|
||||
error_message TEXT,
|
||||
error_traceback TEXT,
|
||||
config_json TEXT,
|
||||
result_json TEXT
|
||||
);
|
||||
""")
|
||||
try:
|
||||
cursor.execute("ALTER TABLE threads ADD COLUMN duration_sec REAL DEFAULT 0.0")
|
||||
except Exception:
|
||||
pass
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS thread_logs (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
@@ -96,6 +101,7 @@ def update_thread_status(
|
||||
result_dict: Optional[Dict[str, Any]] = None,
|
||||
drawing_type: Optional[str] = None,
|
||||
discipline: Optional[str] = None,
|
||||
duration_sec: Optional[float] = None,
|
||||
):
|
||||
now = datetime.now().isoformat()
|
||||
fields = ["updated_at = ?"]
|
||||
@@ -125,6 +131,9 @@ def update_thread_status(
|
||||
if discipline is not None:
|
||||
fields.append("discipline = ?")
|
||||
params.append(discipline)
|
||||
if duration_sec is not None:
|
||||
fields.append("duration_sec = ?")
|
||||
params.append(duration_sec)
|
||||
|
||||
params.append(thread_id)
|
||||
sql = f"UPDATE threads SET {', '.join(fields)} WHERE thread_id = ?"
|
||||
|
||||
+11
-2
@@ -94,12 +94,14 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
|
||||
"""
|
||||
Worker function executed in the background thread.
|
||||
"""
|
||||
start_time = time.time()
|
||||
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",
|
||||
duration_sec=0.0,
|
||||
)
|
||||
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)
|
||||
|
||||
for output in app.stream(initial_state):
|
||||
elapsed = round(time.time() - start_time, 1)
|
||||
if cancel_event.is_set():
|
||||
logger.info(f"Cancellation detected for thread '{thread_id}'")
|
||||
update_thread_status(
|
||||
@@ -134,6 +137,7 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
|
||||
progress=1.0,
|
||||
current_step="Cancelled 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")
|
||||
return
|
||||
@@ -156,12 +160,14 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
|
||||
current_step=desc,
|
||||
drawing_type=dt,
|
||||
discipline=disc,
|
||||
duration_sec=elapsed,
|
||||
)
|
||||
add_log(thread_id, node_name.replace("_", " ").title(), f"Completed stage: {desc}")
|
||||
|
||||
if cancel_event.is_set():
|
||||
return
|
||||
|
||||
final_duration = round(time.time() - start_time, 1)
|
||||
final_meta = current_state.get("metadata", {})
|
||||
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,
|
||||
drawing_type=final_meta.get("drawing_type", "GENERIC"),
|
||||
discipline=final_meta.get("discipline", "Unknown"),
|
||||
duration_sec=final_duration,
|
||||
)
|
||||
add_log(thread_id, "Completed", "Extraction pipeline finished successfully. Deliverables generated.")
|
||||
logger.info(f"Thread '{thread_id}' completed successfully.")
|
||||
add_log(thread_id, "Completed", f"Extraction finished in {final_duration}s. Deliverables generated.")
|
||||
logger.info(f"Thread '{thread_id}' completed successfully in {final_duration}s.")
|
||||
|
||||
except Exception as e:
|
||||
final_duration = round(time.time() - start_time, 1)
|
||||
tb = traceback.format_exc()
|
||||
logger.error(f"Thread '{thread_id}' failed: {e}\n{tb}")
|
||||
update_thread_status(
|
||||
@@ -192,6 +200,7 @@ def _run_workflow_worker(thread_id: str, initial_state: GraphState, cancel_event
|
||||
current_step="Execution Failed",
|
||||
error_message=str(e),
|
||||
error_traceback=tb,
|
||||
duration_sec=final_duration,
|
||||
)
|
||||
add_log(thread_id, "Error", f"Execution failed: {e}", log_level="ERROR")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user