feat: Add P&ID dataset training pipeline, YOLOv8 symbol agent & LLM parameter tuning

This commit is contained in:
Avhinav Gupta
2026-08-11 22:05:48 +05:30
parent 9d78cceef5
commit 36c7739c7e
15 changed files with 1612 additions and 58 deletions
+1
View File
@@ -0,0 +1 @@
"""Training package for SID-AI P&ID Dataset."""
+297
View File
@@ -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:
<class_id> <x_center> <y_center> <width> <height> (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)
+239
View File
@@ -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"<non-serializable: {type(value).__name__}>"
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)
+229
View File
@@ -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()
+269
View File
@@ -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": "<system_prompt>"},
# {"role": "user", "content": [
# {"type": "text", "text": "<user_prompt>"},
# {"type": "image_url", "image_url": {"url": "data:image/png;base64,<b64>"}}
# ]},
# {"role": "model", "content": "<json_answer_string>"}
# ]
# }
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)
+223
View File
@@ -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