Skip to content

Single place to convert your 2D floor plans to 3d model (no LLM)

Python

Audit fixes: cover sheets, broken models, downloads, server races

23f2005639015b5c52c755
diff --git a/AGENTS.md b/AGENTS.md
index 5f0f9f7..13f9192 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -44,7 +44,7 @@ Flow: upload -> `run_detect` -> `plan.json` -> review page edits it -> `POST …
## Tests: run them before you finish
```bash
-tests/run_all.sh # detector on the sample, furniture clashes, stair and wall walking
+tests/run_all.sh # detector on the sample, server guards, furniture clashes, stair and wall walking
python3 tests/test_sample.py # the sample must be read exactly
CHROME=/path/to/chromium node tests/test_site.mjs examples/sample_plan.pdf http://127.0.0.1:8080
```
diff --git a/README.md b/README.md
index beecec3..876d035 100644
--- a/README.md
+++ b/README.md
@@ -190,7 +190,7 @@ assets/ downloaded materials (not in git)
## Tests
```bash
-tests/run_all.sh # detector on the sample, furniture clashes, stair and wall walking
+tests/run_all.sh # detector on the sample, server guards, furniture clashes, stair and wall walking
CHROME=/path/to/chromium node tests/test_site.mjs examples/sample_plan.pdf http://127.0.0.1:8080
```
diff --git a/blender/gen.py b/blender/gen.py
index c4c8c64..d2f9ca4 100644
--- a/blender/gen.py
+++ b/blender/gen.py
@@ -46,7 +46,6 @@ FLOOR_MAT = dict(dress="wood", bedroom="wood", toilet="bathtile", kitchen="marbl
garden="turf", open="pebbles", parking="pavers", yard="pavers", stair="stair", room="tile",
duct="concrete")
OPEN_SKY = {"open", "garden", "yard"} # no slab above these
-INDOOR = {"bedroom", "toilet", "kitchen", "living", "dining", "puja", "study", "store", "passage", "room", "wash", "dress"}
# ------------------------------------------------------------------ helpers
@@ -358,7 +357,13 @@ def custom(it):
if it["fn"] not in CATALOG or not os.path.exists(path) or x1 - x0 < 0.1 or y1 - y0 < 0.1:
return False
before = set(bpy.data.objects)
- bpy.ops.import_scene.gltf(filepath=path) # shortcut: imported once per item, fine for a house; cache if plans grow huge
+ try:
+ bpy.ops.import_scene.gltf(filepath=path) # shortcut: imported once per item, fine for a house; cache if plans grow huge
+ except RuntimeError as e: # a broken file: the built-in item stands in for it
+ print("CUSTOM MODEL FAILED", it["fn"], e, flush=True)
+ for o in set(bpy.data.objects) - before:
+ bpy.data.objects.remove(o)
+ return False
new = [o for o in bpy.data.objects if o not in before]
bpy.context.view_layer.update()
pts = [o.matrix_world @ Vector(c) for o in new if o.type == "MESH" for c in o.bound_box]
@@ -529,7 +534,7 @@ for k, f in enumerate(floors):
curtains(f, items)
# lamps (emissive panel + area light for the bake) in roofed rooms
for zn in f["rooms"]:
- if zn["type"] not in INDOOR and zn["type"] not in ("balcony", "parking", "stair"):
+ if zn["type"] not in furnish.INDOOR and zn["type"] not in ("balcony", "parking", "stair"):
continue
x0, x1, y0, y1 = furnish.max_rect(zn["rects"]) or max(zn["rects"], key=lambda r: (r[1] - r[0]) * (r[3] - r[2]))
if (x1 - x0) * (y1 - y0) < 6:
@@ -606,7 +611,7 @@ sun.rotation_euler = (math.radians(52), 0, math.radians(-28))
collection("lights").objects.link(sun)
for cx, cy, zz, a, typ in LAMPS:
L = bpy.data.lights.new("lamp", "AREA")
- L.energy = (14 if typ in INDOOR else 8) * a * lib.F * lib.F
+ L.energy = (14 if typ in furnish.INDOOR else 8) * a * lib.F * lib.F
L.size, L.shape = 0.6, "SQUARE"
L.color = (1.0, 0.9, 0.78)
o = bpy.data.objects.new("lamp", L)
diff --git a/detect.py b/detect.py
index 0f22d96..657b524 100644
--- a/detect.py
+++ b/detect.py
@@ -960,15 +960,22 @@ def detect_floor(f, T, s, phr, lines, hatch, A, zone_lines, cuts=()):
def detect(pdf):
- pages = []
+ pages, lines = [], 0
for k in range(1, vector.page_count(pdf) + 1):
+ page = vector.read_page(pdf, k)
+ lines = max(lines, len(page["segs"]))
+ if len(page["segs"]) < 150: # a cover sheet or notes: too few lines for a plan
+ continue
try:
- pg = detect_page(vector.read_page(pdf, k))
+ pg = detect_page(page)
except PlanError:
continue
for f in pg["floors"]:
f["page"] = k
pages.append(pg)
+ if lines < 150: # any page of a CAD plan has thousands of lines; a cover sheet before the plans does not count
+ raise PlanError("This PDF has almost no vector lines - it looks like a scan or photo. "
+ "Please export the plan from AutoCAD / your CAD tool as a PDF.")
if not pages:
raise PlanError("No floor plan was found in this PDF. The drawing needs double-line walls and room names.")
floors = [f for p in pages for f in p["floors"]]
diff --git a/fetch_assets.py b/fetch_assets.py
index 39aa5f4..a6f02d0 100644
--- a/fetch_assets.py
+++ b/fetch_assets.py
@@ -56,13 +56,15 @@ def fetch(progress=lambda done, total, name: None, tour=False):
if kind == "model":
g = f["gltf"]["1k"]["gltf"]
d = os.path.join(ROOT, "models", name)
- save(g["url"], os.path.join(d, os.path.basename(g["url"])))
for rel, inc in g["include"].items():
save(inc["url"], os.path.join(d, rel))
- elif kind == "texture":
+ save(g["url"], os.path.join(d, os.path.basename(g["url"]))) # last: missing() counts the model by this file
+ elif kind == "texture": # into name.part/, renamed when whole: missing() counts the texture by its folder
+ d = os.path.join(ROOT, "textures", name)
for key, short in (("Diffuse", "diff"), ("nor_gl", "nor"), ("Rough", "rough")):
if key in f:
- save(f[key]["1k"]["jpg"]["url"], os.path.join(ROOT, "textures", name, f"{short}.jpg"))
+ save(f[key]["1k"]["jpg"]["url"], os.path.join(d + ".part", f"{short}.jpg"))
+ os.replace(d + ".part", d)
elif name == SKY:
save(f["hdri"]["1k"]["hdr"]["url"], os.path.join(ROOT, "hdri", "sky.hdr"))
else:
diff --git a/server.py b/server.py
index f1f887a..6fd9918 100644
--- a/server.py
+++ b/server.py
@@ -16,11 +16,12 @@ MAX_UPLOAD = 200 * 1024 * 1024 # plans are small; recordings sent for MP4
BUILD_TIMEOUT = 2 * 3600 # seconds; a high-quality build of a large house takes well under an hour
ID = re.compile(r"^[a-f0-9]{12}$")
sys.path.insert(0, HERE)
-import catalog, detect, fetch_assets, vector # noqa: E402
+import catalog, detect, fetch_assets # noqa: E402
os.makedirs(JOBS, exist_ok=True)
builds = queue.Queue()
-lock = threading.Lock()
+lock = threading.RLock() # reentrant: request handlers hold it around status() to check and set a stage in one step
+BUSY = ("uploaded", "detecting", "queued", "building")
TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css": "text/css", ".json": "application/json",
".png": "image/png", ".jpg": "image/jpeg", ".webp": "image/webp", ".glb": "model/gltf-binary",
".wasm": "application/wasm", ".svg": "image/svg+xml", ".pdf": "application/pdf", ".hdr": "application/octet-stream",
@@ -82,6 +83,7 @@ def fetch_materials():
assets_job["failed"] = [str(e)]
finally:
assets_job["running"] = False
+ thumbs_job["tried"] = False # the furniture pictures can be drawn now
def export_blend(jid):
@@ -107,7 +109,7 @@ def export_blend(jid):
# ------------------------------------------------------------------ your own furniture models
CUSTOM, THUMBS = os.path.join(fetch_assets.ROOT, "custom"), os.path.join(fetch_assets.ROOT, "thumbs")
-thumbs_job = dict(running=False, again=False)
+thumbs_job = dict(running=False, again=False, tried=False)
def render_thumbs():
@@ -136,12 +138,13 @@ def refresh_thumbs():
if thumbs_job["running"]:
thumbs_job["again"] = True
return
- thumbs_job["running"] = True
+ thumbs_job.update(running=True, tried=True)
threading.Thread(target=render_thumbs, daemon=True).start()
def furniture():
- if not thumbs_job["running"] and not all(os.path.exists(os.path.join(THUMBS, f"{fn}.png")) for fn in catalog.CATALOG):
+ # drawn once on its own; after that only a new or removed model draws them again (a render that fails must not loop)
+ if not thumbs_job["tried"] and not all(os.path.exists(os.path.join(THUMBS, f"{fn}.png")) for fn in catalog.CATALOG):
refresh_thumbs()
return dict(rendering=thumbs_job["running"], items=[
dict(fn=fn, label=label, custom=os.path.exists(os.path.join(CUSTOM, f"{fn}.glb")),
@@ -154,23 +157,19 @@ def run_detect(jid):
pdf = os.path.join(d, "source.pdf")
try:
status(jid, stage="detecting", progress=5, message="Reading the drawing")
- n = vector.page_count(pdf)
- for k in range(1, min(n, 6) + 1): # page images for the review screen (100 dpi = 100/72 px per pt)
- subprocess.run(["pdftocairo", "-png", "-r", "100", "-f", str(k), "-l", str(k), "-singlefile", pdf,
- os.path.join(d, f"page-{k}")], check=True, timeout=120)
- p1 = vector.read_page(pdf, 1)
- if len(p1["segs"]) < 150:
- raise detect.PlanError("This PDF has almost no vector lines - it looks like a scan or photo. "
- "Please export the plan from AutoCAD / your CAD tool as a PDF.")
importlib.reload(detect) # pick up detector fixes without restarting the server
plan = detect.detect(pdf)
+ for k in sorted({f["page"] for f in plan["floors"]}): # page images for the review screen (100 dpi = 100/72 px per pt)
+ subprocess.run(["pdftocairo", "-png", "-r", "100", "-f", str(k), "-l", str(k), "-singlefile", pdf,
+ os.path.join(d, f"page-{k}")], check=True, timeout=120)
with open(os.path.join(d, "plan.json"), "w") as fh:
json.dump(plan, fh)
status(jid, stage="detected", progress=100, message="Plan detected - please review",
floors=[f["name"] for f in plan["floors"]], scale_source=plan["scale_source"])
except Exception as e:
- traceback.print_exc()
known = isinstance(e, detect.PlanError)
+ if not known: # a known one is the drawing's fault, already said in plain words
+ traceback.print_exc()
status(jid, stage="failed", message=str(e) if known else "This drawing could not be read. Is it a floor plan exported from a CAD tool?")
@@ -319,9 +318,10 @@ class H(BaseHTTPRequestHandler):
p = urlparse(self.path).path
m = re.match(r"^/api/jobs/([a-f0-9]{12})$", p)
if m and os.path.isdir(jdir(m.group(1))):
- if (read_status(m.group(1)) or {}).get("stage") in ("building", "queued"):
- return self.send(409, {"error": "This plan is being built. Delete it when the build has finished."})
- shutil.rmtree(jdir(m.group(1)))
+ with lock:
+ if (read_status(m.group(1)) or {}).get("stage") in BUSY:
+ return self.send(409, {"error": "This plan is being read or built. Delete it when that has finished."})
+ shutil.rmtree(jdir(m.group(1)))
return self.send(200, {"ok": True})
m = re.match(r"^/api/furniture/(\w+)$", p)
if m and m.group(1) in catalog.CATALOG: # back to the built-in item
@@ -384,35 +384,38 @@ class H(BaseHTTPRequestHandler):
jid, what = m.groups()
if what == "export":
return self.send(200, {"url": export_blend(jid)})
- st = read_status(jid) or {}
- if st.get("stage") in ("building", "queued"):
- return self.send(409, {"error": "a build is already running"})
- if what == "plan":
- plan = json.loads(self.body())
- if not isinstance(plan, dict) or not isinstance(plan.get("floors"), list) or not plan["floors"]:
- return self.send(400, {"error": "invalid plan"})
- with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
- json.dump(plan, fh)
- return self.send(200, {"ok": True})
- q = json.loads(self.body() or b"{}").get("quality", "high")
- q = q if q in ("draft", "high") else "high"
- status(jid, stage="queued", progress=0, message=f"Waiting for the 3D builder ({builds.qsize()} ahead)")
- builds.put((jid, q))
+ req = json.loads(self.body() or b"{}")
+ if not isinstance(req, dict):
+ raise ValueError("expected a JSON object")
+ with lock: # checked and set in one step: two quick clicks must not queue two builds
+ if (read_status(jid) or {}).get("stage") in BUSY:
+ return self.send(409, {"error": "this plan is being read or built"})
+ if what == "plan":
+ if not isinstance(req.get("floors"), list) or not req["floors"]:
+ return self.send(400, {"error": "invalid plan"})
+ with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
+ json.dump(req, fh)
+ return self.send(200, {"ok": True})
+ q = req.get("quality") if req.get("quality") in ("draft", "high") else "high"
+ status(jid, stage="queued", progress=0, message=f"Waiting for the 3D builder ({builds.qsize()} ahead)")
+ builds.put((jid, q))
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
except (ValueError, json.JSONDecodeError) as e:
self.send(400, {"error": str(e)})
- except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as e:
+ except Exception: # anything else: still answer, so the page can say what failed
traceback.print_exc()
- self.send(500, {"error": "Blender could not write the file"})
+ self.send(500, {"error": "The server could not do that - see its log."})
if __name__ == "__main__":
port = int(sys.argv[sys.argv.index("--port") + 1]) if "--port" in sys.argv else 8080
host = sys.argv[sys.argv.index("--host") + 1] if "--host" in sys.argv else "127.0.0.1"
- for jid in os.listdir(JOBS): # builds interrupted by a restart
+ for jid in os.listdir(JOBS): # work interrupted by a restart: reading starts again, a build is pressed again
st = read_status(jid) if ID.match(jid) else None
- if st and st.get("stage") in ("building", "queued", "detecting"):
+ if st and st.get("stage") in ("uploaded", "detecting"):
+ threading.Thread(target=run_detect, args=(jid,), daemon=True).start()
+ elif st and st.get("stage") in BUSY:
status(jid, stage="failed", message="interrupted by a server restart - press Build again")
threading.Thread(target=builder, daemon=True).start()
print(f"PlanTo3D on http://{host}:{port}", flush=True)
diff --git a/tests/run_all.sh b/tests/run_all.sh
index bd64fe7..5116770 100755
--- a/tests/run_all.sh
+++ b/tests/run_all.sh
@@ -5,6 +5,7 @@ cd "$(dirname "$0")/.."
set -e
python3 tests/test_sample.py
python3 tests/test_detect.py
+python3 tests/test_server.py
python3 detect.py examples/sample_plan.pdf /tmp/planto3d_sample.json > /dev/null
for p in /tmp/planto3d_sample.json jobs/*/plan.json; do
[ -f "$p" ] || continue
diff --git a/tests/test_server.py b/tests/test_server.py
new file mode 100644
index 0000000..ac58f07
--- /dev/null
+++ b/tests/test_server.py
@@ -0,0 +1,73 @@
+"""The server's guards, without Blender: files outside the web folders stay hidden, a plan that is being read or built
+cannot be changed or deleted, bad request bodies get an answer, and a cover sheet before the plan is not taken for a
+scan. python3 tests/test_server.py"""
+import json, os, shutil, subprocess, sys, tempfile, threading, urllib.error, urllib.request
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+ROOT = os.path.dirname(HERE)
+sys.path.insert(0, ROOT)
+import server # noqa: E402
+
+server.JOBS = tempfile.mkdtemp() # never touch the real jobs folder
+httpd = server.ThreadingHTTPServer(("127.0.0.1", 0), server.H)
+threading.Thread(target=httpd.serve_forever, daemon=True).start()
+URL = f"http://127.0.0.1:{httpd.server_port}"
+
+
+def call(method, path, body=None):
+ req = urllib.request.Request(URL + path, data=body, method=method)
+ try:
+ with urllib.request.urlopen(req) as r:
+ return r.status, r.read()
+ except urllib.error.HTTPError as e:
+ return e.code, e.read()
+
+
+def job(stage):
+ jid = os.urandom(6).hex()
+ os.makedirs(server.jdir(jid))
+ server.status(jid, stage=stage)
+ return jid
+
+
+try:
+ assert call("GET", "/web/..%2fserver.py")[0] == 404
+ assert call("GET", "/jobs/" + job("done") + "/..%2f..%2fserver.py")[0] == 404
+ busy = job("detecting")
+ assert call("DELETE", f"/api/jobs/{busy}")[0] == 409 and os.path.isdir(server.jdir(busy))
+ assert call("POST", f"/api/jobs/{busy}/plan", b'{"floors": [{}]}')[0] == 409
+ done = job("done")
+ assert call("POST", f"/api/jobs/{done}/plan", b"[]")[0] == 400
+ assert call("POST", f"/api/jobs/{done}/plan", b"not json")[0] == 400
+ assert call("POST", f"/api/jobs/{done}/plan", b'{"floors": [{"name": "G"}]}')[0] == 200
+ assert json.load(open(os.path.join(server.jdir(done), "plan.json")))["floors"][0]["name"] == "G"
+ assert call("POST", f"/api/jobs/{done}/export")[0] == 400 # nothing built yet
+ assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(server.jdir(done))
+ print("ok server: hidden files, busy plans, bad bodies")
+
+ # a title sheet with no drawing before the plan: the plan on page 2 is found, and its page is the one drawn
+ cover = os.path.join(server.JOBS, "cover.pdf")
+ objs = [b"<</Type/Catalog/Pages 2 0 R>>", b"<</Type/Pages/Kids[3 0 R]/Count 1>>",
+ b"<</Type/Page/Parent 2 0 R/MediaBox[0 0 612 792]>>"]
+ pdf, offs = b"%PDF-1.4\n", []
+ for k, o in enumerate(objs, 1):
+ offs.append(len(pdf))
+ pdf += b"%d 0 obj%s endobj\n" % (k, o)
+ xref = len(pdf)
+ pdf += b"xref\n0 4\n0000000000 65535 f \n" + b"".join(b"%010d 00000 n \n" % o for o in offs)
+ pdf += b"trailer<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n" % xref
+ open(cover, "wb").write(pdf)
+ jid = job("uploaded")
+ subprocess.run(["pdfunite", cover, os.path.join(ROOT, "examples", "sample_plan.pdf"),
+ os.path.join(server.jdir(jid), "source.pdf")], check=True)
+ server.run_detect(jid)
+ st = server.read_status(jid)
+ assert st["stage"] == "detected", st
+ assert sorted(os.listdir(server.jdir(jid))) == ["page-2.png", "plan.json", "source.pdf", "status.json"]
+ shutil.copy(cover, os.path.join(server.jdir(jid), "source.pdf"))
+ server.run_detect(jid)
+ assert "scan" in server.read_status(jid)["message"]
+ print("ok server: a cover sheet before the plan, a PDF without lines")
+finally:
+ httpd.shutdown()
+ shutil.rmtree(server.JOBS)
diff --git a/web/view.js b/web/view.js
index 25ef7fc..cda1c98 100644
--- a/web/view.js
+++ b/web/view.js
@@ -100,6 +100,7 @@ addEventListener('keydown', (e) => {
if (e.code === 'KeyM' && !e.repeat) toggleMap();
});
addEventListener('keyup', (e) => { keys[e.code] = false; });
+addEventListener('blur', () => { for (const k in keys) keys[k] = false; }); // a key let go in another window never sends keyup here
const canvas = renderer.domElement;
$('overlay').addEventListener('click', () => {
if (matchMedia('(pointer: coarse)').matches) { $('overlay').style.display = 'none'; return; }