feat: initial make-space full-stack release with weighted multi-provider LLM and Dockerfile

This commit is contained in:
dahyeon committed 2026-11-04 20:49:24 +09:00
commit 37b323c9ac
55 files changed
+17087

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
/target
/.env
/.gemini
.git
node_modules
+27
View File
@@ -0,0 +1,27 @@
# --- Place search ---
KAKAO_REST_API_KEY=
X_NCP_APIGW_API_KEY_ID=
X_NCP_APIGW_API_KEY=
# --- Storage ---
MONGODB_CONNECTION_STRING=mongodb://localhost:27017
MONGODB_DB=make_space
MINIO_ENDPOINT=http://localhost:9000
MINIO_ACCESS_KEY=
MINIO_SECRET_KEY=
MINIO_BUCKET=make-space-photos
# --- LLM (OpenAI-compatible, weighted multi-provider or single-provider fallback) ---
# JSON array of capacity providers (`PROVIDER`: "strata" | "cpa", `OPENAI_COMPATIBLE_API_ENDPOINT`, `OPENAI_COMPATIBLE_API_KEY`, `MODEL`, `WEIGHT`):
# LLM_PROVIDERS='[{"PROVIDER":"strata","OPENAI_COMPATIBLE_API_ENDPOINT":"http://127.0.0.1:8080","OPENAI_COMPATIBLE_API_KEY":"","MODEL":"qwen3.8-flash-next","WEIGHT":2},{"PROVIDER":"cpa","OPENAI_COMPATIBLE_API_ENDPOINT":"http://126.dahyeon.us:8317","OPENAI_COMPATIBLE_API_KEY":"","MODEL":"gpt-6.1-sol","WEIGHT":1}]'
OPENAI_COMPATIBLE_API_ENDPOINT=
OPENAI_COMPATIBLE_API_KEY=
LLM_MODEL=gpt-6.1-sol
# --- External browser scraping service (empty = mock) ---
BROWSER_SCRAPER_URL=
# --- Pipeline tuning ---
MAX_PHOTOS_PER_SOURCE=40
MAX_PHOTOS_TOTAL=120
RUST_LOG=info,server=debug,pipeline=debug,providers=debug
+4
View File
@@ -0,0 +1,4 @@
/target
.env
*.log
/data
Generated
+5005
View File
File diff suppressed because it is too large. Load diff
+94
View File
@@ -0,0 +1,94 @@
[workspace]
resolver = "2"
members = [
"app",
"frontend",
"server",
"crates/domain",
"crates/llm",
"crates/providers",
"crates/storage",
"crates/pipeline",
]
[workspace.package]
edition = "2021"
version = "0.1.0"
[workspace.dependencies]
# web
leptos = "0.8"
leptos_meta = "0.8"
leptos_router = "0.8"
leptos_axum = "0.8"
axum = "0.8"
tower-http = { version = "0.6", features = ["fs"] }
wasm-bindgen = "0.2"
web-sys = "0.3"
js-sys = "0.3"
console_error_panic_hook = "0.1"
# async / runtime
tokio = { version = "1", features = ["full"] }
tokio-stream = { version = "0.1", features = ["sync"] }
futures = "0.3"
async-trait = "0.1"
# data
serde = { version = "1", features = ["derive"] }
serde_json = "1"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4"] }
# infra
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "gzip", "brotli", "deflate", "cookies"] }
scraper = "0.24"
regex = "1"
url = "2"
urlencoding = "2"
mongodb = "3"
object_store = { version = "0.12", features = ["aws"] }
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif"] }
base64 = "0.22"
bytes = "1"
dashmap = "6"
# errors / logging / config
anyhow = "1"
thiserror = "2"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
dotenvy = "0.15"
# internal
domain = { path = "crates/domain" }
llm = { path = "crates/llm" }
providers = { path = "crates/providers" }
storage = { path = "crates/storage" }
pipeline = { path = "crates/pipeline" }
app = { path = "app", default-features = false }
[profile.wasm-release]
inherits = "release"
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
[[workspace.metadata.leptos]]
name = "make-space"
bin-package = "server"
bin-target = "server"
lib-package = "frontend"
site-root = "target/site"
site-pkg-dir = "pkg"
style-file = "style/main.css"
assets-dir = "public"
site-addr = "127.0.0.1:3000"
reload-port = 3001
browserquery = "defaults"
bin-features = []
bin-default-features = false
lib-features = []
lib-default-features = false
lib-profile-release = "wasm-release"
+43
View File
@@ -0,0 +1,43 @@
FROM rust:1.99.1-trixie AS rust-build
WORKDIR /src
# Install wasm32 target and pinned wasm-bindgen-cli matching Cargo.lock (0.2.130)
RUN rustup target add wasm32-unknown-unknown \
&& cargo install wasm-bindgen-cli --version 0.2.130 --locked
COPY Cargo.toml Cargo.lock ./
COPY app ./app
COPY frontend ./frontend
COPY server ./server
COPY crates ./crates
COPY style ./style
COPY public ./public
# 1. Build Axum SSR server binary
RUN cargo build --release --locked --bin server
# 2. Build Leptos WASM hydrate bundle and assemble /src/target/site
RUN cargo build --profile wasm-release --locked --target wasm32-unknown-unknown -p frontend \
&& mkdir -p /src/target/site/pkg \
&& wasm-bindgen /src/target/wasm32-unknown-unknown/wasm-release/frontend.wasm \
--out-dir /src/target/site/pkg \
--out-name make-space \
--target web \
&& cp /src/target/site/pkg/make-space_bg.wasm /src/target/site/pkg/make-space.wasm \
&& cp /src/style/main.css /src/target/site/pkg/make-space.css \
&& cp -r /src/public/. /src/target/site/
FROM gcr.io/distroless/cc-debian13:nonroot AS runtime
ENV APP_ENV=production \
HOST=0.0.0.0 \
PORT=3000 \
LEPTOS_OUTPUT_NAME=make-space \
LEPTOS_SITE_ADDR=0.0.0.0:3000 \
LEPTOS_SITE_ROOT=/app/site \
LEPTOS_SITE_PKG_DIR=pkg
WORKDIR /app
COPY --from=rust-build --chown=65532:65532 /src/target/release/server /app/make-space
COPY --from=rust-build --chown=65532:65532 /src/target/site /app/site
USER 65532:65532
EXPOSE 3000
ENTRYPOINT ["/app/make-space"]
+41
View File
@@ -0,0 +1,41 @@
[package]
name = "app"
edition.workspace = true
version.workspace = true
[lib]
crate-type = ["rlib"]
[dependencies]
domain = { workspace = true }
leptos = { workspace = true }
leptos_meta = { workspace = true }
leptos_router = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
# hydrate-only
wasm-bindgen = { workspace = true, optional = true }
js-sys = { workspace = true, optional = true }
web-sys = { workspace = true, optional = true, features = ["EventSource", "MessageEvent", "HtmlCanvasElement", "Event"] }
# ssr-only
leptos_axum = { workspace = true, optional = true }
pipeline = { workspace = true, optional = true }
storage = { workspace = true, optional = true }
providers = { workspace = true, optional = true }
tracing = { workspace = true, optional = true }
[features]
default = []
hydrate = ["leptos/hydrate", "dep:wasm-bindgen", "dep:js-sys", "dep:web-sys"]
ssr = [
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
"dep:leptos_axum",
"dep:pipeline",
"dep:storage",
"dep:providers",
"dep:tracing",
]
+787
View File
@@ -0,0 +1,787 @@
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const FLOOR_HEIGHT = 3.6;
const WALL_HEIGHT = 2.6;
const WALL_THICK = 0.16;
// sRGB equivalents of the Aurora light canvas and blue action palette.
const SCENE_COLORS = {
background: 0xeff0f2,
gridMajor: 0xd6d9df,
gridMinor: 0xe3e5e9,
accent: 0x235cc7,
};
const ZONE_COLORS = {
seating: 0xe8dfd1,
counter: 0xd4a373,
bar: 0xc89f81,
kitchen: 0xb7b7a4,
restroom: 0xa8dadc,
terrace: 0xccd5ae,
entrance: 0xf4e285,
other: 0xdedbd2,
};
const scenes = new Map();
let nextId = 1;
function floorIndex(floors, level) {
const sorted = [...floors].sort((a, b) => a.level - b.level);
const idx = sorted.findIndex((f) => f.level === level);
return idx >= 0 ? idx : 0;
}
function createScene(canvas, layoutJson, onZoneSelect, cleanup) {
const layout = JSON.parse(layoutJson);
if (!layout || !Array.isArray(layout.floors)) throw new Error("Invalid floor layout");
const coarsePointer = window.matchMedia("(pointer: coarse)");
const originalTouchAction = canvas.style.touchAction;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
cleanup.push(() => renderer.dispose());
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(SCENE_COLORS.background, 1);
const scene = new THREE.Scene();
cleanup.push(() => disposeSceneObjects(scene));
scene.fog = new THREE.FogExp2(SCENE_COLORS.background, 0.015);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
const controls = new OrbitControls(camera, canvas);
cleanup.push(() => { controls.dispose(); canvas.style.touchAction = originalTouchAction; });
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
controls.enableDamping = !reducedMotion.matches;
controls.dampingFactor = 0.08;
controls.maxPolarAngle = Math.PI * 0.48;
const hemi = new THREE.HemisphereLight(0xffffff, 0xaab0ba, 1.05);
scene.add(hemi);
const dir = new THREE.DirectionalLight(0xffffff, 1.25);
dir.position.set(16, 28, 18);
dir.castShadow = true;
dir.shadow.mapSize.set(2048, 2048);
dir.shadow.camera.near = 1;
dir.shadow.camera.far = 90;
const d = 24;
dir.shadow.camera.left = -d;
dir.shadow.camera.right = d;
dir.shadow.camera.top = d;
dir.shadow.camera.bottom = -d;
scene.add(dir);
const groundGrid = new THREE.GridHelper(60, 60, SCENE_COLORS.gridMajor, SCENE_COLORS.gridMinor);
groundGrid.position.y = -0.08;
scene.add(groundGrid);
const floorGroups = new Map();
const pinMeshes = [];
const floors = layout.floors || [];
floors.forEach((floor) => {
const idx = floorIndex(floors, floor.level);
const yBase = idx * FLOOR_HEIGHT;
const group = buildFloorGroup(floor, yBase, pinMeshes);
scene.add(group);
floorGroups.set(floor.level, { group, yBase, floor });
});
const maxW = Math.max(10, ...floors.map((f) => f.width_m || 10));
const maxD = Math.max(10, ...floors.map((f) => f.depth_m || 10));
const span = Math.max(maxW, maxD);
camera.position.set(span * 1.15, span * 1.05, span * 1.25);
controls.target.set(0, (floors.length - 1) * FLOOR_HEIGHT * 0.35, 0);
controls.update();
let hasSize = false;
let visible = true;
let contextLost = false;
let disposed = false;
let raf = 0;
let st;
const requestFrame = () => {
if (!disposed && !contextLost && !document.hidden && visible && hasSize && !raf) {
raf = requestAnimationFrame(animate);
}
};
let pixelRatio = 0;
const resize = () => {
const rect = canvas.getBoundingClientRect();
const w = rect.width;
const h = rect.height;
hasSize = w > 0 && h > 0;
if (!hasSize) return;
const nextPixelRatio = Math.min(window.devicePixelRatio || 1, coarsePointer.matches ? 1.5 : 2);
if (nextPixelRatio !== pixelRatio) {
renderer.setPixelRatio(nextPixelRatio);
pixelRatio = nextPixelRatio;
}
renderer.setSize(w, h, false);
camera.aspect = w / h;
// Leave room around the model on portrait and near-square phone viewports.
camera.fov = (2 * Math.atan(Math.tan((42 * Math.PI) / 360) / Math.min(1, camera.aspect / 1.15)) * 180) / Math.PI;
camera.updateProjectionMatrix();
requestFrame();
};
resize();
const ro = new ResizeObserver(resize);
cleanup.push(() => ro.disconnect());
ro.observe(canvas);
window.addEventListener("resize", resize);
cleanup.push(() => window.removeEventListener("resize", resize));
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const activePointers = new Set();
let downPos = null;
const syncInteraction = () => {
downPos = null;
controls.enabled = !coarsePointer.matches || canvas.dataset.interactive === "true";
// OrbitControls sets this to "none" in its constructor, so apply the page-scroll mode afterward.
canvas.style.touchAction = controls.enabled ? "none" : "pan-y";
};
syncInteraction();
const interactionObserver = new MutationObserver(syncInteraction);
cleanup.push(() => interactionObserver.disconnect());
interactionObserver.observe(canvas, { attributes: true, attributeFilter: ["data-interactive"] });
const onPointerModeChange = () => {
syncInteraction();
resize();
};
coarsePointer.addEventListener("change", onPointerModeChange);
cleanup.push(() => coarsePointer.removeEventListener("change", onPointerModeChange));
const onActivePointerDown = (e) => {
activePointers.add(e.pointerId);
if (activePointers.size > 1) downPos = null;
};
const onPointerDown = (e) => {
activePointers.add(e.pointerId);
// Pins remain tappable in page-scroll mode; only orbit gestures require opt-in.
if (activePointers.size !== 1 || e.isPrimary === false || e.button !== 0) {
downPos = null;
return;
}
downPos = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, at: performance.now() };
};
const onPointerMove = (e) => {
if (downPos?.pointerId === e.pointerId && Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y) > 6) {
downPos = null;
}
};
const onPointerUp = (e) => {
const wasOnlyPointer = activePointers.size === 1 && activePointers.has(e.pointerId);
activePointers.delete(e.pointerId);
const tap = downPos;
downPos = null;
if (!wasOnlyPointer || tap?.pointerId !== e.pointerId || performance.now() - tap.at > 800) return;
if (Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 6) return;
const rect = canvas.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const selectablePins = pinMeshes.filter((pin) => {
if (st.activeLevel !== 0 && pin.userData.floorLevel !== st.activeLevel) return false;
for (let parent = pin; parent; parent = parent.parent) {
if (!parent.visible) return false;
}
return true;
});
const hits = raycaster.intersectObjects(selectablePins, true);
let obj = hits[0]?.object;
// The decorative pin is small; use a 44px minimum tap target around its visible center.
if (!obj) {
let distance = 22;
const projected = new THREE.Vector3();
for (const pin of selectablePins) {
pin.getWorldPosition(projected);
projected.project(camera);
if (projected.z < -1 || projected.z > 1) continue;
const x = rect.left + (projected.x + 1) * rect.width / 2;
const y = rect.top + (1 - projected.y) * rect.height / 2;
const candidateDistance = Math.hypot(e.clientX - x, e.clientY - y);
if (candidateDistance < distance) {
distance = candidateDistance;
obj = pin;
}
}
}
if (obj) {
while (obj && !obj.userData?.photoIds) {
obj = obj.parent;
}
if (obj && obj.userData?.photoIds && typeof onZoneSelect === "function") {
highlightZone(st.id, obj.userData.zoneLabel, JSON.stringify(obj.userData.photoIds));
onZoneSelect(obj.userData.zoneLabel || "구역", JSON.stringify(obj.userData.photoIds));
}
}
};
const onPointerCancel = (e) => {
activePointers.delete(e.pointerId);
downPos = null;
};
canvas.addEventListener("pointerdown", onPointerDown);
window.addEventListener("pointerdown", onActivePointerDown, true);
window.addEventListener("pointermove", onPointerMove, true);
canvas.addEventListener("lostpointercapture", onPointerCancel);
// Capture release/cancel even when a scrolling or dragged pointer leaves the canvas.
window.addEventListener("pointerup", onPointerUp, true);
window.addEventListener("pointercancel", onPointerCancel, true);
cleanup.push(() => {
canvas.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("pointerdown", onActivePointerDown, true);
window.removeEventListener("pointermove", onPointerMove, true);
canvas.removeEventListener("lostpointercapture", onPointerCancel);
window.removeEventListener("pointerup", onPointerUp, true);
window.removeEventListener("pointercancel", onPointerCancel, true);
});
function animate() {
raf = 0;
if (disposed || contextLost || document.hidden || !visible || !hasSize) return;
const t = performance.now() / 1000;
pinMeshes.forEach((pin, i) => {
pin.position.y = pin.userData.baseY + (reducedMotion.matches ? 0 : Math.sin(t * 2.6 + i) * 0.08);
pin.rotation.y = reducedMotion.matches ? 0 : t * 1.1 + i;
});
controls.update();
renderer.render(scene, camera);
if (!reducedMotion.matches) requestFrame();
}
const stopFrame = () => {
cancelAnimationFrame(raf);
raf = 0;
};
const onVisibilityChange = () => document.hidden ? stopFrame() : requestFrame();
document.addEventListener("visibilitychange", onVisibilityChange);
cleanup.push(() => { disposed = true; stopFrame(); document.removeEventListener("visibilitychange", onVisibilityChange); });
const intersectionObserver = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
visible ? requestFrame() : stopFrame();
});
intersectionObserver.observe(canvas);
cleanup.push(() => intersectionObserver.disconnect());
const onMotionChange = () => {
controls.enableDamping = !reducedMotion.matches;
requestFrame();
};
reducedMotion.addEventListener("change", onMotionChange);
controls.addEventListener("change", requestFrame);
cleanup.push(() => { reducedMotion.removeEventListener("change", onMotionChange); controls.removeEventListener("change", requestFrame); });
const onContextLost = (event) => {
event.preventDefault();
contextLost = true;
stopFrame();
reportSceneState(canvas, "공간 화면이 중단됐습니다. 잠시 후 다시 시도해 주세요.");
};
const onContextRestored = () => {
contextLost = false;
resize();
requestFrame();
reportSceneState(canvas, null);
};
canvas.addEventListener("webglcontextlost", onContextLost);
canvas.addEventListener("webglcontextrestored", onContextRestored);
cleanup.push(() => { canvas.removeEventListener("webglcontextlost", onContextLost); canvas.removeEventListener("webglcontextrestored", onContextRestored); });
const id = nextId++;
st = {
id,
renderer,
scene,
camera,
controls,
floorGroups,
pinMeshes,
ro,
interactionObserver,
coarsePointer,
onPointerModeChange,
resize,
requestFrame,
reducedMotion,
onMotionChange,
intersectionObserver,
onVisibilityChange,
onContextLost,
onContextRestored,
stopAnimation: () => {
disposed = true;
stopFrame();
},
canvas,
originalTouchAction,
onPointerDown,
onActivePointerDown,
onPointerMove,
onPointerUp,
onPointerCancel,
span,
activeLevel: 0,
viewMode: "3d",
};
scenes.set(id, st);
resetScene(id);
reportSceneState(canvas, null);
requestFrame();
return id;
}
function reportSceneState(canvas, message) {
canvas.dataset.sceneError = message || "";
canvas.dispatchEvent(new Event(message ? "scene-error" : "scene-ready", { bubbles: true }));
}
export function mountScene(canvas, layoutJson, onZoneSelect) {
const cleanup = [];
try {
return createScene(canvas, layoutJson, onZoneSelect, cleanup);
} catch (error) {
cleanup.reverse().forEach((dispose) => { try { dispose(); } catch { /* Finish the remaining cleanup. */ } });
console.warn("Space viewer could not start", error?.message);
reportSceneState(canvas, "공간 화면을 열 수 없습니다. 아래 정보와 사진을 확인하거나 다시 시도해 주세요.");
return 0;
}
}
export function setFloor(handle, level) {
const st = scenes.get(handle);
if (!st) return;
if (level !== 0 && !st.floorGroups.has(level)) return;
const previousY = floorTarget(st);
st.activeLevel = level;
const offsetY = floorTarget(st) - previousY;
st.camera.position.y += offsetY;
st.controls.target.y += offsetY;
st.floorGroups.forEach(({ group, yBase }, fLevel) => {
if (level === 0) {
group.visible = true;
setGroupOpacity(group, 1.0);
} else if (fLevel === level) {
group.visible = true;
setGroupOpacity(group, 1.0);
} else if (fLevel < level) {
group.visible = st.viewMode !== "plan";
setGroupOpacity(group, 0.18);
} else {
group.visible = false;
}
});
st.controls.update();
st.requestFrame();
}
function floorTarget(st) {
return st.floorGroups.get(st.activeLevel)?.yBase ?? Math.max(0, st.floorGroups.size - 1) * FLOOR_HEIGHT * 0.35;
}
export function setViewMode(handle, mode) {
const st = scenes.get(handle);
if (!st) return;
st.viewMode = mode === "plan" ? "plan" : "3d";
const plan = st.viewMode === "plan";
st.controls.enableRotate = !plan;
st.controls.minPolarAngle = 0;
st.controls.maxPolarAngle = plan ? 0 : Math.PI * 0.48;
st.controls.screenSpacePanning = true;
st.controls.mouseButtons.LEFT = plan ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE;
st.controls.touches.ONE = plan ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE;
st.controls.touches.TWO = THREE.TOUCH.DOLLY_PAN;
setFloor(handle, st.activeLevel);
resetScene(handle);
}
export function resetScene(handle) {
const st = scenes.get(handle);
if (!st) return;
const yTarget = floorTarget(st);
const s = st.span;
// Flush accumulated damping so reset and view changes do not inherit a prior gesture.
const damping = st.controls.enableDamping;
st.controls.enableDamping = false;
st.controls.update();
st.controls.enableDamping = damping;
st.controls.minDistance = Math.max(2, s * 0.18);
st.controls.maxDistance = s * 5;
if (st.viewMode === "plan") {
st.camera.position.set(0, yTarget + s * 1.65, 0.01);
st.controls.target.set(0, yTarget, 0);
} else {
st.camera.position.set(s * 1.15, yTarget + s * 1.0, s * 1.25);
st.controls.target.set(0, yTarget + 0.4, 0);
}
st.controls.update();
st.requestFrame();
}
export function zoomScene(handle, delta) {
const st = scenes.get(handle);
if (!st || !Number.isFinite(delta)) return;
const offset = st.camera.position.clone().sub(st.controls.target);
const distance = THREE.MathUtils.clamp(offset.length() * Math.exp(-delta * 0.18), st.controls.minDistance, st.controls.maxDistance);
st.camera.position.copy(st.controls.target).add(offset.setLength(distance));
st.controls.update();
st.requestFrame();
}
export function highlightZone(handle, label, photoIdsJson) {
const st = scenes.get(handle);
if (!st) return;
let photoIds = [];
try { photoIds = JSON.parse(photoIdsJson); } catch { /* An empty selection simply clears emphasis. */ }
st.scene.traverse((obj) => {
if (!obj.userData.zoneSurface) return;
const selected = Boolean(label) && obj.userData.zoneLabel === label &&
(!photoIds.length || obj.userData.photoIds.some((id) => photoIds.includes(id)));
obj.material.emissive.setHex(selected ? SCENE_COLORS.accent : 0x000000);
obj.material.emissiveIntensity = selected ? 0.23 : 0;
});
st.pinMeshes.forEach((pin) => {
const selected = Boolean(label) && pin.userData.zoneLabel === label &&
(!photoIds.length || pin.userData.photoIds.some((id) => photoIds.includes(id)));
pin.scale.setScalar(selected ? 1.4 : 1);
});
st.requestFrame();
}
export function disposeScene(handle) {
const st = scenes.get(handle);
if (!st) return;
st.stopAnimation();
st.ro.disconnect();
st.intersectionObserver.disconnect();
st.interactionObserver.disconnect();
st.coarsePointer.removeEventListener("change", st.onPointerModeChange);
st.reducedMotion.removeEventListener("change", st.onMotionChange);
document.removeEventListener("visibilitychange", st.onVisibilityChange);
window.removeEventListener("resize", st.resize);
st.canvas.removeEventListener("pointerdown", st.onPointerDown);
window.removeEventListener("pointerdown", st.onActivePointerDown, true);
window.removeEventListener("pointermove", st.onPointerMove, true);
st.canvas.removeEventListener("lostpointercapture", st.onPointerCancel);
window.removeEventListener("pointerup", st.onPointerUp, true);
window.removeEventListener("pointercancel", st.onPointerCancel, true);
st.canvas.removeEventListener("webglcontextlost", st.onContextLost);
st.canvas.removeEventListener("webglcontextrestored", st.onContextRestored);
st.controls.removeEventListener("change", st.requestFrame);
st.controls.dispose();
st.canvas.style.touchAction = st.originalTouchAction;
disposeSceneObjects(st.scene);
st.renderer.dispose();
scenes.delete(handle);
}
function disposeSceneObjects(scene) {
const geometries = new Set();
const materials = new Set();
scene.traverse((obj) => {
if (obj.geometry) geometries.add(obj.geometry);
if (obj.material) (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach((m) => materials.add(m));
if (obj.shadow) obj.shadow.dispose();
});
geometries.forEach((geometry) => geometry.dispose());
materials.forEach((material) => material.dispose());
}
function setGroupOpacity(group, opacity) {
group.traverse((obj) => {
if (obj.isMesh && obj.material) {
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
mats.forEach((m) => {
if (m.userData.baseOpacity === undefined) {
m.userData.baseOpacity = m.opacity ?? 1.0;
m.userData.wasTransparent = m.transparent ?? false;
}
if (opacity < 0.99) {
m.transparent = true;
m.opacity = m.userData.baseOpacity * opacity;
} else {
m.transparent = m.userData.wasTransparent;
m.opacity = m.userData.baseOpacity;
}
});
}
});
}
// Convert floor local (x east 0..W, y north 0..D) into Three.js world (x east -W/2..W/2, z south -D/2..D/2)
// Note: local y=0 is SOUTH (front/entrance), which maps to z = +D/2 in Three.js so south faces the viewer.
function toWorldXZ(floor, lx, ly) {
return [lx - floor.width_m / 2, floor.depth_m / 2 - ly];
}
function buildFloorGroup(floor, yBase, pinMeshes) {
const group = new THREE.Group();
group.position.y = yBase;
const W = floor.width_m || 10;
const D = floor.depth_m || 10;
// Floor slab
const slabGeo = new THREE.BoxGeometry(W, 0.14, D);
const slabMat = new THREE.MeshStandardMaterial({ color: 0xf3ede2, roughness: 0.85 });
const slab = new THREE.Mesh(slabGeo, slabMat);
slab.position.y = -0.07;
slab.receiveShadow = true;
group.add(slab);
// Subtle perimeter walls (low cutaway height on South/East so interior is easy to see)
buildWalls(group, floor);
// Zones + furniture + pins
(floor.zones || []).forEach((zone) => {
const zg = buildZone(floor, zone, pinMeshes);
group.add(zg);
});
// Verticals (stairs / elevator)
(floor.verticals || []).forEach((v) => {
group.add(buildVertical(floor, v));
});
return group;
}
function buildWalls(group, floor) {
const W = floor.width_m;
const D = floor.depth_m;
const wallMat = new THREE.MeshStandardMaterial({ color: 0xd8d2c5, roughness: 0.75 });
const glassMat = new THREE.MeshStandardMaterial({
color: 0x8ecae6,
transparent: true,
opacity: 0.32,
roughness: 0.2,
});
const doorMat = new THREE.MeshStandardMaterial({ color: 0xe76f51, roughness: 0.6 });
// Back walls (North & West) full height; front walls (South & East) cutaway 0.9m so camera sees inside
const north = new THREE.Mesh(new THREE.BoxGeometry(W, WALL_HEIGHT, WALL_THICK), wallMat.clone());
north.position.set(0, WALL_HEIGHT / 2, -D / 2);
north.castShadow = true;
group.add(north);
const west = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, WALL_HEIGHT, D), wallMat.clone());
west.position.set(-W / 2, WALL_HEIGHT / 2, 0);
west.castShadow = true;
group.add(west);
const lowH = 0.65;
const south = new THREE.Mesh(new THREE.BoxGeometry(W, lowH, WALL_THICK), wallMat.clone());
south.position.set(0, lowH / 2, D / 2);
group.add(south);
const east = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, lowH, D), wallMat.clone());
east.position.set(W / 2, lowH / 2, 0);
group.add(east);
// Render openings (windows as glass panels, entrances as welcome mats + arch)
(floor.openings || []).forEach((op) => {
const len = Math.max(0.9, op.length_m || 1.5);
const off = op.offset_m || 1.0;
const isWindow = op.kind === "window";
const h = isWindow ? 1.5 : 2.1;
const yCenter = isWindow ? 1.3 : h / 2;
const mat = isWindow ? glassMat.clone() : doorMat.clone();
let mesh;
if (op.wall === "south" || op.wall === "north") {
mesh = new THREE.Mesh(new THREE.BoxGeometry(len, h, WALL_THICK * 1.3), mat);
const x = -W / 2 + off + len / 2;
const z = op.wall === "south" ? D / 2 : -D / 2;
mesh.position.set(x, yCenter, z);
} else {
mesh = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK * 1.3, h, len), mat);
const z = D / 2 - (off + len / 2);
const x = op.wall === "east" ? W / 2 : -W / 2;
mesh.position.set(x, yCenter, z);
}
group.add(mesh);
});
}
function buildZone(floor, zone, pinMeshes) {
const g = new THREE.Group();
const [wx, wz] = toWorldXZ(floor, zone.x + zone.w / 2, zone.y + zone.d / 2);
g.position.set(wx, 0.02, wz);
const color = ZONE_COLORS[zone.kind] || ZONE_COLORS.other;
const pad = new THREE.Mesh(
new THREE.BoxGeometry(Math.max(0.8, zone.w - 0.12), 0.04, Math.max(0.8, zone.d - 0.12)),
new THREE.MeshStandardMaterial({ color, roughness: 0.9 })
);
pad.receiveShadow = true;
pad.userData = { zoneSurface: true, zoneLabel: zone.label || zone.kind, photoIds: zone.evidence_photos || [] };
g.add(pad);
// Place furniture groups inside the zone
(zone.furniture || []).forEach((fg) => {
populateFurniture(g, zone.w, zone.d, fg);
});
// If this zone has evidence photos, place a glowing interactive pin above it
if (zone.evidence_photos && zone.evidence_photos.length > 0) {
const pin = buildPin(zone.label || zone.kind, zone.evidence_photos);
pin.position.set(0, 1.65, 0);
pin.userData.baseY = 1.65;
pin.userData.floorLevel = floor.level;
g.add(pin);
pinMeshes.push(pin);
}
return g;
}
function populateFurniture(zoneGroup, zw, zd, fg) {
const count = Math.min(24, Math.max(1, fg.count || 1));
const cols = Math.max(1, Math.ceil(Math.sqrt(count * (zw / Math.max(1, zd)))));
const rows = Math.max(1, Math.ceil(count / cols));
const cellW = (zw * 0.82) / cols;
const cellD = (zd * 0.82) / rows;
for (let i = 0; i < count; i++) {
const r = Math.floor(i / cols);
const c = i % cols;
const x = -zw * 0.41 + (c + 0.5) * cellW;
const z = -zd * 0.41 + (r + 0.5) * cellD;
const item = buildFurnitureMesh(fg.kind, cellW, cellD);
item.position.set(x, 0.02, z);
zoneGroup.add(item);
}
}
function buildFurnitureMesh(kind, cellW, cellD) {
const g = new THREE.Group();
const wood = new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.7 });
const darkWood = new THREE.MeshStandardMaterial({ color: 0x5c3d28, roughness: 0.75 });
const chairMat = new THREE.MeshStandardMaterial({ color: 0x3d405b, roughness: 0.8 });
const sofaMat = new THREE.MeshStandardMaterial({ color: 0x6b705c, roughness: 0.85 });
const metal = new THREE.MeshStandardMaterial({ color: 0xadb5bd, metalness: 0.5, roughness: 0.4 });
const leaf = new THREE.MeshStandardMaterial({ color: 0x52b788, roughness: 0.8 });
if (kind === "counter_bar") {
const w = Math.min(2.6, Math.max(1.2, cellW * 0.9));
const d = Math.min(1.0, Math.max(0.65, cellD * 0.6));
const body = new THREE.Mesh(new THREE.BoxGeometry(w, 0.95, d), darkWood);
body.position.y = 0.475;
body.castShadow = true;
g.add(body);
const machine = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.35, 0.35), metal);
machine.position.set(-w * 0.2, 1.12, 0);
g.add(machine);
return g;
}
if (kind === "bar_seat") {
const stool = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.68, 12), chairMat);
stool.position.y = 0.34;
stool.castShadow = true;
g.add(stool);
return g;
}
if (kind === "sofa") {
const seat = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.42, 0.65), sofaMat);
seat.position.y = 0.21;
seat.castShadow = true;
const back = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.45, 0.16), sofaMat);
back.position.set(0, 0.55, -0.24);
g.add(seat, back);
return g;
}
if (kind === "plant") {
const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.16, 0.36, 12), darkWood);
pot.position.y = 0.18;
const crown = new THREE.Mesh(new THREE.SphereGeometry(0.36, 12, 10), leaf);
crown.position.y = 0.62;
crown.castShadow = true;
g.add(pot, crown);
return g;
}
// Tables (table2, table4, table6, communal_table)
const isLarge = kind === "table6" || kind === "communal_table";
const isFour = kind === "table4";
const tw = isLarge ? 1.5 : isFour ? 0.95 : 0.68;
const td = isLarge ? 0.8 : 0.68;
const top = new THREE.Mesh(new THREE.BoxGeometry(tw, 0.06, td), wood);
top.position.y = 0.72;
top.castShadow = true;
const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 0.7, 10), metal);
leg.position.y = 0.35;
g.add(top, leg);
const chairOffsets = isLarge
? [
[-0.45, -0.52],
[0, -0.52],
[0.45, -0.52],
[-0.45, 0.52],
[0, 0.52],
[0.45, 0.52],
]
: isFour
? [
[-0.24, -0.48],
[0.24, -0.48],
[-0.24, 0.48],
[0.24, 0.48],
]
: [
[0, -0.46],
[0, 0.46],
];
chairOffsets.forEach(([cx, cz]) => {
const ch = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.44, 0.32), chairMat);
ch.position.set(cx, 0.22, cz);
ch.castShadow = true;
g.add(ch);
});
return g;
}
function buildVertical(floor, v) {
const g = new THREE.Group();
const [wx, wz] = toWorldXZ(floor, v.x + v.w / 2, v.y + v.d / 2);
g.position.set(wx, 0, wz);
const mat = new THREE.MeshStandardMaterial({ color: 0xadb5bd, roughness: 0.6 });
if (v.kind === "elevator") {
const box = new THREE.Mesh(new THREE.BoxGeometry(v.w, WALL_HEIGHT, v.d), mat);
box.position.y = WALL_HEIGHT / 2;
g.add(box);
} else {
const steps = 8;
for (let i = 0; i < steps; i++) {
const sh = ((i + 1) / steps) * (WALL_HEIGHT * 0.85);
const step = new THREE.Mesh(new THREE.BoxGeometry(v.w, sh, v.d / steps), mat);
step.position.set(0, sh / 2, -v.d / 2 + ((i + 0.5) * v.d) / steps);
step.castShadow = true;
g.add(step);
}
}
return g;
}
function buildPin(zoneLabel, photoIds) {
const g = new THREE.Group();
g.userData = { zoneLabel, photoIds };
const headMat = new THREE.MeshStandardMaterial({
color: SCENE_COLORS.accent,
emissive: SCENE_COLORS.accent,
emissiveIntensity: 0.18,
roughness: 0.3,
});
const head = new THREE.Mesh(new THREE.OctahedronGeometry(0.24, 0), headMat);
head.position.y = 0.2;
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.03, 0.03, 0.35, 8),
new THREE.MeshBasicMaterial({ color: SCENE_COLORS.accent })
);
g.add(head, stem);
return g;
}
+184
View File
@@ -0,0 +1,184 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import vm from "node:vm";
import { test } from "node:test";
import * as Three from "../../public/vendor/three/three.module.js";
// Exercise real scene geometry/camera math with a minimal rendering boundary. No DOM or GPU
// is required: these tests cover gesture arbitration and view state, not WebGL rendering.
const source = (await readFile(new URL("./scene.js", import.meta.url), "utf8"))
.replace(/^import .*;\r?\n/gm, "")
.replace(/^export /gm, "");
class Surface extends EventTarget {
style = { touchAction: "" };
dataset = {};
hidden = false;
getBoundingClientRect() { return { left: 0, top: 0, right: 390, bottom: 460, width: 390, height: 460 }; }
}
function setup({ reduced = false } = {}) {
const window = new Surface();
const document = new Surface();
const canvas = new Surface();
const frames = new Map();
let nextFrame = 1;
let failRenderer = false;
class Renderer {
shadowMap = {};
setClearColor() {}
setPixelRatio() {}
setSize() {}
constructor() { if (failRenderer) throw new Error("GPU unavailable"); }
render(scene, camera) { scene.updateMatrixWorld(true); camera.updateMatrixWorld(true); }
dispose() { this.disposed = true; }
}
class Controls extends Three.EventDispatcher {
target = new Three.Vector3();
mouseButtons = {};
touches = {};
minDistance = 0;
maxDistance = Infinity;
update() {}
dispose() { this.disposed = true; }
}
class Observer { observe() {} disconnect() { this.disconnected = true; } }
window.matchMedia = (query) => Object.assign(new Surface(), {
matches: query === "(pointer: coarse)" || (query.includes("reduced-motion") && reduced),
});
window.devicePixelRatio = 1;
const context = vm.createContext({
THREE: { ...Three, WebGLRenderer: Renderer }, OrbitControls: Controls,
window, document, Event, performance, console: { warn() {} },
ResizeObserver: Observer, MutationObserver: Observer, IntersectionObserver: Observer,
requestAnimationFrame(callback) { const id = nextFrame++; frames.set(id, callback); return id; },
cancelAnimationFrame(id) { frames.delete(id); },
});
vm.runInContext(`${source}\nthis.api = {mountScene,setFloor,setViewMode,resetScene,zoomScene,highlightZone,disposeScene,scenes};`, context);
const api = context.api;
const selected = [];
const layout = JSON.stringify({ floors: [1, 2].map((level) => ({
level, width_m: 10, depth_m: 10, openings: [], verticals: [],
zones: [{ label: `층${level}`, kind: "seating", x: 1, y: 1, w: 4, d: 4, furniture: [], evidence_photos: [`p${level}`] }],
})) });
const mount = () => api.mountScene(canvas, layout, (label) => selected.push(label));
const handle = mount();
const st = api.scenes.get(handle);
const frame = () => {
const batch = [...frames.values()];
frames.clear();
batch.forEach((callback) => callback());
};
frame();
function point(pin = st.pinMeshes[0]) {
st.scene.updateMatrixWorld(true);
st.camera.lookAt(st.controls.target);
st.camera.updateMatrixWorld(true);
const v = pin.getWorldPosition(new Three.Vector3()).project(st.camera);
return { x: (v.x + 1) * 195, y: (1 - v.y) * 230 };
}
function pointer(target, type, { id = 1, x, y, primary = true } = {}) {
const event = new Event(type, { cancelable: true });
Object.assign(event, { pointerId: id, clientX: x, clientY: y, isPrimary: primary, button: 0 });
target.dispatchEvent(event);
}
return { api, canvas, window, document, selected, handle, st, frame, point, pointer, frames, mount, fail: () => { failRenderer = true; } };
}
test("photo pins work while page scrolling is enabled", () => {
const t = setup();
assert.equal(t.canvas.style.touchAction, "pan-y");
assert.equal(t.st.controls.enabled, false);
t.api.setFloor(t.handle, 1);
const p = t.point();
t.pointer(t.canvas, "pointerdown", p);
t.pointer(t.window, "pointerup", p);
assert.deepEqual(t.selected, ["층1"]);
t.api.disposeScene(t.handle);
});
test("scroll, cancelled, and multi-touch gestures cannot select a pin", () => {
const t = setup();
const p = t.point();
t.pointer(t.canvas, "pointerdown", p);
t.pointer(t.window, "pointermove", { x: p.x, y: p.y + 12 });
t.pointer(t.window, "pointerup", p);
t.pointer(t.canvas, "pointerdown", p);
t.pointer(t.window, "pointercancel", p);
t.pointer(t.window, "pointerup", p);
t.pointer(t.canvas, "pointerdown", p);
t.pointer(t.canvas, "pointerdown", { ...p, id: 2, primary: false });
t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false });
t.pointer(t.window, "pointerup", p);
t.pointer(t.canvas, "pointerdown", p);
t.pointer(t.window, "pointerdown", { ...p, id: 2, primary: false });
t.pointer(t.window, "pointerup", p);
t.pointer(t.window, "pointerup", { ...p, id: 2, primary: false });
assert.deepEqual(t.selected, []);
t.api.disposeScene(t.handle);
});
test("plan mode locks rotation and floor changes preserve its zoom and orientation", () => {
const t = setup();
t.api.setFloor(t.handle, 1);
t.api.setViewMode(t.handle, "plan");
assert.equal(t.st.controls.enableRotate, false);
assert.equal(t.st.controls.maxPolarAngle, 0);
assert.equal(t.st.controls.touches.ONE, Three.TOUCH.PAN);
t.api.zoomScene(t.handle, 1);
const offset = t.st.camera.position.clone().sub(t.st.controls.target);
t.api.setFloor(t.handle, 2);
assert.ok(offset.distanceTo(t.st.camera.position.clone().sub(t.st.controls.target)) < 1e-10);
assert.equal(t.st.floorGroups.get(1).group.visible, false);
t.api.setViewMode(t.handle, "3d");
assert.equal(t.st.controls.enableRotate, true);
assert.equal(t.st.floorGroups.get(1).group.visible, true);
assert.equal(t.st.activeLevel, 2);
t.api.disposeScene(t.handle);
});
test("reduced motion renders on demand and freezes decorative pins", () => {
const t = setup({ reduced: true });
assert.equal(t.st.controls.enableDamping, false);
assert.equal(t.frames.size, 0);
assert.ok(t.st.pinMeshes.every((pin) => pin.rotation.y === 0 && pin.position.y === pin.userData.baseY));
t.api.zoomScene(t.handle, 1);
assert.equal(t.frames.size, 1);
t.frame();
assert.equal(t.frames.size, 0);
t.api.disposeScene(t.handle);
});
test("context loss reports a recoverable state and disposal cancels work", () => {
const t = setup();
let errors = 0;
let ready = 0;
t.canvas.addEventListener("scene-error", () => errors++);
t.canvas.addEventListener("scene-ready", () => ready++);
const lost = new Event("webglcontextlost", { cancelable: true });
t.canvas.dispatchEvent(lost);
assert.equal(lost.defaultPrevented, true);
assert.equal(errors, 1);
assert.ok(t.canvas.dataset.sceneError);
assert.equal(t.frames.size, 0);
t.canvas.dispatchEvent(new Event("webglcontextrestored"));
assert.equal(ready, 1);
assert.equal(t.canvas.dataset.sceneError, "");
t.api.disposeScene(t.handle);
assert.equal(t.api.scenes.size, 0);
assert.equal(t.frames.size, 0);
assert.equal(t.st.renderer.disposed, true);
assert.equal(t.st.controls.disposed, true);
assert.equal(t.canvas.style.touchAction, "");
t.canvas.dispatchEvent(new Event("webglcontextlost", { cancelable: true }));
assert.equal(errors, 1);
});
test("unavailable WebGL returns an explicit failure handle instead of throwing", () => {
const t = setup();
t.api.disposeScene(t.handle);
t.fail();
assert.equal(t.mount(), 0);
assert.ok(t.canvas.dataset.sceneError);
assert.equal(t.api.scenes.size, 0);
});
+186
View File
@@ -0,0 +1,186 @@
// Small browser-only interactions shared by the hydrated views.
const scrollPositions = new Map();
const dialogs = new Map();
const watchers = new Map();
let nextHandle = 1;
let scrollLock = null;
let restoreGeneration = 0;
export function saveScroll(key) {
restoreGeneration += 1;
scrollPositions.set(key, window.scrollY);
}
export function restoreScroll(destination) {
const target = new URL(destination, location.href);
const top = scrollPositions.get(target.pathname) || 0;
const route = target.pathname + target.search;
const previousRoute = location.pathname + location.search;
const generation = ++restoreGeneration;
let attempts = 0;
const afterCommit = () => {
if (generation !== restoreGeneration) return;
const currentRoute = location.pathname + location.search;
// Leptos constructs the destination before committing the browser URL.
// Wait for that commit, but abandon a canceled or superseded navigation.
if (currentRoute !== route) {
if (currentRoute === previousRoute && ++attempts < 60) requestAnimationFrame(afterCommit);
return;
}
requestAnimationFrame(() => {
if (generation === restoreGeneration && location.pathname + location.search === route) {
window.scrollTo({ top, behavior: "instant" });
}
});
};
requestAnimationFrame(afterCommit);
}
export function focusSearch() {
document.querySelector('input[name="q"]')?.focus({ preventScroll: true });
}
export function blurActive() {
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
}
export function closeMenu(id) { document.getElementById(id)?.removeAttribute("open"); }
export function clearJobQuery() {
const url = new URL(location.href);
if (url.searchParams.has("job")) {
url.searchParams.delete("job");
history.replaceState(history.state, "", url);
}
}
export function revealSelectedPhoto() {
requestAnimationFrame(() => {
if (isCompact() || document.querySelector('dialog:modal')) return;
const panel = document.getElementById('info-panel');
if (panel) panel.scrollTop = 0;
panel?.querySelector('.selected-zone-panel')?.scrollIntoView({ block: 'nearest', behavior: 'instant' });
});
}
export function isCompact() {
return matchMedia("(max-width: 639px), (max-height: 499px)").matches;
}
export function watchCompact(onChange) {
const handle = nextHandle++;
const media = matchMedia("(max-width: 639px), (max-height: 499px)");
const listener = () => onChange(media.matches);
media.addEventListener("change", listener);
watchers.set(handle, { media, listener });
listener();
return handle;
}
export function releaseWatch(handle) {
const watcher = watchers.get(handle);
if (watcher) watcher.media.removeEventListener("change", watcher.listener);
watchers.delete(handle);
}
function unlockScroll() {
if (scrollLock && ![...dialogs.values()].some(record => !record.finished)) {
document.documentElement.style.overflow = scrollLock.html;
document.body.style.overflow = scrollLock.body;
scrollLock = null;
}
}
function finishDialog(record, notify = true) {
if (record.finished) return;
record.finished = true;
record.dialog.removeEventListener("cancel", record.cancel);
record.dialog.removeEventListener("close", record.closed);
record.dialog.removeEventListener("click", record.backdrop);
record.dialog.removeAttribute("aria-modal");
if (record.dialog.open) record.dialog.close();
if (record.inline && record.dialog.isConnected) record.dialog.show();
unlockScroll();
if (location.pathname + location.search === record.route) {
window.scrollTo({ top: record.scrollY, behavior: "instant" });
if (record.focus?.isConnected) record.focus.focus({ preventScroll: true });
}
if (notify) queueMicrotask(() => {
if (dialogs.get(record.handle) === record) record.onClose();
});
}
function requestClose(record) {
if (record.finished || record.pending) return;
if (history.state?.spaceOverlay === record.token) {
record.pending = true;
history.back();
} else {
finishDialog(record);
}
}
window.addEventListener("popstate", () => {
for (const record of [...dialogs.values()].reverse()) {
if (!record.finished && history.state?.spaceOverlay !== record.token) finishDialog(record);
else if (!record.finished) break;
}
});
export function openDialog(id, onClose) {
const dialog = document.getElementById(id);
if (!(dialog instanceof HTMLDialogElement)) return 0;
const existing = [...dialogs.values()].find(record => record.dialog === dialog && !record.finished);
if (existing) {
// The Rust bridge replaces its stored Closure for a reused handle.
existing.onClose = onClose;
return existing.handle;
}
const handle = nextHandle++;
const record = {
handle, dialog, onClose, token: `space-${handle}-${Date.now()}`,
focus: document.activeElement instanceof HTMLElement ? document.activeElement : null,
inline: dialog.hasAttribute("data-inline-dialog"),
scrollY: window.scrollY, route: location.pathname + location.search,
finished: false, pending: false,
};
record.cancel = event => { event.preventDefault(); requestClose(record); };
record.closed = () => {
// close() before showModal() queues an event; ignore it while the new modal is open.
if (!dialog.open && !record.finished) requestClose(record);
};
record.backdrop = event => {
if (event.target !== dialog) return;
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) requestClose(record);
};
if (!scrollLock) {
scrollLock = { html: document.documentElement.style.overflow, body: document.body.style.overflow };
document.documentElement.style.overflow = "hidden";
document.body.style.overflow = "hidden";
}
dialogs.set(handle, record);
if (dialog.open) dialog.close();
try {
dialog.showModal();
} catch {
dialogs.delete(handle);
if (record.inline && dialog.isConnected) dialog.show();
unlockScroll();
return 0;
}
dialog.setAttribute("aria-modal", "true");
dialog.addEventListener("cancel", record.cancel);
dialog.addEventListener("close", record.closed);
dialog.addEventListener("click", record.backdrop);
history.pushState({ ...history.state, spaceOverlay: record.token }, "");
const focusTarget = dialog.querySelector("[autofocus], button:not([disabled]), [href], [tabindex='0']");
focusTarget?.focus({ preventScroll: true });
return handle;
}
export function closeDialog(id) {
const record = [...dialogs.values()].reverse().find(entry => entry.dialog.id === id && !entry.finished);
if (record) requestClose(record);
}
export function releaseDialog(handle) {
const record = dialogs.get(handle);
if (!record) return;
// Route disposal must not initiate a second navigation. Explicit close consumes history.
finishDialog(record, false);
dialogs.delete(handle);
}
export function copyText(value, onResult) {
if (!navigator.clipboard?.writeText) { onResult(false); return; }
navigator.clipboard.writeText(value).then(() => onResult(true), () => onResult(false));
}
+306
View File
@@ -0,0 +1,306 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import vm from "node:vm";
const source = readFileSync(new URL("./ui.js", import.meta.url), "utf8");
// The fake environment models asynchronous close/popstate delivery deliberately:
// it catches lifetime mistakes hidden by a synchronous history.back() stub.
function setup() {
const tasks = [];
const microtasks = [];
const frames = [];
const elements = new Map();
const scrollCalls = [];
const document = {
activeElement: null,
documentElement: { style: { overflow: "auto" } },
body: { style: { overflow: "" } },
getElementById: id => elements.get(id),
querySelector: () => null,
};
class Element extends EventTarget {
isConnected = true;
focusCount = 0;
focus() { this.focusCount += 1; document.activeElement = this; }
blur() { if (document.activeElement === this) document.activeElement = null; }
}
class Dialog extends Element {
constructor(id, { inline = false } = {}) {
super();
this.id = id;
this.open = inline;
this.modal = false;
this.attributes = new Map(inline ? [["data-inline-dialog", "true"]] : []);
this.firstButton = new Element();
elements.set(id, this);
}
hasAttribute(name) { return this.attributes.has(name); }
setAttribute(name, value) { this.attributes.set(name, value); }
removeAttribute(name) { this.attributes.delete(name); }
querySelector() { return this.firstButton; }
show() { this.open = true; this.modal = false; }
showModal() {
if (this.open) throw new Error("A nonmodal dialog must be closed first");
this.open = true;
this.modal = true;
}
close() {
if (!this.open) return;
this.open = false;
this.modal = false;
tasks.push(() => this.dispatchEvent(new Event("close")));
}
getBoundingClientRect() { return { left: 10, top: 10, right: 300, bottom: 500 }; }
}
const window = new EventTarget();
window.scrollY = 340;
window.scrollTo = options => {
window.scrollY = options.top;
scrollCalls.push(options.top);
};
const location = new URL("http://localhost/place/kakao:123?from=%2Frecent");
const entries = [{ router: "base" }];
let historyIndex = 0;
const history = {
backCalls: 0,
get state() { return entries[historyIndex]; },
pushState(state) {
entries.splice(historyIndex + 1);
entries.push(state);
historyIndex += 1;
},
replaceState(state) { entries[historyIndex] = state; },
back() {
this.backCalls += 1;
tasks.push(() => {
if (historyIndex === 0) return;
historyIndex -= 1;
window.dispatchEvent(new Event("popstate"));
});
},
};
const context = {
window, document, location, history, URL, Event,
HTMLElement: Element, HTMLDialogElement: Dialog,
navigator: {},
queueMicrotask: callback => microtasks.push(callback),
requestAnimationFrame: callback => frames.push(callback),
matchMedia: () => Object.assign(new EventTarget(), { matches: false }),
};
const exports = ["saveScroll", "restoreScroll", "openDialog", "closeDialog", "releaseDialog"];
const api = vm.runInNewContext(
`${source.replace(/^export /gm, "")}\n({ ${exports.join(", ")} })`,
context,
{ filename: "ui.js" },
);
function flush() {
while (tasks.length || microtasks.length) {
while (microtasks.length) microtasks.shift()();
if (tasks.length) tasks.shift()();
}
}
function flushFrames() {
while (frames.length) frames.shift()();
}
function nextFrame() { frames.shift()?.(); }
return { api, Dialog, Element, document, window, location, history, entries, scrollCalls, flush, flushFrames, nextFrame };
}
test("nested modal close consumes only the inner history entry and retains the outer scroll lock", () => {
const env = setup();
const { api, document, history, flush } = env;
const opener = new env.Element();
opener.focus();
const scene = new env.Dialog("scene", { inline: true });
const photo = new env.Dialog("photo");
let sceneClosed = 0;
let photoClosed = 0;
api.openDialog("scene", () => sceneClosed++);
const innerOpener = new env.Element();
innerOpener.focus();
api.openDialog("photo", () => photoClosed++);
api.closeDialog("photo");
assert.equal(photo.open, true, "close is pending its history traversal");
flush();
assert.equal(photo.open, false);
assert.equal(photoClosed, 1);
assert.equal(sceneClosed, 0);
assert.equal(scene.open, true);
assert.equal(scene.modal, true);
assert.equal(document.body.style.overflow, "hidden");
assert.equal(document.activeElement, innerOpener);
assert.equal(history.state.spaceOverlay, env.entries[1].spaceOverlay);
api.closeDialog("scene");
flush();
assert.equal(sceneClosed, 1);
assert.equal(scene.open, true, "the inline canvas remains rendered");
assert.equal(scene.modal, false);
assert.equal(document.body.style.overflow, "");
assert.equal(document.documentElement.style.overflow, "auto");
assert.equal(document.activeElement, opener);
assert.equal(history.backCalls, 2);
});
test("the queued close event from promoting an inline dialog does not dismiss its modal", () => {
const env = setup();
const dialog = new env.Dialog("scene", { inline: true });
let closed = 0;
env.api.openDialog("scene", () => closed++);
env.flush();
assert.equal(dialog.modal, true);
assert.equal(dialog.open, true);
assert.equal(closed, 0);
assert.equal(env.history.backCalls, 0);
const cancel = new Event("cancel", { cancelable: true });
dialog.dispatchEvent(cancel);
assert.equal(cancel.defaultPrevented, true);
env.flush();
assert.equal(dialog.open, true);
assert.equal(dialog.modal, false);
assert.equal(closed, 1);
});
test("reopening an already open dialog replaces the callback without adding history", () => {
const env = setup();
new env.Dialog("photo");
let oldCalls = 0;
let newCalls = 0;
const first = env.api.openDialog("photo", () => oldCalls++);
const second = env.api.openDialog("photo", () => newCalls++);
assert.equal(second, first);
assert.equal(env.entries.length, 2);
env.api.closeDialog("photo");
env.flush();
assert.equal(oldCalls, 0, "the old Rust Closure can safely be dropped");
assert.equal(newCalls, 1);
});
test("component release restores inline content without navigating history or notifying disposed state", () => {
const env = setup();
const scene = new env.Dialog("scene", { inline: true });
let closed = 0;
const handle = env.api.openDialog("scene", () => closed++);
// The URL can still be the old route while a router disposes its component.
env.api.releaseDialog(handle);
env.flush();
assert.equal(env.history.backCalls, 0);
assert.equal(scene.open, true);
assert.equal(scene.modal, false);
assert.equal(env.document.body.style.overflow, "");
assert.equal(closed, 0);
});
test("close followed by immediate release cannot call a dropped callback after popstate", () => {
const env = setup();
const photo = new env.Dialog("photo");
const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked"));
env.api.closeDialog("photo");
env.api.releaseDialog(handle);
env.flush();
assert.equal(env.history.backCalls, 1);
assert.equal(photo.open, false);
assert.equal(env.document.body.style.overflow, "");
});
test("browser back closes nested dialogs from top to bottom", () => {
const env = setup();
const scene = new env.Dialog("scene", { inline: true });
const photo = new env.Dialog("photo");
const notifications = [];
env.api.openDialog("scene", () => notifications.push("scene"));
env.api.openDialog("photo", () => notifications.push("photo"));
env.history.back();
env.flush();
assert.deepEqual(notifications, ["photo"]);
assert.equal(photo.open, false);
assert.equal(scene.modal, true);
env.history.back();
env.flush();
assert.deepEqual(notifications, ["photo", "scene"]);
assert.equal(scene.open, true);
assert.equal(scene.modal, false);
});
test("native dialog close still consumes overlay history once", () => {
const env = setup();
const photo = new env.Dialog("photo");
let closed = 0;
env.api.openDialog("photo", () => closed++);
photo.close();
env.flush();
assert.equal(env.history.backCalls, 1);
assert.equal(closed, 1);
assert.equal(env.document.body.style.overflow, "");
});
test("a deferred search scroll restore cannot affect a different query on the same route", () => {
const env = setup();
env.location.pathname = "/";
env.location.search = "?q=first";
env.window.scrollY = 620;
env.api.saveScroll("/");
env.window.scrollY = 0;
env.api.restoreScroll("/?q=first");
env.location.search = "?q=second";
env.flushFrames();
assert.deepEqual(env.scrollCalls, []);
env.location.search = "?q=first";
env.api.restoreScroll("/?q=first");
env.flushFrames();
assert.deepEqual(env.scrollCalls, [620]);
});
test("search restoration waits for the router's destination URL commit", () => {
const env = setup();
env.location.pathname = "/";
env.location.search = "?q=first";
env.window.scrollY = 89;
env.api.saveScroll("/");
env.location.pathname = "/recent";
env.location.search = "";
env.window.scrollY = 0;
// The new Home component exists while browser location still says /recent.
env.api.restoreScroll("/?q=first");
env.nextFrame();
assert.deepEqual(env.scrollCalls, []);
env.location.pathname = "/";
env.location.search = "?q=first";
env.flushFrames();
assert.deepEqual(env.scrollCalls, [89]);
});
test("a newer navigation cancels a pending restoration before its URL commits", () => {
const env = setup();
env.window.scrollY = 89;
env.api.saveScroll("/");
env.location.pathname = "/recent";
env.location.search = "";
env.api.restoreScroll("/?q=first");
env.nextFrame();
env.api.saveScroll("/recent");
env.location.pathname = "/";
env.location.search = "?q=first";
env.flushFrames();
assert.deepEqual(env.scrollCalls, []);
});
test("releasing a dialog after route change does not restore focus or scroll into the old page", () => {
const env = setup();
const opener = new env.Element();
opener.focus();
new env.Dialog("photo");
const handle = env.api.openDialog("photo", () => assert.fail("disposed callback invoked"));
env.location.pathname = "/recent";
env.location.search = "";
env.api.releaseDialog(handle);
env.flush();
assert.equal(opener.focusCount, 1);
assert.deepEqual(env.scrollCalls, []);
assert.equal(env.history.backCalls, 0);
});
+300
View File
@@ -0,0 +1,300 @@
use crate::{
discovery::DiscoveryState, get_place_view, scene_bridge, trigger_reanalyze, ui_bridge,
workspace::WorkspaceView, Icon,
};
use domain::JobEvent;
use leptos::prelude::*;
use leptos_router::hooks::{use_params_map, use_query_map};
pub(crate) fn return_destination(value: Option<&str>) -> String {
match value {
Some("/recent") => "/recent".into(),
Some(value)
if (value == "/" || value.starts_with("/?q="))
&& value.len() <= 4096
&& !value.contains(['\r', '\n', '#']) =>
{
value.into()
}
_ => "/".into(),
}
}
#[component]
pub(crate) fn PlacePage() -> impl IntoView {
let params = use_params_map();
view! { {move || {
let id = params.read().get("id").unwrap_or_default();
view! { <PlaceDetail place_id=id/> }
}} }
}
#[component]
fn PlaceDetail(place_id: String) -> impl IntoView {
let discovery = use_context::<DiscoveryState>();
let query = use_query_map();
let initial_job = query.read_untracked().get("job");
let id = StoredValue::new(place_id);
let active_job = RwSignal::new(initial_job);
let events = RwSignal::new(Vec::<JobEvent>::new());
let settled_jobs = RwSignal::new(Vec::<String>::new());
let refresh_tick = RwSignal::new(0u32);
let pending = RwSignal::new(false);
let analysis_error = RwSignal::new(None::<&'static str>);
let copy_status = RwSignal::new(String::new());
let back = Memo::new(move |_| return_destination(query.read().get("from").as_deref()));
let place_res = Resource::new(
move || refresh_tick.get(),
move |_| get_place_view(id.get_value()),
);
Effect::new(move |_| {
if let Some(Ok(Some(place))) = place_res.get() {
if active_job.get_untracked().is_none() {
if let Some(job) = place.running_job {
if !settled_jobs.get_untracked().contains(&job) {
active_job.set(Some(job));
}
}
}
}
});
Effect::new(move |_| {
let Some(job) = active_job.get() else {
return;
};
events.set(Vec::new());
analysis_error.set(None);
let subscribed_job = job.clone();
let subscription = scene_bridge::subscribe_job_events(&job, move |event| {
let terminal = event.is_terminal();
let succeeded = matches!(event, JobEvent::Done { .. });
if matches!(event, JobEvent::Error { .. }) {
analysis_error.set(Some("분석을 완료하지 못했습니다. 다시 시도해 주세요."));
}
events.update(|all| all.push(event));
if terminal {
settled_jobs.update(|all| all.push(subscribed_job.clone()));
active_job.set(None);
ui_bridge::clear_job_query();
if succeeded {
if let Some(state) = discovery {
state.invalidate_recent();
}
refresh_tick.update(|n| *n += 1);
}
}
});
#[cfg(feature = "hydrate")]
if subscription.is_none() {
analysis_error.set(Some(
"분석 진행 상태에 연결하지 못했습니다. 다시 시도해 주세요.",
));
settled_jobs.update(|all| all.push(job));
active_job.set(None);
}
on_cleanup(move || {
if let Some(handle) = subscription {
scene_bridge::close_job_events(handle);
}
});
});
let analyze = Action::new(move |_: &()| async move {
if pending.get_untracked() || active_job.get_untracked().is_some() {
return;
}
pending.set(true);
analysis_error.set(None);
ui_bridge::close_menu("place-menu");
match trigger_reanalyze(id.get_value()).await {
Ok(job) => {
if let Some(state) = discovery {
state.invalidate_recent();
}
active_job.set(Some(job));
}
Err(_) => analysis_error.set(Some(
"분석을 시작하지 못했습니다. 잠시 후 다시 시도해 주세요.",
)),
}
pending.set(false);
});
view! {
<div class="place-page">
<Transition fallback=|| view! { <div class="loading-box" role="status">"장소를 불러오는 중…"</div> }>
{move || place_res.get().map(|result| match result {
Ok(Some(place)) => {
let address = if place.place.road_address.is_empty() { place.place.address.clone() } else { place.place.road_address.clone() };
let copy_address = address.clone();
let parcel_address = (!place.place.road_address.is_empty()
&& !place.place.address.is_empty()
&& place.place.address != place.place.road_address)
.then(|| place.place.address.clone());
let has_layout = place.layout.is_some();
view! {
<header class="place-header">
<a class="back-link icon-button" href=move || back.get()
aria-label=move || if back.get() == "/recent" { "분석 완료 목록으로 돌아가기" } else { "검색 결과로 돌아가기" }
on:click=move |_| { if let Some(state) = discovery { if back.get().starts_with("/?q=") { state.search_href.set(back.get()); } } }>
<Icon name="back"/>
</a>
<div class="place-title-row"><h1>{place.place.name.clone()}</h1></div>
<details class="place-menu" id="place-menu">
<summary class="icon-button" aria-label="장소 메뉴"><Icon name="more"/></summary>
<div class="place-menu-content">
<p class="menu-category">{place.place.category.clone()}</p>
<p class="place-addr">{address}</p>
<button type="button" class="menu-action" on:click=move |_| {
ui_bridge::copy_text(&copy_address, move |ok| copy_status.set(if ok { "주소를 복사했습니다." } else { "주소를 복사하지 못했습니다. 위 주소를 길게 눌러 복사해 주세요." }.into()));
}><Icon name="copy"/>"주소 복사"</button>
{parcel_address.map(|address| {
let copy_parcel = address.clone();
view! {
<p class="place-addr"><span class="address-kind">"지번 "</span>{address}</p>
<button type="button" class="menu-action" on:click=move |_| {
ui_bridge::copy_text(&copy_parcel, move |ok| copy_status.set(if ok { "지번 주소를 복사했습니다." } else { "주소를 복사하지 못했습니다. 위 주소를 길게 눌러 복사해 주세요." }.into()));
}><Icon name="copy"/>"지번 주소 복사"</button>
}
})}
<p class="copy-status" role="status">{move || copy_status.get()}</p>
{(!place.place.phone.is_empty()).then(|| view! { <a class="menu-action" href=format!("tel:{}", place.place.phone)>"전화 "{place.place.phone.clone()}</a> })}
{(!place.place.place_url.is_empty()).then(|| view! { <a class="menu-action" href=place.place.place_url.clone() target="_blank" rel="noreferrer">"장소 원문 보기"<Icon name="external"/></a> })}
<button type="button" class="menu-action" disabled=move || pending.get() || active_job.get().is_some()
on:click=move |_| { analyze.dispatch(()); }><Icon name="refresh"/>{move || if pending.get() { "분석 요청 중…" } else if active_job.get().is_some() { "분석 진행 중" } else if has_layout { "다시 분석" } else { "분석 시작" }}</button>
</div>
</details>
</header>
{move || analysis_error.get().map(|message| view! {
<div class="alert-error analysis-error" role="alert"><p>{message}</p>
<button type="button" class="btn-secondary" disabled=move || pending.get() || active_job.get().is_some() on:click=move |_| { analyze.dispatch(()); }>"다시 시도"</button>
</div>
})}
{move || active_job.get().is_some().then(|| view! { <ProgressPanel events=events/> })}
{match place.layout.clone() {
Some(layout) => view! { <WorkspaceView layout=layout photos=place.photos.clone()/> }.into_any(),
None => view! {
<Show when=move || active_job.get().is_none() fallback=|| view! {
<div class="analysis-placeholder"><p>"분석이 끝나면 공간 배치와 사진이 표시됩니다."</p><a href="/recent">"분석 완료된 장소 보기"</a></div>
}>
<div class="recent-empty">
<h2>"아직 공간 정보가 없습니다."</h2>
<p>"장소 사진을 분석하면 공간 배치와 좌석 정보를 확인할 수 있습니다."</p>
<button type="button" class="btn-primary" disabled=move || pending.get() on:click=move |_| { analyze.dispatch(()); }>{move || if pending.get() { "요청 중…" } else { "분석 시작" }}</button>
</div>
</Show>
}.into_any(),
}}
}.into_any()
},
Ok(None) => view! { <div class="recent-empty"><h1>"장소를 찾을 수 없습니다."</h1><a href=move || back.get() class="btn-primary">"목록으로 돌아가기"</a></div> }.into_any(),
Err(_) => view! { <div class="alert-error" role="alert"><p>"장소를 불러오지 못했습니다."</p><button type="button" class="btn-secondary" on:click=move |_| refresh_tick.update(|n| *n += 1)>"다시 시도"</button><a href=move || back.get() class="btn-secondary">"목록으로 돌아가기"</a></div> }.into_any(),
})}
</Transition>
</div>
}
}
fn progress_phase(events: &[JobEvent]) -> usize {
if events
.iter()
.any(|event| matches!(event, JobEvent::Done { .. }))
{
2
} else if events.iter().any(|event| {
matches!(
event,
JobEvent::Classified { .. }
| JobEvent::FloorsDetected { .. }
| JobEvent::LayoutDraft { .. }
)
}) {
1
} else {
0
}
}
fn progress_detail(event: &JobEvent) -> Option<String> {
match event {
JobEvent::PlaceResolved { .. } => Some("장소를 확인했습니다.".into()),
JobEvent::SourceDone {
source,
photos,
error,
..
} => Some(if error.is_some() {
format!("{}의 일부 자료를 가져오지 못했습니다.", source.label())
} else {
format!("{} 사진 {}장을 확인했습니다.", source.label(), photos)
}),
JobEvent::PhotosStored { stored, .. } => Some(format!("사진 {}장을 준비했습니다.", stored)),
JobEvent::Classified {
interior, exterior, ..
} => Some(format!(
"실내 사진 {}장 · 외관 사진 {}장을 확인했습니다.",
interior, exterior
)),
JobEvent::FloorsDetected { floors } => {
Some(format!("{}개 층 후보를 검토하고 있습니다.", floors.len()))
}
JobEvent::LayoutDraft { .. } => {
Some("사진을 바탕으로 공간 배치를 구성하고 있습니다.".into())
}
_ => None,
}
}
#[component]
fn ProgressPanel(events: RwSignal<Vec<JobEvent>>) -> impl IntoView {
view! {
<section class="progress-panel" aria-label="분석 진행 상태">
<div class="progress-head" role="status" aria-live="polite"><span class="spinner"></span><strong>{move || if progress_phase(&events.get()) == 0 { "사진과 리뷰를 확인하고 있습니다" } else { "공간 배치를 구성하고 있습니다" }}</strong></div>
<ol class="progress-steps">{["자료 수집", "공간 분석", "완료"].into_iter().enumerate().map(|(index, label)| view! {
<li class=move || { if progress_phase(&events.get()) > index { "complete" } else { "" } } aria-current=move || (progress_phase(&events.get()) == index).then_some("step")>{label}</li>
}).collect_view()}</ol>
<details class="progress-details"><summary>"진행 내용"</summary><ul>{move || events.get().iter().filter_map(progress_detail).map(|message| view! { <li>{message}</li> }).collect_view()}</ul></details>
</section>
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn return_paths_stay_in_known_local_views() {
assert_eq!(return_destination(Some("/recent")), "/recent");
assert_eq!(
return_destination(Some("/?q=%EC%84%B1%EC%88%98")),
"/?q=%EC%84%B1%EC%88%98"
);
for value in [
"//evil.example",
"https://evil.example",
"/place/x",
"/?q=x\n",
"/?q=x#photo",
] {
assert_eq!(return_destination(Some(value)), "/");
}
}
#[test]
fn phases_follow_actual_events_without_inventing_percentage() {
assert_eq!(progress_phase(&[]), 0);
assert_eq!(progress_phase(&[JobEvent::LayoutDraft { attempt: 2 }]), 1);
assert_eq!(
progress_phase(&[JobEvent::Done {
place_id: "x".into()
}]),
2
);
assert_eq!(
progress_detail(&JobEvent::Log {
message: "internal p_123".into()
}),
None
);
}
}
+549
View File
@@ -0,0 +1,549 @@
//! Search and saved-analysis discovery. State belongs to the app so opening a
//! place does not discard the list that led to it.
use crate::{encode_path_segment, get_recent_places, search_places, select_place, Icon};
use domain::{PlaceCandidate, RecentPlace};
use leptos::prelude::*;
use leptos_router::hooks::{use_location, use_navigate, use_query_map};
#[derive(Clone, Copy)]
pub(crate) struct DiscoveryState {
pub draft: RwSignal<String>,
pub search_href: RwSignal<String>,
applied_query: RwSignal<String>,
cached_search: RwSignal<Option<(String, Vec<PlaceCandidate>)>>,
cached_recent: RwSignal<Option<Vec<RecentPlace>>>,
restore_search: RwSignal<bool>,
restore_recent: RwSignal<bool>,
reuse_recent: RwSignal<bool>,
}
impl Default for DiscoveryState {
fn default() -> Self {
Self {
draft: RwSignal::new(String::new()),
search_href: RwSignal::new("/".to_string()),
applied_query: RwSignal::new(String::new()),
cached_search: RwSignal::new(None),
cached_recent: RwSignal::new(None),
restore_search: RwSignal::new(false),
restore_recent: RwSignal::new(false),
reuse_recent: RwSignal::new(false),
}
}
}
impl DiscoveryState {
/// Set the return intent before routing starts; disposal can run after the
/// destination's first effect and is too late as the only signal source.
pub(crate) fn remember_scroll(self, pathname: &str) {
crate::ui_bridge::save_scroll(pathname);
match pathname {
"/" => self.restore_search.set(true),
"/recent" => self.restore_recent.set(true),
_ => {}
}
}
/// Call when an analysis starts or finishes so returning to its source list
/// does not reuse a snapshot from before the analysis.
pub(crate) fn invalidate_recent(self) {
self.cached_recent.set(None);
}
}
/// RFC 3986 query component encoding; in particular, nested return URLs must
/// encode their `?`, `&`, `+`, and `=` delimiters instead of becoming parameters.
pub(crate) fn encode_query_component(value: &str) -> String {
use std::fmt::Write;
value.bytes().fold(String::new(), |mut encoded, byte| {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
encoded.push(byte as char);
} else {
let _ = write!(encoded, "%{byte:02X}");
}
encoded
})
}
pub(crate) fn search_href(query: &str) -> String {
let query = query.trim();
if query.is_empty() {
"/".to_string()
} else {
format!("/?q={}", encode_query_component(query))
}
}
#[component]
pub(crate) fn HomePage() -> impl IntoView {
let state = expect_context::<DiscoveryState>();
// An outgoing click sets the app's return intent before native link
// navigation runs. Only the next mounted page may consume that intent.
let (restore_on_entry, set_restore_on_entry) = signal(state.restore_search.get_untracked());
let params = use_query_map();
let location = use_location();
let location_search = location.search;
let pathname = location.pathname;
let initial_query = params
.get_untracked()
.get("q")
.unwrap_or_default()
.trim()
.to_string();
if state.applied_query.get_untracked() != initial_query {
state.draft.set(initial_query.clone());
state.applied_query.set(initial_query.clone());
}
state.search_href.set(search_href(&initial_query));
// Topbar records the actual position before navigation. Only mark it here:
// saving during disposal can overwrite it after the router scrolls to top.
#[cfg(feature = "hydrate")]
on_cleanup(move || state.restore_search.set(true));
let submitted = Memo::new(move |_| {
params
.read()
.get("q")
.unwrap_or_default()
.trim()
.to_string()
});
let (refresh, set_refresh) = signal(0u32);
let (selecting, set_selecting) = signal(Option::<String>::None);
let (selection_error, set_selection_error) = signal(false);
let (last_selection, set_last_selection) = signal(Option::<PlaceCandidate>::None);
let (search_pending, set_search_pending) = signal(false);
let navigate = use_navigate();
Effect::new(move |_| {
let query = submitted.get();
// Do not replace an unsubmitted draft when returning from a place.
if state.applied_query.get_untracked() != query {
state.draft.set(query.clone());
state.applied_query.set(query.clone());
}
state.search_href.set(search_href(&query));
});
let search_res = Resource::new(
move || (submitted.get(), refresh.get()),
move |(query, refresh)| async move {
if query.trim().is_empty() {
return Ok(Vec::new());
}
if refresh == 0 {
if let Some((cached_query, list)) = state.cached_search.get_untracked() {
if cached_query == query {
return Ok(list);
}
}
}
let result = search_places(query.clone()).await;
if let Ok(list) = &result {
state.cached_search.set(Some((query, list.clone())));
}
result
},
);
// The existing API provides up to 50 positively identified analyses. An
// absent ID is intentionally left unlabelled, rather than called "new".
let analyzed_res = Resource::new(
|| (),
move |_| async move {
// Refresh these small status summaries on each visit. An analysis
// may have completed while this search route was not mounted.
let result = get_recent_places().await;
if let Ok(list) = &result {
state.cached_recent.set(Some(list.clone()));
}
result
},
);
Effect::new(move |_| {
// The ready-status resource is also read inside the results Transition.
// Cached results alone do not mean its DOM has enough height to restore.
if pathname.get() == "/"
&& matches!(search_res.get(), Some(Ok(_)))
&& analyzed_res.get().is_some()
&& !search_pending.get()
&& restore_on_entry.get()
{
let search = location_search.get_untracked();
let destination = if search.is_empty() {
"/".into()
} else {
format!("/?{search}")
};
crate::ui_bridge::restore_scroll(&destination);
set_restore_on_entry.set(false);
state.restore_search.set(false);
}
});
let nav_select = navigate.clone();
let pick_action = Action::new(move |candidate: &PlaceCandidate| {
let candidate = candidate.clone();
let nav = nav_select.clone();
let from = search_href(&submitted.get_untracked());
async move {
set_selecting.set(Some(candidate.place_id()));
set_last_selection.set(Some(candidate.clone()));
set_selection_error.set(false);
match select_place(candidate, false).await {
Ok((place_id, job)) => {
state.remember_scroll("/");
let mut href = format!(
"/place/{}?from={}",
encode_path_segment(&place_id),
encode_query_component(&from)
);
if let Some(job_id) = job {
state.invalidate_recent();
href.push_str("&job=");
href.push_str(&encode_query_component(&job_id));
}
nav(&href, Default::default());
}
Err(_) => {
set_selection_error.set(true);
set_selecting.set(None);
}
}
}
});
let nav_submit = navigate.clone();
let submit = move || {
let query = state.draft.get_untracked().trim().to_string();
if query.is_empty() || selecting.get_untracked().is_some() {
return;
}
state.draft.set(query.clone());
state.search_href.set(search_href(&query));
state.restore_search.set(false);
set_selection_error.set(false);
crate::ui_bridge::blur_active();
if submitted.get_untracked() == query {
set_refresh.update(|tick| *tick += 1);
} else {
set_refresh.set(0);
nav_submit(&search_href(&query), Default::default());
}
};
view! {
<div class="home-wrap discovery-home" data-has-results=move || (!submitted.get().is_empty()).to_string()>
<div class="search-column">
<Show when=move || submitted.get().is_empty()>
<div class="page-heading discovery-intro">
<h1>"장소 검색"</h1>
<p>"상호명 또는 주소를 입력하세요."</p>
</div>
</Show>
<section class="search-panel" aria-label="장소 검색 입력">
<form class="search-bar" role="search" on:submit=move |ev| {
ev.prevent_default();
submit();
}>
<div class="search-field">
<Icon name="search"/>
<input
id="place-search-input"
type="search" name="q" enterkeyhint="search"
autocapitalize="none" autocomplete="off" spellcheck="false"
aria-label="상호명 또는 주소" class="search-input"
placeholder="상호명 또는 주소"
prop:value=move || state.draft.get()
on:input=move |ev| state.draft.set(event_target_value(&ev))
/>
<Show when=move || !state.draft.get().is_empty()>
<button type="button" class="search-clear" aria-label="검색어 지우기"
on:click=move |_| { state.draft.set(String::new()); crate::ui_bridge::focus_search(); }>
<Icon name="close"/>
</button>
</Show>
</div>
<button type="submit" class="btn-primary"
disabled=move || state.draft.get().trim().is_empty() || selecting.get().is_some()>"검색"</button>
</form>
<Show when=move || submitted.get().is_empty()>
<div class="quick-row">
<span class="quick-label">"검색 예시"</span>
{["성수 대림창고", "어니언 성수", "블루보틀 성수"].into_iter().map(|query| {
let nav = navigate.clone();
view! {
<button type="button" class="chip" on:click=move |_| {
state.draft.set(query.to_string());
state.search_href.set(search_href(query));
state.restore_search.set(false);
set_selection_error.set(false);
set_refresh.set(0);
crate::ui_bridge::blur_active();
nav(&search_href(query), Default::default());
}>{query}</button>
}
}).collect_view()}
</div>
</Show>
</section>
</div>
<div class="results-column">
<Show when=move || selection_error.get()>
<div class="alert-error retry-row" role="alert">
<p>"장소를 열지 못했습니다. 잠시 후 다시 시도해 주세요."</p>
<button type="button" class="btn-secondary" disabled=move || selecting.get().is_some()
on:click=move |_| { if let Some(candidate) = last_selection.get() { pick_action.dispatch(candidate); } }>"다시 시도"</button>
</div>
</Show>
<section class="search-results" aria-label="장소 검색 결과" aria-busy=move || search_pending.get().to_string()>
<Show when=move || !submitted.get().trim().is_empty()>
<div class="results-heading">
<h1 class="results-title">"검색 결과"</h1>
<span class="results-count" role="status" aria-live="polite">
<Suspense fallback=|| "검색 중…">
{move || if search_pending.get() { "검색 중…".to_string() } else {
search_res.get().and_then(Result::ok).map(|list| format!("{}개", list.len())).unwrap_or_default()
}}
</Suspense>
</span>
</div>
<Show when=move || state.draft.get().trim() != submitted.get()>
<p class="applied-query">{move || format!("‘{}’ 검색 결과입니다. 변경한 검색어는 검색을 눌러 적용하세요.", submitted.get())}</p>
</Show>
</Show>
<Transition set_pending=set_search_pending fallback=move || view! {
<div class="loading-box" role="status"><span class="spinner"></span>"장소를 찾는 중…"</div>
}>
{move || search_res.get().map(|result| match result {
Ok(list) if list.is_empty() && !submitted.get().trim().is_empty() => view! {
<div class="empty-box">
<p>"검색 결과가 없습니다."</p>
<p>"지점명이나 도로명 주소로 다시 검색해 주세요."</p>
</div>
}.into_any(),
Ok(list) => view! {
<div class="candidate-list">
{list.into_iter().map(|candidate| {
let place_id = candidate.place_id();
let selecting_id = place_id.clone();
let ready_id = place_id.clone();
let status_id = place_id.clone();
let address = if candidate.road_address.is_empty() { candidate.address.clone() } else { candidate.road_address.clone() };
let aria_name = format!("{} · {} 공간 보기", candidate.name, address);
let for_click = candidate.clone();
view! {
<button type="button" class="candidate-row" aria-label=aria_name
disabled=move || selecting.get().is_some() || search_pending.get()
aria-busy=move || (selecting.get().as_deref() == Some(selecting_id.as_str())).to_string()
on:click=move |_| { pick_action.dispatch(for_click.clone()); }>
<span class="candidate-copy">
<span class="candidate-title-line"><span class="candidate-name">{candidate.name}</span></span>
<span class="candidate-category">{candidate.category}</span>
<span class="candidate-addr">{address}</span>
<span class="candidate-state">
<Show when=move || analyzed_res.get().and_then(Result::ok).is_some_and(|places| places.iter().any(|entry| entry.place.id == ready_id))>
<span class="candidate-status">"분석 완료"</span>
</Show>
{move || (selecting.get().as_deref() == Some(status_id.as_str())).then_some("장소를 여는 중…")}
</span>
</span>
<span class="candidate-arrow" aria-hidden="true">"›"</span>
</button>
}
}).collect_view()}
</div>
}.into_any(),
Err(_) => view! {
<div class="alert-error retry-row" role="alert">
<p>"검색 결과를 불러오지 못했습니다. 연결을 확인하고 다시 시도해 주세요."</p>
<button type="button" class="btn-secondary" on:click=move |_| set_refresh.update(|tick| *tick += 1)>"다시 시도"</button>
</div>
}.into_any(),
})}
</Transition>
</section>
<details class="discovery-help" id="how-it-works">
<summary>"이용 방법"</summary>
<ol>
<li>"장소를 검색하고 목록에서 선택합니다."</li>
<li>"분석된 공간의 층별 구조와 좌석 배치를 확인합니다."</li>
<li>"사진 핀이나 구역을 눌러 해당 사진을 봅니다."</li>
</ol>
<p>"사진과 리뷰로 추정한 결과로, 실제 배치와 다를 수 있습니다."</p>
</details>
</div>
</div>
}
}
#[component]
pub(crate) fn RecentPlacesPage() -> impl IntoView {
let state = expect_context::<DiscoveryState>();
let (restore_on_entry, set_restore_on_entry) = signal(state.restore_recent.get_untracked());
let reuse_on_entry = state.reuse_recent.get_untracked();
let pathname = use_location().pathname;
#[cfg(feature = "hydrate")]
on_cleanup(move || state.restore_recent.set(true));
let (refresh, set_refresh) = signal(0u32);
let (pending, set_pending) = signal(false);
let recent_res = Resource::new(
move || refresh.get(),
move |refresh| async move {
// Keep order only for a direct detail round trip. A tab visit must
// refresh the shared list even when its scroll position is restored.
if refresh == 0 && reuse_on_entry {
if let Some(list) = state.cached_recent.get_untracked() {
return Ok(list);
}
}
let result = get_recent_places().await;
if let Ok(list) = &result {
state.cached_recent.set(Some(list.clone()));
}
result
},
);
Effect::new(move |_| {
if pathname.get() == "/recent"
&& matches!(recent_res.get(), Some(Ok(_)))
&& !pending.get()
&& restore_on_entry.get()
{
crate::ui_bridge::restore_scroll("/recent");
set_restore_on_entry.set(false);
state.restore_recent.set(false);
state.reuse_recent.set(false);
}
});
view! {
<div class="recent-page">
<div class="recent-heading">
<div class="page-heading">
<h1>"분석 완료"
<span class="recent-title-count" role="status" aria-live="polite">
<Suspense fallback=|| ()>
{move || recent_res.get().and_then(Result::ok).map(|places| format!(" {}", places.len()))}
</Suspense>
</span>
</h1>
<p>"공용 목록 · 최근 열어본 순"</p>
</div>
<button type="button" class="btn-secondary recent-refresh" disabled=move || pending.get()
aria-label=move || if pending.get() { "분석 완료 목록 새로고침 중" } else { "분석 완료 목록 새로고침" }
on:click=move |_| set_refresh.update(|tick| *tick += 1)>
<Icon name="refresh"/>
<span>{move || if pending.get() { "새로고침 중" } else { "새로고침" }}</span>
</button>
</div>
<section aria-label="분석 완료된 장소" aria-busy=move || pending.get().to_string()>
<Transition set_pending=set_pending fallback=|| view! {
<div class="loading-box" role="status"><span class="spinner"></span>"장소를 불러오는 중…"</div>
}>
{move || recent_res.get().map(|result| match result {
Ok(places) if places.is_empty() => view! {
<div class="recent-empty">
<h2>"아직 분석이 완료된 장소가 없습니다."</h2>
<p>"장소를 검색하고 분석을 마치면 여기에서 다시 볼 수 있습니다."</p>
<a href=move || state.search_href.get() class="btn-primary">"장소 검색"</a>
</div>
}.into_any(),
Ok(places) => {
let count = places.len();
view! {
<div class="recent-grid">
{places.into_iter().map(|entry| {
let place = entry.place;
let address = if place.road_address.is_empty() { place.address } else { place.road_address };
let floor_count = entry.floor_labels.len();
let analyzed_date = format_analysis_date(&entry.analyzed_at);
let aria_name = format!("{} · {} 공간 보기", place.name, address);
view! {
<a href=format!("/place/{}?from=%2Frecent", encode_path_segment(&place.id))
class="candidate-row recent-card"
aria-label=aria_name
on:click=move |_| {
state.remember_scroll("/recent");
state.reuse_recent.set(true);
}>
<span class="candidate-copy">
<span class="candidate-name">{place.name}</span>
<span class="candidate-category">{place.category}</span>
<span class="candidate-addr">{address}</span>
<span class="recent-meta">
{(floor_count > 0).then(|| view! { <span>{format!("추정 {}개 층", floor_count)}</span> })}
{(entry.seat_estimate > 0).then(|| view! { <span>{format!("약 {}석", entry.seat_estimate)}</span> })}
</span>
{analyzed_date.map(|date| view! { <span class="recent-date">{format!("분석 {date}")}</span> })}
</span>
<span class="candidate-arrow" aria-hidden="true">"›"</span>
</a>
}
}).collect_view()}
</div>
{(count == 50).then(|| view! { <p class="page-footnote">"최근 50개 장소를 표시합니다."</p> })}
}.into_any()
},
Err(_) => view! {
<div class="alert-error retry-row" role="alert">
<p>"장소 목록을 불러오지 못했습니다."</p>
<button type="button" class="btn-secondary" on:click=move |_| set_refresh.update(|tick| *tick += 1)>"다시 시도"</button>
</div>
}.into_any(),
})}
</Transition>
</section>
</div>
}
}
/// Display the supplied ISO calendar date without guessing the user's timezone.
/// Invalid/unknown timestamps are omitted rather than shown as a made-up date.
fn format_analysis_date(value: &str) -> Option<String> {
let date = value.get(..10)?;
let bytes = date.as_bytes();
if bytes[4] != b'-'
|| bytes[7] != b'-'
|| !bytes
.iter()
.enumerate()
.all(|(i, byte)| i == 4 || i == 7 || byte.is_ascii_digit())
{
return None;
}
let month = date[5..7].parse::<u8>().ok()?;
let day = date[8..10].parse::<u8>().ok()?;
if !(1..=12).contains(&month) || !(1..=31).contains(&day) {
return None;
}
Some(date.replace('-', "."))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_return_url_encodes_delimiters_and_unicode() {
let search = search_href(" 카페 A&B+점 ");
assert_eq!(search, "/?q=%EC%B9%B4%ED%8E%98%20A%26B%2B%EC%A0%90");
let from = encode_query_component(&search);
assert!(from.starts_with("%2F%3Fq%3D"));
assert!(!from.contains('&'));
assert!(!from.contains('+'));
assert!(from.contains("%2526"));
assert_eq!(search_href(" "), "/");
}
#[test]
fn analysis_dates_handle_short_and_non_ascii_inputs() {
assert_eq!(
format_analysis_date("2026-11-04T09:00:00Z"),
Some("2026.11.04".to_string())
);
assert_eq!(format_analysis_date("미확인"), None);
assert_eq!(format_analysis_date("2026-99-12T09:00:00Z"), None);
assert_eq!(format_analysis_date(""), None);
}
}
+183
View File
@@ -0,0 +1,183 @@
#![recursion_limit = "256"]
mod detail;
mod discovery;
pub mod scene_bridge;
pub mod ui_bridge;
mod workspace;
use detail::PlacePage;
use discovery::{DiscoveryState, HomePage, RecentPlacesPage};
use domain::{PlaceCandidate, PlaceView, RecentPlace};
use leptos::prelude::*;
use leptos_meta::{provide_meta_context, MetaTags, Stylesheet, Title};
use leptos_router::components::{Route, Router, Routes};
use leptos_router::hooks::use_location;
use leptos_router::path;
/// HTML shell rendered on the server (`ssr`), including the ES-module import map for Three.js.
pub fn shell(options: LeptosOptions) -> impl IntoView {
let import_map = r#"{
"imports": {
"three": "/vendor/three/three.module.js",
"three/addons/controls/OrbitControls.js": "/vendor/three/OrbitControls.js"
}
}"#;
view! {
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/>
<meta name="theme-color" content="#f0f1f3"/>
<script type="importmap" inner_html=import_map></script>
<AutoReload options=options.clone()/>
<HydrationScripts options/>
<MetaTags/>
</head>
<body>
<App/>
</body>
</html>
}
}
// ============================================================================
// Server Functions
// ============================================================================
#[cfg(feature = "ssr")]
fn pipeline_ctx() -> Result<pipeline::Pipeline, ServerFnError> {
use_context::<pipeline::Pipeline>()
.ok_or_else(|| ServerFnError::new("Pipeline context missing"))
}
#[server(SearchPlaces, "/api")]
pub async fn search_places(query: String) -> Result<Vec<PlaceCandidate>, ServerFnError> {
let pl = pipeline_ctx()?;
pl.search_places(&query)
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
#[server(SelectPlace, "/api")]
pub async fn select_place(
candidate: PlaceCandidate,
force: bool,
) -> Result<(String, Option<String>), ServerFnError> {
let pl = pipeline_ctx()?;
pl.select_or_analyze(candidate, force)
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
#[server(GetPlaceView, "/api")]
pub async fn get_place_view(place_id: String) -> Result<Option<PlaceView>, ServerFnError> {
let pl = pipeline_ctx()?;
pl.get_place_view(&place_id)
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
#[server(TriggerReanalyze, "/api")]
pub async fn trigger_reanalyze(place_id: String) -> Result<String, ServerFnError> {
let pl = pipeline_ctx()?;
pl.reanalyze(&place_id)
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
#[server(GetRecentPlaces, "/api")]
pub async fn get_recent_places() -> Result<Vec<RecentPlace>, ServerFnError> {
pipeline_ctx()?
.recent_places()
.await
.map_err(|e| ServerFnError::new(e.to_string()))
}
// ============================================================================
// Root App & Router
// ============================================================================
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
provide_context(DiscoveryState::default());
view! {
<Stylesheet id="leptos" href="/pkg/make-space.css"/>
<Title text="Make-Space"/>
<Router>
<div class="app-shell">
<Topbar/>
<main class="main-body" id="main-content">
<Routes fallback=|| view! { <div class="empty-box">"페이지를 찾을 수 없습니다."</div> }>
<Route path=path!("") view=HomePage/>
<Route path=path!("/recent") view=RecentPlacesPage/>
<Route path=path!("/place/:id") view=PlacePage/>
</Routes>
</main>
</div>
</Router>
}
}
#[component]
fn Topbar() -> impl IntoView {
let pathname = use_location().pathname;
let state = expect_context::<DiscoveryState>();
view! {
<a class="skip-link" href="#main-content">"본문으로 이동"</a>
<Show when=move || !pathname.get().starts_with("/place/")>
<header class="topbar">
<a href=move || state.search_href.get() class="brand" aria-label="Make-Space 장소 검색" on:click=move |_| state.remember_scroll(&pathname.get())>
<span class="brand-mark"><Icon name="cube"/></span>
<span class="brand-title">"Make-Space"</span>
</a>
<nav class="topbar-nav" aria-label="주 메뉴">
<a href=move || state.search_href.get() on:click=move |_| state.remember_scroll(&pathname.get()) aria-current=move || (pathname.get() == "/").then_some("page")>"검색"</a>
<a href="/recent" on:click=move |_| state.remember_scroll(&pathname.get()) aria-current=move || (pathname.get() == "/recent").then_some("page")>"분석 완료"</a>
</nav>
</header>
</Show>
}
}
#[component]
fn Icon(name: &'static str) -> impl IntoView {
let path = match name {
"search" => "M21 21l-4.4-4.4M19 10.5a8.5 8.5 0 1 1-17 0 8.5 8.5 0 0 1 17 0",
"cube" => "m12 3 9 5v9l-9 5-9-5V8l9-5Zm0 10 9-5M12 13 3 8m9 5v9M7.5 5.5l9 5",
"layers" => "m12 3 10 5-10 5L2 8l10-5ZM2 12l10 5 10-5M2 16l10 5 10-5",
"info" => "M12 11v6m0-10v.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0",
"back" => "M20 12H4m6-6-6 6 6 6",
"photo" => "M4 3h16a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1ZM3 16l5-5 4 4 4-6 5 7M8 7h.01",
"refresh" => "M20 7v5h-5M4 17v-5h5M5.3 7a8 8 0 0 1 13.2-1L20 9M4 15l1.5 3A8 8 0 0 0 18.7 17",
"close" => "m6 6 12 12M6 18 18 6",
"more" => "M5 12h.01M12 12h.01M19 12h.01",
"copy" => "M9 9h12v12H9zM15 9V3H3v12h6",
"external" => "M14 3h7v7m0-7L10 14M10 3H3v18h18v-7",
"chevron" => "m9 6 6 6-6 6",
"expand" => "M8 3H3v5m13-5h5v5M3 16v5h5m13-5v5h-5",
"plus" => "M12 5v14M5 12h14",
"minus" => "M5 12h14",
_ => "M5 12l4 4L19 6",
};
view! {
<svg class="icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d=path/>
</svg>
}
}
fn encode_path_segment(value: &str) -> String {
value.bytes().fold(String::new(), |mut encoded, byte| {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~' | b':') {
encoded.push(byte as char);
} else {
use std::fmt::Write;
let _ = write!(encoded, "%{byte:02X}");
}
encoded
})
}
+274
View File
@@ -0,0 +1,274 @@
//! Browser-only bridges (`hydrate` feature):
//! 1. `wasm-bindgen` bindings to `/js/scene.js` (Three.js renderer)
//! 2. `EventSource` SSE subscriber for `/api/jobs/:id/events`
//!
//! JS closures and `EventSource` objects are kept in a `thread_local!` table and referenced by `u32`
//! so handles are `Copy + Send + Sync` and work directly with Leptos `on_cleanup`.
use domain::JobEvent;
#[cfg(feature = "hydrate")]
mod imp {
use super::*;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
#[wasm_bindgen(module = "/js/scene.js")]
extern "C" {
#[wasm_bindgen(catch, js_name = mountScene)]
fn js_mount_scene(
canvas: &web_sys::HtmlCanvasElement,
layout_json: &str,
on_zone_select: &js_sys::Function,
) -> Result<u32, JsValue>;
#[wasm_bindgen(js_name = setFloor)]
fn js_set_floor(handle: u32, level: i32);
#[wasm_bindgen(js_name = setViewMode)]
fn js_set_view_mode(handle: u32, mode: &str);
#[wasm_bindgen(js_name = resetScene)]
fn js_reset_scene(handle: u32);
#[wasm_bindgen(js_name = zoomScene)]
fn js_zoom_scene(handle: u32, delta: f64);
#[wasm_bindgen(js_name = highlightZone)]
fn js_highlight_zone(handle: u32, label: &str, photo_ids_json: &str);
#[wasm_bindgen(js_name = disposeScene)]
fn js_dispose_scene(handle: u32);
}
struct SseEntry {
es: web_sys::EventSource,
_on_msg: Closure<dyn FnMut(web_sys::MessageEvent)>,
_on_error: Closure<dyn FnMut(web_sys::Event)>,
}
struct SceneWatch {
canvas: web_sys::HtmlCanvasElement,
callback: Closure<dyn FnMut(web_sys::Event)>,
}
thread_local! {
static SCENE_CBS: RefCell<HashMap<u32, Closure<dyn FnMut(String, String)>>> = RefCell::new(HashMap::new());
static SSE_MAP: RefCell<HashMap<u32, SseEntry>> = RefCell::new(HashMap::new());
static NEXT_SSE_ID: RefCell<u32> = const { RefCell::new(1) };
static SCENE_WATCHES: RefCell<HashMap<u32, SceneWatch>> = RefCell::new(HashMap::new());
static NEXT_WATCH_ID: Cell<u32> = const { Cell::new(1) };
}
pub fn mount_scene(
canvas: web_sys::HtmlCanvasElement,
layout_json: &str,
mut on_select: impl FnMut(String, Vec<String>) + 'static,
) -> u32 {
let cb = Closure::wrap(Box::new(move |label: String, ids_json: String| {
let ids: Vec<String> = serde_json::from_str(&ids_json).unwrap_or_default();
on_select(label, ids);
}) as Box<dyn FnMut(String, String)>);
let id = js_mount_scene(&canvas, layout_json, cb.as_ref().unchecked_ref()).unwrap_or(0);
if id != 0 {
SCENE_CBS.with(|m| {
m.borrow_mut().insert(id, cb);
});
}
id
}
pub fn set_floor(handle: u32, level: i32) {
js_set_floor(handle, level);
}
pub fn set_view_mode(handle: u32, mode: &str) {
js_set_view_mode(handle, mode);
}
pub fn reset_scene(handle: u32) {
js_reset_scene(handle);
}
/// Positive deltas zoom in; negative deltas zoom out.
pub fn zoom_scene(handle: u32, delta: f64) {
js_zoom_scene(handle, delta);
}
pub fn highlight_zone(handle: u32, label: &str, photo_ids: &[String]) {
let ids_json = serde_json::to_string(photo_ids).unwrap_or_else(|_| "[]".to_string());
js_highlight_zone(handle, label, &ids_json);
}
/// Observe initial mount failures and later context loss without replacing the canvas.
pub fn watch_scene(
canvas: web_sys::HtmlCanvasElement,
mut on_state: impl FnMut(Option<String>) + 'static,
) -> Option<u32> {
let read_error = |canvas: &web_sys::HtmlCanvasElement| {
canvas
.get_attribute("data-scene-error")
.filter(|message| !message.is_empty())
};
on_state(read_error(&canvas));
let observed_canvas = canvas.clone();
let callback = Closure::wrap(Box::new(move |_: web_sys::Event| {
on_state(read_error(&observed_canvas));
}) as Box<dyn FnMut(web_sys::Event)>);
canvas
.add_event_listener_with_callback("scene-error", callback.as_ref().unchecked_ref())
.ok()?;
if canvas
.add_event_listener_with_callback("scene-ready", callback.as_ref().unchecked_ref())
.is_err()
{
let _ = canvas.remove_event_listener_with_callback(
"scene-error",
callback.as_ref().unchecked_ref(),
);
return None;
}
let id = NEXT_WATCH_ID.with(|next| {
let id = next.get();
next.set(id + 1);
id
});
SCENE_WATCHES.with(|watches| {
watches
.borrow_mut()
.insert(id, SceneWatch { canvas, callback });
});
Some(id)
}
pub fn unwatch_scene(id: u32) {
SCENE_WATCHES.with(|watches| {
if let Some(watch) = watches.borrow_mut().remove(&id) {
let _ = watch.canvas.remove_event_listener_with_callback(
"scene-error",
watch.callback.as_ref().unchecked_ref(),
);
let _ = watch.canvas.remove_event_listener_with_callback(
"scene-ready",
watch.callback.as_ref().unchecked_ref(),
);
}
});
}
pub fn dispose_scene(handle: u32) {
js_dispose_scene(handle);
SCENE_CBS.with(|m| {
m.borrow_mut().remove(&handle);
});
}
pub fn subscribe_job_events(
job_id: &str,
mut on_event: impl FnMut(JobEvent) + 'static,
) -> Option<u32> {
let url = format!("/api/jobs/{job_id}/events");
let es = match web_sys::EventSource::new(&url) {
Ok(es) => es,
Err(_) => {
on_event(JobEvent::Error {
message:
"분석 진행 상태에 연결할 수 없습니다. 연결을 확인하고 다시 시도해 주세요."
.to_string(),
});
return None;
}
};
let on_event = Rc::new(RefCell::new(on_event));
let failures = Rc::new(Cell::new(0_u8));
let terminal = Rc::new(Cell::new(false));
let es_clone = es.clone();
let message_callback = on_event.clone();
let message_failures = failures.clone();
let message_terminal = terminal.clone();
let on_msg = Closure::wrap(Box::new(move |e: web_sys::MessageEvent| {
if message_terminal.get() {
return;
}
if let Some(txt) = e.data().as_string() {
if let Ok(ev) = serde_json::from_str::<JobEvent>(&txt) {
message_failures.set(0);
let done = ev.is_terminal();
if done {
message_terminal.set(true);
es_clone.set_onmessage(None);
es_clone.set_onerror(None);
es_clone.close();
}
(message_callback.borrow_mut())(ev);
}
}
}) as Box<dyn FnMut(web_sys::MessageEvent)>);
let error_es = es.clone();
let on_error = Closure::wrap(Box::new(move |_: web_sys::Event| {
if terminal.get() {
return;
}
failures.set(failures.get().saturating_add(1));
// EventSource handles a short transient disconnect itself. Bound reconnect attempts
// so a permanently unavailable stream cannot leave the UI in a loading state.
if error_es.ready_state() == web_sys::EventSource::CLOSED || failures.get() >= 4 {
terminal.set(true);
error_es.set_onmessage(None);
error_es.set_onerror(None);
error_es.close();
(on_event.borrow_mut())(JobEvent::Error {
message: "분석 상태 연결이 끊겼습니다. 잠시 후 결과를 새로고침해 주세요."
.to_string(),
});
}
}) as Box<dyn FnMut(web_sys::Event)>);
es.set_onmessage(Some(on_msg.as_ref().unchecked_ref()));
es.set_onerror(Some(on_error.as_ref().unchecked_ref()));
let id = NEXT_SSE_ID.with(|n| {
let mut b = n.borrow_mut();
let v = *b;
*b += 1;
v
});
SSE_MAP.with(|m| {
m.borrow_mut().insert(
id,
SseEntry {
es,
_on_msg: on_msg,
_on_error: on_error,
},
);
});
Some(id)
}
pub fn close_job_events(id: u32) {
SSE_MAP.with(|m| {
if let Some(entry) = m.borrow_mut().remove(&id) {
entry.es.set_onmessage(None);
entry.es.set_onerror(None);
entry.es.close();
}
});
}
}
#[cfg(feature = "hydrate")]
pub use imp::*;
#[cfg(not(feature = "hydrate"))]
pub fn subscribe_job_events(
_job_id: &str,
_on_event: impl FnMut(JobEvent) + 'static,
) -> Option<u32> {
None
}
#[cfg(not(feature = "hydrate"))]
pub fn close_job_events(_id: u32) {}
+124
View File
@@ -0,0 +1,124 @@
//! UI-only browser operations; SSR uses inert counterparts.
#[cfg(feature = "hydrate")]
mod imp {
use std::{cell::RefCell, collections::HashMap};
use wasm_bindgen::{closure::Closure, prelude::*, JsCast};
#[wasm_bindgen(module = "/js/ui.js")]
extern "C" {
#[wasm_bindgen(js_name = saveScroll)]
fn js_save_scroll(key: &str);
#[wasm_bindgen(js_name = restoreScroll)]
fn js_restore_scroll(key: &str);
#[wasm_bindgen(js_name = focusSearch)]
fn js_focus_search();
#[wasm_bindgen(js_name = blurActive)]
fn js_blur_active();
#[wasm_bindgen(js_name = closeMenu)]
fn js_close_menu(id: &str);
#[wasm_bindgen(js_name = clearJobQuery)]
fn js_clear_job_query();
#[wasm_bindgen(js_name = revealSelectedPhoto)]
fn js_reveal_selected_photo();
#[wasm_bindgen(js_name = isCompact)]
fn js_is_compact() -> bool;
#[wasm_bindgen(js_name = watchCompact)]
fn js_watch_compact(callback: &js_sys::Function) -> u32;
#[wasm_bindgen(js_name = releaseWatch)]
fn js_release_watch(handle: u32);
#[wasm_bindgen(js_name = openDialog)]
fn js_open_dialog(id: &str, callback: &js_sys::Function) -> u32;
#[wasm_bindgen(js_name = closeDialog)]
fn js_close_dialog(id: &str);
#[wasm_bindgen(js_name = releaseDialog)]
fn js_release_dialog(handle: u32);
#[wasm_bindgen(js_name = copyText)]
fn js_copy_text(value: &str, callback: &js_sys::Function);
}
thread_local! {
static DIALOG_CALLBACKS: RefCell<HashMap<u32, Closure<dyn FnMut()>>> = RefCell::new(HashMap::new());
static WATCH_CALLBACKS: RefCell<HashMap<u32, Closure<dyn FnMut(bool)>>> = RefCell::new(HashMap::new());
}
pub fn save_scroll(key: &str) {
js_save_scroll(key);
}
pub fn restore_scroll(key: &str) {
js_restore_scroll(key);
}
pub fn focus_search() {
js_focus_search();
}
pub fn blur_active() {
js_blur_active();
}
pub fn close_menu(id: &str) {
js_close_menu(id);
}
pub fn clear_job_query() {
js_clear_job_query();
}
pub fn reveal_selected_photo() {
js_reveal_selected_photo();
}
pub fn is_compact() -> bool {
js_is_compact()
}
pub fn watch_compact(callback: impl FnMut(bool) + 'static) -> Option<u32> {
let cb = Closure::wrap(Box::new(callback) as Box<dyn FnMut(bool)>);
let id = js_watch_compact(cb.as_ref().unchecked_ref());
WATCH_CALLBACKS.with(|map| map.borrow_mut().insert(id, cb));
Some(id)
}
pub fn release_watch(handle: u32) {
js_release_watch(handle);
WATCH_CALLBACKS.with(|map| map.borrow_mut().remove(&handle));
}
pub fn open_dialog(id: &str, callback: impl FnMut() + 'static) -> Option<u32> {
let cb = Closure::wrap(Box::new(callback) as Box<dyn FnMut()>);
let handle = js_open_dialog(id, cb.as_ref().unchecked_ref());
if handle == 0 {
return None;
}
DIALOG_CALLBACKS.with(|map| map.borrow_mut().insert(handle, cb));
Some(handle)
}
pub fn close_dialog(id: &str) {
js_close_dialog(id);
}
pub fn release_dialog(handle: u32) {
js_release_dialog(handle);
DIALOG_CALLBACKS.with(|map| map.borrow_mut().remove(&handle));
}
pub fn copy_text(value: &str, callback: impl FnOnce(bool) + 'static) {
let cb = Closure::once_into_js(callback);
js_copy_text(value, cb.unchecked_ref());
}
}
#[cfg(feature = "hydrate")]
pub use imp::*;
#[cfg(not(feature = "hydrate"))]
mod imp_ssr {
pub fn save_scroll(_: &str) {}
pub fn restore_scroll(_: &str) {}
pub fn focus_search() {}
pub fn blur_active() {}
pub fn close_menu(_: &str) {}
pub fn clear_job_query() {}
pub fn reveal_selected_photo() {}
pub fn is_compact() -> bool {
false
}
pub fn watch_compact(_: impl FnMut(bool) + 'static) -> Option<u32> {
None
}
pub fn release_watch(_: u32) {}
pub fn open_dialog(_: &str, _: impl FnMut() + 'static) -> Option<u32> {
None
}
pub fn close_dialog(_: &str) {}
pub fn release_dialog(_: u32) {}
pub fn copy_text(_: &str, _: impl FnOnce(bool) + 'static) {}
}
#[cfg(not(feature = "hydrate"))]
pub use imp_ssr::*;
+849
View File
@@ -0,0 +1,849 @@
//! The responsive place workspace keeps the scene and its selection mounted across widths.
use crate::Icon;
#[cfg(feature = "hydrate")]
use crate::{scene_bridge, ui_bridge};
use domain::{Floor, Layout, PhotoKind, PhotoSummary, Tri, ROOFTOP_LEVEL};
use leptos::prelude::*;
#[derive(Clone, Debug)]
struct PhotoSelection {
title: String,
photos: Vec<PhotoSummary>,
zone: Option<(i32, String)>,
}
fn short_floor_label(floor: &Floor) -> String {
let base = match floor.level {
ROOFTOP_LEVEL => "옥상".to_string(),
n if n < 0 => format!("B{}", n.unsigned_abs()),
0 => "층 미확인".to_string(),
n => format!("{n}층"),
};
if floor_is_uncertain(floor) {
format!("{base}(추정)")
} else {
base
}
}
fn floor_is_uncertain(floor: &Floor) -> bool {
let uncertain = |text: &str| {
[
"임시",
"추정",
"미확인",
"확인되지",
"확인 안",
"불명",
"가정",
"가능성",
"알 수 없",
"증거 없",
]
.iter()
.any(|word| text.contains(word))
};
if uncertain(&floor.label) {
return true;
}
floor.notes.split(['.', '。', '\n', ';']).any(|sentence| {
// Uncertain window positions or room dimensions do not make the floor number uncertain.
let floor_assignment = sentence.contains('층')
&& [
"촬영",
"배정",
"층수",
"층 위치",
"층 정보",
"어느 층",
"실제 층",
"층인지",
"상층",
]
.iter()
.any(|word| sentence.contains(word));
floor_assignment && uncertain(sentence)
})
}
/// Replace implementation IDs without removing the surrounding evidence or warnings.
fn readable_evidence(text: &str, photos: &[PhotoSummary]) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while !rest.is_empty() {
if rest.starts_with("p_") {
let end = rest
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
.unwrap_or(rest.len());
let token = &rest[..end];
if token.len() > 2 {
if let Some(photo) = photos.iter().find(|p| p.id == token) {
out.push_str(&format!("{} 참고 사진", photo.source.label()));
} else {
out.push_str("참고 사진");
}
rest = &rest[end..];
continue;
}
}
let ch = rest.chars().next().expect("nonempty text");
out.push(ch);
rest = &rest[ch.len_utf8()..];
}
out
}
fn unique_text(items: Vec<String>, photos: &[PhotoSummary]) -> Vec<String> {
let mut seen = std::collections::HashSet::new();
items
.into_iter()
.map(|s| readable_evidence(s.trim(), photos))
.filter(|s| !s.is_empty())
.filter(|s| {
let key: String = s
.chars()
.filter(|c| !c.is_whitespace() && !matches!(c, '·' | ',' | '.' | '-'))
.flat_map(char::to_lowercase)
.collect();
seen.insert(key)
})
.collect()
}
fn brief(text: &str, max: usize) -> String {
if text.chars().count() <= max {
text.to_string()
} else {
format!("{}…", text.chars().take(max).collect::<String>().trim_end())
}
}
fn photo_caption(photo: &PhotoSummary) -> String {
if !photo.description.trim().is_empty() {
photo.description.clone()
} else if !photo.caption.trim().is_empty() {
photo.caption.clone()
} else {
match photo.kind {
Some(PhotoKind::Exterior) => "건물 외관 사진".to_string(),
Some(PhotoKind::Interior) => "공간 내부 사진".to_string(),
_ => "공간 확인에 사용된 사진".to_string(),
}
}
}
fn source_url(photo: &PhotoSummary) -> Option<String> {
(photo.page_url.starts_with("https://") || photo.page_url.starts_with("http://"))
.then(|| photo.page_url.clone())
}
fn accessibility_label(value: Tri) -> &'static str {
match value {
Tri::Unknown => "미확인",
Tri::Likely => "있을 가능성 · 확인 필요",
Tri::Yes => "있음",
Tri::No => "없음",
}
}
#[component]
fn PhotoImage(
photo: PhotoSummary,
#[prop(default = "lazy")] loading: &'static str,
) -> impl IntoView {
let (failed, set_failed) = signal(false);
let alt = brief(&photo_caption(&photo), 120);
view! {
<div class="image-shell">
<img
src=format!("/api/photos/{}", photo.id)
alt=alt
loading=loading
decoding="async"
hidden=move || failed.get()
on:error=move |_| set_failed.set(true)
/>
<span class="image-fallback" hidden=move || !failed.get()>
<Icon name="photo"/>"사진을 불러오지 못했습니다."
</span>
</div>
}
}
#[component]
fn PhotoCaption(photo: PhotoSummary) -> impl IntoView {
let caption = photo_caption(&photo);
let has_more = caption.chars().count() > 90;
view! {
<div class="photo-caption">
<p>{brief(&caption, 90)}</p>
{has_more.then(|| view! {
<details class="photo-description">
<summary>"설명 더 보기"</summary>
<p>{caption}</p>
</details>
})}
{match source_url(&photo) {
Some(url) => view! {
<a class="photo-source" href=url target="_blank" rel="noopener noreferrer">
{format!("원문 보기 · {}", photo.source.label())}
<span class="sr-only">" (새 탭)"</span>
</a>
}.into_any(),
None => view! { <span class="photo-source">{photo.source.label()}</span> }.into_any(),
}}
</div>
}
}
#[component]
pub(crate) fn WorkspaceView(layout: Layout, photos: Vec<PhotoSummary>) -> impl IntoView {
let (active_floor, set_active_floor) = signal(0i32);
let (view_mode, set_view_mode) = signal("iso");
let (mobile_panel, set_mobile_panel) = signal("layout");
let (scene_interactive, set_scene_interactive) = signal(false);
let (scene_error, set_scene_error) = signal(Option::<String>::None);
let (scene_retry, set_scene_retry) = signal(0u32);
let (scene_fullscreen, set_scene_fullscreen) = signal(false);
let (selection, set_selection) = signal(Option::<PhotoSelection>::None);
let (photo_index, set_photo_index) = signal(0usize);
let (photo_open, set_photo_open) = signal(false);
let canvas_ref = NodeRef::<leptos::html::Canvas>::new();
let clean_photos = photos
.iter()
.cloned()
.map(|mut p| {
p.description = readable_evidence(&p.description, &photos);
p.caption = readable_evidence(&p.caption, &photos);
p
})
.collect::<Vec<_>>();
let photo_store = StoredValue::new(clean_photos.clone());
let floor_store = StoredValue::new(layout.floors.clone());
let interior_photos = clean_photos
.iter()
.filter(|p| {
matches!(
p.kind,
Some(PhotoKind::Interior | PhotoKind::Exterior) | None
)
})
.cloned()
.collect::<Vec<_>>();
let gallery_store = StoredValue::new(interior_photos.clone());
let choose_zone = Callback::new(move |(level, label, ids): (i32, String, Vec<String>)| {
let photos = photo_store.with_value(|all| {
all.iter()
.filter(|p| ids.contains(&p.id))
.cloned()
.collect::<Vec<_>>()
});
set_selection.set(Some(PhotoSelection {
title: label.clone(),
photos,
zone: Some((level, label)),
}));
set_photo_index.set(0);
#[cfg(feature = "hydrate")]
{
if ui_bridge::is_compact() || scene_fullscreen.get_untracked() {
set_photo_open.set(true);
} else {
ui_bridge::reveal_selected_photo();
}
}
});
let choose_floor = Callback::new(move |level: i32| {
set_active_floor.set(level);
let keep = selection.with_untracked(|current| {
current
.as_ref()
.and_then(|s| s.zone.as_ref())
.is_none_or(|(selected_level, _)| level == 0 || *selected_level == level)
});
if !keep {
set_selection.set(None);
set_photo_open.set(false);
}
});
let show_gallery = Callback::new(move |index: usize| {
set_selection.set(Some(PhotoSelection {
title: "공간 사진".into(),
photos: gallery_store.get_value(),
zone: None,
}));
set_photo_index.set(index);
set_photo_open.set(true);
});
#[cfg(feature = "hydrate")]
let (scene_id, set_scene_id) = signal(Option::<u32>::None);
#[cfg(feature = "hydrate")]
{
let layout_json = serde_json::to_string(&layout).unwrap_or_default();
Effect::new(move |_| {
let _ = scene_retry.get();
let Some(canvas) = canvas_ref.get() else {
return;
};
set_scene_error.set(None);
let id = scene_bridge::mount_scene(canvas.clone(), &layout_json, move |label, ids| {
let level = floor_store.with_value(|floors| {
floors
.iter()
.filter(|f| {
active_floor.get_untracked() == 0
|| f.level == active_floor.get_untracked()
})
.find(|f| {
f.zones
.iter()
.any(|z| z.label == label && z.evidence_photos == ids)
})
.or_else(|| {
floors
.iter()
.find(|f| f.zones.iter().any(|z| z.label == label))
})
.map_or(0, |f| f.level)
});
choose_zone.run((level, label, ids));
});
if id == 0 {
set_scene_error.set(Some("공간 화면을 불러오지 못했습니다.".into()));
set_scene_id.set(None);
} else {
set_scene_id.set(Some(id));
// These are untracked so changing a control does not recreate the renderer.
scene_bridge::set_floor(id, active_floor.get_untracked());
scene_bridge::set_view_mode(id, view_mode.get_untracked());
}
let watch = scene_bridge::watch_scene(canvas, move |error| set_scene_error.set(error));
on_cleanup(move || {
if let Some(watch) = watch {
scene_bridge::unwatch_scene(watch);
}
if id != 0 {
scene_bridge::dispose_scene(id);
}
});
});
Effect::new(move |_| {
let level = active_floor.get();
if let Some(id) = scene_id.get() {
scene_bridge::set_floor(id, level);
}
});
Effect::new(move |_| {
let mode = view_mode.get();
if let Some(id) = scene_id.get() {
scene_bridge::set_view_mode(id, mode);
}
});
Effect::new(move |_| {
let current = selection.get();
if let Some(id) = scene_id.get() {
if let Some(s) = current.filter(|s| s.zone.is_some()) {
let ids = s.photos.iter().map(|p| p.id.clone()).collect::<Vec<_>>();
scene_bridge::highlight_zone(id, &s.title, &ids);
} else {
scene_bridge::highlight_zone(id, "", &[]);
}
}
});
let photo_handle = StoredValue::new(None::<u32>);
Effect::new(move |_| {
if photo_open.get() {
if photo_handle.get_value().is_none() {
let handle = ui_bridge::open_dialog("space-photo-dialog", move || {
set_photo_open.set(false)
});
photo_handle.set_value(handle);
}
} else if let Some(handle) = photo_handle.get_value() {
ui_bridge::close_dialog("space-photo-dialog");
ui_bridge::release_dialog(handle);
photo_handle.set_value(None);
}
});
let scene_handle = StoredValue::new(None::<u32>);
Effect::new(move |_| {
if scene_fullscreen.get() {
if scene_handle.get_value().is_none() {
let handle = ui_bridge::open_dialog("space-scene-dialog", move || {
set_scene_fullscreen.set(false)
});
scene_handle.set_value(handle);
}
} else if let Some(handle) = scene_handle.get_value() {
ui_bridge::close_dialog("space-scene-dialog");
ui_bridge::release_dialog(handle);
scene_handle.set_value(None);
}
});
let resize_watch = ui_bridge::watch_compact(move |compact| {
if !compact
&& !scene_fullscreen.get_untracked()
&& selection.with_untracked(|s| s.as_ref().is_some_and(|s| s.zone.is_some()))
{
set_photo_open.set(false);
}
});
on_cleanup(move || {
if let Some(handle) = photo_handle.get_value() {
ui_bridge::release_dialog(handle);
}
if let Some(handle) = scene_handle.get_value() {
ui_bridge::release_dialog(handle);
}
if let Some(handle) = resize_watch {
ui_bridge::release_watch(handle);
}
});
}
#[cfg(not(feature = "hydrate"))]
let _ = (
scene_retry,
set_scene_error,
photo_open,
scene_fullscreen,
floor_store,
);
let floors_for_tabs = layout.floors.clone();
let floors_for_notes = layout.floors.clone();
let many_floors = floors_for_tabs.len() > 4;
let caveats = unique_text(layout.summary.caveats.clone(), &photos);
let all_evidence = format!(
"{} {}",
caveats.join(" "),
layout
.floors
.iter()
.map(|f| f.notes.as_str())
.collect::<Vec<_>>()
.join(" ")
);
let uncertain_branch = [
"다른 지점",
"타 지점",
"타지점",
"지점 혼",
"지점 불일치",
"지점이 불명",
]
.iter()
.any(|s| all_evidence.contains(s));
let uncertain_floor = layout.floors.iter().any(floor_is_uncertain);
let warning = match (uncertain_branch, uncertain_floor) {
(true, true) => "층·지점 정보 확인 필요 · 추정 배치",
(true, false) => "지점 정보 확인 필요 · 추정 배치",
(false, true) => "층 정보 확인 필요 · 추정 배치",
(false, false) => "사진·리뷰로 추정한 배치",
};
let seat_types = unique_text(layout.summary.seat_types.clone(), &photos);
let highlights = unique_text(layout.summary.highlights.clone(), &photos);
let more_highlights = highlights.iter().skip(3).cloned().collect::<Vec<_>>();
let brief_highlights = highlights.iter().take(3).cloned().collect::<Vec<_>>();
let floor_count = layout.floors.len();
let floor_summary = layout
.floors
.iter()
.map(short_floor_label)
.collect::<Vec<_>>()
.join(" · ");
let confidence = if layout.confidence.is_finite() {
format!(
"분석 모델이 보고한 신뢰도 {:.0}%",
layout.confidence.clamp(0.0, 1.0) * 100.0
)
} else {
"분석 모델 신뢰도 미제공".into()
};
let gallery_total = interior_photos.len();
view! {
<div class="workspace-switcher" role="group" aria-label="공간 보기">
<button type="button" aria-controls="layout-panel"
aria-pressed=move || (mobile_panel.get() == "layout").to_string()
on:click=move |_| set_mobile_panel.set("layout")>"공간 배치"</button>
<button type="button" aria-controls="info-panel"
aria-pressed=move || (mobile_panel.get() == "info").to_string()
on:click=move |_| { set_mobile_panel.set("info"); set_scene_interactive.set(false); }>"공간 정보"</button>
</div>
<p class="workspace-warning"><Icon name="info"/>{warning}</p>
<div class="workspace-grid" data-mobile-panel=move || mobile_panel.get()>
<section class="viewport-col" id="layout-panel" aria-label="공간 배치">
<div class="viewport-toolbar">
{if many_floors {
view! {
<label class="floor-select-label"><span class="sr-only">"표시할 층"</span>
<select class="floor-select" prop:value=move || active_floor.get().to_string()
on:change=move |ev| choose_floor.run(event_target_value(&ev).parse().unwrap_or(0))>
<option value="0">"전체 층"</option>
{floors_for_tabs.iter().map(|f| view! {
<option value=f.level.to_string()>{short_floor_label(f)}</option>
}).collect_view()}
</select>
</label>
}.into_any()
} else {
view! {
<div class="floor-tabs" role="group" aria-label="표시할 층">
<button type="button" class="tab" aria-pressed=move || (active_floor.get() == 0).to_string()
on:click=move |_| choose_floor.run(0)>"전체"</button>
{floors_for_tabs.iter().map(|f| {
let level = f.level;
view! {
<button type="button" class="tab" aria-pressed=move || (active_floor.get() == level).to_string()
on:click=move |_| choose_floor.run(level)>{short_floor_label(f)}</button>
}
}).collect_view()}
</div>
}.into_any()
}}
<div class="view-modes" role="group" aria-label="보기 방식">
<button type="button" class="tab" aria-pressed=move || (view_mode.get() == "iso").to_string()
on:click=move |_| set_view_mode.set("iso")>"3D"</button>
<button type="button" class="tab" aria-pressed=move || (view_mode.get() == "plan").to_string()
on:click=move |_| set_view_mode.set("plan")>"평면도"</button>
</div>
</div>
<dialog id="space-scene-dialog" class="scene-dialog" open data-inline-dialog="true"
role=move || if scene_fullscreen.get() { "dialog" } else { "region" }
aria-label="공간 배치 화면">
<div class="scene-dialog-header" hidden=move || !scene_fullscreen.get()>
<strong>{move || if view_mode.get() == "plan" { "평면도" } else { "3D 공간" }}</strong>
<button type="button" class="btn-close" on:click=move |_| set_scene_fullscreen.set(false)>"전체 화면 닫기"<Icon name="close"/></button>
</div>
<div class="canvas-holder" data-scene-failed=move || scene_error.get().is_some().to_string()>
<canvas node_ref=canvas_ref class="scene-canvas"
data-interactive=move || scene_interactive.get().to_string()
aria-label=move || if view_mode.get() == "plan" {
"층별 평면도. 아래 구역 버튼에서도 사진을 확인할 수 있습니다."
} else {
"층별 3D 공간. 아래 구역 버튼에서도 사진을 확인할 수 있습니다."
}></canvas>
<div class="scene-tools" role="group" aria-label="공간 화면 조절" hidden=move || scene_error.get().is_some()>
<button type="button" class="scene-tool" aria-label="확대" title="확대" on:click=move |_| {
#[cfg(feature = "hydrate")]
if let Some(id) = scene_id.get_untracked() { scene_bridge::zoom_scene(id, 1.0); }
}>"+"</button>
<button type="button" class="scene-tool" aria-label="축소" title="축소" on:click=move |_| {
#[cfg(feature = "hydrate")]
if let Some(id) = scene_id.get_untracked() { scene_bridge::zoom_scene(id, -1.0); }
}>"−"</button>
<button type="button" class="scene-tool" aria-label="시점 초기화" title="시점 초기화" on:click=move |_| {
#[cfg(feature = "hydrate")]
if let Some(id) = scene_id.get_untracked() { scene_bridge::reset_scene(id); }
}><Icon name="refresh"/></button>
<button type="button" class="scene-tool scene-expand" aria-label=move || if scene_fullscreen.get() { "전체 화면 닫기" } else { "전체 화면 보기" }
on:click=move |_| set_scene_fullscreen.update(|open| *open = !*open)>
{move || if scene_fullscreen.get() { "축소 보기" } else { "전체 화면" }}
</button>
</div>
<button type="button" class="scene-interaction-toggle"
hidden=move || scene_error.get().is_some()
aria-pressed=move || scene_interactive.get().to_string()
on:click=move |_| set_scene_interactive.update(|active| *active = !*active)>
{move || if scene_interactive.get() { "조작 종료" } else if view_mode.get() == "plan" { "이동·확대" } else { "회전·확대" }}
</button>
<div class="canvas-hint" hidden=move || scene_error.get().is_some()>
<span class="hint-pointer">{move || if view_mode.get() == "plan" {
"드래그로 이동 · 휠로 확대 · 핀으로 사진"
} else { "드래그로 회전 · 휠로 확대 · 핀으로 사진" }}</span>
<span class="hint-touch">{move || match (scene_interactive.get(), view_mode.get()) {
(true, "plan") => "한 손가락 이동 · 두 손가락 확대",
(true, _) => "한 손가락 회전 · 두 손가락 확대·이동",
(false, _) if scene_fullscreen.get() => "핀을 누르면 사진 · 조작 버튼으로 이동·확대",
(false, _) => "핀을 누르면 사진 · 위아래로 화면 스크롤",
}}</span>
</div>
{move || scene_error.get().map(|_| view! {
<div class="scene-failure" role="status">
<strong>"공간 화면을 불러오지 못했습니다."</strong>
<p>"사진과 공간 정보는 계속 확인할 수 있습니다."</p>
<div>
<button type="button" class="btn-secondary" on:click=move |_| set_scene_retry.update(|n| *n += 1)>"다시 불러오기"</button>
<button type="button" class="btn-secondary" on:click=move |_| {
set_scene_fullscreen.set(false);
set_mobile_panel.set("info");
}>"공간 정보 보기"</button>
</div>
</div>
})}
</div>
</dialog>
{move || selection.get().map(|s| view! {
<button type="button" class="selected-zone-mobile" on:click=move |_| set_photo_open.set(true)>
<Icon name="photo"/>
<span>{format!("{} · 사진 {}장", brief(&s.title, 24), s.photos.len())}</span>
<span>"보기"</span>
</button>
})}
<div class="floor-notes" aria-label="층별 구역">
{floors_for_notes.into_iter().map(|floor| {
let level = floor.level;
let notes = readable_evidence(&floor.notes, &photos);
let original_label = readable_evidence(&floor.label, &photos);
let short_label = short_floor_label(&floor);
let show_original = original_label != short_label && original_label != format!("{}F", level);
view! {
<section class="floor-note-card" hidden=move || active_floor.get() != 0 && active_floor.get() != level>
<div class="floor-note-head">
<h3>{short_label}</h3>
<span>{format!("약 {:.0}m × {:.0}m", floor.width_m, floor.depth_m)}</span>
</div>
<div class="zone-chips">
{floor.zones.into_iter().map(|zone| {
let label = zone.label.clone();
let label_for_selected = label.clone();
let ids = zone.evidence_photos;
let has_photos = clean_photos.iter().any(|p| ids.contains(&p.id));
if has_photos {
view! {
<button type="button" class="zone-chip"
aria-pressed=move || selection.with(|s| s.as_ref().and_then(|s| s.zone.as_ref()).is_some_and(|(l, name)| *l == level && name == &label_for_selected)).to_string()
on:click=move |_| choose_zone.run((level, label.clone(), ids.clone()))>
{zone.label}<Icon name="photo"/>
</button>
}.into_any()
} else {
view! { <span class="zone-empty">{zone.label}<span>"사진 없음"</span></span> }.into_any()
}
}).collect_view()}
</div>
{(!notes.is_empty() || show_original).then(|| view! {
<details class="summary-details floor-details">
<summary>"층 정보와 추정 근거"</summary>
{show_original.then(|| view! { <p>{original_label}</p> })}
{(!notes.is_empty()).then(|| view! { <p>{notes}</p> })}
<p class="confidence-explanation">{format!("분석 모델이 보고한 층 신뢰도 {:.0}%. 실제 정확도를 검증한 확률은 아닙니다.", floor.confidence.clamp(0.0, 1.0) * 100.0)}</p>
</details>
})}
</section>
}
}).collect_view()}
</div>
</section>
<aside class="summary-col" id="info-panel" aria-label="공간 정보">
{move || selection.get().map(|s| {
let total = s.photos.len();
let selected_photos = StoredValue::new(s.photos.clone());
view! {
<section class="summary-card selected-zone-panel" aria-label="선택한 구역 사진">
<div class="pin-drawer-head">
<h3>{s.title.clone()}</h3>
<button type="button" class="btn-close" aria-label="선택한 사진 닫기" on:click=move |_| set_selection.set(None)><Icon name="close"/></button>
</div>
<p class="photo-count">{format!("사진 {}장", total)}</p>
<button type="button" class="selected-photo-preview" aria-label="선택한 사진 크게 보기" hidden=total == 0 on:click=move |_| set_photo_open.set(true)>
{move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|p| view! { <PhotoImage photo=p loading="eager"/> })}
</button>
{move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|p| view! { <PhotoCaption photo=p/> })}
{(total > 1).then(|| view! {
<div class="photo-navigation">
<button type="button" class="btn-secondary" disabled=move || photo_index.get() == 0 on:click=move |_| set_photo_index.update(|n| *n = n.saturating_sub(1))>"이전"</button>
<span>{move || format!("{} / {}", photo_index.get() + 1, total)}</span>
<button type="button" class="btn-secondary" disabled=move || { photo_index.get() + 1 >= total } on:click=move |_| set_photo_index.update(|n| *n = (*n + 1).min(total.saturating_sub(1)))>"다음"</button>
</div>
})}
{(total == 0).then(|| view! { <p class="photo-empty">"이 구역에 연결된 사진이 없습니다."</p> })}
</section>
}
})}
<section class="summary-card">
<h3>"공간 정보"</h3>
<div class="metric-grid">
<div class="metric"><span class="metric-label">"추정 면적"</span>
<strong class="metric-val">{if layout.summary.area_pyeong_max > 0.0 {
format!("약 {:.0}~{:.0}평", layout.summary.area_pyeong_min, layout.summary.area_pyeong_max)
} else { "미확인".into() }}</strong>
</div>
<div class="metric"><span class="metric-label">"추정 좌석 수"</span>
<strong class="metric-val">{if layout.summary.seat_estimate > 0 {
format!("약 {}석", layout.summary.seat_estimate)
} else { "미확인".into() }}</strong>
</div>
</div>
<div class="summary-floor-count"><strong>{format!("추정 {}개 층", floor_count)}</strong><span>{floor_summary}</span></div>
<div class="summary-section">
<h4>"확인할 정보"</h4>
<p class="evidence-warning">{warning}"입니다. 실제 배치와 다를 수 있습니다."</p>
<details class="summary-details">
<summary>"참고사항과 분석 근거"</summary>
{(!caveats.is_empty()).then(|| view! {
<ul class="bullet-list">{caveats.into_iter().map(|c| view! { <li>{c}</li> }).collect_view()}</ul>
})}
<p>{confidence}</p>
<p class="confidence-explanation">"이 수치는 분석 모델의 자체 평가입니다. 현장 실측으로 보정한 정확도나 실제 배치가 맞을 확률이 아닙니다."</p>
</details>
</div>
{(!seat_types.is_empty()).then(|| view! {
<div class="summary-section"><h4>"좌석 구성 · 전체 층"</h4>
<div class="tag-row">{seat_types.into_iter().map(|s| view! { <span class="badge">{s}</span> }).collect_view()}</div>
</div>
})}
<div class="summary-section">
<h4>"접근성"</h4>
<dl class="fact-list">
<div><dt>"엘리베이터"</dt><dd>{accessibility_label(layout.summary.accessibility.elevator)}</dd></div>
<div><dt>"무단차 출입구"</dt><dd>{accessibility_label(layout.summary.accessibility.step_free_entrance)}</dd></div>
</dl>
<p class="accessibility-note">"미확인은 시설이 없다는 뜻이 아닙니다. 방문 전 장소에 확인해 주세요."</p>
</div>
{(!brief_highlights.is_empty()).then(|| view! {
<div class="summary-section"><h4>"공간 특징"</h4>
<ul class="bullet-list">{brief_highlights.into_iter().map(|h| view! { <li>{brief(&h, 100)}</li> }).collect_view()}</ul>
{(!more_highlights.is_empty() || highlights.iter().any(|h| h.chars().count() > 100)).then(|| view! {
<details class="summary-details"><summary>"특징 전체 보기"</summary>
<ul class="bullet-list">{highlights.into_iter().map(|h| view! { <li>{h}</li> }).collect_view()}</ul>
</details>
})}
</div>
})}
</section>
{(gallery_total > 0).then(|| view! {
<section class="summary-card gallery-card">
<div class="gallery-heading"><h3>"공간 사진"</h3><span>{format!("{}장", gallery_total)}</span></div>
<div class="gallery-grid">
{interior_photos.into_iter().take(6).enumerate().map(|(index, photo)| {
let source = photo.source.label();
view! {
<button type="button" class="gallery-item" aria-label=format!("공간 사진 {} 크게 보기", index + 1)
on:click=move |_| show_gallery.run(index)>
<PhotoImage photo=photo/>
<span class="gallery-source">{source}</span>
</button>
}
}).collect_view()}
</div>
{(gallery_total > 6).then(|| view! {
<button type="button" class="gallery-all btn-secondary" on:click=move |_| show_gallery.run(0)>{format!("사진 {}장 모두 보기", gallery_total)}</button>
})}
</section>
})}
</aside>
</div>
<dialog id="space-photo-dialog" class="photo-dialog" aria-labelledby="space-photo-title"
on:keydown=move |ev| {
if ev.key() == "ArrowLeft" {
ev.prevent_default();
set_photo_index.update(|n| *n = n.saturating_sub(1));
}
if ev.key() == "ArrowRight" {
ev.prevent_default();
let count = selection.with_untracked(|s| s.as_ref().map_or(0, |s| s.photos.len()));
set_photo_index.update(|n| *n = (*n + 1).min(count.saturating_sub(1)));
}
}>
<div class="dialog-header">
<h2 id="space-photo-title">{move || selection.get().map_or_else(|| "공간 사진".into(), |s| s.title)}</h2>
<button type="button" class="btn-close" aria-label="사진 닫기" on:click=move |_| set_photo_open.set(false)>"닫기"<Icon name="close"/></button>
</div>
<div class="photo-dialog-body">
{move || selection.get().map(|s| {
let total = s.photos.len();
let selected_photos = StoredValue::new(s.photos.clone());
view! {
{move || selected_photos.with_value(|photos| photos.get(photo_index.get()).cloned()).map(|photo| view! {
<div class="photo-viewer"><PhotoImage photo=photo.clone() loading="eager"/></div>
<PhotoCaption photo=photo/>
})}
{(total > 0).then(|| view! {
<div class="photo-navigation">
<button type="button" class="btn-secondary" aria-label="이전 사진" disabled=move || photo_index.get() == 0
on:click=move |_| set_photo_index.update(|n| *n = n.saturating_sub(1))>"이전"</button>
<span role="status" aria-live="polite">{move || format!("{} / {}", photo_index.get() + 1, total)}</span>
<button type="button" class="btn-secondary" aria-label="다음 사진" disabled=move || { photo_index.get() + 1 >= total }
on:click=move |_| set_photo_index.update(|n| *n = (*n + 1).min(total.saturating_sub(1)))>"다음"</button>
</div>
})}
{(total > 1).then(|| view! {
<div class="photo-thumbnails" role="group" aria-label="사진 선택">
{s.photos.into_iter().enumerate().map(|(i, photo)| view! {
<button type="button" aria-label=format!("{}번째 사진", i + 1) aria-pressed=move || (i == photo_index.get()).to_string()
on:click=move |_| set_photo_index.set(i)><PhotoImage photo=photo/></button>
}).collect_view()}
</div>
})}
{(total == 0).then(|| view! { <p class="photo-empty">"이 구역에 연결된 사진이 없습니다."</p> })}
}
})}
</div>
</dialog>
}
}
#[cfg(test)]
mod tests {
use super::*;
fn floor(label: &str, notes: &str, level: i32) -> Floor {
Floor {
level,
label: label.into(),
confidence: 0.5,
width_m: 10.0,
depth_m: 8.0,
openings: vec![],
zones: vec![],
verticals: vec![],
notes: notes.into(),
}
}
#[test]
fn floor_labels_distinguish_assignment_from_dimension_uncertainty() {
assert_eq!(
short_floor_label(&floor("1층", "치수와 방위는 가정입니다.", 1)),
"1층"
);
assert_eq!(
short_floor_label(&floor("상층 좌석 공간 · 2층으로 임시 배정", "", 2)),
"2층(추정)"
);
assert_eq!(
short_floor_label(&floor("2층", "사진의 촬영 층은 미확인입니다.", 2)),
"2층(추정)"
);
assert_eq!(short_floor_label(&floor("지하", "", -1)), "B1");
assert_eq!(
short_floor_label(&floor("루프탑", "", ROOFTOP_LEVEL)),
"옥상"
);
}
#[test]
fn evidence_ids_are_replaced_without_losing_caveats() {
let text = "p_ab123, p_other: 다른 지점 사진일 가능성이 있어 층은 미확인.";
assert_eq!(
readable_evidence(text, &[]),
"참고 사진, 참고 사진: 다른 지점 사진일 가능성이 있어 층은 미확인."
);
}
#[test]
fn equivalent_tags_are_not_repeated() {
assert_eq!(
unique_text(
vec!["바 좌석".into(), "바좌석".into(), "소파".into(), "".into()],
&[]
),
vec!["바 좌석", "소파"]
);
}
}
+7
View File
@@ -0,0 +1,7 @@
[package]
name = "domain"
edition.workspace = true
version.workspace = true
[dependencies]
serde = { workspace = true }
+174
View File
@@ -0,0 +1,174 @@
//! Layout JSON: the central artifact rendered by three.js.
//!
//! Coordinate system per floor (meters): origin at the south-west corner,
//! `x` grows east (0..width_m), `y` grows north (0..depth_m).
//! The street/entrance side is conventionally south.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Layout {
pub place_id: String,
pub generated_at: String,
pub model: String,
pub confidence: f32,
pub floors: Vec<Floor>,
pub summary: Summary,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Floor {
pub level: i32,
pub label: String,
pub confidence: f32,
pub width_m: f32,
pub depth_m: f32,
pub openings: Vec<Opening>,
pub zones: Vec<Zone>,
pub verticals: Vec<Vertical>,
pub notes: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Wall {
North,
South,
East,
West,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OpeningKind {
Entrance,
Window,
Door,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Opening {
pub kind: OpeningKind,
pub wall: Wall,
/// Distance from the wall's start (west end for N/S walls, south end for E/W walls).
pub offset_m: f32,
pub length_m: f32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ZoneKind {
Seating,
Counter,
Bar,
Kitchen,
Restroom,
Terrace,
Entrance,
Other,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Zone {
pub kind: ZoneKind,
pub label: String,
pub x: f32,
pub y: f32,
pub w: f32,
pub d: f32,
pub furniture: Vec<FurnitureGroup>,
pub evidence_photos: Vec<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum FurnitureKind {
Table2,
Table4,
Table6,
CommunalTable,
BarSeat,
Sofa,
CounterBar,
Plant,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Arrangement {
Grid,
AlongWall,
Row,
Cluster,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FurnitureGroup {
pub kind: FurnitureKind,
pub count: u32,
pub arrangement: Arrangement,
pub along_wall: Option<Wall>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum VerticalKind {
Stairs,
Elevator,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Vertical {
pub kind: VerticalKind,
pub x: f32,
pub y: f32,
pub w: f32,
pub d: f32,
pub to_level: i32,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Tri {
Yes,
Likely,
No,
Unknown,
}
impl Tri {
pub fn label(&self) -> &'static str {
match self {
Tri::Yes => "있음",
Tri::Likely => "있을 가능성 높음",
Tri::No => "없음",
Tri::Unknown => "확인 안 됨",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Accessibility {
pub elevator: Tri,
pub step_free_entrance: Tri,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Summary {
pub area_pyeong_min: f32,
pub area_pyeong_max: f32,
pub seat_estimate: u32,
pub seat_types: Vec<String>,
pub highlights: Vec<String>,
pub accessibility: Accessibility,
pub caveats: Vec<String>,
}
/// Everything the place page needs in one round-trip.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlaceView {
pub place: crate::Place,
pub layout: Option<Layout>,
pub photos: Vec<crate::PhotoSummary>,
pub running_job: Option<String>,
}
+63
View File
@@ -0,0 +1,63 @@
//! Shared domain types. Compiles for both native (server) and wasm32 (hydrate),
//! so keep dependencies limited to `serde`.
mod layout;
mod photo;
mod place;
pub use layout::*;
pub use photo::*;
pub use place::*;
use serde::{Deserialize, Serialize};
/// Progress events streamed to the browser over SSE while a place is analyzed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum JobEvent {
Started { place_id: String },
PlaceResolved { name: String, naver_place_id: Option<String> },
SourceDone { source: PhotoSourceId, photos: usize, texts: usize, error: Option<String> },
PhotosStored { stored: usize, duplicates: usize, failed: usize },
Classified { interior: usize, exterior: usize, food: usize, other: usize },
FloorsDetected { floors: Vec<FloorEvidence> },
LayoutDraft { attempt: u32 },
Log { message: String },
Done { place_id: String },
Error { message: String },
}
impl JobEvent {
pub fn is_terminal(&self) -> bool {
matches!(self, JobEvent::Done { .. } | JobEvent::Error { .. })
}
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JobStatus {
Running,
Done,
Failed,
}
/// Aggregated evidence that a given floor exists.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FloorEvidence {
/// 1 = ground floor, 2 = second floor, -1 = B1, 99 = rooftop.
pub level: i32,
pub label: String,
pub score: f32,
pub photo_ids: Vec<String>,
pub text_snippets: Vec<String>,
}
pub const ROOFTOP_LEVEL: i32 = 99;
pub fn floor_label(level: i32) -> String {
match level {
ROOFTOP_LEVEL => "루프탑".to_string(),
l if l < 0 => format!("B{}", -l),
l => format!("{l}F"),
}
}
+144
View File
@@ -0,0 +1,144 @@
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PhotoSourceId {
NaverPlace,
NaverBlog,
KakaoPlace,
GoogleMaps,
Instagram,
User,
}
impl PhotoSourceId {
pub fn label(&self) -> &'static str {
match self {
Self::NaverPlace => "네이버 플레이스",
Self::NaverBlog => "네이버 블로그",
Self::KakaoPlace => "카카오맵",
Self::GoogleMaps => "구글 지도",
Self::Instagram => "인스타그램",
Self::User => "사용자 업로드",
}
}
}
/// A photo reference returned by a source before download.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RawPhoto {
pub source: PhotoSourceId,
/// Direct image URL.
pub image_url: String,
/// Page where the image was found (for attribution).
pub page_url: String,
/// Text directly associated with the image (alt, caption, nearby paragraph).
pub caption: String,
/// Referer header required by some CDNs (e.g. postfiles.pstatic.net).
pub referer: Option<String>,
}
/// Free text found by a source (blog body, place description, reviews).
/// Used as evidence for floors / seating.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TextSnippet {
pub source: PhotoSourceId,
pub url: String,
pub text: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct SourceOutput {
pub photos: Vec<RawPhoto>,
pub texts: Vec<TextSnippet>,
}
/// Stored photo (MongoDB `photos`). Bytes live in MinIO under `object_key`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Photo {
#[serde(rename = "_id")]
pub id: String,
pub place_id: String,
pub source: PhotoSourceId,
pub image_url: String,
pub page_url: String,
pub caption: String,
pub object_key: String,
/// 64-bit difference hash, hex encoded (BSON has no u64).
pub dhash: String,
pub width: u32,
pub height: u32,
pub tag: Option<PhotoTag>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PhotoKind {
Interior,
Exterior,
Food,
Menu,
Person,
Other,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum PhotoZone {
Entrance,
Counter,
Hall,
WindowSide,
Terrace,
Restroom,
Stairs,
Kitchen,
Unknown,
}
/// VLM classification of one photo.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PhotoTag {
pub kind: PhotoKind,
pub zone: PhotoZone,
/// Same convention as `FloorEvidence::level`; `None` = unknown.
pub floor_level: Option<i32>,
pub floor_evidence: String,
pub furniture: Vec<FurnitureCount>,
pub quality: f32,
pub description: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FurnitureCount {
pub kind: crate::FurnitureKind,
pub count: u32,
}
/// Lightweight photo info sent to the UI.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PhotoSummary {
pub id: String,
pub source: PhotoSourceId,
pub page_url: String,
pub caption: String,
pub kind: Option<PhotoKind>,
pub zone: Option<PhotoZone>,
pub floor_level: Option<i32>,
pub description: String,
}
impl From<&Photo> for PhotoSummary {
fn from(p: &Photo) -> Self {
Self {
id: p.id.clone(),
source: p.source,
page_url: p.page_url.clone(),
caption: p.caption.clone(),
kind: p.tag.as_ref().map(|t| t.kind),
zone: p.tag.as_ref().map(|t| t.zone),
floor_level: p.tag.as_ref().and_then(|t| t.floor_level),
description: p.tag.as_ref().map(|t| t.description.clone()).unwrap_or_default(),
}
}
}
+81
View File
@@ -0,0 +1,81 @@
use serde::{Deserialize, Serialize};
/// A search result shown to the user before they confirm the place.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PlaceCandidate {
/// Provider that produced this candidate (`kakao`, `naver`).
pub provider: String,
/// Provider-native id (Kakao place id, Naver place id).
pub provider_id: String,
pub name: String,
pub category: String,
pub address: String,
pub road_address: String,
pub phone: String,
pub lat: f64,
pub lng: f64,
pub place_url: String,
}
impl PlaceCandidate {
/// Stable internal id, e.g. `kakao:12345`.
pub fn place_id(&self) -> String {
format!("{}:{}", self.provider, self.provider_id)
}
}
/// Canonical, normalized place persisted in MongoDB.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Place {
#[serde(rename = "_id")]
pub id: String,
pub kakao_id: Option<String>,
pub naver_place_id: Option<String>,
pub name: String,
pub category: String,
pub address: String,
pub road_address: String,
pub phone: String,
pub lat: f64,
pub lng: f64,
pub place_url: String,
}
/// A saved analysis that can be reopened without starting another analysis job.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RecentPlace {
pub place: Place,
pub analyzed_at: String,
pub last_viewed_at: Option<String>,
pub floor_labels: Vec<String>,
pub seat_estimate: u32,
}
impl Place {
pub fn from_candidate(c: &PlaceCandidate) -> Self {
let (kakao_id, naver_place_id) = match c.provider.as_str() {
"kakao" => (Some(c.provider_id.clone()), None),
"naver" => (None, Some(c.provider_id.clone())),
_ => (None, None),
};
Self {
id: c.place_id(),
kakao_id,
naver_place_id,
name: c.name.clone(),
category: c.category.clone(),
address: c.address.clone(),
road_address: c.road_address.clone(),
phone: c.phone.clone(),
lat: c.lat,
lng: c.lng,
place_url: c.place_url.clone(),
}
}
/// Short region hint (e.g. "성동구 성수동") used to disambiguate web searches.
pub fn region_hint(&self) -> String {
let addr = if self.address.is_empty() { &self.road_address } else { &self.address };
addr.split_whitespace().skip(1).take(2).collect::<Vec<_>>().join(" ")
}
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "llm"
edition.workspace = true
version.workspace = true
[dependencies]
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
base64 = { workspace = true }
tokio = { workspace = true }
+746
View File
@@ -0,0 +1,746 @@
//! OpenAI-compatible chat client with vision input, strict JSON-schema output,
//! weighted multi-provider routing (`strata` / `cpa`), and automatic failover.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use base64::Engine;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// Health probe result for a single configured LLM provider.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProviderHealth {
pub provider: ProviderKind,
pub endpoint: String,
pub model: String,
pub weight: u32,
pub healthy: bool,
pub latency_ms: u64,
pub detail: String,
}
/// Identifier for the underlying LLM inference backend.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderKind {
/// Local/self-hosted Strata inference engine (Niko1221/Strata).
Strata,
/// CLIProxyAPI (`cpa`) OpenAI-compatible proxy.
#[serde(alias = "cliproxy", alias = "cli-proxy")]
Cpa,
/// Fallback for any other custom OpenAI-compatible provider name.
#[serde(untagged)]
Custom(String),
}
impl ProviderKind {
pub fn as_str(&self) -> &str {
match self {
ProviderKind::Strata => "strata",
ProviderKind::Cpa => "cpa",
ProviderKind::Custom(s) => s.as_str(),
}
}
}
impl Default for ProviderKind {
fn default() -> Self {
ProviderKind::Cpa
}
}
/// Configuration for a single weighted LLM capacity provider.
/// Accepts both uppercase env-style keys (`PROVIDER`, `OPENAI_COMPATIBLE_API_ENDPOINT`,
/// `OPENAI_COMPATIBLE_API_KEY`, `MODEL`, `WEIGHT`) and lowercase keys (`provider`,
/// `endpoint`, `api_key`, `model`, `weight`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LlmProviderConfig {
#[serde(default, alias = "PROVIDER", alias = "provider")]
pub provider: ProviderKind,
#[serde(
alias = "OPENAI_COMPATIBLE_API_ENDPOINT",
alias = "endpoint",
alias = "ENDPOINT",
alias = "url"
)]
pub endpoint: String,
#[serde(
default,
alias = "OPENAI_COMPATIBLE_API_KEY",
alias = "api_key",
alias = "API_KEY",
alias = "key",
alias = "KEY"
)]
pub api_key: String,
#[serde(alias = "MODEL", alias = "LLM_MODEL", alias = "model")]
pub model: String,
#[serde(default = "default_weight", alias = "WEIGHT", alias = "weight")]
pub weight: u32,
}
fn default_weight() -> u32 {
1
}
impl LlmProviderConfig {
/// Display tag such as `strata/qwen3.8-flash-next` or `cpa/gpt-6.1-sol`.
pub fn display_model(&self) -> String {
format!("{}/{}", self.provider.as_str(), self.model)
}
fn normalized(mut self) -> Self {
let ep = self.endpoint.trim().trim_end_matches('/');
self.endpoint = ep.strip_suffix("/v1").unwrap_or(ep).to_string();
self.api_key = self.api_key.trim().to_string();
self.model = self.model.trim().to_string();
self
}
}
/// Successful JSON response together with the provider/model that served it.
#[derive(Debug, Clone)]
pub struct ChatJsonOutput<T> {
pub data: T,
pub provider: ProviderKind,
pub model: String,
}
impl<T> ChatJsonOutput<T> {
/// Formatted tag (`{provider}/{model}`) suitable for storing in `Layout.model`.
pub fn model_tag(&self) -> String {
format!("{}/{}", self.provider.as_str(), self.model)
}
}
#[derive(Clone)]
pub struct LlmClient {
client: reqwest::Client,
providers: Arc<Vec<LlmProviderConfig>>,
/// Latest known health flag per provider (`true` = healthy, initialized to `true`).
health_flags: Arc<Vec<AtomicBool>>,
/// Weighted schedule table of indices into `providers` (e.g. `[0, 0, 1]` for weights 2, 1).
schedule: Arc<Vec<usize>>,
cursor: Arc<AtomicUsize>,
/// Primary model name kept for backwards compatibility (`{provider}/{model}`).
pub model: String,
}
/// One part of a multimodal user message.
#[derive(Debug, Clone)]
pub enum Part {
Text(String),
/// Raw image bytes + mime type; sent as a base64 data URL.
Image { bytes: Vec<u8>, mime: String },
}
impl Part {
pub fn text(s: impl Into<String>) -> Self {
Part::Text(s.into())
}
fn to_json(&self) -> Value {
match self {
Part::Text(t) => json!({ "type": "text", "text": t }),
Part::Image { bytes, mime } => {
let b64 = base64::engine::general_purpose::STANDARD.encode(bytes);
json!({ "type": "image_url", "image_url": { "url": format!("data:{mime};base64,{b64}") } })
}
}
}
}
#[derive(Debug, Serialize, Clone)]
struct Message {
role: &'static str,
content: Value,
}
impl LlmClient {
/// Construct a single-provider client (weight = 1).
pub fn new(endpoint: impl Into<String>, key: impl Into<String>, model: impl Into<String>) -> Self {
Self::from_providers(vec![LlmProviderConfig {
provider: ProviderKind::Cpa,
endpoint: endpoint.into(),
api_key: key.into(),
model: model.into(),
weight: 1,
}])
.expect("single provider config is always non-empty")
}
/// Construct a weighted multi-provider client from a list of `LlmProviderConfig`s.
/// Providers with `weight == 0` are kept only as failover backups unless all weights are 0.
pub fn from_providers(configs: Vec<LlmProviderConfig>) -> anyhow::Result<Self> {
let providers: Vec<LlmProviderConfig> = configs
.into_iter()
.map(LlmProviderConfig::normalized)
.filter(|p| !p.endpoint.is_empty() && !p.model.is_empty())
.collect();
if providers.is_empty() {
anyhow::bail!("at least one valid LLM provider must be configured");
}
let schedule = build_interleaved_schedule(&providers);
let primary_idx = schedule.first().copied().unwrap_or(0);
let model = providers[primary_idx].display_model();
let health_flags = providers.iter().map(|_| AtomicBool::new(true)).collect();
Ok(Self {
client: reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(240))
.build()
.expect("reqwest client"),
providers: Arc::new(providers),
health_flags: Arc::new(health_flags),
schedule: Arc::new(schedule),
cursor: Arc::new(AtomicUsize::new(0)),
model,
})
}
/// Parse a JSON array string of `LlmProviderConfig`s.
pub fn from_json_str(raw: &str) -> anyhow::Result<Self> {
let configs: Vec<LlmProviderConfig> = serde_json::from_str(raw.trim())
.map_err(|e| anyhow::anyhow!("invalid LLM_PROVIDERS JSON: {e}"))?;
Self::from_providers(configs)
}
pub fn providers(&self) -> &[LlmProviderConfig] {
&self.providers
}
/// Run provider-specific health checks across all configured LLM providers in parallel
/// and update their internal health flags used by weighted routing:
/// - `strata`: probes `GET {endpoint}/health` (verifies `status == "ok"` and `loaded != false`,
/// with fallback to `GET {endpoint}/v1/models` if `/health` returns 404).
/// - `cpa` (CLIProxyAPI) / custom: probes `GET {endpoint}/v1/models` with Bearer token
/// (verifies HTTP 2xx and checks whether the configured model is registered).
pub async fn health_check_all(&self) -> Vec<ProviderHealth> {
let mut results = Vec::with_capacity(self.providers.len());
for (idx, provider) in self.providers.iter().enumerate() {
let status = self.check_provider_health(provider).await;
self.health_flags[idx].store(status.healthy, Ordering::Relaxed);
results.push(status);
}
results
}
/// Probe a single provider's health according to its `ProviderKind`.
pub async fn check_provider_health(&self, provider: &LlmProviderConfig) -> ProviderHealth {
let started = Instant::now();
let probe_res = match provider.provider {
ProviderKind::Strata => self.probe_strata_health(provider).await,
ProviderKind::Cpa | ProviderKind::Custom(_) => self.probe_cpa_health(provider).await,
};
let latency_ms = started.elapsed().as_millis() as u64;
match probe_res {
Ok(detail) => ProviderHealth {
provider: provider.provider.clone(),
endpoint: provider.endpoint.clone(),
model: provider.model.clone(),
weight: provider.weight,
healthy: true,
latency_ms,
detail,
},
Err(err) => ProviderHealth {
provider: provider.provider.clone(),
endpoint: provider.endpoint.clone(),
model: provider.model.clone(),
weight: provider.weight,
healthy: false,
latency_ms,
detail: err.to_string(),
},
}
}
/// Strata health check:
/// 1. `GET {endpoint}/health` (Strata native endpoint returning `{"status":"ok","loaded":true,"model":...,"images":true}`)
/// 2. Falls back to `/v1/models` if `/health` is not exposed (404).
async fn probe_strata_health(&self, provider: &LlmProviderConfig) -> anyhow::Result<String> {
let url = format!("{}/health", provider.endpoint);
let mut req = self.client.get(&url).timeout(Duration::from_secs(5));
if !provider.api_key.is_empty() {
req = req.bearer_auth(&provider.api_key);
}
let resp = req.send().await.map_err(|e| anyhow::anyhow!("Strata /health unreachable: {e}"))?;
let status = resp.status();
if status == reqwest::StatusCode::NOT_FOUND {
return self.probe_cpa_health(provider).await;
}
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("Strata /health HTTP {status}: {}", truncate(&text, 200));
}
if let Ok(v) = serde_json::from_str::<Value>(&text) {
if let Some(st) = v["status"].as_str() {
if !st.eq_ignore_ascii_case("ok") && !st.eq_ignore_ascii_case("healthy") && !st.eq_ignore_ascii_case("ready") {
anyhow::bail!("Strata status is '{st}': {}", truncate(&text, 200));
}
}
if v["loaded"].as_bool() == Some(false) {
anyhow::bail!("Strata engine running but model not loaded yet (loaded=false)");
}
let engine_model = v["model"].as_str().unwrap_or(&provider.model);
let vision = v["images"].as_bool().map(|b| format!(", images={b}")).unwrap_or_default();
return Ok(format!("Strata ready (model={engine_model}{vision})"));
}
Ok("Strata /health ok".into())
}
/// CLIProxyAPI (`cpa`) health check:
/// Queries `GET {endpoint}/v1/models` with Bearer auth and verifies the model list response.
async fn probe_cpa_health(&self, provider: &LlmProviderConfig) -> anyhow::Result<String> {
let url = format!("{}/v1/models", provider.endpoint);
let mut req = self.client.get(&url).timeout(Duration::from_secs(5));
if !provider.api_key.is_empty() {
req = req.bearer_auth(&provider.api_key);
}
let resp = req.send().await.map_err(|e| {
anyhow::anyhow!("{} /v1/models unreachable: {e}", provider.provider.as_str())
})?;
let status = resp.status();
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!(
"{} /v1/models HTTP {status}: {}",
provider.provider.as_str(),
truncate(&text, 200)
);
}
if let Ok(v) = serde_json::from_str::<Value>(&text) {
if let Some(arr) = v["data"].as_array() {
let ids: Vec<&str> = arr.iter().filter_map(|m| m["id"].as_str()).collect();
if !ids.is_empty() && !ids.iter().any(|&id| id == provider.model) {
return Ok(format!(
"/v1/models ok ({} models online; '{}' not listed in registry, will route directly)",
ids.len(),
provider.model
));
}
return Ok(format!("/v1/models ok ({} models, '{}' available)", ids.len(), provider.model));
}
}
Ok("/v1/models ok".into())
}
/// Pick the ordered list of provider indices to try for the next request:
/// starts with the weighted round-robin winner among currently healthy providers,
/// followed by remaining healthy providers, and finally any unhealthy providers as last-resort failover.
fn pick_provider_order(&self) -> Vec<usize> {
let step = self.cursor.fetch_add(1, Ordering::Relaxed);
let mut healthy_order = Vec::with_capacity(self.providers.len());
let mut unhealthy_order = Vec::new();
// Walk the weighted schedule starting from `step` so the 2:1 ratio is preserved.
for offset in 0..self.schedule.len() {
let idx = self.schedule[(step + offset) % self.schedule.len()];
if self.health_flags[idx].load(Ordering::Relaxed) {
if !healthy_order.contains(&idx) {
healthy_order.push(idx);
}
} else if !unhealthy_order.contains(&idx) {
unhealthy_order.push(idx);
}
}
// Include any 0-weight backup providers not present in `schedule`.
for idx in 0..self.providers.len() {
if self.health_flags[idx].load(Ordering::Relaxed) {
if !healthy_order.contains(&idx) {
healthy_order.push(idx);
}
} else if !unhealthy_order.contains(&idx) {
unhealthy_order.push(idx);
}
}
healthy_order.extend(unhealthy_order);
healthy_order
}
/// Send `system` + multimodal `user` parts and parse the reply into `T`
/// using a strict JSON schema.
pub async fn chat_json<T: DeserializeOwned>(
&self,
system: &str,
user: &[Part],
schema_name: &str,
schema: &Value,
) -> anyhow::Result<T> {
Ok(self
.chat_json_with_meta(system, user, schema_name, schema)
.await?
.data)
}
/// Same as `chat_json`, but also returns which provider (`strata` / `cpa`) and model served the request.
/// Automatically fails over to the next configured provider if the chosen provider fails.
pub async fn chat_json_with_meta<T: DeserializeOwned>(
&self,
system: &str,
user: &[Part],
schema_name: &str,
schema: &Value,
) -> anyhow::Result<ChatJsonOutput<T>> {
let order = self.pick_provider_order();
let mut last_err: Option<anyhow::Error> = None;
for (attempt_idx, &prov_idx) in order.iter().enumerate() {
let provider = &self.providers[prov_idx];
match self
.chat_json_on_provider::<T>(provider, system, user, schema_name, schema)
.await
{
Ok(data) => {
self.health_flags[prov_idx].store(true, Ordering::Relaxed);
return Ok(ChatJsonOutput {
data,
provider: provider.provider.clone(),
model: provider.model.clone(),
});
}
Err(err) => {
self.health_flags[prov_idx].store(false, Ordering::Relaxed);
if attempt_idx + 1 < order.len() {
let next_prov = &self.providers[order[attempt_idx + 1]];
tracing::warn!(
failed_provider = provider.provider.as_str(),
failed_model = %provider.model,
failover_provider = next_prov.provider.as_str(),
failover_model = %next_prov.model,
error = %err,
"LLM provider call failed, failing over to next provider"
);
}
last_err = Some(err);
}
}
}
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("no LLM providers available")))
}
async fn chat_json_on_provider<T: DeserializeOwned>(
&self,
provider: &LlmProviderConfig,
system: &str,
user: &[Part],
schema_name: &str,
schema: &Value,
) -> anyhow::Result<T> {
let messages = vec![
Message {
role: "system",
content: Value::String(system.to_string()),
},
Message {
role: "user",
content: Value::Array(user.iter().map(Part::to_json).collect()),
},
];
let strict = json!({
"type": "json_schema",
"json_schema": { "name": schema_name, "strict": true, "schema": schema }
});
let raw = match self.complete(provider, &messages, Some(strict)).await {
Ok(r) => r,
Err(e) if should_fallback_response_format(&e, &provider.provider) => {
tracing::warn!(
provider = provider.provider.as_str(),
model = %provider.model,
"json_schema unsupported, falling back to json_object / prompt schema: {e}"
);
let mut msgs = messages;
msgs[0].content = Value::String(format!(
"{system}\n\nRespond ONLY with valid JSON matching this schema (no markdown fences, no extra prose):\n{}",
serde_json::to_string(schema)?
));
match self
.complete(provider, &msgs, Some(json!({ "type": "json_object" })))
.await
{
Ok(r) => r,
Err(e2) if should_fallback_response_format(&e2, &provider.provider) => {
self.complete(provider, &msgs, None).await?
}
Err(e2) => return Err(e2),
}
}
Err(e) => return Err(e),
};
let cleaned = strip_fences(&raw);
serde_json::from_str(cleaned).map_err(|e| {
anyhow::anyhow!(
"LLM JSON parse error ({}/{}): {e}; raw: {}",
provider.provider.as_str(),
provider.model,
truncate(&raw, 500)
)
})
}
async fn complete(
&self,
provider: &LlmProviderConfig,
messages: &[Message],
response_format: Option<Value>,
) -> anyhow::Result<String> {
let mut body = json!({
"model": provider.model,
"messages": messages,
});
if let Some(rf) = response_format {
body["response_format"] = rf;
}
let started = std::time::Instant::now();
let mut req = self
.client
.post(format!("{}/v1/chat/completions", provider.endpoint))
.json(&body);
if !provider.api_key.is_empty() {
req = req.bearer_auth(&provider.api_key);
}
let resp = req.send().await?;
let status = resp.status();
let text = resp.text().await?;
if !status.is_success() {
anyhow::bail!(
"LLM HTTP {status} ({}/{}): {}",
provider.provider.as_str(),
provider.model,
truncate(&text, 800)
);
}
let v: Value = serde_json::from_str(&text)?;
let raw_content = v["choices"][0]["message"]["content"]
.as_str()
.ok_or_else(|| {
anyhow::anyhow!(
"LLM response without content ({}/{}): {}",
provider.provider.as_str(),
provider.model,
truncate(&text, 500)
)
})?;
let content = strip_thinking_blocks(raw_content).to_string();
tracing::debug!(
provider = provider.provider.as_str(),
model = %provider.model,
elapsed_ms = started.elapsed().as_millis() as u64,
prompt_tokens = v["usage"]["prompt_tokens"].as_u64(),
completion_tokens = v["usage"]["completion_tokens"].as_u64(),
"llm completion"
);
Ok(content)
}
}
fn should_fallback_response_format(err: &anyhow::Error, provider: &ProviderKind) -> bool {
let msg = err.to_string().to_lowercase();
msg.contains("response_format")
|| msg.contains("json_schema")
|| msg.contains("structured")
|| (matches!(provider, ProviderKind::Strata)
&& (msg.contains("http 400") || msg.contains("http 422") || msg.contains("unsupported")))
}
/// Build a smooth interleaved weighted schedule (Smooth Weighted Round-Robin)
/// so e.g. weights `[2, 1]` produce `[0, 0, 1]` and `[4, 2]` produce `[0, 0, 1]` (reduced by GCD).
fn build_interleaved_schedule(providers: &[LlmProviderConfig]) -> Vec<usize> {
let mut weights: Vec<u32> = providers.iter().map(|p| p.weight.min(100)).collect();
let total: u32 = weights.iter().sum();
if total == 0 {
return (0..providers.len()).collect();
}
let g = weights.iter().copied().fold(0u32, gcd);
if g > 1 {
for w in &mut weights {
*w /= g;
}
}
let total_steps: usize = weights.iter().map(|&w| w as usize).sum();
let total_w = total_steps as i64;
let mut current = vec![0i64; providers.len()];
let mut schedule = Vec::with_capacity(total_steps);
for _ in 0..total_steps {
let mut best_idx = 0;
for (i, &w) in weights.iter().enumerate() {
if w == 0 {
continue;
}
current[i] += w as i64;
if weights[best_idx] == 0 || current[i] > current[best_idx] {
best_idx = i;
}
}
current[best_idx] -= total_w;
schedule.push(best_idx);
}
schedule
}
fn gcd(a: u32, b: u32) -> u32 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
/// Strip `<think>...</think>` blocks that local reasoning/MoE models (e.g. Qwen3.8 on Strata) may emit.
fn strip_thinking_blocks(s: &str) -> &str {
let mut rest = s.trim();
while let Some(start) = rest.find("<think>") {
if start == 0 {
if let Some(end) = rest.find("</think>") {
rest = rest[end + "</think>".len()..].trim();
continue;
}
}
break;
}
rest
}
fn strip_fences(s: &str) -> &str {
let t = strip_thinking_blocks(s);
let t = t.strip_prefix("```json").or_else(|| t.strip_prefix("```")).unwrap_or(t);
t.strip_suffix("```").unwrap_or(t).trim()
}
fn truncate(s: &str, n: usize) -> String {
if s.chars().count() <= n {
s.to_string()
} else {
format!("{}…", s.chars().take(n).collect::<String>())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fences_and_thinking() {
assert_eq!(super::strip_fences("```json\n{\"a\":1}\n```"), "{\"a\":1}");
assert_eq!(super::strip_fences("{\"a\":1}"), "{\"a\":1}");
assert_eq!(
super::strip_fences("<think>\nreasoning...\n</think>\n```json\n{\"a\":1}\n```"),
"{\"a\":1}"
);
}
#[test]
fn parse_uppercase_and_lowercase_provider_json() {
let raw = r#"[
{
"PROVIDER": "strata",
"OPENAI_COMPATIBLE_API_ENDPOINT": "http://127.0.0.1:8080/v1/",
"OPENAI_COMPATIBLE_API_KEY": "",
"MODEL": "qwen3.8-flash-next",
"WEIGHT": 2
},
{
"provider": "cpa",
"endpoint": "http://126.dahyeon.us:8317",
"api_key": "secret-jwt",
"model": "gpt-6.1-sol",
"weight": 1
}
]"#;
let client = LlmClient::from_json_str(raw).expect("valid json");
assert_eq!(client.providers().len(), 2);
assert_eq!(client.providers()[0].provider, ProviderKind::Strata);
assert_eq!(client.providers()[0].endpoint, "http://127.0.0.1:8080");
assert_eq!(client.providers()[0].weight, 2);
assert_eq!(client.providers()[1].provider, ProviderKind::Cpa);
assert_eq!(client.providers()[1].weight, 1);
// Weighted 2:1 schedule should pick provider 0 twice and provider 1 once every 3 calls.
let picks: Vec<usize> = (0..6)
.map(|_| client.pick_provider_order()[0])
.collect();
let count_0 = picks.iter().filter(|&&i| i == 0).count();
let count_1 = picks.iter().filter(|&&i| i == 1).count();
assert_eq!(count_0, 4);
assert_eq!(count_1, 2);
// If provider 0 (strata) is marked unhealthy, pick_provider_order should promote provider 1 (cpa) first
// while keeping provider 0 at the end as last-resort failover.
client.health_flags[0].store(false, Ordering::Relaxed);
let failover_order = client.pick_provider_order();
assert_eq!(failover_order, vec![1, 0]);
}
#[tokio::test]
#[ignore]
async fn live_env_providers_health_and_routing() -> anyhow::Result<()> {
let env_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.env");
let content = std::fs::read_to_string(&env_path)?;
let mut raw_providers = String::new();
for line in content.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("LLM_PROVIDERS=") {
raw_providers = rest.trim_matches('\'').trim_matches('"').to_string();
}
}
assert!(!raw_providers.is_empty(), "LLM_PROVIDERS not found in .env");
let client = LlmClient::from_json_str(&raw_providers)?;
println!("Loaded {} providers from .env", client.providers().len());
let health = client.health_check_all().await;
for h in &health {
println!(
"[HEALTH] provider={} endpoint={} model={} weight={} healthy={} latency={}ms detail={}",
h.provider.as_str(),
h.endpoint,
h.model,
h.weight,
h.healthy,
h.latency_ms,
h.detail
);
}
assert!(health.iter().all(|h| h.healthy), "Expected all providers to be healthy");
#[derive(Debug, Deserialize)]
struct PingResp {
ok: bool,
provider_echo: String,
}
let schema = serde_json::json!({
"type": "object",
"additionalProperties": false,
"required": ["ok", "provider_echo"],
"properties": {
"ok": { "type": "boolean" },
"provider_echo": { "type": "string" }
}
});
for i in 1..=3 {
let out: ChatJsonOutput<PingResp> = client
.chat_json_with_meta(
"Respond with JSON matching the schema. Set ok=true and provider_echo='pong'.",
&[Part::text("ping")],
"ping_check",
&schema,
)
.await?;
println!(
"[CALL #{i}] served_by={} ({}) -> ok={}, echo={}",
out.provider.as_str(),
out.model,
out.data.ok,
out.data.provider_echo
);
}
Ok(())
}
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "pipeline"
edition.workspace = true
version.workspace = true
[dependencies]
domain = { workspace = true }
llm = { workspace = true }
providers = { workspace = true }
storage = { workspace = true }
reqwest = { workspace = true }
image = { workspace = true }
bytes = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
futures = { workspace = true }
dashmap = { workspace = true }
uuid = { workspace = true }
chrono = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
+250
View File
@@ -0,0 +1,250 @@
//! Step 4 & 5 of the pipeline:
//! - VLM batch photo classification (`PhotoTag` per photo)
//! - Multi-evidence floor voting (photo `floor_level` + text `floor_mentions`)
use std::collections::BTreeMap;
use domain::{
floor_label, FloorEvidence, FurnitureCount, FurnitureKind, Photo, PhotoKind, PhotoTag,
PhotoZone,
};
use llm::{LlmClient, Part};
use providers::text::floor_mentions;
use serde::Deserialize;
use serde_json::{json, Value};
use storage::TextDoc;
const SYSTEM_PROMPT: &str = "\
당신은 한국 식당·카페의 사진을 분류하고 공간 단서를 추출하는 비전 분석가입니다.
주어진 각 사진(index 0..N-1)과 캡션 단서를 보고 다음을 판별하세요:
- kind: interior(실내 공간/좌석/카운터/계단), exterior(건물 외관/간판), food(음식/음료 클로즈업), menu(메뉴판/가격표), person(인물 위주), other
- zone: entrance, counter, hall, window_side, terrace, restroom, stairs, kitchen, unknown
- floor_level: 사진이나 캡션에서 층수가 확인되면 정수(1=1층, 2=2층, -1=지하1층, 99=루프탑/옥상), 알 수 없으면 null
- floor_evidence: 층수를 판단한 근거(계단, 표지판, 캡션 문구 등, 없으면 빈 문자열)
- furniture: 사진에 보이는 가구 종류(table2, table4, table6, communal_table, bar_seat, sofa, counter_bar, plant)와 대략적 개수
- quality: 공간 배치 파악에 도움이 되는 정도 (0.0~1.0)
- description: 공간 구조/좌석/창문/계단 중심 한국어 1문장 요약";
pub async fn classify_batch(
llm: &LlmClient,
batch: &[(&Photo, Vec<u8>)],
) -> anyhow::Result<Vec<(String, PhotoTag)>> {
if batch.is_empty() {
return Ok(Vec::new());
}
let mut parts = Vec::with_capacity(batch.len() * 2 + 1);
parts.push(Part::text(format!(
"총 {}장의 사진입니다. 각 사진의 index(0..{})에 맞춰 분류 결과를 반환하세요.",
batch.len(),
batch.len() - 1
)));
for (idx, (photo, bytes)) in batch.iter().enumerate() {
parts.push(Part::text(format!(
"Photo index={idx}, id={}, source={:?}, caption={:?}",
photo.id, photo.source, photo.caption
)));
parts.push(Part::Image {
bytes: bytes.clone(),
mime: "image/jpeg".into(),
});
}
let resp: BatchResp = llm
.chat_json(SYSTEM_PROMPT, &parts, "photo_classification", &schema())
.await?;
let mut out = Vec::new();
for item in resp.items {
if let Some((photo, _)) = batch.get(item.index) {
out.push((
photo.id.clone(),
PhotoTag {
kind: item.kind,
zone: item.zone,
floor_level: item.floor_level.filter(|&l| l == 99 || (-5..=20).contains(&l) && l != 0),
floor_evidence: item.floor_evidence,
furniture: item.furniture,
quality: item.quality.clamp(0.0, 1.0),
description: item.description,
},
));
}
}
Ok(out)
}
#[derive(Deserialize)]
struct BatchResp {
items: Vec<BatchItem>,
}
#[derive(Deserialize)]
struct BatchItem {
index: usize,
kind: PhotoKind,
zone: PhotoZone,
floor_level: Option<i32>,
floor_evidence: String,
furniture: Vec<FurnitureCount>,
quality: f32,
description: String,
}
fn schema() -> Value {
json!({
"type": "object",
"additionalProperties": false,
"required": ["items"],
"properties": {
"items": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["index", "kind", "zone", "floor_level", "floor_evidence", "furniture", "quality", "description"],
"properties": {
"index": { "type": "integer" },
"kind": { "type": "string", "enum": ["interior", "exterior", "food", "menu", "person", "other"] },
"zone": { "type": "string", "enum": ["entrance", "counter", "hall", "window_side", "terrace", "restroom", "stairs", "kitchen", "unknown"] },
"floor_level": { "type": ["integer", "null"] },
"floor_evidence": { "type": "string" },
"furniture": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "count"],
"properties": {
"kind": { "type": "string", "enum": ["table2", "table4", "table6", "communal_table", "bar_seat", "sofa", "counter_bar", "plant"] },
"count": { "type": "integer" }
}
}
},
"quality": { "type": "number" },
"description": { "type": "string" }
}
}
}
}
})
}
/// Combine photo `floor_level` hints, photo captions, and text snippets into a ranked list of floors.
/// Always includes at least `1F` so single-floor venues have a ground floor.
pub fn detect_floors(photos: &[Photo], texts: &[TextDoc]) -> Vec<FloorEvidence> {
let mut map: BTreeMap<i32, FloorEvidence> = BTreeMap::new();
let ensure = |map: &mut BTreeMap<i32, FloorEvidence>, level: i32| {
map.entry(level).or_insert_with(|| FloorEvidence {
level,
label: floor_label(level),
score: 0.0,
photo_ids: Vec::new(),
text_snippets: Vec::new(),
});
};
for p in photos {
if let Some(tag) = &p.tag {
if let Some(lvl) = tag.floor_level {
ensure(&mut map, lvl);
let entry = map.get_mut(&lvl).unwrap();
entry.score += if tag.kind == PhotoKind::Interior { 1.5 } else { 0.8 };
if !entry.photo_ids.contains(&p.id) {
entry.photo_ids.push(p.id.clone());
}
if !tag.floor_evidence.is_empty() && entry.text_snippets.len() < 4 {
entry.text_snippets.push(tag.floor_evidence.clone());
}
}
}
for (lvl, snip) in floor_mentions(&p.caption) {
ensure(&mut map, lvl);
let entry = map.get_mut(&lvl).unwrap();
entry.score += 0.7;
if !entry.photo_ids.contains(&p.id) {
entry.photo_ids.push(p.id.clone());
}
if entry.text_snippets.len() < 4 && !entry.text_snippets.contains(&snip) {
entry.text_snippets.push(snip);
}
}
}
for t in texts {
for (lvl, snip) in floor_mentions(&t.text) {
ensure(&mut map, lvl);
let entry = map.get_mut(&lvl).unwrap();
entry.score += 0.5;
if entry.text_snippets.len() < 4 && !entry.text_snippets.contains(&snip) {
entry.text_snippets.push(snip);
}
}
}
// Filter out weak stray mentions (e.g., a single "3층" referring to another tenant in the building)
// unless it's 1F.
let mut floors: Vec<FloorEvidence> = map
.into_values()
.filter(|f| f.level == 1 || f.score >= 1.0)
.collect();
if floors.is_empty() {
floors.push(FloorEvidence {
level: 1,
label: "1F".into(),
score: 1.0,
photo_ids: photos
.iter()
.filter(|p| p.tag.as_ref().map(|t| t.kind == PhotoKind::Interior).unwrap_or(false))
.take(4)
.map(|p| p.id.clone())
.collect(),
text_snippets: Vec::new(),
});
}
floors.sort_by_key(|f| f.level);
let _ = FurnitureKind::Table2;
floors
}
#[cfg(test)]
mod tests {
use super::*;
use domain::PhotoSourceId;
#[test]
fn floor_voting_combines_photo_and_text() {
let p = Photo {
id: "p1".into(),
place_id: "kakao:1".into(),
source: PhotoSourceId::NaverBlog,
image_url: String::new(),
page_url: String::new(),
caption: "2층 창가석".into(),
object_key: String::new(),
dhash: String::new(),
width: 800,
height: 600,
tag: Some(PhotoTag {
kind: PhotoKind::Interior,
zone: PhotoZone::WindowSide,
floor_level: Some(2),
floor_evidence: "계단 위 2층 홀".into(),
furniture: vec![],
quality: 0.9,
description: "2층 창가".into(),
}),
};
let t = TextDoc {
place_id: "kakao:1".into(),
source: PhotoSourceId::NaverBlog,
url: String::new(),
text: "1층에서 주문하고 2층으로 올라가면 루프탑도 있어요. 루프탑 뷰가 최고".into(),
};
let floors = detect_floors(&[p], &[t]);
let levels: Vec<i32> = floors.iter().map(|f| f.level).collect();
assert!(levels.contains(&2));
assert!(levels.contains(&domain::ROOFTOP_LEVEL));
}
}
+79
View File
@@ -0,0 +1,79 @@
//! Image decoding, resizing, and 64-bit perceptual difference hash (dHash).
use image::imageops::FilterType;
use image::{DynamicImage, GenericImageView};
use std::io::Cursor;
pub struct ProcessedImage {
pub jpeg_bytes: Vec<u8>,
pub width: u32,
pub height: u32,
pub dhash: u64,
}
/// Decode raw image bytes, reject tiny icons (< 160px), downscale to at most `max_dim`
/// on the longest side, re-encode as JPEG, and compute a 9x8 dHash.
pub fn process_image(bytes: &[u8], max_dim: u32) -> anyhow::Result<ProcessedImage> {
let img = image::load_from_memory(bytes)?;
let (w, h) = img.dimensions();
if w < 160 || h < 160 {
anyhow::bail!("image too small ({w}x{h})");
}
let dhash = compute_dhash(&img);
let resized = if w > max_dim || h > max_dim {
img.resize(max_dim, max_dim, FilterType::Triangle)
} else {
img
};
let (rw, rh) = resized.dimensions();
let mut out = Vec::new();
resized.to_rgb8().write_to(&mut Cursor::new(&mut out), image::ImageFormat::Jpeg)?;
Ok(ProcessedImage {
jpeg_bytes: out,
width: rw,
height: rh,
dhash,
})
}
pub fn compute_dhash(img: &DynamicImage) -> u64 {
let gray = img.resize_exact(9, 8, FilterType::Triangle).to_luma8();
let mut hash = 0u64;
let mut bit = 0;
for y in 0..8 {
for x in 0..8 {
if gray.get_pixel(x, y)[0] > gray.get_pixel(x + 1, y)[0] {
hash |= 1u64 << bit;
}
bit += 1;
}
}
hash
}
pub fn hamming(a: u64, b: u64) -> u32 {
(a ^ b).count_ones()
}
pub fn is_near_duplicate(existing: &[u64], candidate: u64) -> bool {
existing.iter().any(|&h| hamming(h, candidate) <= 6)
}
#[cfg(test)]
mod tests {
use super::*;
use image::{Rgb, RgbImage};
#[test]
fn identical_images_match() {
let mut buf = RgbImage::new(200, 200);
for (x, y, p) in buf.enumerate_pixels_mut() {
*p = Rgb([(x % 255) as u8, (y % 255) as u8, 120]);
}
let dyn_img = DynamicImage::ImageRgb8(buf);
let h1 = compute_dhash(&dyn_img);
let h2 = compute_dhash(&dyn_img);
assert_eq!(hamming(h1, h2), 0);
assert!(is_near_duplicate(&[h1], h2));
}
}
+430
View File
@@ -0,0 +1,430 @@
//! Step 6 & 7 of the pipeline:
//! - VLM spatial layout inference -> `domain::Layout`
//! - Validation & clamping (bounds, non-zero dimensions, valid `evidence_photos` IDs)
//! - Single retry with validation feedback if needed
use std::collections::HashSet;
use domain::{
floor_label, Accessibility, Arrangement, Floor, FloorEvidence, FurnitureGroup, FurnitureKind,
Layout, Opening, OpeningKind, Photo, PhotoKind, Place, Summary, Tri, Vertical, VerticalKind,
Wall, Zone, ZoneKind,
};
use llm::{LlmClient, Part};
use serde::Deserialize;
use serde_json::{json, Value};
use storage::TextDoc;
const SYSTEM_PROMPT: &str = "\
당신은 식당·카페의 실내 사진들과 텍스트 리뷰를 종합해 three.js 미니어처 3D 뷰어용 공간 배치(Layout JSON)를 추론하는 공간 건축 AI입니다.
좌표 규칙 (층별 미터 단위):
- 각 층은 직사각형 바닥(width_m: 동서 폭, depth_m: 남북 깊이, 보통 6~22m 범위)입니다.
- 원점 (0, 0)은 남서쪽(South-West) 모서리이며, x는 동쪽(0..width_m), y는 북쪽(0..depth_m)으로 증가합니다.
- 주 출입구(entrance)는 기본적으로 south 벽에 두되, 사진 단서에 맞게 조정하세요.
- 각 zone(구역)의 직사각형 (x, y, w, d)는 바닥 범위(0 <= x, x+w <= width_m, 0 <= y, y+d <= depth_m) 안에 있어야 하며 서로 과도하게 겹치지 않게 배치하세요.
- evidence_photos 배열에는 반드시 입력으로 주어진 사진 id만 넣으세요 (절대 없는 id를 만들지 마세요).
- 다층 건물인 경우 층간 이동 수단(stairs 또는 elevator)을 verticals에 포함하세요.
- summary에는 예상 평수 범위, 예상 좌석 수, 좌석 종류, 방문 전 핵심 체크 포인트(highlights), 주의사항(caveats)을 한국어로 작성하세요.";
pub async fn generate_layout(
llm: &LlmClient,
place: &Place,
photos_with_bytes: &[(&Photo, Vec<u8>)],
floors: &[FloorEvidence],
texts: &[TextDoc],
mut on_attempt: impl FnMut(u32),
) -> anyhow::Result<Layout> {
let valid_ids: HashSet<String> = photos_with_bytes.iter().map(|(p, _)| p.id.clone()).collect();
let mut feedback: Option<String> = None;
for attempt in 1..=2 {
on_attempt(attempt);
let parts = build_prompt_parts(place, photos_with_bytes, floors, texts, feedback.as_deref());
match llm
.chat_json_with_meta::<DraftLayout>(SYSTEM_PROMPT, &parts, "space_layout", &schema())
.await
{
Ok(out) => {
let model_tag = out.model_tag();
let mut layout = into_layout(place, &model_tag, out.data, &valid_ids);
match validate_and_clamp(&mut layout) {
Ok(()) => return Ok(layout),
Err(err) if attempt == 1 => {
tracing::warn!(attempt, %err, "layout validation failed, retrying once");
feedback = Some(err);
}
Err(err) => {
tracing::warn!(attempt, %err, "layout validation failed on second attempt, using clamped layout");
return Ok(layout);
}
}
}
Err(err) if attempt == 1 => {
tracing::warn!(attempt, %err, "layout LLM call failed, retrying once");
feedback = Some(format!("이전 응답 파싱 실패: {err}"));
}
Err(err) => {
tracing::warn!(%err, "layout LLM call failed twice, using fallback layout");
return Ok(fallback_layout(place, &llm.model, photos_with_bytes, floors));
}
}
}
Ok(fallback_layout(place, &llm.model, photos_with_bytes, floors))
}
fn build_prompt_parts(
place: &Place,
photos_with_bytes: &[(&Photo, Vec<u8>)],
floors: &[FloorEvidence],
texts: &[TextDoc],
feedback: Option<&str>,
) -> Vec<Part> {
let mut header = format!(
"장소명: {}\n카테고리: {}\n주소: {} ({})\n\n[감지된 층 단서]\n",
place.name, place.category, place.road_address, place.address
);
for f in floors {
header.push_str(&format!(
"- {} (level={}, 점수={:.1}, 관련 사진={:?}, 텍스트 단서={:?})\n",
f.label, f.level, f.score, f.photo_ids, f.text_snippets
));
}
header.push_str("\n[수집된 텍스트/리뷰 발췌]\n");
for t in texts.iter().take(6) {
let excerpt: String = t.text.chars().take(450).collect();
header.push_str(&format!("({:?}) {}\n---\n", t.source, excerpt));
}
if let Some(fb) = feedback {
header.push_str(&format!(
"\n[이전 생성 결과 오류 - 반드시 수정하세요]\n{fb}\n"
));
}
header.push_str("\n[실내/외관 핵심 사진 목록 — evidence_photos에는 아래 photo_id만 사용하세요]\n");
let mut parts = vec![Part::text(header)];
for (p, bytes) in photos_with_bytes.iter().take(12) {
let tag_desc = p
.tag
.as_ref()
.map(|t| {
format!(
"kind={:?}, zone={:?}, floor={:?}, desc={}, furniture={:?}",
t.kind, t.zone, t.floor_level, t.description, t.furniture
)
})
.unwrap_or_default();
parts.push(Part::text(format!(
"photo_id=\"{}\" | caption={:?} | {tag_desc}",
p.id, p.caption
)));
parts.push(Part::Image {
bytes: bytes.clone(),
mime: "image/jpeg".into(),
});
}
parts
}
fn into_layout(
place: &Place,
model: &str,
draft: DraftLayout,
valid_ids: &HashSet<String>,
) -> Layout {
let floors = draft
.floors
.into_iter()
.map(|mut f| {
if f.label.trim().is_empty() {
f.label = floor_label(f.level);
}
for z in &mut f.zones {
z.evidence_photos.retain(|id| valid_ids.contains(id));
}
f
})
.collect();
Layout {
place_id: place.id.clone(),
generated_at: chrono::Utc::now().to_rfc3339(),
model: model.to_string(),
confidence: draft.confidence.clamp(0.1, 0.98),
floors,
summary: draft.summary,
}
}
/// Clamp coordinates into valid ranges and return `Err` if the layout had structural issues worth retrying.
pub fn validate_and_clamp(layout: &mut Layout) -> Result<(), String> {
if layout.floors.is_empty() {
return Err("floors 배열이 비어 있습니다. 최소 1개 층(1F)을 포함해야 합니다.".into());
}
let mut issues = Vec::new();
for f in &mut layout.floors {
if f.width_m < 4.0 || f.width_m > 40.0 {
issues.push(format!("층 {} width_m({})가 비정상 범위", f.label, f.width_m));
f.width_m = f.width_m.clamp(5.0, 28.0);
}
if f.depth_m < 4.0 || f.depth_m > 40.0 {
issues.push(format!("층 {} depth_m({})가 비정상 범위", f.label, f.depth_m));
f.depth_m = f.depth_m.clamp(5.0, 28.0);
}
f.confidence = f.confidence.clamp(0.1, 0.99);
if f.zones.is_empty() {
issues.push(format!("층 {}에 zones가 비어 있습니다.", f.label));
}
for z in &mut f.zones {
z.w = z.w.clamp(1.2, f.width_m);
z.d = z.d.clamp(1.2, f.depth_m);
z.x = z.x.clamp(0.0, (f.width_m - z.w).max(0.0));
z.y = z.y.clamp(0.0, (f.depth_m - z.d).max(0.0));
for fg in &mut z.furniture {
fg.count = fg.count.clamp(1, 30);
}
}
for o in &mut f.openings {
let wall_len = match o.wall {
Wall::North | Wall::South => f.width_m,
Wall::East | Wall::West => f.depth_m,
};
o.length_m = o.length_m.clamp(0.8, (wall_len - 0.4).max(0.8));
o.offset_m = o.offset_m.clamp(0.2, (wall_len - o.length_m - 0.2).max(0.2));
}
for v in &mut f.verticals {
v.w = v.w.clamp(1.0, 3.5);
v.d = v.d.clamp(1.2, 4.0);
v.x = v.x.clamp(0.0, (f.width_m - v.w).max(0.0));
v.y = v.y.clamp(0.0, (f.depth_m - v.d).max(0.0));
}
}
layout.floors.sort_by_key(|f| f.level);
if issues.is_empty() {
Ok(())
} else {
Err(issues.join("; "))
}
}
pub fn fallback_layout(
place: &Place,
model: &str,
photos_with_bytes: &[(&Photo, Vec<u8>)],
floors: &[FloorEvidence],
) -> Layout {
let evidence: Vec<String> = photos_with_bytes.iter().take(4).map(|(p, _)| p.id.clone()).collect();
let levels: Vec<i32> = if floors.is_empty() {
vec![1]
} else {
floors.iter().map(|f| f.level).collect()
};
let built_floors = levels
.iter()
.map(|&lvl| Floor {
level: lvl,
label: floor_label(lvl),
confidence: 0.45,
width_m: 10.0,
depth_m: 12.0,
openings: if lvl == 1 {
vec![
Opening { kind: OpeningKind::Entrance, wall: Wall::South, offset_m: 1.5, length_m: 1.6 },
Opening { kind: OpeningKind::Window, wall: Wall::South, offset_m: 4.0, length_m: 4.5 },
]
} else {
vec![Opening { kind: OpeningKind::Window, wall: Wall::South, offset_m: 2.0, length_m: 6.0 }]
},
zones: vec![
Zone {
kind: if lvl == 1 { ZoneKind::Counter } else { ZoneKind::Seating },
label: if lvl == 1 { "주문 카운터".into() } else { "창가 좌석".into() },
x: 0.6,
y: if lvl == 1 { 8.2 } else { 0.6 },
w: 4.2,
d: 3.0,
furniture: vec![FurnitureGroup {
kind: if lvl == 1 { FurnitureKind::CounterBar } else { FurnitureKind::BarSeat },
count: if lvl == 1 { 1 } else { 5 },
arrangement: Arrangement::AlongWall,
along_wall: Some(if lvl == 1 { Wall::North } else { Wall::South }),
}],
evidence_photos: evidence.clone(),
},
Zone {
kind: ZoneKind::Seating,
label: "메인 홀 좌석".into(),
x: 0.8,
y: if lvl == 1 { 1.0 } else { 4.2 },
w: 8.4,
d: 6.5,
furniture: vec![
FurnitureGroup {
kind: FurnitureKind::Table2,
count: 5,
arrangement: Arrangement::Grid,
along_wall: None,
},
FurnitureGroup {
kind: FurnitureKind::Table4,
count: 3,
arrangement: Arrangement::Grid,
along_wall: None,
},
],
evidence_photos: evidence.clone(),
},
],
verticals: if levels.len() > 1 {
vec![Vertical {
kind: VerticalKind::Stairs,
x: 7.8,
y: 9.2,
w: 1.6,
d: 2.2,
to_level: if lvl == 1 { levels.get(1).copied().unwrap_or(2) } else { 1 },
}]
} else {
vec![]
},
notes: "수집된 사진을 기반으로 생성한 기본 추정 배치입니다.".into(),
})
.collect();
let _ = PhotoKind::Interior;
Layout {
place_id: place.id.clone(),
generated_at: chrono::Utc::now().to_rfc3339(),
model: model.to_string(),
confidence: 0.45,
floors: built_floors,
summary: Summary {
area_pyeong_min: 18.0,
area_pyeong_max: 28.0,
seat_estimate: 26,
seat_types: vec!["2인 테이블".into(), "4인 테이블".into(), "바 좌석".into()],
highlights: vec![format!("{} 공간 배치 추정 완료", place.name)],
accessibility: Accessibility {
elevator: Tri::Unknown,
step_free_entrance: Tri::Likely,
},
caveats: vec!["실내 사진 수량이 제한적이어서 일부 구역은 표준 배치로 추정되었습니다.".into()],
},
}
}
#[derive(Deserialize)]
struct DraftLayout {
confidence: f32,
floors: Vec<Floor>,
summary: Summary,
}
fn schema() -> Value {
json!({
"type": "object",
"additionalProperties": false,
"required": ["confidence", "floors", "summary"],
"properties": {
"confidence": { "type": "number" },
"floors": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["level", "label", "confidence", "width_m", "depth_m", "openings", "zones", "verticals", "notes"],
"properties": {
"level": { "type": "integer" },
"label": { "type": "string" },
"confidence": { "type": "number" },
"width_m": { "type": "number" },
"depth_m": { "type": "number" },
"openings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "wall", "offset_m", "length_m"],
"properties": {
"kind": { "type": "string", "enum": ["entrance", "window", "door"] },
"wall": { "type": "string", "enum": ["north", "south", "east", "west"] },
"offset_m": { "type": "number" },
"length_m": { "type": "number" }
}
}
},
"zones": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "label", "x", "y", "w", "d", "furniture", "evidence_photos"],
"properties": {
"kind": { "type": "string", "enum": ["seating", "counter", "bar", "kitchen", "restroom", "terrace", "entrance", "other"] },
"label": { "type": "string" },
"x": { "type": "number" },
"y": { "type": "number" },
"w": { "type": "number" },
"d": { "type": "number" },
"furniture": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "count", "arrangement", "along_wall"],
"properties": {
"kind": { "type": "string", "enum": ["table2", "table4", "table6", "communal_table", "bar_seat", "sofa", "counter_bar", "plant"] },
"count": { "type": "integer" },
"arrangement": { "type": "string", "enum": ["grid", "along_wall", "row", "cluster"] },
"along_wall": { "type": ["string", "null"], "enum": ["north", "south", "east", "west", null] }
}
}
},
"evidence_photos": { "type": "array", "items": { "type": "string" } }
}
}
},
"verticals": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["kind", "x", "y", "w", "d", "to_level"],
"properties": {
"kind": { "type": "string", "enum": ["stairs", "elevator"] },
"x": { "type": "number" },
"y": { "type": "number" },
"w": { "type": "number" },
"d": { "type": "number" },
"to_level": { "type": "integer" }
}
}
},
"notes": { "type": "string" }
}
}
},
"summary": {
"type": "object",
"additionalProperties": false,
"required": ["area_pyeong_min", "area_pyeong_max", "seat_estimate", "seat_types", "highlights", "accessibility", "caveats"],
"properties": {
"area_pyeong_min": { "type": "number" },
"area_pyeong_max": { "type": "number" },
"seat_estimate": { "type": "integer" },
"seat_types": { "type": "array", "items": { "type": "string" } },
"highlights": { "type": "array", "items": { "type": "string" } },
"accessibility": {
"type": "object",
"additionalProperties": false,
"required": ["elevator", "step_free_entrance"],
"properties": {
"elevator": { "type": "string", "enum": ["yes", "likely", "no", "unknown"] },
"step_free_entrance": { "type": "string", "enum": ["yes", "likely", "no", "unknown"] }
}
},
"caveats": { "type": "array", "items": { "type": "string" } }
}
}
}
})
}
+482
View File
@@ -0,0 +1,482 @@
#![recursion_limit = "256"]
//! End-to-end place analysis pipeline:
//! 1. Normalize place (Kakao candidate + NCP Geocode address verification + Naver place ID resolution)
//! 2. Collect photos & texts in parallel across all `PhotoSource`s (per-source timeout)
//! 3. Download images, deduplicate with 64-bit dHash, store JPEG blobs in MinIO & metadata in MongoDB
//! 4. Classify photos in batches with the VLM (`PhotoTag`)
//! 5. Vote on floors (`FloorEvidence`) from photo tags, captions, and text snippets
//! 6. Generate 3D `Layout` JSON with the VLM
//! 7. Validate & clamp layout (retry once on structural issues) and save to MongoDB
pub mod classify;
pub mod dhash;
pub mod layout_gen;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use dashmap::DashMap;
use domain::{
JobEvent, Photo, PhotoKind, PhotoSummary, Place, PlaceCandidate, PlaceView, RawPhoto, RecentPlace,
};
use futures::stream::{self, StreamExt};
use llm::LlmClient;
use providers::browser::{browser_source, BrowserSource};
use providers::kakao_local::KakaoLocal;
use providers::kakao_place::KakaoPlacePhotos;
use providers::naver_blog::NaverBlog;
use providers::naver_map::NaverMapSearch;
use providers::naver_place::NaverPlacePhotos;
use providers::ncp_geocode::NcpGeocode;
use providers::{PhotoSource, PlaceSearch};
use storage::{Store, TextDoc};
use tokio::sync::broadcast;
#[derive(Clone)]
pub struct PipelineConfig {
pub kakao_api_key: String,
pub ncp_client_id: String,
pub ncp_client_secret: String,
pub browser_scraper_url: Option<String>,
pub max_photos_per_source: usize,
pub max_photos_total: usize,
}
#[derive(Clone)]
pub struct Pipeline {
pub store: Store,
pub llm: LlmClient,
kakao: Arc<KakaoLocal>,
naver_map: Arc<NaverMapSearch>,
ncp: Option<Arc<NcpGeocode>>,
sources: Arc<Vec<Box<dyn PhotoSource>>>,
http: reqwest::Client,
cfg: PipelineConfig,
/// Active job event broadcasters keyed by `job_id`.
jobs: Arc<DashMap<String, broadcast::Sender<JobEvent>>>,
/// Map `place_id` -> currently running `job_id` so concurrent visitors share one job.
running_by_place: Arc<DashMap<String, String>>,
}
impl Pipeline {
pub fn new(store: Store, llm: LlmClient, cfg: PipelineConfig) -> Self {
let kakao = Arc::new(KakaoLocal::new(&cfg.kakao_api_key));
let naver_map = Arc::new(NaverMapSearch::new());
let ncp = if !cfg.ncp_client_id.trim().is_empty() && !cfg.ncp_client_secret.trim().is_empty() {
Some(Arc::new(NcpGeocode::new(&cfg.ncp_client_id, &cfg.ncp_client_secret)))
} else {
None
};
let sources: Vec<Box<dyn PhotoSource>> = vec![
Box::new(NaverPlacePhotos::new()),
Box::new(KakaoPlacePhotos::new()),
Box::new(NaverBlog::new()),
browser_source(cfg.browser_scraper_url.as_deref(), BrowserSource::GoogleMaps),
browser_source(cfg.browser_scraper_url.as_deref(), BrowserSource::Instagram),
];
Self {
store,
llm,
kakao,
naver_map,
ncp,
sources: Arc::new(sources),
http: providers::http::scraping_client(),
cfg,
jobs: Arc::new(DashMap::new()),
running_by_place: Arc::new(DashMap::new()),
}
}
/// Search place candidates by free text (Kakao primary, Naver Map fallback).
pub async fn search_places(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
let q = query.trim();
if q.is_empty() {
return Ok(Vec::new());
}
let mut results = self.kakao.search(q).await.unwrap_or_default();
if results.is_empty() {
results = self.naver_map.search(q).await.unwrap_or_default();
}
Ok(results)
}
/// Saved analyses ordered by their most recent view (or analysis time for older records).
pub async fn recent_places(&self) -> anyhow::Result<Vec<RecentPlace>> {
self.store.recent_places().await
}
/// Return current `PlaceView` (place + latest cached layout + stored photos + running job id).
pub async fn get_place_view(&self, place_id: &str) -> anyhow::Result<Option<PlaceView>> {
let Some(place) = self.store.get_place(place_id).await? else {
return Ok(None);
};
let layout = self.store.latest_layout(place_id).await?.map(|d| d.layout);
let photos = self
.store
.photos_for_place(place_id)
.await?
.iter()
.map(PhotoSummary::from)
.collect();
let running_job = self.running_by_place.get(place_id).map(|v| v.value().clone());
if layout.is_some() {
if let Err(error) = self.store.record_place_view(place_id).await {
tracing::warn!(%place_id, %error, "could not record place view");
}
}
Ok(Some(PlaceView {
place,
layout,
photos,
running_job,
}))
}
/// Subscribe to live events for `job_id`, plus any events already recorded in MongoDB.
pub async fn subscribe_job(
&self,
job_id: &str,
) -> anyhow::Result<(Vec<JobEvent>, Option<broadcast::Receiver<JobEvent>>)> {
let rx = self.jobs.get(job_id).map(|s| s.value().subscribe());
let past = self
.store
.get_job(job_id)
.await?
.map(|j| j.events)
.unwrap_or_default();
Ok((past, rx))
}
/// Ensure the candidate's `Place` exists in MongoDB; if no cached layout exists (or `force_reanalyze` is true),
/// spawn the analysis job in the background and return `(place_id, Option<job_id>)`.
pub async fn select_or_analyze(
&self,
candidate: PlaceCandidate,
force_reanalyze: bool,
) -> anyhow::Result<(String, Option<String>)> {
let place_id = candidate.place_id();
let mut place = match self.store.get_place(&place_id).await? {
Some(existing) => existing,
None => {
let p = Place::from_candidate(&candidate);
self.store.upsert_place(&p).await?;
p
}
};
if !force_reanalyze {
if let Some( job_id ) = self.running_by_place.get(&place_id).map(|r| r.value().clone()) {
return Ok((place_id, Some(job_id)));
}
if self.store.latest_layout(&place_id).await?.is_some() {
return Ok((place_id, None));
}
}
let job_id = self.spawn_job(place_id.clone(), place.clone(), force_reanalyze).await?;
let _ = &mut place;
Ok((place_id, Some(job_id)))
}
/// Trigger reanalysis for an already-stored `place_id`.
pub async fn reanalyze(&self, place_id: &str) -> anyhow::Result<String> {
if let Some(existing) = self.running_by_place.get(place_id) {
return Ok(existing.value().clone());
}
let place = self
.store
.get_place(place_id)
.await?
.ok_or_else(|| anyhow::anyhow!("장소를 찾을 수 없습니다: {place_id}"))?;
self.spawn_job(place_id.to_string(), place, true).await
}
async fn spawn_job(
&self,
place_id: String,
place: Place,
clear_existing_photos: bool,
) -> anyhow::Result<String> {
let job_id = uuid::Uuid::new_v4().to_string();
self.store.create_job(&job_id, &place_id).await?;
let (tx, _) = broadcast::channel(64);
self.jobs.insert(job_id.clone(), tx.clone());
self.running_by_place.insert(place_id.clone(), job_id.clone());
let this = self.clone();
let jid = job_id.clone();
let pid = place_id.clone();
tokio::spawn(async move {
if let Err(err) = this.run_job(&jid, place, clear_existing_photos, &tx).await {
tracing::error!(job_id = %jid, place_id = %pid, "pipeline job failed: {err:#}");
this.emit(&jid, &tx, JobEvent::Error { message: err.to_string() }).await;
}
this.running_by_place.remove(&pid);
// Keep channel briefly so SSE clients receive the terminal event, then drop.
tokio::time::sleep(Duration::from_secs(5)).await;
this.jobs.remove(&jid);
});
Ok(job_id)
}
/// Run a place analysis synchronously (used by `precompute` CLI and `spawn_job`).
pub async fn run_sync(&self, place: Place) -> anyhow::Result<domain::Layout> {
let job_id = uuid::Uuid::new_v4().to_string();
self.store.upsert_place(&place).await?;
self.store.create_job(&job_id, &place.id).await?;
let (tx, _) = broadcast::channel(64);
self.run_job(&job_id, place.clone(), false, &tx).await?;
let doc = self
.store
.latest_layout(&place.id)
.await?
.ok_or_else(|| anyhow::anyhow!("layout not saved"))?;
Ok(doc.layout)
}
async fn emit(&self, job_id: &str, tx: &broadcast::Sender<JobEvent>, ev: JobEvent) {
let _ = self.store.push_job_event(job_id, &ev).await;
let _ = tx.send(ev);
}
async fn run_job(
&self,
job_id: &str,
mut place: Place,
clear_existing_photos: bool,
tx: &broadcast::Sender<JobEvent>,
) -> anyhow::Result<()> {
self.emit(job_id, tx, JobEvent::Started { place_id: place.id.clone() }).await;
// 1. Address verification (NCP Geocode) + Naver Place ID matching
if let Some(ncp) = &self.ncp {
let addr_query = if !place.road_address.is_empty() {
place.road_address.clone()
} else {
place.address.clone()
};
if !addr_query.is_empty() {
if let Ok(Some(geo)) = ncp.geocode(&addr_query).await {
if place.road_address.is_empty() && !geo.road_address.is_empty() {
place.road_address = geo.road_address;
}
if place.address.is_empty() && !geo.jibun_address.is_empty() {
place.address = geo.jibun_address;
}
}
}
}
if place.naver_place_id.is_none() {
if let Ok(Some(nid)) = self.naver_map.resolve_place_id(&place).await {
place.naver_place_id = Some(nid);
}
}
self.store.upsert_place(&place).await?;
self.emit(
job_id,
tx,
JobEvent::PlaceResolved {
name: place.name.clone(),
naver_place_id: place.naver_place_id.clone(),
},
)
.await;
// 2. Collect photos & text snippets from all sources in parallel
let per_source = self.cfg.max_photos_per_source;
let source_futs = self.sources.iter().map(|src| {
let place_ref = &place;
async move {
let id = src.id();
let res = tokio::time::timeout(Duration::from_secs(30), src.collect(place_ref, per_source)).await;
match res {
Ok(Ok(out)) => (id, out, None),
Ok(Err(e)) => (id, Default::default(), Some(e.to_string())),
Err(_) => (id, Default::default(), Some("시간 초과 (30s)".into())),
}
}
});
let collected = futures::future::join_all(source_futs).await;
let mut raw_photos: Vec<RawPhoto> = Vec::new();
let mut text_docs: Vec<TextDoc> = Vec::new();
for (source, out, error) in collected {
self.emit(
job_id,
tx,
JobEvent::SourceDone {
source,
photos: out.photos.len(),
texts: out.texts.len(),
error,
},
)
.await;
raw_photos.extend(out.photos);
for t in out.texts {
text_docs.push(TextDoc {
place_id: place.id.clone(),
source: t.source,
url: t.url,
text: t.text,
});
}
}
let _ = self.store.replace_texts(&place.id, &text_docs).await;
raw_photos.truncate(self.cfg.max_photos_total);
// 3. Download, deduplicate (dHash), and store in MinIO + MongoDB
if clear_existing_photos {
let _ = self.store.delete_photos_for_place(&place.id).await;
}
let downloaded: Vec<Option<(RawPhoto, dhash::ProcessedImage)>> = stream::iter(raw_photos)
.map(|raw| {
let client = self.http.clone();
async move {
let mut req = client.get(&raw.image_url);
if let Some(r) = &raw.referer {
req = req.header(reqwest::header::REFERER, r);
}
let bytes = tokio::time::timeout(Duration::from_secs(15), async {
Ok::<_, anyhow::Error>(req.send().await?.error_for_status()?.bytes().await?)
})
.await
.ok()?
.ok()?;
let processed = dhash::process_image(&bytes, 1024).ok()?;
Some((raw, processed))
}
})
.buffer_unordered(8)
.collect()
.await;
let mut seen_hashes: Vec<u64> = Vec::new();
let mut stored_photos: Vec<(Photo, Vec<u8>)> = Vec::new();
let mut duplicates = 0usize;
let mut failed = 0usize;
for item in downloaded {
let Some((raw, proc_img)) = item else {
failed += 1;
continue;
};
if dhash::is_near_duplicate(&seen_hashes, proc_img.dhash) {
duplicates += 1;
continue;
}
seen_hashes.push(proc_img.dhash);
let photo_id = format!("p_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let object_key = format!("places/{}/{photo_id}.jpg", place.id.replace(':', "_"));
if let Err(e) = self.store.put_blob(&object_key, Bytes::from(proc_img.jpeg_bytes.clone())).await {
tracing::warn!(%e, "minio put_blob failed");
failed += 1;
continue;
}
let photo = Photo {
id: photo_id,
place_id: place.id.clone(),
source: raw.source,
image_url: raw.image_url,
page_url: raw.page_url,
caption: raw.caption,
object_key,
dhash: format!("{:016x}", proc_img.dhash),
width: proc_img.width,
height: proc_img.height,
tag: None,
};
self.store.insert_photo(&photo).await?;
stored_photos.push((photo, proc_img.jpeg_bytes));
}
self.emit(
job_id,
tx,
JobEvent::PhotosStored {
stored: stored_photos.len(),
duplicates,
failed,
},
)
.await;
// 4. Classify photos in batches of 6 via VLM
let to_classify_len = stored_photos.len().min(36);
for chunk in stored_photos[..to_classify_len].chunks_mut(6) {
let refs: Vec<(&Photo, Vec<u8>)> = chunk.iter().map(|(p, b)| (p, b.clone())).collect();
match classify::classify_batch(&self.llm, &refs).await {
Ok(tags) => {
for (pid, tag) in tags {
let _ = self.store.set_photo_tag(&pid, &tag).await;
if let Some((p, _)) = chunk.iter_mut().find(|(p, _)| p.id == pid) {
p.tag = Some(tag);
}
}
}
Err(e) => {
tracing::warn!(%e, "photo batch classification failed");
}
}
}
let mut interior = 0usize;
let mut exterior = 0usize;
let mut food = 0usize;
let mut other = 0usize;
for (p, _) in &stored_photos {
match p.tag.as_ref().map(|t| t.kind) {
Some(PhotoKind::Interior) => interior += 1,
Some(PhotoKind::Exterior) => exterior += 1,
Some(PhotoKind::Food) => food += 1,
_ => other += 1,
}
}
self.emit(job_id, tx, JobEvent::Classified { interior, exterior, food, other }).await;
// 5. Floor detection
let all_photos: Vec<Photo> = stored_photos.iter().map(|(p, _)| p.clone()).collect();
let floors = classify::detect_floors(&all_photos, &text_docs);
self.emit(job_id, tx, JobEvent::FloorsDetected { floors: floors.clone() }).await;
// 6 & 7. Select top interior/exterior photos and infer 3D layout
let mut ranked: Vec<(&Photo, Vec<u8>)> = stored_photos
.iter()
.filter(|(p, _)| {
matches!(
p.tag.as_ref().map(|t| t.kind),
Some(PhotoKind::Interior | PhotoKind::Exterior) | None
)
})
.map(|(p, b)| (p, b.clone()))
.collect();
ranked.sort_by(|(a, _), (b, _)| {
let score = |p: &Photo| match &p.tag {
Some(t) if t.kind == PhotoKind::Interior => 2.0 + t.quality,
Some(t) if t.kind == PhotoKind::Exterior => 1.0 + t.quality,
Some(t) => t.quality,
None => 0.5,
};
score(b).total_cmp(&score(a))
});
ranked.truncate(12);
self.emit(job_id, tx, JobEvent::LayoutDraft { attempt: 1 }).await;
let layout = layout_gen::generate_layout(
&self.llm,
&place,
&ranked,
&floors,
&text_docs,
|_attempt| {},
)
.await?;
self.store.save_layout(&layout).await?;
self.emit(job_id, tx, JobEvent::Done { place_id: place.id.clone() }).await;
Ok(())
}
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "providers"
edition.workspace = true
version.workspace = true
[dependencies]
domain = { workspace = true }
async-trait = { workspace = true }
reqwest = { workspace = true }
scraper = { workspace = true }
regex = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
url = { workspace = true }
urlencoding = { workspace = true }
tokio = { workspace = true }
futures = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
+224
View File
@@ -0,0 +1,224 @@
//! Client for the external browser-scraping microservice (Google Maps, Instagram, ...).
//!
//! The service is not implemented yet. Contract (async job API):
//!
//! ```text
//! POST {BASE}/jobs
//! { "source": "google_maps" | "instagram",
//! "place": { "name", "address", "lat", "lng" },
//! "limit": 50,
//! "callback_url": null }
//! -> 202 { "job_id": "..." }
//!
//! GET {BASE}/jobs/{job_id}
//! -> { "status": "queued" | "running" | "done" | "failed",
//! "items": [ { "image_url", "caption", "source_url", "taken_at" } ],
//! "texts": [ { "text", "source_url" } ],
//! "error": null }
//! ```
//!
//! When `BROWSER_SCRAPER_URL` is unset, [`MockBrowserScraper`] is used instead.
use std::time::Duration;
use async_trait::async_trait;
use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet};
use serde::{Deserialize, Serialize};
use crate::PhotoSource;
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum BrowserSource {
GoogleMaps,
Instagram,
}
impl BrowserSource {
pub fn photo_source_id(self) -> PhotoSourceId {
match self {
BrowserSource::GoogleMaps => PhotoSourceId::GoogleMaps,
BrowserSource::Instagram => PhotoSourceId::Instagram,
}
}
}
#[derive(Debug, Serialize)]
pub struct JobRequest<'a> {
pub source: BrowserSource,
pub place: JobPlace<'a>,
pub limit: usize,
pub callback_url: Option<String>,
}
#[derive(Debug, Serialize)]
pub struct JobPlace<'a> {
pub name: &'a str,
pub address: &'a str,
pub lat: f64,
pub lng: f64,
}
#[derive(Debug, Deserialize)]
pub struct JobCreated {
pub job_id: String,
}
#[derive(Debug, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum JobState {
Queued,
Running,
Done,
Failed,
}
#[derive(Debug, Deserialize)]
pub struct JobResult {
pub status: JobState,
#[serde(default)]
pub items: Vec<JobItem>,
#[serde(default)]
pub texts: Vec<JobText>,
pub error: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct JobItem {
pub image_url: String,
#[serde(default)]
pub caption: String,
#[serde(default)]
pub source_url: String,
pub taken_at: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct JobText {
pub text: String,
#[serde(default)]
pub source_url: String,
}
/// HTTP client for the real service.
pub struct BrowserScraperClient {
client: reqwest::Client,
base: String,
source: BrowserSource,
poll_every: Duration,
timeout: Duration,
}
impl BrowserScraperClient {
pub fn new(base: impl Into<String>, source: BrowserSource) -> Self {
Self {
client: crate::http::api_client(),
base: base.into().trim_end_matches('/').to_string(),
source,
poll_every: Duration::from_secs(2),
timeout: Duration::from_secs(120),
}
}
}
#[async_trait]
impl PhotoSource for BrowserScraperClient {
fn id(&self) -> PhotoSourceId {
self.source.photo_source_id()
}
async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> {
let req = JobRequest {
source: self.source,
place: JobPlace {
name: &place.name,
address: if place.road_address.is_empty() { &place.address } else { &place.road_address },
lat: place.lat,
lng: place.lng,
},
limit,
callback_url: None,
};
let created: JobCreated = self
.client
.post(format!("{}/jobs", self.base))
.json(&req)
.send()
.await?
.error_for_status()?
.json()
.await?;
let deadline = tokio::time::Instant::now() + self.timeout;
loop {
tokio::time::sleep(self.poll_every).await;
let r: JobResult = self
.client
.get(format!("{}/jobs/{}", self.base, created.job_id))
.send()
.await?
.error_for_status()?
.json()
.await?;
match r.status {
JobState::Done => return Ok(to_output(self.id(), r)),
JobState::Failed => anyhow::bail!("browser scraper failed: {}", r.error.unwrap_or_default()),
_ if tokio::time::Instant::now() > deadline => anyhow::bail!("browser scraper timed out"),
_ => {}
}
}
}
}
fn to_output(source: PhotoSourceId, r: JobResult) -> SourceOutput {
SourceOutput {
photos: r
.items
.into_iter()
.map(|i| RawPhoto {
source,
image_url: i.image_url,
page_url: i.source_url,
caption: i.caption,
referer: None,
})
.collect(),
texts: r
.texts
.into_iter()
.map(|t| TextSnippet { source, url: t.source_url, text: t.text })
.collect(),
}
}
/// Stand-in used until the browser service exists. Returns nothing (but succeeds)
/// so the pipeline treats the source as "empty" rather than failed.
pub struct MockBrowserScraper {
source: BrowserSource,
}
impl MockBrowserScraper {
pub fn new(source: BrowserSource) -> Self {
Self { source }
}
}
#[async_trait]
impl PhotoSource for MockBrowserScraper {
fn id(&self) -> PhotoSourceId {
self.source.photo_source_id()
}
async fn collect(&self, place: &Place, _limit: usize) -> anyhow::Result<SourceOutput> {
tracing::info!(source = ?self.source, place = %place.name, "browser scraper not configured (mock): returning no results");
Ok(SourceOutput::default())
}
}
/// Pick the real client or the mock depending on configuration.
pub fn browser_source(base_url: Option<&str>, source: BrowserSource) -> Box<dyn PhotoSource> {
match base_url.filter(|u| !u.trim().is_empty()) {
Some(u) => Box::new(BrowserScraperClient::new(u, source)),
None => Box::new(MockBrowserScraper::new(source)),
}
}
+60
View File
@@ -0,0 +1,60 @@
use std::time::Duration;
use regex::Regex;
pub const DESKTOP_UA: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
pub const MOBILE_UA: &str = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.5 Mobile/15E148 Safari/604.1";
/// Shared HTTP client for scraping: browser UA, cookies, gzip, sane timeouts.
pub fn scraping_client() -> reqwest::Client {
reqwest::Client::builder()
.user_agent(DESKTOP_UA)
.cookie_store(true)
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(25))
.default_headers({
let mut h = reqwest::header::HeaderMap::new();
h.insert(reqwest::header::ACCEPT_LANGUAGE, "ko-KR,ko;q=0.9,en;q=0.8".parse().unwrap());
h
})
.build()
.expect("reqwest client")
}
/// Client for official JSON APIs.
pub fn api_client() -> reqwest::Client {
reqwest::Client::builder()
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(20))
.build()
.expect("reqwest client")
}
/// Extract image URLs from arbitrary text (HTML, embedded JSON) whose host matches
/// one of `host_patterns` (regex fragments). Handles `\/` and `\u002F` escaping.
pub fn extract_image_urls(body: &str, host_patterns: &[&str]) -> Vec<String> {
let unescaped = body.replace("\\u002F", "/").replace("\\/", "/").replace("&amp;", "&");
let hosts = host_patterns.join("|");
let re = Regex::new(&format!(
r#"https?://(?:{hosts})[^\s"'<>\\)]*?\.(?:jpe?g|png|webp|JPE?G|PNG|WEBP)(?:\?[^\s"'<>\\)]*)?"#
))
.expect("valid regex");
let mut seen = std::collections::HashSet::new();
re.find_iter(&unescaped)
.map(|m| m.as_str().to_string())
.filter(|u| seen.insert(u.clone()))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_escaped_urls() {
let body = r#"{"a":"https:\/\/ldb-phinf.pstatic.net\/2024\/abc.jpg","b":"https:\u002F\u002Fldb-phinf.pstatic.net\u002Fx\u002Fy.JPG?type=w750"}"#;
let urls = extract_image_urls(body, &[r"ldb-phinf\.pstatic\.net"]);
assert_eq!(urls.len(), 2);
assert!(urls[1].ends_with("?type=w750"));
}
}
+253
View File
@@ -0,0 +1,253 @@
//! Kakao Local REST API (official) with a keyless web-search fallback (`search.map.kakao.com`).
//! Docs: https://developers.kakao.com/docs/latest/ko/local/dev-guide
use async_trait::async_trait;
use domain::PlaceCandidate;
use serde::Deserialize;
use crate::PlaceSearch;
const BASE: &str = "https://dapi.kakao.com/v2/local";
const WEB_SEARCH: &str = "https://search.map.kakao.com/mapsearch/map.daum";
pub struct KakaoLocal {
client: reqwest::Client,
scrape_client: reqwest::Client,
key: String,
}
impl KakaoLocal {
pub fn new(key: impl Into<String>) -> Self {
Self {
client: crate::http::api_client(),
scrape_client: crate::http::scraping_client(),
key: key.into().trim().to_string(),
}
}
pub fn has_api_key(&self) -> bool {
!self.key.is_empty()
}
async fn get<T: for<'de> Deserialize<'de>>(&self, path: &str, query: &[(&str, String)]) -> anyhow::Result<T> {
let resp = self
.client
.get(format!("{BASE}/{path}"))
.header("Authorization", format!("KakaoAK {}", self.key))
.query(query)
.send()
.await?;
let status = resp.status();
if !status.is_success() {
let body = resp.text().await.unwrap_or_default();
anyhow::bail!("kakao {path} {status}: {body}");
}
Ok(resp.json().await?)
}
pub async fn keyword(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
let r: KeywordResp = self.get("search/keyword.json", &[("query", query.to_string()), ("size", "15".into())]).await?;
Ok(r.documents.into_iter().map(Into::into).collect())
}
/// Places of category (FD6 음식점, CE7 카페) around a coordinate.
pub async fn category_near(&self, code: &str, lat: f64, lng: f64, radius_m: u32) -> anyhow::Result<Vec<PlaceCandidate>> {
let r: KeywordResp = self
.get(
"search/category.json",
&[
("category_group_code", code.to_string()),
("x", lng.to_string()),
("y", lat.to_string()),
("radius", radius_m.to_string()),
("sort", "distance".into()),
],
)
.await?;
Ok(r.documents.into_iter().map(Into::into).collect())
}
/// Address → coordinates (first match).
pub async fn address(&self, query: &str) -> anyhow::Result<Option<(f64, f64, String)>> {
let r: AddressResp = self.get("search/address.json", &[("query", query.to_string())]).await?;
Ok(r.documents.into_iter().next().and_then(|d| {
Some((d.y.parse().ok()?, d.x.parse().ok()?, d.address_name))
}))
}
/// Keyless fallback via Kakao Map's web JSONP endpoint (`search.map.kakao.com/mapsearch/map.daum`).
pub async fn web_search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
let text = self
.scrape_client
.get(WEB_SEARCH)
.header(reqwest::header::REFERER, "https://map.kakao.com/")
.query(&[("callback", "j"), ("q", query), ("msFlag", "A"), ("sort", "0")])
.send()
.await?
.error_for_status()?
.text()
.await?;
parse_web_search_jsonp(&text)
}
}
pub fn parse_web_search_jsonp(text: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
let start = text.find('{').ok_or_else(|| anyhow::anyhow!("kakao web search: missing JSON object"))?;
let end = text.rfind('}').ok_or_else(|| anyhow::anyhow!("kakao web search: missing closing brace"))?;
let r: WebSearchResp = serde_json::from_str(&text[start..=end])?;
Ok(r.place
.into_iter()
.filter(|p| !p.confirmid.is_empty() && p.lat != 0.0 && p.lon != 0.0)
.map(|p| PlaceCandidate {
provider: "kakao".into(),
place_url: format!("https://place.map.kakao.com/{}", p.confirmid),
provider_id: p.confirmid,
name: p.name,
category: p.last_cate_name,
address: p.address,
road_address: p.new_address,
phone: p.tel,
lat: p.lat,
lng: p.lon,
})
.collect())
}
#[async_trait]
impl PlaceSearch for KakaoLocal {
fn name(&self) -> &'static str {
"kakao"
}
/// Uses official REST API when `KAKAO_REST_API_KEY` is set; otherwise falls back
/// to Kakao Map's web search so development works without an API key.
async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
if !self.has_api_key() {
return self.web_search(query).await;
}
match self.keyword(query).await {
Ok(mut out) => {
if out.is_empty() || looks_like_address(query) {
if let Some((lat, lng, _)) = self.address(query).await.ok().flatten() {
for code in ["FD6", "CE7"] {
for c in self.category_near(code, lat, lng, 40).await.unwrap_or_default() {
if !out.iter().any(|o| o.provider_id == c.provider_id) {
out.push(c);
}
}
}
}
}
Ok(out)
}
Err(e) => {
tracing::warn!("kakao REST search failed ({e}), falling back to web search");
self.web_search(query).await
}
}
}
}
pub fn looks_like_address(q: &str) -> bool {
let re = regex::Regex::new(r"(로|길|동|읍|면|리)\s*\d+(-\d+)?").unwrap();
re.is_match(q)
}
#[derive(Deserialize)]
struct KeywordResp {
documents: Vec<KakaoPlaceDoc>,
}
#[derive(Deserialize)]
struct KakaoPlaceDoc {
id: String,
place_name: String,
#[serde(default)]
category_name: String,
#[serde(default)]
phone: String,
#[serde(default)]
address_name: String,
#[serde(default)]
road_address_name: String,
x: String,
y: String,
#[serde(default)]
place_url: String,
}
impl From<KakaoPlaceDoc> for PlaceCandidate {
fn from(d: KakaoPlaceDoc) -> Self {
PlaceCandidate {
provider: "kakao".into(),
provider_id: d.id,
name: d.place_name,
category: d.category_name.rsplit(" > ").next().unwrap_or_default().to_string(),
address: d.address_name,
road_address: d.road_address_name,
phone: d.phone,
lat: d.y.parse().unwrap_or_default(),
lng: d.x.parse().unwrap_or_default(),
place_url: d.place_url,
}
}
}
#[derive(Deserialize)]
struct AddressResp {
documents: Vec<AddressDoc>,
}
#[derive(Deserialize)]
struct AddressDoc {
address_name: String,
x: String,
y: String,
}
#[derive(Deserialize)]
struct WebSearchResp {
#[serde(default)]
place: Vec<WebPlaceDoc>,
}
#[derive(Deserialize)]
struct WebPlaceDoc {
#[serde(default)]
confirmid: String,
#[serde(default)]
name: String,
#[serde(default)]
last_cate_name: String,
#[serde(default)]
address: String,
#[serde(default)]
new_address: String,
#[serde(default)]
tel: String,
#[serde(default)]
lat: f64,
#[serde(default)]
lon: f64,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_detection() {
assert!(looks_like_address("서울 성동구 성수이로 78"));
assert!(looks_like_address("연무장길 5-1"));
assert!(!looks_like_address("대림창고"));
}
#[test]
fn parses_jsonp() {
let raw = r#"/**/j({"place":[{"confirmid":"1128989913","name":"대림창고","last_cate_name":"갤러리카페","address":"서울 성동구 성수동2가 322-32 1층","new_address":"서울 성동구 성수이로 78","tel":"0507-1390-9669","lat":37.5417,"lon":127.0562}]});"#;
let list = parse_web_search_jsonp(raw).unwrap();
assert_eq!(list.len(), 1);
assert_eq!(list[0].provider_id, "1128989913");
assert_eq!(list[0].name, "대림창고");
}
}
+203
View File
@@ -0,0 +1,203 @@
//! Kakao Map place panel + photos (unofficial, verified 2026-11-04).
//!
//! Endpoint: `https://place-api.map.kakao.com/places/panel3/{kakao_id}`
//! Required headers: `pf: web`, `Referer: https://place.map.kakao.com/{kakao_id}`.
use std::collections::HashSet;
use async_trait::async_trait;
use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet};
use serde_json::Value;
use crate::{http, PhotoSource};
pub struct KakaoPlacePhotos {
client: reqwest::Client,
}
impl Default for KakaoPlacePhotos {
fn default() -> Self {
Self::new()
}
}
impl KakaoPlacePhotos {
pub fn new() -> Self {
Self { client: http::scraping_client() }
}
}
#[async_trait]
impl PhotoSource for KakaoPlacePhotos {
fn id(&self) -> PhotoSourceId {
PhotoSourceId::KakaoPlace
}
async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> {
let Some(id) = place.kakao_id.as_deref() else {
anyhow::bail!("kakao place id missing");
};
let url = format!("https://place-api.map.kakao.com/places/panel3/{id}");
let referer = format!("https://place.map.kakao.com/{id}");
let text = self
.client
.get(&url)
.header("pf", "web")
.header(reqwest::header::REFERER, &referer)
.header(reqwest::header::ACCEPT, "application/json")
.send()
.await?
.error_for_status()?
.text()
.await?;
parse_panel3_json(&text, &referer, limit)
}
}
pub fn parse_panel3_json(raw: &str, page_url: &str, limit: usize) -> anyhow::Result<SourceOutput> {
let v: Value = serde_json::from_str(raw)?;
let mut seen = HashSet::new();
let mut photos = Vec::new();
let mut text_parts = Vec::new();
// Address detail often contains explicit floor info, e.g. "서울 성동구 성수이로 78 1층".
if let Some(disp) = v.pointer("/summary/address/disp").and_then(Value::as_str) {
text_parts.push(format!("주소: {disp}"));
}
if let Some(detail) = v.pointer("/summary/address/address_detail_part").and_then(Value::as_str) {
if !detail.is_empty() {
text_parts.push(format!("층/호수 정보: {detail}"));
}
}
if let Some(tags) = v.pointer("/place_add_info/tags").and_then(Value::as_array) {
let t: Vec<&str> = tags.iter().filter_map(Value::as_str).collect();
if !t.is_empty() {
text_parts.push(format!("태그: {}", t.join(", ")));
}
}
if let Some(ai_summary) = v.pointer("/ai_mate/bottom_sheet/summary").and_then(Value::as_str) {
text_parts.push(ai_summary.to_string());
}
if let Some(infos) = v.pointer("/place_add_info/full_detail_infos").and_then(Value::as_array) {
for info in infos {
let title = info.get("title").and_then(Value::as_str).unwrap_or_default();
let items: Vec<&str> = info
.get("items")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(|i| i.pointer("/icon/text").and_then(Value::as_str))
.collect();
if !items.is_empty() {
text_parts.push(format!("{title}: {}", items.join(", ")));
}
}
}
// Structured photo list
if let Some(arr) = v.pointer("/photos/photos").and_then(Value::as_array) {
for item in arr {
if photos.len() >= limit {
break;
}
if let Some(u) = item.get("url").and_then(Value::as_str) {
let clean = unwrap_kakao_thumb(u);
if seen.insert(clean.clone()) {
let caption = item.get("title").and_then(Value::as_str).unwrap_or_default().to_string();
photos.push(RawPhoto {
source: PhotoSourceId::KakaoPlace,
image_url: clean,
page_url: page_url.to_string(),
caption,
referer: Some("https://place.map.kakao.com/".into()),
});
}
}
}
}
// Review texts + review photos
for review_path in ["/kakaomap_review/reviews", "/blog_review/reviews"] {
if let Some(reviews) = v.pointer(review_path).and_then(Value::as_array) {
for r in reviews {
let contents = r
.get("contents")
.or_else(|| r.get("Summary"))
.or_else(|| r.get("title"))
.and_then(Value::as_str)
.unwrap_or_default();
if contents.chars().count() >= 6 {
text_parts.push(contents.to_string());
}
if let Some(p_arr) = r.get("photos").or_else(|| r.get("photo_list")).and_then(Value::as_array) {
for p in p_arr {
if photos.len() >= limit {
break;
}
if let Some(u) = p.get("url").or_else(|| p.get("orgurl")).and_then(Value::as_str) {
let clean = unwrap_kakao_thumb(u);
if seen.insert(clean.clone()) {
photos.push(RawPhoto {
source: PhotoSourceId::KakaoPlace,
image_url: clean,
page_url: page_url.to_string(),
caption: contents.chars().take(180).collect(),
referer: Some("https://place.map.kakao.com/".into()),
});
}
}
}
}
}
}
}
let mut texts = Vec::new();
if !text_parts.is_empty() {
let joined: String = text_parts.join("\n").chars().take(3000).collect();
texts.push(TextSnippet {
source: PhotoSourceId::KakaoPlace,
url: page_url.to_string(),
text: joined,
});
}
Ok(SourceOutput { photos, texts })
}
/// Unwrap Kakao's thumbnail proxy (`?fname=https%3A%2F%2F...`) and upgrade `http://` to `https://`.
pub fn unwrap_kakao_thumb(u: &str) -> String {
if let Some(idx) = u.find("fname=") {
let encoded = &u[idx + 6..];
let end = encoded.find('&').unwrap_or(encoded.len());
if let Ok(decoded) = urlencoding::decode(&encoded[..end]) {
if decoded.starts_with("http") {
return decoded.into_owned().replace("http://", "https://");
}
}
}
u.replace("http://", "https://")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unwraps_fname_proxy() {
let u = "https://img1.kakaocdn.net/cthumb/local/R0x420/?fname=http%3A%2F%2Ft1.daumcdn.net%2Flocal%2Fabc.jpg";
assert_eq!(unwrap_kakao_thumb(u), "https://t1.daumcdn.net/local/abc.jpg");
}
#[test]
fn parses_panel_sample() {
let sample = r#"{
"summary":{"address":{"disp":"서울 성동구 성수이로 78 1층","address_detail_part":"1층"}},
"place_add_info":{"tags":["갤러리카페","루프탑있는"]},
"photos":{"photos":[{"url":"http://t1.kakaocdn.net/local/kakaomapPhoto/review/abc?original","title":"실내"}]}
}"#;
let out = parse_panel3_json(sample, "https://place.map.kakao.com/1128989913", 10).unwrap();
assert_eq!(out.photos.len(), 1);
assert!(out.photos[0].image_url.starts_with("https://"));
assert!(out.texts[0].text.contains("루프탑있는"));
}
}
+32
View File
@@ -0,0 +1,32 @@
//! External data providers: place search, geocoding and photo/text sources.
//!
//! * Official APIs: [`kakao_local`], [`ncp_geocode`]
//! * In-process scrapers: [`naver_map`], [`naver_place`], [`naver_blog`], [`kakao_place`]
//! * Delegated to the external browser scraping service: [`browser`] (Google Maps, Instagram)
pub mod browser;
pub mod http;
pub mod kakao_local;
pub mod kakao_place;
pub mod naver_blog;
pub mod naver_map;
pub mod naver_place;
pub mod ncp_geocode;
pub mod text;
use async_trait::async_trait;
use domain::{PhotoSourceId, Place, PlaceCandidate, SourceOutput};
/// Free-text place search (상호명 / 주소 → candidates).
#[async_trait]
pub trait PlaceSearch: Send + Sync {
fn name(&self) -> &'static str;
async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>>;
}
/// A source of photos and text evidence for a resolved place.
#[async_trait]
pub trait PhotoSource: Send + Sync {
fn id(&self) -> PhotoSourceId;
async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput>;
}
+244
View File
@@ -0,0 +1,244 @@
//! Naver Blog posts about the place: inline images + body text (unofficial, verified 2026-11-04).
//!
//! 1. Search `https://search.naver.com/search.naver?ssc=tab.blog.all&query=...` for `blog.naver.com/{blogId}/{logNo}` links.
//! 2. Fetch each post via `https://blog.naver.com/PostView.naver?blogId=...&logNo=...` (bypasses outer iframe).
//! 3. Parse SmartEditor (`.se-main-container`) paragraphs and `postfiles.pstatic.net` images, pairing each image
//! with nearby paragraph text as its caption.
use std::collections::HashSet;
use async_trait::async_trait;
use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet};
use futures::stream::{self, StreamExt};
use regex::Regex;
use scraper::{Html, Selector};
use crate::{http, PhotoSource};
const SEARCH_URL: &str = "https://search.naver.com/search.naver";
const POST_VIEW_URL: &str = "https://blog.naver.com/PostView.naver";
pub struct NaverBlog {
client: reqwest::Client,
max_posts: usize,
}
impl Default for NaverBlog {
fn default() -> Self {
Self::new()
}
}
impl NaverBlog {
pub fn new() -> Self {
Self { client: http::scraping_client(), max_posts: 8 }
}
async fn search_post_ids(&self, query: &str) -> anyhow::Result<Vec<(String, String)>> {
let html = self
.client
.get(SEARCH_URL)
.header(reqwest::header::REFERER, "https://search.naver.com/")
.query(&[("ssc", "tab.blog.all"), ("query", query)])
.send()
.await?
.error_for_status()?
.text()
.await?;
Ok(extract_blog_post_ids(&html))
}
async fn fetch_post(&self, blog_id: &str, log_no: &str) -> anyhow::Result<SourceOutput> {
let page_url = format!("https://blog.naver.com/{blog_id}/{log_no}");
let html = self
.client
.get(POST_VIEW_URL)
.header(reqwest::header::REFERER, "https://blog.naver.com/")
.query(&[("blogId", blog_id), ("logNo", log_no)])
.send()
.await?
.error_for_status()?
.text()
.await?;
Ok(parse_blog_post_html(&html, &page_url))
}
}
#[async_trait]
impl PhotoSource for NaverBlog {
fn id(&self) -> PhotoSourceId {
PhotoSourceId::NaverBlog
}
async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> {
let region = place.region_hint();
let q1 = format!("{} {} 내부 좌석", region, place.name);
let q2 = format!("{} {}", region, place.name);
let mut post_ids = self.search_post_ids(q1.trim()).await.unwrap_or_default();
if post_ids.len() < self.max_posts {
for id in self.search_post_ids(q2.trim()).await.unwrap_or_default() {
if !post_ids.contains(&id) {
post_ids.push(id);
}
}
}
post_ids.truncate(self.max_posts);
let results: Vec<SourceOutput> = stream::iter(post_ids)
.map(|(b, l)| async move { self.fetch_post(&b, &l).await.ok() })
.buffer_unordered(4)
.filter_map(|x| async move { x })
.collect()
.await;
let mut seen = HashSet::new();
let mut photos = Vec::new();
let mut texts = Vec::new();
for r in results {
texts.extend(r.texts);
for p in r.photos {
if photos.len() >= limit {
break;
}
if seen.insert(p.image_url.clone()) {
photos.push(p);
}
}
}
Ok(SourceOutput { photos, texts })
}
}
pub fn extract_blog_post_ids(html: &str) -> Vec<(String, String)> {
let re = Regex::new(r"https?://(?:m\.)?blog\.naver\.com/([a-zA-Z0-9_\-]+)/(\d{10,15})").unwrap();
let mut seen = HashSet::new();
let mut out = Vec::new();
for c in re.captures_iter(html) {
let pair = (c[1].to_string(), c[2].to_string());
if seen.insert(pair.clone()) {
out.push(pair);
}
}
out
}
pub fn parse_blog_post_html(html: &str, page_url: &str) -> SourceOutput {
let doc = Html::parse_document(html);
let container_sel = Selector::parse(".se-main-container, #postViewArea").unwrap();
let p_sel = Selector::parse(".se-text-paragraph, p").unwrap();
let img_sel = Selector::parse("img").unwrap();
let mut paragraphs = Vec::new();
for container in doc.select(&container_sel) {
for p in container.select(&p_sel) {
let t = p.text().collect::<Vec<_>>().join(" ");
let clean = t.split_whitespace().collect::<Vec<_>>().join(" ");
if clean.chars().count() >= 4 {
paragraphs.push(clean);
}
}
}
if paragraphs.is_empty() {
for p in doc.select(&p_sel) {
let clean = p.text().collect::<Vec<_>>().join(" ").split_whitespace().collect::<Vec<_>>().join(" ");
if clean.chars().count() >= 4 {
paragraphs.push(clean);
}
}
}
let full_text: String = paragraphs.join("\n").chars().take(3000).collect();
let mut texts = Vec::new();
if !full_text.is_empty() {
texts.push(TextSnippet {
source: PhotoSourceId::NaverBlog,
url: page_url.to_string(),
text: full_text.clone(),
});
}
let mut seen = HashSet::new();
let mut photos = Vec::new();
for img in doc.select(&img_sel) {
let v = img.value();
let src = v
.attr("data-lazy-src")
.or_else(|| v.attr("data-src"))
.or_else(|| v.attr("src"))
.unwrap_or_default();
if let Some(url) = normalize_blog_image_url(src) {
if seen.insert(url.clone()) {
photos.push(RawPhoto {
source: PhotoSourceId::NaverBlog,
image_url: url,
page_url: page_url.to_string(),
caption: String::new(),
referer: Some("https://blog.naver.com/".into()),
});
}
}
}
// Fallback regex scan if DOM attributes differed
if photos.is_empty() {
for u in http::extract_image_urls(html, &[r"postfiles\.pstatic\.net", r"blogfiles\.pstatic\.net"]) {
if let Some(url) = normalize_blog_image_url(&u) {
if seen.insert(url.clone()) {
photos.push(RawPhoto {
source: PhotoSourceId::NaverBlog,
image_url: url,
page_url: page_url.to_string(),
caption: String::new(),
referer: Some("https://blog.naver.com/".into()),
});
}
}
}
}
// Spread paragraph context across photos proportionally
if !paragraphs.is_empty() && !photos.is_empty() {
let n_p = paragraphs.len();
let n_img = photos.len();
for (i, photo) in photos.iter_mut().enumerate() {
let center = (i * n_p) / n_img;
let start = center.saturating_sub(1);
let end = (center + 2).min(n_p);
photo.caption = paragraphs[start..end].join(" ").chars().take(220).collect();
}
}
SourceOutput { photos, texts }
}
fn normalize_blog_image_url(raw: &str) -> Option<String> {
let u = raw.replace("&amp;", "&");
if !(u.contains("postfiles.pstatic.net") || u.contains("blogfiles.pstatic.net")) {
return None;
}
let lower = u.to_ascii_lowercase();
if lower.contains("sticker") || lower.contains("emoticon") || lower.contains("profile") || lower.contains(".gif") {
return None;
}
let base = u.split('?').next().unwrap_or(&u);
Some(format!("{base}?type=w966"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_blog_html() {
let html = r#"<div class="se-main-container">
<p class="se-text-paragraph">1층에서 주문하고 2층으로 올라갔어요</p>
<img data-lazy-src="https://postfiles.pstatic.net/2026/img1.JPEG?type=w80_blur"/>
<p class="se-text-paragraph">창가 바 좌석이 6자리 정도 있어요</p>
</div>"#;
let out = parse_blog_post_html(html, "https://blog.naver.com/a/123456789012");
assert_eq!(out.photos.len(), 1);
assert_eq!(out.photos[0].image_url, "https://postfiles.pstatic.net/2026/img1.JPEG?type=w966");
assert!(out.photos[0].caption.contains("2층"));
assert_eq!(out.texts.len(), 1);
}
}
+231
View File
@@ -0,0 +1,231 @@
//! Naver Map web search (unofficial, verified 2026-11-04).
//!
//! Primary endpoint: `https://map.naver.com/p/api/search/instant-search?query=...&coords=lat,lng`
//! Fallback endpoint: `https://m.place.naver.com/place/list?query=...&x=lng&y=lat` (parses `window.__APOLLO_STATE__`).
use async_trait::async_trait;
use domain::{Place, PlaceCandidate};
use serde::Deserialize;
use serde_json::Value;
use crate::{http, text, PlaceSearch};
const INSTANT_URL: &str = "https://map.naver.com/p/api/search/instant-search";
const MPLACE_LIST_URL: &str = "https://m.place.naver.com/place/list";
pub struct NaverMapSearch {
client: reqwest::Client,
}
impl Default for NaverMapSearch {
fn default() -> Self {
Self::new()
}
}
impl NaverMapSearch {
pub fn new() -> Self {
Self { client: http::scraping_client() }
}
/// Search places on Naver Map, optionally biased around `(lat, lng)`.
pub async fn search_near(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> {
let mut out = self.instant_search(query, near).await.unwrap_or_default();
if out.is_empty() {
if let Ok(fallback) = self.mobile_list_search(query, near).await {
out = fallback;
}
}
Ok(out)
}
async fn instant_search(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> {
let (lat, lng) = near.unwrap_or((37.5665, 126.9780));
let coords = format!("{lat},{lng}");
let resp = self
.client
.get(INSTANT_URL)
.header(reqwest::header::REFERER, "https://map.naver.com/")
.query(&[("query", query), ("coords", &coords)])
.send()
.await?
.error_for_status()?;
let body: InstantResp = resp.json().await?;
Ok(parse_instant(body))
}
async fn mobile_list_search(&self, query: &str, near: Option<(f64, f64)>) -> anyhow::Result<Vec<PlaceCandidate>> {
let (lat, lng) = near.unwrap_or((37.5665, 126.9780));
let html = self
.client
.get(MPLACE_LIST_URL)
.header(reqwest::header::USER_AGENT, http::MOBILE_UA)
.query(&[("query", query), ("x", &lng.to_string()), ("y", &lat.to_string())])
.send()
.await?
.error_for_status()?
.text()
.await?;
Ok(parse_apollo_place_list(&html))
}
/// Find the Naver place id matching `place` (name similarity + coordinate distance).
pub async fn resolve_place_id(&self, place: &Place) -> anyhow::Result<Option<String>> {
let queries = [
format!("{} {}", place.name, place.region_hint()),
place.name.clone(),
];
for q in queries {
let candidates = self.search_near(q.trim(), Some((place.lat, place.lng))).await.unwrap_or_default();
if let Some(id) = pick_best_match(place, &candidates) {
tracing::debug!(place = %place.name, naver_id = %id, "resolved naver place id");
return Ok(Some(id));
}
}
Ok(None)
}
}
pub fn pick_best_match(place: &Place, candidates: &[PlaceCandidate]) -> Option<String> {
candidates
.iter()
.filter_map(|c| {
let sim = text::name_similarity(&place.name, &c.name);
let dist = text::haversine_m(place.lat, place.lng, c.lat, c.lng);
// Accept either strong name similarity within 200m, or very close (<50m) with moderate name match.
if (sim >= 0.55 && dist <= 200.0) || (sim >= 0.35 && dist <= 50.0) {
let score = sim * 100.0 - (dist as f32) * 0.2;
Some((score, c.provider_id.clone()))
} else {
None
}
})
.max_by(|a, b| a.0.total_cmp(&b.0))
.map(|(_, id)| id)
}
fn parse_instant(body: InstantResp) -> Vec<PlaceCandidate> {
body.place
.into_iter()
.filter_map(|p| {
let lat: f64 = p.y.parse().ok()?;
let lng: f64 = p.x.parse().ok()?;
Some(PlaceCandidate {
provider: "naver".into(),
place_url: format!("https://m.place.naver.com/place/{}/home", p.id),
provider_id: p.id,
name: p.title,
category: p.ctg,
address: p.jibun_address,
road_address: p.road_address,
phone: String::new(),
lat,
lng,
})
})
.collect()
}
pub fn parse_apollo_place_list(html: &str) -> Vec<PlaceCandidate> {
let Some(state) = extract_apollo_state(html) else {
return Vec::new();
};
let Some(obj) = state.as_object() else {
return Vec::new();
};
let mut out = Vec::new();
for (k, v) in obj {
if !k.starts_with("PlaceListBusinessesItem:") && !k.starts_with("PlaceSummary:") {
continue;
}
let Some(id) = v.get("id").and_then(Value::as_str) else { continue };
let Some(name) = v.get("name").and_then(Value::as_str) else { continue };
let lat: f64 = v.get("y").and_then(Value::as_str).and_then(|s| s.parse().ok()).unwrap_or_default();
let lng: f64 = v.get("x").and_then(Value::as_str).and_then(|s| s.parse().ok()).unwrap_or_default();
if lat == 0.0 || lng == 0.0 {
continue;
}
let category = v.get("category").and_then(Value::as_str).unwrap_or_default().to_string();
let address = v
.get("fullAddress")
.or_else(|| v.get("address"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let road_address = v.get("roadAddress").and_then(Value::as_str).unwrap_or_default().to_string();
let phone = v
.get("phone")
.or_else(|| v.get("virtualPhone"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
out.push(PlaceCandidate {
provider: "naver".into(),
provider_id: id.to_string(),
name: name.to_string(),
category,
address,
road_address,
phone,
lat,
lng,
place_url: format!("https://m.place.naver.com/place/{id}/home"),
});
}
out
}
/// Extract the first JSON object assigned to `__APOLLO_STATE__`.
pub fn extract_apollo_state(html: &str) -> Option<Value> {
let marker = "__APOLLO_STATE__";
let idx = html.find(marker)?;
let rest = &html[idx + marker.len()..];
let brace = rest.find('{')?;
let mut de = serde_json::Deserializer::from_str(&rest[brace..]).into_iter::<Value>();
de.next()?.ok()
}
#[async_trait]
impl PlaceSearch for NaverMapSearch {
fn name(&self) -> &'static str {
"naver"
}
async fn search(&self, query: &str) -> anyhow::Result<Vec<PlaceCandidate>> {
self.search_near(query, None).await
}
}
#[derive(Deserialize)]
struct InstantResp {
#[serde(default)]
place: Vec<InstantPlace>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct InstantPlace {
id: String,
title: String,
#[serde(default)]
ctg: String,
#[serde(default)]
jibun_address: String,
#[serde(default)]
road_address: String,
x: String,
y: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_apollo_snippet() {
let html = r#"<script>window.__APOLLO_STATE__ = {"PlaceListBusinessesItem:37910590":{"id":"37910590","name":"성수동대림창고갤러리","category":"카페,디저트","fullAddress":"서울특별시 성동구 성수이로 78","roadAddress":"성수이로 78","virtualPhone":"0507-1390-9669","x":"127.0563952","y":"37.5417036"}};</script>"#;
let list = parse_apollo_place_list(html);
assert_eq!(list.len(), 1);
assert_eq!(list[0].provider_id, "37910590");
}
}
+209
View File
@@ -0,0 +1,209 @@
//! Naver Place photos + info/review text (unofficial, verified 2026-11-04).
//!
//! Fetches `https://m.place.naver.com/place/{id}/{home,photo,review/visitor}` (follows 302 to
//! `/restaurant/{id}/...` or `/cafe/{id}/...`) and extracts image URLs on `*-phinf.pstatic.net`
//! plus descriptive text from `window.__APOLLO_STATE__`.
use std::collections::HashSet;
use async_trait::async_trait;
use domain::{PhotoSourceId, Place, RawPhoto, SourceOutput, TextSnippet};
use serde_json::Value;
use crate::{http, naver_map, PhotoSource};
const PHINF_HOSTS: &[&str] = &[
r"ldb-phinf\.pstatic\.net",
r"pup-review-phinf\.pstatic\.net",
r"naverbooking-phinf\.pstatic\.net",
];
pub struct NaverPlacePhotos {
client: reqwest::Client,
}
impl Default for NaverPlacePhotos {
fn default() -> Self {
Self::new()
}
}
impl NaverPlacePhotos {
pub fn new() -> Self {
Self { client: http::scraping_client() }
}
async fn fetch_tab(&self, place_id: &str, tab: &str) -> anyhow::Result<(String, String)> {
let url = format!("https://m.place.naver.com/place/{place_id}/{tab}");
let resp = self
.client
.get(&url)
.header(reqwest::header::USER_AGENT, http::MOBILE_UA)
.header(reqwest::header::REFERER, "https://m.place.naver.com/")
.send()
.await?
.error_for_status()?;
let final_url = resp.url().to_string();
Ok((final_url, resp.text().await?))
}
}
#[async_trait]
impl PhotoSource for NaverPlacePhotos {
fn id(&self) -> PhotoSourceId {
PhotoSourceId::NaverPlace
}
async fn collect(&self, place: &Place, limit: usize) -> anyhow::Result<SourceOutput> {
let Some(place_id) = place.naver_place_id.as_deref() else {
anyhow::bail!("naver place id not resolved");
};
let mut seen = HashSet::new();
let mut photos = Vec::new();
let mut texts = Vec::new();
for tab in ["photo", "review/visitor", "information", "home"] {
if photos.len() >= limit {
break;
}
let (page_url, html) = match self.fetch_tab(place_id, tab).await {
Ok(v) => v,
Err(e) => {
tracing::debug!(place_id, tab, "naver place tab failed: {e}");
continue;
}
};
parse_naver_place_html(&html, &page_url, limit, &mut seen, &mut photos, &mut texts);
}
Ok(SourceOutput { photos, texts })
}
}
pub fn parse_naver_place_html(
html: &str,
page_url: &str,
limit: usize,
seen: &mut HashSet<String>,
photos: &mut Vec<RawPhoto>,
texts: &mut Vec<TextSnippet>,
) {
if let Some(state) = naver_map::extract_apollo_state(html) {
extract_apollo_texts_and_photos(&state, page_url, limit, seen, photos, texts);
}
for raw_url in http::extract_image_urls(html, PHINF_HOSTS) {
if photos.len() >= limit {
break;
}
if is_noise_image(&raw_url) {
continue;
}
let clean = normalize_phinf_url(&raw_url);
if seen.insert(clean.clone()) {
photos.push(RawPhoto {
source: PhotoSourceId::NaverPlace,
image_url: upgrade_phinf_size(&clean),
page_url: page_url.to_string(),
caption: String::new(),
referer: Some("https://m.place.naver.com/".into()),
});
}
}
}
fn extract_apollo_texts_and_photos(
state: &Value,
page_url: &str,
limit: usize,
seen: &mut HashSet<String>,
photos: &mut Vec<RawPhoto>,
texts: &mut Vec<TextSnippet>,
) {
let Some(obj) = state.as_object() else { return };
let mut text_lines = Vec::new();
for (_k, v) in obj {
let Some(map) = v.as_object() else { continue };
for field in ["description", "introduction", "conveniences", "parking", "direction", "body", "text"] {
if let Some(val) = map.get(field) {
match val {
Value::String(s) if s.chars().count() >= 6 => text_lines.push(s.clone()),
Value::Array(arr) => {
let joined: Vec<&str> = arr.iter().filter_map(Value::as_str).collect();
if !joined.is_empty() {
text_lines.push(joined.join(", "));
}
}
_ => {}
}
}
}
// Review or photo entries often carry both `body`/`text` and `media`/`originUrl`.
if photos.len() < limit {
if let Some(url) = map
.get("originUrl")
.or_else(|| map.get("imageUrl"))
.and_then(Value::as_str)
.filter(|u| u.contains("-phinf.pstatic.net") && !is_noise_image(u))
{
let clean = normalize_phinf_url(url);
if seen.insert(clean.clone()) {
let caption = map
.get("body")
.or_else(|| map.get("text"))
.or_else(|| map.get("description"))
.and_then(Value::as_str)
.unwrap_or_default()
.chars()
.take(200)
.collect();
photos.push(RawPhoto {
source: PhotoSourceId::NaverPlace,
image_url: upgrade_phinf_size(&clean),
page_url: page_url.to_string(),
caption,
referer: Some("https://m.place.naver.com/".into()),
});
}
}
}
}
if !text_lines.is_empty() {
text_lines.dedup();
let combined: String = text_lines.join("\n").chars().take(3000).collect();
texts.push(TextSnippet {
source: PhotoSourceId::NaverPlace,
url: page_url.to_string(),
text: combined,
});
}
}
fn normalize_phinf_url(u: &str) -> String {
u.split('?').next().unwrap_or(u).to_string()
}
fn upgrade_phinf_size(clean_url: &str) -> String {
format!("{clean_url}?type=w1200_60_sharpen")
}
fn is_noise_image(u: &str) -> bool {
let lower = u.to_ascii_lowercase();
lower.contains("profile") || lower.contains("icon") || lower.contains("logo") || lower.contains(" default")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_apollo_and_regex_photos() {
let html = r#"<script>window.__APOLLO_STATE__ = {"VisitorReview:1":{"body":"2층 창가 자리가 넓어요","originUrl":"https:\u002F\u002Fpup-review-phinf.pstatic.net\u002F2026\u002Fa.jpg?type=w300"}};</script><img src="https://ldb-phinf.pstatic.net/2025/b.jpg"/>"#;
let mut seen = HashSet::new();
let mut photos = Vec::new();
let mut texts = Vec::new();
parse_naver_place_html(html, "https://m.place.naver.com/place/1/photo", 10, &mut seen, &mut photos, &mut texts);
assert_eq!(photos.len(), 2);
assert_eq!(photos[0].caption, "2층 창가 자리가 넓어요");
assert_eq!(texts.len(), 1);
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Naver Cloud Platform Maps — Geocoding (official). Address normalization/verification only.
//! Docs: https://api.ncloud-docs.com/docs/application-maps-geocoding
use serde::Deserialize;
const URL: &str = "https://maps.apigw.ntruss.com/map-geocode/v2/geocode";
pub struct NcpGeocode {
client: reqwest::Client,
id: String,
secret: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct GeocodeResult {
pub road_address: String,
pub jibun_address: String,
pub lat: f64,
pub lng: f64,
}
impl NcpGeocode {
pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
Self { client: crate::http::api_client(), id: id.into(), secret: secret.into() }
}
pub async fn geocode(&self, query: &str) -> anyhow::Result<Option<GeocodeResult>> {
let resp = self
.client
.get(URL)
.header("x-ncp-apigw-api-key-id", &self.id)
.header("x-ncp-apigw-api-key", &self.secret)
.header("Accept", "application/json")
.query(&[("query", query)])
.send()
.await?;
let status = resp.status();
if !status.is_success() {
anyhow::bail!("ncp geocode {status}: {}", resp.text().await.unwrap_or_default());
}
let r: Resp = resp.json().await?;
Ok(r.addresses.into_iter().next().map(|a| GeocodeResult {
road_address: a.road_address,
jibun_address: a.jibun_address,
lat: a.y.parse().unwrap_or_default(),
lng: a.x.parse().unwrap_or_default(),
}))
}
}
#[derive(Deserialize)]
struct Resp {
#[serde(default)]
addresses: Vec<Addr>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Addr {
#[serde(default)]
road_address: String,
#[serde(default)]
jibun_address: String,
x: String,
y: String,
}
+139
View File
@@ -0,0 +1,139 @@
//! Text helpers: name normalization/similarity, distance, floor keyword extraction.
use regex::Regex;
use std::sync::LazyLock;
/// Lowercase, strip whitespace/punctuation so "스타벅스 성수점" ≈ "스타벅스성수점".
pub fn normalize_name(s: &str) -> String {
s.chars()
.filter(|c| c.is_alphanumeric())
.flat_map(|c| c.to_lowercase())
.collect()
}
/// Similarity in 0..=1 based on character bigram Dice coefficient.
pub fn name_similarity(a: &str, b: &str) -> f32 {
let a = normalize_name(a);
let b = normalize_name(b);
if a.is_empty() || b.is_empty() {
return 0.0;
}
if a == b {
return 1.0;
}
if a.contains(&b) || b.contains(&a) {
return 0.9;
}
let bigrams = |s: &str| -> Vec<(char, char)> {
let cs: Vec<char> = s.chars().collect();
cs.windows(2).map(|w| (w[0], w[1])).collect()
};
let ba = bigrams(&a);
let mut bb = bigrams(&b);
if ba.is_empty() || bb.is_empty() {
return 0.0;
}
let total = ba.len() + bb.len();
let mut hits = 0;
for g in &ba {
if let Some(pos) = bb.iter().position(|x| x == g) {
bb.swap_remove(pos);
hits += 1;
}
}
(2 * hits) as f32 / total as f32
}
/// Great-circle distance in meters.
pub fn haversine_m(lat1: f64, lng1: f64, lat2: f64, lng2: f64) -> f64 {
let r = 6_371_000.0_f64;
let (p1, p2) = (lat1.to_radians(), lat2.to_radians());
let dp = (lat2 - lat1).to_radians();
let dl = (lng2 - lng1).to_radians();
let a = (dp / 2.0).sin().powi(2) + p1.cos() * p2.cos() * (dl / 2.0).sin().powi(2);
2.0 * r * a.sqrt().asin()
}
static FLOOR_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?x)
(?P<b>지하\s*(?P<bn>\d)\s*층|B(?P<bn2>\d)\b|지하층)
| (?P<n>\d{1,2})\s*(?:층|F\b|f\b)
| (?P<roof>루프탑|옥상)
").unwrap()
});
/// Floor mentions found in text: (level, snippet). Rooftop = `domain::ROOFTOP_LEVEL`.
pub fn floor_mentions(text: &str) -> Vec<(i32, String)> {
let mut out = Vec::new();
for caps in FLOOR_RE.captures_iter(text) {
let m = caps.get(0).unwrap();
let level = if caps.name("b").is_some() {
caps.name("bn")
.or(caps.name("bn2"))
.and_then(|x| x.as_str().parse::<i32>().ok())
.map(|n| -n)
.unwrap_or(-1)
} else if let Some(n) = caps.name("n") {
match n.as_str().parse::<i32>() {
Ok(n) if (1..=20).contains(&n) => n,
_ => continue,
}
} else if caps.name("roof").is_some() {
domain::ROOFTOP_LEVEL
} else {
continue;
};
out.push((level, snippet_around(text, m.start(), m.end(), 40)));
}
out
}
/// Text window of roughly `radius` chars around a byte range, on char boundaries.
pub fn snippet_around(text: &str, start: usize, end: usize, radius: usize) -> String {
let mut s = start;
for _ in 0..radius {
if s == 0 {
break;
}
s -= 1;
while !text.is_char_boundary(s) {
s -= 1;
}
}
let mut e = end;
for _ in 0..radius {
if e >= text.len() {
break;
}
e += 1;
while e < text.len() && !text.is_char_boundary(e) {
e += 1;
}
}
text[s..e].split_whitespace().collect::<Vec<_>>().join(" ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn similarity() {
assert!(name_similarity("스타벅스 성수점", "스타벅스성수점") > 0.99);
assert!(name_similarity("대림창고", "대림창고 갤러리컬럼") >= 0.9);
assert!(name_similarity("블루보틀", "스타벅스") < 0.2);
}
#[test]
fn floors() {
let m = floor_mentions("1층은 주문, 2층 좌석이 넓고 루프탑도 있어요. 지하 1층 화장실");
let levels: Vec<i32> = m.iter().map(|x| x.0).collect();
assert_eq!(levels, vec![1, 2, domain::ROOFTOP_LEVEL, -1]);
}
#[test]
fn distance() {
let d = haversine_m(37.5446, 127.0557, 37.5450, 127.0557);
assert!((d - 44.5).abs() < 2.0);
}
}
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "storage"
edition.workspace = true
version.workspace = true
[dependencies]
domain = { workspace = true }
mongodb = { workspace = true }
object_store = { workspace = true }
bytes = { workspace = true }
serde = { workspace = true }
futures = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
chrono = { workspace = true }
[dev-dependencies]
tokio = { workspace = true }
+557
View File
@@ -0,0 +1,557 @@
//! MongoDB repositories + MinIO (S3) blob store, with automatic in-memory fallback
//! when MongoDB or MinIO is not yet configured/reachable in local development.
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use bytes::Bytes;
use domain::{JobEvent, JobStatus, Layout, Photo, PhotoTag, Place, RecentPlace};
use futures::TryStreamExt;
use mongodb::bson::{self, doc};
use mongodb::options::ClientOptions;
use mongodb::{Collection, Database};
use object_store::aws::AmazonS3Builder;
use object_store::memory::InMemory;
use object_store::path::Path as ObjPath;
use object_store::{ObjectStore, PutPayload};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone)]
pub struct StorageConfig {
pub mongodb_uri: String,
pub mongodb_db: String,
pub minio_endpoint: String,
pub minio_access_key: String,
pub minio_secret_key: String,
pub minio_bucket: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LayoutDoc {
#[serde(rename = "_id")]
pub id: String,
pub place_id: String,
pub version: i64,
pub created_at: String,
pub layout: Layout,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JobDoc {
#[serde(rename = "_id")]
pub id: String,
pub place_id: String,
pub status: JobStatus,
pub events: Vec<JobEvent>,
pub created_at: String,
pub updated_at: String,
}
/// Text evidence persisted per place (blog bodies, place info).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextDoc {
pub place_id: String,
pub source: domain::PhotoSourceId,
pub url: String,
pub text: String,
}
/// View history is separate from place metadata, which analysis may replace.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct PlaceViewDoc {
#[serde(rename = "_id")]
place_id: String,
last_viewed_at: String,
}
const RECENT_PLACES_LIMIT: usize = 50;
#[derive(Default)]
struct MemDb {
places: HashMap<String, Place>,
place_views: HashMap<String, String>,
photos: HashMap<String, Photo>,
layouts: HashMap<String, Vec<LayoutDoc>>,
jobs: HashMap<String, JobDoc>,
texts: HashMap<String, Vec<TextDoc>>,
}
#[derive(Clone)]
pub struct Store {
db: Option<Database>,
mem: Arc<RwLock<MemDb>>,
blobs: Arc<dyn ObjectStore>,
mem_blobs: Arc<InMemory>,
}
fn now() -> String {
chrono::Utc::now().to_rfc3339()
}
fn recent_places_from_memory(mem: &MemDb) -> Vec<RecentPlace> {
let mut places: Vec<_> = mem
.layouts
.iter()
.filter_map(|(place_id, versions)| {
let place = mem.places.get(place_id)?.clone();
let latest = versions.iter().max_by(|a, b| {
a.version.cmp(&b.version).then(a.created_at.cmp(&b.created_at))
})?;
Some(RecentPlace {
place,
analyzed_at: latest.created_at.clone(),
last_viewed_at: mem.place_views.get(place_id).cloned(),
floor_labels: latest.layout.floors.iter().map(|f| f.label.clone()).collect(),
seat_estimate: latest.layout.summary.seat_estimate,
})
})
.collect();
// MongoDB dates have millisecond precision. Match that ordering in fallback mode.
let sort_time = |place: &RecentPlace| {
chrono::DateTime::parse_from_rfc3339(
place.last_viewed_at.as_deref().unwrap_or(&place.analyzed_at),
)
.map(|time| time.timestamp_millis())
.unwrap_or(0)
};
places.sort_by(|a, b| sort_time(b).cmp(&sort_time(a)).then(a.place.id.cmp(&b.place.id)));
places.truncate(RECENT_PLACES_LIMIT);
places
}
fn recent_sort_time() -> bson::Document {
// Older records use chrono's micro/nanosecond RFC3339 output. Normalize only
// fractional precision because MongoDB's date parser accepts milliseconds.
doc! { "$let": {
"vars": { "raw": { "$ifNull": ["$last_viewed_at", "$analyzed_at"] } },
"in": { "$let": {
"vars": { "precise": { "$regexFind": {
"input": "$$raw",
"regex": r"^(.*\.\d{3})\d+(Z|[+-]\d{2}:\d{2})$"
} } },
"in": { "$convert": {
"input": { "$cond": [
{ "$ne": ["$$precise", bson::Bson::Null] },
{ "$concat": [
{ "$arrayElemAt": ["$$precise.captures", 0] },
{ "$arrayElemAt": ["$$precise.captures", 1] }
] },
"$$raw"
] },
"to": "date",
"onError": bson::DateTime::from_millis(0),
"onNull": bson::DateTime::from_millis(0)
} }
} }
} }
}
impl Store {
pub async fn connect(cfg: &StorageConfig) -> anyhow::Result<Self> {
let mut opts = ClientOptions::parse(&cfg.mongodb_uri).await?;
opts.server_selection_timeout = Some(Duration::from_secs(3));
opts.connect_timeout = Some(Duration::from_secs(3));
let client = mongodb::Client::with_options(opts)?;
let candidate_db = client.database(&cfg.mongodb_db);
let db = match candidate_db.run_command(doc! { "ping": 1 }).await {
Ok(_) => {
tracing::info!(uri = %cfg.mongodb_uri, db = %cfg.mongodb_db, "connected to MongoDB");
Some(candidate_db)
}
Err(e) => {
tracing::warn!("MongoDB unreachable ({e}); using in-memory store until MongoDB is available");
None
}
};
let mem_blobs = Arc::new(InMemory::new());
let blobs: Arc<dyn ObjectStore> = if !cfg.minio_access_key.trim().is_empty()
&& !cfg.minio_secret_key.trim().is_empty()
{
let s3 = AmazonS3Builder::new()
.with_endpoint(&cfg.minio_endpoint)
.with_bucket_name(&cfg.minio_bucket)
.with_access_key_id(&cfg.minio_access_key)
.with_secret_access_key(&cfg.minio_secret_key)
.with_region("us-east-1")
.with_allow_http(true)
.with_virtual_hosted_style_request(false)
.build()?;
let probe = ObjPath::from("_health/probe.txt");
match s3.put(&probe, PutPayload::from_static(b"ok")).await {
Ok(_) => {
tracing::info!(endpoint = %cfg.minio_endpoint, bucket = %cfg.minio_bucket, "connected to MinIO/S3");
Arc::new(s3)
}
Err(e) => {
tracing::warn!("MinIO bucket '{}' not reachable ({e}); falling back to in-memory blob store", cfg.minio_bucket);
mem_blobs.clone()
}
}
} else {
tracing::warn!("MINIO_ACCESS_KEY/MINIO_SECRET_KEY empty; using in-memory blob store");
mem_blobs.clone()
};
Ok(Self {
db,
mem: Arc::new(RwLock::new(MemDb::default())),
blobs,
mem_blobs,
})
}
pub async fn health_check(&self) -> anyhow::Result<()> {
if let Some(db) = &self.db {
db.run_command(doc! { "ping": 1 }).await?;
}
let probe = ObjPath::from("_health/probe.txt");
self.blobs.put(&probe, PutPayload::from_static(b"ok")).await?;
self.blobs.get(&probe).await?.bytes().await?;
Ok(())
}
pub async fn ensure_indexes(&self) -> anyhow::Result<()> {
let Some(db) = &self.db else { return Ok(()) };
use mongodb::IndexModel;
db.collection::<Photo>("photos")
.create_index(IndexModel::builder().keys(doc! { "place_id": 1 }).build())
.await?;
db.collection::<LayoutDoc>("layouts")
.create_index(IndexModel::builder().keys(doc! { "place_id": 1, "version": -1 }).build())
.await?;
db.collection::<JobDoc>("jobs")
.create_index(IndexModel::builder().keys(doc! { "place_id": 1, "created_at": -1 }).build())
.await?;
db.collection::<TextDoc>("texts")
.create_index(IndexModel::builder().keys(doc! { "place_id": 1 }).build())
.await?;
Ok(())
}
fn places(&self) -> Option<Collection<Place>> {
self.db.as_ref().map(|d| d.collection("places"))
}
fn photos(&self) -> Option<Collection<Photo>> {
self.db.as_ref().map(|d| d.collection("photos"))
}
fn layouts(&self) -> Option<Collection<LayoutDoc>> {
self.db.as_ref().map(|d| d.collection("layouts"))
}
fn jobs(&self) -> Option<Collection<JobDoc>> {
self.db.as_ref().map(|d| d.collection("jobs"))
}
fn texts(&self) -> Option<Collection<TextDoc>> {
self.db.as_ref().map(|d| d.collection("texts"))
}
// ---------- places ----------
pub async fn upsert_place(&self, place: &Place) -> anyhow::Result<()> {
self.mem.write().unwrap().places.insert(place.id.clone(), place.clone());
if let Some(col) = self.places() {
col.replace_one(doc! { "_id": &place.id }, place).upsert(true).await?;
}
Ok(())
}
pub async fn get_place(&self, id: &str) -> anyhow::Result<Option<Place>> {
if let Some(col) = self.places() {
if let Ok(Some(p)) = col.find_one(doc! { "_id": id }).await {
return Ok(Some(p));
}
}
Ok(self.mem.read().unwrap().places.get(id).cloned())
}
pub async fn record_place_view(&self, place_id: &str) -> anyhow::Result<()> {
let viewed_at = now();
self.mem
.write()
.unwrap()
.place_views
.insert(place_id.to_string(), viewed_at.clone());
if let Some(db) = &self.db {
db.collection::<PlaceViewDoc>("place_views")
.update_one(
doc! { "_id": place_id },
doc! { "$set": { "last_viewed_at": viewed_at } },
)
.upsert(true)
.await?;
}
Ok(())
}
/// Latest saved analyses, including analyses created before view tracking existed.
pub async fn recent_places(&self) -> anyhow::Result<Vec<RecentPlace>> {
if let Some(col) = self.layouts() {
// Project only card data rather than loading every historical 3D layout.
let pipeline = vec![
doc! { "$sort": { "place_id": 1, "version": -1, "created_at": -1, "_id": 1 } },
doc! { "$group": { "_id": "$place_id", "latest": { "$first": "$$ROOT" } } },
doc! { "$lookup": {
"from": "places", "localField": "_id", "foreignField": "_id", "as": "place"
} },
doc! { "$unwind": "$place" },
doc! { "$lookup": {
"from": "place_views", "localField": "_id", "foreignField": "_id", "as": "views"
} },
doc! { "$project": {
"_id": 0,
"place": 1,
"analyzed_at": "$latest.created_at",
"last_viewed_at": { "$ifNull": [
{ "$arrayElemAt": ["$views.last_viewed_at", 0] }, bson::Bson::Null
] },
"floor_labels": "$latest.layout.floors.label",
"seat_estimate": "$latest.layout.summary.seat_estimate"
} },
doc! { "$set": { "sort_time": recent_sort_time() } },
doc! { "$sort": { "sort_time": -1, "place._id": 1 } },
doc! { "$limit": RECENT_PLACES_LIMIT as i64 },
doc! { "$unset": "sort_time" },
];
let result = async {
let docs = col.aggregate(pipeline).await?.try_collect::<Vec<_>>().await?;
docs.into_iter()
.map(bson::from_document::<RecentPlace>)
.collect::<Result<Vec<_>, _>>()
.map_err(anyhow::Error::from)
}
.await;
match result {
Ok(list) if !list.is_empty() => return Ok(list),
Err(error) => {
let fallback = recent_places_from_memory(&self.mem.read().unwrap());
if fallback.is_empty() {
return Err(error);
}
tracing::warn!(%error, "recent places query failed; using in-memory history");
return Ok(fallback);
}
_ => {}
}
}
Ok(recent_places_from_memory(&self.mem.read().unwrap()))
}
// ---------- photos ----------
pub async fn insert_photo(&self, photo: &Photo) -> anyhow::Result<()> {
self.mem.write().unwrap().photos.insert(photo.id.clone(), photo.clone());
if let Some(col) = self.photos() {
col.replace_one(doc! { "_id": &photo.id }, photo).upsert(true).await?;
}
Ok(())
}
pub async fn photos_for_place(&self, place_id: &str) -> anyhow::Result<Vec<Photo>> {
if let Some(col) = self.photos() {
if let Ok(cur) = col.find(doc! { "place_id": place_id }).await {
if let Ok(list) = cur.try_collect::<Vec<Photo>>().await {
if !list.is_empty() {
return Ok(list);
}
}
}
}
Ok(self
.mem
.read()
.unwrap()
.photos
.values()
.filter(|p| p.place_id == place_id)
.cloned()
.collect())
}
pub async fn get_photo(&self, id: &str) -> anyhow::Result<Option<Photo>> {
if let Some(col) = self.photos() {
if let Ok(Some(p)) = col.find_one(doc! { "_id": id }).await {
return Ok(Some(p));
}
}
Ok(self.mem.read().unwrap().photos.get(id).cloned())
}
pub async fn set_photo_tag(&self, id: &str, tag: &PhotoTag) -> anyhow::Result<()> {
if let Some(p) = self.mem.write().unwrap().photos.get_mut(id) {
p.tag = Some(tag.clone());
}
if let Some(col) = self.photos() {
col.update_one(doc! { "_id": id }, doc! { "$set": { "tag": bson::to_bson(tag)? } })
.await?;
}
Ok(())
}
pub async fn delete_photos_for_place(&self, place_id: &str) -> anyhow::Result<()> {
self.mem.write().unwrap().photos.retain(|_, p| p.place_id != place_id);
if let Some(col) = self.photos() {
col.delete_many(doc! { "place_id": place_id }).await?;
}
Ok(())
}
// ---------- texts ----------
pub async fn replace_texts(&self, place_id: &str, texts: &[TextDoc]) -> anyhow::Result<()> {
self.mem
.write()
.unwrap()
.texts
.insert(place_id.to_string(), texts.to_vec());
if let Some(col) = self.texts() {
col.delete_many(doc! { "place_id": place_id }).await?;
if !texts.is_empty() {
col.insert_many(texts).await?;
}
}
Ok(())
}
pub async fn texts_for_place(&self, place_id: &str) -> anyhow::Result<Vec<TextDoc>> {
if let Some(col) = self.texts() {
if let Ok(cur) = col.find(doc! { "place_id": place_id }).await {
if let Ok(list) = cur.try_collect::<Vec<TextDoc>>().await {
if !list.is_empty() {
return Ok(list);
}
}
}
}
Ok(self
.mem
.read()
.unwrap()
.texts
.get(place_id)
.cloned()
.unwrap_or_default())
}
// ---------- layouts ----------
pub async fn save_layout(&self, layout: &Layout) -> anyhow::Result<LayoutDoc> {
let version = self.latest_layout(&layout.place_id).await?.map(|d| d.version + 1).unwrap_or(1);
let d = LayoutDoc {
id: format!("{}#v{version}", layout.place_id),
place_id: layout.place_id.clone(),
version,
created_at: now(),
layout: layout.clone(),
};
self.mem
.write()
.unwrap()
.layouts
.entry(layout.place_id.clone())
.or_default()
.push(d.clone());
if let Some(col) = self.layouts() {
col.insert_one(&d).await?;
}
Ok(d)
}
pub async fn latest_layout(&self, place_id: &str) -> anyhow::Result<Option<LayoutDoc>> {
if let Some(col) = self.layouts() {
if let Ok(Some(d)) = col
.find_one(doc! { "place_id": place_id })
.sort(doc! { "version": -1 })
.await
{
return Ok(Some(d));
}
}
Ok(self
.mem
.read()
.unwrap()
.layouts
.get(place_id)
.and_then(|v| v.last().cloned()))
}
// ---------- jobs ----------
pub async fn create_job(&self, id: &str, place_id: &str) -> anyhow::Result<()> {
let t = now();
let doc = JobDoc {
id: id.to_string(),
place_id: place_id.to_string(),
status: JobStatus::Running,
events: vec![],
created_at: t.clone(),
updated_at: t,
};
self.mem.write().unwrap().jobs.insert(id.to_string(), doc.clone());
if let Some(col) = self.jobs() {
col.insert_one(doc).await?;
}
Ok(())
}
pub async fn push_job_event(&self, id: &str, ev: &JobEvent) -> anyhow::Result<()> {
if let Some(j) = self.mem.write().unwrap().jobs.get_mut(id) {
j.updated_at = now();
if matches!(ev, JobEvent::Done { .. }) {
j.status = JobStatus::Done;
} else if matches!(ev, JobEvent::Error { .. }) {
j.status = JobStatus::Failed;
}
j.events.push(ev.clone());
}
if let Some(col) = self.jobs() {
let mut set = doc! { "updated_at": now() };
match ev {
JobEvent::Done { .. } => {
set.insert("status", bson::to_bson(&JobStatus::Done)?);
}
JobEvent::Error { .. } => {
set.insert("status", bson::to_bson(&JobStatus::Failed)?);
}
_ => {}
}
col.update_one(
doc! { "_id": id },
doc! { "$push": { "events": bson::to_bson(ev)? }, "$set": set },
)
.await?;
}
Ok(())
}
pub async fn get_job(&self, id: &str) -> anyhow::Result<Option<JobDoc>> {
if let Some(col) = self.jobs() {
if let Ok(Some(j)) = col.find_one(doc! { "_id": id }).await {
return Ok(Some(j));
}
}
Ok(self.mem.read().unwrap().jobs.get(id).cloned())
}
// ---------- blobs ----------
pub async fn put_blob(&self, key: &str, bytes: Bytes) -> anyhow::Result<()> {
let p = ObjPath::from(key);
if self.blobs.put(&p, PutPayload::from(bytes.clone())).await.is_err() {
self.mem_blobs.put(&p, PutPayload::from(bytes)).await?;
}
Ok(())
}
pub async fn get_blob(&self, key: &str) -> anyhow::Result<Bytes> {
let p = ObjPath::from(key);
match self.blobs.get(&p).await {
Ok(r) => Ok(r.bytes().await?),
Err(_) => Ok(self.mem_blobs.get(&p).await?.bytes().await?),
}
}
}
#[cfg(test)]
mod recent_tests;
+136
View File
@@ -0,0 +1,136 @@
use super::*;
use domain::{Accessibility, Floor, Summary, Tri};
fn store() -> Store {
let blobs = Arc::new(InMemory::new());
Store {
db: None,
mem: Arc::new(RwLock::new(MemDb::default())),
blobs: blobs.clone(),
mem_blobs: blobs,
}
}
fn place(id: &str) -> Place {
Place {
id: id.into(),
kakao_id: None,
naver_place_id: None,
name: id.into(),
category: "카페".into(),
address: String::new(),
road_address: String::new(),
phone: String::new(),
lat: 0.0,
lng: 0.0,
place_url: String::new(),
}
}
fn layout(id: &str, label: &str, seats: u32) -> Layout {
Layout {
place_id: id.into(),
generated_at: "2024-01-01T00:00:00Z".into(),
model: "test".into(),
confidence: 0.5,
floors: vec![Floor {
level: 1,
label: label.into(),
confidence: 0.5,
width_m: 10.0,
depth_m: 10.0,
openings: vec![],
zones: vec![],
verticals: vec![],
notes: String::new(),
}],
summary: Summary {
area_pyeong_min: 20.0,
area_pyeong_max: 30.0,
seat_estimate: seats,
seat_types: vec![],
highlights: vec![],
accessibility: Accessibility {
elevator: Tri::Unknown,
step_free_entrance: Tri::Unknown,
},
caveats: vec![],
},
}
}
async fn saved_place(store: &Store, id: &str, created_at: &str) {
store.upsert_place(&place(id)).await.unwrap();
store.save_layout(&layout(id, "1F", 20)).await.unwrap();
store.mem.write().unwrap().layouts.get_mut(id).unwrap()[0].created_at = created_at.into();
}
#[tokio::test]
async fn recent_places_require_metadata_and_saved_layout() {
let store = store();
store.upsert_place(&place("unfinished")).await.unwrap();
store.record_place_view("unfinished").await.unwrap();
store.save_layout(&layout("orphaned-layout", "1F", 20)).await.unwrap();
saved_place(&store, "completed", "2024-01-01T00:00:00Z").await;
let recent = store.recent_places().await.unwrap();
assert_eq!(recent.len(), 1);
assert_eq!(recent[0].place.id, "completed");
// Cached records created before this feature need no view-history migration.
assert_eq!(recent[0].last_viewed_at, None);
assert_eq!(recent[0].analyzed_at, "2024-01-01T00:00:00Z");
}
#[tokio::test]
async fn recent_places_use_latest_version_summary_once() {
let store = store();
saved_place(&store, "revised", "2024-01-01T00:00:00Z").await;
let latest = store.save_layout(&layout("revised", "2F", 42)).await.unwrap();
// The list must select the highest version even if the fallback entries are reordered.
store.mem.write().unwrap().layouts.get_mut("revised").unwrap().reverse();
let recent = store.recent_places().await.unwrap();
assert_eq!(recent.len(), 1);
assert_eq!(recent[0].floor_labels, ["2F"]);
assert_eq!(recent[0].seat_estimate, 42);
assert_eq!(recent[0].analyzed_at, latest.created_at);
}
#[tokio::test]
async fn revisiting_updates_order_and_survives_place_refresh() {
let store = store();
saved_place(&store, "older", "2024-01-01T00:00:00Z").await;
saved_place(&store, "newer", "2025-01-01T00:00:00Z").await;
assert_eq!(store.recent_places().await.unwrap()[0].place.id, "newer");
store.record_place_view("older").await.unwrap();
let mut updated = place("older");
updated.name = "Updated name".into();
store.upsert_place(&updated).await.unwrap();
let recent = store.recent_places().await.unwrap();
assert_eq!(recent[0].place.name, "Updated name");
assert_eq!(recent[0].place.id, "older");
assert!(recent[0].last_viewed_at.is_some());
assert_eq!(recent[0].analyzed_at, "2024-01-01T00:00:00Z");
}
#[tokio::test]
async fn recent_places_are_bounded_and_stable_on_timestamp_ties() {
let store = store();
for number in (0..55).rev() {
// Equivalent instants expressed with different offsets still tie.
let at = if number % 2 == 0 {
"2024-01-01T00:00:00Z"
} else {
"2024-01-01T09:00:00+09:00"
};
saved_place(&store, &format!("place-{number:02}"), at).await;
}
let recent = store.recent_places().await.unwrap();
assert_eq!(recent.len(), 50);
let ids: Vec<_> = recent.iter().map(|row| row.place.id.clone()).collect();
let expected: Vec<_> = (0..50).map(|number| format!("place-{number:02}")).collect();
assert_eq!(ids, expected);
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "frontend"
edition.workspace = true
version.workspace = true
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
app = { workspace = true, features = ["hydrate"] }
leptos = { workspace = true, features = ["hydrate"] }
console_error_panic_hook = { workspace = true }
wasm-bindgen = { workspace = true }
+7
View File
@@ -0,0 +1,7 @@
#![recursion_limit = "256"]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(app::App);
}
+787
View File
@@ -0,0 +1,787 @@
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";
const FLOOR_HEIGHT = 3.6;
const WALL_HEIGHT = 2.6;
const WALL_THICK = 0.16;
// sRGB equivalents of the Aurora light canvas and blue action palette.
const SCENE_COLORS = {
background: 0xeff0f2,
gridMajor: 0xd6d9df,
gridMinor: 0xe3e5e9,
accent: 0x235cc7,
};
const ZONE_COLORS = {
seating: 0xe8dfd1,
counter: 0xd4a373,
bar: 0xc89f81,
kitchen: 0xb7b7a4,
restroom: 0xa8dadc,
terrace: 0xccd5ae,
entrance: 0xf4e285,
other: 0xdedbd2,
};
const scenes = new Map();
let nextId = 1;
function floorIndex(floors, level) {
const sorted = [...floors].sort((a, b) => a.level - b.level);
const idx = sorted.findIndex((f) => f.level === level);
return idx >= 0 ? idx : 0;
}
function createScene(canvas, layoutJson, onZoneSelect, cleanup) {
const layout = JSON.parse(layoutJson);
if (!layout || !Array.isArray(layout.floors)) throw new Error("Invalid floor layout");
const coarsePointer = window.matchMedia("(pointer: coarse)");
const originalTouchAction = canvas.style.touchAction;
const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
cleanup.push(() => renderer.dispose());
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(SCENE_COLORS.background, 1);
const scene = new THREE.Scene();
cleanup.push(() => disposeSceneObjects(scene));
scene.fog = new THREE.FogExp2(SCENE_COLORS.background, 0.015);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 200);
const controls = new OrbitControls(camera, canvas);
cleanup.push(() => { controls.dispose(); canvas.style.touchAction = originalTouchAction; });
const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)");
controls.enableDamping = !reducedMotion.matches;
controls.dampingFactor = 0.08;
controls.maxPolarAngle = Math.PI * 0.48;
const hemi = new THREE.HemisphereLight(0xffffff, 0xaab0ba, 1.05);
scene.add(hemi);
const dir = new THREE.DirectionalLight(0xffffff, 1.25);
dir.position.set(16, 28, 18);
dir.castShadow = true;
dir.shadow.mapSize.set(2048, 2048);
dir.shadow.camera.near = 1;
dir.shadow.camera.far = 90;
const d = 24;
dir.shadow.camera.left = -d;
dir.shadow.camera.right = d;
dir.shadow.camera.top = d;
dir.shadow.camera.bottom = -d;
scene.add(dir);
const groundGrid = new THREE.GridHelper(60, 60, SCENE_COLORS.gridMajor, SCENE_COLORS.gridMinor);
groundGrid.position.y = -0.08;
scene.add(groundGrid);
const floorGroups = new Map();
const pinMeshes = [];
const floors = layout.floors || [];
floors.forEach((floor) => {
const idx = floorIndex(floors, floor.level);
const yBase = idx * FLOOR_HEIGHT;
const group = buildFloorGroup(floor, yBase, pinMeshes);
scene.add(group);
floorGroups.set(floor.level, { group, yBase, floor });
});
const maxW = Math.max(10, ...floors.map((f) => f.width_m || 10));
const maxD = Math.max(10, ...floors.map((f) => f.depth_m || 10));
const span = Math.max(maxW, maxD);
camera.position.set(span * 1.15, span * 1.05, span * 1.25);
controls.target.set(0, (floors.length - 1) * FLOOR_HEIGHT * 0.35, 0);
controls.update();
let hasSize = false;
let visible = true;
let contextLost = false;
let disposed = false;
let raf = 0;
let st;
const requestFrame = () => {
if (!disposed && !contextLost && !document.hidden && visible && hasSize && !raf) {
raf = requestAnimationFrame(animate);
}
};
let pixelRatio = 0;
const resize = () => {
const rect = canvas.getBoundingClientRect();
const w = rect.width;
const h = rect.height;
hasSize = w > 0 && h > 0;
if (!hasSize) return;
const nextPixelRatio = Math.min(window.devicePixelRatio || 1, coarsePointer.matches ? 1.5 : 2);
if (nextPixelRatio !== pixelRatio) {
renderer.setPixelRatio(nextPixelRatio);
pixelRatio = nextPixelRatio;
}
renderer.setSize(w, h, false);
camera.aspect = w / h;
// Leave room around the model on portrait and near-square phone viewports.
camera.fov = (2 * Math.atan(Math.tan((42 * Math.PI) / 360) / Math.min(1, camera.aspect / 1.15)) * 180) / Math.PI;
camera.updateProjectionMatrix();
requestFrame();
};
resize();
const ro = new ResizeObserver(resize);
cleanup.push(() => ro.disconnect());
ro.observe(canvas);
window.addEventListener("resize", resize);
cleanup.push(() => window.removeEventListener("resize", resize));
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const activePointers = new Set();
let downPos = null;
const syncInteraction = () => {
downPos = null;
controls.enabled = !coarsePointer.matches || canvas.dataset.interactive === "true";
// OrbitControls sets this to "none" in its constructor, so apply the page-scroll mode afterward.
canvas.style.touchAction = controls.enabled ? "none" : "pan-y";
};
syncInteraction();
const interactionObserver = new MutationObserver(syncInteraction);
cleanup.push(() => interactionObserver.disconnect());
interactionObserver.observe(canvas, { attributes: true, attributeFilter: ["data-interactive"] });
const onPointerModeChange = () => {
syncInteraction();
resize();
};
coarsePointer.addEventListener("change", onPointerModeChange);
cleanup.push(() => coarsePointer.removeEventListener("change", onPointerModeChange));
const onActivePointerDown = (e) => {
activePointers.add(e.pointerId);
if (activePointers.size > 1) downPos = null;
};
const onPointerDown = (e) => {
activePointers.add(e.pointerId);
// Pins remain tappable in page-scroll mode; only orbit gestures require opt-in.
if (activePointers.size !== 1 || e.isPrimary === false || e.button !== 0) {
downPos = null;
return;
}
downPos = { pointerId: e.pointerId, x: e.clientX, y: e.clientY, at: performance.now() };
};
const onPointerMove = (e) => {
if (downPos?.pointerId === e.pointerId && Math.hypot(e.clientX - downPos.x, e.clientY - downPos.y) > 6) {
downPos = null;
}
};
const onPointerUp = (e) => {
const wasOnlyPointer = activePointers.size === 1 && activePointers.has(e.pointerId);
activePointers.delete(e.pointerId);
const tap = downPos;
downPos = null;
if (!wasOnlyPointer || tap?.pointerId !== e.pointerId || performance.now() - tap.at > 800) return;
if (Math.hypot(e.clientX - tap.x, e.clientY - tap.y) > 6) return;
const rect = canvas.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
if (e.clientX < rect.left || e.clientX > rect.right || e.clientY < rect.top || e.clientY > rect.bottom) return;
pointer.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((e.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const selectablePins = pinMeshes.filter((pin) => {
if (st.activeLevel !== 0 && pin.userData.floorLevel !== st.activeLevel) return false;
for (let parent = pin; parent; parent = parent.parent) {
if (!parent.visible) return false;
}
return true;
});
const hits = raycaster.intersectObjects(selectablePins, true);
let obj = hits[0]?.object;
// The decorative pin is small; use a 44px minimum tap target around its visible center.
if (!obj) {
let distance = 22;
const projected = new THREE.Vector3();
for (const pin of selectablePins) {
pin.getWorldPosition(projected);
projected.project(camera);
if (projected.z < -1 || projected.z > 1) continue;
const x = rect.left + (projected.x + 1) * rect.width / 2;
const y = rect.top + (1 - projected.y) * rect.height / 2;
const candidateDistance = Math.hypot(e.clientX - x, e.clientY - y);
if (candidateDistance < distance) {
distance = candidateDistance;
obj = pin;
}
}
}
if (obj) {
while (obj && !obj.userData?.photoIds) {
obj = obj.parent;
}
if (obj && obj.userData?.photoIds && typeof onZoneSelect === "function") {
highlightZone(st.id, obj.userData.zoneLabel, JSON.stringify(obj.userData.photoIds));
onZoneSelect(obj.userData.zoneLabel || "구역", JSON.stringify(obj.userData.photoIds));
}
}
};
const onPointerCancel = (e) => {
activePointers.delete(e.pointerId);
downPos = null;
};
canvas.addEventListener("pointerdown", onPointerDown);
window.addEventListener("pointerdown", onActivePointerDown, true);
window.addEventListener("pointermove", onPointerMove, true);
canvas.addEventListener("lostpointercapture", onPointerCancel);
// Capture release/cancel even when a scrolling or dragged pointer leaves the canvas.
window.addEventListener("pointerup", onPointerUp, true);
window.addEventListener("pointercancel", onPointerCancel, true);
cleanup.push(() => {
canvas.removeEventListener("pointerdown", onPointerDown);
window.removeEventListener("pointerdown", onActivePointerDown, true);
window.removeEventListener("pointermove", onPointerMove, true);
canvas.removeEventListener("lostpointercapture", onPointerCancel);
window.removeEventListener("pointerup", onPointerUp, true);
window.removeEventListener("pointercancel", onPointerCancel, true);
});
function animate() {
raf = 0;
if (disposed || contextLost || document.hidden || !visible || !hasSize) return;
const t = performance.now() / 1000;
pinMeshes.forEach((pin, i) => {
pin.position.y = pin.userData.baseY + (reducedMotion.matches ? 0 : Math.sin(t * 2.6 + i) * 0.08);
pin.rotation.y = reducedMotion.matches ? 0 : t * 1.1 + i;
});
controls.update();
renderer.render(scene, camera);
if (!reducedMotion.matches) requestFrame();
}
const stopFrame = () => {
cancelAnimationFrame(raf);
raf = 0;
};
const onVisibilityChange = () => document.hidden ? stopFrame() : requestFrame();
document.addEventListener("visibilitychange", onVisibilityChange);
cleanup.push(() => { disposed = true; stopFrame(); document.removeEventListener("visibilitychange", onVisibilityChange); });
const intersectionObserver = new IntersectionObserver(([entry]) => {
visible = entry.isIntersecting;
visible ? requestFrame() : stopFrame();
});
intersectionObserver.observe(canvas);
cleanup.push(() => intersectionObserver.disconnect());
const onMotionChange = () => {
controls.enableDamping = !reducedMotion.matches;
requestFrame();
};
reducedMotion.addEventListener("change", onMotionChange);
controls.addEventListener("change", requestFrame);
cleanup.push(() => { reducedMotion.removeEventListener("change", onMotionChange); controls.removeEventListener("change", requestFrame); });
const onContextLost = (event) => {
event.preventDefault();
contextLost = true;
stopFrame();
reportSceneState(canvas, "공간 화면이 중단됐습니다. 잠시 후 다시 시도해 주세요.");
};
const onContextRestored = () => {
contextLost = false;
resize();
requestFrame();
reportSceneState(canvas, null);
};
canvas.addEventListener("webglcontextlost", onContextLost);
canvas.addEventListener("webglcontextrestored", onContextRestored);
cleanup.push(() => { canvas.removeEventListener("webglcontextlost", onContextLost); canvas.removeEventListener("webglcontextrestored", onContextRestored); });
const id = nextId++;
st = {
id,
renderer,
scene,
camera,
controls,
floorGroups,
pinMeshes,
ro,
interactionObserver,
coarsePointer,
onPointerModeChange,
resize,
requestFrame,
reducedMotion,
onMotionChange,
intersectionObserver,
onVisibilityChange,
onContextLost,
onContextRestored,
stopAnimation: () => {
disposed = true;
stopFrame();
},
canvas,
originalTouchAction,
onPointerDown,
onActivePointerDown,
onPointerMove,
onPointerUp,
onPointerCancel,
span,
activeLevel: 0,
viewMode: "3d",
};
scenes.set(id, st);
resetScene(id);
reportSceneState(canvas, null);
requestFrame();
return id;
}
function reportSceneState(canvas, message) {
canvas.dataset.sceneError = message || "";
canvas.dispatchEvent(new Event(message ? "scene-error" : "scene-ready", { bubbles: true }));
}
export function mountScene(canvas, layoutJson, onZoneSelect) {
const cleanup = [];
try {
return createScene(canvas, layoutJson, onZoneSelect, cleanup);
} catch (error) {
cleanup.reverse().forEach((dispose) => { try { dispose(); } catch { /* Finish the remaining cleanup. */ } });
console.warn("Space viewer could not start", error?.message);
reportSceneState(canvas, "공간 화면을 열 수 없습니다. 아래 정보와 사진을 확인하거나 다시 시도해 주세요.");
return 0;
}
}
export function setFloor(handle, level) {
const st = scenes.get(handle);
if (!st) return;
if (level !== 0 && !st.floorGroups.has(level)) return;
const previousY = floorTarget(st);
st.activeLevel = level;
const offsetY = floorTarget(st) - previousY;
st.camera.position.y += offsetY;
st.controls.target.y += offsetY;
st.floorGroups.forEach(({ group, yBase }, fLevel) => {
if (level === 0) {
group.visible = true;
setGroupOpacity(group, 1.0);
} else if (fLevel === level) {
group.visible = true;
setGroupOpacity(group, 1.0);
} else if (fLevel < level) {
group.visible = st.viewMode !== "plan";
setGroupOpacity(group, 0.18);
} else {
group.visible = false;
}
});
st.controls.update();
st.requestFrame();
}
function floorTarget(st) {
return st.floorGroups.get(st.activeLevel)?.yBase ?? Math.max(0, st.floorGroups.size - 1) * FLOOR_HEIGHT * 0.35;
}
export function setViewMode(handle, mode) {
const st = scenes.get(handle);
if (!st) return;
st.viewMode = mode === "plan" ? "plan" : "3d";
const plan = st.viewMode === "plan";
st.controls.enableRotate = !plan;
st.controls.minPolarAngle = 0;
st.controls.maxPolarAngle = plan ? 0 : Math.PI * 0.48;
st.controls.screenSpacePanning = true;
st.controls.mouseButtons.LEFT = plan ? THREE.MOUSE.PAN : THREE.MOUSE.ROTATE;
st.controls.touches.ONE = plan ? THREE.TOUCH.PAN : THREE.TOUCH.ROTATE;
st.controls.touches.TWO = THREE.TOUCH.DOLLY_PAN;
setFloor(handle, st.activeLevel);
resetScene(handle);
}
export function resetScene(handle) {
const st = scenes.get(handle);
if (!st) return;
const yTarget = floorTarget(st);
const s = st.span;
// Flush accumulated damping so reset and view changes do not inherit a prior gesture.
const damping = st.controls.enableDamping;
st.controls.enableDamping = false;
st.controls.update();
st.controls.enableDamping = damping;
st.controls.minDistance = Math.max(2, s * 0.18);
st.controls.maxDistance = s * 5;
if (st.viewMode === "plan") {
st.camera.position.set(0, yTarget + s * 1.65, 0.01);
st.controls.target.set(0, yTarget, 0);
} else {
st.camera.position.set(s * 1.15, yTarget + s * 1.0, s * 1.25);
st.controls.target.set(0, yTarget + 0.4, 0);
}
st.controls.update();
st.requestFrame();
}
export function zoomScene(handle, delta) {
const st = scenes.get(handle);
if (!st || !Number.isFinite(delta)) return;
const offset = st.camera.position.clone().sub(st.controls.target);
const distance = THREE.MathUtils.clamp(offset.length() * Math.exp(-delta * 0.18), st.controls.minDistance, st.controls.maxDistance);
st.camera.position.copy(st.controls.target).add(offset.setLength(distance));
st.controls.update();
st.requestFrame();
}
export function highlightZone(handle, label, photoIdsJson) {
const st = scenes.get(handle);
if (!st) return;
let photoIds = [];
try { photoIds = JSON.parse(photoIdsJson); } catch { /* An empty selection simply clears emphasis. */ }
st.scene.traverse((obj) => {
if (!obj.userData.zoneSurface) return;
const selected = Boolean(label) && obj.userData.zoneLabel === label &&
(!photoIds.length || obj.userData.photoIds.some((id) => photoIds.includes(id)));
obj.material.emissive.setHex(selected ? SCENE_COLORS.accent : 0x000000);
obj.material.emissiveIntensity = selected ? 0.23 : 0;
});
st.pinMeshes.forEach((pin) => {
const selected = Boolean(label) && pin.userData.zoneLabel === label &&
(!photoIds.length || pin.userData.photoIds.some((id) => photoIds.includes(id)));
pin.scale.setScalar(selected ? 1.4 : 1);
});
st.requestFrame();
}
export function disposeScene(handle) {
const st = scenes.get(handle);
if (!st) return;
st.stopAnimation();
st.ro.disconnect();
st.intersectionObserver.disconnect();
st.interactionObserver.disconnect();
st.coarsePointer.removeEventListener("change", st.onPointerModeChange);
st.reducedMotion.removeEventListener("change", st.onMotionChange);
document.removeEventListener("visibilitychange", st.onVisibilityChange);
window.removeEventListener("resize", st.resize);
st.canvas.removeEventListener("pointerdown", st.onPointerDown);
window.removeEventListener("pointerdown", st.onActivePointerDown, true);
window.removeEventListener("pointermove", st.onPointerMove, true);
st.canvas.removeEventListener("lostpointercapture", st.onPointerCancel);
window.removeEventListener("pointerup", st.onPointerUp, true);
window.removeEventListener("pointercancel", st.onPointerCancel, true);
st.canvas.removeEventListener("webglcontextlost", st.onContextLost);
st.canvas.removeEventListener("webglcontextrestored", st.onContextRestored);
st.controls.removeEventListener("change", st.requestFrame);
st.controls.dispose();
st.canvas.style.touchAction = st.originalTouchAction;
disposeSceneObjects(st.scene);
st.renderer.dispose();
scenes.delete(handle);
}
function disposeSceneObjects(scene) {
const geometries = new Set();
const materials = new Set();
scene.traverse((obj) => {
if (obj.geometry) geometries.add(obj.geometry);
if (obj.material) (Array.isArray(obj.material) ? obj.material : [obj.material]).forEach((m) => materials.add(m));
if (obj.shadow) obj.shadow.dispose();
});
geometries.forEach((geometry) => geometry.dispose());
materials.forEach((material) => material.dispose());
}
function setGroupOpacity(group, opacity) {
group.traverse((obj) => {
if (obj.isMesh && obj.material) {
const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
mats.forEach((m) => {
if (m.userData.baseOpacity === undefined) {
m.userData.baseOpacity = m.opacity ?? 1.0;
m.userData.wasTransparent = m.transparent ?? false;
}
if (opacity < 0.99) {
m.transparent = true;
m.opacity = m.userData.baseOpacity * opacity;
} else {
m.transparent = m.userData.wasTransparent;
m.opacity = m.userData.baseOpacity;
}
});
}
});
}
// Convert floor local (x east 0..W, y north 0..D) into Three.js world (x east -W/2..W/2, z south -D/2..D/2)
// Note: local y=0 is SOUTH (front/entrance), which maps to z = +D/2 in Three.js so south faces the viewer.
function toWorldXZ(floor, lx, ly) {
return [lx - floor.width_m / 2, floor.depth_m / 2 - ly];
}
function buildFloorGroup(floor, yBase, pinMeshes) {
const group = new THREE.Group();
group.position.y = yBase;
const W = floor.width_m || 10;
const D = floor.depth_m || 10;
// Floor slab
const slabGeo = new THREE.BoxGeometry(W, 0.14, D);
const slabMat = new THREE.MeshStandardMaterial({ color: 0xf3ede2, roughness: 0.85 });
const slab = new THREE.Mesh(slabGeo, slabMat);
slab.position.y = -0.07;
slab.receiveShadow = true;
group.add(slab);
// Subtle perimeter walls (low cutaway height on South/East so interior is easy to see)
buildWalls(group, floor);
// Zones + furniture + pins
(floor.zones || []).forEach((zone) => {
const zg = buildZone(floor, zone, pinMeshes);
group.add(zg);
});
// Verticals (stairs / elevator)
(floor.verticals || []).forEach((v) => {
group.add(buildVertical(floor, v));
});
return group;
}
function buildWalls(group, floor) {
const W = floor.width_m;
const D = floor.depth_m;
const wallMat = new THREE.MeshStandardMaterial({ color: 0xd8d2c5, roughness: 0.75 });
const glassMat = new THREE.MeshStandardMaterial({
color: 0x8ecae6,
transparent: true,
opacity: 0.32,
roughness: 0.2,
});
const doorMat = new THREE.MeshStandardMaterial({ color: 0xe76f51, roughness: 0.6 });
// Back walls (North & West) full height; front walls (South & East) cutaway 0.9m so camera sees inside
const north = new THREE.Mesh(new THREE.BoxGeometry(W, WALL_HEIGHT, WALL_THICK), wallMat.clone());
north.position.set(0, WALL_HEIGHT / 2, -D / 2);
north.castShadow = true;
group.add(north);
const west = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, WALL_HEIGHT, D), wallMat.clone());
west.position.set(-W / 2, WALL_HEIGHT / 2, 0);
west.castShadow = true;
group.add(west);
const lowH = 0.65;
const south = new THREE.Mesh(new THREE.BoxGeometry(W, lowH, WALL_THICK), wallMat.clone());
south.position.set(0, lowH / 2, D / 2);
group.add(south);
const east = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK, lowH, D), wallMat.clone());
east.position.set(W / 2, lowH / 2, 0);
group.add(east);
// Render openings (windows as glass panels, entrances as welcome mats + arch)
(floor.openings || []).forEach((op) => {
const len = Math.max(0.9, op.length_m || 1.5);
const off = op.offset_m || 1.0;
const isWindow = op.kind === "window";
const h = isWindow ? 1.5 : 2.1;
const yCenter = isWindow ? 1.3 : h / 2;
const mat = isWindow ? glassMat.clone() : doorMat.clone();
let mesh;
if (op.wall === "south" || op.wall === "north") {
mesh = new THREE.Mesh(new THREE.BoxGeometry(len, h, WALL_THICK * 1.3), mat);
const x = -W / 2 + off + len / 2;
const z = op.wall === "south" ? D / 2 : -D / 2;
mesh.position.set(x, yCenter, z);
} else {
mesh = new THREE.Mesh(new THREE.BoxGeometry(WALL_THICK * 1.3, h, len), mat);
const z = D / 2 - (off + len / 2);
const x = op.wall === "east" ? W / 2 : -W / 2;
mesh.position.set(x, yCenter, z);
}
group.add(mesh);
});
}
function buildZone(floor, zone, pinMeshes) {
const g = new THREE.Group();
const [wx, wz] = toWorldXZ(floor, zone.x + zone.w / 2, zone.y + zone.d / 2);
g.position.set(wx, 0.02, wz);
const color = ZONE_COLORS[zone.kind] || ZONE_COLORS.other;
const pad = new THREE.Mesh(
new THREE.BoxGeometry(Math.max(0.8, zone.w - 0.12), 0.04, Math.max(0.8, zone.d - 0.12)),
new THREE.MeshStandardMaterial({ color, roughness: 0.9 })
);
pad.receiveShadow = true;
pad.userData = { zoneSurface: true, zoneLabel: zone.label || zone.kind, photoIds: zone.evidence_photos || [] };
g.add(pad);
// Place furniture groups inside the zone
(zone.furniture || []).forEach((fg) => {
populateFurniture(g, zone.w, zone.d, fg);
});
// If this zone has evidence photos, place a glowing interactive pin above it
if (zone.evidence_photos && zone.evidence_photos.length > 0) {
const pin = buildPin(zone.label || zone.kind, zone.evidence_photos);
pin.position.set(0, 1.65, 0);
pin.userData.baseY = 1.65;
pin.userData.floorLevel = floor.level;
g.add(pin);
pinMeshes.push(pin);
}
return g;
}
function populateFurniture(zoneGroup, zw, zd, fg) {
const count = Math.min(24, Math.max(1, fg.count || 1));
const cols = Math.max(1, Math.ceil(Math.sqrt(count * (zw / Math.max(1, zd)))));
const rows = Math.max(1, Math.ceil(count / cols));
const cellW = (zw * 0.82) / cols;
const cellD = (zd * 0.82) / rows;
for (let i = 0; i < count; i++) {
const r = Math.floor(i / cols);
const c = i % cols;
const x = -zw * 0.41 + (c + 0.5) * cellW;
const z = -zd * 0.41 + (r + 0.5) * cellD;
const item = buildFurnitureMesh(fg.kind, cellW, cellD);
item.position.set(x, 0.02, z);
zoneGroup.add(item);
}
}
function buildFurnitureMesh(kind, cellW, cellD) {
const g = new THREE.Group();
const wood = new THREE.MeshStandardMaterial({ color: 0x8b5e3c, roughness: 0.7 });
const darkWood = new THREE.MeshStandardMaterial({ color: 0x5c3d28, roughness: 0.75 });
const chairMat = new THREE.MeshStandardMaterial({ color: 0x3d405b, roughness: 0.8 });
const sofaMat = new THREE.MeshStandardMaterial({ color: 0x6b705c, roughness: 0.85 });
const metal = new THREE.MeshStandardMaterial({ color: 0xadb5bd, metalness: 0.5, roughness: 0.4 });
const leaf = new THREE.MeshStandardMaterial({ color: 0x52b788, roughness: 0.8 });
if (kind === "counter_bar") {
const w = Math.min(2.6, Math.max(1.2, cellW * 0.9));
const d = Math.min(1.0, Math.max(0.65, cellD * 0.6));
const body = new THREE.Mesh(new THREE.BoxGeometry(w, 0.95, d), darkWood);
body.position.y = 0.475;
body.castShadow = true;
g.add(body);
const machine = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.35, 0.35), metal);
machine.position.set(-w * 0.2, 1.12, 0);
g.add(machine);
return g;
}
if (kind === "bar_seat") {
const stool = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.2, 0.68, 12), chairMat);
stool.position.y = 0.34;
stool.castShadow = true;
g.add(stool);
return g;
}
if (kind === "sofa") {
const seat = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.42, 0.65), sofaMat);
seat.position.y = 0.21;
seat.castShadow = true;
const back = new THREE.Mesh(new THREE.BoxGeometry(1.3, 0.45, 0.16), sofaMat);
back.position.set(0, 0.55, -0.24);
g.add(seat, back);
return g;
}
if (kind === "plant") {
const pot = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.16, 0.36, 12), darkWood);
pot.position.y = 0.18;
const crown = new THREE.Mesh(new THREE.SphereGeometry(0.36, 12, 10), leaf);
crown.position.y = 0.62;
crown.castShadow = true;
g.add(pot, crown);
return g;
}
// Tables (table2, table4, table6, communal_table)
const isLarge = kind === "table6" || kind === "communal_table";
const isFour = kind === "table4";
const tw = isLarge ? 1.5 : isFour ? 0.95 : 0.68;
const td = isLarge ? 0.8 : 0.68;
const top = new THREE.Mesh(new THREE.BoxGeometry(tw, 0.06, td), wood);
top.position.y = 0.72;
top.castShadow = true;
const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.06, 0.08, 0.7, 10), metal);
leg.position.y = 0.35;
g.add(top, leg);
const chairOffsets = isLarge
? [
[-0.45, -0.52],
[0, -0.52],
[0.45, -0.52],
[-0.45, 0.52],
[0, 0.52],
[0.45, 0.52],
]
: isFour
? [
[-0.24, -0.48],
[0.24, -0.48],
[-0.24, 0.48],
[0.24, 0.48],
]
: [
[0, -0.46],
[0, 0.46],
];
chairOffsets.forEach(([cx, cz]) => {
const ch = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.44, 0.32), chairMat);
ch.position.set(cx, 0.22, cz);
ch.castShadow = true;
g.add(ch);
});
return g;
}
function buildVertical(floor, v) {
const g = new THREE.Group();
const [wx, wz] = toWorldXZ(floor, v.x + v.w / 2, v.y + v.d / 2);
g.position.set(wx, 0, wz);
const mat = new THREE.MeshStandardMaterial({ color: 0xadb5bd, roughness: 0.6 });
if (v.kind === "elevator") {
const box = new THREE.Mesh(new THREE.BoxGeometry(v.w, WALL_HEIGHT, v.d), mat);
box.position.y = WALL_HEIGHT / 2;
g.add(box);
} else {
const steps = 8;
for (let i = 0; i < steps; i++) {
const sh = ((i + 1) / steps) * (WALL_HEIGHT * 0.85);
const step = new THREE.Mesh(new THREE.BoxGeometry(v.w, sh, v.d / steps), mat);
step.position.set(0, sh / 2, -v.d / 2 + ((i + 0.5) * v.d) / steps);
step.castShadow = true;
g.add(step);
}
}
return g;
}
function buildPin(zoneLabel, photoIds) {
const g = new THREE.Group();
g.userData = { zoneLabel, photoIds };
const headMat = new THREE.MeshStandardMaterial({
color: SCENE_COLORS.accent,
emissive: SCENE_COLORS.accent,
emissiveIntensity: 0.18,
roughness: 0.3,
});
const head = new THREE.Mesh(new THREE.OctahedronGeometry(0.24, 0), headMat);
head.position.y = 0.2;
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(0.03, 0.03, 0.35, 8),
new THREE.MeshBasicMaterial({ color: SCENE_COLORS.accent })
);
g.add(head, stem);
return g;
}
+94
View File
@@ -0,0 +1,94 @@
Copyright (c) 2022, SUNN (http://sun.fo/suit),
with Reserved Font Name SUIT.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
File diff suppressed because it is too large. Load diff
+6
View File
@@ -0,0 +1,6 @@
/**
* @license
* Copyright 2010-2024 Three.js Authors
* SPDX-License-Identifier: MIT
*/
const t="170",e={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},n={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},i=0,r=1,s=2,a=3,o=0,l=1,c=2,h=3,u=0,d=1,p=2,m=0,f=1,g=2,v=3,_=4,x=5,y=100,M=101,S=102,b=103,T=104,w=200,E=201,A=202,R=203,C=204,I=205,P=206,L=207,U=208,D=209,N=210,O=211,F=212,B=213,z=214,k=0,V=1,H=2,G=3,W=4,X=5,j=6,q=7,Y=0,Z=1,J=2,K=0,$=1,Q=2,tt=3,et=4,nt=5,it=6,rt=7,st="attached",at="detached",ot=300,lt=301,ct=302,ht=303,ut=304,dt=306,pt=1e3,mt=1001,ft=1002,gt=1003,vt=1004,_t=1004,xt=1005,yt=1005,Mt=1006,St=1007,bt=1007,Tt=1008,wt=1008,Et=1009,At=1010,Rt=1011,Ct=1012,It=1013,Pt=1014,Lt=1015,Ut=1016,Dt=1017,Nt=1018,Ot=1020,Ft=35902,Bt=1021,zt=1022,kt=1023,Vt=1024,Ht=1025,Gt=1026,Wt=1027,Xt=1028,jt=1029,qt=1030,Yt=1031,Zt=1032,Jt=1033,Kt=33776,$t=33777,Qt=33778,te=33779,ee=35840,ne=35841,ie=35842,re=35843,se=36196,ae=37492,oe=37496,le=37808,ce=37809,he=37810,ue=37811,de=37812,pe=37813,me=37814,fe=37815,ge=37816,ve=37817,_e=37818,xe=37819,ye=37820,Me=37821,Se=36492,be=36494,Te=36495,we=36283,Ee=36284,Ae=36285,Re=36286,Ce=2200,Ie=2201,Pe=2202,Le=2300,Ue=2301,De=2302,Ne=2400,Oe=2401,Fe=2402,Be=2500,ze=2501,ke=0,Ve=1,He=2,Ge=3200,We=3201,Xe=3202,je=3203,qe=0,Ye=1,Ze="",Je="srgb",Ke="srgb-linear",$e="linear",Qe="srgb",tn=0,en=7680,nn=7681,rn=7682,sn=7683,an=34055,on=34056,ln=5386,cn=512,hn=513,un=514,dn=515,pn=516,mn=517,fn=518,gn=519,vn=512,_n=513,xn=514,yn=515,Mn=516,Sn=517,bn=518,Tn=519,wn=35044,En=35048,An=35040,Rn=35045,Cn=35049,In=35041,Pn=35046,Ln=35050,Un=35042,Dn="100",Nn="300 es",On=2e3,Fn=2001;class Bn{addEventListener(t,e){void 0===this._listeners&&(this._listeners={});const n=this._listeners;void 0===n[t]&&(n[t]=[]),-1===n[t].indexOf(e)&&n[t].push(e)}hasEventListener(t,e){if(void 0===this._listeners)return!1;const n=this._listeners;return void 0!==n[t]&&-1!==n[t].indexOf(e)}removeEventListener(t,e){if(void 0===this._listeners)return;const n=this._listeners[t];if(void 0!==n){const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}dispatchEvent(t){if(void 0===this._listeners)return;const e=this._listeners[t.type];if(void 0!==e){t.target=this;const n=e.slice(0);for(let e=0,i=n.length;e<i;e++)n[e].call(this,t);t.target=null}}}const zn=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];let kn=1234567;const Vn=Math.PI/180,Hn=180/Math.PI;function Gn(){const t=4294967295*Math.random()|0,e=4294967295*Math.random()|0,n=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(zn[255&t]+zn[t>>8&255]+zn[t>>16&255]+zn[t>>24&255]+"-"+zn[255&e]+zn[e>>8&255]+"-"+zn[e>>16&15|64]+zn[e>>24&255]+"-"+zn[63&n|128]+zn[n>>8&255]+"-"+zn[n>>16&255]+zn[n>>24&255]+zn[255&i]+zn[i>>8&255]+zn[i>>16&255]+zn[i>>24&255]).toLowerCase()}function Wn(t,e,n){return Math.max(e,Math.min(n,t))}function Xn(t,e){return(t%e+e)%e}function jn(t,e,n){return(1-n)*t+n*e}function qn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return t/4294967295;case Uint16Array:return t/65535;case Uint8Array:return t/255;case Int32Array:return Math.max(t/2147483647,-1);case Int16Array:return Math.max(t/32767,-1);case Int8Array:return Math.max(t/127,-1);default:throw new Error("Invalid component type.")}}function Yn(t,e){switch(e.constructor){case Float32Array:return t;case Uint32Array:return Math.round(4294967295*t);case Uint16Array:return Math.round(65535*t);case Uint8Array:return Math.round(255*t);case Int32Array:return Math.round(2147483647*t);case Int16Array:return Math.round(32767*t);case Int8Array:return Math.round(127*t);default:throw new Error("Invalid component type.")}}const Zn={DEG2RAD:Vn,RAD2DEG:Hn,generateUUID:Gn,clamp:Wn,euclideanModulo:Xn,mapLinear:function(t,e,n,i,r){return i+(t-e)*(r-i)/(n-e)},inverseLerp:function(t,e,n){return t!==e?(n-t)/(e-t):0},lerp:jn,damp:function(t,e,n,i){return jn(t,e,1-Math.exp(-n*i))},Line truncated
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "server"
edition.workspace = true
version.workspace = true
[[bin]]
name = "server"
path = "src/main.rs"
[[bin]]
name = "precompute"
path = "src/bin/precompute.rs"
[dependencies]
app = { workspace = true, features = ["ssr"] }
domain = { workspace = true }
pipeline = { workspace = true }
storage = { workspace = true }
providers = { workspace = true }
llm = { workspace = true }
leptos = { workspace = true, features = ["ssr"] }
leptos_axum = { workspace = true }
axum = { workspace = true }
tower-http = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true }
futures = { workspace = true }
serde_json = { workspace = true }
anyhow = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
dotenvy = { workspace = true }
+49
View File
@@ -0,0 +1,49 @@
//! Precompute and cache 3D layouts for demo queries.
//!
//! Usage:
//! cargo run --bin precompute -- "성수 대림창고" "어니언 성수" "블루보틀 성수"
#[path = "../config.rs"]
mod config;
use domain::Place;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let _ = dotenvy::dotenv();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "info,pipeline=debug,providers=debug".into()),
)
.init();
let pipeline = config::init_pipeline_from_env().await?;
pipeline.store.health_check().await?;
let args: Vec<String> = std::env::args().skip(1).collect();
let queries: Vec<String> = if args.is_empty() {
vec!["성수 대림창고".into(), "어니언 성수".into(), "블루보틀 성수".into()]
} else {
args
};
for q in queries {
tracing::info!(query = %q, "searching place");
let candidates = pipeline.search_places(&q).await?;
let Some(first) = candidates.into_iter().next() else {
tracing::warn!(query = %q, "no candidates found");
continue;
};
let place = Place::from_candidate(&first);
tracing::info!(place_id = %place.id, name = %place.name, "running full analysis");
let layout = pipeline.run_sync(place).await?;
tracing::info!(
place_id = %layout.place_id,
floors = layout.floors.len(),
confidence = layout.confidence,
"layout saved"
);
}
Ok(())
}
+113
View File
@@ -0,0 +1,113 @@
use llm::{LlmClient, LlmProviderConfig, ProviderKind};
use pipeline::{Pipeline, PipelineConfig};
use storage::{StorageConfig, Store};
fn env_or(key: &str, default: &str) -> String {
std::env::var(key)
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| default.to_string())
}
fn init_llm_from_env() -> anyhow::Result<LlmClient> {
if let Ok(raw_json) = std::env::var("LLM_PROVIDERS") {
let trimmed = raw_json.trim();
if !trimmed.is_empty() {
let client = LlmClient::from_json_str(trimmed)?;
let summary: Vec<String> = client
.providers()
.iter()
.map(|p| format!("{}:{} (weight={})", p.provider.as_str(), p.model, p.weight))
.collect();
tracing::info!(providers = ?summary, "initialized multi-provider LLM client from LLM_PROVIDERS");
return Ok(client);
}
}
let provider_str = env_or("LLM_PROVIDER", &env_or("PROVIDER", "cpa"));
let provider = match provider_str.to_lowercase().as_str() {
"strata" => ProviderKind::Strata,
"cpa" | "cliproxy" | "cli-proxy" => ProviderKind::Cpa,
other => ProviderKind::Custom(other.to_string()),
};
let weight: u32 = env_or("LLM_WEIGHT", &env_or("WEIGHT", "1"))
.parse()
.unwrap_or(1);
LlmClient::from_providers(vec![LlmProviderConfig {
provider,
endpoint: env_or(
"OPENAI_COMPATIBLE_API_ENDPOINT",
"http://126.dahyeon.us:8317",
),
api_key: env_or("OPENAI_COMPATIBLE_API_KEY", ""),
model: env_or("LLM_MODEL", &env_or("MODEL", "gpt-6.1-sol")),
weight,
}])
}
pub async fn init_pipeline_from_env() -> anyhow::Result<Pipeline> {
let _ = dotenvy::dotenv();
let storage_cfg = StorageConfig {
mongodb_uri: env_or(
"MONGODB_CONNECTION_STRING",
&env_or("MONGODB_URI", "mongodb://localhost:27017"),
),
mongodb_db: env_or("MONGODB_DB", "make_space"),
minio_endpoint: env_or("MINIO_ENDPOINT", "http://localhost:9000"),
minio_access_key: env_or("MINIO_ACCESS_KEY", "minioadmin"),
minio_secret_key: env_or("MINIO_SECRET_KEY", "minioadmin"),
minio_bucket: env_or("MINIO_BUCKET", "make-space-photos"),
};
let store = Store::connect(&storage_cfg).await?;
if let Err(e) = store.ensure_indexes().await {
tracing::warn!("MongoDB index creation skipped (is MongoDB reachable?): {e}");
}
let llm = init_llm_from_env()?;
let health_results = llm.health_check_all().await;
for h in &health_results {
if h.healthy {
tracing::info!(
provider = h.provider.as_str(),
endpoint = %h.endpoint,
model = %h.model,
weight = h.weight,
latency_ms = h.latency_ms,
detail = %h.detail,
"LLM provider health check passed"
);
} else {
tracing::warn!(
provider = h.provider.as_str(),
endpoint = %h.endpoint,
model = %h.model,
weight = h.weight,
latency_ms = h.latency_ms,
error = %h.detail,
"LLM provider health check failed (will remain in failover pool)"
);
}
}
let pipe_cfg = PipelineConfig {
kakao_api_key: std::env::var("KAKAO_REST_API_KEY").unwrap_or_default(),
ncp_client_id: env_or(
"X-NCP-APIGW-API-KEY-ID",
&env_or("X_NCP_APIGW_API_KEY_ID", &env_or("NCP_CLIENT_ID", "")),
),
ncp_client_secret: env_or(
"X-NCP-APIGW-API-KEY",
&env_or("X_NCP_APIGW_API_KEY", &env_or("NCP_CLIENT_SECRET", "")),
),
browser_scraper_url: std::env::var("BROWSER_SCRAPER_URL")
.ok()
.filter(|s| !s.trim().is_empty()),
max_photos_per_source: env_or("MAX_PHOTOS_PER_SOURCE", "30").parse().unwrap_or(30),
max_photos_total: env_or("MAX_PHOTOS_TOTAL", "80").parse().unwrap_or(80),
};
Ok(Pipeline::new(store, llm, pipe_cfg))
}
+244
View File
@@ -0,0 +1,244 @@
mod config;
use std::convert::Infallible;
use std::time::Duration;
use axum::extract::{Path, State};
use axum::http::{header, StatusCode};
use axum::response::sse::{Event, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use domain::JobEvent;
use futures::stream::{self, StreamExt};
use leptos::config::get_configuration;
use leptos::prelude::provide_context;
use leptos_axum::{generate_route_list, LeptosRoutes};
use pipeline::Pipeline;
use tokio_stream::wrappers::BroadcastStream;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let _ = dotenvy::dotenv();
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "info,server=debug,pipeline=debug,providers=debug".into()),
)
.init();
let pipeline = config::init_pipeline_from_env().await?;
let conf = get_configuration(None)?;
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
let routes = generate_route_list(app::App);
let pipe_for_ctx = pipeline.clone();
let app_router = Router::new()
.route("/health/live", get(health_live))
.route("/health/ready", get(health_check))
.route("/api/health", get(health_check))
.route("/api/jobs/{id}/events", get(job_events_sse))
.route("/api/photos/{id}", get(serve_photo))
.with_state(pipeline)
.leptos_routes_with_context(
&leptos_options,
routes,
move || {
provide_context(pipe_for_ctx.clone());
},
{
let opts = leptos_options.clone();
move || app::shell(opts.clone())
},
)
.fallback(leptos_axum::file_and_error_handler(app::shell))
.with_state(leptos_options);
tracing::info!("listening on http://{addr}");
let listener = tokio::net::TcpListener::bind(&addr).await?;
axum::serve(listener, app_router.into_make_service()).await?;
Ok(())
}
async fn job_events_sse(
State(pipeline): State<Pipeline>,
Path(job_id): Path<String>,
) -> Sse<impl futures::Stream<Item = Result<Event, Infallible>>> {
let (past, rx_opt) = prepare_job_subscription(pipeline.subscribe_job(&job_id).await);
let already_done = past.iter().any(|e| e.is_terminal());
let past_stream = stream::iter(past).map(|ev| {
let json = serde_json::to_string(&ev).unwrap_or_default();
Ok::<_, Infallible>(Event::default().data(json))
});
let live_stream = match rx_opt {
Some(rx) if !already_done => BroadcastStream::new(rx)
.filter_map(|item| async move { item.ok() })
.map(|ev| {
let done = ev.is_terminal();
let json = serde_json::to_string(&ev).unwrap_or_default();
(done, Ok::<_, Infallible>(Event::default().data(json)))
})
.scan(false, |finished, (done, ev)| {
let emit = if *finished { None } else { Some(ev) };
if done {
*finished = true;
}
futures::future::ready(emit)
})
.left_stream(),
_ => stream::empty().right_stream(),
};
Sse::new(past_stream.chain(live_stream)).keep_alive(
KeepAlive::new()
.interval(Duration::from_secs(10))
.text("keep-alive"),
)
}
type JobSubscription = (
Vec<JobEvent>,
Option<tokio::sync::broadcast::Receiver<JobEvent>>,
);
fn prepare_job_subscription(subscription: anyhow::Result<JobSubscription>) -> JobSubscription {
let (mut past, receiver) = match subscription {
Ok(subscription) => subscription,
Err(error) => {
tracing::warn!(%error, "could not subscribe to analysis job");
return (
vec![JobEvent::Error {
message: "분석 진행 상태를 불러오지 못했습니다. 잠시 후 다시 시도해 주세요."
.into(),
}],
None,
);
}
};
// A stored job may outlive its process. Replaying only its nonterminal history
// would make EventSource reconnect forever, resetting the client's retry counter.
if receiver.is_none() && !past.iter().any(JobEvent::is_terminal) {
let message = if past.is_empty() {
"분석 작업을 찾을 수 없습니다. 장소에서 분석을 다시 시작해 주세요."
} else {
"분석 작업이 중단됐습니다. 장소에서 분석을 다시 시작해 주세요."
};
past.push(JobEvent::Error {
message: message.into(),
});
}
(past, receiver)
}
async fn health_live() -> Response {
(
StatusCode::OK,
[(header::CONTENT_TYPE, "application/json")],
r#"{"status":"ok"}"#,
)
.into_response()
}
async fn health_check(State(pipeline): State<Pipeline>) -> Response {
let storage_ok = pipeline.store.health_check().await.is_ok();
let llm_providers = pipeline.llm.health_check_all().await;
let any_llm_healthy = llm_providers.iter().any(|p| p.healthy);
let status = if storage_ok && any_llm_healthy {
StatusCode::OK
} else {
StatusCode::SERVICE_UNAVAILABLE
};
let body = serde_json::json!({
"status": if status == StatusCode::OK { "ok" } else { "degraded" },
"storage_healthy": storage_ok,
"llm_providers": llm_providers,
});
(
status,
[(header::CONTENT_TYPE, "application/json")],
body.to_string(),
)
.into_response()
}
async fn serve_photo(State(pipeline): State<Pipeline>, Path(photo_id): Path<String>) -> Response {
let Ok(Some(photo)) = pipeline.store.get_photo(&photo_id).await else {
return StatusCode::NOT_FOUND.into_response();
};
match pipeline.store.get_blob(&photo.object_key).await {
Ok(bytes) => (
StatusCode::OK,
[
(header::CONTENT_TYPE, "image/jpeg"),
(header::CACHE_CONTROL, "public, max-age=86400"),
],
bytes,
)
.into_response(),
Err(_) => StatusCode::NOT_FOUND.into_response(),
}
}
#[cfg(test)]
mod job_events_tests {
use super::*;
#[test]
fn missing_job_returns_a_terminal_error() {
let (events, receiver) = prepare_job_subscription(Ok((Vec::new(), None)));
assert!(receiver.is_none());
assert_eq!(events.len(), 1);
assert!(
matches!(&events[0], JobEvent::Error { message } if message.contains("찾을 수 없습니다"))
);
}
#[test]
fn interrupted_job_keeps_history_then_terminates() {
let past = vec![
JobEvent::Started {
place_id: "place-1".into(),
},
JobEvent::LayoutDraft { attempt: 1 },
];
let (events, receiver) = prepare_job_subscription(Ok((past, None)));
assert!(receiver.is_none());
assert_eq!(events.len(), 3);
assert!(matches!(events[0], JobEvent::Started { .. }));
assert!(matches!(events[1], JobEvent::LayoutDraft { .. }));
assert!(matches!(&events[2], JobEvent::Error { message } if message.contains("중단")));
}
#[test]
fn subscription_failure_returns_a_user_facing_terminal_error() {
let (events, receiver) =
prepare_job_subscription(Err(anyhow::anyhow!("private storage error")));
assert!(receiver.is_none());
assert_eq!(events.len(), 1);
assert!(matches!(&events[0], JobEvent::Error { message } if !message.contains("private")));
}
#[test]
fn live_job_and_finished_job_are_not_marked_as_interrupted() {
let (_sender, receiver) = tokio::sync::broadcast::channel(2);
let (events, receiver) = prepare_job_subscription(Ok((Vec::new(), Some(receiver))));
assert!(events.is_empty());
assert!(receiver.is_some());
for terminal in [
JobEvent::Done {
place_id: "place-1".into(),
},
JobEvent::Error {
message: "analysis failed".into(),
},
] {
let (events, receiver) = prepare_job_subscription(Ok((vec![terminal], None)));
assert!(receiver.is_none());
assert_eq!(events.len(), 1);
assert!(events[0].is_terminal());
}
}
}
+373
View File
@@ -0,0 +1,373 @@
@font-face {
font-family: "SUIT Variable";
font-style: normal;
font-weight: 100 900;
font-display: swap;
src: url("/fonts/SUIT-Variable.woff2") format("woff2");
}
/* Aurora semantic tokens, adapted for the Make-Space workspace. */
:root {
color-scheme: light;
--color-bg-canvas: oklch(0.955 0.003 260);
--color-bg-surface: oklch(1 0 0);
--color-bg-raised: oklch(0.958 0.004 260);
--color-bg-hover: oklch(0.94 0.009 260);
--color-bg-pressed: oklch(0.91 0.012 260);
--color-fg-primary: oklch(0.23 0.012 260);
--color-fg-secondary: oklch(0.38 0.014 260);
--color-fg-muted: oklch(0.47 0.015 260);
--color-stroke-subtle: oklch(0.23 0.012 260 / 0.1);
--color-stroke-strong: oklch(0.23 0.012 260 / 0.26);
--color-accent-action: oklch(0.5 0.18 259);
--color-accent-action-hover: oklch(0.48 0.18 259);
--color-accent-action-pressed: oklch(0.44 0.17 259);
--color-accent-action-soft: oklch(0.5 0.18 259 / 0.08);
--color-accent-danger: oklch(0.48 0.17 24);
--color-accent-danger-soft: oklch(0.48 0.17 24 / 0.06);
--color-semantic-success: oklch(0.42 0.1 145);
--font-ui: "SUIT Variable", "Segoe UI Variable", "Apple SD Gothic Neo", "Malgun Gothic", sans-serif;
--space-1: 4px;
--space-2: 8px;
--space-3: 12px;
--space-4: 16px;
--space-5: 20px;
--space-6: 24px;
--radius-control: 12px;
--radius-surface: 20px;
--radius-overlay: 24px;
--shadow-surface: 0 1px 2px oklch(0.23 0.012 260 / 0.04);
--shadow-control: 0 1px 3px oklch(0.23 0.012 260 / 0.08);
--duration-hover: 110ms;
--ease-standard: cubic-bezier(0.2, 0, 0, 1);
}
* { box-sizing: border-box; }
html { scroll-padding-top: 128px; }
body { margin: 0; min-width: 0; background: var(--color-bg-canvas); color: var(--color-fg-primary); font-family: var(--font-ui); font-size: 14px; line-height: 1.55; -webkit-font-smoothing: antialiased; word-break: keep-all; overflow-wrap: anywhere; }
button, input, select { font: inherit; }
button, summary { cursor: pointer; }
button, a { touch-action: manipulation; -webkit-tap-highlight-color: transparent; }
button, a, input, select { transition: background-color var(--duration-hover) var(--ease-standard), color var(--duration-hover) var(--ease-standard), border-color var(--duration-hover) var(--ease-standard); }
button:disabled { cursor: default; opacity: .6; }
a { color: inherit; text-decoration: none; }
button { color: inherit; }
button[hidden], [hidden] { display: none !important; }
:focus-visible { outline: 2px solid var(--color-accent-action); outline-offset: 3px; }
::selection { background: var(--color-accent-action-soft); }
img, svg { max-width: 100%; }
h1, h2, h3, h4, strong { font-weight: 600; }
.icon { display: inline-block; width: 20px; height: 20px; flex: 0 0 20px; vertical-align: middle; }
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; }
.skip-link { position: fixed; top: 8px; left: 16px; z-index: 100; transform: translateY(-180%); padding: 12px 16px; border-radius: 12px; color: white; background: var(--color-accent-action); }
.skip-link:focus { transform: none; }
.app-shell { --page-gutter: 28px; --context-header: calc(64px + env(safe-area-inset-top, 0px)); min-height: 100dvh; }
.topbar { position: sticky; top: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: var(--context-header); padding: calc(8px + env(safe-area-inset-top, 0px)) max(var(--page-gutter), env(safe-area-inset-right, 0px)) 8px max(var(--page-gutter), env(safe-area-inset-left, 0px)); border-bottom: 1px solid var(--color-stroke-subtle); background: var(--color-bg-surface); }
.brand { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; flex-shrink: 0; }
.brand-mark { color: var(--color-accent-action); }
.brand-mark .icon { width: 24px; height: 24px; }
.brand-title { font-size: 18px; font-weight: 600; letter-spacing: -.5px; white-space: nowrap; }
.topbar-nav { display: flex; align-items: center; gap: 4px; }
.topbar-nav a { display: grid; place-items: center; min-width: 44px; min-height: 44px; padding: 9px 14px; border-radius: 10px; color: var(--color-fg-muted); font-size: 14px; white-space: nowrap; }
.topbar-nav a[aria-current="page"] { color: var(--color-accent-action); background: var(--color-accent-action-soft); font-weight: 600; }
.topbar-nav a:hover { background: var(--color-bg-hover); }
.main-body { width: 100%; max-width: 1280px; margin: 0 auto; padding: 32px max(var(--page-gutter), env(safe-area-inset-right, 0px)) max(32px, env(safe-area-inset-bottom, 0px)) max(var(--page-gutter), env(safe-area-inset-left, 0px)); }
.main-body:has(.place-page) { padding-top: 0; }
.home-wrap, .recent-page { width: 100%; max-width: 840px; margin: 0 auto; }
.search-column, .results-column { min-width: 0; }
.page-heading { margin-bottom: 20px; }
.page-heading h1 { margin: 0; font-size: 24px; line-height: 32px; letter-spacing: -.6px; }
.page-heading p { margin: 6px 0 0; color: var(--color-fg-muted); }
.search-panel { padding: 16px; background: var(--color-bg-surface); border-radius: var(--radius-surface); }
.search-bar { display: flex; gap: 8px; }
.search-field { display: flex; align-items: center; flex: 1; min-width: 0; gap: 8px; padding-left: 12px; background: var(--color-bg-raised); border: 1px solid transparent; border-radius: var(--radius-control); }
.search-field > .icon { color: var(--color-fg-muted); width: 18px; height: 18px; flex-basis: 18px; }
.search-field:focus-within { border-color: var(--color-accent-action); background: var(--color-bg-surface); box-shadow: 0 0 0 3px var(--color-accent-action-soft); }
.search-input { width: 100%; min-width: 0; min-height: 48px; padding: 10px 0; outline: 0; border: 0; background: transparent; color: var(--color-fg-primary); font-size: 16px; }
.search-input::-webkit-search-cancel-button { display: none; }
.search-input::placeholder { color: var(--color-fg-muted); opacity: 1; }
.search-clear, .icon-button { display: inline-flex; align-items: center; justify-content: center; min-width: 44px; min-height: 44px; padding: 10px; background: transparent; border: 0; border-radius: 10px; }
.search-clear:hover, .icon-button:hover { background: var(--color-bg-hover); }
.btn-primary, .btn-secondary, .btn-close, .chip, .tab, .zone-chip { display: inline-flex; align-items: center; justify-content: center; gap: 6px; min-height: 44px; padding: 10px 14px; border: 1px solid transparent; border-radius: var(--radius-control); font-size: 14px; line-height: 22px; }
.btn-primary { flex-shrink: 0; min-width: 68px; color: white; background: var(--color-accent-action); font-weight: 600; }
.btn-primary:hover:not(:disabled) { background: var(--color-accent-action-hover); }
.btn-primary:active:not(:disabled) { background: var(--color-accent-action-pressed); }
.btn-secondary { background: var(--color-bg-surface); border-color: var(--color-stroke-subtle); box-shadow: var(--shadow-surface); }
.btn-secondary:hover:not(:disabled), .btn-close:hover { background: var(--color-bg-hover); }
.quick-row { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin-top: 12px; }
.quick-label { color: var(--color-fg-muted); font-size: 12px; margin-right: 4px; }
.chip { color: var(--color-fg-secondary); background: var(--color-bg-raised); font-size: 13px; padding-inline: 10px; }
.chip:hover { background: var(--color-bg-hover); }
.discovery-home[data-has-results="true"] .search-column { position: sticky; top: var(--context-header); z-index: 20; padding-block: 8px; background: var(--color-bg-canvas); }
.discovery-home[data-has-results="true"] .search-panel { padding: 0; background: transparent; }
.discovery-home[data-has-results="true"] .search-field { background: var(--color-bg-surface); }
.search-results { margin-top: 20px; }
.search-results:not(:has(.results-heading, .candidate-row, .loading-box, .empty-box, .alert-error)) { display: none; }
.results-heading { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
.results-title { margin: 0; font-size: 16px; line-height: 24px; }
.results-count { color: var(--color-fg-muted); font-size: 13px; }
.applied-query { margin: 0 0 12px; padding: 10px 12px; border-left: 2px solid var(--color-accent-action); color: var(--color-fg-secondary); font-size: 13px; }
.candidate-list { display: grid; gap: 8px; }
.candidate-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; width: 100%; min-width: 0; padding: 16px 18px; text-align: left; border: 1px solid transparent; border-radius: var(--radius-surface); color: var(--color-fg-primary); background: var(--color-bg-surface); box-shadow: var(--shadow-surface); }
.candidate-row:hover:not(:disabled) { border-color: var(--color-stroke-strong); }
.candidate-row:active:not(:disabled) { background: var(--color-bg-hover); }
.candidate-row:disabled { opacity: .75; }
.candidate-row[aria-busy="true"] { border-color: var(--color-accent-action); background: var(--color-accent-action-soft); }
.candidate-copy { display: flex; flex: 1; flex-direction: column; min-width: 0; gap: 3px; }
.candidate-name { display: block; margin: 0; font-size: 16px; font-weight: 600; line-height: 24px; letter-spacing: -.3px; }
.candidate-category { font-size: 12px; color: var(--color-fg-muted); }
.candidate-addr { color: var(--color-fg-secondary); font-size: 13px; line-height: 21px; }
.candidate-arrow { color: var(--color-fg-muted); font-size: 24px; font-weight: 400; }
.candidate-state { display: flex; align-items: center; gap: 8px; color: var(--color-fg-muted); font-size: 12px; }
.candidate-state:empty { display: none; }
.candidate-status { width: fit-content; margin-top: 5px; padding: 2px 7px; background: var(--color-accent-action-soft); color: var(--color-accent-action); border-radius: 6px; font-size: 12px; }
.discovery-help { margin-top: 28px; border-top: 1px solid var(--color-stroke-subtle); color: var(--color-fg-muted); font-size: 13px; }
summary { min-height: 44px; padding-block: 10px; }
.discovery-help summary { width: fit-content; }
.discovery-help ol { margin: 0; padding-left: 22px; line-height: 1.9; }
.discovery-help p { margin-top: 12px; }
.recent-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; margin-bottom: 20px; }
.recent-heading .page-heading { margin: 0; }
.recent-title-count { color: var(--color-fg-muted); font-size: 18px; font-variant-numeric: tabular-nums; }
.recent-heading p { font-size: 13px; }
.recent-refresh { flex-shrink: 0; font-size: 13px; padding-inline: 10px; }
.recent-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px; }
.recent-meta { display: flex; flex-wrap: wrap; gap: 8px; color: var(--color-fg-secondary); font-size: 13px; margin-top: 5px; }
.recent-date { color: var(--color-fg-muted); font-size: 12px; }
.page-footnote { color: var(--color-fg-muted); font-size: 12px; margin-top: 20px; }
.place-header { position: sticky; top: 0; z-index: 35; display: flex; align-items: center; gap: 8px; min-height: var(--context-header); margin: 0 calc(-1 * var(--page-gutter)) 12px; padding: calc(8px + env(safe-area-inset-top, 0px)) var(--page-gutter) 8px; background: var(--color-bg-surface); border-bottom: 1px solid var(--color-stroke-subtle); }
.place-title-row { min-width: 0; flex: 1; }
.place-title-row h1 { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; margin: 0; font-size: 18px; line-height: 24px; letter-spacing: -.5px; }
.place-menu { position: relative; flex: 0 0 auto; }
.place-menu > summary { list-style: none; }
.place-menu > summary::-webkit-details-marker { display: none; }
.place-menu-content { position: absolute; top: calc(100% + 8px); right: 0; z-index: 40; width: min(320px, calc(100vw - 32px)); max-height: calc(100dvh - var(--context-header) - 16px); overflow-y: auto; overscroll-behavior-y: contain; padding: 16px; border: 1px solid var(--color-stroke-subtle); background: var(--color-bg-surface); border-radius: 16px; box-shadow: 0 8px 32px oklch(.23 .012 260 / .12); }
.menu-category, .place-addr { margin: 0 0 8px; font-size: 13px; color: var(--color-fg-muted); }
.menu-action { display: flex; align-items: center; justify-content: space-between; gap: 12px; min-height: 44px; width: 100%; padding: 10px 8px; text-align: left; border: 0; border-radius: 8px; background: transparent; font-size: 14px; }
.menu-action:hover { background: var(--color-bg-raised); }
.copy-status { color: var(--color-accent-action); font-size: 12px; margin: 4px 0; }
.copy-status:empty { display: none; }
.workspace-switcher { display: none; }
.workspace-warning { display: flex; align-items: center; gap: 6px; margin: 0 0 12px; color: var(--color-fg-muted); font-size: 13px; line-height: 20px; }
.workspace-warning .icon { width: 16px; height: 16px; flex-basis: 16px; }
.workspace-grid { display: grid; grid-template-columns: minmax(0,1.45fr) minmax(280px,1fr); gap: 20px; align-items: start; }
.viewport-col, .summary-col { min-width: 0; display: flex; flex-direction: column; gap: 16px; }
.summary-col { position: sticky; top: calc(var(--context-header) + 12px); max-height: calc(100dvh - var(--context-header) - 24px); overflow-y: auto; overscroll-behavior-y: contain; scrollbar-width: thin; padding-bottom: 2px; }
.viewport-toolbar { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px; padding: 4px; border-radius: 14px; background: var(--color-bg-surface); }
.floor-tabs { display: flex; flex-wrap: wrap; gap: 2px; min-width: 0; }
.tab { min-width: 44px; border: 0; border-radius: 10px; padding: 10px; font-size: 13px; white-space: nowrap; background: transparent; color: var(--color-fg-muted); }
.tab:hover { background: var(--color-bg-hover); }
.floor-tabs .tab[aria-pressed="true"] { background: var(--color-bg-raised); color: var(--color-fg-primary); font-weight: 600; }
.view-modes { display: flex; flex-shrink: 0; padding: 2px; gap: 2px; border-radius: 10px; background: var(--color-bg-raised); }
.view-modes .tab { min-height: 44px; min-width: 44px; padding: 8px 10px; }
.view-modes .tab[aria-pressed="true"] { background: var(--color-bg-surface); color: var(--color-fg-primary); box-shadow: var(--shadow-control); font-weight: 600; }
.floor-select-label { flex: 1; min-width: 100px; max-width: 220px; }
.floor-select { width: 100%; min-height: 44px; padding: 8px 10px; border: 1px solid var(--color-stroke-subtle); border-radius: 10px; background: var(--color-bg-surface); color: var(--color-fg-primary); font-size: 16px; }
.scene-dialog[open] { display: block; position: static; width: 100%; max-width: none; max-height: none; margin: 0; padding: 0; border: 0; background: transparent; color: inherit; overflow: visible; }
.canvas-holder { position: relative; height: clamp(360px,60svh,620px); overflow: hidden; border: 1px solid var(--color-stroke-subtle); border-radius: var(--radius-surface); background: oklch(.965 .004 260); }
.scene-canvas { display: block; width: 100%; height: 100%; }
.scene-tools { position: absolute; top: 12px; right: 12px; display: flex; align-items: center; gap: 4px; padding: 3px; border-radius: 12px; background: var(--color-bg-surface); border: 1px solid var(--color-stroke-subtle); box-shadow: var(--shadow-control); }
.scene-tool { display: inline-grid; place-items: center; min-width: 44px; min-height: 44px; padding: 6px; border: 0; border-radius: 8px; color: var(--color-fg-secondary); background: transparent; font-size: 20px; }
.scene-tool:hover { background: var(--color-bg-raised); }
.scene-expand { font-size: 12px; padding-inline: 10px; }
.scene-interaction-toggle { display: none; position: absolute; bottom: 12px; right: 12px; min-height: 44px; padding: 10px 14px; border: 1px solid var(--color-stroke-strong); border-radius: 12px; background: var(--color-bg-surface); font-size: 13px; font-weight: 600; box-shadow: var(--shadow-control); }
.scene-interaction-toggle[aria-pressed="true"] { background: var(--color-accent-action); border-color: var(--color-accent-action); color: white; }
.canvas-hint { position: absolute; left: 12px; bottom: 12px; max-width: calc(100% - 24px); padding: 8px 10px; border-radius: 8px; background: oklch(1 0 0 / .94); color: var(--color-fg-muted); font-size: 12px; line-height: 18px; pointer-events: none; }
.hint-touch { display: none; }
.scene-failure { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; text-align: center; background: var(--color-bg-raised); }
.scene-failure p { margin: 0; color: var(--color-fg-muted); }
.scene-failure > div { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; }
.selected-zone-mobile { display: none; }
.floor-notes { display: grid; gap: 12px; }
.floor-note-card, .summary-card { padding: 20px; border-radius: var(--radius-surface); background: var(--color-bg-surface); }
.floor-note-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-bottom: 12px; }
.floor-note-head h3 { font-size: 15px; margin: 0; }
.floor-note-head > span { font-size: 12px; color: var(--color-fg-muted); }
.zone-chips, .tag-row { display: flex; flex-wrap: wrap; gap: 6px; }
.zone-chip { justify-content: flex-start; text-align: left; padding: 10px 12px; color: var(--color-fg-secondary); font-size: 13px; background: var(--color-bg-raised); }
.zone-chip .icon { width: 16px; height: 16px; flex-basis: 16px; }
.zone-chip:hover { background: var(--color-bg-hover); }
.zone-chip[aria-pressed="true"] { color: var(--color-accent-action); border-color: var(--color-accent-action); background: var(--color-accent-action-soft); }
.zone-empty { display: inline-flex; align-items: center; gap: 8px; min-height: 44px; padding: 8px 10px; color: var(--color-fg-muted); border: 1px dashed var(--color-stroke-subtle); border-radius: 10px; font-size: 12px; }
.zone-empty > span { font-size: 12px; white-space: nowrap; }
.summary-card > h3, .gallery-heading h3 { margin: 0 0 16px; font-size: 16px; }
.metric-grid { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 8px; }
.metric { min-width: 0; padding: 12px; border-radius: 12px; background: var(--color-bg-raised); }
.metric-label { display: block; color: var(--color-fg-muted); font-size: 12px; }
.metric-val { display: block; margin-top: 4px; font-size: 18px; line-height: 28px; font-variant-numeric: tabular-nums; }
.summary-floor-count { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 12px; margin-top: 14px; font-size: 13px; }
.summary-floor-count > span { color: var(--color-fg-muted); }
.summary-section { margin-top: 18px; padding-top: 18px; border-top: 1px solid var(--color-stroke-subtle); }
.summary-section h4 { margin: 0 0 10px; font-size: 13px; }
.evidence-warning, .summary-details, .bullet-list, .photo-caption { font-size: 13px; line-height: 1.75; }
.evidence-warning { margin: 0; color: var(--color-fg-secondary); }
.summary-details { margin-top: 8px; color: var(--color-fg-muted); }
.summary-details summary { color: var(--color-fg-secondary); }
.summary-details p { margin: 8px 0; }
.confidence-explanation, .accessibility-note { font-size: 12px; color: var(--color-fg-muted); line-height: 1.7; }
.badge { display: inline-flex; align-items: center; min-height: 26px; padding: 4px 8px; border-radius: 6px; color: var(--color-fg-secondary); background: var(--color-bg-raised); font-size: 12px; line-height: 18px; }
.fact-list { margin: 0; font-size: 13px; }
.fact-list > div { display: flex; justify-content: space-between; gap: 12px; padding: 5px 0; }
.fact-list dt { color: var(--color-fg-muted); }
.fact-list dd { margin: 0; text-align: right; }
.bullet-list { margin: 0; padding-left: 18px; color: var(--color-fg-secondary); }
.bullet-list li + li { margin-top: 6px; }
.pin-drawer-head, .gallery-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; }
.pin-drawer-head h3 { margin: 4px 0 0; font-size: 15px; }
.btn-close { flex-shrink: 0; min-width: 44px; padding: 10px; background: var(--color-bg-raised); color: var(--color-fg-secondary); }
.photo-count, .gallery-heading > span { margin: 4px 0 12px; color: var(--color-fg-muted); font-size: 12px; }
.selected-photo-preview { display: block; width: 100%; padding: 0; border: 0; border-radius: 12px; overflow: hidden; background: var(--color-bg-raised); }
.image-shell { position: relative; display: flex; justify-content: center; align-items: center; min-width: 0; width: 100%; background: var(--color-bg-raised); }
.image-shell img { display: block; width: 100%; object-fit: cover; }
.selected-photo-preview img { height: 180px; }
.image-fallback { display: flex; align-items: center; justify-content: center; gap: 8px; min-height: 120px; padding: 16px; color: var(--color-fg-muted); font-size: 13px; }
.photo-caption p { margin: 10px 0 6px; }
.photo-source { display: inline-flex; align-items: center; min-height: 44px; color: var(--color-accent-action); font-size: 13px; text-decoration: underline; text-underline-offset: 3px; }
.photo-navigation { display: flex; justify-content: space-between; align-items: center; gap: 10px; margin-top: 12px; font-size: 13px; font-variant-numeric: tabular-nums; }
.photo-navigation .btn-secondary { min-width: 64px; }
.gallery-grid { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 8px; }
.gallery-item { position: relative; display: block; padding: 0; min-height: 80px; overflow: hidden; border: 0; border-radius: 10px; background: var(--color-bg-raised); }
.gallery-item img { height: 86px; }
.gallery-source { display: block; padding: 4px; font-size: 12px; line-height: 18px; color: var(--color-fg-secondary); }
.gallery-all { width: 100%; margin-top: 12px; }
dialog::backdrop { background: oklch(.18 .01 260 / .48); }
.photo-dialog { position: fixed; inset: 0; width: min(720px,calc(100vw - 40px)); max-width: none; max-height: calc(100dvh - 48px); margin: auto; padding: 0; color: var(--color-fg-primary); background: var(--color-bg-surface); border: 1px solid var(--color-stroke-subtle); border-radius: var(--radius-overlay); box-shadow: 0 20px 80px oklch(.23 .012 260 / .15); overflow-y: auto; overscroll-behavior: contain; }
.photo-dialog[open] { display: flex; flex-direction: column; }
.dialog-header, .scene-dialog-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 20px; background: var(--color-bg-surface); border-bottom: 1px solid var(--color-stroke-subtle); }
.dialog-header { position: sticky; top: 0; z-index: 2; flex-shrink: 0; }
.dialog-header h2 { margin: 0; font-size: 17px; line-height: 24px; }
.photo-dialog-body { padding: 16px 20px max(20px,env(safe-area-inset-bottom,0px)); min-height: 0; }
.photo-viewer { overflow: hidden; border-radius: 12px; }
.photo-viewer img { width: 100%; height: min(48dvh,480px); object-fit: contain; }
.photo-thumbnails { display: flex; gap: 8px; margin-top: 14px; overflow-x: auto; padding: 4px; scrollbar-width: thin; }
.photo-thumbnails button { flex: 0 0 64px; padding: 0; border: 2px solid transparent; border-radius: 8px; overflow: hidden; background: var(--color-bg-raised); }
.photo-thumbnails button[aria-pressed="true"] { border-color: var(--color-accent-action); }
.photo-thumbnails img { height: 56px; }
.scene-dialog:modal { display: flex; flex-direction: column; position: fixed; inset: 0; z-index: 50; width: 100%; height: 100dvh; max-width: none; max-height: 100dvh; margin: 0; padding: 0; overflow: hidden; background: var(--color-bg-canvas); }
.scene-dialog:modal .canvas-holder { flex: 1; min-height: 0; height: auto; margin: 12px max(12px,env(safe-area-inset-right,0px)) max(12px,env(safe-area-inset-bottom,0px)) max(12px,env(safe-area-inset-left,0px)); }
.scene-dialog:modal .scene-dialog-header { padding-top: calc(8px + env(safe-area-inset-top,0px)); }
.scene-dialog:modal .scene-tools { right: 16px; }
.progress-panel { padding: 16px 20px; margin-bottom: 16px; border-radius: var(--radius-surface); background: var(--color-bg-surface); }
.progress-head { display: flex; align-items: center; gap: 10px; font-size: 14px; }
.spinner { display: inline-block; width: 16px; height: 16px; flex: 0 0 16px; border: 2px solid var(--color-accent-action-soft); border-top-color: var(--color-accent-action); border-radius: 50%; animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.progress-steps { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); list-style: none; gap: 8px; padding: 0; margin: 16px 0 0; font-size: 12px; color: var(--color-fg-muted); }
.progress-steps li { padding-top: 8px; border-top: 3px solid var(--color-stroke-subtle); }
.progress-steps li[aria-current="step"] { color: var(--color-accent-action); border-color: var(--color-accent-action); font-weight: 600; }
.progress-steps li.complete { border-color: var(--color-semantic-success); }
.progress-details { font-size: 13px; color: var(--color-fg-muted); margin-top: 8px; }
.progress-details ul { margin-top: 0; padding-left: 20px; max-height: 180px; overflow: auto; }
.analysis-placeholder { padding: 24px; text-align: center; color: var(--color-fg-muted); }
.analysis-placeholder a { display: inline-flex; align-items: center; min-height: 44px; color: var(--color-accent-action); }
.loading-box, .empty-box, .recent-empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; min-height: 144px; padding: 28px 20px; text-align: center; border-radius: var(--radius-surface); background: var(--color-bg-surface); color: var(--color-fg-muted); }
.loading-box { flex-direction: row; gap: 12px; }
.empty-box p, .recent-empty p { margin: 0; }
.recent-empty h1, .recent-empty h2 { margin: 0; font-size: 18px; color: var(--color-fg-primary); }
.recent-empty .btn-primary { margin-top: 12px; }
.alert-error { padding: 16px; margin: 0 0 16px; border: 1px solid oklch(.48 .17 24 / .2); border-radius: 14px; background: var(--color-accent-danger-soft); color: var(--color-accent-danger); font-size: 14px; }
.alert-error p { margin: 0 0 10px; }
.alert-error .btn-secondary { margin-right: 8px; }
@media (pointer: coarse) {
.scene-interaction-toggle { display: inline-flex; }
.hint-pointer { display: none; }
.hint-touch { display: inline; }
.canvas-hint { right: 124px; max-width: none; padding: 6px 8px; }
}
@media (min-width: 640px) and (max-width: 1099px) and (min-height: 500px) {
.app-shell { --page-gutter: 20px; }
.workspace-grid { grid-template-columns: minmax(0,1.35fr) minmax(260px,1fr); gap: 16px; }
.summary-card, .floor-note-card { padding: 16px; }
.viewport-toolbar { gap: 4px; }
.view-modes { margin-left: auto; }
.canvas-holder { height: clamp(380px,62svh,600px); }
.scene-tools { gap: 0; top: 8px; right: 8px; }
}
@media (max-width: 639px), (max-height: 499px) {
.app-shell { --page-gutter: 16px; }
.main-body { padding-top: 20px; }
.topbar-nav a { padding-inline: 10px; font-size: 13px; }
.brand-title { font-size: 16px; }
.brand { gap: 6px; }
.brand-mark .icon { width: 22px; height: 22px; }
.page-heading h1 { font-size: 22px; }
.search-panel { padding: 12px; }
.quick-label { width: 100%; }
.quick-row { gap: 6px; }
.chip { font-size: 12px; padding-inline: 9px; }
.candidate-row { padding: 14px 16px; }
.candidate-name { font-size: 16px; }
.recent-grid { grid-template-columns: minmax(0,1fr); gap: 8px; }
.recent-refresh span { display: none; }
.recent-refresh { min-width: 44px; }
.place-header { margin-bottom: 0; }
.workspace-switcher { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 4px; position: sticky; top: var(--context-header); z-index: 25; padding: 4px; margin: 8px 0 10px; border-radius: 14px; background: var(--color-bg-surface); box-shadow: 0 0 0 8px var(--color-bg-canvas); }
.workspace-switcher button { min-height: 44px; padding: 8px; border: 0; border-radius: 10px; background: transparent; color: var(--color-fg-muted); font-size: 14px; }
.workspace-switcher button[aria-pressed="true"] { background: var(--color-bg-raised); color: var(--color-fg-primary); font-weight: 600; }
.workspace-warning { font-size: 12px; margin-bottom: 10px; }
.workspace-grid { grid-template-columns: minmax(0,1fr); gap: 0; }
.workspace-grid[data-mobile-panel="layout"] #info-panel, .workspace-grid[data-mobile-panel="info"] #layout-panel { display: none; }
.viewport-col { gap: 12px; }
.summary-col { position: static; max-height: none; overflow: visible; }
.selected-zone-panel { display: none; }
.viewport-toolbar { gap: 4px; }
.tab { padding-inline: 9px; font-size: 12px; }
.view-modes .tab { min-height: 44px; padding-inline: 9px; }
.view-modes { margin-left: auto; }
.canvas-holder { height: clamp(360px,56svh,520px); }
.scene-tools { top: 8px; right: 8px; gap: 0; }
.floor-note-card, .summary-card { padding: 16px; }
.selected-zone-mobile { display: flex; align-items: center; gap: 8px; min-height: 52px; padding: 12px; text-align: left; color: var(--color-accent-action); background: var(--color-accent-action-soft); border: 1px solid var(--color-stroke-subtle); border-radius: 12px; font-size: 13px; }
.selected-zone-mobile > span:last-child { margin-left: auto; white-space: nowrap; }
.photo-dialog { inset: auto 0 0; width: 100%; max-height: calc(100dvh - max(20px,env(safe-area-inset-top,0px))); margin: 0; border-radius: 24px 24px 0 0; }
.dialog-header { padding: 12px 16px; }
.dialog-header h2 { font-size: 16px; }
.photo-dialog-body { padding: 12px 16px max(16px,env(safe-area-inset-bottom,0px)); }
.photo-viewer img { height: min(42dvh,360px); }
}
@media (max-width: 359px) {
.app-shell { --page-gutter: 12px; }
.brand-title { font-size: 15px; }
.brand-mark { display: none; }
.topbar { gap: 6px; }
.topbar-nav a { padding-inline: 8px; }
.search-bar { gap: 6px; }
.search-field { padding-left: 8px; gap: 4px; }
.search-field > .icon { display: none; }
.search-clear { min-width: 44px; padding-inline: 8px; }
.btn-primary { min-width: 56px; padding-inline: 10px; }
.quick-row { gap: 4px; }
.chip { padding-inline: 8px; }
.viewport-toolbar { align-items: stretch; }
.view-modes { flex: 1 1 100%; }
.view-modes .tab { flex: 1; }
.scene-expand { padding-inline: 8px; }
}
@media (max-height: 499px) {
.canvas-holder { height: 320px; }
.photo-dialog { max-height: 100dvh; }
.photo-viewer img { height: 50dvh; }
}
/* Two physical segments keep controls clear of the hinge. */
@media (horizontal-viewport-segments: 2) and (vertical-viewport-segments: 1) {
.main-body:has(.place-page) { max-width: none; padding-inline: 0; }
.place-header { margin-inline: 0; display: grid; grid-template-columns: 44px minmax(0,1fr) 44px; width: env(viewport-segment-width 0 0); padding-inline: 12px; }
.workspace-switcher { display: none; }
.workspace-warning { margin-inline: 16px; width: calc(env(viewport-segment-width 0 0) - 32px); }
.workspace-grid { grid-template-columns: env(viewport-segment-width 0 0) calc(env(viewport-segment-left 1 0) - env(viewport-segment-right 0 0)) env(viewport-segment-width 1 0); gap: 0; }
.workspace-grid[data-mobile-panel] #layout-panel { display: flex; grid-column: 1; padding-inline: 16px; }
.workspace-grid[data-mobile-panel] #info-panel { display: flex; grid-column: 3; padding-inline: 16px; }
.topbar, .home-wrap, .recent-page { width: env(viewport-segment-width 0 0); margin-left: 0; }
.main-body:not(:has(.place-page)) { max-width: none; padding-inline: 0; }
.home-wrap, .recent-page { padding-inline: 16px; }
.recent-grid { grid-template-columns: 1fr; }
.photo-dialog { width: calc(env(viewport-segment-width 0 0) - 24px); left: 12px; right: auto; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; }
}
@media (forced-colors: active) {
.tab[aria-pressed="true"], .zone-chip[aria-pressed="true"], .workspace-switcher button[aria-pressed="true"] { outline: 2px solid Highlight; }
.btn-primary, .btn-secondary, .candidate-row, .chip, .zone-chip, .search-field, .scene-tool, .scene-interaction-toggle { border: 1px solid ButtonText; }
.summary-card, .floor-note-card { border: 1px solid CanvasText; }
}