Skip to content

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

Python
16.5 KB
Raw Blame
"""PlanTo3D web app: upload a CAD-exported PDF floor plan -> review the detected plan -> build a walkable 3D house.
Standard library only. Run: python3 server.py [--port 8080] [--host 127.0.0.1] [--cors ORIGIN]
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 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__))
sys.path.insert(0, HERE)
import jobs, quantities, theme_store, themes  # noqa: E402

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",
         ".wasm": "application/wasm", ".svg": "image/svg+xml", ".pdf": "application/pdf", ".hdr": "application/octet-stream",
         ".zip": "application/zip"}
CORS = sys.argv[sys.argv.index("--cors") + 1] if "--cors" in sys.argv else None


def fetch_materials():
    jobs.fetch_materials()
    theme_store.thumbs_job["tried"].clear()          # the themes' pictures can be drawn now


# ------------------------------------------------------------------ http
class H(BaseHTTPRequestHandler):
    server_version = "PlanTo3D/1"

    def log_message(self, fmt, *a):
        if not self.path.startswith("/api/jobs/") or "status" not in self.path:
            sys.stderr.write("%s %s\n" % (self.address_string(), fmt % a))

    def send(self, code, body, ctype="application/json"):
        if isinstance(body, (dict, list)):
            body = json.dumps(body).encode()
        elif isinstance(body, str):
            body = body.encode()
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-cache")
        self.cors()
        self.end_headers()
        self.wfile.write(body)

    def cors(self):
        if CORS:
            self.send_header("Access-Control-Allow-Origin", CORS)
            self.send_header("Access-Control-Allow-Headers", "Content-Type, X-Filename")
            self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE")

    def do_OPTIONS(self):               # the browser's question before a cross-site POST
        self.send_response(204)
        self.cors()
        self.send_header("Content-Length", "0")
        self.end_headers()

    def file(self, path, root):
        path = os.path.realpath(path)
        if not path.startswith(os.path.realpath(root) + os.sep) or not os.path.isfile(path):
            return self.send(404, {"error": "not found"})
        ext = os.path.splitext(path)[1].lower()
        size = os.path.getsize(path)
        self.send_response(200)
        self.send_header("Content-Type", TYPES.get(ext, "application/octet-stream"))
        self.send_header("Content-Length", str(size))
        # job outputs change on every rebuild: never let the browser show a stale house
        fresh = ext in (".json", ".html", ".js", ".css", ".png") or "/jobs/" in path.replace(os.sep, "/")
        self.send_header("Cache-Control", "no-cache" if fresh else "max-age=3600")
        self.cors()
        self.end_headers()
        with open(path, "rb") as fh:
            shutil.copyfileobj(fh, self.wfile)

    def do_GET(self):
        self.guard(self.get)

    def do_DELETE(self):
        self.guard(self.delete)

    def do_POST(self):
        self.guard(self.post)

    def guard(self, fn):
        try:
            fn()
        except (ValueError, json.JSONDecodeError) as e:
            self.send(400, {"error": str(e)})
        except Exception:              # anything else: still answer, so the page can say what failed
            traceback.print_exc()
            self.send(500, {"error": "The server could not do that - see its log."})

    def get(self):
        u = urlparse(self.path)
        p = unquote(u.path)
        if p in ("/", "/index.html"):
            return self.file(os.path.join(jobs.WEB, "index.html"), jobs.WEB)
        if p.startswith("/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(theme_store.THUMBS, p[8:]), theme_store.THUMBS)
        if p == "/api/themes":
            return self.send(200, theme_store.theme_list())
        if p.startswith("/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 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 = 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
                st["elapsed"] = round(time.time() - st["started"])
            if st and st.get("stage") not in jobs.BUSY:      # before a build: how long each quality should take
                st["eta"] = {q: round(jobs.estimate(m.group(1), q)) for q in ("draft", "high")}
            if st and st.get("stage") == "done":            # built before a fix to the build: worth building again
                st["outdated"] = st.get("engine", 0) < jobs.ENGINE
            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(jobs.jdir(m.group(1)), "plan.json")):
                return self.send(404, {"error": "no plan yet"})
            try:
                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(jobs.jdir(m.group(1)), "plan.json")
            if not os.path.exists(f):
                return self.send(404, {"error": "no plan yet"})
            try:
                return self.send(200, quantities.quantities(json.load(open(f))))
            except Exception:
                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, jobs.system())
        if p == "/api/jobs":
            out = []
            for jid in filter(jobs.ID.match, os.listdir(jobs.JOBS)):
                try:
                    st = jobs.read_status(jid)
                except (OSError, ValueError):     # deleted (or being deleted) while we list
                    continue
                if st:
                    out.append(dict(id=jid, **{k: st.get(k) for k in ("name", "stage", "updated", "floors")}))
            return self.send(200, sorted(out, key=lambda j: -(j["updated"] or 0))[:30])
        self.send(404, {"error": "not found"})

    def body(self):
        n = int(self.headers.get("Content-Length") or 0)
        if not 0 <= n <= MAX_UPLOAD:
            raise ValueError("file too large (200 MB max)")
        return self.rfile.read(n)

    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(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(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(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})
        m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
        if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS:     # back to the built-in piece
            t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
            t["slots"].pop(m.group(2), None)
            if os.path.exists(themes.upload_path(*m.groups())):
                os.remove(themes.upload_path(*m.groups()))
            theme_store.save_theme(m.group(1), t)
            return self.send(200, {"ok": True})
        self.send(404, {"error": "not found"})

    def post(self):
        p = urlparse(self.path).path
        m = re.match(r"^/api/themes/([a-z0-9][a-z0-9_-]{0,29})/model/(\w+)$", p)
        if m and m.group(1) in themes.custom_ids() and m.group(2) in themes.SLOTS:   # your model for a piece (.glb)
            data = self.body()
            if not data.startswith(b"glTF"):
                return self.send(400, {"error": "Please upload a .glb file (binary glTF)."})
            os.makedirs(os.path.dirname(themes.upload_path(*m.groups())), exist_ok=True)
            with open(themes.upload_path(*m.groups()), "wb") as fh:
                fh.write(data)
            t = json.load(open(os.path.join(themes.DIR, m.group(1) + ".json")))
            t["slots"][m.group(2)] = "upload"
            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": 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"})
            r = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", "pipe:0", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18",
                                "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2", "-movflags", "frag_keyframe+empty_moov", "-f", "mp4", "pipe:1"],
                               input=self.body(), capture_output=True, timeout=600)
            if r.returncode or not r.stdout:
                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 jobs.lock:
                start = not jobs.assets_job["running"]
                if start:
                    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 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()
            name = os.path.basename(unquote(self.headers.get("X-Filename") or "plan.pdf"))[:120]
            if not data.startswith(b"%PDF"):
                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(jobs.jdir(jid))
            with open(os.path.join(jobs.jdir(jid), "source.pdf"), "wb") as fh:
                fh.write(data)
            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(jobs.jdir(m.group(1))):
            jid, what = m.groups()
            if what == "export":
                return self.send(200, {"url": jobs.export_blend(jid)})
            if what == "site":
                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": jobs.export_site(jid)})
            req = json.loads(self.body() or b"{}")
            if not isinstance(req, dict):
                raise ValueError("expected a JSON object")
            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"]:
                        return self.send(400, {"error": "invalid plan"})
                    # both go to Blender as material names / colours: only values it knows
                    rooms = [z for f in req["floors"] if isinstance(f, dict) and isinstance(f.get("rooms"), list)
                             for z in f["rooms"] if isinstance(z, dict)]
                    if any("floor" in z and z["floor"] not in FINISHES for z in rooms):
                        return self.send(400, {"error": "Unknown floor finish."})
                    wall = req.get("wall_color")
                    if "wall_color" in req and not (isinstance(wall, str) and re.fullmatch(r"#[0-9a-fA-F]{6}", wall)):
                        return self.send(400, {"error": "Wall colour must look like #rrggbb."})
                    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."})
                    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"
                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"})


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.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=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()