Spaces:
Paused
Paused
github-actions[bot] commited on
Commit ·
630bc9b
1
Parent(s): 73828b3
Automated Deploy: 150451664699828d12d53bce0b44593aee3ae545
Browse files- routes/refine.py +50 -17
- scripts/test_refine_requests.py +54 -0
- services/refine/requests.py +59 -0
- services/refine/runner.py +1 -1
- services/refine/task.py +2 -1
routes/refine.py
CHANGED
|
@@ -13,6 +13,7 @@ request from repainting a wall the pipeline never identified.
|
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
import json
|
|
|
|
| 16 |
import uuid
|
| 17 |
from datetime import datetime, timezone
|
| 18 |
|
|
@@ -27,6 +28,7 @@ from errors import bad_request, conflict, not_found, service_unavailable
|
|
| 27 |
from services.jobs.store import read_job, write_job
|
| 28 |
from services.refine.assets import refine_assets_path
|
| 29 |
from services.refine.profiles import MATERIALS, SURFACE_KINDS
|
|
|
|
| 30 |
from services.refine.task import (
|
| 31 |
read_refine_job,
|
| 32 |
refine_job_key,
|
|
@@ -35,6 +37,7 @@ from services.refine.task import (
|
|
| 35 |
)
|
| 36 |
|
| 37 |
router = APIRouter(prefix="/viz2d", tags=["refine"])
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
def _assert_available() -> None:
|
|
@@ -124,24 +127,53 @@ async def start_refinement(
|
|
| 124 |
bad_request("composite must not be empty.")
|
| 125 |
|
| 126 |
parsed_surfaces = _parse_surfaces(surfaces)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
| 145 |
|
| 146 |
print(
|
| 147 |
f"\n[REFINE {refine_id}] queued for job {job_id[:8]} "
|
|
@@ -159,6 +191,7 @@ async def start_refinement(
|
|
| 159 |
"jobId": job_id,
|
| 160 |
"status": JobStatus.QUEUED,
|
| 161 |
"estimatedTotalMs": REFINE_TARGET_MS,
|
|
|
|
| 162 |
}
|
| 163 |
|
| 164 |
|
|
|
|
| 13 |
from __future__ import annotations
|
| 14 |
|
| 15 |
import json
|
| 16 |
+
import threading
|
| 17 |
import uuid
|
| 18 |
from datetime import datetime, timezone
|
| 19 |
|
|
|
|
| 28 |
from services.jobs.store import read_job, write_job
|
| 29 |
from services.refine.assets import refine_assets_path
|
| 30 |
from services.refine.profiles import MATERIALS, SURFACE_KINDS
|
| 31 |
+
from services.refine.requests import active_refinement_jobs, refinement_request_fingerprint
|
| 32 |
from services.refine.task import (
|
| 33 |
read_refine_job,
|
| 34 |
refine_job_key,
|
|
|
|
| 37 |
)
|
| 38 |
|
| 39 |
router = APIRouter(prefix="/viz2d", tags=["refine"])
|
| 40 |
+
_REFINEMENT_REQUEST_LOCK = threading.Lock()
|
| 41 |
|
| 42 |
|
| 43 |
def _assert_available() -> None:
|
|
|
|
| 127 |
bad_request("composite must not be empty.")
|
| 128 |
|
| 129 |
parsed_surfaces = _parse_surfaces(surfaces)
|
| 130 |
+
request_fingerprint = refinement_request_fingerprint(contents, parsed_surfaces)
|
| 131 |
+
|
| 132 |
+
# A reload used to lose the active refine id. Clicking Photoreal again then
|
| 133 |
+
# queued another expensive GPU pass while the original continued invisibly.
|
| 134 |
+
# Admit and persist requests under one lock so concurrent POSTs cannot both
|
| 135 |
+
# observe an empty queue.
|
| 136 |
+
with _REFINEMENT_REQUEST_LOCK:
|
| 137 |
+
active_jobs = active_refinement_jobs(job_id)
|
| 138 |
+
matching_job = next(
|
| 139 |
+
(
|
| 140 |
+
active_job for active_job in active_jobs
|
| 141 |
+
if active_job.get("requestFingerprint") == request_fingerprint
|
| 142 |
+
),
|
| 143 |
+
None,
|
| 144 |
+
)
|
| 145 |
+
if matching_job is not None:
|
| 146 |
+
return {
|
| 147 |
+
"refineId": matching_job["refineId"],
|
| 148 |
+
"jobId": job_id,
|
| 149 |
+
"status": matching_job["status"],
|
| 150 |
+
"estimatedTotalMs": matching_job.get("estimatedTotalMs", REFINE_TARGET_MS),
|
| 151 |
+
"reused": True,
|
| 152 |
+
}
|
| 153 |
+
if active_jobs:
|
| 154 |
+
conflict(
|
| 155 |
+
"Another refinement is already running for this room. "
|
| 156 |
+
"Wait for it to finish before changing the tile arrangement."
|
| 157 |
+
)
|
| 158 |
|
| 159 |
+
refine_id = uuid.uuid4().hex[:12]
|
| 160 |
+
composite_path = JOB_DIR / f"{job_id}.refine-{refine_id}.input.png"
|
| 161 |
+
composite_path.write_bytes(contents)
|
| 162 |
+
|
| 163 |
+
write_job({
|
| 164 |
+
"id": refine_job_key(job_id, refine_id),
|
| 165 |
+
"jobId": job_id,
|
| 166 |
+
"refineId": refine_id,
|
| 167 |
+
"status": JobStatus.QUEUED,
|
| 168 |
+
"phase": "queued",
|
| 169 |
+
"progress": 0,
|
| 170 |
+
"message": "Queued for refinement…",
|
| 171 |
+
"estimatedTotalMs": REFINE_TARGET_MS,
|
| 172 |
+
"createdAt": datetime.now(timezone.utc).isoformat(),
|
| 173 |
+
"surfaces": parsed_surfaces,
|
| 174 |
+
"knownMaterials": sorted(MATERIALS),
|
| 175 |
+
"requestFingerprint": request_fingerprint,
|
| 176 |
+
})
|
| 177 |
|
| 178 |
print(
|
| 179 |
f"\n[REFINE {refine_id}] queued for job {job_id[:8]} "
|
|
|
|
| 191 |
"jobId": job_id,
|
| 192 |
"status": JobStatus.QUEUED,
|
| 193 |
"estimatedTotalMs": REFINE_TARGET_MS,
|
| 194 |
+
"reused": False,
|
| 195 |
}
|
| 196 |
|
| 197 |
|
scripts/test_refine_requests.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dependency-free checks for refinement request admission helpers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import pathlib
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
from datetime import datetime, timedelta, timezone
|
| 10 |
+
|
| 11 |
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
| 12 |
+
|
| 13 |
+
from services.refine.requests import active_refinement_jobs, refinement_request_fingerprint
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def write_job(directory: pathlib.Path, refine_id: str, **values) -> None:
|
| 17 |
+
payload = {
|
| 18 |
+
"id": f"room.refine-{refine_id}",
|
| 19 |
+
"jobId": "room",
|
| 20 |
+
"refineId": refine_id,
|
| 21 |
+
"status": "PROCESSING",
|
| 22 |
+
"createdAt": datetime.now(timezone.utc).isoformat(),
|
| 23 |
+
**values,
|
| 24 |
+
}
|
| 25 |
+
(directory / f"room.refine-{refine_id}.json").write_text(json.dumps(payload))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main() -> int:
|
| 29 |
+
surfaces = [{"segmentIds": [0], "materialType": "marble", "surfaceKind": "floor"}]
|
| 30 |
+
fingerprint = refinement_request_fingerprint(b"same-pixels", surfaces)
|
| 31 |
+
assert fingerprint == refinement_request_fingerprint(b"same-pixels", surfaces)
|
| 32 |
+
assert fingerprint != refinement_request_fingerprint(b"different-pixels", surfaces)
|
| 33 |
+
|
| 34 |
+
with tempfile.TemporaryDirectory() as raw_directory:
|
| 35 |
+
directory = pathlib.Path(raw_directory)
|
| 36 |
+
write_job(directory, "active", requestFingerprint=fingerprint)
|
| 37 |
+
write_job(directory, "complete", status="COMPLETED", requestFingerprint=fingerprint)
|
| 38 |
+
write_job(
|
| 39 |
+
directory,
|
| 40 |
+
"stale",
|
| 41 |
+
createdAt=(datetime.now(timezone.utc) - timedelta(minutes=21)).isoformat(),
|
| 42 |
+
requestFingerprint=fingerprint,
|
| 43 |
+
)
|
| 44 |
+
write_job(directory, "other-room", jobId="different-room", requestFingerprint=fingerprint)
|
| 45 |
+
|
| 46 |
+
active = active_refinement_jobs("room", job_dir=directory)
|
| 47 |
+
assert [job["refineId"] for job in active] == ["active"]
|
| 48 |
+
|
| 49 |
+
print("Refinement request admission checks passed.")
|
| 50 |
+
return 0
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
if __name__ == "__main__":
|
| 54 |
+
raise SystemExit(main())
|
services/refine/requests.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Identity and admission helpers for refinement requests."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
from datetime import datetime, timezone
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from config.paths import JOB_DIR
|
| 11 |
+
from enums import JobStatus
|
| 12 |
+
|
| 13 |
+
ACTIVE_REFINEMENT_STATUSES = {JobStatus.QUEUED, JobStatus.PROCESSING}
|
| 14 |
+
ACTIVE_REFINEMENT_MAX_AGE_SECONDS = 20 * 60
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def refinement_request_fingerprint(composite: bytes, surfaces: list[dict]) -> str:
|
| 18 |
+
"""Return a stable identity for the pixels and material arrangement."""
|
| 19 |
+
digest = hashlib.sha256()
|
| 20 |
+
digest.update(composite)
|
| 21 |
+
digest.update(b"\0")
|
| 22 |
+
digest.update(json.dumps(surfaces, sort_keys=True, separators=(",", ":")).encode())
|
| 23 |
+
return digest.hexdigest()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def active_refinement_jobs(
|
| 27 |
+
job_id: str,
|
| 28 |
+
*,
|
| 29 |
+
job_dir: Path = JOB_DIR,
|
| 30 |
+
now: datetime | None = None,
|
| 31 |
+
) -> list[dict]:
|
| 32 |
+
"""Return recent active refinements for a conversion, newest first.
|
| 33 |
+
|
| 34 |
+
A process restart can leave a PROCESSING JSON file behind even though no
|
| 35 |
+
task exists to finish it. Ignore records older than the frontend timeout so
|
| 36 |
+
they cannot permanently block a new request.
|
| 37 |
+
"""
|
| 38 |
+
current_time = now or datetime.now(timezone.utc)
|
| 39 |
+
active: list[dict] = []
|
| 40 |
+
|
| 41 |
+
for path in job_dir.glob(f"{job_id}.refine-*.json"):
|
| 42 |
+
try:
|
| 43 |
+
candidate = json.loads(path.read_text())
|
| 44 |
+
created_at = datetime.fromisoformat(str(candidate["createdAt"]).replace("Z", "+00:00"))
|
| 45 |
+
if created_at.tzinfo is None:
|
| 46 |
+
created_at = created_at.replace(tzinfo=timezone.utc)
|
| 47 |
+
except (KeyError, OSError, TypeError, ValueError, json.JSONDecodeError):
|
| 48 |
+
continue
|
| 49 |
+
|
| 50 |
+
if candidate.get("jobId") != job_id:
|
| 51 |
+
continue
|
| 52 |
+
if candidate.get("status") not in ACTIVE_REFINEMENT_STATUSES:
|
| 53 |
+
continue
|
| 54 |
+
if (current_time - created_at).total_seconds() > ACTIVE_REFINEMENT_MAX_AGE_SECONDS:
|
| 55 |
+
continue
|
| 56 |
+
active.append(candidate)
|
| 57 |
+
|
| 58 |
+
active.sort(key=lambda item: str(item.get("createdAt") or ""), reverse=True)
|
| 59 |
+
return active
|
services/refine/runner.py
CHANGED
|
@@ -124,7 +124,7 @@ def refine_composite(
|
|
| 124 |
if REFINE_UNLOAD_CV_MODELS:
|
| 125 |
unload_cv_models()
|
| 126 |
|
| 127 |
-
report(0.05, "Loading refinement model…")
|
| 128 |
pipe = load_diffusion_pipeline()
|
| 129 |
print(describe_vram("after model load"), flush=True)
|
| 130 |
|
|
|
|
| 124 |
if REFINE_UNLOAD_CV_MODELS:
|
| 125 |
unload_cv_models()
|
| 126 |
|
| 127 |
+
report(0.05, "Loading refinement model (the first run may take a few minutes)…")
|
| 128 |
pipe = load_diffusion_pipeline()
|
| 129 |
print(describe_vram("after model load"), flush=True)
|
| 130 |
|
services/refine/task.py
CHANGED
|
@@ -91,9 +91,10 @@ def run_refinement_task(
|
|
| 91 |
|
| 92 |
with CONVERSION_GPU_LOCK:
|
| 93 |
def report(percent: float, message: str) -> None:
|
|
|
|
| 94 |
update_refine_job(
|
| 95 |
job_id, refine_id,
|
| 96 |
-
phase=
|
| 97 |
progress=max(1, min(99, round(percent))),
|
| 98 |
message=message,
|
| 99 |
)
|
|
|
|
| 91 |
|
| 92 |
with CONVERSION_GPU_LOCK:
|
| 93 |
def report(percent: float, message: str) -> None:
|
| 94 |
+
phase = "loading-model" if message.startswith("Loading refinement model") else "refining"
|
| 95 |
update_refine_job(
|
| 96 |
job_id, refine_id,
|
| 97 |
+
phase=phase,
|
| 98 |
progress=max(1, min(99, round(percent))),
|
| 99 |
message=message,
|
| 100 |
)
|