File size: 4,595 Bytes
790d9ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""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)