"""'Enhance with AI' v2 (POST /enhance/room): validation, coverage repair, AI lighting, charging. No models; the AI and the Prevision API are stubbed. python -m unittest test_enhance_room """ import asyncio import importlib import io import json import os import tempfile import time import unittest import zipfile from pathlib import Path from unittest import mock import cv2 import jwt import numpy as np from fastapi import FastAPI, HTTPException from fastapi.testclient import TestClient from PIL import Image SECRET = "test-processing-secret-0123456789abcdef012" W, H = 240, 160 # ADE20K ids used by the synthetic room (state.ADE20K_CLASSES order). WALL, FLOOR, CEILING, PAINTING, CHAIR = 0, 3, 5, 22, 19 def token(issuer="prevision-api", role="client", feat=None, sub="user-1"): now = int(time.time()) claims = {"iss": issuer, "aud": "prevision-processing", "sub": sub, "role": role, "iat": now, "exp": now + 600} if feat is not None: claims["feat"] = feat return jwt.encode(claims, SECRET, algorithm="HS256") def png(array: np.ndarray) -> bytes: buffer = io.BytesIO() Image.fromarray(array).save(buffer, format="PNG") return buffer.getvalue() def pattern(seed=3, colours=((200, 60, 60), (60, 120, 200))) -> np.ndarray: """A busy wallpaper print over the whole frame (what the browser's shader would draw).""" rng = np.random.default_rng(seed) cell = rng.random((12, 12)) > 0.5 tiled = np.tile(cell, (H // 12 + 1, W // 12 + 1))[:H, :W] out = np.zeros((H, W, 3), np.uint8) out[tiled] = colours[0] out[~tiled] = colours[1] return cv2.GaussianBlur(out, (3, 3), 0) class Room: """A two-wall room: ceiling strip, left and right walls, floor, a framed painting and a chair.""" def __init__(self): seg = np.full((H, W), WALL, np.uint8) seg[:20] = CEILING seg[130:] = FLOOR seg[45:85, 40:80] = PAINTING seg[95:130, 150:190] = CHAIR self.seg = seg photo = np.zeros((H, W, 3), np.uint8) photo[:] = (205, 200, 190) # bare wall photo[:, 120:] = (195, 190, 182) # right wall a touch darker photo[:20] = (245, 245, 245) photo[130:] = (120, 90, 60) photo[45:85, 40:80] = (60, 40, 20) photo[50:80, 45:75] = (30, 90, 140) photo[95:130, 150:190] = (40, 40, 45) self.photo = photo wall = seg == WALL protected = np.isin(seg, [CEILING, FLOOR, PAINTING, CHAIR]).astype(np.uint8) # The editor cuts protected classes out with a margin: the halo the repair should fill. halo = cv2.dilate(protected, np.ones((7, 7), np.uint8)).astype(bool) self.left = wall & ~halo self.left[:, 120:] = False self.right = wall & ~halo self.right[:, :120] = False self.floor = seg == FLOOR def write_job(root: Path, job_id: str, room: Room, owner="user-1"): (root / "uploads").mkdir(parents=True, exist_ok=True) (root / "jobs").mkdir(parents=True, exist_ok=True) Image.fromarray(room.photo).save(root / "uploads" / f"{job_id}.jpg", quality=100, subsampling=0) with Image.open(root / "uploads" / f"{job_id}.jpg") as opened: room.photo = np.asarray(opened.convert("RGB")) # what the renderer will read back segments = [] buffer = io.BytesIO() with zipfile.ZipFile(buffer, "w") as archive: for index, (segment_id, name, mask) in enumerate(((0, "floor", room.floor), (1, "wall", room.left), (2, "wall", room.right))): path = f"segments/{index}/mask.bitset" archive.writestr(path, np.packbits(mask.reshape(-1).astype(np.uint8), bitorder="little").tobytes()) segments.append({"id": segment_id, "className": name, "mask": {"path": path, "dtype": "bitset"}}) archive.writestr("metadata.json", json.dumps({"width": W, "height": H, "segments": segments})) (root / "jobs" / f"{job_id}.vizbundle").write_bytes(buffer.getvalue()) np.savez_compressed(root / "jobs" / f"{job_id}.enhance.npz", segMap=room.seg) (root / "jobs" / f"{job_id}.json").write_text(json.dumps({"id": job_id, "status": "COMPLETED", "ownerId": owner})) def support_for(mask: np.ndarray, reach=4) -> np.ndarray: return cv2.dilate(mask.astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * reach + 1, 2 * reach + 1))).astype(bool) def layer_files(layer_id: str, mask: np.ndarray, rgb: np.ndarray, support=None, coverage=None, planes_value=0): support = support_for(mask) if support is None else support coverage = mask if coverage is None else coverage rgba = np.dstack([rgb, (support * 255).astype(np.uint8)]) planes = np.where(support, planes_value, 255).astype(np.uint8) return { f"layer.{layer_id}": png(rgba), f"coverage.{layer_id}": png((coverage * 255).astype(np.uint8)), f"planes.{layer_id}": png(planes), } def manifest(job_id, layers, width=W, height=H): return {"version": 2, "jobId": job_id, "snapshotId": "snap-1", "width": width, "height": height, "layers": layers} def tile(slug="embellence-tulip-garden", mural=False): return {"slug": slug, "name": "Tulip Garden", "imageUrl": None, "widthMm": 530, "heightMm": 530, "mural": mural} def load_modules(data_dir: str): env = { "AUTH_ENFORCEMENT": "on", "PROCESSING_TOKEN_SECRET": SECRET, "GEMINI_API_KEY": "test-key", "VISUALIZER_DATA_DIR": data_dir, "ENHANCE_DEBUG_DIR": "", } with mock.patch.dict(os.environ, env): import config.auth import config.gemini import config.paths import config.runtime import routes.enhance import services.access.policy import services.access.usage import services.enhance.ai import services.enhance.debug_dump import services.enhance.job_context import services.enhance.pipeline import services.gemini.client import services.gemini.enhance import services.jobs.store for module in (config.runtime, config.paths, config.auth, config.gemini, services.access.policy, services.access.usage, services.jobs.store, services.gemini.client, services.gemini.enhance, services.enhance.job_context, services.enhance.ai, services.enhance.debug_dump, services.enhance.pipeline, routes.enhance): importlib.reload(module) return routes.enhance def relit(preview: np.ndarray, gradient=(0.8, 1.05)) -> np.ndarray: """An AI answer: the same picture with a left-to-right light falloff.""" ramp = np.linspace(*gradient, preview.shape[1], dtype=np.float32)[None, :, None] return np.clip(preview.astype(np.float32) * ramp, 0, 255).astype(np.uint8) def jpeg(array: np.ndarray) -> bytes: buffer = io.BytesIO() Image.fromarray(array).save(buffer, format="JPEG", quality=95) return buffer.getvalue() class EnhanceRouteTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.root = Path(self.tmp.name) self.route = load_modules(self.tmp.name) self.route._slots = None app = FastAPI() app.include_router(self.route.router) self.client = TestClient(app) self.room = Room() write_job(self.root, "job1", self.room) self.wallpaper = pattern() self.charge = mock.patch.object(self.route, "charge_free_try", return_value="gen-1").start() self.refund = mock.patch.object(self.route, "refund_free_try").start() self.ai_answer = None self.gemini = mock.patch("services.enhance.ai.call_gemini_image", side_effect=self._gemini).start() self.route.rate_limiter._hits.clear() def tearDown(self): mock.patch.stopall() self.tmp.cleanup() def _gemini(self, images, prompt, **kwargs): # Answer with the corrected preview, relit (decoded from what was sent: padded and downscaled). with Image.open(io.BytesIO(images[0][0])) as sent: preview = np.asarray(sent.convert("RGB")) answer = self.ai_answer(preview) if self.ai_answer else relit(preview) return jpeg(answer), "image/jpeg" def post(self, body, files, auth=None): headers = {"Authorization": f"Bearer {auth or token()}"} multipart = [(name, (name + ".png", data, "image/png")) for name, data in files.items()] return self.client.post("/enhance/room", data={"manifest": json.dumps(body)}, files=multipart, headers=headers) def one_wall(self, **overrides): files = layer_files("L0", self.room.left, self.wallpaper, **overrides) return manifest("job1", [{"id": "L0", "segmentId": 1, "kind": "wall", "tile": tile()}]), files # --- access ----------------------------------------------------------------------------- def test_requires_a_token(self): body, files = self.one_wall() response = self.client.post("/enhance/room", data={"manifest": json.dumps(body)}) self.assertEqual(response.status_code, 401) def test_other_issuers_need_the_feature(self): body, files = self.one_wall() with mock.patch.dict(os.environ, {"TOKEN_ISSUER": "prevision-api"}): response = self.post(body, files, auth=token(issuer="someone-else")) self.assertEqual(response.status_code, 401) # unknown issuer self.charge.assert_not_called() def test_prevision_accounts_are_charged_once(self): body, files = self.one_wall() response = self.post(body, files) self.assertEqual(response.status_code, 200, response.text) payload = response.json() self.assertEqual(payload["snapshotId"], "snap-1") self.assertTrue(payload["charged"]) self.charge.assert_called_once() principal, job_id = self.charge.call_args.args self.assertTrue(job_id.startswith("enh_") and len(job_id) == 36) self.refund.assert_not_called() self.assertEqual(payload["lighting"][0]["status"], "applied") def test_other_users_rooms_are_not_found(self): body, files = self.one_wall() response = self.post(body, files, auth=token(sub="user-2")) self.assertEqual(response.status_code, 404) self.assertEqual(response.json()["detail"]["code"], "JOB_NOT_FOUND") self.charge.assert_not_called() # --- validation: refused, never charged, never sent to the AI --------------------------- def assert_rejected(self, response, code): self.assertEqual(response.status_code, 422, response.text) self.assertEqual(response.json()["detail"]["code"], code) self.charge.assert_not_called() self.gemini.assert_not_called() def test_rejects_wrong_size(self): body, files = self.one_wall() files["layer.L0"] = png(np.zeros((H // 2, W // 2, 4), np.uint8)) self.assert_rejected(self.post(body, files), "SIZE_MISMATCH") def test_rejects_unknown_segment(self): body, files = self.one_wall() body["layers"][0]["segmentId"] = 99 self.assert_rejected(self.post(body, files), "UNKNOWN_SEGMENT") def test_rejects_wrong_kind(self): body, files = self.one_wall() body["layers"][0]["kind"] = "floor" self.assert_rejected(self.post(body, files), "UNKNOWN_SEGMENT") def test_rejects_mismatched_coverage(self): shifted = np.roll(self.room.left, 25, axis=1) body, files = self.one_wall(coverage=shifted) self.assert_rejected(self.post(body, files), "COVERAGE_MISMATCH") def test_rejects_support_beyond_its_surface(self): body, files = self.one_wall(support=np.ones((H, W), bool)) self.assert_rejected(self.post(body, files), "SUPPORT_OUT_OF_BOUNDS") def test_rejects_two_layers_on_one_surface(self): body, files = self.one_wall() files.update(layer_files("L1", self.room.left, self.wallpaper)) body["layers"].append({"id": "L1", "segmentId": 1, "kind": "wall", "tile": tile()}) self.assert_rejected(self.post(body, files), "LAYER_OVERLAP") def test_overlap_the_room_itself_has_is_accepted_but_not_more(self): # The room's own two wall masks share a strip (segmentation often does); the editor shows # the later layer there. A layer reaching beyond that shared strip onto the other is refused. shared = np.zeros((H, W), bool) shared[60:100, 112:128] = True self.room.left = self.room.left | (shared & (self.room.seg == WALL)) self.room.right = self.room.right | (shared & (self.room.seg == WALL)) write_job(self.root, "job2", self.room) body = manifest("job2", [ {"id": "L0", "segmentId": 1, "kind": "wall", "tile": tile()}, {"id": "L1", "segmentId": 2, "kind": "wall", "tile": tile("embellence-dawn-forest-9883w", True)}, ]) files = {**layer_files("L0", self.room.left, self.wallpaper), **layer_files("L1", self.room.right, pattern(seed=5))} self.assertEqual(self.post(body, files).status_code, 200) def test_rejects_a_blank_export(self): body, files = self.one_wall() files = layer_files("L0", self.room.left, np.zeros((H, W, 3), np.uint8)) self.assert_rejected(self.post(body, files), "BAD_LAYER") def test_rejects_an_empty_request(self): self.assert_rejected(self.post(manifest("job1", []), {}), "EMPTY_LAYER") # --- failures after the charge are refunded ---------------------------------------------- def test_ai_failure_is_refunded(self): self.gemini.side_effect = HTTPException(status_code=502, detail="Gemini down") body, files = self.one_wall() response = self.post(body, files) self.assertEqual(response.status_code, 502) self.assertEqual(response.json()["detail"]["code"], "AI_UNAVAILABLE") self.refund.assert_called_once_with("gen-1") def test_an_answer_that_moved_the_room_is_refused_and_refunded(self): self.ai_answer = lambda preview: np.roll(preview, preview.shape[1] // 8, axis=1) body, files = self.one_wall() response = self.post(body, files) self.assertEqual(response.status_code, 422) self.assertEqual(response.json()["detail"]["code"], "LIGHTING_REJECTED") self.assertEqual(self.gemini.call_count, 2) # one strict retry self.refund.assert_called_once_with("gen-1") def test_no_tries_left_passes_the_reason_through(self): self.charge.side_effect = HTTPException(status_code=402, detail="none", headers={"X-Error-Code": "PLAN_LIMIT_REACHED"}) body, files = self.one_wall() response = self.post(body, files) self.assertEqual(response.status_code, 402) self.assertEqual(response.headers["x-error-code"], "PLAN_LIMIT_REACHED") self.gemini.assert_not_called() class PipelineTest(unittest.TestCase): """Pixel-level guarantees, on the pipeline functions directly.""" def setUp(self): self.tmp = tempfile.TemporaryDirectory() load_modules(self.tmp.name) from services.enhance import composite, coverage, job_context, lighting, pipeline, validate self.composite, self.coverage, self.lighting, self.pipeline, self.validate = composite, coverage, lighting, pipeline, validate self.room = Room() write_job(Path(self.tmp.name), "job1", self.room) self.context = job_context.load_job_context("job1") self.wallpaper = pattern() def tearDown(self): self.tmp.cleanup() def layers(self, *specs): body = manifest("job1", [ {"id": layer_id, "segmentId": segment_id, "kind": "wall", "tile": tile()} for layer_id, segment_id, _m, _r in specs ]) files = {} for layer_id, _segment_id, mask, rgb in specs: files.update(layer_files(layer_id, mask, rgb, planes_value=_segment_id)) return self.validate.parse_layers(body, files, self.context) def test_repair_fills_the_halo_up_to_the_frame_but_never_onto_it(self): refined = self.coverage.refine_layers(self.layers(("L0", 1, self.room.left, self.wallpaper)), self.context)[0] painting = self.room.seg == PAINTING ceiling = self.room.seg == CEILING halo = (self.room.seg == WALL) & ~self.room.left & support_for(self.room.left) halo[:, 120:] = False self.assertGreater(refined.repaired[halo].mean(), 0.6) self.assertEqual(refined.alpha[painting].max(), 0.0) self.assertEqual(refined.alpha[ceiling].max(), 0.0) self.assertEqual(refined.alpha[self.room.floor].max(), 0.0) self.assertEqual(refined.alpha[self.room.right].max(), 0.0) # never onto the other wall def test_ambiguous_gaps_stay_the_photo(self): # A dark stain in the halo, labelled wall: it does not look like the bare wall, so it is not papered. self.context.original = self.context.original.copy() self.context.original[86:92, 40:80] = (90, 60, 50) refined = self.coverage.refine_layers(self.layers(("L0", 1, self.room.left, self.wallpaper)), self.context)[0] stain = np.zeros((H, W), bool) stain[86:92, 40:80] = True stain &= ~self.room.left self.assertTrue(stain.any()) self.assertEqual(refined.alpha[stain].max(), 0.0) def test_without_a_class_map_nothing_is_repaired(self): self.context.seg_map = None refined = self.coverage.refine_layers(self.layers(("L0", 1, self.room.left, self.wallpaper)), self.context)[0] self.assertFalse(refined.repaired.any()) def test_ai_pixels_never_reach_the_result(self): layers = self.layers(("L0", 1, self.room.left, self.wallpaper)) prepared = self.pipeline.prepare(self.context, layers) def scrambled(images, prompt, **kwargs): # A hostile answer: the wall's print scrambled and tinted magenta, plus a light falloff. with Image.open(io.BytesIO(images[0][0])) as sent: preview = np.asarray(sent.convert("RGB")).copy() answer = relit(preview).astype(np.int16) noise = np.random.default_rng(1).integers(-12, 12, answer.shape) answer = answer + noise + np.array([18, -10, 18]) return jpeg(np.clip(answer, 0, 255).astype(np.uint8)), "image/jpeg" with mock.patch("services.enhance.ai.call_gemini_image", side_effect=scrambled): result = self.pipeline.finish(prepared, {}) alpha = prepared.refined[0].alpha outside = alpha <= 0 self.assertTrue(np.array_equal(result.final[outside], self.context.original[outside])) inside = alpha > 0.99 interior = cv2.erode(inside.astype(np.uint8), np.ones((15, 15), np.uint8)).astype(bool) # away from the photo def high_pass(image): red = image[..., 0].astype(np.float32) # the print's two colours differ most in red return red - cv2.GaussianBlur(red, (0, 0), 3) a, b = high_pass(result.final)[interior], high_pass(self.wallpaper)[interior] correlation = float(np.corrcoef(a, b)[0, 1]) self.assertGreater(correlation, 0.99) gain = result.lighting[0].gain[inside] self.assertGreaterEqual(gain.min(), self.lighting.MIN_GAIN * self.lighting.MIN_CONTACT - 1e-3) self.assertLessEqual(gain.max(), self.lighting.MAX_GAIN + 1e-3) tint = result.lighting[0].tint self.assertTrue(np.all(np.abs(tint - 1.0) <= self.lighting.MAX_TINT + 1e-6)) def _answer_darkening(self, mask: np.ndarray, factor: float): """An AI stub that darkens only `mask` (image coordinates) in the padded frame it was sent.""" from services.enhance.ai import padding_for, _padded_size pad = padding_for(W, H) def answer(images, prompt, **kwargs): with Image.open(io.BytesIO(images[0][0])) as sent: frame = np.asarray(sent.convert("RGB")).astype(np.float32) full = np.zeros(_padded_size(pad)[::-1], np.float32) full[pad.top: pad.top + H, pad.left: pad.left + W] = mask small = cv2.resize(full, (frame.shape[1], frame.shape[0]), interpolation=cv2.INTER_LINEAR) frame *= 1.0 - (1.0 - factor) * small[..., None] return jpeg(np.clip(frame, 0, 255).astype(np.uint8)), "image/jpeg" return answer def test_light_stays_on_its_own_wall(self): second = pattern(seed=9, colours=((40, 160, 90), (230, 220, 120))) layers = self.layers(("L0", 1, self.room.left, self.wallpaper), ("L1", 2, self.room.right, second)) prepared = self.pipeline.prepare(self.context, layers) left_wall = (prepared.refined[0].alpha > 0.5).astype(np.float32) with mock.patch("services.enhance.ai.call_gemini_image", side_effect=self._answer_darkening(left_wall, 0.8)): result = self.pipeline.finish(prepared, {}) left_gain = result.lighting[0].gain[prepared.refined[0].alpha > 0.99] right_gain = result.lighting[1].gain[prepared.refined[1].alpha > 0.99] self.assertLess(float(np.median(left_gain)), 0.8) self.assertGreater(float(np.median(right_gain)), 0.96) self.assertLess(float(np.median(right_gain)), 1.04) def test_an_answer_that_relights_the_whole_room_side_does_not_relight_only_its_wall(self): # The AI darkened the whole left half (wall, ceiling, floor, frame); the photo keeps its # surroundings, so darkening only the wallpaper would look pasted on. prepared = self.pipeline.prepare(self.context, self.layers(("L0", 1, self.room.left, self.wallpaper))) left_half = np.zeros((H, W), np.float32) left_half[:, : W // 2] = 1.0 with mock.patch("services.enhance.ai.call_gemini_image", side_effect=self._answer_darkening(left_half, 0.8)): result = self.pipeline.finish(prepared, {}) gain = result.lighting[0].gain[prepared.refined[0].alpha > 0.99] # Uncorrected this is a 0.61 gain (0.8 in sRGB). The only untouched reference beside this # wall is a thin ceiling and floor strip, so at least 80% of it must be cancelled. self.assertLess(abs(float(np.median(gain)) - 1.0), 0.08) def test_a_globally_brighter_answer_does_not_brighten_only_the_walls(self): prepared = self.pipeline.prepare(self.context, self.layers(("L0", 1, self.room.left, self.wallpaper))) def brighter(images, prompt, **kwargs): with Image.open(io.BytesIO(images[0][0])) as sent: preview = np.asarray(sent.convert("RGB")).astype(np.float32) return jpeg(np.clip(preview * 1.12, 0, 255).astype(np.uint8)), "image/jpeg" with mock.patch("services.enhance.ai.call_gemini_image", side_effect=brighter): result = self.pipeline.finish(prepared, {}) gain = result.lighting[0].gain[prepared.refined[0].alpha > 0.99] self.assertLess(abs(float(np.median(gain)) - 1.0), 0.04) def test_a_sunbeam_in_the_answer_reaches_the_wall(self): # A crisp band of sunlight must survive as a band, not be clamped or smeared flat. height, width = 320, 480 rng = np.random.default_rng(2) cell = rng.random((10, 10)) > 0.5 tiled = np.tile(cell, (height // 10 + 1, width // 10 + 1))[:height, :width] preview = np.where(tiled[..., None], np.uint8([150, 90, 80]), np.uint8([210, 205, 190])).astype(np.uint8) rows, cols = np.indices((height, width)) beam = (cols - rows > 100) & (cols - rows < 200) answer = preview.astype(np.float32) * 0.9 answer[beam] = preview[beam] * 1.2 answer = np.clip(answer, 0, 255).astype(np.uint8) alpha = np.ones((height, width), np.float32) light = self.lighting.estimate_lighting(preview, answer, preview, alpha, np.zeros((height, width), np.uint8)) inside_beam = beam & (cols - rows > 125) & (cols - rows < 175) shade = (cols - rows < 40) & (cols - rows > -100) ratio = float(np.median(light.gain[inside_beam]) / np.median(light.gain[shade])) self.assertGreater(ratio, 1.4) # (1.2 / 0.9) in sRGB is about 1.9 in linear light def test_registration_accepts_small_shifts_and_refuses_large_ones(self): from services.enhance.ai import LightingRejected, register preview = self.pipeline.prepare(self.context, self.layers(("L0", 1, self.room.left, self.wallpaper))).preview shifted = np.roll(preview, 2, axis=1) aligned = register(shifted, preview) self.assertLess(float(np.abs(aligned[:, 10:-10].astype(int) - preview[:, 10:-10]).mean()), 6.0) with self.assertRaises(LightingRejected): register(np.roll(preview, W // 8, axis=1), preview) def test_padding_round_trips_without_stretching(self): from services.enhance.ai import padding_for, unpad, _padded_jpeg image = self.context.original pad = padding_for(W, H) back = unpad(_padded_jpeg(image, pad, max_side=4096), pad) self.assertEqual(back.shape, image.shape) self.assertLess(float(np.abs(back.astype(int) - image).mean()), 3.0) def test_composite_keeps_the_photo_outside_the_layers(self): alpha = np.zeros((H, W), np.float32) alpha[30:60, 30:60] = 1.0 out = self.composite.composite(self.context.original, [self.wallpaper], [alpha]) self.assertTrue(np.array_equal(out[alpha == 0], self.context.original[alpha == 0])) self.assertTrue(np.allclose(out[alpha == 1].astype(int), self.wallpaper[alpha == 1].astype(int), atol=1)) class WronglyCoveredObjectsTest(unittest.TestCase): """Objects the wall mask includes go back to the photo only when the photo and the AI agree.""" SIZE = (240, 320) def setUp(self): from services.enhance import objects self.objects = objects height, width = self.SIZE rng = np.random.default_rng(5) cell = rng.random((12, 12)) > 0.5 tiled = np.tile(cell, (height // 12 + 1, width // 12 + 1))[:height, :width] self.wallpaper = np.where(tiled[..., None], np.uint8([200, 80, 70]), np.uint8([230, 225, 205])).astype(np.uint8) self.wall = np.full((height, width, 3), (205, 200, 190), np.uint8) self.alpha = np.ones((height, width), np.float32) def mount(self, photo): """A framed photo on the wall: dark frame, pale mount, dark picture.""" out = photo.copy() out[60:140, 180:260] = (40, 35, 30) out[66:134, 186:254] = (238, 236, 230) out[85:115, 205:235] = (50, 60, 70) return out def test_a_mount_the_mask_included_goes_back_to_the_photo(self): original = self.mount(self.wall) answer = self.wallpaper.copy() answer[60:140, 180:260] = original[60:140, 180:260] # the AI kept the mount found, regions = self.objects.wrongly_covered(original, answer, self.wallpaper, self.alpha) self.assertGreaterEqual(regions, 1) self.assertGreater(found[66:134, 186:254].mean(), 0.95) # the mount self.assertGreater(found[62:64, 190:250].mean(), 0.9) # the frame self.assertFalse(found[:, :150].any()) # the wall around it stays papered self.assertFalse(found[:45].any()) def test_a_sunbeam_stays_papered(self): original = self.wall.copy() beam = np.zeros(self.SIZE, bool) rows, cols = np.indices(self.SIZE) beam[(cols - rows > 60) & (cols - rows < 140)] = True original[beam] = (250, 245, 232) answer = self.wallpaper.copy() answer[beam] = np.clip(answer[beam].astype(int) * 1.3, 0, 255).astype(np.uint8) # the AI lit the print found, regions = self.objects.wrongly_covered(original, answer, self.wallpaper, self.alpha) self.assertEqual(regions, 0) self.assertFalse(found.any()) def test_an_object_only_the_ai_drew_is_not_trusted(self): answer = self.mount(self.wallpaper) # the photo has a bare wall there found, _ = self.objects.wrongly_covered(self.wall, answer, self.wallpaper, self.alpha) self.assertFalse(found.any()) def test_an_object_the_ai_dropped_the_print_on_is_kept_if_the_ai_did_not_show_it(self): original = self.mount(self.wall) answer = self.wallpaper.copy() answer[60:140, 180:260] = (215, 210, 200) # print gone, but no mount either: not enough evidence found, _ = self.objects.wrongly_covered(original, answer, self.wallpaper, self.alpha) self.assertFalse(found[66:134, 186:254].any()) def test_giving_back_never_adds_coverage(self): found = np.zeros(self.SIZE, bool) found[50:60, 50:60] = True alpha = self.alpha * 0.5 out = self.objects.give_back(alpha, found) self.assertTrue((out <= alpha + 1e-6).all()) self.assertEqual(float(out[50:60, 50:60].max()), 0.0) class ReferenceHostsTest(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() load_modules(self.tmp.name) import services.gemini.enhance as enhance self.enhance = enhance def tearDown(self): self.tmp.cleanup() def test_embellence_cdn_is_allowed(self): url = ("https://baetes-visualizer.fra1.cdn.digitaloceanspaces.com/tiles/embellence-group/" "embellence-tulip-garden/image-adc0e39ce301309f.jpg") self.assertTrue(self.enhance.reference_allowed(url)) self.assertFalse(self.enhance.reference_allowed(url.replace("https://", "http://"))) self.assertFalse(self.enhance.reference_allowed("https://baetes-visualizer.fra1.cdn.digitaloceanspaces.com.evil.test/x.jpg")) def test_redirects_off_the_cdn_are_refused(self): import urllib.error handler = self.enhance._AllowlistedRedirects() request = mock.Mock() with self.assertRaises(urllib.error.HTTPError): handler.redirect_request(request, None, 302, "Found", {}, "https://169.254.169.254/latest/meta-data") class ConversionContextTest(unittest.TestCase): def test_class_map_is_saved_beside_the_bundle(self): with tempfile.TemporaryDirectory() as tmp: load_modules(tmp) from services.enhance import job_context seg = np.random.default_rng(0).integers(0, 150, (H, W)).astype(np.uint8) job_context.save_enhance_context("abc", seg) with np.load(job_context.enhance_context_path("abc")) as saved: self.assertTrue(np.array_equal(saved["segMap"], seg)) if __name__ == "__main__": unittest.main()