File size: 7,079 Bytes
c1a5994 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | # -*- coding: utf-8 -*-
"""
自然语言改参数 → 参数补丁 → 重建模型。
边界(很重要,别越界):
大模型只输出「哪个字段改成什么值」的补丁,**不生成几何、不写脚本**。
几何仍由 demo/build_model.py 里的 bpy 确定性代码执行。这样做的三个理由:
1. 可校验:补丁是几个数字,越界能夹、写错能拒;
2. 可复现:同样的补丁,同样的模型;
3. 可回滚:原图纸不动,改出来的是新的一版(<楼栋号>-V2),随时删。
白名单只放「改了不会让图纸自相矛盾」的字段:层高、墙厚、内隔墙位置、屋面三个尺寸。
洞口、房间、墙轴线不在白名单里 —— 改这些必须回到图纸重画,否则平面和剖面对不上。
"""
import copy
import json
import os
import llm
from paths import PLANS
# 字段 -> (下限, 上限, 中文名, 单位)
FIELDS = {
"floor_h": (2.4, 6.0, "层高", "m"),
"wall_t": (0.10, 0.60, "墙厚", "m"),
"inner_y": (0.5, 60.0, "内隔墙位置", "m"),
"roof.ridge_y": (1.5, 30.0, "屋脊高度", "m"),
"roof.gable_h": (0.0, 12.0, "山墙高度", "m"),
"roof.overhang": (0.0, 2.5, "出檐长度", "m"),
}
SYS = """你是建筑图纸参数助手。用户会用中文提出对当前这栋楼参数的修改要求。
你的唯一任务是把它翻译成一个参数补丁(JSON),不要解释几何、不要写代码。
只能改这些字段(单位米):
floor_h 层高,范围 2.4—6.0
wall_t 墙厚,范围 0.10—0.60
inner_y 内隔墙位置(沿进深的坐标),范围 0.5—60
roof.ridge_y 屋脊高度,范围 1.5—30
roof.gable_h 山墙高度,范围 0.0—12(平屋顶就填 0)
roof.overhang 出檐长度,范围 0.0—2.5
规则:
1. 用户没提到的字段绝对不要出现在补丁里,不要顺手"优化"。
2. 用户说"高一点/矮一点"这类相对说法时,基于给出的当前值加减,幅度取 0.3—0.6 米的常识值。
3. 如果用户不是在改参数(在提问、在讨论、在问能不能做),intent 填 "none",patch 留空。
4. 如果要求超出范围,取最近的边界值,并在 explain 里说明已取边界。
5. 只输出一个 JSON 对象,不要代码块、不要多余文字:
{"intent":"modify" 或 "none","patch":{...},"explain":"一句话说明你改了什么、从多少到多少"}
"""
def _current(plan):
"""把当前值摊平成补丁同构的字典,供模型算相对变化"""
roof = plan.get("roof") or {}
return {"floor_h": plan.get("floor_h"), "wall_t": plan.get("wall_t"),
"inner_y": plan.get("inner_y"), "roof.ridge_y": roof.get("ridge_y"),
"roof.gable_h": roof.get("gable_h"), "roof.overhang": roof.get("overhang")}
def _extract_json(text):
"""模型偶尔会包 ```json 或加前后缀,这里只认第一个平衡的 {...}"""
s = text.strip()
if s.startswith("```"):
s = s.split("```")[1] if len(s.split("```")) > 1 else s
s = s.replace("json", "", 1).strip() if s.lower().startswith("json") else s
i = s.find("{")
if i < 0:
return None
depth = 0
for j in range(i, len(s)):
if s[j] == "{":
depth += 1
elif s[j] == "}":
depth -= 1
if depth == 0:
try:
return json.loads(s[i:j + 1])
except ValueError:
return None
return None
def validate(raw_patch):
"""白名单 + 类型 + 范围。返回 (clean_patch, notes);越界的夹住并记一笔"""
clean, notes = {}, []
for k, v in (raw_patch or {}).items():
if k not in FIELDS:
notes.append("忽略不支持的字段 %s" % k)
continue
try:
num = float(v)
except (TypeError, ValueError):
notes.append("字段 %s 不是数字,已忽略" % k)
continue
lo, hi, cn, unit = FIELDS[k]
if num < lo or num > hi:
clamped = min(max(num, lo), hi)
notes.append("%s %.2f%s 超出范围,已取边界 %.2f%s" % (cn, num, unit, clamped, unit))
num = clamped
clean[k] = round(num, 3)
return clean, notes
def parse(question, plan, engine=None):
"""问模型要补丁。返回 dict(intent, patch, explain, notes, meta)"""
payload = {"当前参数": _current(plan),
"楼栋": "%s %s(%s 层,%s×%s 米)" % (
plan.get("id"), plan.get("name"), plan.get("floors"),
plan.get("footprint", [None])[0], plan.get("footprint", [None, None])[1])}
messages = [
{"role": "system", "content": SYS},
{"role": "user", "content": json.dumps(payload, ensure_ascii=False) +
"\n\n用户的修改要求:" + question},
]
text, meta = llm.chat(engine, messages, temperature=0.1, max_tokens=400)
data = _extract_json(text)
if not data:
return {"intent": "none", "patch": {}, "explain": "没能把这句话解析成参数修改",
"notes": ["模型原始输出:" + text[:120]], "meta": meta}
patch, notes = validate(data.get("patch") or {})
intent = "modify" if patch and data.get("intent", "modify") != "none" else "none"
return {"intent": intent, "patch": patch,
"explain": (data.get("explain") or "").strip()[:200],
"notes": notes, "meta": meta}
def _set(plan, key, value):
if key.startswith("roof."):
plan.setdefault("roof", {})[key.split(".", 1)[1]] = value
else:
plan[key] = value
def _get(plan, key):
if key.startswith("roof."):
return (plan.get("roof") or {}).get(key.split(".", 1)[1])
return plan.get(key)
def apply(plan, patch):
"""返回 (新图纸, 差异列表)。原图纸不动。"""
new = copy.deepcopy(plan)
diffs = []
for k, v in patch.items():
old = _get(new, k)
_set(new, k, v)
diffs.append({"field": k, "name": FIELDS[k][2], "unit": FIELDS[k][3],
"old": old, "new": v})
return new, diffs
def derive_id(plan_id):
"""改出来的版本号:BLD-003 -> _BLD-003_V2(下划线开头,不进入图纸列表)"""
return "_%s_V2" % plan_id
def prepare(plan_id, patch):
"""写一份新图纸到 plans 目录,返回 (新 id, 新图纸, 差异)。重建由调用方排队。"""
src = os.path.join(PLANS, plan_id + ".json")
if not os.path.isfile(src):
raise RuntimeError("图纸不存在:%s" % plan_id)
with open(src, encoding="utf-8") as f:
plan = json.load(f)
new, diffs = apply(plan, patch)
new_id = derive_id(plan_id)
new["id"] = new_id
new["name"] = plan.get("name", plan_id) + "(按对话改参)"
new["derived_from"] = plan_id
new["patch"] = patch
with open(os.path.join(PLANS, new_id + ".json"), "w", encoding="utf-8", newline="\n") as f:
json.dump(new, f, ensure_ascii=False, indent=1)
return new_id, new, diffs
|