Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1290a8bc54 | ||
|
|
2afea16005 | ||
|
|
6899a2977d | ||
|
|
05bcb3b2f5 | ||
|
|
8108a316b2 |
@@ -27,6 +27,8 @@ from typing import List
|
|||||||
VALID_UNITS: List[str] = [
|
VALID_UNITS: List[str] = [
|
||||||
"℃", "kPa", "MPa", "m³/h", "m3/h", "%", "kg", "t", "t/h", "m³", "m3",
|
"℃", "kPa", "MPa", "m³/h", "m3/h", "%", "kg", "t", "t/h", "m³", "m3",
|
||||||
"A", "V", "Hz", "kW", "kWh", "Pa", "bar", "mm", "L", "L/min", "m/s",
|
"A", "V", "Hz", "kW", "kWh", "Pa", "bar", "mm", "L", "L/min", "m/s",
|
||||||
|
# 树脂行业模板(templates/resin)扩展:搅拌转速 rpm / 离子交换容量 mmol/g
|
||||||
|
"rpm", "mmol/g",
|
||||||
]
|
]
|
||||||
|
|
||||||
# 合法数据类型集合
|
# 合法数据类型集合
|
||||||
|
|||||||
@@ -6,8 +6,6 @@
|
|||||||
|
|
||||||
| 文档 | 说明 | 版本 |
|
| 文档 | 说明 | 版本 |
|
||||||
|------|------|------|
|
|------|------|------|
|
||||||
| [用户手册.md](./用户手册.md) | **最终业务用户手册**(监控/优化/LLM 助手三类场景,面向工艺工程师/值班长/管理者) | v1.0 |
|
|
||||||
| [部署手册.md](./部署手册.md) | **运维/交付部署手册**(Helm 一键部署、后端切换、健康巡检、灰度回滚) | v1.0 |
|
|
||||||
| [产品设计文档_iAOP.md](./产品设计文档_iAOP.md) | **PRD 主文件**(开发依据) | v1.2 |
|
| [产品设计文档_iAOP.md](./产品设计文档_iAOP.md) | **PRD 主文件**(开发依据) | v1.2 |
|
||||||
| [产品设计文档_iAOP_对外评审.docx](./产品设计文档_iAOP_对外评审.docx) | 对外评审版(Word,含内嵌架构/流程/ER 图) | v1.2 |
|
| [产品设计文档_iAOP_对外评审.docx](./产品设计文档_iAOP_对外评审.docx) | 对外评审版(Word,含内嵌架构/流程/ER 图) | v1.2 |
|
||||||
| [产品设计评审_iAOP.pptx](./产品设计评审_iAOP.pptx) | 内部评审/汇报版幻灯片 | v1.2 |
|
| [产品设计评审_iAOP.pptx](./产品设计评审_iAOP.pptx) | 内部评审/汇报版幻灯片 | v1.2 |
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""用户手册 / 部署手册(issue #91)文档一致性检查。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 两份手册必备章节齐全;
|
|
||||||
2. 关键红线 / 验收关键词存在(PRD §5.6 / §7.7 / §9 NFR);
|
|
||||||
3. 跨文档引用与配套资产路径存在;
|
|
||||||
4. 角色画像 / 场景流关键词存在(PRD §2 角色画像)。
|
|
||||||
|
|
||||||
用法:python _check_user_deploy_manual.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
USER_DOC = os.path.join(HERE, "用户手册.md")
|
|
||||||
DEPLOY_DOC = os.path.join(HERE, "部署手册.md")
|
|
||||||
|
|
||||||
USER_SECTIONS = [
|
|
||||||
"## 1. 平台简介",
|
|
||||||
"## 2. 角色与权限(RBAC)",
|
|
||||||
"## 3. 登录",
|
|
||||||
"## 4. 场景 A:实时监控与告警处置",
|
|
||||||
"## 5. 场景 B:工艺优化",
|
|
||||||
"## 6. 场景 C:LLM 自然语言助手",
|
|
||||||
"## 7. 交接班报告",
|
|
||||||
"## 8. 常见问题(FAQ)",
|
|
||||||
]
|
|
||||||
|
|
||||||
DEPLOY_SECTIONS = [
|
|
||||||
"## 1. 部署目标与边界",
|
|
||||||
"## 2. 环境要求(前置条件)",
|
|
||||||
"## 3. 一键部署(Quick Start)",
|
|
||||||
"## 4. 配置点速查(values.yaml)",
|
|
||||||
"## 5. 健康巡检(可用性 ≥ 99.8%)",
|
|
||||||
"## 6. 灰度发布与回滚",
|
|
||||||
"## 7. 升级流程",
|
|
||||||
"## 8. 故障排查(SOP)",
|
|
||||||
]
|
|
||||||
|
|
||||||
USER_KEYWORDS = ["可溯源", "敏感度", "DLP", "交接班", "驾驶舱"]
|
|
||||||
DEPLOY_KEYWORDS = [
|
|
||||||
"inference.backend", # 后端可切换配置点
|
|
||||||
"nvidia-5090",
|
|
||||||
"ascend-910b",
|
|
||||||
"99.8%", # 可用性验收口径
|
|
||||||
"helm install",
|
|
||||||
"helm rollback",
|
|
||||||
]
|
|
||||||
|
|
||||||
# 必须存在的配套资产路径(相对仓库根)
|
|
||||||
ASSET_PATHS = [
|
|
||||||
"deploy/k8s/helm/iaop/README.md",
|
|
||||||
"deploy/k8s/helm/iaop/values.yaml",
|
|
||||||
"deploy/k8s/healthz/probe_availability.py",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
repo_root = os.path.dirname(HERE)
|
|
||||||
|
|
||||||
if not os.path.isfile(USER_DOC):
|
|
||||||
failures.append("用户手册不存在:用户手册.md")
|
|
||||||
if not os.path.isfile(DEPLOY_DOC):
|
|
||||||
failures.append("部署手册不存在:部署手册.md")
|
|
||||||
|
|
||||||
user_text = open(USER_DOC, "r", encoding="utf-8").read() if os.path.isfile(USER_DOC) else ""
|
|
||||||
deploy_text = open(DEPLOY_DOC, "r", encoding="utf-8").read() if os.path.isfile(DEPLOY_DOC) else ""
|
|
||||||
|
|
||||||
for sec in USER_SECTIONS:
|
|
||||||
if sec not in user_text:
|
|
||||||
failures.append(f"用户手册缺少章节:{sec}")
|
|
||||||
|
|
||||||
for sec in DEPLOY_SECTIONS:
|
|
||||||
if sec not in deploy_text:
|
|
||||||
failures.append(f"部署手册缺少章节:{sec}")
|
|
||||||
|
|
||||||
for kw in USER_KEYWORDS:
|
|
||||||
if kw not in user_text:
|
|
||||||
failures.append(f"用户手册缺少关键词:{kw}")
|
|
||||||
|
|
||||||
for kw in DEPLOY_KEYWORDS:
|
|
||||||
if kw not in deploy_text:
|
|
||||||
failures.append(f"部署手册缺少关键词:{kw}")
|
|
||||||
|
|
||||||
# 部署手册必须正确引用用户手册(跨文档链接)
|
|
||||||
if "用户手册.md" not in deploy_text:
|
|
||||||
failures.append("部署手册缺少对『用户手册』的引用链接")
|
|
||||||
|
|
||||||
for rel in ASSET_PATHS:
|
|
||||||
if not os.path.isfile(os.path.join(repo_root, *rel.split("/"))):
|
|
||||||
failures.append(f"配套资产缺失:{rel}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print("OK: 用户手册/部署手册 章节齐全、关键词与配套资产校验通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
-117
@@ -1,117 +0,0 @@
|
|||||||
# iAOP 用户手册(User Guide)
|
|
||||||
|
|
||||||
> 对应 issue #91「[M5] 用户手册/部署手册编写」,父 Issue #15(EPIC 跟踪),里程碑 iAOP v1.0 · Template-Ti 一期。
|
|
||||||
> 本手册面向 **最终业务用户**(工艺工程师 / 值班长 / 生产管理者),即 PRD §2 角色画像中的张工、李工、王主任。
|
|
||||||
> 部署 / 运维操作请见《[部署手册](./部署手册.md)》。
|
|
||||||
|
|
||||||
## 1. 平台简介
|
|
||||||
|
|
||||||
iAOP(云美工业 AI 优化平台)= **可配置、可复制的工业 AI 优化内核** + **按行业沉淀的行业模板**。
|
|
||||||
|
|
||||||
- **内核(iAOP-Core)**:采集 → 模型推理 → LLM 解释 → 驾驶舱呈现,一次建设、多行业复用;
|
|
||||||
- **行业模板**:氯化车间/海绵钛(Template-Ti)、吸附树脂(Template-Resin)等,决定 ~90% 落地工作量。
|
|
||||||
|
|
||||||
你日常接触的是**配置化驾驶舱**(Web / 移动端)与 **LLM 自然语言助手**。本手册教你如何用它们完成监控、优化、辅助三类场景。
|
|
||||||
|
|
||||||
## 2. 角色与权限(RBAC)
|
|
||||||
|
|
||||||
| 角色 | 主要入口 | 权限 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 工艺工程师 / 值班长(张工、李工) | 驾驶舱、LLM 助手 | 查看实时数据 / 告警 / 趋势;发起查询;接收优化建议并 review |
|
|
||||||
| 生产管理者(王主任) | 驾驶舱大屏、移动端助手 | 查看 KPI / 趋势 / 报表;接收交接班报告 |
|
|
||||||
|
|
||||||
> 配置台(模板配置台 Template Console)三级权限 Viewer / Editor / Publisher 面向**实施/行业工程师**,普通业务用户无需使用,详见《模板开发手册》。
|
|
||||||
|
|
||||||
## 3. 登录
|
|
||||||
|
|
||||||
1. 浏览器打开驾驶舱地址(由实施提供,形如 `http://iaop.example.com`);
|
|
||||||
2. 输入管理员分配的账号密码登录;
|
|
||||||
3. 登录后默认进入「实时监控」驾驶舱。
|
|
||||||
|
|
||||||
> 移动端:扫描实施提供的二维码,使用同一账号登录(只读模式,支持查看告警 / 报表 / 推送)。
|
|
||||||
|
|
||||||
## 4. 场景 A:实时监控与告警处置
|
|
||||||
|
|
||||||
**目标**:及时发现工艺异常并了解原因。
|
|
||||||
|
|
||||||
1. 进入驾驶舱「实时监控」页:
|
|
||||||
- **四状态工艺流程视图**:直观展示氯化/还原等工序当前状态(绿/黄/红);
|
|
||||||
- **实时趋势**:关键点位(如 `CLF-01.TEMP`)实时曲线;
|
|
||||||
- **KPI 卡片**:核心指标(如 `Ti_purity` 海绵钛纯度);
|
|
||||||
- **告警面板**:当前未确认告警列表。
|
|
||||||
2. 当出现红色告警(如炉层温度异常):
|
|
||||||
- 点击告警条目 → 系统展示 LLM 生成的**报警解释**(原因 + 处置建议,附引用依据,可溯源);
|
|
||||||
- 值班长确认后,按建议处置或转交相关人员;
|
|
||||||
- 处置完成后在告警面板标注「已确认 / 已处置」。
|
|
||||||
|
|
||||||
> 不使用 iAOP 时:靠人工盯趋势、微信群喊人,平均 20–40 分钟才发现,且无根因解释。iAOP 将发现到解释压缩到分钟级。
|
|
||||||
|
|
||||||
## 5. 场景 B:工艺优化(配方 / 参数建议)
|
|
||||||
|
|
||||||
**目标**:给定质量目标,让模型给出参数建议,review 后下发。
|
|
||||||
|
|
||||||
1. 进入「优化建议」页(一期质量预测 + 炉层杂质预警上线后,二期配方优化 / 跨工序寻优逐步开放);
|
|
||||||
2. 输入或确认本批次质量目标(如目标纯度、约束条件);
|
|
||||||
3. 系统给出**可溯源优化建议**:
|
|
||||||
- 建议参数(决策变量取值);
|
|
||||||
- 目标函数值与约束满足情况;
|
|
||||||
- 跨工序权重与依据(引用上游 TiCl₄ 指标 → 下游海绵钛寻优);
|
|
||||||
4. 工艺工程师(李工)**review 建议**,确认后下发 DCS;
|
|
||||||
5. 实际质量反馈回流,持续训练模型。
|
|
||||||
|
|
||||||
> 建议为「辅助决策」,高利害输出低于信度阈值时系统会提示「需人工确认」。
|
|
||||||
|
|
||||||
## 6. 场景 C:LLM 自然语言助手
|
|
||||||
|
|
||||||
**目标**:用自然语言提问,获得带引用的答案 / 报表。
|
|
||||||
|
|
||||||
支持四类能力:
|
|
||||||
|
|
||||||
| 能力 | 示例提问 | 说明 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| NL 工艺查询 | 「最近一周 CLF-01 温度超标几次?」 | NL→SQL/API,返回数据 + 来源 |
|
|
||||||
| 报警解释 | (点击告警自动触发) | 原因 + 处置建议 + 引用 |
|
|
||||||
| 交接班报告 | (班次结束自动生成) | 汇总关键事件/能耗/待办,≤ 2 分钟 |
|
|
||||||
| 配方 RAG 问答 | 「国标对 XX 指标的要求?」 | 命中领域知识库,强制引用溯源 |
|
|
||||||
|
|
||||||
**安全说明**:平台内置**敏感度分级路由**(准确率 ≥ 96.5%)+ **DLP 防泄漏**(拦截率 100%):敏感/核心问题在本地 70B 模型闭环,脱敏/通用问题走云端,结果均附引用来源,可追溯。
|
|
||||||
|
|
||||||
## 7. 交接班报告
|
|
||||||
|
|
||||||
每班次结束时,系统自动生成交接班报告(汇总关键事件、能耗、待办),并推送给下一班。
|
|
||||||
|
|
||||||
- 查看入口:驾驶舱「交接班」页 / 移动端推送;
|
|
||||||
- 报告可导出(PDF);
|
|
||||||
- 历史报告在「报告归档」中可检索。
|
|
||||||
|
|
||||||
> 不使用 iAOP 时:手写记录本 + 口头交代,遗漏率约 15%,夜班回溯困难。
|
|
||||||
|
|
||||||
## 8. 常见问题(FAQ)
|
|
||||||
|
|
||||||
**Q1:建议 / 解释能否给出依据?**
|
|
||||||
A:所有 LLM 输出强制引用溯源(返回命中文档片段 + 来源),可点击查看原文。
|
|
||||||
|
|
||||||
**Q2:数据准吗?多久更新?**
|
|
||||||
A:采集 P99 ≤ 1.8s,驾驶舱数据准实时刷新;批量写入 5k 点 / 100ms。
|
|
||||||
|
|
||||||
**Q3:看不到某个功能?**
|
|
||||||
A:功能按行业模板与里程碑分批开放(一期:监控+预警+LLM;二期:优化寻优)。确认你的模板版本与权限。
|
|
||||||
|
|
||||||
**Q4:发现数据异常 / 误报怎么办?**
|
|
||||||
A:在告警面板标注「误报」并留言,系统回流用于模型迭代;紧急情况联系运维(见《部署手册》§8)。
|
|
||||||
|
|
||||||
## 9. 移动端使用
|
|
||||||
|
|
||||||
- **只读模式**:查看驾驶舱、接收告警 / 报告推送;
|
|
||||||
- 登录账号与 Web 一致;
|
|
||||||
- 支持 ≥ 200 并发只读用户(PRD §9 NFR)。
|
|
||||||
|
|
||||||
## 10. 帮助与反馈
|
|
||||||
|
|
||||||
- 使用问题:联系工艺主管或实施工程师;
|
|
||||||
- 功能建议:在配置台「反馈」入口提交(如已开放);
|
|
||||||
- 故障:参考《部署手册》§8 故障排查 SOP,或联系运维 bot_dev。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**维护**:本文档随行业模板与功能开放节奏更新。当前对应 Template-Ti 一期(氯化车间/海绵钛)。
|
|
||||||
-178
@@ -1,178 +0,0 @@
|
|||||||
# iAOP 部署手册(Deployment Guide)
|
|
||||||
|
|
||||||
> 对应 issue #91「[M5] 用户手册/部署手册编写」,父 Issue #15(EPIC 跟踪),里程碑 iAOP v1.0 · Template-Ti 一期。
|
|
||||||
> 配套 PRD §5.6「⑥ 部署底座」与 `deploy/k8s/helm/iaop/`。本手册面向 **运维/交付工程师(bot_dev、现场运维)**。
|
|
||||||
> 业务最终用户的日常使用请见《[用户手册](./用户手册.md)》。
|
|
||||||
|
|
||||||
## 1. 部署目标与边界
|
|
||||||
|
|
||||||
iAOP 采用「内核 + 行业模板」分层架构,部署目标:
|
|
||||||
|
|
||||||
- **内核(iAOP-Core)**:6 大模块(采集总线 / 模型框架 / LLM 网关 / 配置化驾驶舱 / 部署底座 / 模板配置台)一次部署,多行业复用;
|
|
||||||
- **行业模板(iAOP-Template)**:作为「模板资产包」随内核发布,切换行业仅改配置不改码。
|
|
||||||
|
|
||||||
**验收口径(PRD §5.6 / §10)**:内核 + 模板一键 Helm 部署;昇腾后端切换仅需适配层,不改业务代码;可用性 ≥ 99.8%。
|
|
||||||
|
|
||||||
**本手册覆盖范围**:生产 / 验收环境部署、推理后端切换、健康巡检、灰度与回滚。
|
|
||||||
**不覆盖**:商务定价、第三方 License 采购、单厂实施方案(由交付阶段单独产出)。
|
|
||||||
|
|
||||||
## 2. 环境要求(前置条件)
|
|
||||||
|
|
||||||
### 2.1 软件依赖
|
|
||||||
|
|
||||||
| 组件 | 版本 | 说明 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| Kubernetes | ≥ 1.26 | 生产集群(建议 3 控制面 + N 工作节点) |
|
|
||||||
| Helm | ≥ 3.12 | 一键部署工具 |
|
|
||||||
| kubectl | 与集群匹配 | 集群操作 |
|
|
||||||
| ArgoCD(可选) | ≥ 2.7 | GitOps 灰度发布 |
|
|
||||||
| Python | ≥ 3.10 | 探针 / 离线校验脚本运行时 |
|
|
||||||
| 容器运行时 | containerd ≥ 1.7 | 集群默认即可 |
|
|
||||||
|
|
||||||
### 2.2 推理后端硬件(二选一,PRD §5.6)
|
|
||||||
|
|
||||||
| 后端 (`inference.backend`) | 设备 (`inference.device`) | 运行时 | 驱动要求 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| `gpu` | `nvidia-5090` | vllm / triton | NVIDIA Driver + nvidia-container-toolkit |
|
|
||||||
| `npu` | `ascend-910b` / `ascend-310p` | mindie / onnx-ascend | CANN 工具链(见 `inference.cannVersion`) |
|
|
||||||
|
|
||||||
> 切换后端 = 改 `values.yaml` 的 `inference.backend` / `inference.device`,业务代码零改动(差异收敛在 `core/inference-backend/` 适配层)。
|
|
||||||
|
|
||||||
### 2.3 资源配额基线(默认 values,可调)
|
|
||||||
|
|
||||||
| 资源 | requests | limits |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| CPU | 2 core | 8 core |
|
|
||||||
| 内存 | 8 Gi | 32 Gi |
|
|
||||||
| 模型权重存储 | 100 Gi(PVC) | — |
|
|
||||||
|
|
||||||
> 生产环境建议启用 HPA(`autoscaling.enabled: true`,min 2 / max 8,CPU 70%)。
|
|
||||||
|
|
||||||
## 3. 一键部署(Quick Start)
|
|
||||||
|
|
||||||
### 3.1 部署内核 + 模板(默认 GPU 后端)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1) 命名空间(一次性)
|
|
||||||
kubectl create namespace iaop
|
|
||||||
|
|
||||||
# 2) Helm 一键部署(Chart 在仓库 deploy/k8s/helm/iaop/)
|
|
||||||
helm install iaop deploy/k8s/helm/iaop \
|
|
||||||
-n iaop \
|
|
||||||
--set inference.backend=gpu \
|
|
||||||
--set inference.device=nvidia-5090
|
|
||||||
|
|
||||||
# 3) 验证
|
|
||||||
kubectl -n iaop rollout status deployment/iaop-inference
|
|
||||||
kubectl -n iaop get svc iaop-inference # ClusterIP :8000
|
|
||||||
```
|
|
||||||
|
|
||||||
部署成功标志:Deployment 就绪、`/health` 返回 200(见 §5 健康巡检)。
|
|
||||||
|
|
||||||
### 3.2 切换为华为昇腾 NPU 后端
|
|
||||||
|
|
||||||
```bash
|
|
||||||
helm upgrade iaop deploy/k8s/helm/iaop -n iaop \
|
|
||||||
--set inference.backend=npu \
|
|
||||||
--set inference.device=ascend-910b \
|
|
||||||
--set inference.cannVersion=8.0
|
|
||||||
```
|
|
||||||
|
|
||||||
切换行为(模板自动处理,无需手工干预):
|
|
||||||
|
|
||||||
- `backend-configmap.yaml` 渲染对应后端适配层配置(npu 追加 `cann_version`);
|
|
||||||
- `deployment.yaml` 的 nodeSelector 自动切到 `ascend.com/npu=true`(GPU 为 `nvidia.com/gpu=true`);
|
|
||||||
- Pod 标签标注 `iaop.ai/inference-backend`,便于灰度与监控分流。
|
|
||||||
|
|
||||||
### 3.3 开启域名入口(可选)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
helm upgrade iaop deploy/k8s/helm/iaop -n iaop \
|
|
||||||
--set ingress.enabled=true \
|
|
||||||
--set ingress.host=iaop.example.com \
|
|
||||||
--set ingress.className=nginx
|
|
||||||
```
|
|
||||||
|
|
||||||
## 4. 配置点速查(values.yaml)
|
|
||||||
|
|
||||||
完整配置见 `deploy/k8s/helm/iaop/values.yaml`,常用项:
|
|
||||||
|
|
||||||
| 配置点 | values 路径 | 默认 | 说明 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| 推理后端 | `inference.backend` | `gpu` | `gpu` / `npu` |
|
|
||||||
| 模型名 | `inference.model` | `iaop-ti-cl4-v1` | 随模板切换 |
|
|
||||||
| 副本数 | `replicaCount` | `2` | 生产 ≥ 2 |
|
|
||||||
| 滚动策略 | `rollingUpdate` | `maxUnavailable:0, maxSurge:1` | 灰度发布策略 |
|
|
||||||
| HPA | `autoscaling.enabled` | `false` | 生产建议 `true` |
|
|
||||||
| 资源配额 | `resources.requests/limits` | 见 §2.3 | CPU/内存 |
|
|
||||||
| 存储 | `storage.size` | `100Gi` | 模型权重持久卷 |
|
|
||||||
| 域名 | `ingress.host` | — | 可选 |
|
|
||||||
|
|
||||||
**多环境分离**:用 `values.dev.yaml` / `values.prod.yaml` 覆盖,例如:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
helm upgrade iaop deploy/k8s/helm/iaop -n iaop \
|
|
||||||
-f deploy/k8s/helm/iaop/values.prod.yaml
|
|
||||||
```
|
|
||||||
|
|
||||||
## 5. 健康巡检(可用性 ≥ 99.8%)
|
|
||||||
|
|
||||||
部署底座提供可用性探针(EPIC #8 子任务 #61):
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 轮询 60 轮(每 1s),目标可用率 99.8%
|
|
||||||
python deploy/k8s/healthz/probe_availability.py \
|
|
||||||
--endpoints http://<iaop-inference>:8000 \
|
|
||||||
--rounds 60 --interval 1 --target 0.998
|
|
||||||
```
|
|
||||||
|
|
||||||
- 退出码 `0` = 达标(PASS);`1` = 低于目标(FAIL);
|
|
||||||
- 建议以 K8s CronJob 定时执行,FAIL 时触发告警(接 Prometheus / 企业微信)。
|
|
||||||
|
|
||||||
## 6. 灰度发布与回滚
|
|
||||||
|
|
||||||
### 6.1 ArgoCD 灰度(推荐)
|
|
||||||
|
|
||||||
Chart 已内置滚动策略(`maxUnavailable: 0, maxSurge: 1`),配合 ArgoCD 可实现 GitOps 灰度:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1) Chart 纳入 Git 仓库,ArgoCD Application 指向该仓库
|
|
||||||
# 2) 升级 = 改 values 并提交,ArgoCD 自动同步 + 滚动
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6.2 Helm 回滚
|
|
||||||
|
|
||||||
```bash
|
|
||||||
helm history iaop -n iaop # 查看修订历史
|
|
||||||
helm rollback iaop <REVISION> -n iaop # 回滚到上一版本
|
|
||||||
```
|
|
||||||
|
|
||||||
> 模板资产包发布同样走「校验 → 灰度 → 回滚点」流程(PRD §5.7 模板配置台),配置台支持版本 diff 与一键回滚。
|
|
||||||
|
|
||||||
## 7. 升级流程
|
|
||||||
|
|
||||||
1. **预演**:在 dev 命名空间用 `values.dev.yaml` 部署,跑通探针与冒烟用例;
|
|
||||||
2. **生产灰度**:`helm upgrade`,观察 `rollout status` 与探针可用率;
|
|
||||||
3. **质保观察**:上线后进入 1 个月质保观察期(PRD §7.7),监控 NFR 指标(可用性 ≥ 99.8% / P99 ≤ 1.8s)。
|
|
||||||
|
|
||||||
## 8. 故障排查(SOP)
|
|
||||||
|
|
||||||
| 现象 | 排查步骤 |
|
|
||||||
| --- | --- |
|
|
||||||
| Deployment 不就绪 | `kubectl describe pod` 看 nodeSelector / 镜像 / 资源;GPU/NPU 驱动是否就绪 |
|
|
||||||
| `/health` 不通 | `kubectl logs`;确认推理后端适配层加载(`core/inference-backend/`) |
|
|
||||||
| 可用率 < 99.8% | 看探针 FAIL 轮次分布;HPA 是否触发;节点资源是否打满 |
|
|
||||||
| 推理慢 | 确认 `inference.runtime` 与硬件匹配;检查 `maxTokens/temperature` |
|
|
||||||
|
|
||||||
## 9. 交付物清单(对应 PRD §7.7)
|
|
||||||
|
|
||||||
部署阶段交付:
|
|
||||||
|
|
||||||
- [ ] 内核 + 模板 Helm 一键部署通过(GPU / NPU 各验一次);
|
|
||||||
- [ ] 可用性探针连续达标(≥ 99.8%);
|
|
||||||
- [ ] 灰度 + 回滚演练通过;
|
|
||||||
- [ ] 故障排查 SOP(本文 §8)就绪。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
**维护**:本文档随部署底座(`deploy/`)演进,版本与 Chart `appVersion` 对齐。模板资产打包发布见 `templates/<行业>/version.yaml`。
|
|
||||||
@@ -30,7 +30,7 @@ templates/resin/
|
|||||||
|
|
||||||
| 资产 | 对应子任务 | 说明 |
|
| 资产 | 对应子任务 | 说明 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `point_dict.resin.csv` | #82 抽取树脂点位字典 | 反应釜/交联釜温度压力液位、搅拌转速、引发剂滴加速率、原料(苯乙烯/二乙烯苯)流量、称重/能源/蒸汽点位,协议覆盖 opcua/s7/weighing/energy/manual |
|
| `point_dict.resin.csv` | #82 抽取树脂点位字典 | 反应釜/交联釜温度压力液位、搅拌转速、引发剂滴加速率、原料(苯乙烯/二乙烯苯)流量、称重/能源/蒸汽点位,协议覆盖 opcua/s7/modbus/weighing/energy(人工录入质检值经 Modbus holding 寄存器),量纲/协议与内核 schema 完全对齐,`core/edge-gateway/point_dict/validator.py` 校验通过 |
|
||||||
| `kb.resin.template.yaml` | #83 树脂 RAG 知识库导出 | 吸附树脂合成工艺规范、异常处置 SOP、GB/T 离子交换树脂标准(5475/8144/8330) |
|
| `kb.resin.template.yaml` | #83 树脂 RAG 知识库导出 | 吸附树脂合成工艺规范、异常处置 SOP、GB/T 离子交换树脂标准(5475/8144/8330) |
|
||||||
| `cockpit.resin.yaml` | #84 树脂驾驶舱布局提取 | 四状态工艺视图(合成→交联→洗涤→干燥)、温度/转速趋势、交换容量/交联度/批产率/单吨能耗 KPI、告警面板、NL 查询入口 |
|
| `cockpit.resin.yaml` | #84 树脂驾驶舱布局提取 | 四状态工艺视图(合成→交联→洗涤→干燥)、温度/转速趋势、交换容量/交联度/批产率/单吨能耗 KPI、告警面板、NL 查询入口 |
|
||||||
| `version.yaml` | #85 树脂模板打包与版本发布 | 模板元信息 + 资产清单 + 基线(已交付化工AI平台) |
|
| `version.yaml` | #85 树脂模板打包与版本发布 | 模板元信息 + 资产清单 + 基线(已交付化工AI平台) |
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ EXPECTED_COLUMNS = [
|
|||||||
"sampleRate", "qualityCode", "opcNode", "protocol",
|
"sampleRate", "qualityCode", "opcNode", "protocol",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
# 对齐内核 schema.VALID_PROTOCOLS / VALID_UNITS(含树脂模板扩展量纲 rpm / mmol/g)
|
||||||
|
VALID_PROTOCOLS = {"opcua", "s7", "modbus", "weighing", "energy", "simulator"}
|
||||||
|
VALID_UNITS = {
|
||||||
|
"℃", "kPa", "MPa", "m³/h", "m3/h", "%", "kg", "t", "t/h", "m³", "m3",
|
||||||
|
"A", "V", "Hz", "kW", "kWh", "Pa", "bar", "mm", "L", "L/min", "m/s",
|
||||||
|
"rpm", "mmol/g",
|
||||||
|
}
|
||||||
|
|
||||||
# PRD 5.5 iAOP-cockpit-layout-v1 允许的 widget 类型
|
# PRD 5.5 iAOP-cockpit-layout-v1 允许的 widget 类型
|
||||||
ALLOWED_WIDGETS = {
|
ALLOWED_WIDGETS = {
|
||||||
"process_view", "trend", "kpi_card", "alarm_panel", "nl_query",
|
"process_view", "trend", "kpi_card", "alarm_panel", "nl_query",
|
||||||
@@ -49,6 +57,12 @@ def main() -> int:
|
|||||||
for i, row in enumerate(rows[1:], 2):
|
for i, row in enumerate(rows[1:], 2):
|
||||||
if len(row) != len(EXPECTED_COLUMNS):
|
if len(row) != len(EXPECTED_COLUMNS):
|
||||||
failures.append(f"CSV 第 {i} 行列数异常:{len(row)}")
|
failures.append(f"CSV 第 {i} 行列数异常:{len(row)}")
|
||||||
|
continue
|
||||||
|
unit, protocol = row[3].strip(), row[8].strip()
|
||||||
|
if unit not in VALID_UNITS:
|
||||||
|
failures.append(f"CSV 第 {i} 行非法量纲: '{unit}'(对齐内核 schema.VALID_UNITS)")
|
||||||
|
if protocol and protocol not in VALID_PROTOCOLS:
|
||||||
|
failures.append(f"CSV 第 {i} 行非法协议: '{protocol}'(对齐内核 schema.VALID_PROTOCOLS)")
|
||||||
|
|
||||||
# 2) YAML 资产可解析
|
# 2) YAML 资产可解析
|
||||||
for rel in ("rag-kb/kb.resin.template.yaml",
|
for rel in ("rag-kb/kb.resin.template.yaml",
|
||||||
@@ -58,11 +72,11 @@ def main() -> int:
|
|||||||
with open(path, "r", encoding="utf-8") as fh:
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
yaml.safe_load(fh)
|
yaml.safe_load(fh)
|
||||||
|
|
||||||
# 3) version.yaml assets 清单存在
|
# 3) version.yaml assets 清单存在(支持文件与目录条目)
|
||||||
with open(os.path.join(HERE, "version.yaml"), "r", encoding="utf-8") as fh:
|
with open(os.path.join(HERE, "version.yaml"), "r", encoding="utf-8") as fh:
|
||||||
version = yaml.safe_load(fh)
|
version = yaml.safe_load(fh)
|
||||||
for rel in version.get("assets", []):
|
for rel in version.get("assets", []):
|
||||||
if not os.path.isfile(os.path.join(HERE, rel)):
|
if not os.path.exists(os.path.join(HERE, rel)):
|
||||||
failures.append(f"version.yaml 声明资产缺失:{rel}")
|
failures.append(f"version.yaml 声明资产缺失:{rel}")
|
||||||
|
|
||||||
# 4) 驾驶舱布局 widget 类型合法
|
# 4) 驾驶舱布局 widget 类型合法
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ R-801,R-801.DOSAGE,引发剂滴加速率,L/min,float,1000,true,ns=2;s=R801.Dosag
|
|||||||
R-802,R-802.TEMP,交联釜温度,℃,float,1000,true,ns=2;s=R802.Temp,opcua
|
R-802,R-802.TEMP,交联釜温度,℃,float,1000,true,ns=2;s=R802.Temp,opcua
|
||||||
R-802,R-802.PRES,交联釜压力,kPa,float,1000,true,ns=2;s=R802.Pres,opcua
|
R-802,R-802.PRES,交联釜压力,kPa,float,1000,true,ns=2;s=R802.Pres,opcua
|
||||||
R-802,R-802.LEVEL,交联釜液位,%,float,1000,true,ns=2;s=R802.Level,opcua
|
R-802,R-802.LEVEL,交联釜液位,%,float,1000,true,ns=2;s=R802.Level,opcua
|
||||||
X-801,X-801.CROSS,交联度,%,float,60000,true,holding:40021,manual
|
X-801,X-801.CROSS,交联度,%,float,60000,true,holding:40021,modbus
|
||||||
X-801,X-801.EXC,交换容量,mmol/g,float,60000,true,holding:40022,manual
|
X-801,X-801.EXC,交换容量,mmol/g,float,60000,true,holding:40022,modbus
|
||||||
ST-01,ST-01.FLOW,苯乙烯流量,m3/h,float,1000,true,ns=2;s=ST.Flow,opcua
|
ST-01,ST-01.FLOW,苯乙烯流量,m3/h,float,1000,true,ns=2;s=ST.Flow,opcua
|
||||||
ST-01,ST-01.TANK,苯乙烯储罐液位,%,float,1000,true,ns=2;s=ST.Tank,opcua
|
ST-01,ST-01.TANK,苯乙烯储罐液位,%,float,1000,true,ns=2;s=ST.Tank,opcua
|
||||||
DVB-01,DVB-01.FLOW,二乙烯苯流量,m3/h,float,1000,true,ns=2;s=DVB.Flow,opcua
|
DVB-01,DVB-01.FLOW,二乙烯苯流量,m3/h,float,1000,true,ns=2;s=DVB.Flow,opcua
|
||||||
|
|||||||
|
@@ -0,0 +1,6 @@
|
|||||||
|
# GB/T 5475 离子交换树脂取样方法
|
||||||
|
|
||||||
|
- 规定离子交换树脂产品取样方法:从批中按规定数量抽取样品。
|
||||||
|
- 取样要求代表性:不同包装单元均匀取样,混合后缩分。
|
||||||
|
- 样品量:每批取样量按标准规定,样品密封保存并标识批次。
|
||||||
|
- 取样记录:批次号、取样时间、取样人、样品编号(对齐 sample_id)。
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# GB/T 8144 阳离子交换树脂交换容量测定方法
|
||||||
|
|
||||||
|
- 规定阳离子交换树脂交换容量(mmol/g)测定方法。
|
||||||
|
- 原理:树脂经酸/碱转型后,用标准溶液滴定测定交换容量。
|
||||||
|
- 结果用于质量分级:交换容量 ≥ 规定值(如 ≥ 4.2 mmol/g)为合格品。
|
||||||
|
- 测定结果按批次录入 LIMS(tag_id: LIMS.ExchangeCapacity),供质量预测模型训练。
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# GB/T 8330 离子交换树脂湿真密度测定方法
|
||||||
|
|
||||||
|
- 规定离子交换树脂湿真密度测定方法(比重瓶法)。
|
||||||
|
- 湿真密度反映树脂交联度与孔结构,与交换容量、强度相关。
|
||||||
|
- 测定条件:恒温(25℃)、湿态样品、排除气泡后称量。
|
||||||
|
- 结果记录:按批次录入,作为工艺优化与质量追溯的辅助指标。
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# 交接班报告生成规范
|
||||||
|
|
||||||
|
- 交接班报告须包含:生产概况、设备运行状态、异常与处置、安全注意事项、待办事项。
|
||||||
|
- 异常事项必须标注发生时间、处理人与处置结果。
|
||||||
|
- 待办事项需明确责任人与期望完成时间。
|
||||||
|
- 每班次结束前 30 分钟生成,当班班长审核后交下一班。
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# 交联度超标处置流程
|
||||||
|
|
||||||
|
1. 化验确认交联度超标(相对配方设计值偏差 > 5%)后,立即隔离该批树脂。
|
||||||
|
2. 通知当班班长与质检科,暂停同一配方后续批次投料。
|
||||||
|
3. 原因排查:DVB 计量偏差、搅拌不均、温度曲线漂移。
|
||||||
|
4. 处置选项:回用(与低交联度批次调配)或降级(非标用途),由 QE 评审放行。
|
||||||
|
5. 处置结果录入批次记录,并更新配方/工艺参数优化建议。
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# 吸附树脂合成工艺规范
|
||||||
|
|
||||||
|
- 吸附树脂系列:ASC / ASD / HPR / ACD,采用悬浮聚合法,间歇/配方驱动生产。
|
||||||
|
- 主要单体:苯乙烯(ST)+ 交联剂二乙烯苯(DVB),按配方比例投料。
|
||||||
|
- 关键工艺参数:聚合温度 70–90℃,引发剂滴加速率按配方设定,搅拌转速 100–300 rpm。
|
||||||
|
- 交联度(DVB 含量)直接影响树脂机械强度与交换容量,须按批次记录。
|
||||||
|
- 生产批次按 batch_id 追踪,聚合时间 8–12 小时,出料后水洗、筛分。
|
||||||
|
- 涉及车间:802(合成)、803(交联)、804(洗涤干燥),配污水/纯水/能源公用工程。
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# 树脂合成异常处置SOP
|
||||||
|
|
||||||
|
- SOP-R-001:釜温超上限(>95℃)→ 立即停引发剂滴加、加大冷却水,10 分钟未回落按紧急排料流程。
|
||||||
|
- SOP-R-002:釜压异常升高 → 停止加热、检查放空阀,联系仪表检修。
|
||||||
|
- SOP-R-003:搅拌故障 → 降速至停止,启用备用搅拌(如有),未恢复则终止本批。
|
||||||
|
- SOP-R-004:交联度超标(>设计值 15%)→ 该批隔离评审,按 QE 决定回用或降级。
|
||||||
|
- 所有异常必须记录发生时间、处理人、处置措施与结果,纳入交接班报告。
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# 离子交换树脂生产操作手册
|
||||||
|
|
||||||
|
- 开机前确认:原料计量罐、反应釜密封、加热/冷却系统、尾气处理正常。
|
||||||
|
- 投料顺序:先加去离子水与分散剂,再按配方加入苯乙烯/二乙烯苯与引发剂。
|
||||||
|
- 反应期间每 30 分钟记录一次釜温、釜压、搅拌转速。
|
||||||
|
- 聚合完成判断:釜温回落且无明显放热,取样测交联度。
|
||||||
|
- 洗涤:去离子水洗至 pH 中性;干燥:60–80℃ 流化干燥至含水率达标。
|
||||||
|
- 停机:关闭加热与搅拌,釜内残余物料按危废流程处理。
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""树脂 RAG 知识库导出加载器 —— issue #83。
|
||||||
|
|
||||||
|
把已交付化工新材料AI平台(吸附树脂)的领域知识库**导出为模板资产**
|
||||||
|
(`documents/*.md`),并提供与 `kb.resin.template.yaml` 清单一致的加载器:
|
||||||
|
|
||||||
|
- `resin_kb_loader(title)`:标题 → 文档文本(对齐 rag-kb 的 loader 约定,
|
||||||
|
可直接用于 `RagKnowledgeBase.from_template_config(..., loader=resin_kb_loader)`);
|
||||||
|
- `validate_export()`:校验 kb 清单声明的文档均有对应文件且非空
|
||||||
|
(导出完整性检查,防止清单与文档漂移)。
|
||||||
|
|
||||||
|
标题规范化:`GB/T 5475 ...` → 文件名 `GB-T-5475 ....md`(`/` 不允许出现在文件名)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
#: 知识库配置资产(与模板清单同目录)
|
||||||
|
DEFAULT_KB_CONFIG = os.path.join(
|
||||||
|
os.path.dirname(os.path.abspath(__file__)), "kb.resin.template.yaml")
|
||||||
|
|
||||||
|
|
||||||
|
def resin_documents_dir() -> str:
|
||||||
|
"""文档集目录(documents/)。"""
|
||||||
|
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||||
|
"documents")
|
||||||
|
|
||||||
|
|
||||||
|
def _doc_path(title: str) -> str:
|
||||||
|
"""标题 → 文档文件路径(规范化:/ 与空格 → -,对齐导出文件名)。"""
|
||||||
|
safe = title.replace("/", "-").replace(" ", "-")
|
||||||
|
return os.path.join(resin_documents_dir(), f"{safe}.md")
|
||||||
|
|
||||||
|
|
||||||
|
def resin_kb_loader(title: str) -> str:
|
||||||
|
"""按标题返回文档文本(找不到返回空串,与 rag-kb loader 约定一致)。"""
|
||||||
|
path = _doc_path(title)
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
return ""
|
||||||
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
|
return fh.read()
|
||||||
|
|
||||||
|
|
||||||
|
def load_kb_config(kb_config_path: str = DEFAULT_KB_CONFIG) -> dict:
|
||||||
|
"""加载树脂知识库配置资产。"""
|
||||||
|
with open(kb_config_path, "r", encoding="utf-8") as fh:
|
||||||
|
return yaml.safe_load(fh) or {}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_export(kb_config_path: str = DEFAULT_KB_CONFIG) -> List[str]:
|
||||||
|
"""校验导出完整性:清单声明的文档均有文件且非空。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
缺失/为空的问题列表(空 = 导出完整)。
|
||||||
|
"""
|
||||||
|
problems: List[str] = []
|
||||||
|
raw = load_kb_config(kb_config_path)
|
||||||
|
for src in raw.get("sources", []):
|
||||||
|
kind = src.get("kind")
|
||||||
|
for doc in src.get("documents", []):
|
||||||
|
text = resin_kb_loader(doc)
|
||||||
|
if not text:
|
||||||
|
problems.append(f"[{kind}] 文档缺失或为空: {doc}")
|
||||||
|
return problems
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""树脂 RAG 知识库导出测试(issue #83)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. kb.resin.template.yaml 清单声明的 9 篇文档全部导出且非空(validate_export);
|
||||||
|
2. resin_kb_loader 按标题返回文本(含 GB/T 标题规范化);
|
||||||
|
3. loader 可直接用于 RagKnowledgeBase(from_template_config + loader);
|
||||||
|
4. 未知标题 → 空串。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
_RAGKB_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, _RAGKB_DIR)
|
||||||
|
from loader import ( # noqa: E402
|
||||||
|
DEFAULT_KB_CONFIG,
|
||||||
|
resin_kb_loader,
|
||||||
|
validate_export,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestExportCompleteness(unittest.TestCase):
|
||||||
|
"""导出完整性:清单 ↔ 文档文件一致。"""
|
||||||
|
|
||||||
|
def test_all_listed_documents_exported(self):
|
||||||
|
problems = validate_export()
|
||||||
|
self.assertEqual(problems, [], f"导出不完整: {problems}")
|
||||||
|
|
||||||
|
def test_document_count(self):
|
||||||
|
docs = os.listdir(os.path.join(_RAGKB_DIR, "documents"))
|
||||||
|
self.assertEqual(len(docs), 8)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLoader(unittest.TestCase):
|
||||||
|
"""加载器行为。"""
|
||||||
|
|
||||||
|
def test_process_doc(self):
|
||||||
|
text = resin_kb_loader("吸附树脂合成工艺规范")
|
||||||
|
self.assertIn("悬浮聚合法", text)
|
||||||
|
|
||||||
|
def test_gbt_title_normalization(self):
|
||||||
|
# 标题含 / → 文件名用 -(GB/T 5475 → GB-T-5475)
|
||||||
|
text = resin_kb_loader("GB/T 5475 离子交换树脂取样方法")
|
||||||
|
self.assertIn("取样", text)
|
||||||
|
|
||||||
|
def test_unknown_title_empty(self):
|
||||||
|
self.assertEqual(resin_kb_loader("不存在的文档"), "")
|
||||||
|
|
||||||
|
def test_kb_config_loads(self):
|
||||||
|
import yaml
|
||||||
|
with open(DEFAULT_KB_CONFIG, "r", encoding="utf-8") as fh:
|
||||||
|
raw = yaml.safe_load(fh)
|
||||||
|
self.assertEqual(raw["template"], "resin")
|
||||||
|
|
||||||
|
|
||||||
|
class TestRagKbIntegration(unittest.TestCase):
|
||||||
|
"""与内核 rag-kb 集成(loader 直接可用)。"""
|
||||||
|
|
||||||
|
def test_build_kb_from_export(self):
|
||||||
|
import importlib.util
|
||||||
|
# 挂载 core/rag-kb(目录含连字符)
|
||||||
|
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
||||||
|
rag_kb_dir = os.path.join(repo_root, "core", "rag-kb")
|
||||||
|
if "rag_kb" not in sys.modules:
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
"rag_kb", os.path.join(rag_kb_dir, "__init__.py"),
|
||||||
|
submodule_search_locations=[rag_kb_dir])
|
||||||
|
_kb = importlib.util.module_from_spec(spec)
|
||||||
|
sys.modules["rag_kb"] = _kb
|
||||||
|
spec.loader.exec_module(_kb)
|
||||||
|
|
||||||
|
from rag_kb import RagKnowledgeBase, load_kb_config # noqa: E402
|
||||||
|
|
||||||
|
kb = RagKnowledgeBase.from_template_config(
|
||||||
|
load_kb_config(DEFAULT_KB_CONFIG), loader=resin_kb_loader)
|
||||||
|
self.assertGreater(kb.doc_count, 0)
|
||||||
|
hits = kb.search("交换容量测定", top_k=3, categories=None)
|
||||||
|
self.assertGreater(len(hits), 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""树脂模板打包与版本发布 —— issue #85(父 Issue #13 子任务)。
|
||||||
|
|
||||||
|
按 `version.yaml`(#13)的 assets 清单把 iAOP-Template-Resin 打包发布:
|
||||||
|
|
||||||
|
- `validate_version()`:semver 校验 + assets 清单文件/目录存在性检查
|
||||||
|
(发布前门禁,防止打包不完整);
|
||||||
|
- `package_template()`:按清单打包 zip(含 version.yaml + README),
|
||||||
|
输出 `dist/resin-{version}.zip`;
|
||||||
|
- `render_release_notes()`:从 version.yaml 生成 Markdown 发布说明
|
||||||
|
(版本/行业/基线/资产清单/备注),供仓库 Release 使用。
|
||||||
|
|
||||||
|
纯标准库实现(zipfile),无第三方依赖。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
import yaml
|
||||||
|
|
||||||
|
#: 模板根目录(相对本模块)
|
||||||
|
TEMPLATE_ROOT = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
#: 版本清单(与 #13 同构)
|
||||||
|
VERSION_PATH = os.path.join(TEMPLATE_ROOT, "version.yaml")
|
||||||
|
|
||||||
|
#: semver 校验(x.y.z)
|
||||||
|
_SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+$")
|
||||||
|
|
||||||
|
#: 打包时始终包含的清单外文件
|
||||||
|
_ALWAYS_INCLUDE = ["version.yaml", "README.md"]
|
||||||
|
|
||||||
|
|
||||||
|
def load_version(path: str = VERSION_PATH) -> dict:
|
||||||
|
"""加载版本清单。"""
|
||||||
|
with open(path, "r", encoding="utf-8") as fh:
|
||||||
|
return yaml.safe_load(fh) or {}
|
||||||
|
|
||||||
|
|
||||||
|
def validate_version(path: str = VERSION_PATH) -> List[str]:
|
||||||
|
"""版本清单校验:semver 合法 + assets 文件/目录存在。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
问题列表(空 = 校验通过)。
|
||||||
|
"""
|
||||||
|
problems: List[str] = []
|
||||||
|
version = load_version(path)
|
||||||
|
ver = str(version.get("version", ""))
|
||||||
|
if not _SEMVER_RE.match(ver):
|
||||||
|
problems.append(f"version 非法(需 semver x.y.z):{ver!r}")
|
||||||
|
for rel in version.get("assets", []):
|
||||||
|
full = os.path.join(TEMPLATE_ROOT, rel)
|
||||||
|
if not os.path.exists(full):
|
||||||
|
problems.append(f"资产缺失:{rel}")
|
||||||
|
return problems
|
||||||
|
|
||||||
|
|
||||||
|
def _add_entry(zf: zipfile.ZipFile, rel: str) -> None:
|
||||||
|
"""把单个文件或目录加入 zip(保留相对路径)。"""
|
||||||
|
full = os.path.join(TEMPLATE_ROOT, rel)
|
||||||
|
if os.path.isdir(full):
|
||||||
|
for root, _, files in os.walk(full):
|
||||||
|
for name in files:
|
||||||
|
abs_path = os.path.join(root, name)
|
||||||
|
zf.write(abs_path, os.path.relpath(abs_path, TEMPLATE_ROOT))
|
||||||
|
else:
|
||||||
|
zf.write(full, rel)
|
||||||
|
|
||||||
|
|
||||||
|
def package_template(path: str = VERSION_PATH,
|
||||||
|
output_dir: Optional[str] = None) -> str:
|
||||||
|
"""按 assets 清单打包模板为 zip。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
生成的 zip 文件路径。
|
||||||
|
"""
|
||||||
|
version = load_version(path)
|
||||||
|
ver = str(version.get("version", ""))
|
||||||
|
problems = validate_version(path)
|
||||||
|
if problems:
|
||||||
|
raise ValueError("打包前校验未通过:" + "; ".join(problems))
|
||||||
|
|
||||||
|
dist = output_dir or os.path.join(TEMPLATE_ROOT, "dist")
|
||||||
|
os.makedirs(dist, exist_ok=True)
|
||||||
|
zip_path = os.path.join(dist, f"resin-{ver}.zip")
|
||||||
|
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
entries = _ALWAYS_INCLUDE + list(version.get("assets", []))
|
||||||
|
for rel in dict.fromkeys(entries): # 去重保序
|
||||||
|
_add_entry(zf, rel)
|
||||||
|
return zip_path
|
||||||
|
|
||||||
|
|
||||||
|
def render_release_notes(path: str = VERSION_PATH) -> str:
|
||||||
|
"""从 version.yaml 生成 Markdown 发布说明。"""
|
||||||
|
version = load_version(path)
|
||||||
|
lines = [
|
||||||
|
f"# iAOP-Template-Resin v{version.get('version', '?')}",
|
||||||
|
"",
|
||||||
|
f"- 行业:{version.get('industry', '')}",
|
||||||
|
f"- 基线:{version.get('baseline', '')}",
|
||||||
|
f"- 并行:{version.get('parallel_with', '')}",
|
||||||
|
f"- 状态:{version.get('status', '')}",
|
||||||
|
"",
|
||||||
|
"## 资产清单",
|
||||||
|
]
|
||||||
|
lines += [f"- `{a}`" for a in version.get("assets", [])]
|
||||||
|
notes = version.get("notes", [])
|
||||||
|
if notes:
|
||||||
|
lines.append("")
|
||||||
|
lines.append("## 备注")
|
||||||
|
lines += [f"- {n}" for n in notes]
|
||||||
|
return "\n".join(lines) + "\n"
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""树脂模板打包与版本发布测试(issue #85)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. validate_version:semver 合法、assets 清单文件/目录存在;
|
||||||
|
2. 非法 semver → 问题列表;
|
||||||
|
3. package_template:按清单打包 zip(含 version.yaml + 资产文件/目录递归);
|
||||||
|
4. 打包前校验失败(资产缺失)→ ValueError;
|
||||||
|
5. render_release_notes:发布说明含版本/行业/基线/资产清单。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
_RESIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, _RESIN_DIR)
|
||||||
|
from template_packaging import ( # noqa: E402
|
||||||
|
TEMPLATE_ROOT,
|
||||||
|
VERSION_PATH,
|
||||||
|
package_template,
|
||||||
|
render_release_notes,
|
||||||
|
validate_version,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidateVersion(unittest.TestCase):
|
||||||
|
"""版本清单校验。"""
|
||||||
|
|
||||||
|
def test_valid_template(self):
|
||||||
|
self.assertEqual(validate_version(), [])
|
||||||
|
|
||||||
|
def test_invalid_semver(self):
|
||||||
|
tmp = tempfile.NamedTemporaryFile(
|
||||||
|
"w", suffix=".yaml", delete=False, encoding="utf-8")
|
||||||
|
tmp.write("version: abc\nassets: []\n")
|
||||||
|
tmp.close()
|
||||||
|
try:
|
||||||
|
problems = validate_version(tmp.name)
|
||||||
|
finally:
|
||||||
|
os.unlink(tmp.name)
|
||||||
|
self.assertTrue(any("semver" in p for p in problems))
|
||||||
|
|
||||||
|
def test_missing_asset_reported(self):
|
||||||
|
tmp = tempfile.NamedTemporaryFile(
|
||||||
|
"w", suffix=".yaml", delete=False, encoding="utf-8")
|
||||||
|
tmp.write("version: 1.0.0\nassets: [no/such/file.yaml]\n")
|
||||||
|
tmp.close()
|
||||||
|
try:
|
||||||
|
problems = validate_version(tmp.name)
|
||||||
|
finally:
|
||||||
|
os.unlink(tmp.name)
|
||||||
|
self.assertTrue(any("缺失" in p for p in problems))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPackage(unittest.TestCase):
|
||||||
|
"""打包。"""
|
||||||
|
|
||||||
|
def test_package_zip_contents(self):
|
||||||
|
with tempfile.TemporaryDirectory() as out:
|
||||||
|
zip_path = package_template(output_dir=out)
|
||||||
|
self.assertTrue(os.path.isfile(zip_path))
|
||||||
|
self.assertTrue(zip_path.endswith("resin-0.1.0.zip"))
|
||||||
|
with zipfile.ZipFile(zip_path) as zf:
|
||||||
|
names = zf.namelist()
|
||||||
|
# 必含清单与核心资产
|
||||||
|
self.assertIn("version.yaml", names)
|
||||||
|
self.assertIn("point-dict/point_dict.resin.csv", names)
|
||||||
|
self.assertIn("rag-kb/kb.resin.template.yaml", names)
|
||||||
|
# 目录递归(documents/ 8 篇)
|
||||||
|
docs = [n for n in names if n.startswith("rag-kb/documents/")]
|
||||||
|
self.assertEqual(len(docs), 8)
|
||||||
|
|
||||||
|
def test_package_fails_on_missing_asset(self):
|
||||||
|
tmp = tempfile.NamedTemporaryFile(
|
||||||
|
"w", suffix=".yaml", delete=False, encoding="utf-8")
|
||||||
|
tmp.write("version: 1.0.0\nassets: [no/such/file.yaml]\n")
|
||||||
|
tmp.close()
|
||||||
|
try:
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
package_template(path=tmp.name)
|
||||||
|
finally:
|
||||||
|
os.unlink(tmp.name)
|
||||||
|
|
||||||
|
|
||||||
|
class TestReleaseNotes(unittest.TestCase):
|
||||||
|
"""发布说明。"""
|
||||||
|
|
||||||
|
def test_release_notes_content(self):
|
||||||
|
notes = render_release_notes()
|
||||||
|
self.assertIn("# iAOP-Template-Resin v0.1.0", notes)
|
||||||
|
self.assertIn("吸附树脂", notes)
|
||||||
|
self.assertIn("化工新材料AI平台", notes)
|
||||||
|
self.assertIn("point-dict/point_dict.resin.csv", notes)
|
||||||
|
self.assertIn("## 资产清单", notes)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -15,7 +15,11 @@ version: 0.1.0
|
|||||||
assets:
|
assets:
|
||||||
- point-dict/point_dict.resin.csv
|
- point-dict/point_dict.resin.csv
|
||||||
- rag-kb/kb.resin.template.yaml
|
- rag-kb/kb.resin.template.yaml
|
||||||
|
- rag-kb/loader.py
|
||||||
|
- rag-kb/documents/
|
||||||
- dashboard/cockpit.resin.yaml
|
- dashboard/cockpit.resin.yaml
|
||||||
|
- README.md
|
||||||
notes:
|
notes:
|
||||||
- 点位字典取自已交付平台采集层(和利时DCS/威盛DCS/西门子S7-1200/称重/能源/人工录入)
|
- 点位字典取自已交付平台采集层(和利时DCS/威盛DCS/西门子S7-1200/称重/能源/人工录入)
|
||||||
- 驾驶舱布局对齐 PRD 5.5 iAOP-cockpit-layout-v1 schema
|
- 驾驶舱布局对齐 PRD 5.5 iAOP-cockpit-layout-v1 schema
|
||||||
|
- RAG 知识库文档集与加载器(issue #83)随模板发布
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# 海绵钛驾驶舱布局资产 + 校验器(Issue #55 / PRD 5.5)
|
||||||
|
|
||||||
|
> 父 Issue「⑤ Ti 行业布局模板(四状态流程视图)· 0.5d」
|
||||||
|
|
||||||
|
把海绵钛车间驾驶舱布局落为**对齐 iAOP-cockpit-layout-v1 的资产 + 可校验的纯标准库
|
||||||
|
校验器**(无 node/前端构建环境,零运行时依赖)。
|
||||||
|
|
||||||
|
## 资产:`cockpit.ti.yaml`
|
||||||
|
|
||||||
|
四状态工艺流程(PRD 4.2 海绵钛:**氯化 → 精制 → 还原 → 蒸馏**):
|
||||||
|
|
||||||
|
- `process_view` 主视图(首屏立即加载),`stages` 声明四状态覆盖;
|
||||||
|
- `trend` 实时趋势(氯化炉温度 `CLF-01.TEMP` / 氯气流量 `CLF-01.CL2`);
|
||||||
|
- `kpi_card` KPI(TiCl₄纯度 `RF-01.PURITY` / 杂质 `RF-01.IMP` / 电耗 `E-01.KWH` / 蒸汽 `ST-01.STEAM`);
|
||||||
|
- `alarm_panel` 告警面板 + `nl_query` NL 查询入口。
|
||||||
|
|
||||||
|
所有 `bind` 的 `point_id` 对齐 `templates/ti-cl4/point-dict/point_dict.default.csv`。
|
||||||
|
|
||||||
|
## 校验器:`layout_validator.py`
|
||||||
|
|
||||||
|
`LayoutValidator(layout_yaml, point_dict_csv).validate()` → `LayoutReport`,校验:
|
||||||
|
|
||||||
|
1. **widget 类型合法**:在 `iAOP-cockpit-layout-v1` 允许集合内(process_view/trend/kpi_card/alarm_panel/nl_query);
|
||||||
|
2. **12 列网格不越界**:`0 ≤ x`、`x + w ≤ 12`、`y ≥ 0`、`w/h > 0`;
|
||||||
|
3. **bind point_id 在点位字典内**:防模板漂移(trend/kpi_card 的 bind 必须命中点字典);
|
||||||
|
4. **四状态覆盖完整**:process_view 的 stages 必须覆盖氯化/精制/还原/蒸馏,order 单调递增、id 唯一。
|
||||||
|
|
||||||
|
零依赖 YAML 子集解析(复制 impurity-forecast 的 `_parse_yaml_subset`,无 pyyaml)。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m unittest discover -s templates/ti-cl4/dashboard/tests -p "test_*.py" -v
|
||||||
|
```
|
||||||
|
|
||||||
|
覆盖正常 + 边界 + 错误(18 用例):真实资产端到端通过、非法类型、网格越界/负坐标/零宽、
|
||||||
|
bind 漂移、缺 process_view、缺必需状态、order 非单调、stage 重复、$schema 头、CSV 加载、空布局。
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""海绵钛驾驶舱布局资产 + 校验器包(Issue #55)。
|
||||||
|
|
||||||
|
对齐 PRD 5.5「⑤ 配置化驾驶舱」布局 JSON Schema(iAOP-cockpit-layout-v1):
|
||||||
|
四状态工艺流程(氯化 → 精制 → 还原 → 蒸馏)。
|
||||||
|
"""
|
||||||
|
from .layout_validator import (
|
||||||
|
LayoutError,
|
||||||
|
LayoutIssue,
|
||||||
|
LayoutReport,
|
||||||
|
LayoutValidator,
|
||||||
|
WidgetSpec,
|
||||||
|
ALLOWED_WIDGET_TYPES,
|
||||||
|
GRID_COLUMNS,
|
||||||
|
REQUIRED_STAGES,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"LayoutError",
|
||||||
|
"LayoutIssue",
|
||||||
|
"LayoutReport",
|
||||||
|
"LayoutValidator",
|
||||||
|
"WidgetSpec",
|
||||||
|
"ALLOWED_WIDGET_TYPES",
|
||||||
|
"GRID_COLUMNS",
|
||||||
|
"REQUIRED_STAGES",
|
||||||
|
]
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""海绵钛驾驶舱布局冒烟脚本(Issue #55)。
|
||||||
|
|
||||||
|
直接运行 ``python _sanity_check.py`` 验证:cockpit.ti.yaml + point_dict.default.csv
|
||||||
|
端到端校验通过(widget 类型/网格/bind/四状态全覆盖)。零第三方依赖。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, HERE)
|
||||||
|
|
||||||
|
from layout_validator import LayoutValidator # noqa: E402
|
||||||
|
|
||||||
|
LAYOUT_YAML = os.path.join(HERE, "cockpit.ti.yaml")
|
||||||
|
POINT_DICT_CSV = os.path.join(
|
||||||
|
HERE, os.pardir, "point-dict", "point_dict.default.csv")
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
|
||||||
|
if not report.passed:
|
||||||
|
print("FAIL")
|
||||||
|
for issue in report.errors:
|
||||||
|
print(f" - [{issue.widget_id}] {issue.field}: {issue.reason}")
|
||||||
|
return 1
|
||||||
|
print(f"OK: {report.widget_count} widgets,"
|
||||||
|
f"类型/网格/bind/四状态校验通过")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# 海绵钛(Ti)车间驾驶舱布局资产(iAOP-Template-Ti,EPIC #12)。
|
||||||
|
#
|
||||||
|
# 对齐 PRD 5.5「⑤ 配置化驾驶舱」布局 JSON Schema(iAOP-cockpit-layout-v1):
|
||||||
|
# 切换行业模板后,驾驶舱按本布局自动重排,无需改前端代码。
|
||||||
|
# widget 类型:process_view(工艺流程视图)/ trend(实时趋势)/ kpi_card(KPI卡片)/
|
||||||
|
# alarm_panel(告警面板)/ nl_query(NL查询入口)。
|
||||||
|
#
|
||||||
|
# 四状态工艺流程(PRD 4.2 海绵钛:氯化 → 精制 → 还原 → 蒸馏):
|
||||||
|
# - 氯化 (CLF-01):TiO₂ + Cl₂ + C → TiCl₄(沸腾氯化炉)
|
||||||
|
# - 精制 :粗 TiCl₄ → 精 TiCl₄(除钒/除硅,常压精馏)
|
||||||
|
# - 还原 (RF-01):TiCl₄ + Mg → 海绵钛(真空还原,Kroll 法)
|
||||||
|
# - 蒸馏 :海绵钛 + 残余 Mg/MgCl₂ 分离(真空蒸馏)
|
||||||
|
# process_view 的 stages 字段声明四状态覆盖,layout_validator 校验完整性。
|
||||||
|
#
|
||||||
|
# bind 的 point_id 对齐 templates/ti-cl4/point-dict/point_dict.default.csv。
|
||||||
|
$schema: iAOP-cockpit-layout-v1
|
||||||
|
title: 海绵钛车间驾驶舱
|
||||||
|
theme: dark
|
||||||
|
widgets:
|
||||||
|
# ---- 四状态工艺流程主视图(首屏立即加载) ---------------------------
|
||||||
|
- type: process_view
|
||||||
|
src: ti_four_state.svg
|
||||||
|
x: 0
|
||||||
|
y: 0
|
||||||
|
w: 12
|
||||||
|
h: 4
|
||||||
|
description: 四状态工艺流程(氯化 → 精制 → 还原 → 蒸馏)
|
||||||
|
stages:
|
||||||
|
- id: chlorination
|
||||||
|
name: 氯化
|
||||||
|
device: CLF-01
|
||||||
|
order: 1
|
||||||
|
- id: purification
|
||||||
|
name: 精制
|
||||||
|
order: 2
|
||||||
|
- id: reduction
|
||||||
|
name: 还原
|
||||||
|
device: RF-01
|
||||||
|
order: 3
|
||||||
|
- id: distillation
|
||||||
|
name: 蒸馏
|
||||||
|
order: 4
|
||||||
|
# ---- 实时趋势:氯化炉温度/氯气流量(工艺核心监控) -------------------
|
||||||
|
- type: trend
|
||||||
|
bind: CLF-01.TEMP
|
||||||
|
x: 0
|
||||||
|
y: 4
|
||||||
|
w: 6
|
||||||
|
h: 2
|
||||||
|
description: 氯化炉温度实时趋势(沸腾氯化炉温 850±50℃)
|
||||||
|
- type: trend
|
||||||
|
bind: CLF-01.CL2
|
||||||
|
x: 6
|
||||||
|
y: 4
|
||||||
|
w: 6
|
||||||
|
h: 2
|
||||||
|
description: 氯气流量实时趋势(流态化监控)
|
||||||
|
# ---- KPI 卡片:还原质量/能耗(海绵钛核心指标) -----------------------
|
||||||
|
- type: kpi_card
|
||||||
|
metric: ticl4_purity
|
||||||
|
bind: RF-01.PURITY
|
||||||
|
label: TiCl₄纯度
|
||||||
|
x: 0
|
||||||
|
y: 6
|
||||||
|
w: 3
|
||||||
|
h: 2
|
||||||
|
description: 还原 TiCl₄ 纯度(%,工艺 ≥ 99.9%)
|
||||||
|
- type: kpi_card
|
||||||
|
metric: ticl4_impurity
|
||||||
|
bind: RF-01.IMP
|
||||||
|
label: 杂质含量
|
||||||
|
x: 3
|
||||||
|
y: 6
|
||||||
|
w: 3
|
||||||
|
h: 2
|
||||||
|
description: 还原杂质含量(%,越低越好)
|
||||||
|
- type: kpi_card
|
||||||
|
metric: energy_per_ton
|
||||||
|
bind: E-01.KWH
|
||||||
|
label: 累计电耗
|
||||||
|
x: 6
|
||||||
|
y: 6
|
||||||
|
w: 3
|
||||||
|
h: 2
|
||||||
|
description: 车间累计电耗(kWh,单吨海绵钛综合能耗输入)
|
||||||
|
- type: kpi_card
|
||||||
|
metric: steam_flow
|
||||||
|
bind: ST-01.STEAM
|
||||||
|
label: 蒸汽流量
|
||||||
|
x: 9
|
||||||
|
y: 6
|
||||||
|
w: 3
|
||||||
|
h: 2
|
||||||
|
description: 蒸汽流量(t/h,公用工程监控)
|
||||||
|
# ---- 告警面板 + NL 查询入口 ------------------------------------------
|
||||||
|
- type: alarm_panel
|
||||||
|
x: 0
|
||||||
|
y: 8
|
||||||
|
w: 9
|
||||||
|
h: 3
|
||||||
|
description: 告警面板(氯化炉温/还原真空度/纯度/杂质异常)
|
||||||
|
- type: nl_query
|
||||||
|
x: 9
|
||||||
|
y: 8
|
||||||
|
w: 3
|
||||||
|
h: 3
|
||||||
|
description: 自然语言查询入口(工艺/质量/能耗问答)
|
||||||
@@ -0,0 +1,500 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""海绵钛驾驶舱布局校验器(Issue #55 / PRD 5.5「⑤ 配置化驾驶舱」)。
|
||||||
|
|
||||||
|
PRD 5.5:切换行业模板后,驾驶舱按布局资产自动重排,无需改前端代码。
|
||||||
|
本模块把布局资产(``cockpit.ti.yaml``)落为**可校验的纯标准库资产 + 校验器**——
|
||||||
|
给定布局 YAML + 点位字典 CSV,校验:
|
||||||
|
|
||||||
|
1. **widget 类型合法**:在 PRD 5.5 ``iAOP-cockpit-layout-v1`` 允许集合内
|
||||||
|
(process_view/trend/kpi_card/alarm_panel/nl_query)。
|
||||||
|
2. **12 列网格不越界**:每个 widget ``0 ≤ x`` 且 ``x + w ≤ 12``,``y ≥ 0``、
|
||||||
|
``h > 0``;坐标为非负整数,w/h 正整数(网格对齐)。
|
||||||
|
3. **bind 的 point_id 在点位字典内**:trend/kpi_card 的 ``bind`` 必须命中
|
||||||
|
``point_dict.default.csv`` 的 ``point_id`` 列(防模板漂移)。
|
||||||
|
4. **四状态视图覆盖完整**:process_view 的 ``stages`` 必须覆盖工艺全流程
|
||||||
|
(氯化/精制/还原/蒸馏),且 order 单调递增、id 唯一。
|
||||||
|
|
||||||
|
校验产出 :class:`LayoutReport`(PASS/FAIL + 逐条 :class:`LayoutIssue`,
|
||||||
|
每条 issue 带 ``reason`` 可解释)。
|
||||||
|
|
||||||
|
设计要点
|
||||||
|
--------
|
||||||
|
- **零依赖 YAML 子集解析**:复制 impurity-forecast features.py 的
|
||||||
|
``_parse_yaml_subset``(无 pyyaml),支持 map/list/标量/行内 flow map。
|
||||||
|
- **纯标准库**:CSV 用标准库 csv,无 numpy/pyyaml 依赖。
|
||||||
|
- **换行业只改资产**:校验器对任何对齐 ``iAOP-cockpit-layout-v1`` 的布局都适用。
|
||||||
|
|
||||||
|
用法::
|
||||||
|
|
||||||
|
report = LayoutValidator(layout_yaml, point_dict_csv).validate()
|
||||||
|
if not report.passed:
|
||||||
|
for issue in report.issues:
|
||||||
|
print(issue.severity, issue.widget_id, issue.reason)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import csv
|
||||||
|
import os
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
#: iAOP-cockpit-layout-v1 允许的 widget 类型集合(对齐 resin _sanity_check)。
|
||||||
|
ALLOWED_WIDGET_TYPES = frozenset({
|
||||||
|
"process_view", "trend", "kpi_card", "alarm_panel", "nl_query",
|
||||||
|
})
|
||||||
|
|
||||||
|
#: 12 列网格(主流前端栅格标准,对齐 cockpit layout v1)。
|
||||||
|
GRID_COLUMNS = 12
|
||||||
|
|
||||||
|
#: 海绵钛四状态工艺流程(PRD 4.2:氯化 → 精制 → 还原 → 蒸馏)。
|
||||||
|
#: process_view 的 stages 必须覆盖这四个 id。
|
||||||
|
REQUIRED_STAGES = ("chlorination", "purification", "reduction", "distillation")
|
||||||
|
|
||||||
|
|
||||||
|
class LayoutError(ValueError):
|
||||||
|
"""布局资产解析/声明错误(YAML 格式错、表头缺字段等)。"""
|
||||||
|
|
||||||
|
|
||||||
|
class Severity(str, Enum):
|
||||||
|
"""问题严重度。"""
|
||||||
|
|
||||||
|
ERROR = "error" # 阻断:布局不可用(类型非法/越界/bind 缺失/状态缺失)
|
||||||
|
WARN = "warn" # 告警:可运行但不规范(重复/顺序乱)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LayoutIssue:
|
||||||
|
"""单条布局校验问题(含 reason 可解释)。"""
|
||||||
|
|
||||||
|
severity: Severity
|
||||||
|
reason: str
|
||||||
|
widget_id: str = "" # 关联 widget(index 或 src/metric)
|
||||||
|
field: str = "" # 关联字段(type/x/bind/stages ...)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_error(self) -> bool:
|
||||||
|
return self.severity is Severity.ERROR
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LayoutReport:
|
||||||
|
"""布局校验报告。"""
|
||||||
|
|
||||||
|
issues: List[LayoutIssue] = field(default_factory=list)
|
||||||
|
widget_count: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def errors(self) -> List[LayoutIssue]:
|
||||||
|
return [i for i in self.issues if i.is_error]
|
||||||
|
|
||||||
|
@property
|
||||||
|
def passed(self) -> bool:
|
||||||
|
"""通过 = 无 ERROR(WARN 不阻断)。"""
|
||||||
|
return not any(i.is_error for i in self.issues)
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
return {
|
||||||
|
"passed": self.passed,
|
||||||
|
"widget_count": self.widget_count,
|
||||||
|
"error_count": len(self.errors),
|
||||||
|
"warn_count": len(self.issues) - len(self.errors),
|
||||||
|
"issues": [
|
||||||
|
{"severity": i.severity.value, "widget_id": i.widget_id,
|
||||||
|
"field": i.field, "reason": i.reason}
|
||||||
|
for i in self.issues
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class WidgetSpec:
|
||||||
|
"""单个 widget 的内存模型(从 YAML 解析)。"""
|
||||||
|
|
||||||
|
index: int # 在 widgets 列表中的位置(0 起)
|
||||||
|
type: str
|
||||||
|
x: int = 0
|
||||||
|
y: int = 0
|
||||||
|
w: int = 1
|
||||||
|
h: int = 1
|
||||||
|
bind: str = "" # trend/kpi_card 绑定的 point_id
|
||||||
|
src: str = "" # process_view 的 SVG
|
||||||
|
metric: str = "" # kpi_card 的 metric
|
||||||
|
label: str = ""
|
||||||
|
description: str = ""
|
||||||
|
stages: List[Dict[str, object]] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 零依赖 YAML 子集解析(复制自 impurity-forecast features.py,对齐 data-bus)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _parse_scalar(text: str) -> str:
|
||||||
|
"""去掉标量两侧引号与行内注释。"""
|
||||||
|
t = text.split(" #", 1)[0].strip()
|
||||||
|
if len(t) >= 2 and t[0] == t[-1] and t[0] in ("'", '"'):
|
||||||
|
return t[1:-1]
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_flow_value(text: str):
|
||||||
|
"""解析 ``key: value`` 右侧值,支持行内 flow map ``{k: v, k: v}``。"""
|
||||||
|
t = text.split(" #", 1)[0].strip()
|
||||||
|
if t.startswith("{") and t.endswith("}"):
|
||||||
|
inner = t[1:-1].strip()
|
||||||
|
out: Dict[str, object] = {}
|
||||||
|
if not inner:
|
||||||
|
return out
|
||||||
|
for part in inner.split(","):
|
||||||
|
if ":" not in part:
|
||||||
|
raise LayoutError(f"flow map 项不是键值对:{part!r}")
|
||||||
|
k, _, v = part.partition(":")
|
||||||
|
out[k.strip()] = _parse_scalar(v)
|
||||||
|
return out
|
||||||
|
return _parse_scalar(text)
|
||||||
|
|
||||||
|
|
||||||
|
def _strip_comments(lines: List[str]) -> List[Tuple[str, int]]:
|
||||||
|
out: List[Tuple[str, int]] = []
|
||||||
|
for i, ln in enumerate(lines):
|
||||||
|
s = ln.strip()
|
||||||
|
if not s or s.startswith("#"):
|
||||||
|
continue
|
||||||
|
out.append((ln, i + 1))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_node(lines: List[Tuple[str, int]], i: int, indent: int):
|
||||||
|
"""递归解析 YAML 节点(map / list / scalar)。返回 (value, next_i)。"""
|
||||||
|
text, _ = lines[i]
|
||||||
|
# ---- list 节点 ----
|
||||||
|
if text.lstrip(" ").startswith("- "):
|
||||||
|
items: List[object] = []
|
||||||
|
while i < len(lines):
|
||||||
|
t, no = lines[i]
|
||||||
|
stripped = t.lstrip(" ")
|
||||||
|
if not stripped.startswith("- "):
|
||||||
|
break
|
||||||
|
lead_j = len(t) - len(t.lstrip(" "))
|
||||||
|
if lead_j != indent:
|
||||||
|
break
|
||||||
|
item_text = stripped[2:].strip()
|
||||||
|
if not item_text:
|
||||||
|
raise LayoutError(f"cockpit.yaml 第 {no} 行:list 项为空")
|
||||||
|
if ":" in item_text:
|
||||||
|
map_indent = len(t) - len(t.lstrip(" ")) + 2
|
||||||
|
lines[i] = (" " * map_indent + item_text, no)
|
||||||
|
v, i = _parse_node(lines, i, map_indent)
|
||||||
|
items.append(v)
|
||||||
|
else:
|
||||||
|
items.append(_parse_flow_value(item_text))
|
||||||
|
i += 1
|
||||||
|
return items, i
|
||||||
|
# ---- map 节点 ----
|
||||||
|
result: Dict[str, object] = {}
|
||||||
|
while i < len(lines):
|
||||||
|
t, no = lines[i]
|
||||||
|
lead_j = len(t) - len(t.lstrip(" "))
|
||||||
|
if lead_j < indent or t.lstrip(" ").startswith("- "):
|
||||||
|
break
|
||||||
|
if lead_j > indent:
|
||||||
|
raise LayoutError(
|
||||||
|
f"cockpit.yaml 第 {no} 行缩进异常(期望 {indent},实际 {lead_j})")
|
||||||
|
if ":" not in t:
|
||||||
|
raise LayoutError(f"cockpit.yaml 第 {no} 行不是合法键值对:{t!r}")
|
||||||
|
key, _, rest = t.partition(":")
|
||||||
|
key = key.strip()
|
||||||
|
rest = rest.strip()
|
||||||
|
if rest:
|
||||||
|
result[key] = _parse_flow_value(rest)
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if i + 1 >= len(lines):
|
||||||
|
raise LayoutError(f"cockpit.yaml 第 {no} 行 {key!r} 缺少值")
|
||||||
|
sub_indent = len(lines[i + 1][0]) - len(lines[i + 1][0].lstrip(" "))
|
||||||
|
if sub_indent <= indent:
|
||||||
|
raise LayoutError(f"cockpit.yaml 第 {no} 行 {key!r} 缺少值(无嵌套)")
|
||||||
|
v, i = _parse_node(lines, i + 1, sub_indent)
|
||||||
|
result[key] = v
|
||||||
|
return result, i
|
||||||
|
|
||||||
|
|
||||||
|
def _load_yaml_text(text: str) -> Dict[str, object]:
|
||||||
|
"""解析 YAML 文本为 dict(顶层必须是 map)。"""
|
||||||
|
lines = _strip_comments(text.splitlines())
|
||||||
|
if not lines:
|
||||||
|
return {}
|
||||||
|
top_indent = len(lines[0][0]) - len(lines[0][0].lstrip(" "))
|
||||||
|
value, next_i = _parse_node(lines, 0, top_indent)
|
||||||
|
if not isinstance(value, dict):
|
||||||
|
raise LayoutError("cockpit.yaml 顶层必须是 map")
|
||||||
|
if next_i < len(lines):
|
||||||
|
raise LayoutError(
|
||||||
|
f"cockpit.yaml 第 {lines[next_i][1]} 行:顶层存在多个节点")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 点位字典加载(CSV → point_id 集合)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def load_point_ids(csv_path: str) -> List[str]:
|
||||||
|
"""从点位字典 CSV 加载全部 point_id(保序,对齐 CSV point_id 列)。
|
||||||
|
|
||||||
|
CSV 表头对齐 core/edge-gateway point_dict schema(第二列 point_id)。
|
||||||
|
"""
|
||||||
|
if not os.path.isfile(csv_path):
|
||||||
|
raise LayoutError(f"点位字典 CSV 不存在:{csv_path}")
|
||||||
|
with open(csv_path, "r", encoding="utf-8") as fh:
|
||||||
|
rows = list(csv.reader(fh))
|
||||||
|
if not rows:
|
||||||
|
raise LayoutError(f"点位字典 CSV 为空:{csv_path}")
|
||||||
|
header = [c.strip() for c in rows[0]]
|
||||||
|
if "point_id" not in header:
|
||||||
|
raise LayoutError(
|
||||||
|
f"点位字典 CSV 表头缺 point_id 列:{header}")
|
||||||
|
col = header.index("point_id")
|
||||||
|
ids: List[str] = []
|
||||||
|
for i, row in enumerate(rows[1:], 2):
|
||||||
|
if len(row) <= col:
|
||||||
|
continue
|
||||||
|
pid = row[col].strip()
|
||||||
|
if pid:
|
||||||
|
ids.append(pid)
|
||||||
|
if not ids:
|
||||||
|
raise LayoutError(f"点位字典 CSV 无 point_id 数据行:{csv_path}")
|
||||||
|
return ids
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 校验器
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class LayoutValidator:
|
||||||
|
"""海绵钛驾驶舱布局校验器。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
layout_yaml_path: 布局资产路径(cockpit.ti.yaml)。
|
||||||
|
point_dict_csv_path: 点位字典 CSV 路径(point_dict.default.csv)。
|
||||||
|
grid_columns: 网格列数(默认 12,对齐 cockpit layout v1)。
|
||||||
|
required_stages: process_view 必须覆盖的 stage id(默认海绵钛四状态)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
layout_yaml_path: str,
|
||||||
|
point_dict_csv_path: Optional[str] = None,
|
||||||
|
grid_columns: int = GRID_COLUMNS,
|
||||||
|
required_stages: Tuple[str, ...] = REQUIRED_STAGES,
|
||||||
|
) -> None:
|
||||||
|
if grid_columns <= 0:
|
||||||
|
raise LayoutError(f"grid_columns 必须 > 0,实际 {grid_columns}")
|
||||||
|
self.layout_path = layout_yaml_path
|
||||||
|
self.point_dict_path = point_dict_csv_path
|
||||||
|
self.grid_columns = int(grid_columns)
|
||||||
|
self.required_stages = tuple(required_stages)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def validate(self) -> LayoutReport:
|
||||||
|
"""执行全部校验,返回报告。"""
|
||||||
|
report = LayoutReport()
|
||||||
|
# 1) 解析布局 YAML
|
||||||
|
try:
|
||||||
|
with open(self.layout_path, "r", encoding="utf-8") as fh:
|
||||||
|
data = _load_yaml_text(fh.read())
|
||||||
|
except LayoutError:
|
||||||
|
raise
|
||||||
|
except OSError as exc:
|
||||||
|
raise LayoutError(f"布局 YAML 读取失败:{self.layout_path} ({exc})") from exc
|
||||||
|
|
||||||
|
# schema 头校验
|
||||||
|
schema = str(data.get("$schema", "")).strip()
|
||||||
|
if schema != "iAOP-cockpit-layout-v1":
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR,
|
||||||
|
field="$schema",
|
||||||
|
reason=f"$schema 应为 'iAOP-cockpit-layout-v1',实际 {schema!r}",
|
||||||
|
))
|
||||||
|
|
||||||
|
# 2) 解析 widgets
|
||||||
|
raw_widgets = data.get("widgets") or []
|
||||||
|
if not isinstance(raw_widgets, list):
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, field="widgets",
|
||||||
|
reason=f"widgets 必须是 list,实际 {type(raw_widgets).__name__}"))
|
||||||
|
return report
|
||||||
|
widgets = self._parse_widgets(raw_widgets, report)
|
||||||
|
report.widget_count = len(widgets)
|
||||||
|
|
||||||
|
if not widgets:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, field="widgets",
|
||||||
|
reason="布局无任何 widget"))
|
||||||
|
return report
|
||||||
|
|
||||||
|
# 3) 加载点位字典(bind 校验需要)
|
||||||
|
point_ids: Optional[set] = None
|
||||||
|
if self.point_dict_path:
|
||||||
|
try:
|
||||||
|
point_ids = set(load_point_ids(self.point_dict_path))
|
||||||
|
except LayoutError as exc:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, field="point_dict",
|
||||||
|
reason=str(exc)))
|
||||||
|
|
||||||
|
# 4) 逐 widget 校验
|
||||||
|
for w in widgets:
|
||||||
|
self._check_widget(w, point_ids, report)
|
||||||
|
|
||||||
|
# 5) process_view 四状态覆盖
|
||||||
|
self._check_process_views(widgets, report)
|
||||||
|
|
||||||
|
return report
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _parse_widgets(self, raw_widgets: List[object],
|
||||||
|
report: LayoutReport) -> List[WidgetSpec]:
|
||||||
|
widgets: List[WidgetSpec] = []
|
||||||
|
for idx, item in enumerate(raw_widgets):
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=f"[{idx}]",
|
||||||
|
field="widgets",
|
||||||
|
reason=f"widgets[{idx}] 必须是 map,实际 {type(item).__name__}"))
|
||||||
|
continue
|
||||||
|
wtype = str(item.get("type", "")).strip()
|
||||||
|
widgets.append(WidgetSpec(
|
||||||
|
index=idx,
|
||||||
|
type=wtype,
|
||||||
|
x=_to_int(item.get("x"), 0),
|
||||||
|
y=_to_int(item.get("y"), 0),
|
||||||
|
w=_to_int(item.get("w"), 1),
|
||||||
|
h=_to_int(item.get("h"), 1),
|
||||||
|
bind=str(item.get("bind", "")).strip(),
|
||||||
|
src=str(item.get("src", "")).strip(),
|
||||||
|
metric=str(item.get("metric", "")).strip(),
|
||||||
|
label=str(item.get("label", "")).strip(),
|
||||||
|
description=str(item.get("description", "")).strip(),
|
||||||
|
stages=_as_list_of_dict(item.get("stages")),
|
||||||
|
))
|
||||||
|
return widgets
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _check_widget(self, w: WidgetSpec, point_ids: Optional[set],
|
||||||
|
report: LayoutReport) -> None:
|
||||||
|
wid = f"[{w.index}]({w.type})"
|
||||||
|
# 4a) widget 类型合法
|
||||||
|
if w.type not in ALLOWED_WIDGET_TYPES:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="type",
|
||||||
|
reason=f"非法 widget 类型 {w.type!r}(允许 {sorted(ALLOWED_WIDGET_TYPES)})"))
|
||||||
|
|
||||||
|
# 4b) 12 列网格不越界(坐标非负整数、x+w ≤ columns、h>0)
|
||||||
|
if w.x < 0 or w.y < 0:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="grid",
|
||||||
|
reason=f"坐标不能为负:x={w.x} y={w.y}"))
|
||||||
|
if w.w <= 0 or w.h <= 0:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="grid",
|
||||||
|
reason=f"w/h 必须为正整数:w={w.w} h={w.h}"))
|
||||||
|
if w.x + w.w > self.grid_columns:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="grid",
|
||||||
|
reason=f"越出 {self.grid_columns} 列网格:x={w.x}+w={w.w}"
|
||||||
|
f"={w.x + w.w} > {self.grid_columns}"))
|
||||||
|
|
||||||
|
# 4c) bind 的 point_id 必须在点位字典内(trend/kpi_card)
|
||||||
|
if w.bind:
|
||||||
|
if point_ids is not None and w.bind not in point_ids:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="bind",
|
||||||
|
reason=f"bind point_id {w.bind!r} 不在点位字典内"
|
||||||
|
f"(防模板漂移,对齐 point_dict.default.csv)"))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _check_process_views(self, widgets: List[WidgetSpec],
|
||||||
|
report: LayoutReport) -> None:
|
||||||
|
"""校验 process_view 的四状态覆盖完整。"""
|
||||||
|
pv = [w for w in widgets if w.type == "process_view"]
|
||||||
|
if not pv:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, field="process_view",
|
||||||
|
reason="布局缺少 process_view(四状态工艺流程主视图必需)"))
|
||||||
|
return
|
||||||
|
|
||||||
|
covered: Dict[str, WidgetSpec] = {} # stage_id → widget
|
||||||
|
for w in pv:
|
||||||
|
wid = f"[{w.index}](process_view)"
|
||||||
|
if not w.stages:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="stages",
|
||||||
|
reason="process_view 缺少 stages 声明(四状态覆盖必需)"))
|
||||||
|
continue
|
||||||
|
|
||||||
|
stage_ids: List[str] = []
|
||||||
|
orders: List[int] = []
|
||||||
|
seen: set = set()
|
||||||
|
for st in w.stages:
|
||||||
|
sid = str(st.get("id", "")).strip()
|
||||||
|
sname = str(st.get("name", "")).strip()
|
||||||
|
if not sid:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="stages",
|
||||||
|
reason=f"stage 缺少 id(name={sname!r})"))
|
||||||
|
continue
|
||||||
|
if sid in seen:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.WARN, widget_id=wid, field="stages",
|
||||||
|
reason=f"stage id 重复:{sid!r}"))
|
||||||
|
continue
|
||||||
|
seen.add(sid)
|
||||||
|
stage_ids.append(sid)
|
||||||
|
covered.setdefault(sid, w)
|
||||||
|
order = st.get("order")
|
||||||
|
if order is not None:
|
||||||
|
try:
|
||||||
|
orders.append(int(order))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="stages",
|
||||||
|
reason=f"stage {sid!r} order 非整数:{order!r}"))
|
||||||
|
|
||||||
|
# order 单调递增校验
|
||||||
|
if orders and len(orders) == len(stage_ids):
|
||||||
|
if orders != sorted(orders):
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, widget_id=wid, field="stages",
|
||||||
|
reason=f"stage order 非单调递增:{orders}"))
|
||||||
|
|
||||||
|
# 必需四状态全覆盖
|
||||||
|
missing = [s for s in self.required_stages if s not in covered]
|
||||||
|
if missing:
|
||||||
|
report.issues.append(LayoutIssue(
|
||||||
|
severity=Severity.ERROR, field="stages",
|
||||||
|
reason=f"process_view stages 未覆盖必需四状态:{missing}"
|
||||||
|
f"(氯化/精制/还原/蒸馏)"))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 辅助
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _to_int(value: object, default: int) -> int:
|
||||||
|
"""把 YAML 解析出的值(可能是 str/int)转为 int;失败返回 default。"""
|
||||||
|
if value is None or value == "":
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
raise LayoutError(f"坐标值不是整数:{value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _as_list_of_dict(value: object) -> List[Dict[str, object]]:
|
||||||
|
if not isinstance(value, list):
|
||||||
|
return []
|
||||||
|
out: List[Dict[str, object]] = []
|
||||||
|
for item in value:
|
||||||
|
if isinstance(item, dict):
|
||||||
|
out.append(item)
|
||||||
|
return out
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""测试引导:把 dashboard 测试根目录加入 sys.path,使 layout_validator 可导入。
|
||||||
|
|
||||||
|
dashboard 目录名是合法 Python 标识符,直接作为包导入;本引导把父目录
|
||||||
|
(templates/ti-cl4/dashboard)挂到 sys.path,使 ``from layout_validator import ...``
|
||||||
|
在 unittest 发现机制下可解析(与 core 模块测试引导同款)。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
PKG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
if PKG_DIR not in sys.path:
|
||||||
|
sys.path.insert(0, PKG_DIR)
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""海绵钛驾驶舱布局校验器测试(Issue #55)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. 真实 cockpit.ti.yaml + point_dict.default.csv 全部通过(端到端);
|
||||||
|
2. widget 类型合法集合(非法类型 → ERROR);
|
||||||
|
3. 12 列网格校验(越界/负坐标/非正 w/h);
|
||||||
|
4. bind point_id 在点位字典内(漂移 → ERROR);
|
||||||
|
5. process_view 四状态覆盖(缺 stage id / order 非单调 / 缺必需状态);
|
||||||
|
6. $schema 头校验;
|
||||||
|
7. YAML 解析(flow map / 嵌套);
|
||||||
|
8. 点位字典 CSV 加载(缺表头/空文件);
|
||||||
|
9. 空布局 / 边界。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import _bootstrap # noqa: F401 (sys.path 挂载)
|
||||||
|
|
||||||
|
from layout_validator import (
|
||||||
|
GRID_COLUMNS,
|
||||||
|
LayoutError,
|
||||||
|
LayoutValidator,
|
||||||
|
REQUIRED_STAGES,
|
||||||
|
Severity,
|
||||||
|
load_point_ids,
|
||||||
|
)
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
DASHBOARD_DIR = os.path.dirname(HERE)
|
||||||
|
LAYOUT_YAML = os.path.join(DASHBOARD_DIR, "cockpit.ti.yaml")
|
||||||
|
POINT_DICT_CSV = os.path.join(
|
||||||
|
DASHBOARD_DIR, os.pardir, "point-dict", "point_dict.default.csv")
|
||||||
|
|
||||||
|
|
||||||
|
def _write_layout(tmp_path: str, content: str) -> str:
|
||||||
|
"""把布局内容写到临时文件,返回路径。"""
|
||||||
|
path = os.path.join(tmp_path, "cockpit.test.yaml")
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write(content)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _write_point_dict(tmp_path: str, ids: list) -> str:
|
||||||
|
"""写一个最小点位字典 CSV(仅 point_id 列)。"""
|
||||||
|
path = os.path.join(tmp_path, "points.csv")
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write("device_id,point_id,name,unit,dataType,sampleRate,qualityCode,opcNode,protocol\n")
|
||||||
|
for i, pid in enumerate(ids):
|
||||||
|
fh.write(f"D{i},{pid},n,u,float,1000,true,n,simulator\n")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
# 最小合法布局模板(便于构造各类变形)
|
||||||
|
_VALID_LAYOUT = """\
|
||||||
|
$schema: iAOP-cockpit-layout-v1
|
||||||
|
title: 测试驾驶舱
|
||||||
|
theme: dark
|
||||||
|
widgets:
|
||||||
|
- type: process_view
|
||||||
|
src: ti_four_state.svg
|
||||||
|
x: 0
|
||||||
|
y: 0
|
||||||
|
w: 12
|
||||||
|
h: 4
|
||||||
|
description: 四状态工艺流程
|
||||||
|
stages:
|
||||||
|
- id: chlorination
|
||||||
|
name: 氯化
|
||||||
|
order: 1
|
||||||
|
- id: purification
|
||||||
|
name: 精制
|
||||||
|
order: 2
|
||||||
|
- id: reduction
|
||||||
|
name: 还原
|
||||||
|
order: 3
|
||||||
|
- id: distillation
|
||||||
|
name: 蒸馏
|
||||||
|
order: 4
|
||||||
|
- type: trend
|
||||||
|
bind: CLF-01.TEMP
|
||||||
|
x: 0
|
||||||
|
y: 4
|
||||||
|
w: 6
|
||||||
|
h: 2
|
||||||
|
description: 氯化炉温度
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class TestEndToEndRealAssets(unittest.TestCase):
|
||||||
|
"""真实 cockpit.ti.yaml + point_dict.default.csv 端到端校验。"""
|
||||||
|
|
||||||
|
def test_real_layout_passes(self):
|
||||||
|
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
|
||||||
|
if not report.passed:
|
||||||
|
for issue in report.errors:
|
||||||
|
print("ERROR:", issue.widget_id, issue.field, issue.reason)
|
||||||
|
self.assertTrue(report.passed, "真实布局应通过全部校验")
|
||||||
|
self.assertGreater(report.widget_count, 0)
|
||||||
|
|
||||||
|
def test_real_layout_has_process_view_with_four_stages(self):
|
||||||
|
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
|
||||||
|
# 无 stages 相关 ERROR
|
||||||
|
stage_errors = [i for i in report.errors if i.field == "stages"]
|
||||||
|
self.assertEqual(stage_errors, [])
|
||||||
|
|
||||||
|
|
||||||
|
class TestWidgetType(unittest.TestCase):
|
||||||
|
"""widget 类型合法性。"""
|
||||||
|
|
||||||
|
def test_invalid_widget_type_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
layout = _VALID_LAYOUT.replace("type: trend", "type: radar_chart")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
errors = [i for i in report.errors if i.field == "type"]
|
||||||
|
self.assertEqual(len(errors), 1)
|
||||||
|
self.assertIn("非法 widget 类型", errors[0].reason)
|
||||||
|
|
||||||
|
|
||||||
|
class TestGridBounds(unittest.TestCase):
|
||||||
|
"""12 列网格校验。"""
|
||||||
|
|
||||||
|
def test_x_plus_w_exceeds_columns(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
# trend x=10 w=6 → 16 > 12
|
||||||
|
layout = _VALID_LAYOUT.replace(
|
||||||
|
" bind: CLF-01.TEMP\n x: 0\n y: 4\n w: 6\n h: 2",
|
||||||
|
" bind: CLF-01.TEMP\n x: 10\n y: 4\n w: 6\n h: 2")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
grid_errors = [i for i in report.errors if i.field == "grid"
|
||||||
|
and "越出" in i.reason]
|
||||||
|
self.assertEqual(len(grid_errors), 1)
|
||||||
|
|
||||||
|
def test_negative_x_rejected(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
layout = _VALID_LAYOUT.replace(" x: 0\n y: 4\n w: 6\n h: 2",
|
||||||
|
" x: -1\n y: 4\n w: 6\n h: 2")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
neg = [i for i in report.errors if "坐标不能为负" in i.reason]
|
||||||
|
self.assertEqual(len(neg), 1)
|
||||||
|
|
||||||
|
def test_zero_width_rejected(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
layout = _VALID_LAYOUT.replace(" x: 0\n y: 4\n w: 6\n h: 2",
|
||||||
|
" x: 0\n y: 4\n w: 0\n h: 2")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
wh = [i for i in report.errors if "w/h 必须为正整数" in i.reason]
|
||||||
|
self.assertEqual(len(wh), 1)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBindPointId(unittest.TestCase):
|
||||||
|
"""bind point_id 在点位字典内。"""
|
||||||
|
|
||||||
|
def test_bind_not_in_dict_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
path = _write_layout(td, _VALID_LAYOUT)
|
||||||
|
# 点位字典不含 CLF-01.TEMP
|
||||||
|
csv_path = _write_point_dict(td, ["OTHER-01.X"])
|
||||||
|
report = LayoutValidator(path, csv_path).validate()
|
||||||
|
bind_err = [i for i in report.errors if i.field == "bind"]
|
||||||
|
self.assertEqual(len(bind_err), 1)
|
||||||
|
self.assertIn("不在点位字典内", bind_err[0].reason)
|
||||||
|
|
||||||
|
def test_bind_in_dict_passes(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
path = _write_layout(td, _VALID_LAYOUT)
|
||||||
|
csv_path = _write_point_dict(td, ["CLF-01.TEMP"])
|
||||||
|
report = LayoutValidator(path, csv_path).validate()
|
||||||
|
bind_err = [i for i in report.errors if i.field == "bind"]
|
||||||
|
self.assertEqual(bind_err, [])
|
||||||
|
|
||||||
|
|
||||||
|
class TestProcessViewStages(unittest.TestCase):
|
||||||
|
"""process_view 四状态覆盖。"""
|
||||||
|
|
||||||
|
def test_missing_process_view_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
# 删除 process_view 块(保留 trend)
|
||||||
|
layout = """\
|
||||||
|
$schema: iAOP-cockpit-layout-v1
|
||||||
|
title: t
|
||||||
|
widgets:
|
||||||
|
- type: trend
|
||||||
|
bind: CLF-01.TEMP
|
||||||
|
x: 0
|
||||||
|
y: 0
|
||||||
|
w: 6
|
||||||
|
h: 2
|
||||||
|
"""
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
pv_err = [i for i in report.errors if i.field == "process_view"]
|
||||||
|
self.assertEqual(len(pv_err), 1)
|
||||||
|
|
||||||
|
def test_missing_required_stage_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
# 删除 distillation stage
|
||||||
|
layout = _VALID_LAYOUT.replace(
|
||||||
|
" - id: distillation\n name: 蒸馏\n order: 4\n", "")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
missing = [i for i in report.errors if "未覆盖必需四状态" in i.reason]
|
||||||
|
self.assertEqual(len(missing), 1)
|
||||||
|
self.assertIn("distillation", missing[0].reason)
|
||||||
|
|
||||||
|
def test_non_monotonic_order_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
# 把 reduction order 改为 5(> distillation 的 4)→ 非单调
|
||||||
|
layout = _VALID_LAYOUT.replace(" - id: reduction\n name: 还原\n order: 3",
|
||||||
|
" - id: reduction\n name: 还原\n order: 5")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
order_err = [i for i in report.errors if "order 非单调递增" in i.reason]
|
||||||
|
self.assertEqual(len(order_err), 1)
|
||||||
|
|
||||||
|
def test_duplicate_stage_id_warn(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
# 重复 chlorination(覆盖必需状态校验仍过,但 WARN 重复)
|
||||||
|
layout = _VALID_LAYOUT + """\
|
||||||
|
"""
|
||||||
|
# 构造一个有重复 stage 的 process_view(替换 stages 块)
|
||||||
|
dup_layout = _VALID_LAYOUT.replace(
|
||||||
|
" - id: distillation\n name: 蒸馏\n order: 4",
|
||||||
|
" - id: distillation\n name: 蒸馏\n order: 4\n"
|
||||||
|
" - id: chlorination\n name: 氯化2\n order: 5")
|
||||||
|
path = _write_layout(td, dup_layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
dup = [i for i in report.issues if "stage id 重复" in i.reason]
|
||||||
|
self.assertEqual(len(dup), 1)
|
||||||
|
|
||||||
|
|
||||||
|
class TestSchemaHeader(unittest.TestCase):
|
||||||
|
"""$schema 头校验。"""
|
||||||
|
|
||||||
|
def test_wrong_schema_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
layout = _VALID_LAYOUT.replace("iAOP-cockpit-layout-v1", "some-other-schema")
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
schema_err = [i for i in report.errors if i.field == "$schema"]
|
||||||
|
self.assertEqual(len(schema_err), 1)
|
||||||
|
|
||||||
|
|
||||||
|
class TestPointDictLoader(unittest.TestCase):
|
||||||
|
"""点位字典 CSV 加载。"""
|
||||||
|
|
||||||
|
def test_load_point_ids(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
csv_path = _write_point_dict(td, ["A.X", "B.Y"])
|
||||||
|
ids = load_point_ids(csv_path)
|
||||||
|
self.assertEqual(ids, ["A.X", "B.Y"])
|
||||||
|
|
||||||
|
def test_missing_csv_raises(self):
|
||||||
|
with self.assertRaises(LayoutError):
|
||||||
|
load_point_ids("/nonexistent/points.csv")
|
||||||
|
|
||||||
|
def test_csv_missing_point_id_column_raises(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
path = os.path.join(td, "bad.csv")
|
||||||
|
with open(path, "w", encoding="utf-8") as fh:
|
||||||
|
fh.write("device_id,name\nD1,n\n")
|
||||||
|
with self.assertRaises(LayoutError):
|
||||||
|
load_point_ids(path)
|
||||||
|
|
||||||
|
|
||||||
|
class TestReportExport(unittest.TestCase):
|
||||||
|
"""报告序列化 + 边界。"""
|
||||||
|
|
||||||
|
def test_empty_layout_error(self):
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
layout = """\
|
||||||
|
$schema: iAOP-cockpit-layout-v1
|
||||||
|
title: t
|
||||||
|
widgets: []
|
||||||
|
"""
|
||||||
|
path = _write_layout(td, layout)
|
||||||
|
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
|
||||||
|
self.assertFalse(report.passed)
|
||||||
|
|
||||||
|
def test_report_to_dict(self):
|
||||||
|
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
|
||||||
|
d = report.to_dict()
|
||||||
|
self.assertEqual(d["passed"], True)
|
||||||
|
self.assertIn("widget_count", d)
|
||||||
|
self.assertEqual(d["error_count"], 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# 前端对话组件(Chat Widget)
|
||||||
|
|
||||||
|
对应 EPIC #11「④ LLM 报警解释 / 交接班 / NL 查询」子任务 **#77**(0.5d):
|
||||||
|
驾驶舱/移动端**对话组件**及配套后端 API(标准库实现,无框架依赖)。
|
||||||
|
|
||||||
|
## 文件
|
||||||
|
|
||||||
|
```
|
||||||
|
web/chat/
|
||||||
|
├── chat_api.py 对话后端 API(http.server):场景分发 + 统一 JSON
|
||||||
|
├── chat_widget.html 前端对话组件(内联 HTML/CSS/JS,深色主题对齐驾驶舱)
|
||||||
|
├── tests/
|
||||||
|
│ └── test_chat_api.py 场景分发 / 端点 / 错误处理测试
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 启动对话 API 服务(默认 127.0.0.1:8080;runner 未注入时仅返回健康/页面)
|
||||||
|
python chat_api.py --host 127.0.0.1 --port 8080
|
||||||
|
```
|
||||||
|
|
||||||
|
浏览器打开 `http://127.0.0.1:8080/` 即见对话组件。
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
| 方法 | 路径 | 说明 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/` | 对话组件页面(chat_widget.html) |
|
||||||
|
| GET | `/api/health` | 健康检查 |
|
||||||
|
| POST | `/api/chat` | 对话接口(见下) |
|
||||||
|
|
||||||
|
`POST /api/chat` 请求体:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "question": "氯气流量最近1小时趋势", "scenario": "nl_query", "confidence": 1.0 }
|
||||||
|
```
|
||||||
|
|
||||||
|
`scenario`:`alarm_explain`(报警解释)/ `shift_handover`(交接班摘要)/
|
||||||
|
`nl_query`(NL 查询,缺省);未知场景降级 `nl_query`。
|
||||||
|
|
||||||
|
响应(统一 JSON):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{ "answer": "...", "route": "local", "answer_id": "...",
|
||||||
|
"scenario": "nl_query", "needs_human": false }
|
||||||
|
```
|
||||||
|
|
||||||
|
## 与场景层集成
|
||||||
|
|
||||||
|
`chat_api.dispatch(runner, request)` 按场景调用 runner 的
|
||||||
|
`explain_alarm / generate_handover / query_cockpit`(与
|
||||||
|
`templates/ti-cl4/llm-scenarios.TiScenarioRunner` 对接);
|
||||||
|
runner 可注入(`make_server(host, port, runner=...)`),便于联调与替换实现。
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python -m unittest discover -s tests -p "test_*.py"
|
||||||
|
```
|
||||||
|
覆盖:三场景分发、空 question、未知场景降级、异常 → error JSON、
|
||||||
|
GET / 与 /api/health、POST /api/chat、非法 JSON 400、404。
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""前端对话组件后端 API —— issue #77(Template-Ti 一期)。
|
||||||
|
|
||||||
|
父 Issue #11「④ LLM 报警解释 / 交接班 / NL 查询」子任务:
|
||||||
|
为驾驶舱/移动端提供对话组件所需的后端 API:
|
||||||
|
|
||||||
|
- `GET /`:返回对话组件页面(chat_widget.html,静态);
|
||||||
|
- `GET /api/health`:服务健康;
|
||||||
|
- `POST /api/chat`:对话接口——按 `scenario` 分发到 Ti 场景
|
||||||
|
(alarm_explain / shift_handover / nl_query),返回统一 JSON:
|
||||||
|
`{answer, route, answer_id, scenario}`。
|
||||||
|
|
||||||
|
纯标准库实现(http.server,无框架依赖),便于联调/内嵌;
|
||||||
|
runner 可注入(测试/替换实现均解耦)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from typing import Optional
|
||||||
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
#: 组件页面路径(相对本模块)
|
||||||
|
WIDGET_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||||
|
"chat_widget.html")
|
||||||
|
|
||||||
|
#: 场景 → runner 方法映射
|
||||||
|
SCENARIO_METHODS = {
|
||||||
|
"alarm_explain": "explain_alarm",
|
||||||
|
"shift_handover": "generate_handover",
|
||||||
|
"nl_query": "query_cockpit",
|
||||||
|
"default": "query_cockpit",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def dispatch(runner, request: dict) -> dict:
|
||||||
|
"""按请求分发到场景 runner,返回统一响应。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
runner: 提供 explain_alarm / generate_handover / query_cockpit 的对象;
|
||||||
|
request: `{question, scenario, confidence?}`。
|
||||||
|
Returns:
|
||||||
|
统一 JSON 字典;场景未知 → 降级 nl_query;异常 → error 响应。
|
||||||
|
"""
|
||||||
|
question = str(request.get("question", "")).strip()
|
||||||
|
scenario = str(request.get("scenario", "default"))
|
||||||
|
confidence = float(request.get("confidence", 1.0))
|
||||||
|
if not question:
|
||||||
|
return {"error": "question 不能为空"}
|
||||||
|
|
||||||
|
method_name = SCENARIO_METHODS.get(
|
||||||
|
scenario, SCENARIO_METHODS["default"])
|
||||||
|
resolved = scenario if scenario in SCENARIO_METHODS else "default"
|
||||||
|
method = getattr(runner, method_name, None)
|
||||||
|
if method is None:
|
||||||
|
return {"error": f"场景 {scenario!r} 未实现"}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = method(question, confidence=confidence)
|
||||||
|
except Exception as exc: # noqa: BLE001 - 统一异常 → error JSON
|
||||||
|
return {"error": f"处理失败: {exc}"}
|
||||||
|
|
||||||
|
return {
|
||||||
|
"answer": result.answer,
|
||||||
|
"route": getattr(result.route, "target", ""),
|
||||||
|
"answer_id": getattr(result, "answer_id", ""),
|
||||||
|
"scenario": resolved,
|
||||||
|
"needs_human": bool(getattr(result, "needs_human", False)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ChatHandler(BaseHTTPRequestHandler):
|
||||||
|
"""对话 API HTTP 处理(GET 组件页 / POST /api/chat)。"""
|
||||||
|
|
||||||
|
#: 场景 runner(由 make_server 注入)
|
||||||
|
runner = None
|
||||||
|
|
||||||
|
def log_message(self, *args): # 静默访问日志
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
path = urlparse(self.path).path
|
||||||
|
if path == "/api/health":
|
||||||
|
self._json(200, {"status": "ok"})
|
||||||
|
return
|
||||||
|
if path in ("/", "/index.html", "/chat_widget.html"):
|
||||||
|
self._html(WIDGET_PATH)
|
||||||
|
return
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
|
||||||
|
def do_POST(self):
|
||||||
|
if urlparse(self.path).path != "/api/chat":
|
||||||
|
self._json(404, {"error": "not found"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
length = int(self.headers.get("Content-Length", 0))
|
||||||
|
request = json.loads(self.rfile.read(length).decode("utf-8"))
|
||||||
|
except (ValueError, json.JSONDecodeError):
|
||||||
|
self._json(400, {"error": "请求体不是合法 JSON"})
|
||||||
|
return
|
||||||
|
self._json(200, dispatch(self.runner, request))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def _json(self, code: int, payload: dict) -> None:
|
||||||
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||||
|
self.send_response(code)
|
||||||
|
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
def _html(self, path: str) -> None:
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
self._json(404, {"error": "widget 页面缺失"})
|
||||||
|
return
|
||||||
|
with open(path, "rb") as fh:
|
||||||
|
body = fh.read()
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header("Content-Type", "text/html; charset=utf-8")
|
||||||
|
self.send_header("Content-Length", str(len(body)))
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(body)
|
||||||
|
|
||||||
|
|
||||||
|
def make_server(host: str, port: int, runner=None) -> ThreadingHTTPServer:
|
||||||
|
"""构建对话 API 服务器(runner 可注入,便于测试/替换)。"""
|
||||||
|
ChatHandler.runner = runner
|
||||||
|
return ThreadingHTTPServer((host, port), ChatHandler)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="对话 API 服务(issue #77)")
|
||||||
|
parser.add_argument("--host", default="127.0.0.1")
|
||||||
|
parser.add_argument("--port", type=int, default=8080)
|
||||||
|
args = parser.parse_args()
|
||||||
|
print(f"对话 API 服务:http://{args.host}:{args.port}/(组件页)")
|
||||||
|
make_server(args.host, args.port).serve_forever()
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>iAOP 对话助手</title>
|
||||||
|
<style>
|
||||||
|
/* iAOP 对话组件(issue #77):深色主题,对齐驾驶舱 */
|
||||||
|
body { margin:0; font-family: "Microsoft YaHei", sans-serif; background:#0f172a; color:#e2e8f0; }
|
||||||
|
#app { max-width: 720px; margin: 0 auto; padding: 16px; }
|
||||||
|
h1 { font-size: 18px; color:#38bdf8; }
|
||||||
|
#messages { height: 420px; overflow-y:auto; border:1px solid #1e293b; border-radius:8px;
|
||||||
|
padding:12px; background:#111c33; }
|
||||||
|
.msg { margin: 8px 0; }
|
||||||
|
.msg .who { font-size:12px; color:#94a3b8; }
|
||||||
|
.msg .text { display:inline-block; max-width:85%; padding:8px 12px; border-radius:8px; white-space:pre-wrap; }
|
||||||
|
.user .text { background:#1d4ed8; }
|
||||||
|
.bot .text { background:#1e293b; }
|
||||||
|
.meta { font-size:11px; color:#64748b; margin-top:2px; }
|
||||||
|
#panel { margin-top:10px; display:flex; gap:8px; }
|
||||||
|
select, input { padding:8px; border-radius:6px; border:1px solid #334155; background:#0b1526; color:#e2e8f0; }
|
||||||
|
input { flex:1; }
|
||||||
|
button { padding:8px 16px; border:none; border-radius:6px; background:#0ea5e9; color:#fff; cursor:pointer; }
|
||||||
|
button:disabled { opacity:.5; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app">
|
||||||
|
<h1>iAOP 对话助手(Template-Ti 一期)</h1>
|
||||||
|
<div id="messages"></div>
|
||||||
|
<div id="panel">
|
||||||
|
<select id="scenario">
|
||||||
|
<option value="nl_query">自然语言查询</option>
|
||||||
|
<option value="alarm_explain">报警解释</option>
|
||||||
|
<option value="shift_handover">交接班摘要</option>
|
||||||
|
</select>
|
||||||
|
<input id="question" placeholder="请输入问题,如:氯气流量最近1小时趋势">
|
||||||
|
<button id="send" onclick="send()">发送</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
const el = id => document.getElementById(id);
|
||||||
|
function addMsg(who, text, meta) {
|
||||||
|
const box = el('messages');
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'msg ' + who;
|
||||||
|
div.innerHTML = '<div class="who">' + (who === 'user' ? '我' : 'iAOP') + '</div>' +
|
||||||
|
'<div class="text"></div>' + (meta ? '<div class="meta">' + meta + '</div>' : '');
|
||||||
|
div.querySelector('.text').textContent = text;
|
||||||
|
box.appendChild(div);
|
||||||
|
box.scrollTop = box.scrollHeight;
|
||||||
|
}
|
||||||
|
async function send() {
|
||||||
|
const question = el('question').value.trim();
|
||||||
|
if (!question) return;
|
||||||
|
const scenario = el('scenario').value;
|
||||||
|
addMsg('user', question);
|
||||||
|
el('question').value = ''; el('send').disabled = true;
|
||||||
|
try {
|
||||||
|
const resp = await fetch('/api/chat', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ question, scenario })
|
||||||
|
});
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.error) addMsg('bot', '错误:' + data.error);
|
||||||
|
else addMsg('bot', data.answer,
|
||||||
|
'路由: ' + data.route + ' | 场景: ' + data.scenario +
|
||||||
|
(data.needs_human ? ' | ⚠ 转人工确认' : ''));
|
||||||
|
} catch (e) {
|
||||||
|
addMsg('bot', '请求失败:' + e);
|
||||||
|
} finally {
|
||||||
|
el('send').disabled = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
el('question').addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""对话 API 测试(issue #77)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. dispatch 场景分发:alarm_explain / shift_handover / nl_query / default;
|
||||||
|
2. 请求校验:空 question、非法场景、异常处理 → error JSON;
|
||||||
|
3. HTTP 端点冒烟(mock runner):GET /、/api/health、POST /api/chat、404。
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
from chat_api import ChatHandler, dispatch # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeResult:
|
||||||
|
def __init__(self, answer="ok", route_target="local", answer_id="a1",
|
||||||
|
needs_human=False):
|
||||||
|
self.answer = answer
|
||||||
|
self.route = mock.MagicMock()
|
||||||
|
self.route.target = route_target
|
||||||
|
self.answer_id = answer_id
|
||||||
|
self.needs_human = needs_human
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeRunner:
|
||||||
|
"""模拟 TiScenarioRunner 三场景方法。"""
|
||||||
|
|
||||||
|
def explain_alarm(self, q, confidence=1.0):
|
||||||
|
return _FakeResult(answer=f"报警解释: {q}", route_target="local")
|
||||||
|
|
||||||
|
def generate_handover(self, q, confidence=1.0):
|
||||||
|
return _FakeResult(answer=f"交接班: {q}", route_target="local")
|
||||||
|
|
||||||
|
def query_cockpit(self, q, confidence=1.0):
|
||||||
|
return _FakeResult(answer=f"查询: {q}", route_target="local")
|
||||||
|
|
||||||
|
|
||||||
|
class TestDispatch(unittest.TestCase):
|
||||||
|
"""场景分发与统一响应。"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.runner = _FakeRunner()
|
||||||
|
|
||||||
|
def test_nl_query_default(self):
|
||||||
|
resp = dispatch(self.runner, {"question": "氯气流量趋势"})
|
||||||
|
self.assertEqual(resp["scenario"], "default")
|
||||||
|
self.assertTrue(resp["answer"].startswith("查询"))
|
||||||
|
|
||||||
|
def test_alarm_explain(self):
|
||||||
|
resp = dispatch(self.runner, {"question": "炉温报警",
|
||||||
|
"scenario": "alarm_explain"})
|
||||||
|
self.assertTrue(resp["answer"].startswith("报警解释"))
|
||||||
|
|
||||||
|
def test_shift_handover(self):
|
||||||
|
resp = dispatch(self.runner, {"question": "甲班交接",
|
||||||
|
"scenario": "shift_handover"})
|
||||||
|
self.assertTrue(resp["answer"].startswith("交接班"))
|
||||||
|
|
||||||
|
def test_empty_question(self):
|
||||||
|
resp = dispatch(self.runner, {"question": " "})
|
||||||
|
self.assertIn("error", resp)
|
||||||
|
|
||||||
|
def test_unknown_scenario_falls_back(self):
|
||||||
|
resp = dispatch(self.runner, {"question": "x",
|
||||||
|
"scenario": "no_such"})
|
||||||
|
self.assertEqual(resp["scenario"], "default")
|
||||||
|
|
||||||
|
def test_runner_exception_to_error(self):
|
||||||
|
bad = mock.MagicMock()
|
||||||
|
bad.query_cockpit.side_effect = RuntimeError("boom")
|
||||||
|
resp = dispatch(bad, {"question": "x"})
|
||||||
|
self.assertIn("处理失败", resp["error"])
|
||||||
|
|
||||||
|
|
||||||
|
class TestHTTPEndpoints(unittest.TestCase):
|
||||||
|
"""HTTP 端点冒烟(直接用 handler 方法 + mock runner)。"""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.handler = ChatHandler.__new__(ChatHandler)
|
||||||
|
self.handler.runner = _FakeRunner()
|
||||||
|
self.handler.wfile = mock.MagicMock()
|
||||||
|
self.handler.send_response = mock.MagicMock()
|
||||||
|
self.handler.send_header = mock.MagicMock()
|
||||||
|
self.handler.end_headers = mock.MagicMock()
|
||||||
|
|
||||||
|
def _json_response(self, code, payload):
|
||||||
|
return json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||||
|
|
||||||
|
def test_get_health(self):
|
||||||
|
self.handler.path = "/api/health"
|
||||||
|
self.handler.do_GET()
|
||||||
|
sent = self.handler.wfile.write.call_args[0][0]
|
||||||
|
self.assertIn(b'"status": "ok"', sent)
|
||||||
|
|
||||||
|
def test_get_widget(self):
|
||||||
|
self.handler.path = "/"
|
||||||
|
with mock.patch("chat_api.WIDGET_PATH",
|
||||||
|
os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||||
|
"..", "chat_widget.html")):
|
||||||
|
self.handler.do_GET()
|
||||||
|
sent = self.handler.wfile.write.call_args[0][0]
|
||||||
|
self.assertIn(b"iAOP", sent)
|
||||||
|
|
||||||
|
def test_post_chat(self):
|
||||||
|
self.handler.path = "/api/chat"
|
||||||
|
self.handler.headers = {"Content-Length": str(
|
||||||
|
len('{"question":"炉温报警","scenario":"alarm_explain"}'))}
|
||||||
|
self.handler.rfile = mock.MagicMock()
|
||||||
|
self.handler.rfile.read.return_value = (
|
||||||
|
'{"question":"炉温报警","scenario":"alarm_explain"}'.encode())
|
||||||
|
self.handler.do_POST()
|
||||||
|
sent = self.handler.wfile.write.call_args[0][0]
|
||||||
|
self.assertIn("报警解释", json.loads(sent.decode())["answer"])
|
||||||
|
|
||||||
|
def test_post_bad_json(self):
|
||||||
|
self.handler.path = "/api/chat"
|
||||||
|
self.handler.headers = {"Content-Length": "3"}
|
||||||
|
self.handler.rfile = mock.MagicMock()
|
||||||
|
self.handler.rfile.read.return_value = b"not json"
|
||||||
|
self.handler.do_POST()
|
||||||
|
sent = self.handler.wfile.write.call_args[0][0]
|
||||||
|
self.assertIn("合法 JSON", sent.decode())
|
||||||
|
|
||||||
|
def test_404(self):
|
||||||
|
self.handler.path = "/nope"
|
||||||
|
self.handler.do_GET()
|
||||||
|
sent = self.handler.wfile.write.call_args[0][0]
|
||||||
|
self.assertIn(b"not found", sent)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user