feat: add EasyOCR engine with GPU support and generalize line/valve patterns for raster images
This commit is contained in:
@@ -201,6 +201,7 @@ st.sidebar.markdown("### 🔤 Layer 1: OCR Reading Layer")
|
|||||||
ocr_option = st.sidebar.selectbox(
|
ocr_option = st.sidebar.selectbox(
|
||||||
"1st Layer: OCR Text Engine",
|
"1st Layer: OCR Text Engine",
|
||||||
options=[
|
options=[
|
||||||
|
"EasyOCR (Local / Offline — Images & PDFs)",
|
||||||
"PyMuPDF Vector Text (Local / Offline)",
|
"PyMuPDF Vector Text (Local / Offline)",
|
||||||
"PaddleOCR (Local / Offline)",
|
"PaddleOCR (Local / Offline)",
|
||||||
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)",
|
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)",
|
||||||
@@ -211,9 +212,10 @@ ocr_option = st.sidebar.selectbox(
|
|||||||
"Qwen 3.7-VL / OpenRouter (Online)",
|
"Qwen 3.7-VL / OpenRouter (Online)",
|
||||||
],
|
],
|
||||||
index=0,
|
index=0,
|
||||||
help="Select the 1st layer OCR engine. PyMuPDF extracts 100% accurate vector text layer instantly.",
|
help="Select the 1st layer OCR engine. EasyOCR works reliably offline on GPU/CPU for both raster images (PNG/JPG) and PDFs.",
|
||||||
)
|
)
|
||||||
ocr_engine_map = {
|
ocr_engine_map = {
|
||||||
|
"EasyOCR (Local / Offline — Images & PDFs)": "easyocr",
|
||||||
"PyMuPDF Vector Text (Local / Offline)": "pdf_text",
|
"PyMuPDF Vector Text (Local / Offline)": "pdf_text",
|
||||||
"PaddleOCR (Local / Offline)": "paddle",
|
"PaddleOCR (Local / Offline)": "paddle",
|
||||||
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)": "pathnovo_api",
|
"Pathnovo ISA 5.1 Extraction Engine (High Accuracy)": "pathnovo_api",
|
||||||
@@ -223,7 +225,7 @@ ocr_engine_map = {
|
|||||||
"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",
|
"Qwen 3.7-VL / OpenRouter (Online)": "qwen_37_ocr",
|
||||||
}
|
}
|
||||||
ocr_engine = ocr_engine_map.get(ocr_option, "pdf_text")
|
ocr_engine = ocr_engine_map.get(ocr_option, "easyocr")
|
||||||
|
|
||||||
st.sidebar.markdown("### 🧠 Layer 2: Reasoning & Refinement Engine")
|
st.sidebar.markdown("### 🧠 Layer 2: Reasoning & Refinement Engine")
|
||||||
reasoning_option = st.sidebar.selectbox(
|
reasoning_option = st.sidebar.selectbox(
|
||||||
@@ -503,7 +505,7 @@ with tab_main_dashboard:
|
|||||||
"llm_api_key": llm_api_key,
|
"llm_api_key": llm_api_key,
|
||||||
"llm_base_url": llm_base_url,
|
"llm_base_url": llm_base_url,
|
||||||
"use_mocks": use_mocks,
|
"use_mocks": use_mocks,
|
||||||
"local_mode": local_mode or (reasoning_engine == "rule_based" and ocr_engine in ("paddle", "pdf_text")),
|
"local_mode": local_mode or (reasoning_engine == "rule_based" and ocr_engine in ("paddle", "pdf_text", "easyocr")),
|
||||||
"re_extracted_targets": [],
|
"re_extracted_targets": [],
|
||||||
"yolo_weights_path": yolo_weights_path,
|
"yolo_weights_path": yolo_weights_path,
|
||||||
"yolo_conf": yolo_conf,
|
"yolo_conf": yolo_conf,
|
||||||
|
|||||||
+23
-12
@@ -133,13 +133,19 @@ def run_pdf_text_extraction(pdf_path: str) -> List[Dict[str, Any]]:
|
|||||||
# ──────────────────────────────────────────────────────────────────────────────
|
# ──────────────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def _get_easyocr():
|
def _get_easyocr():
|
||||||
"""Lazy-load EasyOCR reader with English model."""
|
"""Lazy-load EasyOCR reader with English model (CUDA GPU accelerated if available)."""
|
||||||
global _easyocr_reader
|
global _easyocr_reader
|
||||||
if _easyocr_reader is None:
|
if _easyocr_reader is None:
|
||||||
import easyocr
|
import easyocr
|
||||||
logger.info("Initializing EasyOCR reader (en)...")
|
use_gpu = False
|
||||||
_easyocr_reader = easyocr.Reader(['en'], gpu=False, verbose=False)
|
try:
|
||||||
logger.info("EasyOCR initialized successfully.")
|
import torch
|
||||||
|
use_gpu = torch.cuda.is_available()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
logger.info(f"Initializing EasyOCR reader (en, gpu={use_gpu})...")
|
||||||
|
_easyocr_reader = easyocr.Reader(['en'], gpu=use_gpu, verbose=False)
|
||||||
|
logger.info(f"EasyOCR initialized successfully (gpu={use_gpu}).")
|
||||||
return _easyocr_reader
|
return _easyocr_reader
|
||||||
|
|
||||||
|
|
||||||
@@ -317,16 +323,21 @@ def run_paddle_ocr(image_path: str) -> List[Dict[str, Any]]:
|
|||||||
|
|
||||||
Returns list of dicts with: text, confidence, bbox, center_x, center_y.
|
Returns list of dicts with: text, confidence, bbox, center_x, center_y.
|
||||||
"""
|
"""
|
||||||
# ── Check for original PDF vector text first ──────────────────────────────
|
# ── Check for original matching PDF vector text if applicable ───────────
|
||||||
try:
|
try:
|
||||||
parent_dir = os.path.dirname(os.path.dirname(image_path))
|
if image_path.lower().endswith('.pdf'):
|
||||||
if os.path.exists(parent_dir):
|
pdf_items = run_pdf_text_extraction(image_path)
|
||||||
pdf_candidates = [f for f in os.listdir(parent_dir) if f.lower().endswith(".pdf")]
|
|
||||||
if pdf_candidates:
|
|
||||||
pdf_path = os.path.join(parent_dir, pdf_candidates[0])
|
|
||||||
pdf_items = run_pdf_text_extraction(pdf_path)
|
|
||||||
if len(pdf_items) > 20:
|
if len(pdf_items) > 20:
|
||||||
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from '{pdf_candidates[0]}'.")
|
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from '{image_path}'.")
|
||||||
|
return pdf_items
|
||||||
|
else:
|
||||||
|
# Check if there is an exact matching PDF in the same directory
|
||||||
|
base_stem = os.path.splitext(os.path.basename(image_path))[0].replace('_preprocessed', '')
|
||||||
|
matching_pdf = os.path.join(os.path.dirname(image_path), f"{base_stem}.pdf")
|
||||||
|
if os.path.exists(matching_pdf):
|
||||||
|
pdf_items = run_pdf_text_extraction(matching_pdf)
|
||||||
|
if len(pdf_items) > 20:
|
||||||
|
logger.info(f"run_paddle_ocr: PyMuPDF vector text layer extracted {len(pdf_items)} items from matching '{base_stem}.pdf'.")
|
||||||
return pdf_items
|
return pdf_items
|
||||||
except Exception as pdf_chk_err:
|
except Exception as pdf_chk_err:
|
||||||
logger.warning(f"PyMuPDF vector text check warning: {pdf_chk_err}")
|
logger.warning(f"PyMuPDF vector text check warning: {pdf_chk_err}")
|
||||||
|
|||||||
@@ -168,24 +168,30 @@ _SERVICE_CODE_PATTERN = re.compile(
|
|||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
# Valve tags (ISA 5.1 comprehensive):
|
# Valve tags (ISA 5.1 comprehensive + synthetic P&ID / schematic tags):
|
||||||
# Dense format: 26CB9131, 26GB9178 (no separator)
|
# Dense format: 26CB9131, 26GB9178 (no separator)
|
||||||
# Separated: 26-CB-9131A, 26-GB-9178
|
# Separated: 26-CB-9131A, 26-GB-9178
|
||||||
# Named control valves: HV-101, XV-201, FV-9076, PCV-9044, SDV-201
|
# Named control valves: HV-101, XV-201, FV-9076, PCV-9044, SDV-201
|
||||||
# Block valves: BV-101, NV-201, GV-101, BFV-201
|
# Block valves: BV-101, NV-201, GV-101, BFV-201
|
||||||
|
# Synthetic / Vendor prefixes: QR-70427, GH-83714, KL-21519, EF-96470, ST-93705, CS-97
|
||||||
_VALVE_SEARCH = re.compile(
|
_VALVE_SEARCH = re.compile(
|
||||||
r'\b('
|
r'\b('
|
||||||
r'\d{2}-?[A-Z]{2}-?\d{4,6}[A-Z]?' # 26CB9131, 26-CB-9131A
|
r'\d{2}-?[A-Z]{2}-?\d{4,6}[A-Z]?' # 26CB9131, 26-CB-9131A
|
||||||
r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV)[-–]\d{2,5}[A-Z]?' # HV-101, SDV-201
|
r'|(?:HV|XV|CV|PCV|FCV|TCV|LCV|EV|MOV|SDV|BDV|FV|UV|TV|LV|AV|ZV|RV|SV)[-–]\d{2,6}[A-Z]?' # HV-101, SDV-201
|
||||||
r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|RV|PRV)[-–]\d{2,5}[A-Z]?' # BV-101, NV-201
|
r'|(?:BV|NV|GV|BFV|SBV|NGV|PLV|PRV)[-–]\d{2,6}[A-Z]?' # BV-101, NV-201
|
||||||
|
r'|(?:QR|GH|KL|EF|ST|CS)[-–]\d{2,6}[A-Z]?' # Synthetic P&ID valve tags
|
||||||
r'|\bV-\d{3,5}[A-Z]?' # V-101
|
r'|\bV-\d{3,5}[A-Z]?' # V-101
|
||||||
|
r'|(?:(?:LOADING|SUCTION|PURGE|VENT|DISCHARGE|RECYCLE|BYPASS|RELIEF|BLOWDOWN|CHECK|MAINLINE(?:\s+BLOCK)?)\s+VALVE)' # Schematic valve callouts
|
||||||
r')\b',
|
r')\b',
|
||||||
re.IGNORECASE
|
re.IGNORECASE
|
||||||
)
|
)
|
||||||
|
|
||||||
# Line tags: 8"-PV-26-9035-FC11S-08, 12mm-PV-26-9116-FD70X-00, 3"-VA-26-9121-AC21-00, PV-26-9035-FC11S-08
|
# Line tags: 8"-PV-26-9035-FC11S-08, 12mm-PV-26-9116-FD70X-00, 3"-VA-26-9121-AC21-00, 4"-TA-4424, PV-26-9035-FC11S-08
|
||||||
_LINE_SEARCH = re.compile(
|
_LINE_SEARCH = re.compile(
|
||||||
r'((?:\d+(?:[/\.]\d+)?(?:["\']|mm|DN)?\s*[-–]?\s*)?[A-Z]{1,4}\s*[-–]\s*(?:\d{2,4}\s*[-–]\s*)?\d{3,5}'
|
r'((?:\d+(?:[/\.]\d+)?(?:["\']|mm|DN)\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})?)?'
|
||||||
|
r'|'
|
||||||
|
r'[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})?)',
|
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