Codex staging deploy commited on
Commit
c77cb97
·
1 Parent(s): 5003ea5

Preview feature/realistic-floor-rendering at 2ded5de

Browse files
app.py CHANGED
@@ -9,6 +9,7 @@ import os
9
  import shutil
10
  import subprocess
11
  import time
 
12
  import urllib.error
13
  import urllib.parse
14
  import urllib.request
@@ -258,7 +259,13 @@ DEBUG_ARTIFACTS_ENABLED = str(config_value(
258
  "debug_artifacts_enabled",
259
  "1",
260
  )).lower() in {"1", "true", "yes", "on"}
261
- DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
 
 
 
 
 
 
262
  "DEBUG_ARTIFACTS_MAX_DIMENSION",
263
  "runtime",
264
  "debug_artifacts_max_dimension",
@@ -717,6 +724,7 @@ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
717
  JOB_DIR.mkdir(parents=True, exist_ok=True)
718
  MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
719
  QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
 
720
  app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
721
 
722
 
@@ -3749,7 +3757,7 @@ def build_manifest_segmentation_bundle(
3749
  return buffer.getvalue()
3750
 
3751
 
3752
- def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None):
3753
  t_start = time.perf_counter()
3754
 
3755
  t0 = time.perf_counter()
@@ -3769,8 +3777,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3769
  image_loading_elapsed * 1000,
3770
  )
3771
 
3772
- t0 = time.perf_counter()
3773
- seg_map = run_segmentation(img, img_np)
 
 
3774
  segmentation_elapsed = time.perf_counter() - t0
3775
  print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True)
3776
  if debug is not None:
@@ -3793,8 +3803,12 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3793
  segmentation_elapsed * 1000,
3794
  )
3795
 
3796
- t0 = time.perf_counter()
3797
- pixels_b64 = encode_bundle_image_data_url(img_np)
 
 
 
 
3798
  print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
3799
 
3800
  t0 = time.perf_counter()
@@ -3834,8 +3848,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3834
  floor_mask_elapsed * 1000,
3835
  )
3836
 
3837
- t0 = time.perf_counter()
3838
- geometry = estimate_scene_geometry(img, img_np, w, h)
 
 
 
3839
  depth = geometry.get("depth")
3840
  geometry_elapsed = time.perf_counter() - t0
3841
  print(
@@ -3860,8 +3877,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3860
  geometry_elapsed * 1000,
3861
  )
3862
 
3863
- t0 = time.perf_counter()
3864
- homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
 
 
3865
  plane_elapsed = time.perf_counter() - t0
3866
  print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True)
3867
  if debug is not None:
@@ -3881,8 +3900,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3881
  plane_elapsed * 1000,
3882
  )
3883
 
3884
- t0 = time.perf_counter()
3885
- quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
 
 
3886
  surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
3887
  replaced_material_mask = (
3888
  np.isin(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES))
@@ -3909,8 +3930,10 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3909
  surface_mask_elapsed * 1000,
3910
  )
3911
 
3912
- t0 = time.perf_counter()
3913
- surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
 
 
3914
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
3915
  mapping_metadata = (
3916
  surface_mapping["metadata"]
@@ -3964,8 +3987,11 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
3964
  surface_mapping_elapsed * 1000,
3965
  )
3966
 
3967
- t0 = time.perf_counter()
3968
- lighting_maps = None
 
 
 
3969
  shade_map = None
3970
  showroom_shade_map = None
3971
  reflection_map = None
@@ -4021,9 +4047,12 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
4021
  "shadingAvailable": shade_map is not None,
4022
  "reflectionsAvailable": reflection_map is not None,
4023
  },
4024
- lighting_elapsed * 1000,
4025
- )
4026
-
 
 
 
4027
  t0 = time.perf_counter()
4028
  direction_transform = (
4029
  plane.get("floorTransform")
@@ -4083,9 +4112,12 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
4083
  [("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))],
4084
  floor_direction,
4085
  floor_direction_elapsed * 1000,
4086
- )
4087
-
4088
- t0 = time.perf_counter()
 
 
 
4089
  segments = []
4090
  models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
4091
 
@@ -4192,7 +4224,9 @@ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | Non
4192
  },
4193
  })
4194
 
4195
- total_elapsed = time.perf_counter() - t_start
 
 
4196
  print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True)
4197
  if debug is not None:
4198
  debug.complete(total_elapsed * 1000)
@@ -4217,8 +4251,97 @@ def read_job(job_id: str):
4217
  return json.loads(path.read_text())
4218
 
4219
 
4220
- def write_job(job: dict):
4221
- job_path(job["id"]).write_text(json.dumps(job))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4222
 
4223
 
4224
  def spaces_upload_enabled() -> bool:
@@ -5143,34 +5266,86 @@ def run_qa_task(run_id: str, image_keys: list[str], tiles: list[str], descriptio
5143
 
5144
 
5145
  def run_conversion_task(job_id: str, upload_path: Path):
5146
- debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
5147
- try:
5148
- t_start = time.perf_counter()
5149
- image_bytes = upload_path.read_bytes()
5150
- bundle = build_segmentation_bundle(image_bytes, debug=debug)
5151
- binary_bundle = build_manifest_segmentation_bundle(
5152
- bundle,
5153
- job_id,
5154
- image_url=f"/uploads/{upload_path.name}",
5155
- include_image=False,
5156
- )
5157
- (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
5158
- job = read_job(job_id)
5159
- job["status"] = "COMPLETED"
5160
- job["modelName"] = bundle.get("modelName")
5161
- job["models"] = bundle.get("models")
5162
- job["outputFormat"] = "split-vizbundle"
5163
- write_job(job)
5164
- print(f"[TIMING] Background conversion task for job {job_id} took {time.perf_counter() - t_start:.3f} seconds", flush=True)
5165
- except Exception as exc:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5166
  print(f"Background conversion failed: {exc}", flush=True)
5167
  if debug is not None:
5168
  debug.fail(exc)
5169
  try:
5170
- job = read_job(job_id)
5171
- job["status"] = "FAILED"
5172
- job["error"] = str(exc)
5173
- write_job(job)
 
 
5174
  except Exception:
5175
  pass
5176
 
@@ -5498,10 +5673,18 @@ async def convert_to_viz2d(background_tasks: BackgroundTasks, file: UploadFile =
5498
  upload_path = UPLOAD_DIR / f"{job_id}{ext}"
5499
  upload_path.write_bytes(normalized_contents)
5500
 
5501
- job = {
5502
- "id": job_id,
5503
- "status": "PROCESSING",
5504
- "inputUrl": f"/uploads/{upload_path.name}",
 
 
 
 
 
 
 
 
5505
  "outputUrl": f"/viz2d/jobs/{job_id}/file",
5506
  "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
5507
  }
 
9
  import shutil
10
  import subprocess
11
  import time
12
+ import threading
13
  import urllib.error
14
  import urllib.parse
15
  import urllib.request
 
259
  "debug_artifacts_enabled",
260
  "1",
261
  )).lower() in {"1", "true", "yes", "on"}
262
+ CONVERSION_TARGET_MS = max(5_000, int(config_value(
263
+ "CONVERSION_TARGET_MS",
264
+ "runtime",
265
+ "conversion_target_ms",
266
+ "30000",
267
+ )))
268
+ DEBUG_ARTIFACTS_MAX_DIMENSION = max(320, int(config_value(
269
  "DEBUG_ARTIFACTS_MAX_DIMENSION",
270
  "runtime",
271
  "debug_artifacts_max_dimension",
 
724
  JOB_DIR.mkdir(parents=True, exist_ok=True)
725
  MATERIAL_DIR.mkdir(parents=True, exist_ok=True)
726
  QA_RUN_DIR.mkdir(parents=True, exist_ok=True)
727
+ TIMING_BASELINE_PATH = DATA_DIR / "conversion-timings.json"
728
  app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
729
 
730
 
 
3757
  return buffer.getvalue()
3758
 
3759
 
3760
+ def build_segmentation_bundle(contents: bytes, debug: PipelineDebugCapture | None = None, progress_callback=None):
3761
  t_start = time.perf_counter()
3762
 
3763
  t0 = time.perf_counter()
 
3777
  image_loading_elapsed * 1000,
3778
  )
3779
 
3780
+ if progress_callback:
3781
+ progress_callback("segmentation", 0)
3782
+ t0 = time.perf_counter()
3783
+ seg_map = run_segmentation(img, img_np)
3784
  segmentation_elapsed = time.perf_counter() - t0
3785
  print(f"[TIMING] Floor segmentation took {segmentation_elapsed:.3f} seconds", flush=True)
3786
  if debug is not None:
 
3803
  segmentation_elapsed * 1000,
3804
  )
3805
 
3806
+ if progress_callback:
3807
+ progress_callback("segmentation", 100)
3808
+ if progress_callback:
3809
+ progress_callback("masking", 0)
3810
+ t0 = time.perf_counter()
3811
+ pixels_b64 = encode_bundle_image_data_url(img_np)
3812
  print(f"[TIMING] Image bundle encoding took {time.perf_counter() - t0:.3f} seconds", flush=True)
3813
 
3814
  t0 = time.perf_counter()
 
3848
  floor_mask_elapsed * 1000,
3849
  )
3850
 
3851
+ if progress_callback:
3852
+ progress_callback("masking", 100)
3853
+ progress_callback("geometry", 0)
3854
+ t0 = time.perf_counter()
3855
+ geometry = estimate_scene_geometry(img, img_np, w, h)
3856
  depth = geometry.get("depth")
3857
  geometry_elapsed = time.perf_counter() - t0
3858
  print(
 
3877
  geometry_elapsed * 1000,
3878
  )
3879
 
3880
+ if progress_callback:
3881
+ progress_callback("geometry", 55)
3882
+ t0 = time.perf_counter()
3883
+ homography, plane = estimate_floor_plane(floor_mask, img_np, geometry)
3884
  plane_elapsed = time.perf_counter() - t0
3885
  print(f"[TIMING] Plane fitting / homography calculation took {plane_elapsed:.3f} seconds", flush=True)
3886
  if debug is not None:
 
3900
  plane_elapsed * 1000,
3901
  )
3902
 
3903
+ if progress_callback:
3904
+ progress_callback("geometry", 100)
3905
+ t0 = time.perf_counter()
3906
+ quad = np.asarray(plane["quad"], dtype=np.float32).reshape(4, 2) if plane and plane.get("quad") else None
3907
  surface_mask, edge_metadata = build_floor_surface_mask(floor_mask, seg_map, quad, depth, geometry, plane)
3908
  replaced_material_mask = (
3909
  np.isin(seg_map, class_ids(REPLACEABLE_SOFT_FLOOR_CLASSES))
 
3930
  surface_mask_elapsed * 1000,
3931
  )
3932
 
3933
+ if progress_callback:
3934
+ progress_callback("surface-mapping", 0)
3935
+ t0 = time.perf_counter()
3936
+ surface_mapping = build_surface_uv_mapping(surface_mask, surface_indices, geometry)
3937
  use_surface_uv = bool(surface_mapping and surface_mapping.get("useSurfaceUv"))
3938
  mapping_metadata = (
3939
  surface_mapping["metadata"]
 
3987
  surface_mapping_elapsed * 1000,
3988
  )
3989
 
3990
+ if progress_callback:
3991
+ progress_callback("surface-mapping", 100)
3992
+ progress_callback("lighting", 0)
3993
+ t0 = time.perf_counter()
3994
+ lighting_maps = None
3995
  shade_map = None
3996
  showroom_shade_map = None
3997
  reflection_map = None
 
4047
  "shadingAvailable": shade_map is not None,
4048
  "reflectionsAvailable": reflection_map is not None,
4049
  },
4050
+ lighting_elapsed * 1000,
4051
+ )
4052
+
4053
+ if progress_callback:
4054
+ progress_callback("lighting", 100)
4055
+ progress_callback("direction", 0)
4056
  t0 = time.perf_counter()
4057
  direction_transform = (
4058
  plane.get("floorTransform")
 
4112
  [("Direction analysis", debug_floor_direction_overlay(img_np, floor_direction))],
4113
  floor_direction,
4114
  floor_direction_elapsed * 1000,
4115
+ )
4116
+
4117
+ if progress_callback:
4118
+ progress_callback("direction", 100)
4119
+ progress_callback("packaging", 0)
4120
+ t0 = time.perf_counter()
4121
  segments = []
4122
  models = active_model_metadata(geometry, depth, shade_map, intrinsic_lighting_used)
4123
 
 
4224
  },
4225
  })
4226
 
4227
+ if progress_callback:
4228
+ progress_callback("packaging", 100)
4229
+ total_elapsed = time.perf_counter() - t_start
4230
  print(f"[TIMING] Total bundle processing completed in {total_elapsed:.3f} seconds", flush=True)
4231
  if debug is not None:
4232
  debug.complete(total_elapsed * 1000)
 
4251
  return json.loads(path.read_text())
4252
 
4253
 
4254
+ def write_job(job: dict):
4255
+ path = job_path(job["id"])
4256
+ temporary = path.with_suffix(f"{path.suffix}.{os.getpid()}.tmp")
4257
+ temporary.write_text(json.dumps(job, separators=(",", ":")))
4258
+ temporary.replace(path)
4259
+
4260
+
4261
+ CONVERSION_STAGE_WEIGHTS = {
4262
+ "segmentation": 0.28,
4263
+ "masking": 0.08,
4264
+ "geometry": 0.18,
4265
+ "surface-mapping": 0.12,
4266
+ "lighting": 0.15,
4267
+ "direction": 0.08,
4268
+ "packaging": 0.11,
4269
+ }
4270
+ CONVERSION_STAGE_ORDER = tuple(CONVERSION_STAGE_WEIGHTS)
4271
+ CONVERSION_GPU_LOCK = threading.Lock()
4272
+
4273
+
4274
+ def update_conversion_job(
4275
+ job_id: str,
4276
+ *,
4277
+ phase: str | None = None,
4278
+ progress: int | None = None,
4279
+ phase_progress: int | None = None,
4280
+ message: str | None = None,
4281
+ **values,
4282
+ ):
4283
+ """Persist live conversion state for the browser's progress and ETA display."""
4284
+ try:
4285
+ job = read_job(job_id)
4286
+ except HTTPException:
4287
+ return
4288
+ if phase is not None:
4289
+ job["phase"] = phase
4290
+ if progress is not None:
4291
+ job["progress"] = max(0, min(100, int(progress)))
4292
+ if phase_progress is not None:
4293
+ job["phaseProgress"] = max(0, min(100, int(phase_progress)))
4294
+ if message is not None:
4295
+ job["message"] = message
4296
+ job.update(values)
4297
+ write_job(job)
4298
+
4299
+
4300
+ def weighted_conversion_progress(completed_phases: set[str], phase: str, phase_progress: float) -> int:
4301
+ completed_weight = sum(
4302
+ CONVERSION_STAGE_WEIGHTS.get(item, 0.0)
4303
+ for item in completed_phases
4304
+ if item != phase
4305
+ )
4306
+ current_weight = CONVERSION_STAGE_WEIGHTS.get(phase, 0.0) * max(0.0, min(1.0, phase_progress / 100.0))
4307
+ return round((completed_weight + current_weight) * 100)
4308
+
4309
+
4310
+ TIMING_BASELINE_LOCK = threading.Lock()
4311
+ TIMING_BASELINE_PATH: Path | None = None
4312
+
4313
+
4314
+ def estimate_conversion_ms() -> int:
4315
+ default_ms = CONVERSION_TARGET_MS
4316
+ if TIMING_BASELINE_PATH is None or not TIMING_BASELINE_PATH.exists():
4317
+ return default_ms
4318
+ try:
4319
+ data = json.loads(TIMING_BASELINE_PATH.read_text())
4320
+ samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0]
4321
+ if len(samples) < 3:
4322
+ return default_ms
4323
+ samples.sort()
4324
+ return max(5_000, round(samples[min(len(samples) - 1, int(len(samples) * 0.75))]))
4325
+ except (OSError, TypeError, ValueError, json.JSONDecodeError):
4326
+ return default_ms
4327
+
4328
+
4329
+ def record_conversion_ms(duration_ms: float):
4330
+ if TIMING_BASELINE_PATH is None:
4331
+ return
4332
+ with TIMING_BASELINE_LOCK:
4333
+ data = {"totalMs": []}
4334
+ try:
4335
+ if TIMING_BASELINE_PATH.exists():
4336
+ data = json.loads(TIMING_BASELINE_PATH.read_text())
4337
+ except (OSError, TypeError, ValueError, json.JSONDecodeError):
4338
+ data = {"totalMs": []}
4339
+ samples = [float(value) for value in data.get("totalMs", []) if float(value) > 0]
4340
+ samples.append(float(duration_ms))
4341
+ data["totalMs"] = samples[-40:]
4342
+ temporary = TIMING_BASELINE_PATH.with_suffix(f"{TIMING_BASELINE_PATH.suffix}.{os.getpid()}.tmp")
4343
+ temporary.write_text(json.dumps(data, separators=(",", ":")))
4344
+ temporary.replace(TIMING_BASELINE_PATH)
4345
 
4346
 
4347
  def spaces_upload_enabled() -> bool:
 
5266
 
5267
 
5268
  def run_conversion_task(job_id: str, upload_path: Path):
5269
+ debug = PipelineDebugCapture(job_id) if DEBUG_ARTIFACTS_ENABLED else None
5270
+ estimate_ms = estimate_conversion_ms()
5271
+ try:
5272
+ update_conversion_job(
5273
+ job_id,
5274
+ status="QUEUED",
5275
+ phase="queued",
5276
+ progress=0,
5277
+ phase_progress=0,
5278
+ message="Waiting for an analysis slot…",
5279
+ estimatedTotalMs=estimate_ms,
5280
+ estimatedRemainingMs=estimate_ms,
5281
+ )
5282
+ with CONVERSION_GPU_LOCK:
5283
+ t_start = time.perf_counter()
5284
+ update_conversion_job(
5285
+ job_id,
5286
+ status="PROCESSING",
5287
+ phase="segmentation",
5288
+ progress=0,
5289
+ phase_progress=0,
5290
+ message="Analyzing floor…",
5291
+ startedAt=datetime.now(timezone.utc).isoformat(),
5292
+ estimatedTotalMs=estimate_ms,
5293
+ estimatedRemainingMs=estimate_ms,
5294
+ )
5295
+ completed_phases: set[str] = set()
5296
+
5297
+ def report_stage(phase: str, phase_progress: float):
5298
+ if phase_progress >= 100:
5299
+ completed_phases.add(phase)
5300
+ elapsed_ms = (time.perf_counter() - t_start) * 1000
5301
+ remaining_ms = max(0, estimate_ms - elapsed_ms)
5302
+ update_conversion_job(
5303
+ job_id,
5304
+ phase=phase,
5305
+ progress=weighted_conversion_progress(completed_phases, phase, phase_progress),
5306
+ phase_progress=round(phase_progress),
5307
+ message=f"Analyzing {phase.replace('-', ' ')}…",
5308
+ estimatedRemainingMs=round(remaining_ms),
5309
+ )
5310
+
5311
+ image_bytes = upload_path.read_bytes()
5312
+ bundle = build_segmentation_bundle(image_bytes, debug=debug, progress_callback=report_stage)
5313
+ report_stage("packaging", 25)
5314
+ binary_bundle = build_manifest_segmentation_bundle(
5315
+ bundle,
5316
+ job_id,
5317
+ image_url=f"/uploads/{upload_path.name}",
5318
+ include_image=False,
5319
+ )
5320
+ (JOB_DIR / f"{job_id}.vizbundle").write_bytes(binary_bundle)
5321
+ report_stage("packaging", 100)
5322
+ elapsed_ms = (time.perf_counter() - t_start) * 1000
5323
+ record_conversion_ms(elapsed_ms)
5324
+ job = read_job(job_id)
5325
+ job["status"] = "COMPLETED"
5326
+ job["phase"] = "completed"
5327
+ job["progress"] = 100
5328
+ job["phaseProgress"] = 100
5329
+ job["message"] = "Surfaces ready"
5330
+ job["estimatedRemainingMs"] = 0
5331
+ job["completedAt"] = datetime.now(timezone.utc).isoformat()
5332
+ job["durationMs"] = round(elapsed_ms)
5333
+ job["modelName"] = bundle.get("modelName")
5334
+ job["models"] = bundle.get("models")
5335
+ job["outputFormat"] = "split-vizbundle"
5336
+ write_job(job)
5337
+ print(f"[TIMING] Background conversion task for job {job_id} took {elapsed_ms / 1000:.3f} seconds", flush=True)
5338
+ except Exception as exc:
5339
  print(f"Background conversion failed: {exc}", flush=True)
5340
  if debug is not None:
5341
  debug.fail(exc)
5342
  try:
5343
+ job = read_job(job_id)
5344
+ job["status"] = "FAILED"
5345
+ job["phase"] = "failed"
5346
+ job["estimatedRemainingMs"] = None
5347
+ job["error"] = str(exc)
5348
+ write_job(job)
5349
  except Exception:
5350
  pass
5351
 
 
5673
  upload_path = UPLOAD_DIR / f"{job_id}{ext}"
5674
  upload_path.write_bytes(normalized_contents)
5675
 
5676
+ job = {
5677
+ "id": job_id,
5678
+ "status": "QUEUED",
5679
+ "phase": "queued",
5680
+ "progress": 0,
5681
+ "phaseProgress": 0,
5682
+ "message": "Waiting for an analysis slot…",
5683
+ "createdAt": datetime.now(timezone.utc).isoformat(),
5684
+ "estimatedTotalMs": estimate_conversion_ms(),
5685
+ "estimatedRemainingMs": estimate_conversion_ms(),
5686
+ "targetMs": CONVERSION_TARGET_MS,
5687
+ "inputUrl": f"/uploads/{upload_path.name}",
5688
  "outputUrl": f"/viz2d/jobs/{job_id}/file",
5689
  "debugUrl": f"/viz2d/jobs/{job_id}/debug" if DEBUG_ARTIFACTS_ENABLED else None,
5690
  }
frontend/viz2d-demo/e2e/lighting-preservation.spec.ts CHANGED
@@ -3,6 +3,37 @@ import { expect, test, type Page } from "@playwright/test";
3
  const WIDTH = 120;
4
  const HEIGHT = 72;
5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  for (const renderer of ["webgl", "canvas"] as const) {
7
  test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
8
  if (renderer === "canvas") {
@@ -32,6 +63,24 @@ for (const renderer of ["webgl", "canvas"] as const) {
32
  expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
33
  });
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
36
  if (renderer === "canvas") {
37
  await disableWebGl(page);
@@ -59,11 +108,36 @@ for (const renderer of ["webgl", "canvas"] as const) {
59
  });
60
  }
61
 
62
- function buildLightingBundle() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  const pixelCount = WIDTH * HEIGHT;
64
  const pixels = new Uint8Array(pixelCount * 4);
65
  const mask = new Uint32Array(pixelCount);
66
  const shadeMap = new Uint8Array(pixelCount);
 
67
 
68
  for (let index = 0; index < pixelCount; index += 1) {
69
  const x = index % WIDTH;
@@ -76,6 +150,7 @@ function buildLightingBundle() {
76
  pixels[pixelIndex + 3] = 255;
77
  mask[index] = index;
78
  shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
 
79
  }
80
 
81
  return {
@@ -93,10 +168,10 @@ function buildLightingBundle() {
93
  plane: null,
94
  shadeMap: Buffer.from(shadeMap).toString("base64"),
95
  showroomShadeMap: null,
96
- reflectionMap: null,
97
  metadata: {
98
  lightingSource: "synthetic-test",
99
- lightingTransferVersion: 3,
100
  shadeMapEncoding: "linear-relative",
101
  shadeMapRange: [0.08, 1.85],
102
  renderPresetDefaults: {
@@ -175,6 +250,27 @@ async function disableWebGl(page: Page) {
175
  });
176
  }
177
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  async function readLightingRegions(page: Page) {
179
  return page.getByTestId("visualizer-canvas").evaluate((node) => {
180
  const canvas = node as HTMLCanvasElement;
 
3
  const WIDTH = 120;
4
  const HEIGHT = 72;
5
 
6
+ test("shows a persistent floor label without tinting the mask", async ({ page }) => {
7
+ await page.goto("/");
8
+ await page.getByTestId("room-file-input").setInputFiles({
9
+ name: "surface-label.vizbundle.json",
10
+ mimeType: "application/json",
11
+ buffer: Buffer.from(JSON.stringify(buildLightingBundle())),
12
+ });
13
+
14
+ const canvas = page.getByTestId("visualizer-canvas");
15
+ const label = page.getByTestId("surface-label").filter({ hasText: "Floor" });
16
+ await expect(canvas).toBeVisible();
17
+ await expect(label).toBeVisible();
18
+ await expectLabelInsideCanvas(canvas, label);
19
+
20
+ const beforeHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
21
+ const canvasBox = await canvas.boundingBox();
22
+ expect(canvasBox).not.toBeNull();
23
+ await page.mouse.move(canvasBox!.x + canvasBox!.width / 2, canvasBox!.y + canvasBox!.height / 2);
24
+ const afterHover = await readCanvasPixel(canvas, WIDTH / 2, HEIGHT / 2);
25
+ expect(afterHover).toEqual(beforeHover);
26
+
27
+ const labelBox = await label.boundingBox();
28
+ expect(labelBox).not.toBeNull();
29
+ await page.mouse.click(labelBox!.x + labelBox!.width / 2, labelBox!.y + labelBox!.height / 2);
30
+ await expect(page.getByTestId("texture-selector")).toBeVisible();
31
+ await page.getByLabel("Close", { exact: true }).click();
32
+
33
+ await page.setViewportSize({ width: 390, height: 844 });
34
+ await expectLabelInsideCanvas(canvas, label);
35
+ });
36
+
37
  for (const renderer of ["webgl", "canvas"] as const) {
38
  test(`applied tile preserves scene lighting in ${renderer}`, async ({ page }) => {
39
  if (renderer === "canvas") {
 
63
  expect(luminance.bright, "bright source region should approach white").toBeGreaterThan(240);
64
  });
65
 
66
+ test(`v4 keeps shadows unchanged and controls highlights on dark tile in ${renderer}`, async ({ page }) => {
67
+ if (renderer === "canvas") {
68
+ await disableWebGl(page);
69
+ }
70
+
71
+ const legacy = await renderLightingBundle(page, 3, false, "Dark Marble");
72
+ const materialAware = await renderLightingBundle(page, 4, false, "Dark Marble");
73
+ const materialAwareWithReflection = await renderLightingBundle(page, 4, true, "Dark Marble");
74
+
75
+ expect(materialAware.dark, "v4 must not weaken or strengthen source shadows").toBeCloseTo(legacy.dark, 0);
76
+ expect(materialAware.neutral, "v4 must not alter neutral source lighting").toBeCloseTo(legacy.neutral, 0);
77
+ expect(materialAwareWithReflection.bright, "bright source lighting should remain visible").toBeGreaterThan(
78
+ materialAwareWithReflection.neutral + 8,
79
+ );
80
+ expect(materialAwareWithReflection.bright, "dark tile highlights should retain material color").toBeLessThan(190);
81
+ expect(materialAware.bright, "v4 should reduce additive whitening").toBeLessThan(legacy.bright);
82
+ });
83
+
84
  test(`applied tile fully covers the floor-mask edge in ${renderer}`, async ({ page }) => {
85
  if (renderer === "canvas") {
86
  await disableWebGl(page);
 
108
  });
109
  }
110
 
111
+ async function readCanvasPixel(pageCanvas: ReturnType<import("@playwright/test").Page["getByTestId"]>, x: number, y: number) {
112
+ return pageCanvas.evaluate((canvas, point) => {
113
+ const context = (canvas as HTMLCanvasElement).getContext("2d");
114
+ if (!context) throw new Error("Canvas context is unavailable.");
115
+ return Array.from(context.getImageData(point.x, point.y, 1, 1).data);
116
+ }, { x, y });
117
+ }
118
+
119
+ async function expectLabelInsideCanvas(
120
+ canvas: ReturnType<import("@playwright/test").Page["getByTestId"]>,
121
+ label: ReturnType<import("@playwright/test").Page["getByTestId"]>,
122
+ ) {
123
+ await expect.poll(async () => {
124
+ const [canvasBox, labelBox] = await Promise.all([canvas.boundingBox(), label.boundingBox()]);
125
+ if (!canvasBox || !labelBox) return false;
126
+ return (
127
+ labelBox.x >= canvasBox.x &&
128
+ labelBox.y >= canvasBox.y &&
129
+ labelBox.x + labelBox.width <= canvasBox.x + canvasBox.width &&
130
+ labelBox.y + labelBox.height <= canvasBox.y + canvasBox.height
131
+ );
132
+ }).toBe(true);
133
+ }
134
+
135
+ function buildLightingBundle(lightingTransferVersion = 3, includeReflection = false) {
136
  const pixelCount = WIDTH * HEIGHT;
137
  const pixels = new Uint8Array(pixelCount * 4);
138
  const mask = new Uint32Array(pixelCount);
139
  const shadeMap = new Uint8Array(pixelCount);
140
+ const reflectionMap = new Uint8Array(pixelCount);
141
 
142
  for (let index = 0; index < pixelCount; index += 1) {
143
  const x = index % WIDTH;
 
150
  pixels[pixelIndex + 3] = 255;
151
  mask[index] = index;
152
  shadeMap[index] = Math.round(((shade - 0.08) / (1.85 - 0.08)) * 255);
153
+ reflectionMap[index] = includeReflection && x >= 80 ? 255 : 0;
154
  }
155
 
156
  return {
 
168
  plane: null,
169
  shadeMap: Buffer.from(shadeMap).toString("base64"),
170
  showroomShadeMap: null,
171
+ reflectionMap: includeReflection ? Buffer.from(reflectionMap).toString("base64") : null,
172
  metadata: {
173
  lightingSource: "synthetic-test",
174
+ lightingTransferVersion,
175
  shadeMapEncoding: "linear-relative",
176
  shadeMapRange: [0.08, 1.85],
177
  renderPresetDefaults: {
 
250
  });
251
  }
252
 
253
+ async function renderLightingBundle(
254
+ page: Page,
255
+ lightingTransferVersion: number,
256
+ includeReflection: boolean,
257
+ textureName: string,
258
+ ) {
259
+ await page.goto("/");
260
+ await page.getByTestId("room-file-input").setInputFiles({
261
+ name: `lighting-v${lightingTransferVersion}.vizbundle.json`,
262
+ mimeType: "application/json",
263
+ buffer: Buffer.from(JSON.stringify(buildLightingBundle(lightingTransferVersion, includeReflection))),
264
+ });
265
+ await expect(page.getByTestId("visualizer-editor")).toBeVisible();
266
+ await page.getByTestId("surface-card").click();
267
+ await expect(page.getByTestId("texture-selector")).toBeVisible();
268
+ await page.getByTestId("texture-card").filter({ hasText: textureName }).click();
269
+ await expect(page.getByTestId("texture-selector")).toBeHidden();
270
+ await page.mouse.move(4, 4);
271
+ return readLightingRegions(page);
272
+ }
273
+
274
  async function readLightingRegions(page: Page) {
275
  return page.getByTestId("visualizer-canvas").evaluate((node) => {
276
  const canvas = node as HTMLCanvasElement;
frontend/viz2d-demo/package.json CHANGED
@@ -11,7 +11,13 @@
11
  "qa:e2e": "playwright test",
12
  "qa:e2e:headed": "playwright test --headed",
13
  "qa:report": "node scripts/build-qa-summary.mjs",
14
- "qa:real": "npm run build && playwright test"
 
 
 
 
 
 
15
  },
16
  "dependencies": {
17
  "@radix-ui/react-dialog": "^1.1.15",
 
11
  "qa:e2e": "playwright test",
12
  "qa:e2e:headed": "playwright test --headed",
13
  "qa:report": "node scripts/build-qa-summary.mjs",
14
+ "qa:real": "npm run build && playwright test",
15
+ "hf:dev:check": "bash scripts/hf-stage-dev.sh check",
16
+ "hf:dev:ssh": "bash scripts/hf-stage-dev.sh ssh",
17
+ "hf:dev:tunnel": "bash scripts/hf-stage-dev.sh tunnel",
18
+ "hf:dev:sync": "bash scripts/hf-stage-dev.sh sync",
19
+ "hf:dev:watch": "bash scripts/hf-stage-dev.sh watch",
20
+ "hf:dev:stop": "bash scripts/hf-stage-dev.sh stop"
21
  },
22
  "dependencies": {
23
  "@radix-ui/react-dialog": "^1.1.15",
visualizer.gpu.toml CHANGED
@@ -25,6 +25,8 @@ enable_shading_transfer = true
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = false
27
  warm_start_models = true
 
 
28
  bundle_image_format = "jpeg"
29
  bundle_image_quality = 92
30
  data_dir = "data"
 
25
  enable_sam_refinement = false
26
  enable_floor_mask_cleanup = false
27
  warm_start_models = true
28
+ debug_artifacts_enabled = false
29
+ conversion_target_ms = 30000
30
  bundle_image_format = "jpeg"
31
  bundle_image_quality = 92
32
  data_dir = "data"
visualizer.hf.toml CHANGED
@@ -23,6 +23,8 @@ enable_multi_plane_surfaces = true
23
  enable_intrinsic_shading = true
24
  enable_shading_transfer = true
25
  enable_sam_refinement = true
 
 
26
  data_dir = "data"
27
 
28
  [surface_mapping]
 
23
  enable_intrinsic_shading = true
24
  enable_shading_transfer = true
25
  enable_sam_refinement = true
26
+ debug_artifacts_enabled = false
27
+ conversion_target_ms = 30000
28
  data_dir = "data"
29
 
30
  [surface_mapping]