diff --git a/app.py b/app.py index db84c81..1fdda59 100644 --- a/app.py +++ b/app.py @@ -9,6 +9,7 @@ import time import uuid import logging from datetime import datetime +from typing import Dict, Any, List, Optional import streamlit as st import pandas as pd from PIL import Image @@ -29,6 +30,16 @@ from src.thread_manager import ( 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 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"] # ─── Sidebar ─────────────────────────────────────────────────────────────────── -st.sidebar.markdown("## 🧵 Generation Threads") - -if all_threads: - for t in all_threads: - tid = t["thread_id"] - status = t["status"] - fname = t.get("filename", "Drawing") - dt_label = t.get("drawing_type", "GENERIC") - created = t.get("created_at", "")[:19].replace("T", " ") - - status_icon = "🟢" if status == "COMPLETED" else "🔵" if status == "RUNNING" else "❌" if status == "FAILED" else "⛔" - prog_str = f" ({int(t.get('progress', 0)*100)}%)" if status == "RUNNING" else "" - - col_t1, col_t2 = st.sidebar.columns([0.8, 0.2]) - with col_t1: - button_label = f"{status_icon} {fname[:18]}...{prog_str}" - is_active = (st.session_state.get("active_thread_id") == tid) - if st.button( - button_label, - key=f"btn_thread_{tid}", - use_container_width=True, - type="primary" if is_active else "secondary", - help=f"Type: {dt_label} | Status: {status} | Created: {created}", - ): - st.session_state["active_thread_id"] = tid - st.rerun() - - with col_t2: - if st.button("🗑️", key=f"del_thread_{tid}", help=f"Delete thread '{fname}' and its log"): - delete_thread(tid) - if st.session_state.get("active_thread_id") == tid: - remaining = [x for x in all_threads if x["thread_id"] != tid] - st.session_state["active_thread_id"] = remaining[0]["thread_id"] if remaining else None - st.rerun() -else: - st.sidebar.info("No previous extraction threads found.") - -st.sidebar.markdown("---") st.sidebar.markdown("## ⚙️ 2-Layer Extraction Pipeline") max_retries = st.sidebar.slider( @@ -195,6 +168,7 @@ ocr_option = st.sidebar.selectbox( "PyMuPDF Vector Text (Local / Offline)", "Gemini Vision OCR (Online API)", "Qwen 2.5-VL / Vision API (Online)", + "Qwen 3.7-VL / OpenRouter (Online)", ], index=0, 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", "Gemini Vision OCR (Online API)": "gemini_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") @@ -213,6 +188,7 @@ reasoning_option = st.sidebar.selectbox( options=[ "Rule-Based Regex Classifier (Local / Offline)", "Qwen 2.5 Reasoning Engine (OpenRouter / API)", + "Qwen 3.7 Reasoning Engine (OpenRouter / API)", "Gemini 2.0 Flash Engine (Online / API)", "OpenAI GPT-4o Engine (Online / API)", ], @@ -222,6 +198,7 @@ reasoning_option = st.sidebar.selectbox( reasoning_engine_map = { "Rule-Based Regex Classifier (Local / Offline)": "rule_based", "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", "OpenAI GPT-4o Engine (Online / API)": "openai", } @@ -232,8 +209,8 @@ llm_api_key = None llm_base_url = None llm_model = None -if reasoning_engine in ("qwen", "openai") or ocr_engine == "qwen_ocr": - llm_provider = "qwen" if ("Qwen" in reasoning_option or ocr_engine == "qwen_ocr") else "openai" +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 "qwen" in ocr_engine) else "openai" 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", ""))) llm_api_key = st.text_input( @@ -248,11 +225,11 @@ if reasoning_engine in ("qwen", "openai") or ocr_engine == "qwen_ocr": value=default_endpoint, 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( "Model Name", 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": llm_provider = "gemini" @@ -273,6 +250,45 @@ local_mode = st.sidebar.checkbox( if local_mode: st.sidebar.info("🔌 Full Offline Mode forced — PaddleOCR + Regex Classifier. Zero API tokens.") +st.sidebar.markdown("---") +st.sidebar.markdown("## 🧵 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 ─────────────────────────────────── tab_main_dashboard, tab_main_history = st.tabs([ "📊 Current Extraction Dashboard", @@ -375,10 +391,22 @@ with tab_main_dashboard: # ── Active Process & Progress Bar ───────────────────────────────── if status == "RUNNING" or status == "QUEUED": st.markdown("
⚡ Active Subprocess Progress
", 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]) with col_p1: 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: if st.button("🛑 Cancel Process", type="secondary", use_container_width=True): cancel_extraction_thread(active_id) @@ -429,7 +457,7 @@ with tab_main_dashboard: # Metadata Block st.markdown("
📋 Drawing Metadata
", 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: st.markdown(f"
Drawing Title
{metadata.get('title', 'N/A')}
", unsafe_allow_html=True) with col_m2: @@ -440,6 +468,9 @@ with tab_main_dashboard: st.markdown(f"
Discipline
{metadata.get('discipline', 'N/A')}
", unsafe_allow_html=True) with col_m5: st.markdown(f"
Client
{metadata.get('client_name', 'N/A')}
", unsafe_allow_html=True) + with col_m6: + proc_time = format_duration(active_thread.get("duration_sec")) + st.markdown(f"
Processing Time
{proc_time}
", unsafe_allow_html=True) # Extracted Data Tabs if graph: @@ -680,13 +711,16 @@ with tab_main_dashboard: st.subheader("Consistency Errors & Warnings") if reports: for r in reports: - icon = "❌" if r.get("severity") == "ERROR" else "⚠️" - bg_color = "#FDF2F2" if r.get("severity") == "ERROR" else "#FEFBF0" - border_color = "#F05252" if r.get("severity") == "ERROR" else "#FACA15" + is_err = (r.get("severity") == "ERROR") + icon = "❌" if is_err else "⚠️" + 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""" -
- {icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})
- {r.get('message')} +
+ {icon} {r.get('rule_id', 'RULE')} (Target: {r.get('target_tag', 'N/A')})
+ {r.get('message')}
""", unsafe_allow_html=True) else: @@ -783,6 +817,7 @@ with tab_main_history: "Type": t.get("drawing_type"), "Status": t.get("status"), "Progress": f"{int(t.get('progress', 0)*100)}%", + "Duration": format_duration(t.get("duration_sec")), "Step": t.get("current_step"), "Created At": t.get("created_at", "")[:19].replace("T", " "), }) diff --git a/src/agents/parallel_vision.py b/src/agents/parallel_vision.py index 405597b..4ceec52 100644 --- a/src/agents/parallel_vision.py +++ b/src/agents/parallel_vision.py @@ -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, diff --git a/src/db.py b/src/db.py index 4766cd5..e9b702e 100644 --- a/src/db.py +++ b/src/db.py @@ -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 = ?" diff --git a/src/thread_manager.py b/src/thread_manager.py index 0532cb1..4733532 100644 --- a/src/thread_manager.py +++ b/src/thread_manager.py @@ -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")