275 lines
12 KiB
Python
275 lines
12 KiB
Python
from pathlib import Path
|
||
|
||
from .cad_export import export_verified
|
||
|
||
from .claims import check_claims
|
||
from .postcondition import PostconditionError, check_postcondition
|
||
from .validation import finite, solid_errors
|
||
|
||
|
||
class IRError(Exception):
|
||
"""IR中某个操作校验失败或执行失败时抛出,携带具体是哪个操作、哪些错误。"""
|
||
|
||
def __init__(self, op_index: int, op_name: str, errors: list):
|
||
self.op_index = op_index
|
||
self.op_name = op_name
|
||
self.errors = errors
|
||
super().__init__(f"操作[{op_index}] {op_name} 未通过: {errors}")
|
||
|
||
|
||
_TYPE_CHECKERS = {
|
||
"numbers": lambda v: isinstance(v, list) and all(type(x) in (int,float) for x in v),
|
||
"objects": lambda v: isinstance(v, list) and all(isinstance(x,dict) for x in v),
|
||
"vector": lambda v: isinstance(v, list) and len(v) == 3 and all(type(c) in (float, int) for c in v),
|
||
"float": lambda v: isinstance(v, (int, float)) and not isinstance(v, bool),
|
||
"int": lambda v: isinstance(v, int) and not isinstance(v, bool),
|
||
"bool": lambda v: isinstance(v, bool),
|
||
"enum": lambda v: isinstance(v, str),
|
||
"str": lambda v: isinstance(v, str),
|
||
"list_int": lambda v: isinstance(v, list) and all(type(x) is int for x in v),
|
||
"list_str": lambda v: isinstance(v, list) and all(isinstance(x, str) for x in v),
|
||
"points": lambda v: (
|
||
isinstance(v, list)
|
||
and len(v) >= 2
|
||
and all(
|
||
isinstance(pt, list)
|
||
and len(pt) == 2
|
||
and all(isinstance(c, (int, float)) and not isinstance(c, bool) for c in pt)
|
||
for pt in v
|
||
)
|
||
),
|
||
}
|
||
|
||
|
||
def validate_params(contract: dict, params: dict) -> list:
|
||
"""按契约里声明的 parameters(必填/类型/取值范围/枚举)做通用校验。
|
||
|
||
这是③校验层的一部分:契约文件本身就是校验规则的来源,不需要额外维护一份规则文档。
|
||
"""
|
||
if not isinstance(params, dict):
|
||
return ["TYPE_ERROR: params 必须是对象"]
|
||
errors = []
|
||
allowed = {p["name"] for p in contract.get("parameters", [])}
|
||
if set(params) - allowed:
|
||
errors.append(f"UNKNOWN_PARAM: 未声明的参数 {sorted(set(params) - allowed)}")
|
||
if not finite(params):
|
||
errors.append("NON_FINITE: 参数不能包含 NaN 或 Infinity")
|
||
for p in contract.get("parameters", []):
|
||
name = p["name"]
|
||
if p.get("required") and name not in params:
|
||
errors.append(f"MISSING_PARAM: 缺少必填参数 '{name}'")
|
||
continue
|
||
if name not in params:
|
||
continue
|
||
|
||
value = params[name]
|
||
ptype = p.get("type")
|
||
|
||
# 大模型偶尔会把数字写成带引号的字符串(比如"20"而不是20)——这不是零件本身的问题,
|
||
# 是JSON输出的小瑕疵,值本身是对的,不该因为类型不严格匹配就判失败重来一轮。
|
||
if ptype in ("float", "int") and isinstance(value, str):
|
||
try:
|
||
value = float(value) if ptype == "float" else int(value)
|
||
params[name] = value
|
||
except ValueError:
|
||
pass # 转不了数字就留给下面的类型检查器正常报TYPE_ERROR
|
||
|
||
checker = _TYPE_CHECKERS.get(ptype)
|
||
if checker and not checker(value):
|
||
errors.append(
|
||
f"TYPE_ERROR: 参数 '{name}' 类型应为 {ptype}, 实际为 {type(value).__name__}"
|
||
)
|
||
continue
|
||
|
||
if not finite(value):
|
||
errors.append(f"NON_FINITE: 参数 '{name}' 必须是有限数值")
|
||
continue
|
||
|
||
if ptype == "enum":
|
||
options = p.get("options", [])
|
||
if options and value not in options:
|
||
errors.append(
|
||
f"INVALID_ENUM: 参数 '{name}' 取值 '{value}' 不在允许范围 {options}"
|
||
)
|
||
|
||
rng = p.get("range")
|
||
if rng and ptype in ("float", "int"):
|
||
lo, hi = rng
|
||
if not (lo <= value <= hi):
|
||
errors.append(
|
||
f"RANGE_ERROR: 参数 '{name}' 取值 {value} 超出允许范围 [{lo}, {hi}]"
|
||
)
|
||
return errors
|
||
|
||
|
||
def ir_from_report(report: dict) -> dict:
|
||
"""把 run_ir() 产出的 report 还原成一份可以重新执行的IR。
|
||
|
||
用于"参数化修改"场景:不用把整个零件重新描述一遍,只需要在这份还原出来的IR上
|
||
改几个params,就能重新跑一遍executor得到修改后的模型。
|
||
"""
|
||
ir = {
|
||
"name": report["part_name"],
|
||
"operations": [
|
||
{"op": op["op"], "id": op["id"], "target": op["target"], "params": op["params"]}
|
||
for op in report["operations"]
|
||
],
|
||
"output": report["output_id"],
|
||
}
|
||
if report.get("expected_solid_count") is not None:
|
||
ir["expected_solid_count"] = report["expected_solid_count"]
|
||
if report.get("claims"):
|
||
ir["claims"] = report["claims"]
|
||
return ir
|
||
|
||
|
||
def run_ir(ir: dict, registry: dict, output_dir) -> dict:
|
||
"""执行一份IR(operations列表),返回包含体积/包围盒/输出文件路径的报告。
|
||
|
||
每个op: {"op": 能力名, "id": 结果标识(可选), "target": 输入结果标识(可选,默认上一步), "params": {...}}
|
||
"""
|
||
context = {}
|
||
last_id = None
|
||
trace = []
|
||
|
||
if not isinstance(ir, dict) or not isinstance(ir.get("operations"), list) or not ir["operations"]:
|
||
raise IRError(-1, "schema", ["INVALID_IR: operations 必须是非空数组"])
|
||
for i, op in enumerate(ir["operations"]):
|
||
if not isinstance(op, dict) or not isinstance(op.get("op"), str):
|
||
raise IRError(i, "schema", ["INVALID_OPERATION: 缺少合法 op"])
|
||
op_name = op["op"]
|
||
if op_name not in registry:
|
||
raise IRError(i, op_name, [f"UNKNOWN_CAPABILITY: 能力库中不存在 '{op_name}'"])
|
||
|
||
cap = registry[op_name]
|
||
params = op.get("params", {})
|
||
|
||
errors = validate_params(cap.contract, params)
|
||
if errors:
|
||
raise IRError(i, op_name, errors)
|
||
|
||
target_id = op.get("target", last_id)
|
||
if target_id == "": # Legacy reports used an empty string for independent operations.
|
||
target_id = None
|
||
op_id = op.get("id", f"op{i}")
|
||
if not isinstance(op_id, str) or not op_id or op_id in context:
|
||
raise IRError(i, op_name, ["INVALID_ID: 操作 id 必须非空且不可重复"])
|
||
if target_id is not None and (not isinstance(target_id, str) or target_id not in context):
|
||
raise IRError(i, op_name, [f"UNKNOWN_ID: target '{target_id}' 不存在"])
|
||
target_obj = context.get(target_id) if target_id else None
|
||
|
||
if hasattr(cap.impl, "validate"):
|
||
try:
|
||
errors += cap.impl.validate(context, target_obj, params) or []
|
||
except Exception as exc:
|
||
errors.append(f"VALIDATION_ERROR: {exc}")
|
||
|
||
if errors:
|
||
raise IRError(i, op_name, errors)
|
||
|
||
try:
|
||
result = cap.impl.run(context, target_obj, params)
|
||
except Exception as e: # noqa: BLE001 - 统一包装成结构化错误返回给上层
|
||
raise IRError(i, op_name, [f"EXECUTION_ERROR: {e}"])
|
||
|
||
# 每一步都无条件核对契约自己声明的postcondition:操作"返回成功"不等于
|
||
# "真的干成了",这里挡住的是那类最难查的静默失败(切没切到、抽壳没抽动)
|
||
try:
|
||
check_postcondition(
|
||
op_name, cap.contract.get("postcondition_check"), target_obj, result
|
||
)
|
||
except PostconditionError as e:
|
||
raise IRError(i, op_name, [str(e)])
|
||
|
||
op_id = op.get("id", f"op{i}")
|
||
context[op_id] = result
|
||
last_id = op_id
|
||
# target_id 也要存下来,report.json 的 operations 才能被完整还原成一份可重新执行的IR
|
||
# (用于②理解层的"参数化修改"场景:改一个尺寸重新生成,而不是整个零件重新描述一遍)
|
||
trace.append({"index": i, "op": op_name, "id": op_id, "target": target_id, "params": params})
|
||
|
||
final_id = ir.get("output", last_id)
|
||
if not isinstance(final_id, str) or final_id not in context:
|
||
raise IRError(-1, "output", ["UNKNOWN_ID: output 不存在"])
|
||
final = context[final_id]
|
||
errors = solid_errors(final, ir.get("expected_solid_count"))
|
||
if errors:
|
||
raise IRError(-1, "final", errors)
|
||
|
||
# 通用结构校验:不针对任何具体能力,对所有零件都生效。
|
||
# 之前好几个真实bug(环被自己的槽切断、该独立的环被意外焊死)都是靠事后人工导出来
|
||
# 数体积才发现的,系统自己完全没拦住——这里补上两条最基础的自动检查。
|
||
if not final.is_valid:
|
||
raise IRError(
|
||
len(ir["operations"]) - 1,
|
||
"final_validity_check",
|
||
["INVALID_GEOMETRY: 最终生成的实体几何无效(is_valid=False),"
|
||
"布尔运算可能产生了非法结果,请检查参数或换一种构造方式(比如先在2D轮廓上"
|
||
"处理再整体成型,而不是对两个已成型的3D曲面直接做布尔运算)"],
|
||
)
|
||
|
||
invalid_solids = [s for s in final.solids() if not s.is_valid]
|
||
if invalid_solids:
|
||
raise IRError(
|
||
len(ir["operations"]) - 1,
|
||
"solid_validity_check",
|
||
[f"INVALID_SOLID: 最终结果里有{len(invalid_solids)}个实体几何无效,可能是某个"
|
||
"特征(比如开槽)把某个部件切断或产生了自相交"],
|
||
)
|
||
|
||
expected_count = ir.get("expected_solid_count")
|
||
if isinstance(expected_count, str):
|
||
# 同样的"大模型把数字写成字符串"问题——之前真实出现过报错文案两边数字看起来
|
||
# 一样却仍判定不相等的诡异情况,根源就是这里 int(2) != "2" 类型不一致。
|
||
try:
|
||
expected_count = int(expected_count)
|
||
except ValueError:
|
||
expected_count = None
|
||
if expected_count is not None:
|
||
actual_count = len(final.solids())
|
||
if actual_count != expected_count:
|
||
raise IRError(
|
||
len(ir["operations"]) - 1,
|
||
"solid_count_check",
|
||
[f"SOLID_COUNT_MISMATCH: IR声明预期{expected_count}个独立实体,"
|
||
f"实际生成了{actual_count}个——如果预期是多个互不接触的独立实体(比如"
|
||
"多个能各自转动的环),说明有的部件之间距离/间隙没留够、意外融合到一起了;"
|
||
"如果预期是1个整体,说明本该焊接的部件之间没有真实体积重叠,只是贴合"],
|
||
)
|
||
|
||
# ⑤核验层:核对claims——把GPT在assumptions里声称做到的具体结构事实(孔真的打穿了、
|
||
# 轴向没理解反、该焊死的地方真有体积重叠、精确数字真被采纳)变成自动几何核验,
|
||
# 而不是像过去那样全靠人工对着截图/写一次性脚本才发现问题。claims是可选字段,
|
||
# 没有就跳过,不影响任何旧的IR。
|
||
claims = ir.get("claims")
|
||
if claims:
|
||
violations = check_claims(claims, context, trace)
|
||
if violations:
|
||
raise IRError(len(ir["operations"]) - 1, "claims_check", violations)
|
||
|
||
out_dir = Path(output_dir)
|
||
out_dir.mkdir(parents=True, exist_ok=True)
|
||
step_path = out_dir / "model.step"
|
||
stl_path = out_dir / "model.stl"
|
||
try:
|
||
export_check = export_verified(final, step_path, stl_path)
|
||
except ValueError as exc:
|
||
raise IRError(-1, "export", [str(exc)]) from exc
|
||
|
||
bbox = final.bounding_box()
|
||
return {
|
||
"part_name": ir.get("name", "part"),
|
||
"output_id": final_id,
|
||
"export_validation": export_check,
|
||
"operations": trace,
|
||
"volume_mm3": final.volume,
|
||
"bounding_box_mm": {
|
||
"min": [bbox.min.X, bbox.min.Y, bbox.min.Z],
|
||
"max": [bbox.max.X, bbox.max.Y, bbox.max.Z],
|
||
},
|
||
"step_file": str(step_path),
|
||
"stl_file": str(stl_path),
|
||
"expected_solid_count": ir.get("expected_solid_count"),
|
||
"claims": ir.get("claims", []),
|
||
}
|