# -*- coding: utf-8 -*- """ 建筑机器人绘图系统 · 本地编排服务(多用户并发版) 纯 Python 标准库。默认监听 0.0.0.0:8765,局域网内其他同事可直接访问。 任务进入 FIFO 队列,由单个 Blender 工作线程串行消费,多人同时提交不会互相覆盖。 """ import json, os, queue, socket, subprocess, sys, threading, time, webbrowser from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import unquote, urlparse, parse_qs ROOT = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, ROOT) from paths import (STATIC, PLANS, THUMBS, OUTPUT, MEDIA, BLENDER, BUILD_SCRIPT, BLENDER_DIR_NAME) import kb import llm import chat import patch import quickqa import projects PORT = int(os.environ.get("ARCHROBOT_PORT", "8765")) HOST = os.environ.get("ARCHROBOT_HOST", "127.0.0.1") os.makedirs(OUTPUT, exist_ok=True) STATUS = {} STATUS_LOCK = threading.Lock() TASK_Q = queue.Queue() RUNNING = {"id": None} MIME = {".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".mp4": "video/mp4", ".blend": "application/octet-stream", ".ico": "image/x-icon"} def set_status(pid, d): with STATUS_LOCK: STATUS[pid] = d class RateGate: """按 IP 的滑动窗口 + 全局并发上限。 为什么要有:部署到公网后 API Key 在服务端,别人刷对话花的是本账号的钱。 这里不追求精确,只挡住"手抖连点"和"脚本刷"两种最常见的情况。 """ def __init__(self, per_ip=30, window=600, concurrent=3): self.per_ip = per_ip # 每个 IP 在窗口内最多问几次 self.window = window # 窗口长度(秒) self.concurrent = concurrent # 同时进行中的模型调用上限 self._hits = {} # ip -> [时间戳] self._lock = threading.Lock() self._inflight = 0 def take(self, ip): now = time.time() with self._lock: if self._inflight >= self.concurrent: return False, "同时提问的人有点多,请稍等几秒再发", 5 arr = [t for t in self._hits.get(ip, []) if now - t < self.window] if len(arr) >= self.per_ip: wait = int(self.window - (now - arr[0])) + 1 self._hits[ip] = arr return False, "本机提问次数已达上限(%d 次 / %d 分钟)" % ( self.per_ip, self.window // 60), wait arr.append(now) self._hits[ip] = arr self._inflight += 1 return True, "", 0 def done(self): with self._lock: self._inflight = max(0, self._inflight - 1) CHAT_GATE = RateGate() def get_status(pid): with STATUS_LOCK: return dict(STATUS[pid]) if pid in STATUS else None def cached_state(pid): """内存状态优先;服务重启后从磁盘产物恢复,避免"已建模"标记丢失""" s = get_status(pid) if s: return s if os.path.exists(os.path.join(OUTPUT, pid, "model.blend")): return {"state": "done", "msg": "已建模(本地已有产物)", "cached": True} return {"state": "idle"} def run_blender(plan_id): out_dir = os.path.join(OUTPUT, plan_id) json_path = os.path.join(PLANS, plan_id + ".json") if not os.path.exists(json_path): set_status(plan_id, {"state": "error", "msg": "图纸不存在"}) return set_status(plan_id, {"state": "running", "msg": "Blender 引擎启动,解析多视角图纸..."}) cmd = [BLENDER, "--background", "--factory-startup", "--threads", "4", "--python", BUILD_SCRIPT, "--", "--json", json_path, "--out", out_dir] # 低优先级:建模跑满 CPU 时,网页和其他同事的请求仍然响应得动 # 注意:creationflags 仅 Windows 可用,Linux(容器/HF Space)必须不传 extra = {"creationflags": 0x00004000 | 0x08000000} if os.name == "nt" else {} try: t0 = time.time() proc = subprocess.run(cmd, capture_output=True, text=True, timeout=1800, encoding="utf-8", errors="replace", **extra) log_tail = "\n".join((proc.stdout or "").splitlines()[-8:]) if proc.returncode == 0 and os.path.exists(os.path.join(out_dir, "model.blend")): set_status(plan_id, {"state": "done", "msg": "建模完成,耗时 %.0f 秒" % (time.time() - t0), "log": log_tail}) else: set_status(plan_id, {"state": "error", "msg": "Blender 返回码 %s" % proc.returncode, "log": log_tail + "\n" + (proc.stderr or "")[-600:]}) except Exception as e: set_status(plan_id, {"state": "error", "msg": "调用失败: %s" % e}) def worker_loop(): """单线程消费队列:Blender 是 CPU 重活,串行最稳;多人同时提交只会排队""" while True: pid = TASK_Q.get() RUNNING["id"] = pid try: st = get_status(pid) or {} if st.get("state") != "done": run_blender(pid) except Exception as e: set_status(pid, {"state": "error", "msg": str(e)}) finally: RUNNING["id"] = None TASK_Q.task_done() class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" timeout = 30 def log_message(self, *a): pass def _client_ip(self): """HF / Nginx 之类反代后面,socket 里只有反代 IP,真实来源在 X-Forwarded-For""" fwd = (self.headers.get("X-Forwarded-For") or "").split(",")[0].strip() return fwd or (self.client_address[0] if self.client_address else "?") def _send(self, code, body, ctype="application/json; charset=utf-8"): if isinstance(body, str): body = body.encode("utf-8") self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store, max-age=0") self.send_header("Access-Control-Allow-Origin", "*") self.end_headers() self.wfile.write(body) def _file(self, path): if not os.path.isfile(path): return self._send(404, '{"error":"not found"}') ext = os.path.splitext(path)[1].lower() with open(path, "rb") as f: data = f.read() self.send_response(200) self.send_header("Content-Type", MIME.get(ext, "application/octet-stream")) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store, max-age=0") self.send_header("Access-Control-Allow-Origin", "*") if ext == ".blend": self.send_header("Content-Disposition", "attachment; filename=%s_model.blend" % os.path.basename(os.path.dirname(path))) self.end_headers() self.wfile.write(data) def _safe(self, base, rel): base = os.path.realpath(base) p = os.path.realpath(os.path.join(base, rel.replace("/", os.sep))) try: return p if os.path.commonpath([p, base]) == base else None except ValueError: return None def do_OPTIONS(self): self.send_response(204) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Methods", "GET,POST,OPTIONS") self.send_header("Access-Control-Allow-Headers", "Content-Type") self.send_header("Content-Length", "0") self.end_headers() def do_GET(self): try: self._get() except Exception as e: self._send(500, json.dumps({"error": str(e)}, ensure_ascii=False)) def _get(self): if projects.route(self, 'GET'): return url = urlparse(self.path).path if url in ("/", "/index.html"): return self._file(os.path.join(STATIC, "workspace.html")) if url == "/legacy": return self._file(os.path.join(STATIC, "index.html")) if url == "/api/health": nb = 0 idx = os.path.join(PLANS, "index.json") if os.path.exists(idx): try: nb = len(json.load(open(idx, encoding="utf-8"))) except Exception: nb = 0 thumbs = len(os.listdir(THUMBS)) if os.path.isdir(THUMBS) else 0 return self._send(200, json.dumps( {"ok": True, "blender": os.path.exists(BLENDER), "buildings": nb, "plans": thumbs, "media": os.path.isdir(MEDIA), "three": os.path.exists(os.path.join(STATIC, "lib", "three.min.js")), "chat": llm.ready(), "engines": len(llm.ENGINES), "kb": kb.stats()["chunks"], "running": RUNNING["id"], "queued": TASK_Q.qsize()}, ensure_ascii=False)) if url in ("/api/buildings", "/api/plans"): idx = os.path.join(PLANS, "index.json") if not os.path.exists(idx): return self._send(500, '{"error":"plans/index.json 缺失"}') return self._file(idx) if url.startswith("/api/status/"): pid = url.rsplit("/", 1)[-1] return self._send(200, json.dumps(cached_state(pid), ensure_ascii=False)) if url.startswith("/api/model/"): pid = url.rsplit("/", 1)[-1] info = os.path.join(OUTPUT, pid, "model_info.json") if not os.path.exists(info): return self._send(404, '{"error":"no model info"}') return self._file(info) if url.startswith("/api/state"): with STATUS_LOCK: mem = {k: v.get("state") for k, v in STATUS.items()} out = {} for p in os.listdir(OUTPUT): out[p] = "done" if os.path.exists(os.path.join(OUTPUT, p, "model.blend")) else "idle" out.update(mem) return self._send(200, json.dumps(out, ensure_ascii=False)) # ---- 图纸对话 / 知识库 ---- if url == "/api/chat/engines": return self._send(200, json.dumps({ "engines": llm.engines(), "default": llm.DEFAULT_ENGINE, "ready": llm.ready(), "token_source": llm.token_source(), "kb": kb.stats(), }, ensure_ascii=False)) if url == "/api/chat/suggest": q = parse_qs(urlparse(self.path).query) pid = (q.get("id") or [""])[0] return self._send(200, json.dumps( {"id": pid, "questions": kb.suggest(pid)}, ensure_ascii=False)) if url == "/api/kb/search": q = parse_qs(urlparse(self.path).query) query = (q.get("q") or [""])[0] pid = (q.get("building") or [None])[0] or None return self._send(200, json.dumps( {"query": query, "hits": kb.search(query, pid, 6)}, ensure_ascii=False)) if url == "/api/kb/stats": return self._send(200, json.dumps(kb.stats(), ensure_ascii=False)) rel = unquote(url).lstrip("/") # 稳定的 ASCII 别名,避免中文文件名在部分浏览器/代理下取不到 if rel == "media/demo.mp4": return self._file(os.path.join(MEDIA, "ArchRobot_演示_配音版.mp4")) if rel.startswith("media/"): p = self._safe(MEDIA, rel[6:]) return self._file(p) if p else self._send(403, '{"error":"forbidden"}') if rel.startswith("static/"): p = self._safe(STATIC, rel[7:]) return self._file(p) if p else self._send(403, '{"error":"forbidden"}') if rel.startswith("output/"): p = self._safe(OUTPUT, rel[7:]) return self._file(p) if p else self._send(403, '{"error":"forbidden"}') if rel.startswith("thumbs/") or rel.startswith("plans/"): p = self._safe(STATIC, rel) return self._file(p) if p else self._send(403, '{"error":"forbidden"}') self._send(404, '{"error":"not found"}') def do_POST(self): try: self._post() except Exception as e: self._send(500, json.dumps({"error": str(e)}, ensure_ascii=False)) def _post(self): if projects.route(self, 'POST'): return url = urlparse(self.path).path try: ln = int(self.headers.get("Content-Length", 0) or 0) req = json.loads(self.rfile.read(ln) or b"{}") except Exception: return self._send(400, '{"error":"bad request"}') if url == "/api/generate": pid = str(req.get("id", "")) if not pid or not os.path.exists(os.path.join(PLANS, pid + ".json")): return self._send(400, '{"error":"bad id"}') if os.path.exists(os.path.join(OUTPUT, pid, "model.blend")): set_status(pid, {"state": "done", "msg": "已建模(复用本地产物)", "cached": True}) return self._send(200, json.dumps({"state": "done", "cached": True}, ensure_ascii=False)) cur = get_status(pid) if cur and cur.get("state") in ("queued", "running"): return self._send(200, json.dumps(cur, ensure_ascii=False)) set_status(pid, {"state": "queued", "msg": "已入队,等待 Blender 空闲..."}) TASK_Q.put(pid) return self._send(200, json.dumps({"state": "queued", "queued": TASK_Q.qsize()}, ensure_ascii=False)) if url == "/api/open": pid = str(req.get("id", "")) blend = os.path.join(OUTPUT, pid, "model.blend") if not os.path.exists(blend): return self._send(404, '{"error":"model not found"}') subprocess.Popen([BLENDER, blend], cwd=os.path.dirname(blend)) return self._send(200, '{"state":"launching"}') # 对话改参数:大模型只出参数补丁,几何仍由 bpy 确定性执行,改出来是一版新模型 if url == "/api/chat/build": question = (req.get("question") or "").strip() pid = (req.get("building") or "").strip() if not question or not pid: return self._send(400, '{"error":"缺少问题或楼栋号"}') if not os.path.exists(os.path.join(PLANS, pid + ".json")): return self._send(400, '{"error":"图纸不存在"}') if not llm.ready(): return self._send(200, json.dumps( {"ok": False, "error": "服务端未找到百炼 API Key", "hint": "设置环境变量 BAILIAN_API_KEY 后可用"}, ensure_ascii=False)) ok, why, _wait = CHAT_GATE.take(self._client_ip()) if not ok: return self._send(429, json.dumps({"ok": False, "error": why}, ensure_ascii=False)) try: with open(os.path.join(PLANS, pid + ".json"), encoding="utf-8") as f: plan = json.load(f) got = patch.parse(question, plan, engine=req.get("engine")) except Exception as e: return self._send(200, json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False)) finally: CHAT_GATE.done() if got["intent"] != "modify" or not got["patch"]: # 这句话不是改参(比如「洞口开在几个面上」)。以前这里直接报错, # 客户勾着「改参数并重建」问属性就会被顶回来——所以改成自动回落问答, # 顺手告诉他一嘴怎么改参。宁可多答一句,不能让客户以为系统不认问题。 try: answer, meta = chat.ask(question, engine=req.get("engine"), building=pid) except Exception as e: return self._send(200, json.dumps( {"ok": False, "error": str(e)}, ensure_ascii=False)) return self._send(200, json.dumps( dict(ok=True, intent="qa", fallback=True, answer=answer, patch={}, notes=[got.get("explain") or ""], hint="这句不是改参,已按问答回答;要改参数可以说「层高改成 3.6 米」", **meta), ensure_ascii=False)) try: new_id, _new_plan, diffs = patch.prepare(pid, got["patch"]) except Exception as e: return self._send(200, json.dumps({"ok": False, "error": str(e)}, ensure_ascii=False)) # 同一版号重跑前先清空旧产物,避免界面读到上一版 out_dir = os.path.join(OUTPUT, new_id) if os.path.isdir(out_dir): for n in os.listdir(out_dir): if n.startswith("model.") or n.startswith("render"): os.remove(os.path.join(out_dir, n)) set_status(new_id, {"state": "queued", "msg": "按对话改参,已入队..."}) TASK_Q.put(new_id) return self._send(200, json.dumps( {"ok": True, "task": new_id, "source": pid, "patch": got["patch"], "diff": diffs, "answer": got["explain"], "notes": got["notes"], "meta": {k: v for k, v in (got.get("meta") or {}).items() if k in ("engine", "label", "latency_ms", "total_tokens")}}, ensure_ascii=False)) if url == "/api/chat": question = (req.get("question") or "").strip() if not question: return self._send(400, '{"error":"问题为空"}') if not llm.ready(): # 没接模型时不要拿「检索片段」冒充答案:先前那条路会让客户问「洞口在几个面上」, # 屏幕上却弹出两条无关的 FAQ 原文。这里改成规则直答——先正面回答,再说明降级状态。 qa = quickqa.answer(question, req.get("building")) if qa: return self._send(200, json.dumps( {"ok": True, "answer": qa, "degraded": True, "engine": "rule-qa", "label": "图纸直答(未接模型)", "citations": [], "note": "当前部署未配置大模型 Key,这条答案是按图纸参数表逐字取数得出的,不是模型生成。"}, ensure_ascii=False)) return self._send(200, json.dumps( {"ok": False, "degraded": True, "error": "当前部署未接入大模型,这个问题超出了直答规则能覆盖的范围", "hint": "已接入的直答范围:层数/层高/总高、墙厚、轮廓与面积、房间分隔、" "门窗与内墙门洞、屋面坡度出檐山墙、构件总数与材质、图纸视角与约束点、改参口径、导出格式。" "其余问题需要配置百炼 Key 后才能回答。"}, ensure_ascii=False)) # 公网部署时这道闸必须有:key 在服务端,被刷就是真金白银 ok, why, wait = CHAT_GATE.take(self._client_ip()) if not ok: return self._send(429, json.dumps( {"ok": False, "error": why, "hint": "稍后再试;本演示对每个 IP 限流"}, ensure_ascii=False)) try: answer, meta = chat.ask(question, engine=req.get("engine"), building=req.get("building") or None, history=req.get("history") or []) return self._send(200, json.dumps(dict(ok=True, answer=answer, **meta), ensure_ascii=False)) except Exception as e: # 模型侧抖动(限流/超时/配额)时,先用参数表直答保住这次提问,再把原因说清楚 qa = quickqa.answer(question, req.get("building")) if qa: return self._send(200, json.dumps( {"ok": True, "answer": qa, "degraded": True, "engine": "rule-qa", "label": "图纸直答(模型暂时不可用)", "citations": [], "note": "大模型这次没调通(%s),这条是按图纸参数表取数直答的。" % str(e)[:120]}, ensure_ascii=False)) return self._send(200, json.dumps( {"ok": False, "error": str(e)}, ensure_ascii=False)) finally: CHAT_GATE.done() self._send(404, '{"error":"not found"}') def lan_ips(): ips = [] try: for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET): ip = info[4][0] if ip not in ips and not ip.startswith("127."): ips.append(ip) except Exception: pass return ips def main(): try: srv = ThreadingHTTPServer((HOST, PORT), Handler) except OSError: print("端口 %d 已被占用:服务可能已在运行。" % PORT) print("直接访问 http://127.0.0.1:%d/ 即可,无需重复启动。" % PORT) return projects.initialize() srv.daemon_threads = True srv.request_queue_size = 128 threading.Thread(target=worker_loop, daemon=True).start() print("=" * 62) print(" ArchRobot 本地服务已启动(多用户并发)") print(" 本机 http://127.0.0.1:%d/" % PORT) if HOST not in ('127.0.0.1','localhost','::1'): for ip in lan_ips(): print(" 同事 http://%s:%d/" % (ip, PORT)) print(" 健康 http://127.0.0.1:%d/api/health" % PORT) print(" 提示:不要直接双击 index.html(file:// 无法调用接口)") if not os.path.isfile(BLENDER): print("-" * 62) print(" [!] 未找到 Blender,图纸可浏览但无法建模") print(" 期望位置:本仓库根目录 %s\\blender.exe" % BLENDER_DIR_NAME) print(" 或设置环境变量 BLENDER_EXE 指向 blender.exe") print(" Windows 一键准备:powershell -ExecutionPolicy Bypass -File setup_blender.ps1") print("=" * 62) try: if not os.environ.get("ARCHROBOT_NO_BROWSER"): webbrowser.open("http://127.0.0.1:%d/" % PORT) except Exception: pass srv.serve_forever() if __name__ == "__main__": main()