From 36c7739c7e2b1ee147fba1b1f871fad877a2a7b2 Mon Sep 17 00:00:00 2001 From: Avhinav Gupta Date: Tue, 11 Aug 2026 22:05:48 +0530 Subject: [PATCH] feat: Add P&ID dataset training pipeline, YOLOv8 symbol agent & LLM parameter tuning --- .env.example | 51 +++++- .gitignore | 3 + README.md | 3 - app.py | 62 ++++++- requirements.txt | 4 + src/agents/base.py | 74 ++++++-- src/agents/parallel_vision.py | 81 ++++++++- src/config.py | 123 ++++++++++--- src/state.py | 11 +- training/__init__.py | 1 + training/annotation_generator.py | 297 +++++++++++++++++++++++++++++++ training/corpus_builder.py | 239 +++++++++++++++++++++++++ training/train.py | 229 ++++++++++++++++++++++++ training/vlm_dataset_builder.py | 269 ++++++++++++++++++++++++++++ training/yolo_train_launcher.py | 223 +++++++++++++++++++++++ 15 files changed, 1612 insertions(+), 58 deletions(-) create mode 100644 training/__init__.py create mode 100644 training/annotation_generator.py create mode 100644 training/corpus_builder.py create mode 100644 training/train.py create mode 100644 training/vlm_dataset_builder.py create mode 100644 training/yolo_train_launcher.py diff --git a/.env.example b/.env.example index 09620da..6456699 100644 --- a/.env.example +++ b/.env.example @@ -1,14 +1,53 @@ -# API Keys Configuration +# ── API Keys ──────────────────────────────────────────────────────────────────── GEMINI_API_KEY=your_gemini_api_key_here OPENROUTER_API_KEY=sk-or-v1-your_openrouter_api_key_here OPENAI_API_KEY=your_openai_api_key_here GROQ_API_KEY=your_groq_api_key_here -# Qwen 2.5 / OpenRouter Settings -QWEN_BASE_URL=https://openrouter.ai/api/v1 -QWEN_MODEL=qwen/qwen-2.5-72b-instruct +# ── Pathnovo (enhanced fallback — ISA 5.1 extraction API) ──────────────────── +PATHNOVO_API_KEY=your_pathnovo_key_here +PATHNOVO_TIMEOUT=60 +PATHNOVO_MAX_RETRIES=3 -# Default Model Selection -GEMINI_MODEL=gemini-2.0-flash +# ── Model Versions ─────────────────────────────────────────────────────────────── +# Gemini: 2.5-flash (default, fast) or 2.5-pro (higher accuracy, slower) +GEMINI_MODEL=gemini-2.5-flash +GEMINI_PRO_MODEL=gemini-2.5-pro +# Qwen: upgraded to qwen2.5-vl-72b-instruct (better vision understanding) +QWEN_MODEL=qwen/qwen2.5-vl-72b-instruct +QWEN_BASE_URL=https://openrouter.ai/api/v1 OPENAI_MODEL=gpt-4o GROQ_MODEL=llama-3.3-70b-versatile + +# ── Per-Agent Token Budgets ───────────────────────────────────────────────────── +# TextRecognitionAgent: high budget for dense tag/spec extraction +TEXT_AGENT_MAX_TOKENS=16384 +# SymbolRecognitionAgent: moderate budget for structured bounding-box output +SYMBOL_AGENT_MAX_TOKENS=8192 +# PipelineRecognitionAgent: moderate budget for relation/geometry lists +PIPELINE_AGENT_MAX_TOKENS=8192 +# CompilerAgent: highest budget — builds the full engineering graph +COMPILER_MAX_TOKENS=32768 +# Default fallback for all other agents +DEFAULT_MAX_TOKENS=8192 + +# ── Per-Agent Temperature Tuning ──────────────────────────────────────────────── +# Deterministic for tag/spec parsing (must be exact) +TEXT_AGENT_TEMPERATURE=0.0 +# Slight randomness helps with ambiguous ISA symbols +SYMBOL_AGENT_TEMPERATURE=0.1 +# Deterministic for topology/connectivity tracing +PIPELINE_AGENT_TEMPERATURE=0.0 + +# ── Retry & Exponential Backoff ───────────────────────────────────────────────── +LLM_MAX_RETRIES=5 +LLM_BASE_DELAY_SECONDS=2.0 +LLM_MAX_DELAY_SECONDS=60.0 + +# ── Token Budget Warning ──────────────────────────────────────────────────────── +# Warns in logs when response reaches 85% of token budget +LLM_TOKEN_BUDGET_WARN_THRESHOLD=0.85 + +# ── Text Chunking ──────────────────────────────────────────────────────────────── +CHUNK_SIZE=1200 +CHUNK_OVERLAP=250 diff --git a/.gitignore b/.gitignore index 447ca00..612de3b 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,9 @@ outputs/ rasterized/ temp/ tmp/ +runs/ +*.pt + # ------------------------------------------------------------------------------ # 5. Databases, Execution Logs & Runtime Metrics diff --git a/README.md b/README.md index dd262e9..e4e48ca 100644 --- a/README.md +++ b/README.md @@ -234,10 +234,7 @@ pid_project/ --- -## 👤 Author & Contact -**Developer**: Abhinav Gupta -**Email**: [abhinavgupta15.ag@gmail.com](mailto:abhinavgupta15.ag@gmail.com) --- diff --git a/app.py b/app.py index e6342ef..0d90965 100644 --- a/app.py +++ b/app.py @@ -227,21 +227,74 @@ symbol_option = st.sidebar.selectbox( options=[ "Pathnovo ISA 5.1 Instrument & Symbol Engine", "ISA-5.1 VLM Symbol Detector (Multimodal VLM)", + "🏋️ Trained YOLOv8 Symbol Detector (Local / Offline)", "GLM-OCR / RF-DETR Object Pipeline (Local / API)", "Heuristic Bounding Box Harvester (Local / Offline)", ], index=0, - help="Select symbol detector. Pathnovo ISA 5.1 & VLMs classify graphical symbols & bounding boxes.", + help="Select symbol detector. 'Trained YOLOv8' uses your custom best.pt trained on the P&ID dataset — fastest and offline.", ) symbol_engine_map = { "Pathnovo ISA 5.1 Instrument & Symbol Engine": "pathnovo_isa51", "ISA-5.1 VLM Symbol Detector (Multimodal VLM)": "vlm", + "🏋️ Trained YOLOv8 Symbol Detector (Local / Offline)": "yolo_trained", "GLM-OCR / RF-DETR Object Pipeline (Local / API)": "glm_rfdetr", "Heuristic Bounding Box Harvester (Local / Offline)": "local", } symbol_engine = symbol_engine_map.get(symbol_option, "pathnovo_isa51") -st.sidebar.markdown("### ⚡ Pipeline & Connectivity Agent Engine") +# ── Trained YOLO settings panel (only shown when yolo_trained is selected) ── +yolo_weights_path = None +if symbol_engine == "yolo_trained": + _default_yolo_path = os.getenv( + "DEFAULT_YOLO_WEIGHTS", + os.path.join(os.getcwd(), "training", "outputs", "yolo_runs", + "pid_symbol_detector", "weights", "best.pt") + ) + _yolo_weights_exist = os.path.exists(_default_yolo_path) + + with st.sidebar.expander("⚙️ Trained YOLOv8 Settings", expanded=True): + if _yolo_weights_exist: + st.success(f"✅ Weights found: `.../{'/'.join(_default_yolo_path.replace(os.sep, '/').split('/')[-3:])}`") + else: + st.warning( + "⚠️ No trained weights found at the default path. " + "Run `python training/train.py yolo` first, or paste a custom path below." + ) + + yolo_weights_path = st.text_input( + "Weights Path (best.pt)", + value=_default_yolo_path, + help="Absolute path to your trained YOLOv8 best.pt weights file.", + key="yolo_weights_path_input", + ) + + yolo_conf = st.slider( + "Detection Confidence Threshold", + min_value=0.10, max_value=0.90, value=0.25, step=0.05, + help="Lower → more detections (may include false positives). Higher → fewer but more precise.", + key="yolo_conf_slider", + ) + + yolo_iou = st.slider( + "NMS IoU Threshold", + min_value=0.30, max_value=0.80, value=0.45, step=0.05, + help="Controls how aggressively overlapping boxes are suppressed.", + key="yolo_iou_slider", + ) + + st.caption( + "🖥️ Will run on **CUDA GPU (RTX 3050)** if available, otherwise CPU. " + "Model class vocab: 26 ISA-5.1 symbol classes." + ) + +# Defaults when yolo_trained is not selected +if symbol_engine != "yolo_trained": + yolo_weights_path = None + yolo_conf = 0.25 + yolo_iou = 0.45 + + pipeline_option = st.sidebar.selectbox( "Pipeline & Line Tracing Engine", options=[ @@ -426,8 +479,13 @@ with tab_main_dashboard: "use_mocks": use_mocks, "local_mode": local_mode or (reasoning_engine == "rule_based" and ocr_engine in ("paddle", "pdf_text")), "re_extracted_targets": [], + "yolo_weights_path": yolo_weights_path, + "yolo_conf": yolo_conf, + "yolo_iou": yolo_iou, + } + # Start asynchronous background thread start_extraction_thread( thread_id=new_thread_id, diff --git a/requirements.txt b/requirements.txt index 0a342d6..ad5edcc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,3 +15,7 @@ pdf2image>=1.17.0 opencv-python-headless>=4.8.0 paddlepaddle>=2.6.0 paddleocr>=2.7.0 +# Training dependencies +ultralytics>=8.0.0 +datasets>=2.0.0 +tqdm>=4.60.0 diff --git a/src/agents/base.py b/src/agents/base.py index c2ee2b3..3ecb7d2 100644 --- a/src/agents/base.py +++ b/src/agents/base.py @@ -6,7 +6,11 @@ import logging from typing import Type, TypeVar, Optional, Union, List, Dict, Any from pydantic import BaseModel from langchain_core.messages import SystemMessage, HumanMessage -from src.config import get_gemini_client, get_llm_client +from src.config import ( + get_gemini_client, get_llm_client, + LLM_MAX_RETRIES, LLM_BASE_DELAY_SECONDS, LLM_MAX_DELAY_SECONDS, + LLM_TOKEN_BUDGET_WARN_THRESHOLD, DEFAULT_MAX_TOKENS, +) T = TypeVar('T', bound=BaseModel) logger = logging.getLogger(__name__) @@ -95,15 +99,17 @@ class BaseAgent: base_url: Optional[str] = None, temperature: float = 0.0, has_image: bool = False, + max_tokens: Optional[int] = None, ): """ Helper to select the requested LLM client (Gemini, Qwen, OpenAI, etc.). Auto-remaps text-only model names to vision models when images are present. + Passes per-agent max_tokens budget to the underlying client factory. """ # Auto-remap text-only model names when vision/image input is required if has_image and model_name and "instruct" in model_name.lower() and "-vl" not in model_name.lower(): - logger.info(f"Auto-mapping text-only model '{model_name}' to vision model 'qwen/qwen-3.7-vl' for multimodal input.") - model_name = "qwen/qwen-3.7-vl" + logger.info(f"Auto-mapping text-only model '{model_name}' to vision model 'qwen/qwen2.5-vl-72b-instruct' for multimodal input.") + model_name = "qwen/qwen2.5-vl-72b-instruct" if provider and provider.lower() not in ("default", "gemini"): return get_llm_client( @@ -112,10 +118,11 @@ class BaseAgent: api_key=api_key, base_url=base_url, temperature=temperature, + max_tokens=max_tokens, ) if self.llm is not None: return self.llm - return get_gemini_client(temperature=temperature, model_name=model_name) + return get_gemini_client(temperature=temperature, model_name=model_name, max_tokens=max_tokens) def invoke_structured( self, @@ -129,10 +136,12 @@ class BaseAgent: model_name: Optional[str] = None, api_key: Optional[str] = None, base_url: Optional[str] = None, + max_tokens: Optional[int] = None, ) -> T: """ Invokes the target model with a requested Pydantic output schema. Supports text-only and multimodal structured extraction across providers. + Uses configurable exponential backoff from LLM_MAX_RETRIES / LLM_BASE_DELAY_SECONDS. """ has_img = bool(image_path or image_uri) llm_instance = self.get_target_llm( @@ -141,7 +150,12 @@ class BaseAgent: api_key=api_key, base_url=base_url, has_image=has_img, + max_tokens=max_tokens, ) + + # Log token budget if set + if max_tokens: + logger.debug(f"invoke_structured: token budget = {max_tokens} tokens.") structured_llm = llm_instance.with_structured_output(schema) @@ -171,32 +185,37 @@ class BaseAgent: messages.append(HumanMessage(content=content)) else: messages.append(HumanMessage(content=prompt)) - - max_attempts = 2 if has_img else 3 - delay = 1 + + # Configurable retry policy with exponential backoff + max_attempts = LLM_MAX_RETRIES + base_delay = LLM_BASE_DELAY_SECONDS + max_delay = LLM_MAX_DELAY_SECONDS + delay = base_delay + for attempt in range(max_attempts): try: response = structured_llm.invoke(messages) return response except Exception as e: err_msg = str(e) - # Fast failover on fatal client/model errors to avoid wasting minutes + # Fast failover on fatal client/model errors if "400" in err_msg or "Invalid" in err_msg or "unsupported" in err_msg or "BadRequest" in err_msg: logger.warning(f"Fatal client/model error ({err_msg[:120]}). Fast failover to local fallback.") raise e if "429" in err_msg or "RESOURCE_EXHAUSTED" in err_msg or "Quota exceeded" in err_msg: if attempt < max_attempts - 1: - wait_time = delay + random.uniform(0.5, 1.5) - logger.warning(f"Rate limit hit. Waiting {wait_time:.2f} seconds before retry...") + wait_time = min(delay + random.uniform(0.5, 2.0), max_delay) + logger.warning(f"Rate limit hit (attempt {attempt+1}/{max_attempts}). Waiting {wait_time:.1f}s before retry...") time.sleep(wait_time) - delay *= 2 + delay = min(delay * 2, max_delay) continue else: raise e else: if attempt < max_attempts - 1: - time.sleep(1) + time.sleep(min(delay, max_delay)) + delay = min(delay * 2, max_delay) continue else: raise e @@ -212,17 +231,22 @@ class BaseAgent: model_name: Optional[str] = None, api_key: Optional[str] = None, base_url: Optional[str] = None, + max_tokens: Optional[int] = None, ) -> str: """ Standard text-based model invocation (returns raw string). Supports multimodal context via image path or file URI across providers. + Logs token budget usage warnings when nearing LLM_TOKEN_BUDGET_WARN_THRESHOLD. """ llm_instance = self.get_target_llm( provider=provider, model_name=model_name, api_key=api_key, base_url=base_url, + max_tokens=max_tokens, ) + + _budget = max_tokens or DEFAULT_MAX_TOKENS messages = [] if system_instruction: @@ -250,21 +274,33 @@ class BaseAgent: messages.append(HumanMessage(content=content)) else: messages.append(HumanMessage(content=prompt)) - - max_attempts = 5 - delay = 4 + + # Configurable retry policy with exponential backoff + max_attempts = LLM_MAX_RETRIES + base_delay = LLM_BASE_DELAY_SECONDS + max_delay = LLM_MAX_DELAY_SECONDS + delay = base_delay + for attempt in range(max_attempts): try: response = llm_instance.invoke(messages) - return str(response.content) + result = str(response.content) + # Token budget warning: rough char-to-token estimate (4 chars ≈ 1 token) + approx_tokens = len(result) // 4 + if approx_tokens > _budget * LLM_TOKEN_BUDGET_WARN_THRESHOLD: + logger.warning( + f"Token budget warning: response ~{approx_tokens} tokens " + f"({approx_tokens/_budget*100:.0f}% of {_budget} budget)." + ) + return result except Exception as e: err_msg = str(e) if "429" in err_msg or "RESOURCE_EXHAUSTED" in err_msg or "Quota exceeded" in err_msg: if attempt < max_attempts - 1: jitter = random.uniform(0.5, 2.5) - wait_time = delay + jitter - logger.warning(f"Rate limit 429 hit. Waiting {wait_time:.2f} seconds before retry...") + wait_time = min(delay + jitter, max_delay) + logger.warning(f"Rate limit 429 hit (attempt {attempt+1}/{max_attempts}). Waiting {wait_time:.1f}s before retry...") time.sleep(wait_time) - delay *= 2 + delay = min(delay * 2, max_delay) continue raise e diff --git a/src/agents/parallel_vision.py b/src/agents/parallel_vision.py index 3390051..e1d24d2 100644 --- a/src/agents/parallel_vision.py +++ b/src/agents/parallel_vision.py @@ -33,6 +33,15 @@ from src.utils.mock_data import MOCK_TEXT_ELEMENTS, MOCK_SYMBOLS, MOCK_RELATIONS logger = logging.getLogger(__name__) +def _is_cuda_available() -> bool: + """Returns True if a CUDA GPU is available (e.g. RTX 3050).""" + try: + import torch + return torch.cuda.is_available() + except ImportError: + return False + + # ────────────────────────────────────────────────────────────────────────────── # Drawing-type-aware prompt builders # ────────────────────────────────────────────────────────────────────────────── @@ -426,8 +435,78 @@ class SymbolRecognitionAgent(BaseAgent): except Exception as p_err: logger.warning(f"Pathnovo Symbol Parser failed ({p_err}). Falling back to standard VLM pipeline.") - # Option B: VLM or GLM-OCR / RF-DETR object detector + # Option B: Trained YOLOv8 Symbol Detector (custom best.pt from training pipeline) + elif symbol_engine == "yolo_trained": + weights_path = ( + state.get("yolo_weights_path") + or os.getenv("DEFAULT_YOLO_WEIGHTS", "") + ) + if not weights_path or not os.path.exists(weights_path): + logger.warning( + f"YOLOv8 weights not found at '{weights_path}'. " + "Falling back to heuristic harvester. " + "Run training first: python training/train.py yolo ..." + ) + else: + try: + from ultralytics import YOLO + from src.agents.base import BaseAgent as _BA + + logger.info(f"SymbolRecognitionAgent: Loading trained YOLOv8 from '{weights_path}'...") + yolo_model = YOLO(weights_path) + + # Encode image for inference + import numpy as np + from PIL import Image as _PilImage + with _PilImage.open(raw_image) as _img: + img_w, img_h = _img.size + _img_rgb = _img.convert("RGB") + + results = yolo_model.predict( + source=str(raw_image), + conf=state.get("yolo_conf") or 0.25, + iou=state.get("yolo_iou") or 0.45, + imgsz=800, # Match training imgsz + device="0" if _is_cuda_available() else "cpu", + verbose=False, + ) + + # YOLO class names from the training annotation_generator + from training.annotation_generator import SYMBOL_CLASSES + + for result in results: + for box in result.boxes: + cls_id = int(box.cls[0].item()) + conf_val = float(box.conf[0].item()) + # box.xyxyn → normalized [x1, y1, x2, y2] + x1n, y1n, x2n, y2n = box.xyxyn[0].tolist() + sym_type = SYMBOL_CLASSES[cls_id] if cls_id < len(SYMBOL_CLASSES) else "UNKNOWN" + + symbols.append({ + "symbol_type" : sym_type, + "inferred_tag": None, + "ymin" : round(y1n, 4), + "xmin" : round(x1n, 4), + "ymax" : round(y2n, 4), + "xmax" : round(x2n, 4), + "confidence" : round(conf_val, 3), + }) + + logger.info( + f"SymbolRecognitionAgent (yolo_trained): detected {len(symbols)} symbols " + f"from '{os.path.basename(weights_path)}'." + ) + except ImportError: + logger.error( + "ultralytics not installed. Run: pip install ultralytics. " + "Falling back to heuristic harvester." + ) + except Exception as yolo_err: + logger.error(f"Trained YOLOv8 inference failed ({yolo_err}). Falling back to heuristic harvester.") + + # Option C: VLM or GLM-OCR / RF-DETR object detector elif not (local_mode or symbol_engine == "local"): + prompt = ( f"You are an expert industrial vision detector specializing in ISA-5.1 and engineering symbol recognition for {dt_label} drawings.\n" f"Identify all graphical component symbols present in this drawing image.\n\n" diff --git a/src/config.py b/src/config.py index 24e35ad..e9292b9 100644 --- a/src/config.py +++ b/src/config.py @@ -1,37 +1,77 @@ import os +import logging from typing import Optional from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() -# API Keys -GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "") -OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") -GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") -OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "") -QWEN_API_KEY = os.getenv("QWEN_API_KEY", os.getenv("OPENROUTER_API_KEY", os.getenv("DASHSCOPE_API_KEY", os.getenv("OPENAI_API_KEY", "")))) -PATHNOVO_API_KEY = os.getenv("PATHNOVO_API_KEY", "") +logger = logging.getLogger(__name__) -# API Endpoints -QWEN_BASE_URL = os.getenv("QWEN_BASE_URL", "https://openrouter.ai/api/v1") -OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") +# ── API Keys ─────────────────────────────────────────────────────────────────── +GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "") +OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "") +GROQ_API_KEY = os.getenv("GROQ_API_KEY", "") +OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY", "") +QWEN_API_KEY = os.getenv("QWEN_API_KEY", os.getenv("OPENROUTER_API_KEY", os.getenv("DASHSCOPE_API_KEY", os.getenv("OPENAI_API_KEY", "")))) +PATHNOVO_API_KEY = os.getenv("PATHNOVO_API_KEY", "") + +# ── API Endpoints ────────────────────────────────────────────────────────────── +QWEN_BASE_URL = os.getenv("QWEN_BASE_URL", "https://openrouter.ai/api/v1") +OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL", "https://api.openai.com/v1") PATHNOVO_BASE_URL = os.getenv("PATHNOVO_BASE_URL", "https://api.pathnovo.com/v1/pid/extract") -# Model configurations -GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.0-flash") -OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o") -GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile") -QWEN_MODEL = os.getenv("QWEN_MODEL", "qwen/qwen-2.5-72b-instruct") +# ── Model Versions ───────────────────────────────────────────────────────────── +# Gemini: upgraded to 2.5-flash (faster, higher context) with 2.5-pro available for accuracy +GEMINI_MODEL = os.getenv("GEMINI_MODEL", "gemini-2.5-flash") +GEMINI_PRO_MODEL = os.getenv("GEMINI_PRO_MODEL", "gemini-2.5-pro") +OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o") +GROQ_MODEL = os.getenv("GROQ_MODEL", "llama-3.3-70b-versatile") +# Qwen: upgraded to qwen2.5-vl-72b-instruct for better vision understanding +QWEN_MODEL = os.getenv("QWEN_MODEL", "qwen/qwen2.5-vl-72b-instruct") -# Default settings -CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1200")) +# ── Text Chunking ────────────────────────────────────────────────────────────── +CHUNK_SIZE = int(os.getenv("CHUNK_SIZE", "1200")) CHUNK_OVERLAP = int(os.getenv("CHUNK_OVERLAP", "250")) +# ── Per-Agent Token Budgets ──────────────────────────────────────────────────── +# TextRecognitionAgent needs high token budget for dense tag extraction +TEXT_AGENT_MAX_TOKENS = int(os.getenv("TEXT_AGENT_MAX_TOKENS", "16384")) +# SymbolRecognitionAgent: moderate budget for bounding-box structured output +SYMBOL_AGENT_MAX_TOKENS = int(os.getenv("SYMBOL_AGENT_MAX_TOKENS", "8192")) +# PipelineRecognitionAgent: moderate budget for relation/geometry lists +PIPELINE_AGENT_MAX_TOKENS = int(os.getenv("PIPELINE_AGENT_MAX_TOKENS", "8192")) +# CompilerAgent: highest budget — builds the full engineering graph +COMPILER_MAX_TOKENS = int(os.getenv("COMPILER_MAX_TOKENS", "32768")) +# Default fallback for all other agents +DEFAULT_MAX_TOKENS = int(os.getenv("DEFAULT_MAX_TOKENS", "8192")) -def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None): +# ── Per-Agent Temperature Tuning ─────────────────────────────────────────────── +# Text extraction: deterministic (temperature=0.0) for consistent tag parsing +TEXT_AGENT_TEMPERATURE = float(os.getenv("TEXT_AGENT_TEMPERATURE", "0.0")) +# Symbol detection: slight randomness helps with ambiguous symbols +SYMBOL_AGENT_TEMPERATURE = float(os.getenv("SYMBOL_AGENT_TEMPERATURE", "0.1")) +# Pipeline/relation tracing: deterministic for consistent topology +PIPELINE_AGENT_TEMPERATURE = float(os.getenv("PIPELINE_AGENT_TEMPERATURE", "0.0")) + +# ── Retry & Backoff Policy ───────────────────────────────────────────────────── +LLM_MAX_RETRIES = int(os.getenv("LLM_MAX_RETRIES", "5")) +LLM_BASE_DELAY_SECONDS = float(os.getenv("LLM_BASE_DELAY_SECONDS", "2.0")) +LLM_MAX_DELAY_SECONDS = float(os.getenv("LLM_MAX_DELAY_SECONDS", "60.0")) + +# ── Pathnovo Enhanced Fallback Settings ─────────────────────────────────────── +PATHNOVO_TIMEOUT = int(os.getenv("PATHNOVO_TIMEOUT", "60")) +PATHNOVO_MAX_RETRIES = int(os.getenv("PATHNOVO_MAX_RETRIES", "3")) + +# ── Token Budget Warning Threshold (fraction of max_tokens) ─────────────────── +LLM_TOKEN_BUDGET_WARN_THRESHOLD = float(os.getenv("LLM_TOKEN_BUDGET_WARN_THRESHOLD", "0.85")) + + +def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None, + max_tokens: Optional[int] = None): """ Initializes and returns the ChatGoogleGenerativeAI instance. + Defaults to gemini-2.5-flash with configurable token budget. """ if not GEMINI_API_KEY: raise ValueError("GEMINI_API_KEY is not set in the environment or .env file.") @@ -42,7 +82,7 @@ def get_gemini_client(temperature: float = 0.0, model_name: Optional[str] = None model=model_name or GEMINI_MODEL, google_api_key=GEMINI_API_KEY, temperature=temperature, - max_output_tokens=8192, + max_output_tokens=max_tokens or DEFAULT_MAX_TOKENS, ) @@ -52,12 +92,15 @@ def get_llm_client( api_key: Optional[str] = None, base_url: Optional[str] = None, temperature: float = 0.0, + max_tokens: Optional[int] = None, ): """ - Universal factory for LLM clients supporting Gemini, OpenRouter (Qwen 2.5), OpenAI, - Groq, or local endpoints (Ollama/vLLM). + Universal factory for LLM clients supporting Gemini (2.5-flash / 2.5-pro), + OpenRouter (Qwen2.5-VL-72B), OpenAI, Groq, Pathnovo, and local PaddleOCR fallback. + Accepts per-agent max_tokens for fine-grained token budget control. """ prov = (provider or "gemini").lower() + _max_tokens = max_tokens or DEFAULT_MAX_TOKENS if prov == "gemini": key = api_key or GEMINI_API_KEY @@ -68,7 +111,21 @@ def get_llm_client( model=model_name or GEMINI_MODEL, google_api_key=key, temperature=temperature, - max_output_tokens=8192, + max_output_tokens=_max_tokens, + ) + + elif prov == "gemini_pro": + # High-accuracy path: use Gemini 2.5 Pro for complex structured extraction + key = api_key or GEMINI_API_KEY + if not key: + raise ValueError("GEMINI_API_KEY is required for Gemini Pro provider.") + from langchain_google_genai import ChatGoogleGenerativeAI + logger.info(f"Using Gemini Pro model: {GEMINI_PRO_MODEL} (higher accuracy, slower).") + return ChatGoogleGenerativeAI( + model=model_name or GEMINI_PRO_MODEL, + google_api_key=key, + temperature=temperature, + max_output_tokens=_max_tokens, ) elif prov in ("qwen", "openrouter", "openai_compatible", "openai"): @@ -92,10 +149,10 @@ def get_llm_client( openai_api_key=key, openai_api_base=endpoint, temperature=temperature, - max_tokens=4096, + max_tokens=_max_tokens, default_headers=headers, ) - + elif prov == "groq": key = api_key or GROQ_API_KEY if not key: @@ -106,8 +163,22 @@ def get_llm_client( openai_api_key=key, openai_api_base="https://api.groq.com/openai/v1", temperature=temperature, + max_tokens=_max_tokens, ) - + + elif prov in ("pathnovo", "pathnovo_api"): + # Pathnovo is a REST API client, not an LLM — return None here; + # agents handle Pathnovo via PathnovoAPIClient directly. + logger.info("Provider 'pathnovo' selected. Agents will use PathnovoAPIClient directly.") + return None + + elif prov in ("paddle", "local", "paddle_ocr"): + # PaddleOCR is a local OCR engine — return None here; + # agents handle PaddleOCR via run_paddle_ocr() directly. + logger.info("Provider 'paddle' selected. Agents will use PaddleOCR locally (zero API cost).") + return None + else: # Fallback to Gemini - return get_gemini_client(temperature=temperature, model_name=model_name) + logger.warning(f"Unknown provider '{prov}'. Falling back to Gemini.") + return get_gemini_client(temperature=temperature, model_name=model_name, max_tokens=_max_tokens) diff --git a/src/state.py b/src/state.py index 9156f30..572e829 100644 --- a/src/state.py +++ b/src/state.py @@ -66,7 +66,7 @@ class GraphState(TypedDict): # Selected Layer 2 Reasoning Engine choice ('rule_based', 'qwen', 'qwen_37', 'gemini', 'openai') reasoning_engine: Optional[str] - # Selected Symbol Recognition Engine choice ('vlm', 'glm_rfdetr', 'local') + # Selected Symbol Recognition Engine choice ('vlm', 'glm_rfdetr', 'local', 'yolo_trained') symbol_engine: Optional[str] # Selected Pipeline Recognition Engine choice ('cv_vlm_tracer', 'vlm_tracer', 'proximity_tracer') @@ -86,3 +86,12 @@ class GraphState(TypedDict): # List of tags already sent for re-extraction to prevent infinite validation loops re_extracted_targets: List[str] + + # Path to custom trained YOLOv8 weights (best.pt) for symbol detection + # Set when symbol_engine='yolo_trained'. Falls back to DEFAULT_YOLO_WEIGHTS env var. + yolo_weights_path: Optional[str] + + # YOLOv8 inference thresholds (tunable from Streamlit sidebar) + yolo_conf: Optional[float] # confidence threshold (default 0.25) + yolo_iou: Optional[float] # NMS IoU threshold (default 0.45) + diff --git a/training/__init__.py b/training/__init__.py new file mode 100644 index 0000000..9e8a096 --- /dev/null +++ b/training/__init__.py @@ -0,0 +1 @@ +"""Training package for SID-AI P&ID Dataset.""" diff --git a/training/annotation_generator.py b/training/annotation_generator.py new file mode 100644 index 0000000..9c2ea8d --- /dev/null +++ b/training/annotation_generator.py @@ -0,0 +1,297 @@ +""" +Strategy B — Part 1: Object Detection Annotation Generator. + +Runs SymbolRecognitionAgent on each patch image to extract ISA-5.1 symbol +bounding boxes, then converts them to: + 1. YOLO v8 .txt format (one file per patch image) + 2. COCO JSON format (single merged annotations file) + 3. data.yaml (YOLOv8 dataset config) + +Usage: + python training/train.py annotate --dataset C:/path/to/pid_aug_dataset/claude + python training/train.py annotate --dataset C:/path/to/pid_aug_dataset/claude --limit 10 +""" + +import os +import sys +import json +import shutil +import csv +import logging +from pathlib import Path +from typing import List, Dict, Any, Optional, Tuple + +logger = logging.getLogger(__name__) + +# ISA-5.1 Symbol class labels (used as YOLO class IDs) +SYMBOL_CLASSES = [ + "INST_BUBBLE", # 0 — Instrument circles (PI, TI, FI, etc.) + "COMPRESSOR", # 1 + "MOTOR", # 2 + "COOLER", # 3 + "FILTER", # 4 + "VESSEL", # 5 + "PUMP", # 6 + "HEAT_EXCHANGER", # 7 + "GLOBE_VALVE", # 8 + "GATE_VALVE", # 9 + "CHECK_VALVE", # 10 + "BALL_VALVE", # 11 + "CONTROL_VALVE", # 12 + "NEEDLE_VALVE", # 13 + "BUTTERFLY_VALVE", # 14 + "SAFETY_VALVE", # 15 + "PSV", # 16 + "STRAINER", # 17 + "REDUCER", # 18 + "NOZZLE", # 19 + "SPECTACLE_BLIND", # 20 + "TEE", # 21 + "FLANGE", # 22 + "SKID", # 23 + "COALESCER", # 24 + "SEPARATOR", # 25 +] + +CLASS_TO_ID = {cls: i for i, cls in enumerate(SYMBOL_CLASSES)} + + +def _run_symbol_recognition( + image_path: str, + provider: Optional[str] = None, + model_name: Optional[str] = None, +) -> List[Dict[str, Any]]: + """ + Runs SymbolRecognitionAgent on a patch image. + Returns list of symbol dicts with keys: symbol_type, ymin, xmin, ymax, xmax, inferred_tag. + """ + try: + sys.path.insert(0, str(Path(__file__).parent.parent)) + from src.agents.parallel_vision import SymbolRecognitionAgent + from src.state import GraphState + + agent = SymbolRecognitionAgent() + state: GraphState = { + "raw_documents": [image_path], + "metadata": {"drawing_type": "PID", "rasterized_pages": [image_path]}, + "engineering_context": {}, + "extracted_entities": {"text_elements": [], "symbols": [], "relations": [], "geometry": {}}, + "engineering_graph": None, + "validation_reports": [], + "missing_entities": [], + "revision_history": [], + "deliverables": {}, + "re_extraction_count": 0, + "max_re_extractions": 1, + "re_extracted_targets": [], + "symbol_engine": "vlm", + "llm_provider": provider, + "llm_model": model_name, + "use_mocks": False, + "local_mode": False, + } + result = agent.run(state) + return result.get("extracted_entities", {}).get("symbols", []) + except Exception as e: + logger.error(f"Symbol recognition failed for {os.path.basename(image_path)}: {e}") + return [] + + +def _normalize_class(symbol_type: str) -> int: + """Maps detected symbol type string to YOLO class ID.""" + sym_upper = symbol_type.upper().strip() + # Direct match + if sym_upper in CLASS_TO_ID: + return CLASS_TO_ID[sym_upper] + # Partial match + for cls, idx in CLASS_TO_ID.items(): + if cls in sym_upper or sym_upper in cls: + return idx + # Fallback: INST_BUBBLE for unknown circular symbols + logger.debug(f"Unknown symbol type '{symbol_type}' — mapping to INST_BUBBLE (0).") + return 0 + + +def _convert_to_yolo(symbols: List[Dict[str, Any]], img_w: int = 1000, img_h: int = 800) -> List[str]: + """ + Converts normalized [ymin, xmin, ymax, xmax] bboxes to YOLO format: + (all normalized 0-1) + """ + lines = [] + for sym in symbols: + ymin = float(sym.get("ymin", 0)) + xmin = float(sym.get("xmin", 0)) + ymax = float(sym.get("ymax", 1)) + xmax = float(sym.get("xmax", 1)) + + # Skip degenerate boxes + if xmax <= xmin or ymax <= ymin: + continue + if xmin < 0 or ymin < 0 or xmax > 1 or ymax > 1: + # Clamp to [0, 1] + xmin, ymin = max(0.0, xmin), max(0.0, ymin) + xmax, ymax = min(1.0, xmax), min(1.0, ymax) + + x_center = (xmin + xmax) / 2 + y_center = (ymin + ymax) / 2 + width = xmax - xmin + height = ymax - ymin + + class_id = _normalize_class(sym.get("symbol_type", "INST_BUBBLE")) + lines.append(f"{class_id} {x_center:.6f} {y_center:.6f} {width:.6f} {height:.6f}") + return lines + + +def generate_annotations( + dataset_dir: str, + limit: Optional[int] = None, + provider: Optional[str] = None, + model_name: Optional[str] = None, +) -> Tuple[str, str]: + + """ + Main entry: generates YOLO .txt annotations and COCO JSON for all patches. + + Returns: + Tuple of (annotations_dir, coco_json_path) + """ + dataset_path = Path(dataset_dir) + patches_dir = dataset_path / "patches" + manifest_path = dataset_path / "manifest.csv" + + if not manifest_path.exists(): + raise FileNotFoundError(f"manifest.csv not found at: {manifest_path}") + + # Output directories + output_dir = Path(__file__).parent / "outputs" + ann_dir = output_dir / "annotations" + images_train = ann_dir / "images" / "train" + labels_train = ann_dir / "labels" / "train" + images_val = ann_dir / "images" / "val" + labels_val = ann_dir / "labels" / "val" + + for d in [images_train, labels_train, images_val, labels_val]: + d.mkdir(parents=True, exist_ok=True) + + # Read only patch entries from manifest + patch_entries = [] + with open(manifest_path, "r", encoding="utf-8") as f: + reader = csv.DictReader(f) + for row in reader: + if row["type"] == "patch": + patch_entries.append(row) + + if limit: + patch_entries = patch_entries[:limit] + + logger.info(f"=== Annotation Generator ===") + logger.info(f"Patches to annotate: {len(patch_entries)}") + + # 80/20 train/val split + split_idx = int(len(patch_entries) * 0.8) + train_entries = patch_entries[:split_idx] + val_entries = patch_entries[split_idx:] + + coco_annotations = { + "info": {"description": "SID-AI P&ID Symbol Detection Dataset", "version": "1.0"}, + "categories": [{"id": i, "name": cls} for i, cls in enumerate(SYMBOL_CLASSES)], + "images": [], + "annotations": [] + } + ann_id = 0 + stats = {"processed": 0, "skipped_empty": 0, "failed": 0, "total_symbols": 0} + + def _process_entry(entry: Dict, split: str, img_id: int): + nonlocal ann_id + filename = entry["filename"] + img_path = str(patches_dir / filename) + stem = Path(filename).stem + + if not os.path.exists(img_path): + logger.warning(f"Patch image not found: {img_path} — skipping.") + stats["failed"] += 1 + return + + logger.info(f" Annotating [{split}]: {filename} ...") + stats["processed"] += 1 + + # Run symbol recognition + symbols = _run_symbol_recognition(img_path, provider=provider, model_name=model_name) + if not symbols: + logger.warning(f" No symbols detected in {filename} — writing empty label file.") + stats["skipped_empty"] += 1 + + # Determine output dirs + img_out_dir = images_train if split == "train" else images_val + lbl_out_dir = labels_train if split == "train" else labels_val + + # Copy image + shutil.copy2(img_path, img_out_dir / filename) + + # Write YOLO .txt + yolo_lines = _convert_to_yolo(symbols) + lbl_path = lbl_out_dir / (stem + ".txt") + with open(lbl_path, "w") as f: + f.write("\n".join(yolo_lines)) + + # Add COCO image entry + coco_annotations["images"].append({ + "id": img_id, "file_name": filename, + "width": int(entry.get("width", 1000)), + "height": int(entry.get("height", 800)) + }) + + # Add COCO annotations + for sym in symbols: + class_id = _normalize_class(sym.get("symbol_type", "INST_BUBBLE")) + ymin, xmin = float(sym.get("ymin", 0)), float(sym.get("xmin", 0)) + ymax, xmax = float(sym.get("ymax", 1)), float(sym.get("xmax", 1)) + # COCO bbox: [x, y, width, height] in absolute pixels + w_img = int(entry.get("width", 1000)) + h_img = int(entry.get("height", 800)) + x_abs = xmin * w_img + y_abs = ymin * h_img + w_abs = (xmax - xmin) * w_img + h_abs = (ymax - ymin) * h_img + coco_annotations["annotations"].append({ + "id": ann_id, "image_id": img_id, + "category_id": class_id, + "bbox": [round(x_abs, 2), round(y_abs, 2), round(w_abs, 2), round(h_abs, 2)], + "area": round(w_abs * h_abs, 2), + "iscrowd": 0 + }) + ann_id += 1 + stats["total_symbols"] += 1 + + for img_id, entry in enumerate(train_entries): + _process_entry(entry, "train", img_id) + for img_id, entry in enumerate(val_entries, start=len(train_entries)): + _process_entry(entry, "val", img_id) + + # Write COCO JSON + coco_path = ann_dir / "coco_annotations.json" + with open(coco_path, "w", encoding="utf-8") as f: + json.dump(coco_annotations, f, indent=2, ensure_ascii=False) + + # Write YOLOv8 data.yaml + yaml_path = ann_dir / "data.yaml" + with open(yaml_path, "w") as f: + f.write(f"path: {ann_dir.resolve()}\n") + f.write(f"train: images/train\n") + f.write(f"val: images/val\n") + f.write(f"nc: {len(SYMBOL_CLASSES)}\n") + f.write(f"names: {SYMBOL_CLASSES}\n") + + # Summary + logger.info("\n" + "="*55) + logger.info("Annotation Generator — Summary") + logger.info("="*55) + logger.info(f" Train patches : {len(train_entries)}") + logger.info(f" Val patches : {len(val_entries)}") + logger.info(f" Total symbols : {stats['total_symbols']}") + logger.info(f" Empty patches : {stats['skipped_empty']}") + logger.info(f" Failed : {stats['failed']}") + logger.info(f" COCO JSON : {coco_path}") + logger.info(f" YOLO data.yaml : {yaml_path}") + + return str(ann_dir), str(coco_path) diff --git a/training/corpus_builder.py b/training/corpus_builder.py new file mode 100644 index 0000000..2e2ac3e --- /dev/null +++ b/training/corpus_builder.py @@ -0,0 +1,239 @@ +""" +Strategy C: Full Pipeline Corpus Builder. + +Runs the complete SID-AI LangGraph pipeline on every full-page image in the +P&ID augmented dataset and serializes the structured outputs (engineering_graph, +validation_reports, deliverables) to JSON files. The resulting corpus can be +used for model evaluation, training data analysis, or downstream fine-tuning. + +Usage: + python training/train.py corpus --dataset C:/path/to/pid_aug_dataset/claude + python training/train.py corpus --dataset C:/path/to/pid_aug_dataset/claude --limit 3 +""" + +import os +import sys +import json +import csv +import logging +import traceback +from pathlib import Path +from typing import List, Dict, Any, Optional +from datetime import datetime + +logger = logging.getLogger(__name__) + + +def _serialize_state(final_state: Dict[str, Any]) -> Dict[str, Any]: + """ + Converts the final GraphState to a JSON-serializable dict. + Handles Pydantic models (UniversalEngineeringGraph) via .model_dump(). + """ + result = {} + for key, value in final_state.items(): + try: + if hasattr(value, "model_dump"): + result[key] = value.model_dump() + elif isinstance(value, (str, int, float, bool, type(None))): + result[key] = value + elif isinstance(value, (list, dict)): + result[key] = value + else: + result[key] = str(value) + except Exception: + result[key] = f"" + return result + + +def _extract_quality_metrics(final_state: Dict[str, Any]) -> Dict[str, Any]: + """Extracts extraction quality metrics from a final pipeline state.""" + graph = final_state.get("engineering_graph") + graph_dump = graph.model_dump() if hasattr(graph, "model_dump") else (graph or {}) + + return { + "equipment_count" : len(graph_dump.get("equipment", [])), + "lines_count" : len(graph_dump.get("lines", [])), + "instruments_count" : len(graph_dump.get("instruments", [])), + "valves_count" : len(graph_dump.get("valves", [])), + "relationships_count": len(graph_dump.get("relationships", [])), + "validation_issues" : len(final_state.get("validation_reports", [])), + "missing_entities" : len(final_state.get("missing_entities", [])), + "re_extraction_loops": final_state.get("re_extraction_count", 0), + "revision_events" : len(final_state.get("revision_history", [])), + } + + +def build_corpus( + dataset_dir: str, + limit: Optional[int] = None, + ocr_engine: str = "paddle", + reasoning_engine: str = "gemini", +) -> str: + """ + Main entry: runs the full pipeline on every full-page image in the dataset. + Saves per-image JSON outputs and a corpus_summary.json. + + Args: + dataset_dir: Path to dataset root (containing manifest.csv + full_page/) + limit: Max images to process (for testing) + ocr_engine: Layer 1 OCR engine ('paddle', 'gemini_ocr', 'llamaparse') + reasoning_engine: Layer 2 reasoning engine ('gemini', 'rule_based') + + Returns: + Path to corpus output directory. + """ + dataset_path = Path(dataset_dir) + manifest_path = dataset_path / "manifest.csv" + + if not manifest_path.exists(): + raise FileNotFoundError(f"manifest.csv not found at: {manifest_path}") + + # Output directories + output_dir = Path(__file__).parent / "outputs" / "corpus" + output_dir.mkdir(parents=True, exist_ok=True) + + # Import SID-AI workflow + sys.path.insert(0, str(Path(__file__).parent.parent)) + from src.graph import create_workflow + from src.state import GraphState + from src.config import ( + TEXT_AGENT_MAX_TOKENS, SYMBOL_AGENT_MAX_TOKENS, + PIPELINE_AGENT_MAX_TOKENS, COMPILER_MAX_TOKENS, + ) + + workflow = create_workflow() + app = workflow.compile() + + # Read full_page entries from manifest + full_page_entries = [] + with open(manifest_path, "r", encoding="utf-8") as f: + reader = csv.DictReader(f) + for row in reader: + if row["type"] == "full_page": + full_page_entries.append(row) + + if limit: + full_page_entries = full_page_entries[:limit] + + logger.info(f"=== Pipeline Corpus Builder ===") + logger.info(f"Dataset : {dataset_path}") + logger.info(f"Images : {len(full_page_entries)} full-page drawings") + logger.info(f"OCR Engine : {ocr_engine}") + logger.info(f"Reasoning : {reasoning_engine}") + logger.info(f"Output dir : {output_dir}") + + corpus_summary = { + "generated_at" : datetime.now().isoformat(), + "dataset_dir" : str(dataset_path), + "ocr_engine" : ocr_engine, + "reasoning_engine": reasoning_engine, + "total_images" : len(full_page_entries), + "results" : [] + } + stats = {"success": 0, "failed": 0, "skipped": 0} + + for i, entry in enumerate(full_page_entries): + filename = entry["filename"] + img_path = str(dataset_path / "full_page" / filename) + + if not os.path.exists(img_path): + logger.warning(f"[{i+1}/{len(full_page_entries)}] Image not found: {img_path} — skipping.") + stats["skipped"] += 1 + corpus_summary["results"].append({ + "filename": filename, "status": "skipped", "reason": "file_not_found" + }) + continue + + logger.info(f"\n[{i+1}/{len(full_page_entries)}] Running pipeline on: {filename}") + + # Build initial state + initial_state: GraphState = { + "raw_documents" : [img_path], + "metadata" : {}, + "engineering_context": {}, + "extracted_entities" : { + "text_elements": [], "symbols": [], "relations": [], "geometry": {} + }, + "engineering_graph" : None, + "validation_reports" : [], + "missing_entities" : [], + "revision_history" : [], + "deliverables" : {}, + "re_extraction_count": 0, + "max_re_extractions" : 2, + "re_extracted_targets": [], + "ocr_engine" : ocr_engine, + "reasoning_engine" : reasoning_engine, + "use_mocks" : False, + "local_mode" : ocr_engine == "paddle", + } + + try: + final_state = app.invoke(initial_state) + quality = _extract_quality_metrics(final_state) + serialized = _serialize_state(final_state) + + # Write per-image JSON + stem = Path(filename).stem + out_path = output_dir / f"{stem}_output.json" + with open(out_path, "w", encoding="utf-8") as f: + json.dump({ + "source_image" : img_path, + "quality_metrics": quality, + "pipeline_output": serialized, + }, f, indent=2, ensure_ascii=False) + + logger.info(f" ✓ Success — Equipment:{quality['equipment_count']} " + f"Lines:{quality['lines_count']} " + f"Instruments:{quality['instruments_count']} " + f"Valves:{quality['valves_count']}") + stats["success"] += 1 + + corpus_summary["results"].append({ + "filename" : filename, + "status" : "success", + "output_file": str(out_path), + **quality, + }) + + except Exception as e: + logger.error(f" ✗ Pipeline failed for {filename}: {e}") + logger.debug(traceback.format_exc()) + stats["failed"] += 1 + corpus_summary["results"].append({ + "filename": filename, "status": "failed", "error": str(e) + }) + + # Compute aggregate metrics + successful = [r for r in corpus_summary["results"] if r["status"] == "success"] + if successful: + corpus_summary["aggregate"] = { + "avg_equipment" : sum(r["equipment_count"] for r in successful) / len(successful), + "avg_lines" : sum(r["lines_count"] for r in successful) / len(successful), + "avg_instruments" : sum(r["instruments_count"] for r in successful) / len(successful), + "avg_valves" : sum(r["valves_count"] for r in successful) / len(successful), + "avg_relationships": sum(r["relationships_count"] for r in successful) / len(successful), + "avg_val_issues" : sum(r["validation_issues"] for r in successful) / len(successful), + "success_rate" : stats["success"] / len(full_page_entries), + } + + # Write corpus summary + summary_path = output_dir / "corpus_summary.json" + with open(summary_path, "w", encoding="utf-8") as f: + json.dump(corpus_summary, f, indent=2, ensure_ascii=False) + + logger.info("\n" + "="*55) + logger.info("Pipeline Corpus Builder — Summary") + logger.info("="*55) + logger.info(f" Successful : {stats['success']}") + logger.info(f" Failed : {stats['failed']}") + logger.info(f" Skipped : {stats['skipped']}") + if successful: + agg = corpus_summary["aggregate"] + logger.info(f" Avg Equipment : {agg['avg_equipment']:.1f}") + logger.info(f" Avg Lines : {agg['avg_lines']:.1f}") + logger.info(f" Avg Instruments: {agg['avg_instruments']:.1f}") + logger.info(f" Success rate : {agg['success_rate']*100:.0f}%") + logger.info(f" Summary file : {summary_path}") + + return str(output_dir) diff --git a/training/train.py b/training/train.py new file mode 100644 index 0000000..fb6c4ca --- /dev/null +++ b/training/train.py @@ -0,0 +1,229 @@ +""" +SID-AI Training CLI — Master Entry Point. + +Subcommands: + vlm — Strategy A: Generate Gemini SFT JSONL dataset from all images + annotate — Strategy B Step 1: Generate YOLO + COCO annotations from patches + yolo — Strategy B Step 2: Launch YOLOv8 training on RTX 3050 + corpus — Strategy C: Run full pipeline on all images, build training corpus + +Usage Examples: + # Generate Gemini SFT fine-tuning dataset (all images) + python training/train.py vlm --dataset C:/Users/ADMIN/Downloads/pid_aug_dataset/claude + + # Generate only 5 samples (test run) + python training/train.py vlm --dataset C:/path/to/dataset --limit 5 + + # Generate YOLO bounding box annotations from patches + python training/train.py annotate --dataset C:/path/to/dataset + + # Launch YOLOv8 training on RTX 3050 (run annotate first) + python training/train.py yolo --annotations training/outputs/annotations --epochs 100 + + # Build full pipeline corpus (run full pipeline on all full-page images) + python training/train.py corpus --dataset C:/path/to/dataset --ocr-engine paddle + + # Full run: annotate + yolo in sequence + python training/train.py annotate --dataset C:/path/to/dataset + python training/train.py yolo --annotations training/outputs/annotations +""" + +import argparse +import logging +import sys +import os +from pathlib import Path + +# Ensure project root is on PYTHONPATH +PROJECT_ROOT = Path(__file__).parent.parent +sys.path.insert(0, str(PROJECT_ROOT)) + +# ── Logging Setup ────────────────────────────────────────────────────────────── +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + handlers=[ + logging.StreamHandler(sys.stdout), + ] +) +logger = logging.getLogger("sid_ai.training") + + +def cmd_vlm(args): + """Strategy A: Generate Gemini SFT JSONL dataset.""" + logger.info("Starting Strategy A: VLM Fine-tuning Dataset Builder") + logger.info(f" Dataset : {args.dataset}") + logger.info(f" Limit : {args.limit or 'all'}") + + from training.vlm_dataset_builder import build_vlm_dataset + output_path = build_vlm_dataset( + dataset_dir=args.dataset, + limit=args.limit, + ) + logger.info(f"\n✅ VLM dataset ready: {output_path}") + logger.info(" → Upload to Gemini SFT: https://console.cloud.google.com/vertex-ai/generative/language/tuning") + + +def cmd_annotate(args): + """Strategy B Step 1: Generate YOLO + COCO annotations.""" + logger.info("Starting Strategy B-1: Object Detection Annotation Generator") + logger.info(f" Dataset : {args.dataset}") + logger.info(f" Provider : {args.provider or 'default (gemini)'}") + logger.info(f" Model : {args.model or 'default'}") + logger.info(f" Limit : {args.limit or 'all'}") + + from training.annotation_generator import generate_annotations + ann_dir, coco_path = generate_annotations( + dataset_dir=args.dataset, + limit=args.limit, + provider=args.provider, + model_name=args.model, + ) + logger.info(f"\n✅ Annotations ready at: {ann_dir}") + logger.info(f" COCO JSON: {coco_path}") + logger.info(f" → Now run: python training/train.py yolo --annotations {ann_dir}") + + + +def cmd_yolo(args): + """Strategy B Step 2: Launch YOLOv8 training on RTX 3050.""" + logger.info("Starting Strategy B-2: YOLOv8 Training Launcher (RTX 3050)") + logger.info(f" Annotations : {args.annotations}") + logger.info(f" Epochs : {args.epochs}") + logger.info(f" Batch size : {args.batch}") + logger.info(f" Model : {args.model}") + + from training.yolo_train_launcher import launch_yolo_training + best_weights = launch_yolo_training( + annotations_dir=args.annotations, + epochs=args.epochs, + batch=args.batch, + model=args.model, + ) + logger.info(f"\n✅ Training complete. Best weights: {best_weights}") + logger.info(f" → To use in SID-AI: set YOLO_WEIGHTS_PATH={best_weights}") + + +def cmd_corpus(args): + """Strategy C: Run full pipeline on all images, build corpus.""" + logger.info("Starting Strategy C: Full Pipeline Corpus Builder") + logger.info(f" Dataset : {args.dataset}") + logger.info(f" Limit : {args.limit or 'all'}") + logger.info(f" OCR engine : {args.ocr_engine}") + logger.info(f" Reasoning : {args.reasoning_engine}") + + from training.corpus_builder import build_corpus + corpus_dir = build_corpus( + dataset_dir=args.dataset, + limit=args.limit, + ocr_engine=args.ocr_engine, + reasoning_engine=args.reasoning_engine, + ) + logger.info(f"\n✅ Corpus built at: {corpus_dir}") + logger.info(f" → See corpus_summary.json for aggregate metrics") + + +def main(): + parser = argparse.ArgumentParser( + description="SID-AI Training CLI — P&ID Model Training & Dataset Generation", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__ + ) + + subparsers = parser.add_subparsers(dest="command", required=True) + + # ── vlm subcommand ────────────────────────────────────────────────────────── + p_vlm = subparsers.add_parser( + "vlm", + help="Strategy A: Generate Gemini SFT JSONL dataset from all images" + ) + p_vlm.add_argument( + "--dataset", required=True, + help="Path to dataset root dir (must contain manifest.csv)" + ) + p_vlm.add_argument( + "--limit", type=int, default=None, + help="Max images to process (omit for all)" + ) + p_vlm.set_defaults(func=cmd_vlm) + + # ── annotate subcommand ───────────────────────────────────────────────────── + p_ann = subparsers.add_parser( + "annotate", + help="Strategy B Step 1: Generate YOLO + COCO annotations from patch images" + ) + p_ann.add_argument( + "--dataset", required=True, + help="Path to dataset root dir (must contain manifest.csv + patches/)" + ) + p_ann.add_argument( + "--provider", default=None, + choices=["gemini", "qwen", "openrouter", "openai"], + help="LLM provider for symbol extraction (default: gemini; use openrouter/qwen or openai to avoid Gemini free-tier daily quota)" + ) + p_ann.add_argument( + "--model", default=None, + help="Specific model name (e.g. qwen/qwen2.5-vl-72b-instruct or gpt-4o)" + ) + p_ann.add_argument( + "--limit", type=int, default=None, + help="Max patches to annotate (omit for all)" + ) + + p_ann.set_defaults(func=cmd_annotate) + + # ── yolo subcommand ───────────────────────────────────────────────────────── + p_yolo = subparsers.add_parser( + "yolo", + help="Strategy B Step 2: Launch YOLOv8 training on RTX 3050 GPU" + ) + p_yolo.add_argument( + "--annotations", required=True, + help="Path to annotations dir (output of 'annotate' subcommand)" + ) + p_yolo.add_argument( + "--epochs", type=int, default=50, + help="Number of training epochs (default: 50)" + ) + p_yolo.add_argument( + "--batch", type=int, default=8, + help="Batch size for RTX 3050 4GB VRAM (default: 8)" + ) + p_yolo.add_argument( + "--model", default="yolov8m.pt", + choices=["yolov8n.pt", "yolov8s.pt", "yolov8m.pt", "yolov8l.pt"], + help="YOLOv8 model variant (default: yolov8m — best for 4GB VRAM)" + ) + p_yolo.set_defaults(func=cmd_yolo) + + # ── corpus subcommand ─────────────────────────────────────────────────────── + p_corpus = subparsers.add_parser( + "corpus", + help="Strategy C: Run full SID-AI pipeline on all images to build training corpus" + ) + p_corpus.add_argument( + "--dataset", required=True, + help="Path to dataset root dir (must contain manifest.csv + full_page/)" + ) + p_corpus.add_argument( + "--limit", type=int, default=None, + help="Max full-page images to process (omit for all)" + ) + p_corpus.add_argument( + "--ocr-engine", default="paddle", + choices=["paddle", "gemini_ocr", "llamaparse", "pathnovo", "pdf_text"], + help="Layer 1 OCR engine (default: paddle — local, no API cost)" + ) + p_corpus.add_argument( + "--reasoning-engine", default="gemini", + choices=["gemini", "rule_based", "qwen", "qwen_37", "openai"], + help="Layer 2 reasoning engine (default: gemini)" + ) + p_corpus.set_defaults(func=cmd_corpus) + + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/training/vlm_dataset_builder.py b/training/vlm_dataset_builder.py new file mode 100644 index 0000000..fb33dae --- /dev/null +++ b/training/vlm_dataset_builder.py @@ -0,0 +1,269 @@ +""" +Strategy A: VLM Fine-tuning Dataset Builder (Gemini Supervised Fine-tuning Format). + +Generates a JSONL dataset of (system, user_with_image, model_answer) triplets +from every image in the P&ID augmented dataset. Output is ready for upload to +the Gemini Supervised Fine-tuning API. + +Usage: + python training/train.py vlm --dataset C:/path/to/pid_aug_dataset/claude + python training/train.py vlm --dataset C:/path/to/pid_aug_dataset/claude --limit 5 +""" + +import os +import sys +import json +import base64 +import logging +import csv +from pathlib import Path +from typing import List, Dict, Any, Optional + +logger = logging.getLogger(__name__) + +# ── Gemini SFT JSONL format ──────────────────────────────────────────────────── +# +# Each line in the output JSONL follows Gemini's supervised fine-tuning format: +# { +# "messages": [ +# {"role": "system", "content": ""}, +# {"role": "user", "content": [ +# {"type": "text", "text": ""}, +# {"type": "image_url", "image_url": {"url": "data:image/png;base64,"}} +# ]}, +# {"role": "model", "content": ""} +# ] +# } + +SYSTEM_PROMPT_FULL = ( + "You are SID-AI, an expert engineering drawing analysis system specialized in " + "P&ID (Piping and Instrumentation Diagram) interpretation per ISA-5.1 standards. " + "Given a full-page P&ID drawing image, extract ALL engineering entities: " + "equipment tags, line tags, instrument tags, valve tags, PSV tags, notes, and ratings. " + "Return a structured JSON object with an 'items' array. Each item must have: " + "tag, classification, value, and optional attributes dict." +) + +SYSTEM_PROMPT_PATCH = ( + "You are SID-AI, an expert engineering drawing analysis system specialized in " + "P&ID (Piping and Instrumentation Diagram) interpretation per ISA-5.1 standards. " + "Given a cropped patch from a P&ID drawing, extract ALL visible engineering entities " + "including instrument bubbles, valve symbols, piping line tags, and equipment labels. " + "Return a structured JSON object with an 'items' array. Each item must have: " + "tag, classification, value, and optional attributes dict." +) + +USER_PROMPT_FULL = ( + "Analyze this full P&ID drawing and extract every engineering entity you can identify. " + "Include: EQUIPMENT_TAG, LINE_TAG, INSTRUMENT_TAG, VALVE_TAG, PSV_TAG, NOTE, RATING. " + "For each entity, provide its exact tag string, classification, and any specifications " + "(design_pressure, design_temperature, flow_rate, material, vendor) in the attributes field." +) + +USER_PROMPT_PATCH = ( + "Analyze this cropped patch from a P&ID drawing and extract all visible engineering entities. " + "Focus on instrument bubbles (PI, TI, FI, PDIT, PDI), valve symbols, line tags, and equipment labels. " + "Return a JSON object with an 'items' array containing each detected entity." +) + + +def _encode_image_base64(image_path: str, max_dim: int = 1024) -> str: + """Encode image as base64, downscaling large images to reduce JSONL size.""" + try: + from PIL import Image + import io + with Image.open(image_path) as img: + w, h = img.size + if max(w, h) > max_dim: + ratio = max_dim / float(max(w, h)) + new_size = (max(1, int(w * ratio)), max(1, int(h * ratio))) + img = img.resize(new_size, Image.Resampling.LANCZOS) + buf = io.BytesIO() + img.save(buf, format="PNG", optimize=True) + return base64.b64encode(buf.getvalue()).decode("utf-8") + except Exception: + with open(image_path, "rb") as f: + return base64.b64encode(f.read()).decode("utf-8") + + +def _run_pipeline_on_image(image_path: str, image_type: str) -> Optional[Dict[str, Any]]: + """ + Runs the SID-AI text extraction pipeline on a single image to generate + the ground-truth answer for the training sample. + Returns extracted entities dict or None on failure. + """ + try: + # Import pipeline components + sys.path.insert(0, str(Path(__file__).parent.parent)) + from src.agents.parallel_vision import TextRecognitionAgent + from src.state import GraphState + + agent = TextRecognitionAgent() + state: GraphState = { + "raw_documents": [image_path], + "metadata": {"drawing_type": "PID", "rasterized_pages": [image_path]}, + "engineering_context": {}, + "extracted_entities": {"text_elements": [], "symbols": [], "relations": [], "geometry": {}}, + "engineering_graph": None, + "validation_reports": [], + "missing_entities": [], + "revision_history": [], + "deliverables": {}, + "re_extraction_count": 0, + "max_re_extractions": 1, + "re_extracted_targets": [], + "ocr_engine": "paddle", + "reasoning_engine": "gemini", + "use_mocks": False, + "local_mode": False, + } + result = agent.run(state) + text_elements = result.get("extracted_entities", {}).get("text_elements", []) + if len(text_elements) < 3: + logger.warning(f"Low yield ({len(text_elements)} entities) for {os.path.basename(image_path)} — skipping.") + return None + return {"items": text_elements} + except Exception as e: + logger.error(f"Pipeline extraction failed for {os.path.basename(image_path)}: {e}") + return None + + +def _build_gemini_sft_record( + image_path: str, + image_type: str, + extracted_answer: Dict[str, Any], + patch_coords: Optional[str] = None, +) -> Dict[str, Any]: + """ + Builds a single Gemini SFT JSONL record. + Full-page images are downscaled to 1024px max; patches keep 1000×800. + """ + max_dim = 1024 if image_type == "full_page" else 1000 + b64_image = _encode_image_base64(image_path, max_dim=max_dim) + + system_prompt = SYSTEM_PROMPT_FULL if image_type == "full_page" else SYSTEM_PROMPT_PATCH + user_prompt = USER_PROMPT_FULL if image_type == "full_page" else USER_PROMPT_PATCH + + if patch_coords: + user_prompt += f"\n\nNote: This patch originates from coordinates {patch_coords} in the full drawing." + + return { + "messages": [ + { + "role": "system", + "content": system_prompt + }, + { + "role": "user", + "content": [ + {"type": "text", "text": user_prompt}, + { + "type": "image_url", + "image_url": {"url": f"data:image/png;base64,{b64_image}"} + } + ] + }, + { + "role": "model", + "content": json.dumps(extracted_answer, ensure_ascii=False) + } + ] + } + + +def build_vlm_dataset(dataset_dir: str, limit: Optional[int] = None) -> str: + """ + Main entry point: reads manifest.csv, runs pipeline on each image, + and writes Gemini SFT JSONL to training/outputs/vlm_finetune_gemini.jsonl. + + Args: + dataset_dir: Path to the dataset root (containing manifest.csv) + limit: Optional max number of images to process (for testing) + + Returns: + Path to generated JSONL file. + """ + dataset_path = Path(dataset_dir) + manifest_path = dataset_path / "manifest.csv" + + if not manifest_path.exists(): + raise FileNotFoundError(f"manifest.csv not found at: {manifest_path}") + + # Output directory + output_dir = Path(__file__).parent / "outputs" + output_dir.mkdir(parents=True, exist_ok=True) + output_path = output_dir / "vlm_finetune_gemini.jsonl" + + logger.info(f"=== VLM Fine-tuning Dataset Builder (Gemini SFT Format) ===") + logger.info(f"Dataset: {dataset_path}") + logger.info(f"Output: {output_path}") + + # Read manifest + entries = [] + with open(manifest_path, "r", encoding="utf-8") as f: + reader = csv.DictReader(f) + for row in reader: + entries.append(row) + + if limit: + entries = entries[:limit] + logger.info(f"Limit mode: processing {limit}/{len(entries)} images.") + + stats = {"processed": 0, "skipped_low_yield": 0, "failed": 0, "written": 0} + + with open(output_path, "w", encoding="utf-8") as out_f: + for i, entry in enumerate(entries): + img_type = entry["type"] # "full_page" or "patch" + filename = entry["filename"] + + # Resolve absolute path + if img_type == "full_page": + img_path = str(dataset_path / "full_page" / filename) + else: + img_path = str(dataset_path / "patches" / filename) + + if not os.path.exists(img_path): + logger.warning(f"[{i+1}/{len(entries)}] Image not found: {img_path} — skipping.") + stats["failed"] += 1 + continue + + logger.info(f"[{i+1}/{len(entries)}] Processing {img_type}: {filename} ...") + stats["processed"] += 1 + + # Extract patch coordinates from filename (patch_NNN_xX_yY.png) + patch_coords = None + if img_type == "patch": + parts = filename.replace(".png", "").split("_") + coords_parts = [p for p in parts if p.startswith("x") or p.startswith("y")] + if len(coords_parts) >= 2: + patch_coords = f"({coords_parts[0][1:]}, {coords_parts[1][1:]})" + + # Run pipeline to generate ground-truth answer + answer = _run_pipeline_on_image(img_path, img_type) + if answer is None: + stats["skipped_low_yield"] += 1 + continue + + # Build and write Gemini SFT record + try: + record = _build_gemini_sft_record(img_path, img_type, answer, patch_coords) + out_f.write(json.dumps(record, ensure_ascii=False) + "\n") + stats["written"] += 1 + logger.info(f" ✓ Written record with {len(answer.get('items', []))} entities.") + except Exception as e: + logger.error(f" ✗ Failed to build record for {filename}: {e}") + stats["failed"] += 1 + + # Summary + logger.info("\n" + "="*55) + logger.info("VLM Dataset Builder — Summary") + logger.info("="*55) + logger.info(f" Total processed : {stats['processed']}") + logger.info(f" Written records : {stats['written']}") + logger.info(f" Skipped (low yield): {stats['skipped_low_yield']}") + logger.info(f" Failed : {stats['failed']}") + logger.info(f" Output file : {output_path}") + logger.info(f"\n → Upload to Gemini SFT API at:") + logger.info(f" https://console.cloud.google.com/vertex-ai/generative/language/tuning") + + return str(output_path) diff --git a/training/yolo_train_launcher.py b/training/yolo_train_launcher.py new file mode 100644 index 0000000..4e25fa1 --- /dev/null +++ b/training/yolo_train_launcher.py @@ -0,0 +1,223 @@ +""" +Strategy B — Part 2: YOLOv8 Training Launcher. + +Launches YOLOv8 object detection training on the annotated P&ID symbol dataset. +Configured for NVIDIA RTX 3050 (4GB VRAM) with CUDA acceleration. + +Usage: + python training/train.py yolo --annotations training/outputs/annotations + python training/train.py yolo --annotations training/outputs/annotations --epochs 100 +""" + +import os +import sys +import logging +import subprocess +from pathlib import Path +from typing import Optional + +logger = logging.getLogger(__name__) + +# ── RTX 3050 Optimal Hyperparameters ────────────────────────────────────────── +# +# RTX 3050 has 4GB VRAM. These settings are tuned to maximize utilisation +# while avoiding OOM errors on a 4GB VRAM budget: +# - batch=8 : safe for 1000x800 patches on 4GB VRAM +# - imgsz=800 : matches patch height (wider dimension) +# - workers=4 : good for 8-core consumer CPUs +# - amp=True : Automatic Mixed Precision (FP16) saves ~50% VRAM +# - cache=True : caches images to RAM for faster I/O + +RTX3050_CONFIG = { + "model" : "yolov8m.pt", # YOLOv8-Medium: best accuracy/speed on 4GB VRAM + "epochs" : 50, + "batch" : 8, + "imgsz" : 800, + "device" : "0", # CUDA device 0 (RTX 3050) + "workers" : 4, + "amp" : True, # Automatic Mixed Precision (FP16) + "cache" : True, # Cache images in RAM + "patience" : 0, # Set 0 to disable EarlyStopping and train ALL requested epochs + "lr0" : 0.01, # Initial learning rate + "lrf" : 0.01, # Final LR fraction + "momentum" : 0.937, + "weight_decay": 0.0005, + "warmup_epochs": 3, + "box" : 7.5, # Box loss gain (higher → better bbox regression) + "cls" : 0.5, # Classification loss gain + "dfl" : 1.5, # Distribution focal loss gain + "augment" : True, # Enable YOLOv8 built-in augmentation + "degrees" : 5.0, # Rotation augmentation ±5° (matches dataset's ±2° + more) + "translate" : 0.1, + "scale" : 0.2, + "shear" : 2.0, + "perspective": 0.001, + "flipud" : 0.0, # No vertical flip (P&ID symbols are orientation-sensitive) + "fliplr" : 0.3, + "mosaic" : 0.8, + "mixup" : 0.1, +} + + + +def _check_cuda_available() -> bool: + """Check if CUDA/torch is available for GPU training.""" + try: + import torch + if torch.cuda.is_available(): + device_name = torch.cuda.get_device_name(0) + vram_gb = torch.cuda.get_device_properties(0).total_memory / 1e9 + logger.info(f"GPU detected: {device_name} ({vram_gb:.1f} GB VRAM)") + return True + else: + logger.warning("CUDA not available. Training will run on CPU (very slow).") + return False + except ImportError: + logger.warning("PyTorch not installed. Training will use CPU.") + return False + + +def _check_ultralytics() -> bool: + """Verify ultralytics is installed.""" + try: + import ultralytics + logger.info(f"Ultralytics YOLOv8 version: {ultralytics.__version__}") + return True + except ImportError: + logger.error("ultralytics not installed. Run: pip install ultralytics") + return False + + +def launch_yolo_training( + annotations_dir: str, + epochs: int = 50, + batch: int = 8, + model: str = "yolov8m.pt", + project_name: str = "pid_symbol_detector", +) -> str: + """ + Launches YOLOv8 training on the annotated P&ID symbol dataset. + + Args: + annotations_dir: Path to annotations directory (must contain data.yaml) + epochs: Number of training epochs + batch: Batch size (8 recommended for RTX 3050 4GB) + model: YOLOv8 model variant (yolov8n/s/m/l/x) + project_name: Training run project name + + Returns: + Path to trained weights (best.pt) + """ + if not _check_ultralytics(): + raise RuntimeError("ultralytics not installed. Run: pip install ultralytics") + + ann_path = Path(annotations_dir) + yaml_path = ann_path / "data.yaml" + + if not yaml_path.exists(): + raise FileNotFoundError( + f"data.yaml not found at {yaml_path}. " + "Run annotation generation first: python training/train.py annotate ..." + ) + + # Check dataset has images + train_imgs = list((ann_path / "images" / "train").glob("*.png")) + val_imgs = list((ann_path / "images" / "val").glob("*.png")) + logger.info(f"Dataset: {len(train_imgs)} train / {len(val_imgs)} val images") + + if not train_imgs: + raise ValueError("No training images found. Run annotation generation first.") + + # Output directory + output_dir = Path(__file__).parent / "outputs" / "yolo_runs" + output_dir.mkdir(parents=True, exist_ok=True) + + # Check if last.pt exists for resuming training from epoch 21 + last_ckpt = output_dir / project_name / "weights" / "last.pt" + + resume_flag = False + if last_ckpt.exists(): + logger.info(f"Checkpoint found at '{last_ckpt}' — resuming training from last epoch...") + model_to_load = str(last_ckpt) + resume_flag = True + else: + model_to_load = model + + # Check GPU availability + cuda_ok = _check_cuda_available() + device = RTX3050_CONFIG["device"] if cuda_ok else "cpu" + + logger.info("=== YOLOv8 Training Launcher (RTX 3050 Optimized) ===") + + + logger.info(f"Model : {model_to_load}") + logger.info(f"Epochs : {epochs}") + logger.info(f"Batch : {batch}") + logger.info(f"Device : {device} ({'CUDA/GPU' if cuda_ok else 'CPU — slow!'})") + logger.info(f"AMP (FP16): {RTX3050_CONFIG['amp']}") + logger.info(f"Img size : {RTX3050_CONFIG['imgsz']}") + logger.info(f"Patience : {RTX3050_CONFIG['patience']} (0 = disabled, train all {epochs} epochs)") + logger.info(f"Project : {output_dir / project_name}") + + # Launch YOLO training via Python API + try: + from ultralytics import YOLO + + yolo_model = YOLO(model_to_load) + + train_results = yolo_model.train( + data = str(yaml_path), + epochs = epochs, + batch = batch, + imgsz = RTX3050_CONFIG["imgsz"], + device = device, + workers = RTX3050_CONFIG["workers"], + amp = RTX3050_CONFIG["amp"], + cache = RTX3050_CONFIG["cache"], + patience = RTX3050_CONFIG["patience"], + resume = resume_flag, + + lr0 = RTX3050_CONFIG["lr0"], + lrf = RTX3050_CONFIG["lrf"], + momentum = RTX3050_CONFIG["momentum"], + weight_decay= RTX3050_CONFIG["weight_decay"], + warmup_epochs= RTX3050_CONFIG["warmup_epochs"], + box = RTX3050_CONFIG["box"], + cls = RTX3050_CONFIG["cls"], + dfl = RTX3050_CONFIG["dfl"], + degrees = RTX3050_CONFIG["degrees"], + translate = RTX3050_CONFIG["translate"], + scale = RTX3050_CONFIG["scale"], + shear = RTX3050_CONFIG["shear"], + perspective = RTX3050_CONFIG["perspective"], + flipud = RTX3050_CONFIG["flipud"], + fliplr = RTX3050_CONFIG["fliplr"], + mosaic = RTX3050_CONFIG["mosaic"], + mixup = RTX3050_CONFIG["mixup"], + augment = RTX3050_CONFIG["augment"], + project = str(output_dir), + name = project_name, + exist_ok = True, + verbose = True, + ) + + # Run validation + logger.info("\n=== Running Validation on Best Weights ===") + val_results = yolo_model.val() + + best_weights = output_dir / project_name / "weights" / "best.pt" + logger.info("\n" + "="*55) + logger.info("YOLOv8 Training — Complete") + logger.info("="*55) + logger.info(f" mAP50 : {val_results.box.map50:.4f}") + logger.info(f" mAP50-95 : {val_results.box.map:.4f}") + logger.info(f" Best weights : {best_weights}") + logger.info(f"\n → To use in SID-AI pipeline, set:") + logger.info(f" symbol_engine=local in your run config") + logger.info(f" YOLO_WEIGHTS_PATH={best_weights}") + + return str(best_weights) + + except Exception as e: + logger.error(f"YOLOv8 training failed: {e}") + raise