"""PipelineDebugCapture – writes versioned inspection manifests for conversion jobs.""" import json import time import cv2 import numpy as np from config.paths import JOB_DIR from config.runtime import DEBUG_ARTIFACTS_ENABLED from enums import JobStatus from services.debug.helpers import ( _debug_json_default, _debug_preview_rgb, _debug_resize_rgb, ) class PipelineDebugCapture: """Writes a generic, versioned inspection manifest alongside a conversion job.""" def __init__(self, job_id: str): self.job_id = job_id self.root = JOB_DIR / f"{job_id}.debug" self.root.mkdir(parents=True, exist_ok=True) self.manifest_path = self.root / "manifest.json" self.manifest = { "schemaVersion": 2, "jobId": job_id, "status": JobStatus.PROCESSING, "stages": [], } self._write_manifest() def _write_manifest(self): self.manifest["updatedAtMs"] = int(time.time() * 1000) self.manifest_path.write_text( json.dumps(self.manifest, separators=(",", ":"), default=_debug_json_default), encoding="utf-8", ) def record_images( self, stage_id: str, title: str, description: str, images: list[tuple[str, np.ndarray]], metrics: dict | None = None, elapsed_ms: float | None = None, ): if not DEBUG_ARTIFACTS_ENABLED: return try: artifacts = [] for index, (label, image_rgb) in enumerate(images): filename = f"{len(self.manifest['stages']) + 1:02d}-{stage_id}-{index + 1}.jpg" image_rgb = _debug_resize_rgb(image_rgb) ok, encoded = cv2.imencode(".jpg", cv2.cvtColor(image_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 90]) if not ok: continue (self.root / filename).write_bytes(encoded.tobytes()) preview_filename = f"{filename[:-4]}.preview.jpg" preview_rgb = _debug_preview_rgb(image_rgb) preview_ok, preview_encoded = cv2.imencode( ".jpg", cv2.cvtColor(preview_rgb, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 82], ) if preview_ok: (self.root / preview_filename).write_bytes(preview_encoded.tobytes()) artifacts.append({ "type": "image", "label": label, "url": f"/viz2d/jobs/{self.job_id}/debug/assets/{filename}", "previewUrl": ( f"/viz2d/jobs/{self.job_id}/debug/assets/{preview_filename}" if preview_ok else None ), }) stage = { "id": stage_id, "title": title, "description": description, "artifacts": artifacts, "metrics": metrics or {}, } if elapsed_ms is not None: stage["elapsedMs"] = round(float(elapsed_ms), 1) self.manifest["stages"].append(stage) self._write_manifest() except Exception as exc: print(f"[DEBUG] Could not capture {stage_id} for job {self.job_id}: {exc}", flush=True) def complete(self, total_elapsed_ms: float): if not DEBUG_ARTIFACTS_ENABLED: return self.manifest["status"] = JobStatus.COMPLETED self.manifest["totalElapsedMs"] = round(float(total_elapsed_ms), 1) self._write_manifest() def fail(self, error: Exception): if not DEBUG_ARTIFACTS_ENABLED: return self.manifest["status"] = JobStatus.FAILED self.manifest["error"] = str(error) self._write_manifest()