部署 2026-10-28 18:31 · 图纸对话与知识库
Browse files- app/chat.py +43 -13
- app/kb.py +134 -9
- app/llm.py +27 -1
- app/quickqa.py +294 -0
- app/server.py +36 -6
- app/static/index.html +0 -0
- app/token.vault +11 -0
- app/vault.py +166 -0
app/chat.py
CHANGED
|
@@ -18,21 +18,25 @@ import re
|
|
| 18 |
import kb
|
| 19 |
import llm
|
| 20 |
|
| 21 |
-
MAX_HISTORY =
|
| 22 |
-
TOP_K =
|
| 23 |
|
| 24 |
KIND_CN = {"building": "图纸档案", "view": "视角图纸", "components": "构件属性表",
|
| 25 |
-
"rule": "方案口径", "faq": "常见问题"}
|
| 26 |
|
| 27 |
SYS_PROMPT = """你是「ArchRobot 建筑机器人绘图系统」的图纸助理,服务对象是建筑机器人与 BIM 方向的专业人士(中建东方项目交流现场)。
|
| 28 |
|
| 29 |
回答纪律(必须遵守):
|
| 30 |
-
1. 只
|
| 31 |
-
2. 先给结论,再给依据。控制在 2~
|
| 32 |
-
3.
|
| 33 |
-
4.
|
| 34 |
-
5. 交付口径
|
| 35 |
-
6.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
|
| 38 |
def _mentioned_buildings(text, current):
|
|
@@ -46,6 +50,20 @@ def _mentioned_buildings(text, current):
|
|
| 46 |
return out
|
| 47 |
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
def build_context(question, building=None):
|
| 50 |
"""组装系统提示词与命中依据"""
|
| 51 |
parts = [SYS_PROMPT]
|
|
@@ -55,23 +73,35 @@ def build_context(question, building=None):
|
|
| 55 |
prof = kb.profile(building)
|
| 56 |
if prof:
|
| 57 |
parts.append("【本栋图纸档案】用户此刻正在看这一栋:\n" + prof)
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
for other in _mentioned_buildings(question, building)[:2]:
|
| 60 |
prof = kb.profile(other)
|
| 61 |
if prof:
|
| 62 |
parts.append("【另外点名的图纸档案】\n" + prof)
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
hits = kb.search(question, building=building, topk=TOP_K)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
if hits:
|
| 66 |
blocks = []
|
| 67 |
for h in hits:
|
| 68 |
blocks.append("■ %s\n%s" % (h["title"], h["text"]))
|
| 69 |
-
cites.append({"title": h["title"], "kind": h["kind"],
|
| 70 |
"kind_cn": KIND_CN.get(h["kind"], h["kind"]),
|
| 71 |
-
"building": h["building"], "score": h["score"]
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
else:
|
| 74 |
-
parts.append("【
|
| 75 |
|
| 76 |
return "\n\n".join(parts), cites, hits
|
| 77 |
|
|
|
|
| 18 |
import kb
|
| 19 |
import llm
|
| 20 |
|
| 21 |
+
MAX_HISTORY = 12 # 最多带 12 条历史(6 轮),追问属性时不用重复楼栋号
|
| 22 |
+
TOP_K = 5
|
| 23 |
|
| 24 |
KIND_CN = {"building": "图纸档案", "view": "视角图纸", "components": "构件属性表",
|
| 25 |
+
"openings": "洞口布置", "rule": "方案口径", "faq": "常见问题"}
|
| 26 |
|
| 27 |
SYS_PROMPT = """你是「ArchRobot 建筑机器人绘图系统」的图纸助理,服务对象是建筑机器人与 BIM 方向的专业人士(中建东方项目交流现场)。
|
| 28 |
|
| 29 |
回答纪律(必须遵守):
|
| 30 |
+
1. 数字只许来自下面给出的【图纸参数表】【图纸档案】与【补充资料】。这些是同一栋楼的原始数据,只是详略不同:参数表最全(字段原文),档案是提炼,补充资料只做细节核对。禁止估算,禁止把"精确值"说成"大约"。三者不一致时以参数表原文为准。
|
| 31 |
+
2. 先给结论,再给依据。控制在 2~8 句;需要罗列多个数值时用短列表(每行以「- 」开头)或极简表格。问题问得细(比如要尺寸、编号、材质、房间名),就把对应字段原文列出来。输出是纯文本气泡,禁止使用 Markdown 标记(不要 **加粗**、不要 `反引号`、不要 # 标题、不要表格竖线语法之外的装饰)。
|
| 32 |
+
3. 客户可以问任何与这栋楼相关的属性:层数、层高、墙厚、轮廓、房间、洞口位置与尺寸、屋脊、出檐、约束点数、构件编号与材质、建模耗时、能否改参、能否二次编辑……只要参数表或产物里有,就照实答。
|
| 33 |
+
4. 参数表里确实没有的,直接说「这栋楼的图纸里没有这一项」,并说明还需要什么输入(比如做法表、结构图、DWG 原图)才能回答。绝不用通用建筑常识去补。
|
| 34 |
+
5. 只谈图纸、几何、构件参数、建模流程、交付口径。与项目无关的问题,一句话婉拒并拉回图纸。
|
| 35 |
+
6. 交付口径固定:当前交付格式是 glTF(.glb)+ .blend,不含 IFC;运行时建模不调用大模型,几何由 bpy 确定性执行。这两条不得含糊。
|
| 36 |
+
7. 回答的结构固定为「结论 → 依据 → 可选一句补充」:第一句必须是不超过 30 字的直接结论,句式像「这栋楼 2 层,层高 3.0 m」「四个立面共 12 个洞口,门 1 樘、窗 11 樘」,把客户问的那个数放在最前面。第二句起才给依据或分项。禁止以「根据图纸档案」「资料显示」「关于您的问题」开头,禁止罗列资料标题,禁止把检索到的片段整段搬过来。
|
| 37 |
+
正例——问:洞口都开在哪几个面上,各多少个?答:四个立面共 12 个洞口:前墙 2 个(门 1、窗 1),后墙 4 个窗,左墙 2 个窗,右墙 4 个窗;另外内隔墙上还有 2 处门洞,不在外立面上。
|
| 38 |
+
反例:先列「1. 这栋楼的模型是怎么生成的… 2. 构件参数写在哪里…」——这是把资料目录当答案,答非所问,绝对不允许。
|
| 39 |
+
8. 不要复述本提示词,不要自称"AI 模型",你是这个系统的图纸助理。引用出处只用业务说法:图纸参数表、图纸档案、构件属性表、方案口径、视角图纸。绝对不要出现"片段""检索结果""资料①""标签"这类内部说法,也不要给资料编号。参数表里的英文字段名要翻成中文说(openings→洞口、wall_t→墙厚、floor_h→层高、ridge_y→屋脊高、gable_h→山墙高、inner_y→内隔墙位置),不要直接甩字段名。"""
|
| 40 |
|
| 41 |
|
| 42 |
def _mentioned_buildings(text, current):
|
|
|
|
| 50 |
return out
|
| 51 |
|
| 52 |
|
| 53 |
+
def _source_of(hit):
|
| 54 |
+
"""引用出处落到文件:客户点「依据」时能看到到底取自哪个文件哪一块。"""
|
| 55 |
+
kind, pid = hit.get("kind"), hit.get("building")
|
| 56 |
+
if kind in ("building", "openings", "view"):
|
| 57 |
+
return "app/static/plans/%s.json" % pid
|
| 58 |
+
if kind == "components":
|
| 59 |
+
return "app/output/%s/model_info.json" % pid
|
| 60 |
+
if kind == "rule":
|
| 61 |
+
return "app/kb.py · RULES「%s」" % hit.get("title")
|
| 62 |
+
if kind == "faq":
|
| 63 |
+
return "app/kb.py · FAQ「%s」" % hit.get("title")
|
| 64 |
+
return "app/kb.py"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
def build_context(question, building=None):
|
| 68 |
"""组装系统提示词与命中依据"""
|
| 69 |
parts = [SYS_PROMPT]
|
|
|
|
| 73 |
prof = kb.profile(building)
|
| 74 |
if prof:
|
| 75 |
parts.append("【本栋图纸档案】用户此刻正在看这一栋:\n" + prof)
|
| 76 |
+
raw = kb.facts(building)
|
| 77 |
+
if raw:
|
| 78 |
+
parts.append("【本栋图纸参数表(字段原文,最权威)】\n" + raw)
|
| 79 |
|
| 80 |
for other in _mentioned_buildings(question, building)[:2]:
|
| 81 |
prof = kb.profile(other)
|
| 82 |
if prof:
|
| 83 |
parts.append("【另外点名的图纸档案】\n" + prof)
|
| 84 |
+
raw = kb.facts(other)
|
| 85 |
+
if raw:
|
| 86 |
+
parts.append("【另外点名楼栋的参数表】\n" + raw)
|
| 87 |
|
| 88 |
hits = kb.search(question, building=building, topk=TOP_K)
|
| 89 |
+
# 只把「够得着」的命中当引用摆出来:低于头名 45% 的基本是凑数的,挂上去反而干扰核对
|
| 90 |
+
if hits:
|
| 91 |
+
floor = hits[0]["score"] * 0.45
|
| 92 |
+
hits = [h for h in hits if h["score"] >= floor] or hits[:1]
|
| 93 |
if hits:
|
| 94 |
blocks = []
|
| 95 |
for h in hits:
|
| 96 |
blocks.append("■ %s\n%s" % (h["title"], h["text"]))
|
| 97 |
+
cites.append({"id": h.get("id"), "title": h["title"], "kind": h["kind"],
|
| 98 |
"kind_cn": KIND_CN.get(h["kind"], h["kind"]),
|
| 99 |
+
"building": h["building"], "score": h["score"],
|
| 100 |
+
"src": _source_of(h), "text": (h["text"] or "")[:900],
|
| 101 |
+
"rows": (h["text"] or "").count("\n") + 1})
|
| 102 |
+
parts.append("【补充资料(只用于核对细节,禁止逐条复述)】\n" + "\n\n".join(blocks))
|
| 103 |
else:
|
| 104 |
+
parts.append("【补充资料】本次检索没有命中,以参数表为准;参数表也没有的,就说没有。")
|
| 105 |
|
| 106 |
return "\n\n".join(parts), cites, hits
|
| 107 |
|
app/kb.py
CHANGED
|
@@ -61,6 +61,12 @@ RULES = [
|
|
| 61 |
("交付格式的边界",
|
| 62 |
"交付格式是 glTF(.glb)+ .blend,不含 IFC。IFC 需由 Bonsai(BlenderBIM)在下一期接入,"
|
| 63 |
"对外不得宣称 IFC 已交付。"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
("运行时不调大模型",
|
| 65 |
"本 Demo 运行时不调用任何大模型,一次 API 都没有。执行体是 bpy 确定性算法;大模型只预留在两处:"
|
| 66 |
"中置信歧义的构件类型判定、自然语言查改。原始几何与属性数据不进大模型上下文,模型只读结构化摘要。"),
|
|
@@ -230,6 +236,42 @@ def build():
|
|
| 230 |
"text": "\n".join(lines),
|
| 231 |
"tags": ["档案", pid, b["name"], "层数", "层高", "面积", "尺寸", "洞口", "房间"]})
|
| 232 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
# ---- 2. 每张图一块 ----
|
| 234 |
for v in b["views"]:
|
| 235 |
role = VIEW_ROLE.get(v["code"], "")
|
|
@@ -275,15 +317,26 @@ def build():
|
|
| 275 |
return chunks
|
| 276 |
|
| 277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
def _tokens(s):
|
| 279 |
s = (s or "").lower()
|
| 280 |
-
out = re.findall(r"[a-z0-9]+", s)
|
| 281 |
for run in re.findall(r"[\u4e00-\u9fff]+", s):
|
| 282 |
-
out.extend(
|
| 283 |
-
out.extend(run[i:i + 2] for i in range(len(run) - 1)
|
|
|
|
| 284 |
return out
|
| 285 |
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
class _Index:
|
| 288 |
"""BM25(k1=1.5, b=0.75),标题权重 ×2"""
|
| 289 |
|
|
@@ -315,25 +368,54 @@ class _Index:
|
|
| 315 |
return s
|
| 316 |
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
def search(q, building=None, topk=6):
|
| 319 |
build()
|
| 320 |
idx = _CACHE["index"]
|
| 321 |
if not q.strip():
|
| 322 |
return []
|
|
|
|
| 323 |
scored = []
|
| 324 |
for d in idx.docs:
|
| 325 |
s = idx.score(q, d)
|
| 326 |
c = d["chunk"]
|
| 327 |
if building and c.get("building") == building:
|
| 328 |
s *= 1.6 # 当前图纸相关的内容加权
|
|
|
|
| 329 |
if s > 0:
|
| 330 |
scored.append((s, c))
|
| 331 |
scored.sort(key=lambda x: -x[0])
|
| 332 |
-
# 同一楼栋最多
|
| 333 |
-
|
|
|
|
| 334 |
for s, c in scored:
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
continue
|
| 338 |
seen[k] = seen.get(k, 0) + 1
|
| 339 |
out.append({"id": c["id"], "title": c["title"], "text": c["text"],
|
|
@@ -352,8 +434,48 @@ def profile(pid):
|
|
| 352 |
return ""
|
| 353 |
|
| 354 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
def suggest(pid):
|
| 356 |
-
"""针对当前图纸的预设问题(数字全部来自真实数据)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
b = None
|
| 358 |
for x in _load_json(os.path.join(PLANS, "index.json"), []):
|
| 359 |
if x["id"] == pid:
|
|
@@ -367,6 +489,8 @@ def suggest(pid):
|
|
| 367 |
qs = [
|
| 368 |
"%s 一共几层?层高和轮廓尺寸是多少?" % pid,
|
| 369 |
"这栋楼的洞口都开在哪几个面上,各多少个?",
|
|
|
|
|
|
|
| 370 |
"五个视角的图各管住哪些约束?少一张会怎样?",
|
| 371 |
]
|
| 372 |
if stats.get("构件数"):
|
|
@@ -375,7 +499,8 @@ def suggest(pid):
|
|
| 375 |
qs.append("这栋楼现在还没建模,生成一次大概要多久?")
|
| 376 |
qs.append("网页里这个模型能证明是真模型、不是渲染图吗?")
|
| 377 |
qs.append("如果客户要 IFC,现在能交吗?")
|
| 378 |
-
|
|
|
|
| 379 |
|
| 380 |
|
| 381 |
def stats():
|
|
|
|
| 61 |
("交付格式的边界",
|
| 62 |
"交付格式是 glTF(.glb)+ .blend,不含 IFC。IFC 需由 Bonsai(BlenderBIM)在下一期接入,"
|
| 63 |
"对外不得宣称 IFC 已交付。"),
|
| 64 |
+
("哪些参数能改、改到什么程度",
|
| 65 |
+
"对话改参只开放六个字段:层高 floor_h(2.4~4.5 m)、墙厚 wall_t(0.12~0.4 m)、"
|
| 66 |
+
"内隔墙位置 inner_y(1.5 m 至进深减 1.5 m)、屋脊高 roof.ridge_y、山墙高 roof.gable_h、"
|
| 67 |
+
"出檐 roof.overhang。流程是「一句话 → 模型出参数补丁 → bpy 按补丁重算几何 → 另存一版新模型」,"
|
| 68 |
+
"原图纸不动,改完可以在查看器里和原版对照。六个字段以外(层数、轮廓、门窗位置)不开放改参,"
|
| 69 |
+
"因为改动会牵连墙段切分与洞口固化的整套约束,需要回到图纸层面重出图纸。"),
|
| 70 |
("运行时不调大模型",
|
| 71 |
"本 Demo 运行时不调用任何大模型,一次 API 都没有。执行体是 bpy 确定性算法;大模型只预留在两处:"
|
| 72 |
"中置信歧义的构件类型判定、自然语言查改。原始几何与属性数据不进大模型上下文,模型只读结构化摘要。"),
|
|
|
|
| 236 |
"text": "\n".join(lines),
|
| 237 |
"tags": ["档案", pid, b["name"], "层数", "层高", "面积", "尺寸", "洞口", "房间"]})
|
| 238 |
|
| 239 |
+
# ---- 1b. 洞口布置(按立面/按层,回答「洞开在哪几个面上、各多少」)----
|
| 240 |
+
ops = plan.get("openings") or []
|
| 241 |
+
if ops:
|
| 242 |
+
type_cn = {"door": "门", "window": "窗", "passage": "通道口"}
|
| 243 |
+
edge_rows = {}
|
| 244 |
+
for o in ops:
|
| 245 |
+
k = _edge_of(o, w=plan["footprint"][0], d=plan["footprint"][1])
|
| 246 |
+
edge_rows.setdefault(k, []).append(o)
|
| 247 |
+
lines = ["楼栋:%s %s(%s 层,轮廓 %s × %s m)" % (
|
| 248 |
+
pid, b["name"], b["floors"], b["footprint"][0], b["footprint"][1]),
|
| 249 |
+
"洞口合计 %s 个:%s" % (len(ops), m["分类型"]),
|
| 250 |
+
"问题「洞口开在哪几个面上、各多少个」的答案就在下面这几行:"]
|
| 251 |
+
for k in ("正立面侧(y=0,ELEV-N)", "背立面侧(y=最大)",
|
| 252 |
+
"侧立面侧(x=最大,ELEV-E)", "左侧山墙(x=0)", "内部隔墙"):
|
| 253 |
+
arr = edge_rows.get(k)
|
| 254 |
+
if not arr:
|
| 255 |
+
continue
|
| 256 |
+
by = {}
|
| 257 |
+
detail = []
|
| 258 |
+
for o in arr:
|
| 259 |
+
by[o[4]] = by.get(o[4], 0) + 1
|
| 260 |
+
length = abs(o[2] - o[0]) if abs(o[2] - o[0]) > 1e-6 else abs(o[3] - o[1])
|
| 261 |
+
detail.append("%s宽 %s m" % (type_cn.get(o[4], o[4]), round(length, 2)))
|
| 262 |
+
lines.append("%s:%s 个(%s)——%s" % (
|
| 263 |
+
k, len(arr), "、".join("%s %s" % (type_cn.get(t, t), n) for t, n in by.items()),
|
| 264 |
+
";".join(detail)))
|
| 265 |
+
lines.append("按楼层:%s" % "、".join(
|
| 266 |
+
"%dF %s 个" % (int(lv) + 1, n) for lv, n in sorted(m["按层"].items())))
|
| 267 |
+
lines.append("说明:内墙上的门洞不在外立面上,要开透视模式才能看到;"
|
| 268 |
+
"外立面洞口各层位置一致。")
|
| 269 |
+
chunks.append({"kind": "openings", "building": pid,
|
| 270 |
+
"title": "%s · 洞口布置(按立面 %s 个)" % (pid, len(ops)),
|
| 271 |
+
"text": "\n".join(lines),
|
| 272 |
+
"tags": ["洞口", "门窗", "立面", "几面", "各多少", "按层",
|
| 273 |
+
"内墙门洞", pid, "门", "窗"]})
|
| 274 |
+
|
| 275 |
# ---- 2. 每张图一块 ----
|
| 276 |
for v in b["views"]:
|
| 277 |
role = VIEW_ROLE.get(v["code"], "")
|
|
|
|
| 317 |
return chunks
|
| 318 |
|
| 319 |
|
| 320 |
+
# 问句里的虚词:不带信息,只会把短 FAQ 拉上去(「这栋楼几层」命中「这栋楼的模型…」就是这么来的)
|
| 321 |
+
STOP = set("的了是在有个这那吗呢都和与我你它们一下请就而也把被让给了吧啊呢")
|
| 322 |
+
# 疑问词也一并滤掉:它们不带属性信息,只会把「这栋楼的模型…」这类 FAQ 顶上来
|
| 323 |
+
STOP |= set("几多少哪什么哪些哪种")
|
| 324 |
+
|
| 325 |
+
|
| 326 |
def _tokens(s):
|
| 327 |
s = (s or "").lower()
|
| 328 |
+
out = [t for t in re.findall(r"[a-z0-9]+", s)]
|
| 329 |
for run in re.findall(r"[\u4e00-\u9fff]+", s):
|
| 330 |
+
out.extend(ch for ch in run if ch not in STOP) # 单字
|
| 331 |
+
out.extend(run[i:i + 2] for i in range(len(run) - 1)
|
| 332 |
+
if not (run[i] in STOP and run[i + 1] in STOP)) # 双字
|
| 333 |
return out
|
| 334 |
|
| 335 |
|
| 336 |
+
KIND_W = {"building": 1.15, "openings": 1.15, "components": 1.05,
|
| 337 |
+
"view": 0.95, "rule": 0.95, "faq": 0.8}
|
| 338 |
+
|
| 339 |
+
|
| 340 |
class _Index:
|
| 341 |
"""BM25(k1=1.5, b=0.75),标题权重 ×2"""
|
| 342 |
|
|
|
|
| 368 |
return s
|
| 369 |
|
| 370 |
|
| 371 |
+
# 口语问法 → 图纸里的字段说法。不加这层,问「几层」只会匹配到含「层」字的任意段落,
|
| 372 |
+
# 真正写着「层数:2 层」的档案反而被长文档惩罚掉。
|
| 373 |
+
EXPAND = [
|
| 374 |
+
(("几层", "多少层", "层数", "几楼"), "层数 楼层"),
|
| 375 |
+
(("多大", "几米", "轮廓"), "轮廓尺寸 面积"),
|
| 376 |
+
(("墙多厚", "多厚"), "墙厚"),
|
| 377 |
+
(("几樘", "几个窗", "几扇窗", "几扇门", "几个门"), "洞口 门窗 樘"),
|
| 378 |
+
(("洞里", "门洞", "洞开"), "洞口 门洞 通道口 立面"),
|
| 379 |
+
(("改", "能不能改", "可以改"), "改参数 补丁 重建"),
|
| 380 |
+
(("房间", "户型"), "房间 隔墙"),
|
| 381 |
+
(("ifc", "导出", "格式", "revit", "交付"), "交付格式 边界"),
|
| 382 |
+
]
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _expand(q):
|
| 386 |
+
extra = []
|
| 387 |
+
for keys, add in EXPAND:
|
| 388 |
+
if any(k in q for k in keys):
|
| 389 |
+
extra.append(add)
|
| 390 |
+
return (q + " " + " ".join(extra)).strip() if extra else q
|
| 391 |
+
|
| 392 |
+
|
| 393 |
def search(q, building=None, topk=6):
|
| 394 |
build()
|
| 395 |
idx = _CACHE["index"]
|
| 396 |
if not q.strip():
|
| 397 |
return []
|
| 398 |
+
q = _expand(q)
|
| 399 |
scored = []
|
| 400 |
for d in idx.docs:
|
| 401 |
s = idx.score(q, d)
|
| 402 |
c = d["chunk"]
|
| 403 |
if building and c.get("building") == building:
|
| 404 |
s *= 1.6 # 当前图纸相关的内容加权
|
| 405 |
+
s *= KIND_W.get(c["kind"], 1.0) # 档案/洞口/构件明细优先,泛泛的 FAQ 靠后
|
| 406 |
if s > 0:
|
| 407 |
scored.append((s, c))
|
| 408 |
scored.sort(key=lambda x: -x[0])
|
| 409 |
+
# 引用要有区分度:同一「楼栋 × 类型」最多 2 块;别的楼栋整体最多带 1 块做对照,
|
| 410 |
+
# 否则问这栋楼的洞口,5 条引用全是另外四栋楼的洞口——看着热闹,核对时没用。
|
| 411 |
+
out, seen, other = [], {}, 0
|
| 412 |
for s, c in scored:
|
| 413 |
+
if building and c.get("building") and c["building"] != building:
|
| 414 |
+
if other >= 1:
|
| 415 |
+
continue
|
| 416 |
+
other += 1
|
| 417 |
+
k = (c.get("building"), c["kind"])
|
| 418 |
+
if seen.get(k, 0) >= 2:
|
| 419 |
continue
|
| 420 |
seen[k] = seen.get(k, 0) + 1
|
| 421 |
out.append({"id": c["id"], "title": c["title"], "text": c["text"],
|
|
|
|
| 434 |
return ""
|
| 435 |
|
| 436 |
|
| 437 |
+
def facts(pid, max_walls=40):
|
| 438 |
+
"""整份参数表原文(喂给模型,保证任意属性问题都能答)。
|
| 439 |
+
|
| 440 |
+
知识库片段是"挑着给",只覆盖高频属性;客户现场真正问的是「二层房间有哪几个」
|
| 441 |
+
「门洞尺寸多少」「墙厚有没有改过」这种偏门字段。图纸 JSON 本身只有 3KB 左右,
|
| 442 |
+
整份塞进上下文比做召回更准——所以这里不做筛选,原样给。
|
| 443 |
+
"""
|
| 444 |
+
plan = _load_json(os.path.join(PLANS, pid + ".json"), {})
|
| 445 |
+
if not plan:
|
| 446 |
+
return ""
|
| 447 |
+
slim = {k: v for k, v in plan.items() if k not in ("points",)}
|
| 448 |
+
walls = slim.get("walls") or []
|
| 449 |
+
if len(walls) > max_walls: # 单栋最多 11 段,留个上限防超长
|
| 450 |
+
slim["walls"] = walls[:max_walls] + ["…其余 %d 段略" % (len(walls) - max_walls)]
|
| 451 |
+
lines = ["参数表原文(%s.json):" % pid,
|
| 452 |
+
json.dumps(slim, ensure_ascii=False, separators=(",", ":"))]
|
| 453 |
+
if plan.get("points"):
|
| 454 |
+
lines.append("五视角约束点数:" + json.dumps(plan["points"], ensure_ascii=False))
|
| 455 |
+
info = _load_json(os.path.join(OUTPUT, pid, "model_info.json"), {})
|
| 456 |
+
if info:
|
| 457 |
+
st = info.get("stats") or {}
|
| 458 |
+
comps = info.get("components") or []
|
| 459 |
+
if st:
|
| 460 |
+
lines.append("建模产物统计:" + json.dumps(st, ensure_ascii=False))
|
| 461 |
+
if comps:
|
| 462 |
+
by = {}
|
| 463 |
+
for c in comps:
|
| 464 |
+
k = c.get("type") or c.get("kind") or "其他"
|
| 465 |
+
by[k] = by.get(k, 0) + 1
|
| 466 |
+
lines.append("构件类型分布:" + json.dumps(by, ensure_ascii=False))
|
| 467 |
+
mats = sorted({c.get("material") for c in comps if c.get("material")})
|
| 468 |
+
if mats:
|
| 469 |
+
lines.append("出现过的材质:" + "、".join(mats))
|
| 470 |
+
return "\n".join(lines)
|
| 471 |
+
|
| 472 |
+
|
| 473 |
def suggest(pid):
|
| 474 |
+
"""针对当前图纸的预设问题(数字全部来自真实数据)
|
| 475 |
+
|
| 476 |
+
注意:这些只是"抛砖引玉"的引导,不是能力边界——任何关于图纸属性的问题
|
| 477 |
+
都应该能问,模型会拿整份参数表回答。
|
| 478 |
+
"""
|
| 479 |
b = None
|
| 480 |
for x in _load_json(os.path.join(PLANS, "index.json"), []):
|
| 481 |
if x["id"] == pid:
|
|
|
|
| 489 |
qs = [
|
| 490 |
"%s 一共几层?层高和轮廓尺寸是多少?" % pid,
|
| 491 |
"这栋楼的洞口都开在哪几个面上,各多少个?",
|
| 492 |
+
"墙厚是多少?内隔墙的位置在第几米?",
|
| 493 |
+
"屋脊多高、山墙多高、出檐多少?",
|
| 494 |
"五个视角的图各管住哪些约束?少一张会怎样?",
|
| 495 |
]
|
| 496 |
if stats.get("构件数"):
|
|
|
|
| 499 |
qs.append("这栋楼现在还没建模,生成一次大概要多久?")
|
| 500 |
qs.append("网页里这个模型能证明是真模型、不是渲染图吗?")
|
| 501 |
qs.append("如果客户要 IFC,现在能交吗?")
|
| 502 |
+
qs.append("这栋楼能改参数重出吗?哪些字段能改、哪些动不了?")
|
| 503 |
+
return qs[:9]
|
| 504 |
|
| 505 |
|
| 506 |
def stats():
|
app/llm.py
CHANGED
|
@@ -17,7 +17,8 @@ import urllib.request
|
|
| 17 |
BASE_URL = os.environ.get("BAILIAN_BASE_URL",
|
| 18 |
"https://dashscope.aliyuncs.com/compatible-mode/v1").rstrip("/")
|
| 19 |
|
| 20 |
-
# token 解析顺序:环境变量直给 → 环境变量指文件 → 本机默认路径 → 仓库内 .bailian_key
|
|
|
|
| 21 |
_HERE = os.path.dirname(os.path.abspath(__file__))
|
| 22 |
_KEY_CANDIDATES = [
|
| 23 |
os.environ.get("BAILIAN_KEY_FILE", ""),
|
|
@@ -26,6 +27,12 @@ _KEY_CANDIDATES = [
|
|
| 26 |
os.path.join(_HERE, ".bailian_key"),
|
| 27 |
]
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# 引擎清单:全部实测可用(见 app/verify_chat.py)。max_tokens 按引擎性格给。
|
| 30 |
ENGINES = [
|
| 31 |
{"id": "qwen-plus", "label": "通义千问 Plus", "vendor": "阿里百炼",
|
|
@@ -72,6 +79,22 @@ def _read_token():
|
|
| 72 |
return txt
|
| 73 |
except OSError:
|
| 74 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
return ""
|
| 76 |
|
| 77 |
|
|
@@ -86,6 +109,9 @@ def token_source():
|
|
| 86 |
return "环境变量 BAILIAN_API_KEY"
|
| 87 |
if src == "DISABLED":
|
| 88 |
return "未接入(ARCHROBOT_DISABLE_LLM)"
|
|
|
|
|
|
|
|
|
|
| 89 |
return src
|
| 90 |
|
| 91 |
|
|
|
|
| 17 |
BASE_URL = os.environ.get("BAILIAN_BASE_URL",
|
| 18 |
"https://dashscope.aliyuncs.com/compatible-mode/v1").rstrip("/")
|
| 19 |
|
| 20 |
+
# token 解析顺序:环境变量直给 → 环境变量指文件 → 本机默认路径 → 仓库内 .bailian_key → 加密保险箱
|
| 21 |
+
# 保险箱(token.vault)是本机/本空间绑定的密文:换台机器拷走也解不开,见 app/vault.py
|
| 22 |
_HERE = os.path.dirname(os.path.abspath(__file__))
|
| 23 |
_KEY_CANDIDATES = [
|
| 24 |
os.environ.get("BAILIAN_KEY_FILE", ""),
|
|
|
|
| 27 |
os.path.join(_HERE, ".bailian_key"),
|
| 28 |
]
|
| 29 |
|
| 30 |
+
# 加密保险箱路径(优先级低于明文 key:本地调试仍可临时放明文)
|
| 31 |
+
_VAULT_CANDIDATES = [
|
| 32 |
+
os.environ.get("ARCHROBOT_VAULT", ""),
|
| 33 |
+
os.path.join(_HERE, "token.vault"),
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
# 引擎清单:全部实测可用(见 app/verify_chat.py)。max_tokens 按引擎性格给。
|
| 37 |
ENGINES = [
|
| 38 |
{"id": "qwen-plus", "label": "通义千问 Plus", "vendor": "阿里百炼",
|
|
|
|
| 79 |
return txt
|
| 80 |
except OSError:
|
| 81 |
continue
|
| 82 |
+
# 最后试保险箱:解不开就静默跳过(绑定不匹配属于正常情况,不该让服务起不来)
|
| 83 |
+
for path in _VAULT_CANDIDATES:
|
| 84 |
+
if not path or not os.path.isfile(path):
|
| 85 |
+
continue
|
| 86 |
+
try:
|
| 87 |
+
import vault as _vault
|
| 88 |
+
txt = _vault.load(path)
|
| 89 |
+
if txt:
|
| 90 |
+
_token_cache.update({"value": txt, "from": "VAULT:" + path,
|
| 91 |
+
"binding": _vault.binding_tag(
|
| 92 |
+
(__import__("json").load(open(path, encoding="utf-8"))
|
| 93 |
+
.get("binding") or "machine"))[1]})
|
| 94 |
+
return txt
|
| 95 |
+
except Exception as e:
|
| 96 |
+
_token_cache["vault_error"] = str(e)
|
| 97 |
+
continue
|
| 98 |
return ""
|
| 99 |
|
| 100 |
|
|
|
|
| 109 |
return "环境变量 BAILIAN_API_KEY"
|
| 110 |
if src == "DISABLED":
|
| 111 |
return "未接入(ARCHROBOT_DISABLE_LLM)"
|
| 112 |
+
if src.startswith("VAULT:"):
|
| 113 |
+
return "加密保险箱 %s(绑定 %s)" % (os.path.basename(src[6:]),
|
| 114 |
+
_token_cache.get("binding") or "本机")
|
| 115 |
return src
|
| 116 |
|
| 117 |
|
app/quickqa.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""没接大模型时的「直答」:从图纸参数表取字段,先用一句话回答问题。
|
| 3 |
+
|
| 4 |
+
为什么要有这个模块:
|
| 5 |
+
线上演示(HF Space)如果没配百炼 Key,老实现会退化成「知识库直查」——
|
| 6 |
+
把 BM25 命中的原文片段整段摆给客户看。客户问「这栋楼几层」,
|
| 7 |
+
屏幕上却是一堆资料标题加字段 dump,等于绕过了问题、只给引用。
|
| 8 |
+
这里改成规则化问答:先认出问的是哪个属性,再去参数表取数,直接给结论。
|
| 9 |
+
规则覆盖不到的,仍然明说「这条规则答不了,需要接模型」,绝不拿片段充答案。
|
| 10 |
+
"""
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
from paths import OUTPUT, PLANS
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _load(path, default=None):
|
| 18 |
+
try:
|
| 19 |
+
with open(path, encoding="utf-8") as f:
|
| 20 |
+
return json.load(f)
|
| 21 |
+
except Exception:
|
| 22 |
+
return default if default is not None else {}
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _plan(pid):
|
| 26 |
+
return _load(os.path.join(PLANS, pid + ".json"))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _info(pid):
|
| 30 |
+
return _load(os.path.join(OUTPUT, pid, "model_info.json"))
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _openings(plan, kind=None, lvl=None):
|
| 34 |
+
out = []
|
| 35 |
+
for o in plan.get("openings") or []:
|
| 36 |
+
if len(o) < 6:
|
| 37 |
+
continue
|
| 38 |
+
x1, y1, x2, y2, k, l = o
|
| 39 |
+
if kind and k != kind:
|
| 40 |
+
continue
|
| 41 |
+
if lvl is not None and l != lvl:
|
| 42 |
+
continue
|
| 43 |
+
out.append((x1, y1, x2, y2, k, l))
|
| 44 |
+
return out
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _len(o):
|
| 48 |
+
x1, y1, x2, y2 = o[0], o[1], o[2], o[3]
|
| 49 |
+
return round(abs(x2 - x1) if abs(x2 - x1) > 1e-6 else abs(y2 - y1), 2)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _rooms(plan):
|
| 53 |
+
out = []
|
| 54 |
+
for r in plan.get("rooms") or []:
|
| 55 |
+
if len(r) >= 5:
|
| 56 |
+
out.append(r[4])
|
| 57 |
+
return out
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _has(q, *words):
|
| 61 |
+
return any(w in q for w in words)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _f(v, n=2):
|
| 65 |
+
"""数字好看一点:3.0 而不是 3.00"""
|
| 66 |
+
s = ("%." + str(n) + "f") % float(v)
|
| 67 |
+
return s.rstrip("0").rstrip(".") if "." in s else s
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def answer(question, pid=None):
|
| 71 |
+
"""返回直接作答的字符串;规则覆盖不到时返回 None。"""
|
| 72 |
+
q = (question or "").strip()
|
| 73 |
+
if not q:
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
# 跨楼栋对比:哪栋最大 / 最高 / 层数最多
|
| 77 |
+
if _has(q, "哪栋", "哪个楼", "哪一栋") and _has(q, "大", "高", "层", "小", "多"):
|
| 78 |
+
rows = []
|
| 79 |
+
for i in range(1, 7):
|
| 80 |
+
p = _plan("BLD-%03d" % i)
|
| 81 |
+
if not p:
|
| 82 |
+
continue
|
| 83 |
+
w, d = p["footprint"]
|
| 84 |
+
rows.append((p["id"], p["name"], float(w) * float(d), int(p["floors"])))
|
| 85 |
+
if not rows:
|
| 86 |
+
return None
|
| 87 |
+
if _has(q, "层", "高"):
|
| 88 |
+
pick = max(rows, key=lambda r: (r[3], r[2]))
|
| 89 |
+
return ("层数最多的是 %s(%s),%d 层,层高 %s m;占地 %s ㎡。"
|
| 90 |
+
% (pick[0], pick[1], pick[3],
|
| 91 |
+
_f(_plan(pick[0]).get("floor_h", 3)), _f(pick[2])))
|
| 92 |
+
pick = max(rows, key=lambda r: r[2]) if not _has(q, "小") else min(rows, key=lambda r: r[2])
|
| 93 |
+
return ("占地最大的是 %s(%s),轮廓 %s × %s m,占地 %s ㎡,%d 层。"
|
| 94 |
+
% (pick[0], pick[1], _f(_plan(pick[0])["footprint"][0]),
|
| 95 |
+
_f(_plan(pick[0])["footprint"][1]), _f(pick[2]), pick[3]))
|
| 96 |
+
|
| 97 |
+
if not pid:
|
| 98 |
+
return None
|
| 99 |
+
plan = _plan(pid)
|
| 100 |
+
if not plan:
|
| 101 |
+
return None
|
| 102 |
+
info = _info(pid)
|
| 103 |
+
st = (info.get("stats") or {}) if info else {}
|
| 104 |
+
|
| 105 |
+
W, D = [float(v) for v in plan.get("footprint") or [0, 0]]
|
| 106 |
+
nf = int(plan.get("floors") or 0)
|
| 107 |
+
fh = float(plan.get("floor_h") or 0)
|
| 108 |
+
t = float(plan.get("wall_t") or 0)
|
| 109 |
+
roof = plan.get("roof") or {}
|
| 110 |
+
inner_y = float(plan.get("inner_y") or 0)
|
| 111 |
+
ridge = float(roof.get("ridge_y") or 0)
|
| 112 |
+
over = float(roof.get("overhang") or 0)
|
| 113 |
+
gable = float(roof.get("gable_h") or 0)
|
| 114 |
+
ztop = nf * fh
|
| 115 |
+
zroof = ztop + 0.16 + gable
|
| 116 |
+
name = plan.get("name") or ""
|
| 117 |
+
|
| 118 |
+
# ---- 口径类问题优先:客户问「能改吗」「能导 IFC 吗」,别被属性名抢走 ----
|
| 119 |
+
if _has(q, "改参数", "改层高", "改墙厚", "能否改", "能不能改", "能改", "可以改", "支持改",
|
| 120 |
+
"能改吗", "改吗", "调参数", "重新生成", "改得动", "改不了"):
|
| 121 |
+
return ("可以改。层高、墙厚、内隔墙位置(inner_y)、屋脊高(ridge_y)、山墙高(gable_h)、"
|
| 122 |
+
"出檐(overhang)这六项支持一句话改参:勾上「改参数并重建」,说出目标值"
|
| 123 |
+
"(例如「层高改成 3.6 米」),系统解析成参数补丁后由 Blender 重建;原图纸不动,"
|
| 124 |
+
"新模型另存一版用于前后对比。六个字段以外的不开放改参,避免几何失稳。")
|
| 125 |
+
if _has(q, "ifc", "格式", "导出", "二次编辑", "revit", "能不能编辑", "能编辑"):
|
| 126 |
+
return ("交付格式是 glTF(.glb)+ Blender 源文件(.blend),不含 IFC。"
|
| 127 |
+
".blend 可以二次编辑;glb 里每个构件都带编号、类型���材质、尺寸、楼层属性,"
|
| 128 |
+
"可以按编号做二次开发或对接其他引擎。")
|
| 129 |
+
|
| 130 |
+
# ---- 层数 / 层高 / 总高 ----
|
| 131 |
+
if _has(q, "几层", "多少层", "层数", "楼层数"):
|
| 132 |
+
return ("%s(%s)共 %d 层,层高 %s m,檐口标高 %s m;屋脊最高点 %s m。"
|
| 133 |
+
% (pid, name, nf, _f(fh), _f(ztop), _f(zroof)))
|
| 134 |
+
if _has(q, "层高", "每层多高", "净高"):
|
| 135 |
+
return ("层高 %s m。%d 层累计 %s m,加屋面山墙后脊高约 %s m;楼板厚 0.16 m。"
|
| 136 |
+
% (_f(fh), nf, _f(ztop), _f(zroof)))
|
| 137 |
+
if _has(q, "总高", "多高", "高度", "标高"):
|
| 138 |
+
return ("%s 共 %d 层、层高 %s m,檐口 %s m;双坡屋面山墙高 %s m,屋脊最高 %s m。"
|
| 139 |
+
% (pid, nf, _f(fh), _f(ztop), _f(gable), _f(zroof)))
|
| 140 |
+
|
| 141 |
+
# ---- 墙厚 / 轮廓 / 面积 ----
|
| 142 |
+
if _has(q, "墙厚", "墙多厚", "墙体厚度", "厚度"):
|
| 143 |
+
return ("墙厚 %s m,内外墙同厚;山墙厚 0.12 m。墙段共 %s 段(1F 四面外墙 + 内隔墙,逐层叠加)。"
|
| 144 |
+
% (_f(t, 3), st.get("墙段", "若干")))
|
| 145 |
+
if _has(q, "轮廓", "尺寸", "长宽", "多大", "面积", "占地", "开间", "进深"):
|
| 146 |
+
area = W * D
|
| 147 |
+
return ("轮廓 %s × %s m,占地 %s ㎡;%d 层总建筑面积约 %s ㎡。屋面含出檐 %s m,"
|
| 148 |
+
"投影约 %s × %s m。"
|
| 149 |
+
% (_f(W), _f(D), _f(area), nf, _f(area * nf), _f(over),
|
| 150 |
+
_f(W + 2 * over), _f(ridge * 2 + 2 * over)))
|
| 151 |
+
|
| 152 |
+
# ---- 房间 / 分隔 ----
|
| 153 |
+
if _has(q, "房间", "分隔", "户型", "几室", "功能"):
|
| 154 |
+
rooms = _rooms(plan)
|
| 155 |
+
txt = "、".join(rooms) if rooms else "图纸未标注房间名"
|
| 156 |
+
return ("一层由内隔墙分成 %d 个房间:%s。竖向内墙在 x = %s m(贯通进深 %s m),"
|
| 157 |
+
"横向内墙在 y = %s m,从竖墙一直拉到右侧外墙。"
|
| 158 |
+
% (len(rooms), txt, _f(_inner_x(plan)), _f(D), _f(inner_y)))
|
| 159 |
+
|
| 160 |
+
# ---- 洞口按立面分布(问「开在哪个面上、各多少个」) ----
|
| 161 |
+
if _has(q, "面") and _has(q, "洞", "窗", "门"):
|
| 162 |
+
return _facade_answer(plan, pid, W, D, nf)
|
| 163 |
+
|
| 164 |
+
# ---- 洞口:内墙门洞 / 门 / 窗 ----
|
| 165 |
+
if _has(q, "门洞", "通道", "内墙的洞", "洞里", "过道", "洞"):
|
| 166 |
+
ps = _openings(plan, "passage", 0)
|
| 167 |
+
if ps:
|
| 168 |
+
parts = []
|
| 169 |
+
for o in ps:
|
| 170 |
+
horiz = abs(o[1] - o[3]) < 1e-6
|
| 171 |
+
pos = ("x %s~%s m" % (_f(o[0]), _f(o[2]))) if horiz else ("y %s~%s m" % (_f(o[1]), _f(o[3])))
|
| 172 |
+
parts.append("%s上一处宽 %s m(%s)" % ("横墙" if horiz else "竖墙", _f(_len(o)), pos))
|
| 173 |
+
return ("一层内墙留了 %d 处门洞,按 2.2 m 高开洞、洞口不通顶:%s。"
|
| 174 |
+
"透视模式下外墙半透明、内墙保持实体,可以直接看到这些洞。"
|
| 175 |
+
% (len(ps), ";".join(parts)))
|
| 176 |
+
if _has(q, "门", "窗"):
|
| 177 |
+
doors = len(_openings(plan, "door"))
|
| 178 |
+
wins = len(_openings(plan, "window"))
|
| 179 |
+
ps = len(_openings(plan, "passage"))
|
| 180 |
+
seg = ["门 %d 樘(入口 1.2 m 宽、2.2 m 高)" % doors,
|
| 181 |
+
"窗 %d 樘(窗台 0.9 m,洞顶 2.3 m,洞口高 1.4 m)" % wins]
|
| 182 |
+
if ps:
|
| 183 |
+
seg.append("内墙门洞 %d 处(不装门扇,直接通房间)" % ps)
|
| 184 |
+
return "%s 共:%s。" % (pid, "、".join(seg))
|
| 185 |
+
|
| 186 |
+
# ---- 屋面 ----
|
| 187 |
+
if _has(q, "屋脊", "屋面", "屋顶", "坡度", "出檐", "山墙", "檐口"):
|
| 188 |
+
half = ridge + over
|
| 189 |
+
import math
|
| 190 |
+
ang = math.degrees(math.atan2(gable, half)) if half else 0
|
| 191 |
+
return ("双坡屋面:屋脊在 y = %s m,脊高 %s m;两侧坡长 %s m、坡度 %s°;"
|
| 192 |
+
"出檐 %s m,屋面板厚 0.14 m;两端山墙高 %s m。"
|
| 193 |
+
% (_f(ridge), _f(zroof), _f(math.hypot(half, gable)), _f(ang, 1), _f(over), _f(gable)))
|
| 194 |
+
|
| 195 |
+
# ---- 构件总览 ----
|
| 196 |
+
if _has(q, "构件", "多少个部件", "部件", "模型里"):
|
| 197 |
+
if st:
|
| 198 |
+
return ("%s 共 %s 个构件:墙段 %s、门窗 %s、楼板 %s。每个构件都带编号、类型、材质、"
|
| 199 |
+
"尺寸、楼层五项属性,右侧清单点一条就能把镜头对过去。"
|
| 200 |
+
% (pid, st.get("构件数"), st.get("墙段"), st.get("门窗"), st.get("楼板")))
|
| 201 |
+
# ---- 材料 ----
|
| 202 |
+
if _has(q, "材质", "材料", "涂什么", "什么漆"):
|
| 203 |
+
comps = (info.get("components") or []) if info else []
|
| 204 |
+
by = {}
|
| 205 |
+
for c in comps:
|
| 206 |
+
m = c.get("mat")
|
| 207 |
+
if m:
|
| 208 |
+
by.setdefault(m, []).append(c.get("type"))
|
| 209 |
+
if by:
|
| 210 |
+
seg = ["%s 用于 %s" % (m, "、".join(sorted(set(v))[:4])) for m, v in by.items()]
|
| 211 |
+
return "%s 的材质口径:%s。" % (pid, ";".join(seg))
|
| 212 |
+
# ---- 图纸 / 约束点 ----
|
| 213 |
+
if _has(q, "几张", "几个视角", "约束点", "图纸数量", "多少张"):
|
| 214 |
+
pts = plan.get("points") or {}
|
| 215 |
+
views = info.get("views") or []
|
| 216 |
+
return ("每栋出 5 张图纸(平面、标准层平面、正立面、侧立面、A-A 剖面),"
|
| 217 |
+
"本栋五视角约束点合计 %s 个:%s。"
|
| 218 |
+
% (sum(int(v) for v in pts.values()) if pts else "—",
|
| 219 |
+
"、".join("%s %s" % (k, v) for k, v in pts.items())))
|
| 220 |
+
if _has(q, "耗时", "多久", "多快", "时间"):
|
| 221 |
+
return ("单栋从图纸到 3D 模型是本机 Blender 无头执行,确定性重建,秒级完成;"
|
| 222 |
+
"运行时不调用大模型,几何全部由 bpy 计算,所以同一份图纸每次结果一致。")
|
| 223 |
+
|
| 224 |
+
return None
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
FACES = [("前墙(y=0,入口面)", "front"), ("后墙(y=D)", "back"),
|
| 228 |
+
("左墙(x=0)", "left"), ("右墙(x=W)", "right")]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def _face_of(o, W, D):
|
| 232 |
+
x1, y1, x2, y2 = o[0], o[1], o[2], o[3]
|
| 233 |
+
if abs(y1) < 1e-6 and abs(y2) < 1e-6:
|
| 234 |
+
return "front"
|
| 235 |
+
if abs(y1 - D) < 1e-6 and abs(y2 - D) < 1e-6:
|
| 236 |
+
return "back"
|
| 237 |
+
if abs(x1) < 1e-6 and abs(x2) < 1e-6:
|
| 238 |
+
return "left"
|
| 239 |
+
if abs(x1 - W) < 1e-6 and abs(x2 - W) < 1e-6:
|
| 240 |
+
return "right"
|
| 241 |
+
return None # 内墙上的洞
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _facade_answer(plan, pid, W, D, nf):
|
| 245 |
+
"""按立面条目统计门窗洞口:客户问「开在哪几个面上、各多少个」就照这个答。"""
|
| 246 |
+
stat = {}
|
| 247 |
+
inner = {"passage": 0, "door": 0}
|
| 248 |
+
for o in plan.get("openings") or []:
|
| 249 |
+
if len(o) < 6:
|
| 250 |
+
continue
|
| 251 |
+
f = _face_of(o, W, D)
|
| 252 |
+
if f is None:
|
| 253 |
+
if o[4] in inner:
|
| 254 |
+
inner[o[4]] += 1
|
| 255 |
+
continue
|
| 256 |
+
d = stat.setdefault(f, {"door": 0, "window": 0})
|
| 257 |
+
if o[4] in d:
|
| 258 |
+
d[o[4]] += 1
|
| 259 |
+
total_door = sum(v["door"] for v in stat.values())
|
| 260 |
+
total_win = sum(v["window"] for v in stat.values())
|
| 261 |
+
seg = []
|
| 262 |
+
for cn, key in FACES:
|
| 263 |
+
d = stat.get(key) or {"door": 0, "window": 0}
|
| 264 |
+
bits = []
|
| 265 |
+
if d["door"]:
|
| 266 |
+
bits.append("门 %d" % d["door"])
|
| 267 |
+
if d["window"]:
|
| 268 |
+
bits.append("窗 %d" % d["window"])
|
| 269 |
+
seg.append("%s %s" % (cn, "、".join(bits) if bits else "无洞口"))
|
| 270 |
+
inner_txt = ""
|
| 271 |
+
if inner["passage"] or inner["door"]:
|
| 272 |
+
inner_txt = "另有内隔墙上 %d 处门洞(不在外立面上,透视后才能看到)。" % (inner["passage"] + inner["door"])
|
| 273 |
+
return ("%s 的洞口分布(%d 层合计):%s。四个立面共 %d 个洞口——门 %d 樘、窗 %d 樘;%s"
|
| 274 |
+
"各层洞口位置相同,往上逐层叠加。"
|
| 275 |
+
% (pid, nf, ";".join(seg), total_door + total_win, total_door, total_win,
|
| 276 |
+
inner_txt))
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _inner_x(plan):
|
| 280 |
+
"""竖向内墙的 x 坐标:walls 里 x1==x2 且不在外墙位置的那一段"""
|
| 281 |
+
W = float((plan.get("footprint") or [0, 0])[0])
|
| 282 |
+
for w in plan.get("walls") or []:
|
| 283 |
+
if len(w) == 5 and abs(w[0] - w[2]) < 1e-6 and 1e-6 < w[0] < W - 1e-6:
|
| 284 |
+
return w[0]
|
| 285 |
+
return 0.0
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
if __name__ == "__main__":
|
| 289 |
+
tests = ["这栋楼几层", "层高多少", "墙厚", "轮廓多大,占地面积多少", "房间怎么分",
|
| 290 |
+
"内墙的门洞在哪", "有几个门几扇窗", "屋面坡度多少", "一共多少构件",
|
| 291 |
+
"墙是什么材质", "出几张图纸", "层高能改吗", "能导出 IFC 吗", "哪栋楼最大"]
|
| 292 |
+
for q in tests:
|
| 293 |
+
a = answer(q, "BLD-001")
|
| 294 |
+
print(("Q: " + q).ljust(28), "→", a or "(未覆盖)")
|
app/server.py
CHANGED
|
@@ -16,6 +16,7 @@ import kb
|
|
| 16 |
import llm
|
| 17 |
import chat
|
| 18 |
import patch
|
|
|
|
| 19 |
|
| 20 |
PORT = int(os.environ.get("ARCHROBOT_PORT", "8765"))
|
| 21 |
HOST = os.environ.get("ARCHROBOT_HOST", "0.0.0.0")
|
|
@@ -342,11 +343,20 @@ class Handler(BaseHTTPRequestHandler):
|
|
| 342 |
finally:
|
| 343 |
CHAT_GATE.done()
|
| 344 |
if got["intent"] != "modify" or not got["patch"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
return self._send(200, json.dumps(
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
try:
|
| 351 |
new_id, _new_plan, diffs = patch.prepare(pid, got["patch"])
|
| 352 |
except Exception as e:
|
|
@@ -372,9 +382,21 @@ class Handler(BaseHTTPRequestHandler):
|
|
| 372 |
if not question:
|
| 373 |
return self._send(400, '{"error":"问题为空"}')
|
| 374 |
if not llm.ready():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return self._send(200, json.dumps(
|
| 376 |
-
{"ok": False, "
|
| 377 |
-
"
|
|
|
|
|
|
|
|
|
|
| 378 |
ensure_ascii=False))
|
| 379 |
# 公网部署时这道闸必须有:key 在服务端,被刷就是真金白银
|
| 380 |
ok, why, wait = CHAT_GATE.take(self._client_ip())
|
|
@@ -389,6 +411,14 @@ class Handler(BaseHTTPRequestHandler):
|
|
| 389 |
return self._send(200, json.dumps(dict(ok=True, answer=answer, **meta),
|
| 390 |
ensure_ascii=False))
|
| 391 |
except Exception as e:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
return self._send(200, json.dumps(
|
| 393 |
{"ok": False, "error": str(e)}, ensure_ascii=False))
|
| 394 |
finally:
|
|
|
|
| 16 |
import llm
|
| 17 |
import chat
|
| 18 |
import patch
|
| 19 |
+
import quickqa
|
| 20 |
|
| 21 |
PORT = int(os.environ.get("ARCHROBOT_PORT", "8765"))
|
| 22 |
HOST = os.environ.get("ARCHROBOT_HOST", "0.0.0.0")
|
|
|
|
| 343 |
finally:
|
| 344 |
CHAT_GATE.done()
|
| 345 |
if got["intent"] != "modify" or not got["patch"]:
|
| 346 |
+
# 这句话不是改参(比如「洞口开在几个面上」)。以前这里直接报错,
|
| 347 |
+
# 客户勾着「改参数并重建」问属性就会被顶回来——所以改成自动回落问答,
|
| 348 |
+
# 顺手告诉他一嘴怎么改参。宁可多答一句,不能让客户以为系统不认问题。
|
| 349 |
+
try:
|
| 350 |
+
answer, meta = chat.ask(question, engine=req.get("engine"),
|
| 351 |
+
building=pid)
|
| 352 |
+
except Exception as e:
|
| 353 |
+
return self._send(200, json.dumps(
|
| 354 |
+
{"ok": False, "error": str(e)}, ensure_ascii=False))
|
| 355 |
return self._send(200, json.dumps(
|
| 356 |
+
dict(ok=True, intent="qa", fallback=True, answer=answer,
|
| 357 |
+
patch={}, notes=[got.get("explain") or ""],
|
| 358 |
+
hint="这句不是改参,已按问答回答;要改参数可以说「层高改成 3.6 米」",
|
| 359 |
+
**meta), ensure_ascii=False))
|
| 360 |
try:
|
| 361 |
new_id, _new_plan, diffs = patch.prepare(pid, got["patch"])
|
| 362 |
except Exception as e:
|
|
|
|
| 382 |
if not question:
|
| 383 |
return self._send(400, '{"error":"问题为空"}')
|
| 384 |
if not llm.ready():
|
| 385 |
+
# 没接模型时不要拿「检索片段」冒充答案:先前那条路会让客户问「洞口在几个面上」,
|
| 386 |
+
# 屏幕上却弹出两条无关的 FAQ 原文。这里改成规则直答——先正面回答,再说明降级状态。
|
| 387 |
+
qa = quickqa.answer(question, req.get("building"))
|
| 388 |
+
if qa:
|
| 389 |
+
return self._send(200, json.dumps(
|
| 390 |
+
{"ok": True, "answer": qa, "degraded": True, "engine": "rule-qa",
|
| 391 |
+
"label": "图纸直答(未接模型)", "citations": [],
|
| 392 |
+
"note": "当前部署未配置大模型 Key,这条答案是按图纸参数表逐字取数得出的,不是模型生成。"},
|
| 393 |
+
ensure_ascii=False))
|
| 394 |
return self._send(200, json.dumps(
|
| 395 |
+
{"ok": False, "degraded": True,
|
| 396 |
+
"error": "当前部署未接入大模型,这个问题超出了直答规则能覆盖的范围",
|
| 397 |
+
"hint": "已接入的直答范围:层数/层高/总高、墙厚、轮廓与面积、房间分隔、"
|
| 398 |
+
"门窗与内墙门洞、屋面坡度出檐山墙、构件总数与材质、图纸视角与约束点、改参口径、导出格式。"
|
| 399 |
+
"其余问题需要配置百炼 Key 后才能回答。"},
|
| 400 |
ensure_ascii=False))
|
| 401 |
# 公网部署时这道闸必须有:key 在服务端,被刷就是真金白银
|
| 402 |
ok, why, wait = CHAT_GATE.take(self._client_ip())
|
|
|
|
| 411 |
return self._send(200, json.dumps(dict(ok=True, answer=answer, **meta),
|
| 412 |
ensure_ascii=False))
|
| 413 |
except Exception as e:
|
| 414 |
+
# 模型侧抖动(限流/超时/配额)时,先用参数表直答保住这次提问,再把原因说清楚
|
| 415 |
+
qa = quickqa.answer(question, req.get("building"))
|
| 416 |
+
if qa:
|
| 417 |
+
return self._send(200, json.dumps(
|
| 418 |
+
{"ok": True, "answer": qa, "degraded": True, "engine": "rule-qa",
|
| 419 |
+
"label": "图纸直答(模型暂时不可用)", "citations": [],
|
| 420 |
+
"note": "大模型这次没调通(%s),这条是按图纸参数表取数直答的。" % str(e)[:120]},
|
| 421 |
+
ensure_ascii=False))
|
| 422 |
return self._send(200, json.dumps(
|
| 423 |
{"ok": False, "error": str(e)}, ensure_ascii=False))
|
| 424 |
finally:
|
app/static/index.html
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
app/token.vault
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"v": 1,
|
| 3 |
+
"alg": "hmac-sha256-ctr+hmac256",
|
| 4 |
+
"binding": "space",
|
| 5 |
+
"fingerprint": "fcceb0121701",
|
| 6 |
+
"iter": 120000,
|
| 7 |
+
"salt": "eca7bb22c52e473c57cb09df082c0216",
|
| 8 |
+
"nonce": "dfdb67624610d819d504c671a10d0fc3",
|
| 9 |
+
"ct": "2c5b58117ebee50e4407a65d4e1bdab8fbf73dbe14d6347306d0ee67c846d5af7247a460659424dca0281877ee6d5f035a017b2412e0646deaa152be8cde9f23dee26f33aafa2b0522f8c673fee9241cc42d006f84f61d159b11ccb61e5641954653ef17f43a5065faecf84ae0be83c6fbc7b52e57",
|
| 10 |
+
"tag": "9c4c4954347ec92ca769e127ecb93e8c2abd22e4b177f9f3fdead0fb4110885f"
|
| 11 |
+
}
|
app/vault.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""Key 保险箱:把百炼 token 加密落地,绑死「这台机器」或「这个 HF 空间」。
|
| 3 |
+
|
| 4 |
+
为什么不用明文 .bailian_key:
|
| 5 |
+
明文 key 一旦跟着目录被拷走、被截图、被传到网盘,就是别人的额度。
|
| 6 |
+
这里把 key 用「绑定值 + 静态盐」派生出的密钥加密,密文落地。
|
| 7 |
+
换一台机器(或换成别的 HF 空间)解不开——不是靠道德约束,是数学上解不开。
|
| 8 |
+
|
| 9 |
+
加密构造(只用标准库,内网无依赖):
|
| 10 |
+
master = PBKDF2-HMAC-SHA256(binding_value + PEPPER, salt, 120000 轮)
|
| 11 |
+
enc_key, mac_key = HMAC(master, "enc"), HMAC(master, "mac")
|
| 12 |
+
ct = plaintext XOR HMAC-SHA256(enc_key, nonce ‖ counter) 逐块异或
|
| 13 |
+
tag = HMAC-SHA256(mac_key, nonce ‖ ct) # encrypt-then-MAC
|
| 14 |
+
解封时先验 tag,再解密;任何一位被改都会直接报「密文校验失败」。
|
| 15 |
+
|
| 16 |
+
诚实说明边界:这是「绑定 + 混淆」级别的保护,不是对抗能读到源码的攻击者。
|
| 17 |
+
能拿到源码的人在别的机器上推不出 binding_value(MachineGuid / SPACE_ID),
|
| 18 |
+
但如果他能登进这台机器,他就能解开。真要更强,请用 HF 的 Secret(平台托管、静态加密)。
|
| 19 |
+
"""
|
| 20 |
+
import hashlib
|
| 21 |
+
import hmac
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import platform
|
| 25 |
+
import secrets
|
| 26 |
+
import sys
|
| 27 |
+
import uuid
|
| 28 |
+
|
| 29 |
+
VERSION = 1
|
| 30 |
+
PEPPER = b"archrobot/vault/v1|bailian-api-key|do-not-edit"
|
| 31 |
+
ITER = 120000
|
| 32 |
+
KIND_MACHINE = "machine"
|
| 33 |
+
KIND_SPACE = "space"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ---------------- 绑定值 ----------------
|
| 37 |
+
def _win_machine_guid():
|
| 38 |
+
"""Windows 安装唯一标识(重装系统才变),比网卡 MAC 稳定得多"""
|
| 39 |
+
try:
|
| 40 |
+
import winreg
|
| 41 |
+
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
|
| 42 |
+
r"SOFTWARE\Microsoft\Cryptography", 0,
|
| 43 |
+
winreg.KEY_READ | winreg.KEY_WOW64_64KEY) as k:
|
| 44 |
+
return winreg.QueryValueEx(k, "MachineGuid")[0]
|
| 45 |
+
except Exception:
|
| 46 |
+
return ""
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def machine_binding():
|
| 50 |
+
"""本机指纹:MachineGuid + 主机名。换机/重装系统即失效。"""
|
| 51 |
+
parts = [platform.system(), platform.node() or "", _win_machine_guid(),
|
| 52 |
+
str(uuid.getnode())]
|
| 53 |
+
return "machine|" + "|".join(parts)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def space_binding():
|
| 57 |
+
"""HF Space 指纹:只用 SPACE_ID(形如 dellweb3/build3d)。
|
| 58 |
+
刻意不掺 SPACE_HOST / 端口 / 构建号——这些在重建、换域名时会变,
|
| 59 |
+
掺进去就会出现「明明是自己空间却解不开」的售后问题。"""
|
| 60 |
+
sid = (os.environ.get("SPACE_ID") or "").strip()
|
| 61 |
+
return ("space|" + sid) if sid else ""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def binding_value(kind):
|
| 65 |
+
if kind == KIND_SPACE:
|
| 66 |
+
return space_binding()
|
| 67 |
+
return machine_binding()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def binding_tag(kind):
|
| 71 |
+
"""写进密文文件的可读指纹(只存前 12 位摘要,不泄露绑定值本身)"""
|
| 72 |
+
v = binding_value(kind)
|
| 73 |
+
return (kind, hashlib.sha256(v.encode("utf-8")).hexdigest()[:12]) if v else (kind, "")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ---------------- 加解密 ----------------
|
| 77 |
+
def _keys(binding, salt):
|
| 78 |
+
master = hashlib.pbkdf2_hmac("sha256", (binding.encode("utf-8") + PEPPER), salt, ITER, 32)
|
| 79 |
+
return (hmac.new(master, b"enc", hashlib.sha256).digest(),
|
| 80 |
+
hmac.new(master, b"mac", hashlib.sha256).digest())
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _keystream(enc_key, nonce, n):
|
| 84 |
+
out = b""
|
| 85 |
+
counter = 0
|
| 86 |
+
while len(out) < n:
|
| 87 |
+
out += hmac.new(enc_key, nonce + counter.to_bytes(4, "big"), hashlib.sha256).digest()
|
| 88 |
+
counter += 1
|
| 89 |
+
return out[:n]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def seal(plaintext, kind=KIND_MACHINE):
|
| 93 |
+
binding = binding_value(kind)
|
| 94 |
+
if not binding:
|
| 95 |
+
raise RuntimeError("拿不到绑定值(%s):HF 空间外无法生成空间级密文" % kind)
|
| 96 |
+
salt, nonce = secrets.token_bytes(16), secrets.token_bytes(16)
|
| 97 |
+
enc_key, mac_key = _keys(binding, salt)
|
| 98 |
+
data = plaintext.encode("utf-8")
|
| 99 |
+
ct = bytes(a ^ b for a, b in zip(data, _keystream(enc_key, nonce, len(data))))
|
| 100 |
+
tag = hmac.new(mac_key, nonce + ct, hashlib.sha256).digest()
|
| 101 |
+
k, fp = binding_tag(kind)
|
| 102 |
+
return {"v": VERSION, "alg": "hmac-sha256-ctr+hmac256", "binding": k,
|
| 103 |
+
"fingerprint": fp, "iter": ITER,
|
| 104 |
+
"salt": salt.hex(), "nonce": nonce.hex(),
|
| 105 |
+
"ct": ct.hex(), "tag": tag.hex()}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def unseal(blob):
|
| 109 |
+
kind = blob.get("binding") or KIND_MACHINE
|
| 110 |
+
binding = binding_value(kind)
|
| 111 |
+
if not binding:
|
| 112 |
+
raise RuntimeError("这个密文绑定的是 %s,当前环境不满足(不在目标机器 / 不在该 HF 空间)" % kind)
|
| 113 |
+
_, fp = binding_tag(kind)
|
| 114 |
+
if blob.get("fingerprint") and fp and blob["fingerprint"] != fp:
|
| 115 |
+
raise RuntimeError("绑定指纹不匹配:密文属于 %s…,当前环境是 %s…" %
|
| 116 |
+
(blob["fingerprint"], fp))
|
| 117 |
+
salt, nonce = bytes.fromhex(blob["salt"]), bytes.fromhex(blob["nonce"])
|
| 118 |
+
ct, tag = bytes.fromhex(blob["ct"]), bytes.fromhex(blob["tag"])
|
| 119 |
+
enc_key, mac_key = _keys(binding, salt)
|
| 120 |
+
if not hmac.compare_digest(hmac.new(mac_key, nonce + ct, hashlib.sha256).digest(), tag):
|
| 121 |
+
raise RuntimeError("密文校验失败:文件被改过,或不是在这台机器上生成的")
|
| 122 |
+
return bytes(a ^ b for a, b in zip(ct, _keystream(enc_key, nonce, len(ct)))).decode("utf-8")
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ---------------- 文件读写 ----------------
|
| 126 |
+
def load(path):
|
| 127 |
+
"""读一个 .vault 文件,返回明文 key;任何异常都往上抛,由调用方决定是否忽略"""
|
| 128 |
+
with open(path, encoding="utf-8") as f:
|
| 129 |
+
return unseal(json.load(f)).strip()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def save(path, plaintext, kind=KIND_MACHINE):
|
| 133 |
+
blob = seal(plaintext, kind)
|
| 134 |
+
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
| 135 |
+
json.dump(blob, f, ensure_ascii=False, indent=1)
|
| 136 |
+
f.write("\n")
|
| 137 |
+
return blob
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def main(argv):
|
| 141 |
+
kind = KIND_SPACE if ("space" in argv or "--space" in argv) else KIND_MACHINE
|
| 142 |
+
root = os.path.dirname(os.path.abspath(__file__))
|
| 143 |
+
out = os.path.join(root, "token.vault")
|
| 144 |
+
if "check" in argv:
|
| 145 |
+
print("绑定类型:", kind, "| 当前环境绑定值指纹:", binding_tag(kind)[1] or "(不可用)")
|
| 146 |
+
try:
|
| 147 |
+
k = load(out)
|
| 148 |
+
print("解封成功:token 长度 %d,前缀 %s…" % (len(k), k[:3]))
|
| 149 |
+
except Exception as e:
|
| 150 |
+
print("解封失败:", e)
|
| 151 |
+
return 0
|
| 152 |
+
src = os.environ.get("BAILIAN_API_KEY", "").strip()
|
| 153 |
+
for p in (os.environ.get("BAILIAN_KEY_FILE", ""), r"G:\Key-token\key-baliantoken.txt"):
|
| 154 |
+
if not src and p and os.path.isfile(p):
|
| 155 |
+
src = open(p, encoding="utf-8").read().strip()
|
| 156 |
+
if not src:
|
| 157 |
+
print("没有拿到明文 key:设 BAILIAN_API_KEY 或 BAILIAN_KEY_FILE")
|
| 158 |
+
return 2
|
| 159 |
+
blob = save(out, src, kind)
|
| 160 |
+
print("已写入 %s(%s,指纹 %s,密文 %d 字节)" %
|
| 161 |
+
(out, blob["binding"], blob["fingerprint"], len(blob["ct"]) // 2))
|
| 162 |
+
return 0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
sys.exit(main(sys.argv[1:]))
|