Skip to content

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

Python

Split server.py: HTTP routes, job work, themes

23f2005639f4f9aa26f6b8
diff --git a/jobs.py b/jobs.py
new file mode 100644
index 0000000..4c90d54
--- /dev/null
+++ b/jobs.py
@@ -0,0 +1,259 @@
+"""A plan's job folder and the work done on it: status, reading the drawing, the build queue (one Blender at a time),
+the exports, the furniture list and its checks, and whether this machine is set up to build. No HTTP here: server.py."""
+import importlib, json, math, os, posixpath, queue, re, shutil, subprocess, threading, time, traceback, zipfile
+
+HERE = os.path.dirname(os.path.abspath(__file__))
+JOBS = os.path.join(HERE, "jobs")
+WEB = os.path.join(HERE, "web")
+THREE = os.path.join(HERE, "node_modules", "three")
+BLENDER = os.environ.get("BLENDER") or shutil.which("blender") or "blender" # set BLENDER to its full path if it is not on PATH
+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}$")
+import catalog, detect, fetch_assets, furnish, themes # noqa: E402
+
+os.makedirs(JOBS, exist_ok=True)
+builds = queue.Queue()
+lock = threading.RLock() # reentrant: request handlers hold it around status() to check and set a stage in one step
+BUSY = ("uploaded", "detecting", "queued", "building")
+
+
+def jdir(jid):
+ return os.path.join(JOBS, jid)
+
+
+def status(jid, **kw):
+ p = os.path.join(jdir(jid), "status.json")
+ with lock:
+ st = json.load(open(p)) if os.path.exists(p) else {}
+ st.update(kw, updated=time.time())
+ tmp = p + ".tmp"
+ with open(tmp, "w") as fh:
+ json.dump(st, fh)
+ os.replace(tmp, p)
+ return st
+
+
+def read_status(jid):
+ p = os.path.join(jdir(jid), "status.json")
+ return json.load(open(p)) if os.path.exists(p) else None
+
+
+# ------------------------------------------------------------------ system check and the materials download
+_blender = None # Blender's version, read once ("" = not found)
+assets_job = dict(running=False, done=0, total=0, failed=[])
+export_lock, site_lock = threading.Lock(), threading.Lock() # the site zip takes a second: it must not wait for a Blender pack
+gpu = threading.Lock() # a house build and the themes' pictures both render on the GPU: one at a time
+
+
+def system():
+ """what must be in place before a plan is accepted (shown on the home page, enforced on upload and build)"""
+ global _blender
+ if _blender is None:
+ try:
+ out = subprocess.run([BLENDER, "--version"], capture_output=True, text=True, timeout=60).stdout
+ _blender = (re.search(r"Blender (\d+\.\d+)", out) or [None, ""])[1]
+ except (OSError, subprocess.TimeoutExpired):
+ _blender = ""
+ checks = dict(
+ blender=dict(ok=bool(_blender) and tuple(map(int, _blender.split("."))) >= (4, 2), version=_blender),
+ pdf_tools=dict(ok=all(shutil.which(c) for c in ("pdftocairo", "pdftotext", "pdfinfo"))),
+ viewer=dict(ok=os.path.isfile(os.path.join(THREE, "build", "three.module.js"))),
+ materials=dict(ok=not fetch_assets.missing(), **assets_job))
+ return dict(ready=all(c["ok"] for c in checks.values()), **checks)
+
+
+def fetch_materials():
+ def progress(done, total, name):
+ assets_job.update(done=done, total=total)
+ try:
+ assets_job["failed"] = fetch_assets.fetch(progress)
+ except Exception as e:
+ traceback.print_exc()
+ assets_job["failed"] = [str(e)]
+ finally:
+ assets_job["running"] = False
+
+
+def export_blend(jid):
+ """jobs/<id>/house_blender.zip: the built house as one .blend with every texture packed inside (made once per build)"""
+ d = jdir(jid)
+ src, out = os.path.join(d, "house_baked.blend"), os.path.join(d, "house_blender.zip")
+ if not os.path.exists(src):
+ raise ValueError("build the 3D house first")
+ with export_lock:
+ if not os.path.exists(out) or os.path.getmtime(out) < os.path.getmtime(src):
+ tmp = os.path.join(d, "export.blend")
+ expr = f"import bpy; bpy.ops.file.pack_all(); bpy.ops.wm.save_as_mainfile(filepath={tmp!r}, copy=True, compress=True)"
+ subprocess.run([BLENDER, "-b", src, "--python-expr", expr], check=True, timeout=900, capture_output=True)
+ with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_STORED) as z: # the .blend is already compressed
+ z.write(tmp, "house.blend")
+ z.writestr("README.txt", "house.blend - made by PlanTo3D. Open it in Blender 4.2 or newer.\n"
+ "Every texture is packed inside the file. Each storey is one mesh (bake_level_N) with its lamps;\n"
+ "the render engine is Cycles. Textures and models are CC0, from polyhaven.com.\n")
+ os.remove(tmp)
+ os.replace(out + ".part", out)
+ return f"/jobs/{jid}/house_blender.zip"
+
+
+def three_files():
+ """the three.js files the viewer loads: what view.js and walk.js import from three, and what those import in turn"""
+ def deps(text, here):
+ for s in re.findall(r"\b(?:from|import)\s*['\"]([^'\"]+)['\"]", text):
+ if s == "three":
+ yield "build/three.module.js"
+ elif s.startswith("three/addons/"):
+ yield "examples/jsm/" + s[13:]
+ elif s.startswith(".") and here is not None:
+ yield posixpath.normpath(posixpath.join(here, s))
+ todo, seen = [f for w in ("view.js", "walk.js") for f in deps(open(os.path.join(WEB, w)).read(), None)], set()
+ while todo:
+ f = todo.pop()
+ if f not in seen and os.path.isfile(os.path.join(THREE, f)): # (an example in a doc comment may name a file that is not there)
+ seen.add(f)
+ todo += deps(open(os.path.join(THREE, f)).read(), posixpath.dirname(f))
+ # DRACOLoader fetches its decoder at run time (the WebAssembly one, as every browser with import maps has it)
+ return sorted(seen) + ["examples/jsm/libs/draco/draco_wasm_wrapper.js", "examples/jsm/libs/draco/draco_decoder.wasm"]
+
+
+def export_site(jid):
+ """jobs/<id>/house_site.zip: the walkthrough as a static website for any web host, without this server (made once
+ per build). Only the house itself leaves the job folder: never the client's PDF, the plan or the logs."""
+ d = jdir(jid)
+ glb, out = os.path.join(d, "house.glb"), os.path.join(d, "house_site.zip")
+ if not os.path.exists(glb):
+ raise ValueError("build the 3D house first")
+ srcs = [glb, os.path.join(d, "meta.json")] + [os.path.join(WEB, f) for f in ("view.html", "view.js", "walk.js", "style.css")]
+ with site_lock:
+ if not os.path.exists(out) or os.path.getmtime(out) < max(map(os.path.getmtime, srcs)): # a new build or a new viewer
+ meta = json.load(open(os.path.join(d, "meta.json")))
+ house = (["meta.json", "house.glb"] + [os.path.basename(f) for f in (meta.get("lightmaps") or {}).values()]
+ + [f["file"] for f in (meta.get("finishes") or {}).values()])
+ # view.html with three.js next to it; view.js finds no ?job= and reads the house from ./house/
+ page = open(os.path.join(WEB, "view.html")).read().replace('"/three/', '"./three/')
+ with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_DEFLATED) as z:
+ z.writestr("index.html", page)
+ for f in ("view.js", "walk.js", "style.css"):
+ z.write(os.path.join(WEB, f), f)
+ for f in three_files():
+ z.write(os.path.join(THREE, f), "three/" + f)
+ for f in house: # already compressed (Draco, WebP)
+ z.write(os.path.join(d, f), "house/" + f, zipfile.ZIP_STORED)
+ z.writestr("README.txt", "3D walkthrough - made by PlanTo3D.\n\n"
+ "Put this folder on any static web host (Netlify, GitHub Pages, your own server) and open index.html.\n"
+ "To try it on your computer, run a web server in this folder, for example\n"
+ " python3 -m http.server 8000\n"
+ "and open http://localhost:8000/ . Opening index.html straight from the disk does not work:\n"
+ "browsers do not load the viewer's modules from file:// pages.\n\n"
+ "Viewer: three.js (MIT). Textures and models are CC0, from polyhaven.com.\n")
+ os.replace(out + ".part", out)
+ return f"/jobs/{jid}/house_site.zip"
+
+
+def plan_items(jid):
+ """the furniture each floor will get (the review page's own list if it edited that floor, else the rules' choice),
+ and what can be added, at the sizes of the plan's theme"""
+ plan = json.load(open(os.path.join(jdir(jid), "plan.json")))
+ T, cat = themes.load(plan.get("theme")), {}
+ for fn, (label, w, d, kw) in catalog.CATALOG.items():
+ m = themes.size(T, fn)
+ cat[fn] = [themes.label(T, fn), *((m[0], m[1] + (3.2 if fn == "dining_set" else 0)) if m else (w, d)), kw]
+ for fn in ("armchair", "corner", "bed_end"): # decor of the theme that stands on the floor
+ if themes.size(T, fn):
+ cat[fn] = [themes.label(T, fn), *themes.size(T, fn)[:2], {}]
+ return dict(floors=[furnish.floor_items(plan, f) for f in plan["floors"]], catalog=cat)
+
+
+# items the browser may send: must match gen.CALLS (gen.py runs inside Blender, so it cannot be imported here),
+# minus "model", whose argument is an asset file name
+ITEM_FNS = set(catalog.CATALOG) | {"shower2", "geyser", "kitchen_run", "chimney", "wall_cab2", "rug", "car",
+ "outdoor_set", "bathtub", "round_rug", "armchair", "art", "mirror", "decor", "corner", "bed_end"}
+WORD = re.compile(r"@?[\w+-]{0,24}") # side names such as "-x", material names, "@style" pieces; nothing that can be a path
+
+
+def check_items(plan):
+ """furniture lists from the browser go to Blender as function arguments: only known items, plain values"""
+ num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
+ plain = lambda v: v is None or isinstance(v, bool) or num(v) or (isinstance(v, str) and WORD.fullmatch(v))
+ for f in plan["floors"]:
+ if not isinstance(f, dict) or "items" not in f:
+ continue
+ items = f["items"]
+ if not isinstance(items, list) or len(items) > 400:
+ raise ValueError("invalid furniture list")
+ for it in items:
+ if not (isinstance(it, dict) and isinstance(it.get("fn"), str) and it["fn"] in ITEM_FNS
+ and isinstance(it.get("args"), list) and len(it["args"]) <= 8 and all(num(v) or isinstance(v, str) and WORD.fullmatch(v) for v in it["args"])
+ and isinstance(it.get("box"), list) and len(it["box"]) == 4 and all(map(num, it["box"]))
+ and isinstance(it.get("kw"), dict) and len(it["kw"]) <= 12
+ and all(WORD.fullmatch(k) and plain(v) for k, v in it["kw"].items())
+ and isinstance(it.get("solid", True), bool) and isinstance(it.get("room", ""), str)):
+ raise ValueError("invalid furniture item")
+
+
+# ------------------------------------------------------------------ pipeline steps
+def run_detect(jid):
+ d = jdir(jid)
+ pdf = os.path.join(d, "source.pdf")
+ try:
+ status(jid, stage="detecting", progress=5, message="Reading the drawing")
+ 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:
+ 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?")
+
+
+def estimate(jid, quality):
+ """seconds this build should take: the latest finished build of the same quality on this machine, scaled by the
+ number of light maps (one per storey + the site); README timings until a build has been measured"""
+ n = len((read_status(jid) or {}).get("floors") or [1]) + 1
+ past = [st for st in (read_status(j) for j in os.listdir(JOBS) if ID.match(j))
+ if st and st.get("build_seconds") and st.get("quality") == quality]
+ if not past:
+ return {"draft": 45, "high": 240}[quality] * n
+ st = max(past, key=lambda s: s["updated"])
+ return st["build_seconds"] * n / (len(st.get("floors") or [1]) + 1)
+
+
+def builder():
+ while True:
+ jid, quality = builds.get()
+ d = jdir(jid)
+ try:
+ t0 = time.time()
+ status(jid, stage="building", progress=1, message="Starting Blender", started=t0, eta_total=estimate(jid, quality))
+ cmd = [BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
+ os.path.join(d, "plan.json"), d, "--quality", quality]
+ with gpu, open(os.path.join(d, "build.log"), "w") as log:
+ pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
+ watchdog = threading.Timer(BUILD_TIMEOUT, pr.kill) # a hung Blender must not block every later build
+ watchdog.start()
+ ok = False
+ for line in pr.stdout:
+ log.write(line)
+ m = re.match(r"PROGRESS (\d+) (.*)", line)
+ if m:
+ status(jid, progress=int(m.group(1)), message=m.group(2).strip())
+ ok = ok or line.startswith("GEN OK")
+ pr.wait()
+ watchdog.cancel()
+ if not ok or not os.path.exists(os.path.join(d, "house.glb")):
+ raise RuntimeError("3D build failed - see build.log")
+ for f in ("house.blend", "house.blend1", "house_baked.blend1"): # keep house_baked.blend only
+ if os.path.exists(os.path.join(d, f)):
+ os.remove(os.path.join(d, f))
+ status(jid, stage="done", progress=100, message="Ready", quality=quality, build_seconds=round(time.time() - t0))
+ except Exception as e:
+ traceback.print_exc()
+ status(jid, stage="failed", message=str(e))
+ finally:
+ builds.task_done()
diff --git a/server.py b/server.py
index 76583a6..d245b1a 100644
--- a/server.py
+++ b/server.py
@@ -3,25 +3,15 @@ Standard library only. Run: python3 server.py [--port 8080] [--host 127.0.0.1] [
Builds run one at a time in Blender (GPU) in a background thread; progress is polled by the pages.
--cors lets pages on another site call the API from the browser (ORIGIN such as https://example.com, or *).
There is no login: run it on a trusted network, or behind your own backend or proxy."""
-import importlib, json, math, os, posixpath, queue, re, shutil, subprocess, sys, threading, time, traceback, uuid, zipfile
+import json, os, re, shutil, subprocess, sys, threading, time, traceback, uuid
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, unquote
HERE = os.path.dirname(os.path.abspath(__file__))
-JOBS = os.path.join(HERE, "jobs")
-WEB = os.path.join(HERE, "web")
-THREE = os.path.join(HERE, "node_modules", "three")
-BLENDER = os.environ.get("BLENDER") or shutil.which("blender") or "blender" # set BLENDER to its full path if it is not on PATH
-MAX_UPLOAD = 200 * 1024 * 1024 # plans are small; recordings sent for MP4 conversion are not
-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, furnish, quantities, themes # noqa: E402
+import jobs, quantities, theme_store, themes # noqa: E402
-os.makedirs(JOBS, exist_ok=True)
-builds = queue.Queue()
-lock = threading.RLock() # reentrant: request handlers hold it around status() to check and set a stage in one step
-BUSY = ("uploaded", "detecting", "queued", "building")
+MAX_UPLOAD = 200 * 1024 * 1024 # plans are small; recordings sent for MP4 conversion are not
FINISHES = themes.FINISHES # room.floor: blender/lib.py materials, as in edit.js FINISH
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",
@@ -30,332 +20,9 @@ TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript", ".css":
CORS = sys.argv[sys.argv.index("--cors") + 1] if "--cors" in sys.argv else None
-def jdir(jid):
- return os.path.join(JOBS, jid)
-
-
-def status(jid, **kw):
- p = os.path.join(jdir(jid), "status.json")
- with lock:
- st = json.load(open(p)) if os.path.exists(p) else {}
- st.update(kw, updated=time.time())
- tmp = p + ".tmp"
- with open(tmp, "w") as fh:
- json.dump(st, fh)
- os.replace(tmp, p)
- return st
-
-
-def read_status(jid):
- p = os.path.join(jdir(jid), "status.json")
- return json.load(open(p)) if os.path.exists(p) else None
-
-
-# ------------------------------------------------------------------ system check and the materials download
-_blender = None # Blender's version, read once ("" = not found)
-assets_job = dict(running=False, done=0, total=0, failed=[])
-export_lock, site_lock = threading.Lock(), threading.Lock() # the site zip takes a second: it must not wait for a Blender pack
-gpu = threading.Lock() # a house build and the themes' pictures both render on the GPU: one at a time
-
-
-def system():
- """what must be in place before a plan is accepted (shown on the home page, enforced on upload and build)"""
- global _blender
- if _blender is None:
- try:
- out = subprocess.run([BLENDER, "--version"], capture_output=True, text=True, timeout=60).stdout
- _blender = (re.search(r"Blender (\d+\.\d+)", out) or [None, ""])[1]
- except (OSError, subprocess.TimeoutExpired):
- _blender = ""
- checks = dict(
- blender=dict(ok=bool(_blender) and tuple(map(int, _blender.split("."))) >= (4, 2), version=_blender),
- pdf_tools=dict(ok=all(shutil.which(c) for c in ("pdftocairo", "pdftotext", "pdfinfo"))),
- viewer=dict(ok=os.path.isfile(os.path.join(THREE, "build", "three.module.js"))),
- materials=dict(ok=not fetch_assets.missing(), **assets_job))
- return dict(ready=all(c["ok"] for c in checks.values()), **checks)
-
-
def fetch_materials():
- def progress(done, total, name):
- assets_job.update(done=done, total=total)
- try:
- assets_job["failed"] = fetch_assets.fetch(progress)
- except Exception as e:
- traceback.print_exc()
- assets_job["failed"] = [str(e)]
- finally:
- assets_job["running"] = False
- thumbs_job["tried"].clear() # the themes' pictures can be drawn now
-
-
-def export_blend(jid):
- """jobs/<id>/house_blender.zip: the built house as one .blend with every texture packed inside (made once per build)"""
- d = jdir(jid)
- src, out = os.path.join(d, "house_baked.blend"), os.path.join(d, "house_blender.zip")
- if not os.path.exists(src):
- raise ValueError("build the 3D house first")
- with export_lock:
- if not os.path.exists(out) or os.path.getmtime(out) < os.path.getmtime(src):
- tmp = os.path.join(d, "export.blend")
- expr = f"import bpy; bpy.ops.file.pack_all(); bpy.ops.wm.save_as_mainfile(filepath={tmp!r}, copy=True, compress=True)"
- subprocess.run([BLENDER, "-b", src, "--python-expr", expr], check=True, timeout=900, capture_output=True)
- with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_STORED) as z: # the .blend is already compressed
- z.write(tmp, "house.blend")
- z.writestr("README.txt", "house.blend - made by PlanTo3D. Open it in Blender 4.2 or newer.\n"
- "Every texture is packed inside the file. Each storey is one mesh (bake_level_N) with its lamps;\n"
- "the render engine is Cycles. Textures and models are CC0, from polyhaven.com.\n")
- os.remove(tmp)
- os.replace(out + ".part", out)
- return f"/jobs/{jid}/house_blender.zip"
-
-
-def three_files():
- """the three.js files the viewer loads: what view.js and walk.js import from three, and what those import in turn"""
- def deps(text, here):
- for s in re.findall(r"\b(?:from|import)\s*['\"]([^'\"]+)['\"]", text):
- if s == "three":
- yield "build/three.module.js"
- elif s.startswith("three/addons/"):
- yield "examples/jsm/" + s[13:]
- elif s.startswith(".") and here is not None:
- yield posixpath.normpath(posixpath.join(here, s))
- todo, seen = [f for w in ("view.js", "walk.js") for f in deps(open(os.path.join(WEB, w)).read(), None)], set()
- while todo:
- f = todo.pop()
- if f not in seen and os.path.isfile(os.path.join(THREE, f)): # (an example in a doc comment may name a file that is not there)
- seen.add(f)
- todo += deps(open(os.path.join(THREE, f)).read(), posixpath.dirname(f))
- # DRACOLoader fetches its decoder at run time (the WebAssembly one, as every browser with import maps has it)
- return sorted(seen) + ["examples/jsm/libs/draco/draco_wasm_wrapper.js", "examples/jsm/libs/draco/draco_decoder.wasm"]
-
-
-def export_site(jid):
- """jobs/<id>/house_site.zip: the walkthrough as a static website for any web host, without this server (made once
- per build). Only the house itself leaves the job folder: never the client's PDF, the plan or the logs."""
- d = jdir(jid)
- glb, out = os.path.join(d, "house.glb"), os.path.join(d, "house_site.zip")
- if not os.path.exists(glb):
- raise ValueError("build the 3D house first")
- srcs = [glb, os.path.join(d, "meta.json")] + [os.path.join(WEB, f) for f in ("view.html", "view.js", "walk.js", "style.css")]
- with site_lock:
- if not os.path.exists(out) or os.path.getmtime(out) < max(map(os.path.getmtime, srcs)): # a new build or a new viewer
- meta = json.load(open(os.path.join(d, "meta.json")))
- house = (["meta.json", "house.glb"] + [os.path.basename(f) for f in (meta.get("lightmaps") or {}).values()]
- + [f["file"] for f in (meta.get("finishes") or {}).values()])
- # view.html with three.js next to it; view.js finds no ?job= and reads the house from ./house/
- page = open(os.path.join(WEB, "view.html")).read().replace('"/three/', '"./three/')
- with zipfile.ZipFile(out + ".part", "w", zipfile.ZIP_DEFLATED) as z:
- z.writestr("index.html", page)
- for f in ("view.js", "walk.js", "style.css"):
- z.write(os.path.join(WEB, f), f)
- for f in three_files():
- z.write(os.path.join(THREE, f), "three/" + f)
- for f in house: # already compressed (Draco, WebP)
- z.write(os.path.join(d, f), "house/" + f, zipfile.ZIP_STORED)
- z.writestr("README.txt", "3D walkthrough - made by PlanTo3D.\n\n"
- "Put this folder on any static web host (Netlify, GitHub Pages, your own server) and open index.html.\n"
- "To try it on your computer, run a web server in this folder, for example\n"
- " python3 -m http.server 8000\n"
- "and open http://localhost:8000/ . Opening index.html straight from the disk does not work:\n"
- "browsers do not load the viewer's modules from file:// pages.\n\n"
- "Viewer: three.js (MIT). Textures and models are CC0, from polyhaven.com.\n")
- os.replace(out + ".part", out)
- return f"/jobs/{jid}/house_site.zip"
-
-
-# ------------------------------------------------------------------ interior themes and their pictures
-THUMBS = os.path.join(fetch_assets.ROOT, "thumbs") # <theme>/<slot>.png
-thumbs_job = dict(running=False, queue=[], tried=set())
-
-
-def render_thumbs():
- """pictures of each queued theme's pieces as they will be built now: a small house with all of them in a row is
- built without baking, then photographed (a minute or so per theme)"""
- try:
- while True:
- with lock:
- if not thumbs_job["queue"]:
- thumbs_job["running"] = False
- return
- tid = thumbs_job["queue"].pop(0)
- out = os.path.join(THUMBS, tid)
- os.makedirs(out, exist_ok=True)
- with open(os.path.join(out, "plan.json"), "w") as fh:
- json.dump(catalog.preview_plan(tid), fh)
- with gpu:
- for cmd, t, done in (([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
- os.path.join(out, "plan.json"), out, "--no-bake"], 1800, "GEN OK"),
- ([BLENDER, "-b", os.path.join(out, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
- "--", out], 900, "THUMBS OK")):
- r = subprocess.run(cmd, capture_output=True, text=True, timeout=t)
- if done not in r.stdout: # (Blender exits 0 even when the script fails; say why in the server log)
- print(f"theme pictures for {tid} failed:\n{(r.stdout + r.stderr)[-2000:]}", file=sys.stderr, flush=True)
- break
- if tid not in themes.THEMES and tid not in themes.custom_ids(): # deleted meanwhile
- shutil.rmtree(out, ignore_errors=True)
- except Exception:
- traceback.print_exc()
- with lock:
- thumbs_job["running"] = False
-
-
-def refresh_thumbs(tid, again=True):
- """draw a theme's pictures (again: also if they were drawn before, after the theme changed)"""
- with lock:
- if not again and tid in thumbs_job["tried"]:
- return
- thumbs_job["tried"].add(tid)
- if tid not in thumbs_job["queue"]:
- thumbs_job["queue"].append(tid)
- if thumbs_job["running"]:
- return
- thumbs_job["running"] = True
- threading.Thread(target=render_thumbs, daemon=True).start()
-
-
-def theme_list():
- out = []
- for tid in [*themes.THEMES, *themes.custom_ids()]:
- T = themes.load(tid)
- if T["id"] != tid: # a custom theme file that cannot be read
- continue
- pics = {s: os.path.getmtime(f) for s in themes.SLOTS if T["slots"][s]
- for f in [os.path.join(THUMBS, tid, s + ".png")] if os.path.exists(f)}
- if any(T["slots"][s] and s not in pics for s in themes.SLOTS) and system()["ready"]:
- refresh_thumbs(tid, again=False) # drawn once on its own; a picture that fails must not loop
- out.append(dict(id=tid, label=T["label"], about=T["about"], builtin=T["builtin"], colours=T["colours"], tex=T.get("tex", {}),
- floors=T["floors"], wall=T["wall"], tv=T["tv"], pictures={s: int(v) for s, v in pics.items()},
- slots={s: dict(value=v, label=themes.label(T, s)) for s, v in T["slots"].items() if v}))
- return dict(themes=out, rendering=thumbs_job["running"], slots=themes.SLOTS, colours=themes.COLOURS, finishes=FINISHES,
- choices={s: themes.choices(s) for s in themes.SLOTS})
-
-
-def save_theme(tid, req):
- """a person's own theme from the Themes page: -> its id. tid None makes a new one, named after its label"""
- t = themes.check(req)
- if tid is None:
- base = re.sub(r"[^a-z0-9]+", "-", t["label"].lower()).strip("-")[:24] or "theme"
- tid, n = base, 2
- while tid in themes.THEMES or os.path.exists(os.path.join(themes.DIR, tid + ".json")):
- tid, n = f"{base}-{n}", n + 1
- elif tid in themes.THEMES or not os.path.exists(os.path.join(themes.DIR, tid + ".json")):
- raise ValueError("Only your own themes can be changed.")
- os.makedirs(themes.DIR, exist_ok=True)
- with open(os.path.join(themes.DIR, tid + ".json.part"), "w") as fh:
- json.dump(t, fh)
- os.replace(os.path.join(themes.DIR, tid + ".json.part"), os.path.join(themes.DIR, tid + ".json"))
- refresh_thumbs(tid)
- return tid
-
-
-def plan_items(jid):
- """the furniture each floor will get (the review page's own list if it edited that floor, else the rules' choice),
- and what can be added, at the sizes of the plan's theme"""
- plan = json.load(open(os.path.join(jdir(jid), "plan.json")))
- T, cat = themes.load(plan.get("theme")), {}
- for fn, (label, w, d, kw) in catalog.CATALOG.items():
- m = themes.size(T, fn)
- cat[fn] = [themes.label(T, fn), *((m[0], m[1] + (3.2 if fn == "dining_set" else 0)) if m else (w, d)), kw]
- for fn in ("armchair", "corner", "bed_end"): # decor of the theme that stands on the floor
- if themes.size(T, fn):
- cat[fn] = [themes.label(T, fn), *themes.size(T, fn)[:2], {}]
- return dict(floors=[furnish.floor_items(plan, f) for f in plan["floors"]], catalog=cat)
-
-
-# items the browser may send: must match gen.CALLS (gen.py runs inside Blender, so it cannot be imported here),
-# minus "model", whose argument is an asset file name
-ITEM_FNS = set(catalog.CATALOG) | {"shower2", "geyser", "kitchen_run", "chimney", "wall_cab2", "rug", "car",
- "outdoor_set", "bathtub", "round_rug", "armchair", "art", "mirror", "decor", "corner", "bed_end"}
-WORD = re.compile(r"@?[\w+-]{0,24}") # side names such as "-x", material names, "@style" pieces; nothing that can be a path
-
-
-def check_items(plan):
- """furniture lists from the browser go to Blender as function arguments: only known items, plain values"""
- num = lambda v: isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
- plain = lambda v: v is None or isinstance(v, bool) or num(v) or (isinstance(v, str) and WORD.fullmatch(v))
- for f in plan["floors"]:
- if not isinstance(f, dict) or "items" not in f:
- continue
- items = f["items"]
- if not isinstance(items, list) or len(items) > 400:
- raise ValueError("invalid furniture list")
- for it in items:
- if not (isinstance(it, dict) and isinstance(it.get("fn"), str) and it["fn"] in ITEM_FNS
- and isinstance(it.get("args"), list) and len(it["args"]) <= 8 and all(num(v) or isinstance(v, str) and WORD.fullmatch(v) for v in it["args"])
- and isinstance(it.get("box"), list) and len(it["box"]) == 4 and all(map(num, it["box"]))
- and isinstance(it.get("kw"), dict) and len(it["kw"]) <= 12
- and all(WORD.fullmatch(k) and plain(v) for k, v in it["kw"].items())
- and isinstance(it.get("solid", True), bool) and isinstance(it.get("room", ""), str)):
- raise ValueError("invalid furniture item")
-
-
-# ------------------------------------------------------------------ pipeline steps
-def run_detect(jid):
- d = jdir(jid)
- pdf = os.path.join(d, "source.pdf")
- try:
- status(jid, stage="detecting", progress=5, message="Reading the drawing")
- 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:
- 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?")
-
-
-def estimate(jid, quality):
- """seconds this build should take: the latest finished build of the same quality on this machine, scaled by the
- number of light maps (one per storey + the site); README timings until a build has been measured"""
- n = len((read_status(jid) or {}).get("floors") or [1]) + 1
- past = [st for st in (read_status(j) for j in os.listdir(JOBS) if ID.match(j))
- if st and st.get("build_seconds") and st.get("quality") == quality]
- if not past:
- return {"draft": 45, "high": 240}[quality] * n
- st = max(past, key=lambda s: s["updated"])
- return st["build_seconds"] * n / (len(st.get("floors") or [1]) + 1)
-
-
-def builder():
- while True:
- jid, quality = builds.get()
- d = jdir(jid)
- try:
- t0 = time.time()
- status(jid, stage="building", progress=1, message="Starting Blender", started=t0, eta_total=estimate(jid, quality))
- cmd = [BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
- os.path.join(d, "plan.json"), d, "--quality", quality]
- with gpu, open(os.path.join(d, "build.log"), "w") as log:
- pr = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
- watchdog = threading.Timer(BUILD_TIMEOUT, pr.kill) # a hung Blender must not block every later build
- watchdog.start()
- ok = False
- for line in pr.stdout:
- log.write(line)
- m = re.match(r"PROGRESS (\d+) (.*)", line)
- if m:
- status(jid, progress=int(m.group(1)), message=m.group(2).strip())
- ok = ok or line.startswith("GEN OK")
- pr.wait()
- watchdog.cancel()
- if not ok or not os.path.exists(os.path.join(d, "house.glb")):
- raise RuntimeError("3D build failed - see build.log")
- for f in ("house.blend", "house.blend1", "house_baked.blend1"): # keep house_baked.blend only
- if os.path.exists(os.path.join(d, f)):
- os.remove(os.path.join(d, f))
- status(jid, stage="done", progress=100, message="Ready", quality=quality, build_seconds=round(time.time() - t0))
- except Exception as e:
- traceback.print_exc()
- status(jid, stage="failed", message=str(e))
- finally:
- builds.task_done()
+ jobs.fetch_materials()
+ theme_store.thumbs_job["tried"].clear() # the themes' pictures can be drawn now
# ------------------------------------------------------------------ http
@@ -430,41 +97,41 @@ class H(BaseHTTPRequestHandler):
u = urlparse(self.path)
p = unquote(u.path)
if p in ("/", "/index.html"):
- return self.file(os.path.join(WEB, "index.html"), WEB)
+ return self.file(os.path.join(jobs.WEB, "index.html"), jobs.WEB)
if p.startswith("/web/"):
- return self.file(os.path.join(WEB, p[5:]), WEB)
+ return self.file(os.path.join(jobs.WEB, p[5:]), jobs.WEB)
if p.startswith("/examples/"):
return self.file(os.path.join(HERE, "examples", p[10:]), os.path.join(HERE, "examples"))
if p.startswith("/thumbs/"):
- return self.file(os.path.join(THUMBS, p[8:]), THUMBS)
+ return self.file(os.path.join(theme_store.THUMBS, p[8:]), theme_store.THUMBS)
if p == "/api/themes":
- return self.send(200, theme_list())
+ return self.send(200, theme_store.theme_list())
if p.startswith("/three/"):
- return self.file(os.path.join(THREE, p[7:]), THREE)
+ return self.file(os.path.join(jobs.THREE, p[7:]), jobs.THREE)
if p.startswith("/jobs/"):
parts = p[6:].split("/", 1)
- if len(parts) == 2 and ID.match(parts[0]):
- return self.file(os.path.join(jdir(parts[0]), parts[1]), jdir(parts[0]))
+ if len(parts) == 2 and jobs.ID.match(parts[0]):
+ return self.file(os.path.join(jobs.jdir(parts[0]), parts[1]), jobs.jdir(parts[0]))
return self.send(404, {"error": "not found"})
m = re.match(r"^/api/jobs/([a-f0-9]{12})$", p)
if m:
- st = read_status(m.group(1))
+ st = jobs.read_status(m.group(1))
if st and st.get("stage") == "building" and st.get("started"): # counted here: the viewer's clock may differ
left = st["started"] + st["eta_total"] - time.time()
st["eta_left"] = max(0, round(min(left, 15) if st.get("progress", 0) >= 92 else left)) # 92 = exporting, the last step
return self.send(200 if st else 404, st or {"error": "no such job"})
m = re.match(r"^/api/jobs/([a-f0-9]{12})/furniture$", p)
if m:
- if not os.path.exists(os.path.join(jdir(m.group(1)), "plan.json")):
+ if not os.path.exists(os.path.join(jobs.jdir(m.group(1)), "plan.json")):
return self.send(404, {"error": "no plan yet"})
try:
- return self.send(200, plan_items(m.group(1)))
+ return self.send(200, jobs.plan_items(m.group(1)))
except Exception:
traceback.print_exc()
return self.send(500, {"error": "The furniture could not be worked out - see the server log."})
m = re.match(r"^/api/jobs/([a-f0-9]{12})/quantities$", p)
if m:
- f = os.path.join(jdir(m.group(1)), "plan.json")
+ f = os.path.join(jobs.jdir(m.group(1)), "plan.json")
if not os.path.exists(f):
return self.send(404, {"error": "no plan yet"})
try:
@@ -473,12 +140,12 @@ class H(BaseHTTPRequestHandler):
traceback.print_exc()
return self.send(500, {"error": "The quantities could not be worked out - see the server log."})
if p == "/api/system":
- return self.send(200, system())
+ return self.send(200, jobs.system())
if p == "/api/jobs":
out = []
- for jid in filter(ID.match, os.listdir(JOBS)):
+ for jid in filter(jobs.ID.match, os.listdir(jobs.JOBS)):
try:
- st = read_status(jid)
+ st = jobs.read_status(jid)
except (OSError, ValueError): # deleted (or being deleted) while we list
continue
if st:
@@ -495,15 +162,15 @@ class H(BaseHTTPRequestHandler):
def delete(self):
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))):
- with lock:
- if (read_status(m.group(1)) or {}).get("stage") in BUSY:
+ if m and os.path.isdir(jobs.jdir(m.group(1))):
+ with jobs.lock:
+ if (jobs.read_status(m.group(1)) or {}).get("stage") in jobs.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)))
+ shutil.rmtree(jobs.jdir(m.group(1)))
return self.send(200, {"ok": True})
m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})$", p)
if m and m.group(1) in themes.custom_ids(): # a person's own theme (plans built with it get contemporary)
- for f in (os.path.join(themes.DIR, m.group(1)), os.path.join(THUMBS, m.group(1))):
+ for f in (os.path.join(themes.DIR, m.group(1)), os.path.join(theme_store.THUMBS, m.group(1))):
shutil.rmtree(f, ignore_errors=True)
os.remove(os.path.join(themes.DIR, m.group(1) + ".json"))
return self.send(200, {"ok": True})
@@ -513,7 +180,7 @@ class H(BaseHTTPRequestHandler):
t["slots"].pop(m.group(2), None)
if os.path.exists(themes.upload_path(*m.groups())):
os.remove(themes.upload_path(*m.groups()))
- save_theme(m.group(1), t)
+ theme_store.save_theme(m.group(1), t)
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
@@ -529,11 +196,11 @@ class H(BaseHTTPRequestHandler):
fh.write(data)
t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
t["slots"][m.group(2)] = "upload"
- save_theme(m.group(1), t)
+ theme_store.save_theme(m.group(1), t)
return self.send(200, {"ok": True})
m = re.match(r"^/api/themes(?:/([a-z0-9][a-z0-9_-]{0,29}))?$", p)
if m: # make (no id) or change one of your own themes
- return self.send(200, {"id": save_theme(m.group(1), json.loads(self.body() or b"{}"))})
+ return self.send(200, {"id": theme_store.save_theme(m.group(1), json.loads(self.body() or b"{}"))})
if p == "/api/mp4": # a WebM recording in, the same video as MP4 out
if not shutil.which("ffmpeg"):
return self.send(501, {"error": "ffmpeg is not installed on the server"})
@@ -544,14 +211,14 @@ class H(BaseHTTPRequestHandler):
return self.send(500, {"error": "the recording could not be converted"})
return self.send(200, r.stdout, "video/mp4")
if p == "/api/materials": # start the Poly Haven download (the home page's button)
- with lock:
- start = not assets_job["running"]
+ with jobs.lock:
+ start = not jobs.assets_job["running"]
if start:
- assets_job.update(running=True, done=0, total=0, failed=[])
+ jobs.assets_job.update(running=True, done=0, total=0, failed=[])
if start:
threading.Thread(target=fetch_materials, daemon=True).start()
return self.send(200, {"ok": True})
- if (p == "/api/upload" or p.endswith("/build")) and not system()["ready"]:
+ if (p == "/api/upload" or p.endswith("/build")) and not jobs.system()["ready"]:
return self.send(503, {"error": "The server is not set up yet: open its home page to see what is missing."})
if p == "/api/upload":
data = self.body()
@@ -560,26 +227,26 @@ class H(BaseHTTPRequestHandler):
return self.send(400, {"error": "Please upload a PDF exported from your CAD tool "
"(images and DWG are not supported yet)."})
jid = uuid.uuid4().hex[:12]
- os.makedirs(jdir(jid))
- with open(os.path.join(jdir(jid), "source.pdf"), "wb") as fh:
+ os.makedirs(jobs.jdir(jid))
+ with open(os.path.join(jobs.jdir(jid), "source.pdf"), "wb") as fh:
fh.write(data)
- status(jid, name=name, stage="uploaded", progress=0, message="Uploaded", created=time.time())
- threading.Thread(target=run_detect, args=(jid,), daemon=True).start()
+ jobs.status(jid, name=name, stage="uploaded", progress=0, message="Uploaded", created=time.time())
+ threading.Thread(target=jobs.run_detect, args=(jid,), daemon=True).start()
return self.send(200, {"id": jid})
m = re.match(r"^/api/jobs/([a-f0-9]{12})/(plan|build|export|site)$", p)
- if m and os.path.isdir(jdir(m.group(1))):
+ if m and os.path.isdir(jobs.jdir(m.group(1))):
jid, what = m.groups()
if what == "export":
- return self.send(200, {"url": export_blend(jid)})
+ return self.send(200, {"url": jobs.export_blend(jid)})
if what == "site":
- if (read_status(jid) or {}).get("stage") in BUSY: # half old, half new files: and it would be kept
+ if (jobs.read_status(jid) or {}).get("stage") in jobs.BUSY: # half old, half new files: and it would be kept
return self.send(409, {"error": "this plan is being read or built"})
- return self.send(200, {"url": export_site(jid)})
+ return self.send(200, {"url": jobs.export_site(jid)})
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:
+ with jobs.lock: # checked and set in one step: two quick clicks must not queue two builds
+ if (jobs.read_status(jid) or {}).get("stage") in jobs.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"]:
@@ -595,13 +262,13 @@ class H(BaseHTTPRequestHandler):
th = req.get("theme")
if "theme" in req and not (isinstance(th, str) and (th in themes.THEMES or th in themes.custom_ids())):
return self.send(400, {"error": "Unknown interior theme."})
- check_items(req)
- with open(os.path.join(jdir(jid), "plan.json"), "w") as fh:
+ jobs.check_items(req)
+ with open(os.path.join(jobs.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))
+ jobs.status(jid, stage="queued", progress=0, message=f"Waiting for the 3D builder ({jobs.builds.qsize()} ahead)")
+ jobs.builds.put((jid, q))
return self.send(200, {"ok": True})
self.send(404, {"error": "not found"})
@@ -609,12 +276,12 @@ class H(BaseHTTPRequestHandler):
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): # work interrupted by a restart: reading starts again, a build is pressed again
- st = read_status(jid) if ID.match(jid) else None
+ for jid in os.listdir(jobs.JOBS): # work interrupted by a restart: reading starts again, a build is pressed again
+ st = jobs.read_status(jid) if jobs.ID.match(jid) else None
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()
+ threading.Thread(target=jobs.run_detect, args=(jid,), daemon=True).start()
+ elif st and st.get("stage") in jobs.BUSY:
+ jobs.status(jid, stage="failed", message="interrupted by a server restart - press Build again")
+ threading.Thread(target=jobs.builder, daemon=True).start()
print(f"PlanTo3D on http://{host}:{port}", flush=True)
ThreadingHTTPServer((host, port), H).serve_forever()
diff --git a/tests/test_server.py b/tests/test_server.py
index de75976..4be306c 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -8,11 +8,11 @@ HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(HERE)
sys.path[:0] = [ROOT, os.path.join(ROOT, "examples")]
import make_sample as M # noqa: E402
-import detect, server, themes # noqa: E402
+import detect, jobs, server, theme_store, themes # noqa: E402
-server.JOBS = tempfile.mkdtemp() # never touch the real jobs folder
-themes.DIR, server.THUMBS = tempfile.mkdtemp(), tempfile.mkdtemp() # nor the real themes and their pictures
-server.refresh_thumbs = lambda tid, again=True: None # (pictures need Blender)
+jobs.JOBS = tempfile.mkdtemp() # never touch the real jobs folder
+themes.DIR, theme_store.THUMBS = tempfile.mkdtemp(), tempfile.mkdtemp() # nor the real themes and their pictures
+theme_store.refresh_thumbs = lambda tid, again=True: None # (pictures need Blender)
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}"
@@ -29,8 +29,8 @@ def call(method, path, body=None):
def job(stage):
jid = os.urandom(6).hex()
- os.makedirs(server.jdir(jid))
- server.status(jid, stage=stage)
+ os.makedirs(jobs.jdir(jid))
+ jobs.status(jid, stage=stage)
return jid
@@ -38,31 +38,31 @@ 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("DELETE", f"/api/jobs/{busy}")[0] == 409 and os.path.isdir(jobs.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 json.load(open(os.path.join(jobs.jdir(done), "plan.json")))["floors"][0]["name"] == "G"
# room finishes and wall colour reach Blender as material names and colours: only known values pass
plan = lambda room, **kw: json.dumps({"floors": [{"rooms": [room]}], **kw}).encode()
for bad in (plan({"floor": "lava"}), plan({"floor": ["wood"]}), plan({}, wall_color="red"), plan({}, wall_color="#12345g"),
plan({}, wall_color="#123456\n"), plan({}, wall_color=None)):
assert call("POST", f"/api/jobs/{done}/plan", bad)[0] == 400, bad
assert call("POST", f"/api/jobs/{done}/plan", plan({"floor": "wood"}, wall_color="#C3cdb4"))[0] == 200
- saved = json.load(open(os.path.join(server.jdir(done), "plan.json")))
+ saved = json.load(open(os.path.join(jobs.jdir(done), "plan.json")))
assert saved["floors"][0]["rooms"][0]["floor"] == "wood" and saved["wall_color"] == "#C3cdb4"
assert call("POST", f"/api/jobs/{done}/export")[0] == 400 # nothing built yet
assert call("POST", f"/api/jobs/{done}/site")[0] == 400 # nothing built yet
- assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(server.jdir(done))
+ assert call("DELETE", f"/api/jobs/{done}")[0] == 200 and not os.path.exists(jobs.jdir(done))
print("ok server: hidden files, busy plans, bad bodies, room finishes")
# furniture: the rules' list until the review page sends its own; an empty list is an empty floor
jid = job("detected")
assert call("GET", f"/api/jobs/{jid}/furniture")[0] == 404 # not read yet
plan = detect.detect(os.path.join(ROOT, "examples", "sample_plan.pdf"))
- json.dump(plan, open(os.path.join(server.jdir(jid), "plan.json"), "w"))
+ json.dump(plan, open(os.path.join(jobs.jdir(jid), "plan.json"), "w"))
code, out = call("GET", f"/api/jobs/{jid}/furniture")
out = json.loads(out)
assert code == 200 and len(out["floors"]) == len(plan["floors"]) and "bed" in out["catalog"], out
@@ -91,10 +91,10 @@ try:
built = job("done")
for f, data in (("meta.json", b'{"lightmaps": {"bake_level_0": "lm_bake_level_0.webp"}}'), ("house.glb", b"glTF"),
("lm_bake_level_0.webp", b"RIFF"), ("source.pdf", b"%PDF"), ("plan.json", b"{}")):
- open(os.path.join(server.jdir(built), f), "wb").write(data)
+ open(os.path.join(jobs.jdir(built), f), "wb").write(data)
code, body = call("POST", f"/api/jobs/{built}/site")
assert code == 200, body
- names = zipfile.ZipFile(os.path.join(server.jdir(built), "house_site.zip")).namelist()
+ names = zipfile.ZipFile(os.path.join(jobs.jdir(built), "house_site.zip")).namelist()
for f in ("index.html", "view.js", "walk.js", "three/build/three.module.js", "three/examples/jsm/libs/draco/draco_decoder.wasm",
"house/meta.json", "house/house.glb", "house/lm_bake_level_0.webp"):
assert f in names, f
@@ -102,18 +102,18 @@ try:
print("ok server: website zip")
# 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")
+ cover = os.path.join(jobs.JOBS, "cover.pdf")
open(cover, "wb").write(M.pdf_page(b""))
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)
+ os.path.join(jobs.jdir(jid), "source.pdf")], check=True)
+ jobs.run_detect(jid)
+ st = jobs.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"]
+ assert sorted(os.listdir(jobs.jdir(jid))) == ["page-2.png", "plan.json", "source.pdf", "status.json"]
+ shutil.copy(cover, os.path.join(jobs.jdir(jid), "source.pdf"))
+ jobs.run_detect(jid)
+ assert "scan" in jobs.read_status(jid)["message"]
print("ok server: a cover sheet before the plan, a PDF without lines")
# interior themes: the built-in ones are listed and fixed; own ones are checked, take .glb models, and can be chosen
@@ -143,4 +143,4 @@ try:
print("ok server: interior themes")
finally:
httpd.shutdown()
- shutil.rmtree(server.JOBS)
+ shutil.rmtree(jobs.JOBS)
diff --git a/theme_store.py b/theme_store.py
new file mode 100644
index 0000000..88ddadd
--- /dev/null
+++ b/theme_store.py
@@ -0,0 +1,90 @@
+"""People's own interior themes on disk, the list the Themes page shows, and the pictures of each theme's pieces
+(rendered in Blender, one theme at a time, sharing the GPU with house builds)."""
+import json, os, re, shutil, subprocess, sys, threading, traceback
+
+import catalog, fetch_assets, themes
+from jobs import BLENDER, HERE, gpu, lock, system
+
+
+THUMBS = os.path.join(fetch_assets.ROOT, "thumbs") # <theme>/<slot>.png
+thumbs_job = dict(running=False, queue=[], tried=set())
+
+
+def render_thumbs():
+ """pictures of each queued theme's pieces as they will be built now: a small house with all of them in a row is
+ built without baking, then photographed (a minute or so per theme)"""
+ try:
+ while True:
+ with lock:
+ if not thumbs_job["queue"]:
+ thumbs_job["running"] = False
+ return
+ tid = thumbs_job["queue"].pop(0)
+ out = os.path.join(THUMBS, tid)
+ os.makedirs(out, exist_ok=True)
+ with open(os.path.join(out, "plan.json"), "w") as fh:
+ json.dump(catalog.preview_plan(tid), fh)
+ with gpu:
+ for cmd, t, done in (([BLENDER, "-b", "--factory-startup", "-P", os.path.join(HERE, "blender", "gen.py"), "--",
+ os.path.join(out, "plan.json"), out, "--no-bake"], 1800, "GEN OK"),
+ ([BLENDER, "-b", os.path.join(out, "house.blend"), "-P", os.path.join(HERE, "blender", "thumbs.py"),
+ "--", out], 900, "THUMBS OK")):
+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=t)
+ if done not in r.stdout: # (Blender exits 0 even when the script fails; say why in the server log)
+ print(f"theme pictures for {tid} failed:\n{(r.stdout + r.stderr)[-2000:]}", file=sys.stderr, flush=True)
+ break
+ if tid not in themes.THEMES and tid not in themes.custom_ids(): # deleted meanwhile
+ shutil.rmtree(out, ignore_errors=True)
+ except Exception:
+ traceback.print_exc()
+ with lock:
+ thumbs_job["running"] = False
+
+
+def refresh_thumbs(tid, again=True):
+ """draw a theme's pictures (again: also if they were drawn before, after the theme changed)"""
+ with lock:
+ if not again and tid in thumbs_job["tried"]:
+ return
+ thumbs_job["tried"].add(tid)
+ if tid not in thumbs_job["queue"]:
+ thumbs_job["queue"].append(tid)
+ if thumbs_job["running"]:
+ return
+ thumbs_job["running"] = True
+ threading.Thread(target=render_thumbs, daemon=True).start()
+
+
+def theme_list():
+ out = []
+ for tid in [*themes.THEMES, *themes.custom_ids()]:
+ T = themes.load(tid)
+ if T["id"] != tid: # a custom theme file that cannot be read
+ continue
+ pics = {s: os.path.getmtime(f) for s in themes.SLOTS if T["slots"][s]
+ for f in [os.path.join(THUMBS, tid, s + ".png")] if os.path.exists(f)}
+ if any(T["slots"][s] and s not in pics for s in themes.SLOTS) and system()["ready"]:
+ refresh_thumbs(tid, again=False) # drawn once on its own; a picture that fails must not loop
+ out.append(dict(id=tid, label=T["label"], about=T["about"], builtin=T["builtin"], colours=T["colours"], tex=T.get("tex", {}),
+ floors=T["floors"], wall=T["wall"], tv=T["tv"], pictures={s: int(v) for s, v in pics.items()},
+ slots={s: dict(value=v, label=themes.label(T, s)) for s, v in T["slots"].items() if v}))
+ return dict(themes=out, rendering=thumbs_job["running"], slots=themes.SLOTS, colours=themes.COLOURS, finishes=themes.FINISHES,
+ choices={s: themes.choices(s) for s in themes.SLOTS})
+
+
+def save_theme(tid, req):
+ """a person's own theme from the Themes page: -> its id. tid None makes a new one, named after its label"""
+ t = themes.check(req)
+ if tid is None:
+ base = re.sub(r"[^a-z0-9]+", "-", t["label"].lower()).strip("-")[:24] or "theme"
+ tid, n = base, 2
+ while tid in themes.THEMES or os.path.exists(os.path.join(themes.DIR, tid + ".json")):
+ tid, n = f"{base}-{n}", n + 1
+ elif tid in themes.THEMES or not os.path.exists(os.path.join(themes.DIR, tid + ".json")):
+ raise ValueError("Only your own themes can be changed.")
+ os.makedirs(themes.DIR, exist_ok=True)
+ with open(os.path.join(themes.DIR, tid + ".json.part"), "w") as fh:
+ json.dump(t, fh)
+ os.replace(os.path.join(themes.DIR, tid + ".json.part"), os.path.join(themes.DIR, tid + ".json"))
+ refresh_thumbs(tid)
+ return tid