"""Background conversion task: segment an uploaded image into a vizbundle.""" import time import threading from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path from fastapi import HTTPException from config.paths import JOB_DIR from config.runtime import DEBUG_ARTIFACTS_ENABLED, MAX_CONCURRENT_CONVERSIONS from services.jobs.store import read_job, release_live_job, write_job from services.jobs.timing import estimate_conversion_ms, record_conversion_ms from enums import JobStatus, PipelinePhase CONVERSION_STAGE_WEIGHTS = { PipelinePhase.SEGMENTATION: 0.28, PipelinePhase.MASKING: 0.08, PipelinePhase.GEOMETRY: 0.18, PipelinePhase.SURFACE_MAPPING: 0.12, PipelinePhase.LIGHTING: 0.15, PipelinePhase.DIRECTION: 0.08, PipelinePhase.PACKAGING: 0.11, } CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS) CONVERSION_SLOTS = threading.BoundedSemaphore(MAX_CONCURRENT_CONVERSIONS) @contextmanager def conversion_slot(on_wait): """Hold a conversion slot; call on_wait only if the job must actually queue.""" if not CONVERSION_SLOTS.acquire(blocking=False): on_wait() CONVERSION_SLOTS.acquire() try: yield finally: CONVERSION_SLOTS.release() def update_conversion_job( job_id: str, *, phase: str | None = None, progress: int | None = None, phase_progress: int | None = None, message: str | None = None, **values, ): """Persist live conversion state for the browser's progress and ETA display.""" try: job = read_job(job_id) except HTTPException: return if phase is not None: job["phase"] = phase if progress is not None: job["progress"] = max(0, min(100, int(progress))) if phase_progress is not None: job["phaseProgress"] = max(0, min(100, int(phase_progress))) if message is not None: job["message"] = message job.update(values) write_job(job, durable=False) def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int: completed_weight = sum( CONVERSION_STAGE_WEIGHTS.get(item, 0.0) for item in completed_phases if item != phase ) current_weight = CONVERSION_STAGE_WEIGHTS.get(phase, 0.0) * max(0.0, min(1.0, phase_progress / 100.0)) return round((completed_weight + current_weight) * 100) def run_conversion_task(job_id: str, upload_path: Path): # Deferred imports to avoid circular dependencies with pipeline modules from services.debug.capture import PipelineDebugCapture from services.pipeline.packaging import build_manifest_segmentation_bundle task_started = time.perf_counter() debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None estimate_ms = estimate_conversion_ms() t_read = time.perf_counter() image_bytes = upload_path.read_bytes() input_read_ms = (time.perf_counter() - t_read) * 1000 image_url = f"/uploads/{upload_path.name}" def announce_queued(): update_conversion_job( job_id, status=JobStatus.QUEUED, phase="queued", progress=0, phase_progress=0, message="Waiting for an analysis slot\u2026", estimatedTotalMs=estimate_ms, estimatedRemainingMs=estimate_ms, ) try: # Run one authoritative HD pass. The former preview repeated # segmentation and full-resolution CPU work, then was normally missed # before the status returned to PROCESSING. gpu_wait_started = time.perf_counter() with conversion_slot(announce_queued): gpu_queue_wait_ms = (time.perf_counter() - gpu_wait_started) * 1000 t_start = time.perf_counter() update_conversion_job( job_id, status=JobStatus.PROCESSING, phase=PipelinePhase.SEGMENTATION, progress=0, phase_progress=0, message="Analyzing floor (HD)\u2026", estimatedTotalMs=estimate_ms, estimatedRemainingMs=estimate_ms, gpuQueueWaitMs=round(gpu_queue_wait_ms), ) completed_phases: set[str] = set() def report_stage(phase: str, phase_progress: float): if phase_progress >= 100: completed_phases.add(phase) elapsed_ms = (time.perf_counter() - t_start) * 1000 remaining_ms = max(0, estimate_ms - elapsed_ms) hd_progress = weighted_conversion_progress(completed_phases, phase, phase_progress) update_conversion_job( job_id, phase=phase, progress=hd_progress, phase_progress=round(phase_progress), message=f"Enhancing {phase.replace('-', ' ')}\u2026", estimatedRemainingMs=round(remaining_ms), ) from services.pipeline.builder import build_segmentation_bundle bundle = build_segmentation_bundle( image_bytes, debug=debug, progress_callback=report_stage, include_pixels=False, ) report_stage(PipelinePhase.PACKAGING, 25) serialization_started = time.perf_counter() binary_bundle = build_manifest_segmentation_bundle( bundle, job_id, image_url=image_url, include_image=False, ) (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle) serialization_ms = (time.perf_counter() - serialization_started) * 1000 report_stage(PipelinePhase.PACKAGING, 100) elapsed_ms = (time.perf_counter() - t_start) * 1000 record_conversion_ms(elapsed_ms) pipeline_stages = [ stage for stage in (bundle.get("pipelineStages") or []) if stage.get("name") != "TOTAL" ] pipeline_stages.append({ "name": "Bundle Serialization", "elapsed_s": round(serialization_ms / 1000, 3), "detail": f"{len(binary_bundle) / 1024:.0f} KB", }) accounted_s = sum(float(stage.get("elapsed_s") or 0.0) for stage in pipeline_stages) conversion_overhead_s = max(0.0, elapsed_ms / 1000 - accounted_s) if conversion_overhead_s >= 0.001: pipeline_stages.append({ "name": "Conversion Overhead", "elapsed_s": round(conversion_overhead_s, 3), "detail": "job-state updates and orchestration", }) pipeline_stages.append({ "name": "TOTAL", "elapsed_s": round(elapsed_ms / 1000, 3), "detail": "full HD conversion", }) job = read_job(job_id) job["status"] = JobStatus.COMPLETED job["phase"] = "completed" job["progress"] = 100 job["phaseProgress"] = 100 job["message"] = "Surfaces ready" job["estimatedRemainingMs"] = 0 job["completedAt"] = datetime.now(timezone.utc).isoformat() job["durationMs"] = round(elapsed_ms) job["modelName"] = bundle.get("modelName") job["models"] = bundle.get("models") job["pipelineStages"] = pipeline_stages job["inputReadMs"] = round(input_read_ms) job["gpuQueueWaitMs"] = round(gpu_queue_wait_ms) job["bundleSerializationMs"] = round(serialization_ms) job["taskDurationMs"] = round((time.perf_counter() - task_started) * 1000) job["outputFormat"] = "split-vizbundle" write_job(job) print(f"\n[JOB {job_id[:8]}] HD conversion completed in around {elapsed_ms / 1000:.2f}s\n", flush=True) except Exception as exc: print(f"Background conversion failed: {exc}", flush=True) if debug is not None: debug.fail(exc) try: job = read_job(job_id) job["status"] = JobStatus.FAILED job["phase"] = "failed" job["estimatedRemainingMs"] = None job["error"] = str(exc) write_job(job) except Exception: pass finally: release_live_job(job_id)