"""Background task and job bookkeeping for refinement requests. Refinement is a job rather than a blocking response for the same reason conversion is: a pass takes tens of seconds to minutes, which no reverse proxy or tunnel will hold open reliably. It reuses the conversion job store -- same JSON-file-per-job pattern, namespaced ids -- so the frontend polls it exactly the way it already polls a conversion. It also shares CONVERSION_GPU_LOCK. Refinement and conversion must never run concurrently: they compete for the same GPU, and refinement deliberately unloads the models conversion depends on. """ from __future__ import annotations import time import traceback from datetime import datetime, timezone from pathlib import Path import numpy as np from PIL import Image from config.paths import JOB_DIR from enums import JobStatus from services.jobs.conversion import CONVERSION_GPU_LOCK from services.jobs.store import read_job, write_job from services.refine.assets import read_refine_assets from services.refine.runner import RefinementError, refine_composite def refine_job_key(job_id: str, refine_id: str) -> str: return f"{job_id}.refine-{refine_id}" def refine_result_path(job_id: str, refine_id: str) -> Path: return JOB_DIR / f"{job_id}.refine-{refine_id}.png" def read_refine_job(job_id: str, refine_id: str) -> dict: return read_job(refine_job_key(job_id, refine_id)) def update_refine_job(job_id: str, refine_id: str, **fields) -> dict: job = read_job(refine_job_key(job_id, refine_id)) job.update(fields) write_job(job) return job def run_refinement_task( job_id: str, refine_id: str, composite_path: Path, original_path: Path, surfaces: list[dict], ) -> None: started = time.perf_counter() def fail(message: str) -> None: update_refine_job( job_id, refine_id, status=JobStatus.FAILED, phase="failed", message=message, progress=100, completedAt=datetime.now(timezone.utc).isoformat(), durationMs=round((time.perf_counter() - started) * 1000), ) try: assets = read_refine_assets(job_id) if assets is None: fail( "This job has no stored refinement assets. It was converted before " "refinement existed — re-upload the photo to regenerate them." ) return depth = assets["depth"] depth_image = ( Image.fromarray((np.asarray(depth) >> 8).astype(np.uint8), mode="L") if depth is not None else None ) update_refine_job( job_id, refine_id, status=JobStatus.PROCESSING, phase="queued", progress=1, message="Waiting for the GPU…", ) with CONVERSION_GPU_LOCK: def report(percent: float, message: str) -> None: phase = "loading-model" if message.startswith("Loading refinement model") else "refining" update_refine_job( job_id, refine_id, phase=phase, progress=max(1, min(99, round(percent))), message=message, ) original = Image.open(original_path).convert("RGB") composite = Image.open(composite_path).convert("RGB") final_image, metadata = refine_composite( composite_full=composite, original_full=original, depth_full=depth_image, masks_by_id=assets["masks"], surfaces=surfaces, progress_callback=report, ) result_path = refine_result_path(job_id, refine_id) final_image.save(result_path, format="PNG") update_refine_job( job_id, refine_id, status=JobStatus.COMPLETED, phase="completed", progress=100, message="Refinement complete", completedAt=datetime.now(timezone.utc).isoformat(), durationMs=round((time.perf_counter() - started) * 1000), resultBytes=result_path.stat().st_size, refinement=metadata, ) except RefinementError as exc: print(f"[REFINE] {exc}", flush=True) fail(str(exc)) except Exception as exc: traceback.print_exc() fail(f"Refinement failed: {exc}") finally: # The uploaded composite is a full-resolution PNG and is of no use once # the pass is done. composite_path.unlink(missing_ok=True)