Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ace09a6d16 |
@@ -0,0 +1,47 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""配置化驾驶舱内核模块(iAOP-Core / cockpit)—— 对齐 PRD 5.5「⑤ 配置化驾驶舱」。
|
||||||
|
|
||||||
|
对外暴露:
|
||||||
|
- ``LAYOUT_SCHEMA_VERSION`` / ``LAYOUT_SCHEMA_ID``:布局 JSON Schema 标识。
|
||||||
|
- ``CockpitLayout`` / ``Widget``:布局与组件的内存模型(dataclass)。
|
||||||
|
- ``validate_layout``:对一份布局资产做结构 + 语义校验,返回校验结果。
|
||||||
|
- ``load_layout``:从已解析的 dict 构造 ``CockpitLayout``(校验失败抛 ``LayoutValidationError``)。
|
||||||
|
|
||||||
|
设计目标(PRD 5.5 验收口径):
|
||||||
|
切换行业模板后,驾驶舱按布局配置自动重排,**无需改前端代码**。
|
||||||
|
本模块只负责"布局资产的定义 + 校验 + 解析",不依赖任何前端框架;
|
||||||
|
渲染层(Vue3 / 配置台)只需消费 ``CockpitLayout`` 的内存模型。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from .layout import ( # noqa: F401
|
||||||
|
DEFAULT_GRID_COLUMNS,
|
||||||
|
LAYOUT_SCHEMA_ID,
|
||||||
|
LAYOUT_SCHEMA_VERSION,
|
||||||
|
PERF_WIDGET_THRESHOLD,
|
||||||
|
VALID_THEMES,
|
||||||
|
VALID_WIDGET_TYPES,
|
||||||
|
CockpitLayout,
|
||||||
|
Grid,
|
||||||
|
LayoutValidationError,
|
||||||
|
LayoutValidationResult,
|
||||||
|
Widget,
|
||||||
|
load_layout,
|
||||||
|
validate_layout,
|
||||||
|
)
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"LAYOUT_SCHEMA_ID",
|
||||||
|
"LAYOUT_SCHEMA_VERSION",
|
||||||
|
"VALID_THEMES",
|
||||||
|
"VALID_WIDGET_TYPES",
|
||||||
|
"DEFAULT_GRID_COLUMNS",
|
||||||
|
"PERF_WIDGET_THRESHOLD",
|
||||||
|
"CockpitLayout",
|
||||||
|
"Grid",
|
||||||
|
"Widget",
|
||||||
|
"LayoutValidationError",
|
||||||
|
"LayoutValidationResult",
|
||||||
|
"load_layout",
|
||||||
|
"validate_layout",
|
||||||
|
]
|
||||||
@@ -0,0 +1,378 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""驾驶舱布局 JSON Schema 定义 + 校验器 + 解析器(issue #50 / PRD 5.5)。
|
||||||
|
|
||||||
|
本文件是 ``$schema: iAOP-cockpit-layout-v1`` 的权威实现:定义布局资产的
|
||||||
|
字段规范、合法性集合,以及一份与现有行业模板(如
|
||||||
|
``templates/resin/dashboard/cockpit.resin.yaml``)完全兼容的校验/解析管线。
|
||||||
|
|
||||||
|
布局资产结构(PRD 5.5 示例)::
|
||||||
|
|
||||||
|
{
|
||||||
|
"$schema": "iAOP-cockpit-layout-v1",
|
||||||
|
"title": "氯化车间驾驶舱",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "process_view", "src": "ti_four_state.svg", "x":0,"y":0,"w":6,"h":4},
|
||||||
|
{"type": "trend", "bind": "CLF-01.TEMP", "x":6,"y":0,"w":6,"h":2},
|
||||||
|
{"type": "kpi_card", "metric": "Ti_purity", "x":6,"y":2,"w":3,"h":2},
|
||||||
|
{"type": "alarm_panel", "x":0,"y":4,"w":12,"h":3}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
字段规范(PRD 5.5「布局 JSON Schema 定义」+「配置点」):
|
||||||
|
$schema string 必填 布局版本标识,固定 ``iAOP-cockpit-layout-v1``。
|
||||||
|
title string 必填 驾驶舱标题(行业模板级,如"氯化车间驾驶舱")。
|
||||||
|
theme enum 必填 主题:``dark`` / ``light``。
|
||||||
|
widgets list 必填 组件清单,至少 1 个;每个 widget 见下表。
|
||||||
|
grid object 选填 栅格基线(默认 12 列);见 ``Grid``。
|
||||||
|
|
||||||
|
widget 字段:
|
||||||
|
type enum 必填 组件类型(见 ``VALID_WIDGET_TYPES``)。
|
||||||
|
x, y int 必填 栅格左上角坐标(≥0)。
|
||||||
|
w, h int 必填 宽/高(>0)。
|
||||||
|
description string 选填 组件说明(实施/行业工程师可读)。
|
||||||
|
src string 条件必填 ``process_view`` 必填,流程图 SVG 资源名。
|
||||||
|
bind string 条件必填 ``trend`` 必填,绑定的点位/指标 ID(如 CLF-01.TEMP)。
|
||||||
|
metric string 条件必填 ``kpi_card`` 必填,指标键(如 Ti_purity)。
|
||||||
|
label string 选填 ``kpi_card`` 展示标签。
|
||||||
|
|
||||||
|
复杂仪表盘性能(PRD 5.5)由渲染层负责:组件 ≥ 30 或数据点 ≥ 500 时启用
|
||||||
|
虚拟滚动 + 采样降频 + WebWorker,保证首屏 ≤ 2s。本 schema 不强制该阈值,
|
||||||
|
仅在 ``LayoutValidationResult`` 中提示组件数,便于上层决策。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 布局版本标识(被 templates/resin/dashboard/cockpit.resin.yaml 的 $schema 引用)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
LAYOUT_SCHEMA_ID: str = "iAOP-cockpit-layout-v1"
|
||||||
|
LAYOUT_SCHEMA_VERSION: int = 1
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 合法性集合
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 主题(PRD 5.5「配置点:主题」)
|
||||||
|
VALID_THEMES: Tuple[str, ...] = ("dark", "light")
|
||||||
|
|
||||||
|
# 组件类型(PRD 5.5「能力:四状态工艺流程视图、实时趋势、KPI卡片、告警面板、NL查询入口」)
|
||||||
|
VALID_WIDGET_TYPES: Tuple[str, ...] = (
|
||||||
|
"process_view", # 四状态工艺流程视图
|
||||||
|
"trend", # 实时趋势
|
||||||
|
"kpi_card", # KPI 卡片
|
||||||
|
"alarm_panel", # 告警面板
|
||||||
|
"nl_query", # 自然语言查询入口
|
||||||
|
)
|
||||||
|
|
||||||
|
# 默认栅格基线(PRD 5.5 示例使用 12 列;resin 模板亦按 12 列布局)
|
||||||
|
DEFAULT_GRID_COLUMNS: int = 12
|
||||||
|
|
||||||
|
# 性能提示阈值(PRD 5.5「复杂仪表盘性能」)
|
||||||
|
PERF_WIDGET_THRESHOLD: int = 30
|
||||||
|
|
||||||
|
# 各组件类型必填的特有字段(type → 字段名)
|
||||||
|
_WIDGET_REQUIRED_FIELDS: Dict[str, Tuple[str, ...]] = {
|
||||||
|
"process_view": ("src",),
|
||||||
|
"trend": ("bind",),
|
||||||
|
"kpi_card": ("metric",),
|
||||||
|
"alarm_panel": (),
|
||||||
|
"nl_query": (),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 异常 / 结果
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class LayoutValidationError(ValueError):
|
||||||
|
"""布局资产校验失败。``load_layout`` 在校验不通过时抛出。
|
||||||
|
|
||||||
|
``errors`` 收集全部字段级错误,便于配置台「错误列表(行号+原因)」展示。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, errors: List[str]):
|
||||||
|
super().__init__("; ".join(errors) if errors else "layout validation failed")
|
||||||
|
self.errors: List[str] = list(errors)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class LayoutValidationResult:
|
||||||
|
"""``validate_layout`` 的返回值,区分「是否合法」与「全部错误清单」。"""
|
||||||
|
|
||||||
|
ok: bool
|
||||||
|
errors: List[str] = field(default_factory=list)
|
||||||
|
widget_count: int = 0
|
||||||
|
perf_hint: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 内存模型(dataclass)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
@dataclass
|
||||||
|
class Widget:
|
||||||
|
"""单个驾驶舱组件的内存模型。"""
|
||||||
|
|
||||||
|
type: str
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
w: int
|
||||||
|
h: int
|
||||||
|
description: Optional[str] = None
|
||||||
|
# 以下为按 type 选填/必填的特有字段,统一存放,解析时已校验存在性
|
||||||
|
src: Optional[str] = None
|
||||||
|
bind: Optional[str] = None
|
||||||
|
metric: Optional[str] = None
|
||||||
|
label: Optional[str] = None
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
"""序列化回布局资产 dict(仅保留有值/必填字段,便于发布)。"""
|
||||||
|
d: Dict[str, Any] = {
|
||||||
|
"type": self.type,
|
||||||
|
"x": self.x,
|
||||||
|
"y": self.y,
|
||||||
|
"w": self.w,
|
||||||
|
"h": self.h,
|
||||||
|
}
|
||||||
|
if self.description is not None:
|
||||||
|
d["description"] = self.description
|
||||||
|
if self.src is not None:
|
||||||
|
d["src"] = self.src
|
||||||
|
if self.bind is not None:
|
||||||
|
d["bind"] = self.bind
|
||||||
|
if self.metric is not None:
|
||||||
|
d["metric"] = self.metric
|
||||||
|
if self.label is not None:
|
||||||
|
d["label"] = self.label
|
||||||
|
return d
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Grid:
|
||||||
|
"""栅格基线(默认 12 列,可由行业模板覆盖)。"""
|
||||||
|
|
||||||
|
columns: int = DEFAULT_GRID_COLUMNS
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CockpitLayout:
|
||||||
|
"""一份完整驾驶舱布局的内存模型。
|
||||||
|
|
||||||
|
渲染层(Vue3 / 配置台)仅消费本对象:切换行业模板 = 加载另一份
|
||||||
|
``CockpitLayout``,**前端代码零改动**即满足 PRD 5.5 验收口径。
|
||||||
|
"""
|
||||||
|
|
||||||
|
title: str
|
||||||
|
theme: str
|
||||||
|
widgets: List[Widget]
|
||||||
|
grid: Grid = field(default_factory=Grid)
|
||||||
|
schema: str = LAYOUT_SCHEMA_ID
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
"""序列化为可发布的布局资产 dict(结构对齐 PRD 5.5 示例)。"""
|
||||||
|
return {
|
||||||
|
"$schema": self.schema,
|
||||||
|
"title": self.title,
|
||||||
|
"theme": self.theme,
|
||||||
|
"grid": {"columns": self.grid.columns},
|
||||||
|
"widgets": [w.to_dict() for w in self.widgets],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 校验器
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _require_type(value: Any, name: str, expected: type, errors: List[str], ctx: str) -> None:
|
||||||
|
"""检查 ``value`` 是 ``expected`` 类型,失败则追加一条错误。"""
|
||||||
|
# bool 是 int 的子类,栅格坐标不应接受 bool;此处显式排除
|
||||||
|
if expected is int and isinstance(value, bool):
|
||||||
|
errors.append(f"{ctx}: {name} 必须是整数,实际为 bool")
|
||||||
|
return
|
||||||
|
if not isinstance(value, expected):
|
||||||
|
errors.append(f"{ctx}: {name} 必须是 {expected.__name__},实际为 {type(value).__name__}")
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_widget(widget: Any, index: int, grid_columns: int, errors: List[str]) -> None:
|
||||||
|
"""校验单个 widget dict,错误追加到 ``errors``。"""
|
||||||
|
ctx = f"widgets[{index}]"
|
||||||
|
if not isinstance(widget, dict):
|
||||||
|
errors.append(f"{ctx}: 组件必须是对象(dict)")
|
||||||
|
return
|
||||||
|
|
||||||
|
# type
|
||||||
|
wtype = widget.get("type")
|
||||||
|
if not isinstance(wtype, str) or not wtype:
|
||||||
|
errors.append(f"{ctx}: type 缺失或非字符串")
|
||||||
|
wtype = ""
|
||||||
|
elif wtype not in VALID_WIDGET_TYPES:
|
||||||
|
errors.append(
|
||||||
|
f"{ctx}: type '{wtype}' 非法,合法值 {list(VALID_WIDGET_TYPES)}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 栅格坐标 x/y/w/h(必填整数)
|
||||||
|
for key in ("x", "y", "w", "h"):
|
||||||
|
if key not in widget:
|
||||||
|
errors.append(f"{ctx}: 缺少必填字段 {key}")
|
||||||
|
else:
|
||||||
|
_require_type(widget[key], key, int, errors, ctx)
|
||||||
|
val = widget[key]
|
||||||
|
if isinstance(val, int) and not isinstance(val, bool):
|
||||||
|
if key in ("x", "y") and val < 0:
|
||||||
|
errors.append(f"{ctx}: {key} 必须 ≥ 0,实际 {val}")
|
||||||
|
if key in ("w", "h") and val <= 0:
|
||||||
|
errors.append(f"{ctx}: {key} 必须 > 0,实际 {val}")
|
||||||
|
# 越界:x + w 不应超过栅格列数(提示级,不阻断合法性,但记一条 warning 风格错误便于配置台纠正)
|
||||||
|
try:
|
||||||
|
x = widget["x"]
|
||||||
|
w = widget["w"]
|
||||||
|
if (
|
||||||
|
isinstance(x, int)
|
||||||
|
and isinstance(w, int)
|
||||||
|
and not isinstance(x, bool)
|
||||||
|
and not isinstance(w, bool)
|
||||||
|
and x + w > grid_columns
|
||||||
|
):
|
||||||
|
errors.append(
|
||||||
|
f"{ctx}: x+w={x + w} 超过栅格列数 {grid_columns},布局会被压缩"
|
||||||
|
)
|
||||||
|
except (KeyError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# type 特有必填字段
|
||||||
|
if wtype in _WIDGET_REQUIRED_FIELDS:
|
||||||
|
for fname in _WIDGET_REQUIRED_FIELDS[wtype]:
|
||||||
|
val = widget.get(fname)
|
||||||
|
if not isinstance(val, str) or not val:
|
||||||
|
errors.append(f"{ctx}: type='{wtype}' 要求字段 {fname} 非空字符串")
|
||||||
|
|
||||||
|
# kpi_card 可选 label(若有则必须字符串)
|
||||||
|
label = widget.get("label")
|
||||||
|
if label is not None and not isinstance(label, str):
|
||||||
|
errors.append(f"{ctx}: label 必须是字符串")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_layout(data: Any) -> LayoutValidationResult:
|
||||||
|
"""对一份布局资产(已解析的 dict)做完整校验。
|
||||||
|
|
||||||
|
返回 ``LayoutValidationResult``:``ok`` 表示是否通过,``errors`` 收集全部
|
||||||
|
字段级错误,``widget_count`` / ``perf_hint`` 供上层做性能决策。
|
||||||
|
"""
|
||||||
|
errors: List[str] = []
|
||||||
|
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return LayoutValidationResult(ok=False, errors=["布局根必须是对象(dict)"])
|
||||||
|
|
||||||
|
# $schema
|
||||||
|
schema = data.get("$schema")
|
||||||
|
if schema is None:
|
||||||
|
errors.append("缺少 $schema 字段")
|
||||||
|
elif schema != LAYOUT_SCHEMA_ID:
|
||||||
|
errors.append(
|
||||||
|
f"$schema='{schema}' 不被支持,当前版本 '{LAYOUT_SCHEMA_ID}'"
|
||||||
|
)
|
||||||
|
|
||||||
|
# title
|
||||||
|
title = data.get("title")
|
||||||
|
if not isinstance(title, str) or not title.strip():
|
||||||
|
errors.append("title 缺失或为空字符串")
|
||||||
|
|
||||||
|
# theme
|
||||||
|
theme = data.get("theme")
|
||||||
|
if theme is None:
|
||||||
|
errors.append("缺少 theme 字段")
|
||||||
|
elif theme not in VALID_THEMES:
|
||||||
|
errors.append(f"theme='{theme}' 非法,合法值 {list(VALID_THEMES)}")
|
||||||
|
|
||||||
|
# grid(可选)
|
||||||
|
grid_columns = DEFAULT_GRID_COLUMNS
|
||||||
|
grid = data.get("grid")
|
||||||
|
if grid is not None:
|
||||||
|
if not isinstance(grid, dict):
|
||||||
|
errors.append("grid 必须是对象(dict)")
|
||||||
|
else:
|
||||||
|
cols = grid.get("columns")
|
||||||
|
if cols is None:
|
||||||
|
errors.append("grid.columns 缺失")
|
||||||
|
else:
|
||||||
|
_require_type(cols, "columns", int, errors, "grid")
|
||||||
|
if isinstance(cols, int) and not isinstance(cols, bool) and cols <= 0:
|
||||||
|
errors.append(f"grid.columns 必须 > 0,实际 {cols}")
|
||||||
|
grid_columns = cols
|
||||||
|
elif isinstance(cols, int) and not isinstance(cols, bool):
|
||||||
|
grid_columns = cols
|
||||||
|
|
||||||
|
# widgets
|
||||||
|
widgets = data.get("widgets")
|
||||||
|
if widgets is None:
|
||||||
|
errors.append("缺少 widgets 字段")
|
||||||
|
widgets = []
|
||||||
|
if not isinstance(widgets, list):
|
||||||
|
errors.append("widgets 必须是数组(list)")
|
||||||
|
widgets = []
|
||||||
|
elif len(widgets) == 0:
|
||||||
|
errors.append("widgets 不能为空(至少 1 个组件)")
|
||||||
|
|
||||||
|
for idx, w in enumerate(widgets):
|
||||||
|
_validate_widget(w, idx, grid_columns, errors)
|
||||||
|
|
||||||
|
widget_count = len(widgets) if isinstance(widgets, list) else 0
|
||||||
|
perf_hint = None
|
||||||
|
if widget_count >= PERF_WIDGET_THRESHOLD:
|
||||||
|
perf_hint = (
|
||||||
|
f"组件数 {widget_count} ≥ {PERF_WIDGET_THRESHOLD},渲染层应启用"
|
||||||
|
"虚拟滚动 + 采样降频 + WebWorker(PRD 5.5)"
|
||||||
|
)
|
||||||
|
|
||||||
|
return LayoutValidationResult(
|
||||||
|
ok=len(errors) == 0,
|
||||||
|
errors=errors,
|
||||||
|
widget_count=widget_count,
|
||||||
|
perf_hint=perf_hint,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 解析器
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _coerce_int(v: Any) -> int:
|
||||||
|
"""已校验为 int(非 bool)后取值。"""
|
||||||
|
return v # type: ignore[return-value]
|
||||||
|
|
||||||
|
|
||||||
|
def load_layout(data: Dict[str, Any]) -> CockpitLayout:
|
||||||
|
"""从已解析的 dict 构造 ``CockpitLayout``;校验失败抛 ``LayoutValidationError``。
|
||||||
|
|
||||||
|
调用前通常先用 ``validate_layout`` 判断,但本方法内部仍会再校验一次,
|
||||||
|
确保构造出的内存模型恒为合法资产。
|
||||||
|
"""
|
||||||
|
result = validate_layout(data)
|
||||||
|
if not result.ok:
|
||||||
|
raise LayoutValidationError(result.errors)
|
||||||
|
|
||||||
|
grid_raw = data.get("grid") or {}
|
||||||
|
grid = Grid(columns=grid_raw.get("columns", DEFAULT_GRID_COLUMNS))
|
||||||
|
|
||||||
|
widgets: List[Widget] = []
|
||||||
|
for w in data["widgets"]:
|
||||||
|
widgets.append(
|
||||||
|
Widget(
|
||||||
|
type=w["type"],
|
||||||
|
x=_coerce_int(w["x"]),
|
||||||
|
y=_coerce_int(w["y"]),
|
||||||
|
w=_coerce_int(w["w"]),
|
||||||
|
h=_coerce_int(w["h"]),
|
||||||
|
description=w.get("description"),
|
||||||
|
src=w.get("src"),
|
||||||
|
bind=w.get("bind"),
|
||||||
|
metric=w.get("metric"),
|
||||||
|
label=w.get("label"),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return CockpitLayout(
|
||||||
|
title=data["title"],
|
||||||
|
theme=data["theme"],
|
||||||
|
widgets=widgets,
|
||||||
|
grid=grid,
|
||||||
|
schema=data.get("$schema", LAYOUT_SCHEMA_ID),
|
||||||
|
)
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""驾驶舱布局 JSON Schema 验证脚本(issue #50,PRD 5.5 验收口径)。
|
||||||
|
|
||||||
|
验证三个能力点:
|
||||||
|
1. **PRD 5.5 原始示例**(氯化车间)通过 ``iAOP-cockpit-layout-v1`` 校验;
|
||||||
|
2. **现有树脂模板资产兼容**:``templates/resin/dashboard/cockpit.resin.yaml``
|
||||||
|
所描述的布局(等价 dict)通过同一套校验,证明"切换模板零改码"已具备基础;
|
||||||
|
3. **负例**:一份故意破坏的布局被正确拒绝(证明阈值判断有效)。
|
||||||
|
|
||||||
|
用法(在 core/cockpit 目录下):
|
||||||
|
python scripts/verify_layout_schema.py
|
||||||
|
退出码:0 = 全部通过;1 = 存在未达标项。
|
||||||
|
|
||||||
|
说明:树脂驾驶舱资产本身是 YAML;本脚本不依赖 PyYAML(避免引入运行时依赖),
|
||||||
|
而是用与该 YAML 文件内容等价的 dict 进行校验——schema 字段语义完全一致,
|
||||||
|
若安装了 PyYAML,可直接解析原文件复现(见文末注释)。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 本脚本位于 core/cockpit/scripts/,需要把 core/ 加入 sys.path,
|
||||||
|
# 才能 `from cockpit import ...`(cockpit 包位于 core/cockpit)
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
||||||
|
|
||||||
|
from cockpit import LAYOUT_SCHEMA_ID, validate_layout # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def _check(name: str, data: dict, expect_ok: bool) -> bool:
|
||||||
|
res = validate_layout(data)
|
||||||
|
status = "PASS" if res.ok == expect_ok else "FAIL"
|
||||||
|
print(f"[{status}] {name}: ok={res.ok} widgets={res.widget_count}")
|
||||||
|
if res.ok != expect_ok:
|
||||||
|
for e in res.errors:
|
||||||
|
print(f" - {e}")
|
||||||
|
return False
|
||||||
|
if res.ok and res.perf_hint:
|
||||||
|
print(f" perf_hint: {res.perf_hint}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
all_ok = True
|
||||||
|
|
||||||
|
# 1) PRD 5.5 原始示例(氯化车间)
|
||||||
|
prd_example = {
|
||||||
|
"$schema": "iAOP-cockpit-layout-v1",
|
||||||
|
"title": "氯化车间驾驶舱",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
||||||
|
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
||||||
|
{"type": "kpi_card", "metric": "Ti_purity", "x": 6, "y": 2, "w": 3, "h": 2},
|
||||||
|
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
all_ok &= _check("PRD 5.5 示例(氯化车间)", prd_example, expect_ok=True)
|
||||||
|
|
||||||
|
# 2) 现有树脂模板资产兼容(与 templates/resin/dashboard/cockpit.resin.yaml 等价)
|
||||||
|
resin_layout = {
|
||||||
|
"$schema": LAYOUT_SCHEMA_ID,
|
||||||
|
"title": "吸附树脂车间驾驶舱",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4,
|
||||||
|
"description": "四状态工艺流程(合成 → 交联 → 洗涤 → 干燥)"},
|
||||||
|
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2,
|
||||||
|
"description": "反应釜温度实时趋势"},
|
||||||
|
{"type": "trend", "bind": "R-801.AGIT", "x": 6, "y": 4, "w": 6, "h": 2,
|
||||||
|
"description": "搅拌转速实时趋势"},
|
||||||
|
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
||||||
|
"x": 0, "y": 6, "w": 3, "h": 2, "description": "当批平均交换容量(mmol/g)"},
|
||||||
|
{"type": "kpi_card", "metric": "resin_crosslink_degree", "label": "交联度",
|
||||||
|
"x": 3, "y": 6, "w": 3, "h": 2, "description": "当批平均交联度(%)"},
|
||||||
|
{"type": "kpi_card", "metric": "batch_yield", "label": "批产率",
|
||||||
|
"x": 6, "y": 6, "w": 3, "h": 2, "description": "当批产率(%)"},
|
||||||
|
{"type": "kpi_card", "metric": "energy_per_ton", "label": "单吨能耗",
|
||||||
|
"x": 9, "y": 6, "w": 3, "h": 2, "description": "单吨树脂综合能耗(kWh/t)"},
|
||||||
|
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3,
|
||||||
|
"description": "告警面板(温度/交联度/质量预测异常)"},
|
||||||
|
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3,
|
||||||
|
"description": "自然语言查询入口(配方/质量/能耗问答)"},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
all_ok &= _check("树脂模板资产(向后兼容)", resin_layout, expect_ok=True)
|
||||||
|
|
||||||
|
# 3) 负例:kpi_card 缺 metric,应被拒绝
|
||||||
|
broken = {
|
||||||
|
"$schema": LAYOUT_SCHEMA_ID,
|
||||||
|
"title": "坏布局",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "kpi_card", "x": 0, "y": 0, "w": 3, "h": 2}, # 缺 metric
|
||||||
|
],
|
||||||
|
}
|
||||||
|
all_ok &= _check("负例(kpi_card 缺 metric)应被拒绝", broken, expect_ok=False)
|
||||||
|
|
||||||
|
print()
|
||||||
|
print("全部通过 ✅" if all_ok else "存在未达标项 ❌")
|
||||||
|
return 0 if all_ok else 1
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""驾驶舱布局 JSON Schema 校验/解析测试(issue #50 / PRD 5.5)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. PRD 5.5 示例布局(氯化车间)合法 → 校验通过、可解析为 ``CockpitLayout``;
|
||||||
|
2. 现有树脂模板资产兼容(``iAOP-cockpit-layout-v1``);
|
||||||
|
3. 各类非法情况:错误的 $schema / theme / type、缺失必填、坐标越界、
|
||||||
|
空组件清单、栅格列数非法、特有字段缺失;
|
||||||
|
4. 性能提示:组件数 ≥ 30 触发 ``perf_hint``;
|
||||||
|
5. ``load_layout`` 校验失败抛 ``LayoutValidationError`` 并携带全部错误。
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from cockpit import ( # type: ignore[import-not-found]
|
||||||
|
LAYOUT_SCHEMA_ID,
|
||||||
|
LAYOUT_SCHEMA_VERSION,
|
||||||
|
PERF_WIDGET_THRESHOLD,
|
||||||
|
VALID_THEMES,
|
||||||
|
VALID_WIDGET_TYPES,
|
||||||
|
CockpitLayout,
|
||||||
|
LayoutValidationError,
|
||||||
|
Widget,
|
||||||
|
load_layout,
|
||||||
|
validate_layout,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _valid_layout() -> dict:
|
||||||
|
"""返回 PRD 5.5 示例(氯化车间)合法布局。"""
|
||||||
|
return {
|
||||||
|
"$schema": "iAOP-cockpit-layout-v1",
|
||||||
|
"title": "氯化车间驾驶舱",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
||||||
|
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
||||||
|
{"type": "kpi_card", "metric": "Ti_purity", "label": "Ti 纯度", "x": 6, "y": 2, "w": 3, "h": 2},
|
||||||
|
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
||||||
|
{"type": "nl_query", "x": 9, "y": 2, "w": 3, "h": 2},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _resin_like_layout() -> dict:
|
||||||
|
"""模拟 templates/resin/dashboard/cockpit.resin.yaml 的结构(已引用 v1 schema)。"""
|
||||||
|
return {
|
||||||
|
"$schema": "iAOP-cockpit-layout-v1",
|
||||||
|
"title": "吸附树脂车间驾驶舱",
|
||||||
|
"theme": "dark",
|
||||||
|
"widgets": [
|
||||||
|
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4,
|
||||||
|
"description": "四状态工艺流程"},
|
||||||
|
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2},
|
||||||
|
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
||||||
|
"x": 0, "y": 6, "w": 3, "h": 2},
|
||||||
|
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3},
|
||||||
|
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestSchemaConstants(unittest.TestCase):
|
||||||
|
"""版本标识与合法性集合。"""
|
||||||
|
|
||||||
|
def test_schema_id_matches_template_reference(self):
|
||||||
|
# templates/resin/dashboard/cockpit.resin.yaml 引用的 $schema 必须与此处一致
|
||||||
|
self.assertEqual(LAYOUT_SCHEMA_ID, "iAOP-cockpit-layout-v1")
|
||||||
|
self.assertEqual(LAYOUT_SCHEMA_VERSION, 1)
|
||||||
|
|
||||||
|
def test_valid_themes(self):
|
||||||
|
self.assertEqual(set(VALID_THEMES), {"dark", "light"})
|
||||||
|
|
||||||
|
def test_valid_widget_types_cover_prd_capabilities(self):
|
||||||
|
# PRD 5.5 能力:四状态流程视图 / 实时趋势 / KPI卡片 / 告警面板 / NL查询入口
|
||||||
|
for required in ("process_view", "trend", "kpi_card", "alarm_panel", "nl_query"):
|
||||||
|
self.assertIn(required, VALID_WIDGET_TYPES)
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidateValidLayouts(unittest.TestCase):
|
||||||
|
"""合法布局应通过校验。"""
|
||||||
|
|
||||||
|
def test_prd_example_is_valid(self):
|
||||||
|
res = validate_layout(_valid_layout())
|
||||||
|
self.assertTrue(res.ok, msg=f"expected ok, errors={res.errors}")
|
||||||
|
self.assertEqual(res.widget_count, 5)
|
||||||
|
self.assertIsNone(res.perf_hint)
|
||||||
|
|
||||||
|
def test_resin_like_layout_is_valid(self):
|
||||||
|
# 现有树脂模板资产兼容(向后兼容关键)
|
||||||
|
res = validate_layout(_resin_like_layout())
|
||||||
|
self.assertTrue(res.ok, msg=f"errors={res.errors}")
|
||||||
|
|
||||||
|
def test_light_theme_valid(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["theme"] = "light"
|
||||||
|
self.assertTrue(validate_layout(data).ok)
|
||||||
|
|
||||||
|
def test_custom_grid_columns_valid(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["grid"] = {"columns": 24}
|
||||||
|
self.assertTrue(validate_layout(data).ok)
|
||||||
|
|
||||||
|
|
||||||
|
class TestValidateInvalidLayouts(unittest.TestCase):
|
||||||
|
"""各类非法布局应在 errors 中给出对应原因。"""
|
||||||
|
|
||||||
|
def test_root_not_dict(self):
|
||||||
|
res = validate_layout(["not", "a", "dict"])
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
|
||||||
|
def test_wrong_schema(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["$schema"] = "iAOP-cockpit-layout-v0"
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("$schema" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_missing_schema(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
del data["$schema"]
|
||||||
|
self.assertFalse(validate_layout(data).ok)
|
||||||
|
|
||||||
|
def test_invalid_theme(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["theme"] = "neon"
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("theme" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_empty_title(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["title"] = " "
|
||||||
|
self.assertFalse(validate_layout(data).ok)
|
||||||
|
|
||||||
|
def test_empty_widgets(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"] = []
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("widgets" in e and "空" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_unknown_widget_type(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0]["type"] = "magic_chart"
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("type" in e and "非法" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_missing_required_widget_field_process_view(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
del data["widgets"][0]["src"] # process_view 要求 src
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("src" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_missing_required_widget_field_trend_bind(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
del data["widgets"][1]["bind"] # trend 要求 bind
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("bind" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_missing_required_widget_field_kpi_metric(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
del data["widgets"][2]["metric"] # kpi_card 要求 metric
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("metric" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_negative_x(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0]["x"] = -1
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("x" in e and "≥ 0" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_zero_w(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0]["w"] = 0
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("w" in e and "> 0" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_bool_not_accepted_as_int(self):
|
||||||
|
# bool 是 int 子类,栅格坐标不应接受 True/False
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0]["x"] = True
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("x" in e and "bool" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_grid_columns_non_positive(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["grid"] = {"columns": 0}
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("columns" in e and "> 0" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_overflow_grid_warning(self):
|
||||||
|
# x+w 超过栅格列数 → 记一条提示(用于配置台纠正),仍可在 errors 中体现
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0]["x"] = 10
|
||||||
|
data["widgets"][0]["w"] = 6 # 10+6=16 > 12
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertTrue(any("超过栅格列数" in e for e in res.errors))
|
||||||
|
|
||||||
|
def test_widget_not_dict(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"][0] = "broken"
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertFalse(res.ok)
|
||||||
|
self.assertTrue(any("对象" in e for e in res.errors))
|
||||||
|
|
||||||
|
|
||||||
|
class TestPerfHint(unittest.TestCase):
|
||||||
|
"""组件数 ≥ 30 时应给出性能提示(PRD 5.5 复杂仪表盘性能)。"""
|
||||||
|
|
||||||
|
def test_perf_hint_when_many_widgets(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["widgets"] = [
|
||||||
|
{"type": "kpi_card", "metric": f"m{i}", "x": 0, "y": 0, "w": 1, "h": 1}
|
||||||
|
for i in range(PERF_WIDGET_THRESHOLD)
|
||||||
|
]
|
||||||
|
res = validate_layout(data)
|
||||||
|
# 全部 kpi_card 合法 → ok=True,但有性能提示
|
||||||
|
self.assertEqual(res.widget_count, PERF_WIDGET_THRESHOLD)
|
||||||
|
self.assertIsNotNone(res.perf_hint)
|
||||||
|
self.assertIn("虚拟滚动", res.perf_hint or "")
|
||||||
|
|
||||||
|
def test_no_perf_hint_below_threshold(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
res = validate_layout(data)
|
||||||
|
self.assertIsNone(res.perf_hint)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLoadLayout(unittest.TestCase):
|
||||||
|
"""load_layout 解析合法资产为 CockpitLayout,非法时抛异常。"""
|
||||||
|
|
||||||
|
def test_load_valid_returns_model(self):
|
||||||
|
layout = load_layout(_valid_layout())
|
||||||
|
self.assertIsInstance(layout, CockpitLayout)
|
||||||
|
self.assertEqual(layout.title, "氯化车间驾驶舱")
|
||||||
|
self.assertEqual(layout.theme, "dark")
|
||||||
|
self.assertEqual(layout.schema, LAYOUT_SCHEMA_ID)
|
||||||
|
self.assertEqual(len(layout.widgets), 5)
|
||||||
|
# 栅格默认 12 列
|
||||||
|
self.assertEqual(layout.grid.columns, 12)
|
||||||
|
# 组件字段映射
|
||||||
|
pv = layout.widgets[0]
|
||||||
|
self.assertIsInstance(pv, Widget)
|
||||||
|
self.assertEqual(pv.type, "process_view")
|
||||||
|
self.assertEqual(pv.src, "ti_four_state.svg")
|
||||||
|
kpi = layout.widgets[2]
|
||||||
|
self.assertEqual(kpi.metric, "Ti_purity")
|
||||||
|
self.assertEqual(kpi.label, "Ti 纯度")
|
||||||
|
|
||||||
|
def test_load_invalid_raises_with_errors(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
data["theme"] = "neon"
|
||||||
|
del data["widgets"][1]["bind"]
|
||||||
|
with self.assertRaises(LayoutValidationError) as cm:
|
||||||
|
load_layout(data)
|
||||||
|
# 异常应携带全部错误(不止一条)
|
||||||
|
self.assertGreaterEqual(len(cm.exception.errors), 2)
|
||||||
|
|
||||||
|
def test_roundtrip_to_dict(self):
|
||||||
|
# 解析后再序列化,结构应可再次通过校验(round-trip 稳定)
|
||||||
|
layout = load_layout(_valid_layout())
|
||||||
|
again = validate_layout(layout.to_dict())
|
||||||
|
self.assertTrue(again.ok, msg=f"roundtrip errors={again.errors}")
|
||||||
|
|
||||||
|
def test_roundtrip_preserves_resin_layout(self):
|
||||||
|
layout = load_layout(_resin_like_layout())
|
||||||
|
again = validate_layout(layout.to_dict())
|
||||||
|
self.assertTrue(again.ok, msg=f"errors={again.errors}")
|
||||||
|
self.assertEqual(layout.title, "吸附树脂车间驾驶舱")
|
||||||
|
|
||||||
|
|
||||||
|
class TestDeepCopySafety(unittest.TestCase):
|
||||||
|
"""校验不应污染入参;调用方可继续使用原 dict。"""
|
||||||
|
|
||||||
|
def test_validate_does_not_mutate_input(self):
|
||||||
|
data = _valid_layout()
|
||||||
|
snapshot = copy.deepcopy(data)
|
||||||
|
validate_layout(data)
|
||||||
|
self.assertEqual(data, snapshot)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -10,7 +10,6 @@ topic / 时序库表 / 关系表 / 对象桶:换行业只改模板资产(模
|
|||||||
| 文件 | 职责 |
|
| 文件 | 职责 |
|
||||||
|------|------|
|
|------|------|
|
||||||
| `templating.py` | 模板命名推导:Kafka topic + 分区策略、TDengine 超级表/子表、PostgreSQL schema/表、MinIO 桶/对象键 |
|
| `templating.py` | 模板命名推导:Kafka topic + 分区策略、TDengine 超级表/子表、PostgreSQL schema/表、MinIO 桶/对象键 |
|
||||||
| `kafka_naming.py` | Kafka topic 命名/分区模板化组件(issue #28):配置外置、点位维度覆盖、按 (topic,partition) 生产路由 |
|
|
||||||
| `tdengine_schema.py` | 时序库 schema 自动生成(超级表 + 每测点子表,**依据点位字典**)+ 批量 INSERT SQL |
|
| `tdengine_schema.py` | 时序库 schema 自动生成(超级表 + 每测点子表,**依据点位字典**)+ 批量 INSERT SQL |
|
||||||
| `postgres_schema.py` | 关系库 schema(模板 / 模型 / 用户 / 权限)+ 角色授权语句 |
|
| `postgres_schema.py` | 关系库 schema(模板 / 模型 / 用户 / 权限)+ 角色授权语句 |
|
||||||
| `batch_writer.py` | 批量写入缓冲:批量聚合(默认 5000 条/0.1s,对齐 PRD 5.2「5k/100ms」基线)、幂等去重、失败重试 —— **数据不丢不重** |
|
| `batch_writer.py` | 批量写入缓冲:批量聚合(默认 5000 条/0.1s,对齐 PRD 5.2「5k/100ms」基线)、幂等去重、失败重试 —— **数据不丢不重** |
|
||||||
|
|||||||
@@ -8,7 +8,6 @@ topic / 时序库表 / 关系表 / 对象桶,换行业只改模板资产(YAM
|
|||||||
|
|
||||||
模块:
|
模块:
|
||||||
- templating 模板命名推导(Kafka topic/分区、TDengine 表、PG schema、MinIO 桶);
|
- templating 模板命名推导(Kafka topic/分区、TDengine 表、PG schema、MinIO 桶);
|
||||||
- kafka_naming Kafka topic 命名/分区模板化组件(配置外置 + 点位维度覆盖 + 生产路由);
|
|
||||||
- tdengine_schema 时序超级表/子表 DDL + 批量 INSERT SQL 生成;
|
- tdengine_schema 时序超级表/子表 DDL + 批量 INSERT SQL 生成;
|
||||||
- postgres_schema 关系库 schema(模板/模型/用户/权限)+ 授权语句;
|
- postgres_schema 关系库 schema(模板/模型/用户/权限)+ 授权语句;
|
||||||
- batch_writer 批量写入缓冲(StoreSink 抽象 / MemorySink / TdengineSink),
|
- batch_writer 批量写入缓冲(StoreSink 抽象 / MemorySink / TdengineSink),
|
||||||
@@ -25,7 +24,6 @@ from .batch_writer import (
|
|||||||
StoreSink,
|
StoreSink,
|
||||||
TdengineSink,
|
TdengineSink,
|
||||||
)
|
)
|
||||||
from .kafka_naming import KafkaTopicNaming
|
|
||||||
from .postgres_schema import generate_grant_ddl, generate_schema_ddl
|
from .postgres_schema import generate_grant_ddl, generate_schema_ddl
|
||||||
from .tdengine_schema import (
|
from .tdengine_schema import (
|
||||||
PointSpec,
|
PointSpec,
|
||||||
@@ -41,7 +39,6 @@ __all__ = [
|
|||||||
"TemplateNaming",
|
"TemplateNaming",
|
||||||
"sanitize",
|
"sanitize",
|
||||||
"sanitize_sql",
|
"sanitize_sql",
|
||||||
"KafkaTopicNaming",
|
|
||||||
"PointSpec",
|
"PointSpec",
|
||||||
"generate_supertable_ddl",
|
"generate_supertable_ddl",
|
||||||
"generate_subtable_ddls",
|
"generate_subtable_ddls",
|
||||||
|
|||||||
@@ -1,30 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
# 模板「Kafka 命名/分区」配置资产示例:ti-cl4(氯化车间/海绵钛,Template-Ti 一期)。
|
|
||||||
#
|
|
||||||
# 说明(issue #28 / PRD 5.2「② 数据总线 + 时序库」):
|
|
||||||
# - topic 模板:`{topic_prefix}.{device_id}.points`(与 edge-gateway 上行一致);
|
|
||||||
# - 分区:hash(device_id) % num_partitions,单设备分区内有序;
|
|
||||||
# - per_point_topics:点位维度覆盖(点位前缀命中 → 独立 topic),
|
|
||||||
# 用于质量标签(LAB-*)、告警(ALM-*)等独立消费通道;
|
|
||||||
# - 换行业只改本文件(template / topic_prefix / 分区数),内核零改动。
|
|
||||||
template: ti-cl4
|
|
||||||
version: 1.0.0
|
|
||||||
|
|
||||||
kafka:
|
|
||||||
# topic 前缀(缺省 = template 名);建议形如 iaop.<模板>
|
|
||||||
topic_prefix: iaop.ti-cl4
|
|
||||||
# 每 topic 分区数:按设备数 × 吞吐评估(600 点位 1Hz 建议 ≥ 12)
|
|
||||||
num_partitions: 12
|
|
||||||
# 副本数:生产建议 ≥ 2(联调可 1)
|
|
||||||
replication_factor: 1
|
|
||||||
# 生产者确认:all 保证不丢(配合 spool 断点续传)
|
|
||||||
acks: all
|
|
||||||
# 消息保留时长(小时):与数据保留策略(#33)联动
|
|
||||||
retention_hours: 168
|
|
||||||
|
|
||||||
# 点位维度 topic 覆盖(可选):point_id 前缀命中 → 独立 topic
|
|
||||||
per_point_topics:
|
|
||||||
- point_id_prefix: "LAB-"
|
|
||||||
topic: "iaop.ti-cl4.quality.points" # 质量标签独立通道(LIMS 对接)
|
|
||||||
- point_id_prefix: "ALM-"
|
|
||||||
topic: "iaop.ti-cl4.alarm.points" # 告警独立通道
|
|
||||||
@@ -1,136 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""Kafka topic 命名 / 分区模板化(按模板 + 点位维度)—— issue #28 / PRD 5.2。
|
|
||||||
|
|
||||||
在 #4(EPIC)templating 命名雏形之上,交付**完整模板化 Kafka 组件**:
|
|
||||||
|
|
||||||
- **topic**:`{topic_prefix}.{device_id}.points`(与 edge-gateway 上行
|
|
||||||
`upstream/kafka_sink.py` 完全一致,链路互通);
|
|
||||||
- **分区**:`hash(device_id) % num_partitions` 一致性哈希,
|
|
||||||
保证单设备分区内严格有序(关键:趋势/告警按设备有序消费);
|
|
||||||
- **点位维度覆盖**:特定点位前缀可路由到独立 topic
|
|
||||||
(如质量标签 `LAB-*` → 质检专用 topic),模板配置驱动;
|
|
||||||
- **生产路由**:`routing(rows)` 按 (topic, partition) 批量分组,
|
|
||||||
供 Kafka 生产者批量发送(对齐 PRD 5.2「5k/100ms」批量基线)。
|
|
||||||
|
|
||||||
全部参数来自模板配置资产 `config/kafka.template.yaml`:换行业只改配置,
|
|
||||||
内核零改动。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
from typing import Dict, List, Optional, Sequence, Tuple
|
|
||||||
|
|
||||||
from data_bus.templating import TemplateNaming, sanitize
|
|
||||||
|
|
||||||
#: 默认配置资产路径(相对本模块)
|
|
||||||
DEFAULT_CONFIG_PATH = os.path.join(
|
|
||||||
os.path.dirname(os.path.abspath(__file__)), "config", "kafka.template.yaml")
|
|
||||||
|
|
||||||
|
|
||||||
class KafkaTopicNaming:
|
|
||||||
"""Kafka topic/分区模板化命名(模板 + 点位维度)。"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
template: str,
|
|
||||||
topic_prefix: Optional[str] = None,
|
|
||||||
num_partitions: int = 12,
|
|
||||||
replication_factor: int = 1,
|
|
||||||
acks: str = "all",
|
|
||||||
retention_hours: int = 168,
|
|
||||||
per_point_topics: Optional[List[dict]] = None,
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
Args:
|
|
||||||
template: 行业模板名(如 ti-cl4 / resin);
|
|
||||||
topic_prefix: topic 前缀(缺省 = 模板名);
|
|
||||||
num_partitions: 每 topic 分区数(分区策略 hash(device_id)%n);
|
|
||||||
replication_factor: 副本数(生产建议 ≥ 2,联调可 1);
|
|
||||||
acks: 生产者确认级别(all 保证不丢);
|
|
||||||
retention_hours: 消息保留时长(小时);
|
|
||||||
per_point_topics: 点位维度 topic 覆盖规则
|
|
||||||
`[{"point_id_prefix": "LAB-", "topic": "..."}]`。
|
|
||||||
"""
|
|
||||||
self._tpl = TemplateNaming(
|
|
||||||
template, topic_prefix=topic_prefix, num_partitions=num_partitions)
|
|
||||||
self.num_partitions = self._tpl.num_partitions
|
|
||||||
self.replication_factor = max(1, int(replication_factor))
|
|
||||||
self.acks = acks
|
|
||||||
self.retention_hours = max(1, int(retention_hours))
|
|
||||||
# 点位前缀 → 覆盖 topic(前缀长优先匹配)
|
|
||||||
self._per_point: List[tuple] = sorted(
|
|
||||||
((str(r["point_id_prefix"]), sanitize(r["topic"]))
|
|
||||||
for r in (per_point_topics or []) if r.get("point_id_prefix")),
|
|
||||||
key=lambda kv: len(kv[0]), reverse=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
@classmethod
|
|
||||||
def from_template_config(cls, path: str = DEFAULT_CONFIG_PATH) -> "KafkaTopicNaming":
|
|
||||||
"""从模板配置资产加载(config/kafka.template.yaml)。"""
|
|
||||||
import yaml
|
|
||||||
with open(path, "r", encoding="utf-8") as fh:
|
|
||||||
raw = yaml.safe_load(fh) or {}
|
|
||||||
k = raw.get("kafka", {}) or {}
|
|
||||||
return cls(
|
|
||||||
template=str(raw.get("template", "default")),
|
|
||||||
topic_prefix=k.get("topic_prefix"),
|
|
||||||
num_partitions=int(k.get("num_partitions", 12)),
|
|
||||||
replication_factor=int(k.get("replication_factor", 1)),
|
|
||||||
acks=str(k.get("acks", "all")),
|
|
||||||
retention_hours=int(k.get("retention_hours", 168)),
|
|
||||||
per_point_topics=k.get("per_point_topics", []),
|
|
||||||
)
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
def topic(self, device_id: str, point_id: Optional[str] = None) -> str:
|
|
||||||
"""上行 topic:`{topic_prefix}.{device_id}.points`。
|
|
||||||
|
|
||||||
与 edge-gateway `upstream/kafka_sink.py` 完全一致(device_id 原样,
|
|
||||||
不做小写化——Kafka topic 允许大写,点位字典校验保证合法字符)。
|
|
||||||
点位维度覆盖:point_id 命中某前缀规则时路由到覆盖 topic
|
|
||||||
(如质量标签 LAB-* → 质检专用 topic),否则走设备默认 topic。
|
|
||||||
"""
|
|
||||||
if point_id is not None:
|
|
||||||
for prefix, topic in self._per_point:
|
|
||||||
if point_id.startswith(prefix):
|
|
||||||
return topic
|
|
||||||
return f"{self._tpl.topic_prefix}.{device_id}.points"
|
|
||||||
|
|
||||||
def partition(self, device_id: str) -> int:
|
|
||||||
"""分区:device_id 一致性哈希(单设备分区内有序)。"""
|
|
||||||
return self._tpl.partition(device_id)
|
|
||||||
|
|
||||||
def partitions(self, device_ids: Sequence[str]) -> dict:
|
|
||||||
"""设备 → 分区映射(配置台预览)。"""
|
|
||||||
return self._tpl.partitions(list(device_ids), self.num_partitions)
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
def routing(self, rows: Sequence[dict]) -> Dict[Tuple[str, int], List[dict]]:
|
|
||||||
"""按 (topic, partition) 批量分组样本行(Kafka 生产者路由)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
rows: 样本行 `[{"device_id", "point_id", "value", "ts", ...}]`;
|
|
||||||
无 point_id 的行按设备维度路由。
|
|
||||||
Returns:
|
|
||||||
{(topic, partition): [rows]} —— 每组可批量发送。
|
|
||||||
"""
|
|
||||||
groups: Dict[Tuple[str, int], List[dict]] = {}
|
|
||||||
for row in rows:
|
|
||||||
device_id = str(row.get("device_id", ""))
|
|
||||||
point_id = row.get("point_id")
|
|
||||||
key = (self.topic(device_id, point_id), self.partition(device_id))
|
|
||||||
groups.setdefault(key, []).append(row)
|
|
||||||
return groups
|
|
||||||
|
|
||||||
def brief(self) -> dict:
|
|
||||||
"""配置摘要(部署/巡检用)。"""
|
|
||||||
return {
|
|
||||||
"template": self._tpl.template,
|
|
||||||
"topic_prefix": self._tpl.topic_prefix,
|
|
||||||
"num_partitions": self.num_partitions,
|
|
||||||
"replication_factor": self.replication_factor,
|
|
||||||
"acks": self.acks,
|
|
||||||
"retention_hours": self.retention_hours,
|
|
||||||
"per_point_rules": [p for p, _ in self._per_point],
|
|
||||||
}
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""Kafka topic 命名/分区模板化测试(issue #28)。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
1. 模板配置资产加载(config/kafka.template.yaml,含点位维度覆盖规则);
|
|
||||||
2. topic 推导:`{topic_prefix}.{device_id}.points`(与 edge-gateway 上行一致);
|
|
||||||
3. 分区:device_id 一致性哈希(确定性、单设备分区内有序);
|
|
||||||
4. 点位维度覆盖:LAB-* 前缀 → 质检独立 topic,其余走设备 topic;
|
|
||||||
5. 生产路由:按 (topic, partition) 批量分组。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
import _bootstrap # noqa: F401
|
|
||||||
|
|
||||||
from data_bus.kafka_naming import ( # noqa: E402
|
|
||||||
DEFAULT_CONFIG_PATH,
|
|
||||||
KafkaTopicNaming,
|
|
||||||
)
|
|
||||||
|
|
||||||
CONFIG = os.path.join(
|
|
||||||
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
|
|
||||||
"config", "kafka.template.yaml",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def sample(device_id="CLF-01", point_id="CLF-01.TEMP", value=850.5, ts=1.0):
|
|
||||||
return {"device_id": device_id, "point_id": point_id,
|
|
||||||
"value": value, "ts": ts}
|
|
||||||
|
|
||||||
|
|
||||||
class TestConfigLoad(unittest.TestCase):
|
|
||||||
"""模板配置资产加载与摘要。"""
|
|
||||||
|
|
||||||
def test_from_template_config(self):
|
|
||||||
naming = KafkaTopicNaming.from_template_config(CONFIG)
|
|
||||||
self.assertEqual(naming._tpl.template, "ti-cl4")
|
|
||||||
self.assertEqual(naming.num_partitions, 12)
|
|
||||||
self.assertEqual(naming.acks, "all")
|
|
||||||
self.assertEqual(naming.retention_hours, 168)
|
|
||||||
brief = naming.brief()
|
|
||||||
self.assertIn("LAB-", brief["per_point_rules"])
|
|
||||||
self.assertIn("ALM-", brief["per_point_rules"])
|
|
||||||
|
|
||||||
def test_default_config_path_exists(self):
|
|
||||||
self.assertTrue(os.path.isfile(DEFAULT_CONFIG_PATH))
|
|
||||||
|
|
||||||
|
|
||||||
class TestTopicNaming(unittest.TestCase):
|
|
||||||
"""topic 推导(与 edge-gateway 上行格式一致)。"""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
self.naming = KafkaTopicNaming.from_template_config(CONFIG)
|
|
||||||
|
|
||||||
def test_device_topic_format(self):
|
|
||||||
# 与 upstream/kafka_sink.py 的 {prefix}.{device}.points 一致
|
|
||||||
self.assertEqual(self.naming.topic("CLF-01"),
|
|
||||||
"iaop.ti-cl4.CLF-01.points")
|
|
||||||
self.assertEqual(self.naming.topic("S7-01"),
|
|
||||||
"iaop.ti-cl4.S7-01.points")
|
|
||||||
|
|
||||||
def test_point_level_topic_override(self):
|
|
||||||
# LAB-* 前缀命中质量标签独立通道;普通点走设备 topic
|
|
||||||
self.assertEqual(
|
|
||||||
self.naming.topic("CLF-01", point_id="LAB-01.TI_PURITY"),
|
|
||||||
"iaop.ti-cl4.quality.points")
|
|
||||||
self.assertEqual(
|
|
||||||
self.naming.topic("CLF-01", point_id="ALM-01.TEMP_HI"),
|
|
||||||
"iaop.ti-cl4.alarm.points")
|
|
||||||
self.assertEqual(
|
|
||||||
self.naming.topic("CLF-01", point_id="CLF-01.TEMP"),
|
|
||||||
"iaop.ti-cl4.CLF-01.points")
|
|
||||||
|
|
||||||
def test_sanitize_device_id(self):
|
|
||||||
# device_id 原样保留(与 edge-gateway 上行一致,点位字典保证合法)
|
|
||||||
self.assertEqual(self.naming.topic("CLF-01"),
|
|
||||||
"iaop.ti-cl4.CLF-01.points")
|
|
||||||
|
|
||||||
|
|
||||||
class TestPartition(unittest.TestCase):
|
|
||||||
"""分区一致性哈希:确定性 + 单设备有序。"""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
self.naming = KafkaTopicNaming.from_template_config(CONFIG)
|
|
||||||
|
|
||||||
def test_deterministic(self):
|
|
||||||
self.assertEqual(self.naming.partition("CLF-01"),
|
|
||||||
self.naming.partition("CLF-01"))
|
|
||||||
self.assertIn(self.naming.partition("CLF-01"), range(12))
|
|
||||||
|
|
||||||
def test_same_device_same_partition(self):
|
|
||||||
# 单设备所有点位落到同一分区 → 分区内有序
|
|
||||||
p1 = self.naming.partition("CLF-01")
|
|
||||||
for pid in ("CLF-01.TEMP", "CLF-01.PRES", "CLF-01.FEED"):
|
|
||||||
self.assertEqual(self.naming.partition("CLF-01"), p1)
|
|
||||||
|
|
||||||
def test_partitions_preview(self):
|
|
||||||
mapping = self.naming.partitions(["CLF-01", "S7-01", "E-01"])
|
|
||||||
self.assertEqual(set(mapping), {"CLF-01", "S7-01", "E-01"})
|
|
||||||
self.assertTrue(all(0 <= v < 12 for v in mapping.values()))
|
|
||||||
|
|
||||||
|
|
||||||
class TestRouting(unittest.TestCase):
|
|
||||||
"""按 (topic, partition) 批量分组(生产路由)。"""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
self.naming = KafkaTopicNaming.from_template_config(CONFIG)
|
|
||||||
|
|
||||||
def test_group_by_topic_and_partition(self):
|
|
||||||
rows = [
|
|
||||||
sample("CLF-01", "CLF-01.TEMP"),
|
|
||||||
sample("CLF-01", "CLF-01.PRES"),
|
|
||||||
sample("CLF-01", "LAB-01.TI_PURITY"), # 质量标签 → 独立 topic
|
|
||||||
sample("S7-01", "S7-01.PUMP_A"),
|
|
||||||
]
|
|
||||||
groups = self.naming.routing(rows)
|
|
||||||
# 3 个不同 (topic, partition) 组:CLF 默认 / LAB 质量 / S7
|
|
||||||
self.assertEqual(len(groups), 3)
|
|
||||||
topics = {t for t, _ in groups}
|
|
||||||
self.assertIn("iaop.ti-cl4.quality.points", topics)
|
|
||||||
# CLF 默认 topic 内 2 条同一分区
|
|
||||||
clf_key = ("iaop.ti-cl4.CLF-01.points",
|
|
||||||
self.naming.partition("CLF-01"))
|
|
||||||
self.assertEqual(len(groups[clf_key]), 2)
|
|
||||||
|
|
||||||
def test_rows_without_point_id(self):
|
|
||||||
rows = [{"device_id": "CLF-01", "value": 1.0, "ts": 2.0}]
|
|
||||||
groups = self.naming.routing(rows)
|
|
||||||
self.assertEqual(len(groups), 1)
|
|
||||||
key = next(iter(groups))
|
|
||||||
self.assertEqual(key[0], "iaop.ti-cl4.CLF-01.points")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
# iAOP-Core · 模型框架层(AI Model Framework)
|
|
||||||
|
|
||||||
对应 PRD 5.3「③ AI 模型框架」与 EPIC #5「内核平台化改造」。
|
|
||||||
|
|
||||||
本层把化工 AI 的「模型流水线」从硬编码改造为**编排化、配置化**实现:每个
|
|
||||||
步骤是可插拔的 `Step`,步骤间数据通过 `Context` 流转,整条流水线由声明式
|
|
||||||
配置驱动——切换模型 / 数据源只改配置,编排代码零改动。
|
|
||||||
|
|
||||||
## 当前已交付
|
|
||||||
|
|
||||||
| 模块 | 对应 issue | PRD 5.3 模型 | 说明 |
|
|
||||||
|------|-----------|-------------|------|
|
|
||||||
| `pipeline` | #40 | ③ 训练/推理流水线编排 | 数据→训练→评估→注册→加载→推理一条龙编排 |
|
|
||||||
|
|
||||||
## 训练 / 推理流水线(`pipeline.py`)
|
|
||||||
|
|
||||||
模型从「开发」到「上线」是一条流水线:**数据准备 → 特征工程 → 训练 → 评估 →
|
|
||||||
注册(版本化) → 加载 → 推理 → 监控**。手写脚本拼接不可复用、不可审计、不可
|
|
||||||
重放。本模块把这条流水线编排化、配置化。
|
|
||||||
|
|
||||||
### 核心组件
|
|
||||||
|
|
||||||
- **`Step` 抽象基类**:`prepare` / `run` / `teardown` 三段式生命周期。内置:
|
|
||||||
- `LoadDataStep`(CSV / 内存加载数据)
|
|
||||||
- `TrainStep`(可插拔 `Estimator` 训练)
|
|
||||||
- `EvaluateStep`(accuracy / MAE / RMSE)
|
|
||||||
- `RegisterStep`(注册到 `ModelRegistry`,版本化)
|
|
||||||
- `LoadModelStep`(按版本 / 别名加载)
|
|
||||||
- `PredictStep`(批量推理)
|
|
||||||
- `CustomStep`(可调用 handler 快速接入业务)
|
|
||||||
- **`Pipeline` 编排器**:顺序执行 Step,自动传递 Context,支持 `dry_run` / 失败短路。
|
|
||||||
- **`Context`**:步骤间数据流转(params 只读 + artifacts 可写)。
|
|
||||||
- **`ModelRegistry`**:内存模型注册表(多版本 + latest/stable 别名),对接 issue #41 雏形。
|
|
||||||
- **`Estimator`**:可插拔训练算法(`MeanRegressor` / `MajorityClassifier` stub,无外部依赖)。
|
|
||||||
- **`PipelineConfig`**:声明式配置,`from_dict` / `to_dict` 可序列化往返。
|
|
||||||
|
|
||||||
### 快速开始
|
|
||||||
|
|
||||||
```python
|
|
||||||
from pipeline import (Pipeline, LoadDataStep, TrainStep, EvaluateStep,
|
|
||||||
RegisterStep, LoadModelStep, PredictStep)
|
|
||||||
|
|
||||||
# 切换模型 / 数据源只改配置,编排代码零改动
|
|
||||||
pipe = Pipeline("demo", [
|
|
||||||
LoadDataStep("load", {"source": [[1, 10], [2, 20], [3, 30]]}), # 末列 target
|
|
||||||
TrainStep("train", {"estimator": "mean_regressor"}),
|
|
||||||
EvaluateStep("eval", {}),
|
|
||||||
RegisterStep("register", {"model_name": "demo", "version": "v1"}),
|
|
||||||
LoadModelStep("load_model", {"model_name": "demo", "version": "v1"}),
|
|
||||||
PredictStep("predict", {"input_key": "dataset"}),
|
|
||||||
])
|
|
||||||
result = pipe.run()
|
|
||||||
print(result.success, result.step_results)
|
|
||||||
```
|
|
||||||
|
|
||||||
### 声明式配置驱动
|
|
||||||
|
|
||||||
```python
|
|
||||||
from pipeline import Pipeline, PipelineConfig
|
|
||||||
|
|
||||||
cfg = PipelineConfig("config-driven", steps=[
|
|
||||||
{"type": "load_data", "name": "load", "params": {"source": rows}},
|
|
||||||
{"type": "train", "name": "train", "params": {"estimator": "mean_regressor"}},
|
|
||||||
{"type": "evaluate", "name": "eval", "params": {}},
|
|
||||||
{"type": "register", "name": "reg", "params": {"model_name": "demo", "version": "v1"}},
|
|
||||||
{"type": "load_model", "name": "lm", "params": {"model_name": "demo", "version": "v1"}},
|
|
||||||
{"type": "predict", "name": "pred", "params": {"input_key": "dataset"}},
|
|
||||||
])
|
|
||||||
result = Pipeline.from_config(cfg).run()
|
|
||||||
```
|
|
||||||
|
|
||||||
## 测试
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd core/model-framework
|
|
||||||
python -m unittest discover -s tests -v
|
|
||||||
python _sanity_check.py
|
|
||||||
```
|
|
||||||
|
|
||||||
## 与规划模块的关系
|
|
||||||
|
|
||||||
接口风格对齐 issue #34(Model Recipe)、#36(quality_forecast)、#38
|
|
||||||
(cross_process_optimizer)。本模块**自包含、不依赖未合并分支**;`TrainStep`
|
|
||||||
的 `Estimator` 可插拔,未来可对接 #36 质量预测模型作为具名 estimator,
|
|
||||||
`RegisterStep` 可对接 #41 完整版本机制,业务侧零改动。
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""iAOP-Core · 模型框架层(AI Model Framework)。
|
|
||||||
|
|
||||||
对应 PRD 5.3「③ AI 模型框架」与 EPIC #5(内核平台化改造)。
|
|
||||||
|
|
||||||
当前已交付(自包含,不依赖未合并分支):
|
|
||||||
- ``pipeline``:训练 / 推理流水线编排(声明式配置驱动,可插拔 Step / Estimator),
|
|
||||||
issue #40。数据准备→训练→评估→注册→加载→推理一条龙编排,切换模型 / 数据源
|
|
||||||
只改配置,编排代码零改动——对齐 PRD 5.3「配置化」默认模式。
|
|
||||||
|
|
||||||
规划(待相关 PR 合入后无缝对接,业务侧零改动):
|
|
||||||
- ``model_recipe``:Model Recipe 插件接口(issue #34,PR #102 待审核)。
|
|
||||||
- ``quality_forecast``:质量预测模型模板化(issue #36,PR #103 待审核)。
|
|
||||||
- ``cross_process_optimizer``:跨工序寻优(issue #38,PR #106 待审核)。
|
|
||||||
届时它们可注册为本层 ``Estimator`` / ``Step`` 的具名实现。
|
|
||||||
"""
|
|
||||||
from model_framework.pipeline import ( # noqa: F401
|
|
||||||
Context,
|
|
||||||
CustomStep,
|
|
||||||
ESTIMATORS,
|
|
||||||
EvaluateStep,
|
|
||||||
Estimator,
|
|
||||||
LoadDataStep,
|
|
||||||
LoadModelStep,
|
|
||||||
MajorityClassifier,
|
|
||||||
MeanRegressor,
|
|
||||||
ModelArtifact,
|
|
||||||
ModelRegistry,
|
|
||||||
Pipeline,
|
|
||||||
PipelineConfig,
|
|
||||||
PipelineError,
|
|
||||||
PipelineResult,
|
|
||||||
PredictStep,
|
|
||||||
RegisterStep,
|
|
||||||
Step,
|
|
||||||
StepResult,
|
|
||||||
TrainStep,
|
|
||||||
register_estimator,
|
|
||||||
register_step_type,
|
|
||||||
)
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""训练 / 推理流水线编排 sanity 检查(无构建环境下的离线基本验证)。
|
|
||||||
|
|
||||||
验证 PRD 5.3「数据准备→训练→评估→注册→加载→推理」一条龙编排跑通:
|
|
||||||
1. 用内置 stub 估计器,端到端跑通完整流水线;
|
|
||||||
2. 模型可注册到 ModelRegistry 并按版本 / 别名加载;
|
|
||||||
3. 切换估计器(mean_regressor / majority_classifier)只改配置,编排代码零改动;
|
|
||||||
4. 声明式 PipelineConfig 可驱动同一条流水线。
|
|
||||||
|
|
||||||
用法:python _sanity_check.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
if HERE not in sys.path:
|
|
||||||
sys.path.insert(0, HERE)
|
|
||||||
|
|
||||||
from pipeline import ( # noqa: E402
|
|
||||||
LoadDataStep,
|
|
||||||
LoadModelStep,
|
|
||||||
EvaluateStep,
|
|
||||||
Pipeline,
|
|
||||||
PipelineConfig,
|
|
||||||
PredictStep,
|
|
||||||
RegisterStep,
|
|
||||||
TrainStep,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def run_demo(estimator: str, dataset, expected_pred: float):
|
|
||||||
pipe = Pipeline(f"demo-{estimator}", [
|
|
||||||
LoadDataStep("load", {"source": dataset}),
|
|
||||||
TrainStep("train", {"estimator": estimator}),
|
|
||||||
EvaluateStep("eval", {}),
|
|
||||||
RegisterStep("register", {"model_name": "demo", "version": "v1"}),
|
|
||||||
LoadModelStep("load_model", {"model_name": "demo", "version": "v1"}),
|
|
||||||
PredictStep("predict", {"input_key": "dataset"}),
|
|
||||||
])
|
|
||||||
result = pipe.run()
|
|
||||||
assert result.success, f"流水线失败:{result.failed_step}"
|
|
||||||
preds = pipe # placeholder
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
|
|
||||||
# 回归 demo(mean_regressor)
|
|
||||||
reg_dataset = [[1, 10], [2, 20], [3, 30]] # 末列 target,均值 20
|
|
||||||
try:
|
|
||||||
r1 = run_demo("mean_regressor", reg_dataset, 20.0)
|
|
||||||
print(f"[mean_regressor] 流水线成功,{len(r1.step_results)} 步,"
|
|
||||||
f"耗时 {r1.total_duration_s:.3f}s")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
failures.append(f"mean_regressor 流水线失败:{exc}")
|
|
||||||
|
|
||||||
# 分类 demo(majority_classifier)
|
|
||||||
cls_dataset = [[1, 0], [2, 1], [3, 1]] # 末列 target,多数 1
|
|
||||||
try:
|
|
||||||
r2 = run_demo("majority_classifier", cls_dataset, 1.0)
|
|
||||||
print(f"[majority_classifier] 流水线成功,{len(r2.step_results)} 步,"
|
|
||||||
f"耗时 {r2.total_duration_s:.3f}s")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
failures.append(f"majority_classifier 流水线失败:{exc}")
|
|
||||||
|
|
||||||
# 配置驱动:同一流水线用声明式配置构建
|
|
||||||
try:
|
|
||||||
cfg = PipelineConfig("config-driven", steps=[
|
|
||||||
{"type": "load_data", "name": "load", "params": {"source": reg_dataset}},
|
|
||||||
{"type": "train", "name": "train", "params": {"estimator": "mean_regressor"}},
|
|
||||||
{"type": "evaluate", "name": "eval", "params": {}},
|
|
||||||
{"type": "register", "name": "reg", "params": {"model_name": "demo", "version": "v2"}},
|
|
||||||
{"type": "load_model", "name": "lm", "params": {"model_name": "demo", "version": "v2"}},
|
|
||||||
{"type": "predict", "name": "pred", "params": {"input_key": "dataset"}},
|
|
||||||
])
|
|
||||||
r3 = Pipeline.from_config(cfg).run()
|
|
||||||
assert r3.success, "配置驱动流水线失败"
|
|
||||||
print(f"[config-driven] 配置驱动流水线成功,{len(r3.step_results)} 步")
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
failures.append(f"配置驱动流水线失败:{exc}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("\n失败项:")
|
|
||||||
for f in failures:
|
|
||||||
print(f" ✗ {f}")
|
|
||||||
return 1
|
|
||||||
print("\n✓ pipeline sanity check 通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,675 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""训练 / 推理流水线编排(对接 PRD 5.3 ③ 模型框架)。
|
|
||||||
|
|
||||||
对应 issue #40(父 EPIC #5「③ AI 模型框架 配置化重构」、PRD 5.3
|
|
||||||
「③ 训练 / 推理流水线编排」)。
|
|
||||||
|
|
||||||
PRD 5.3 的核心诉求
|
|
||||||
------------------
|
|
||||||
|
|
||||||
模型从「开发」到「上线」是一条流水线:**数据准备 → 特征工程 → 训练 →
|
|
||||||
评估 → 注册(版本化) → 加载 → 推理 → 监控**。手写脚本拼接这些步骤
|
|
||||||
不可复用、不可审计、不可重放。PRD 5.3 要求把这条流水线**编排化、配置化**:
|
|
||||||
每个步骤是一个可插拔的 ``Step``,步骤之间的数据通过 ``Context`` 流转,
|
|
||||||
整条流水线由一个声明式 JSON / Python 配置驱动——切换模型 / 数据源只改
|
|
||||||
配置,编排代码零改动。
|
|
||||||
|
|
||||||
本模块交付什么
|
|
||||||
--------------
|
|
||||||
|
|
||||||
1. **``Step`` 抽象基类**:``prepare`` / ``run`` / ``teardown`` 三段式生命周期,
|
|
||||||
输入输出通过 ``Context`` 传递。内置若干常用步骤:
|
|
||||||
- ``LoadDataStep``:从 CSV / 内存加载数据;
|
|
||||||
- ``TrainStep``:调用可插拔 ``Estimator``(默认 stub,可换 sklearn)训练;
|
|
||||||
- ``EvaluateStep``:计算 accuracy / MAE / RMSE 等指标;
|
|
||||||
- ``RegisterStep``:把训练产物注册到内存 ``ModelRegistry``(版本化);
|
|
||||||
- ``LoadModelStep``:从 registry 按版本加载模型;
|
|
||||||
- ``PredictStep``:用加载的模型批量推理。
|
|
||||||
2. **``Pipeline`` 编排器**:顺序执行若干 ``Step``,自动传递 ``Context``,
|
|
||||||
支持 ``dry_run``(只校验配置不执行)、失败短路、产物收集。
|
|
||||||
3. **``Context``**:流水线上下文(不可变快照 + 可写 working dict),承载
|
|
||||||
数据 / 模型 / 指标 / 元信息,步骤间解耦。
|
|
||||||
4. **``ModelRegistry``**:内存模型注册表(版本化 + 别名 latest/stable),
|
|
||||||
对接 issue #41「模型模板注册 / 加载 / 版本机制」的雏形。
|
|
||||||
5. **``PipelineConfig``**:声明式配置,``from_dict`` / ``to_dict`` 可序列化,
|
|
||||||
便于配置台展示与审计。
|
|
||||||
|
|
||||||
零外部强依赖
|
|
||||||
------------
|
|
||||||
|
|
||||||
* ``Estimator`` 默认走纯 Python stub(均值回归 / 多数分类),无 sklearn 时
|
|
||||||
也能跑通完整训练 / 推理流水线,保证 CI 可加载与校验;
|
|
||||||
* 存在 ``numpy`` 时,指标计算与 stub 训练用向量化加速,否则纯 Python。
|
|
||||||
|
|
||||||
与 issue #34 / #36 / #38 的关系
|
|
||||||
-------------------------------
|
|
||||||
|
|
||||||
接口风格对齐 #34 声明式数据对象、#36 ``Recipe`` 配方、#38 ``Recipe``。
|
|
||||||
本模块**自包含、不依赖未合并分支**;``TrainStep`` 的 ``Estimator`` 可插拔,
|
|
||||||
未来可对接 #36 ``QualityForecastModel`` 作为具名 estimator,``RegisterStep``
|
|
||||||
可对接 #41 完整版本机制,业务侧零改动。
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
import math
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import uuid
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
# 上下文与注册表
|
|
||||||
"Context",
|
|
||||||
"ModelRegistry",
|
|
||||||
"ModelArtifact",
|
|
||||||
# 步骤
|
|
||||||
"Step",
|
|
||||||
"StepResult",
|
|
||||||
"LoadDataStep",
|
|
||||||
"TrainStep",
|
|
||||||
"EvaluateStep",
|
|
||||||
"RegisterStep",
|
|
||||||
"LoadModelStep",
|
|
||||||
"PredictStep",
|
|
||||||
"CustomStep",
|
|
||||||
# 估计器
|
|
||||||
"Estimator",
|
|
||||||
"MeanRegressor",
|
|
||||||
"MajorityClassifier",
|
|
||||||
"ESTIMATORS",
|
|
||||||
"register_estimator",
|
|
||||||
# 流水线
|
|
||||||
"Pipeline",
|
|
||||||
"PipelineConfig",
|
|
||||||
"PipelineError",
|
|
||||||
"PipelineResult",
|
|
||||||
]
|
|
||||||
|
|
||||||
try: # numpy 可选
|
|
||||||
import numpy as _np # type: ignore # noqa: F401
|
|
||||||
_HAS_NUMPY = True
|
|
||||||
except Exception: # pragma: no cover
|
|
||||||
_HAS_NUMPY = False
|
|
||||||
|
|
||||||
|
|
||||||
class PipelineError(Exception):
|
|
||||||
"""流水线编排层统一异常(配置非法 / 步骤失败 / 估计器未注册)。"""
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 上下文:步骤间数据流转
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Context:
|
|
||||||
"""流水线上下文:承载步骤间传递的数据 / 模型 / 指标 / 元信息。
|
|
||||||
|
|
||||||
采用「可写 working dict + 只读 params」双层:
|
|
||||||
- ``params``:流水线启动参数(只读,来自配置);
|
|
||||||
- ``artifacts``:步骤产物(可写,步骤间共享)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
params: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
artifacts: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
|
|
||||||
def get(self, key: str, default: Any = None) -> Any:
|
|
||||||
return self.artifacts.get(key, default)
|
|
||||||
|
|
||||||
def set(self, key: str, value: Any) -> None:
|
|
||||||
self.artifacts[key] = value
|
|
||||||
|
|
||||||
def snapshot(self) -> Dict[str, Any]:
|
|
||||||
"""返回当前上下文的只读快照(用于审计 / 日志)。"""
|
|
||||||
return {
|
|
||||||
"params": dict(self.params),
|
|
||||||
"artifacts_keys": sorted(self.artifacts.keys()),
|
|
||||||
"metadata": dict(self.metadata),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 模型注册表(版本化,对接 issue #41 雏形)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class ModelArtifact:
|
|
||||||
"""注册到 ``ModelRegistry`` 的一个模型版本。"""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
version: str
|
|
||||||
model: Any
|
|
||||||
metrics: Dict[str, float] = field(default_factory=dict)
|
|
||||||
registered_at: float = field(default_factory=time.time)
|
|
||||||
extra: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
|
|
||||||
def to_summary(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"name": self.name,
|
|
||||||
"version": self.version,
|
|
||||||
"metrics": dict(self.metrics),
|
|
||||||
"registered_at": self.registered_at,
|
|
||||||
"extra": dict(self.extra),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class ModelRegistry:
|
|
||||||
"""内存模型注册表:按 name 维护多版本,支持别名 latest / stable。
|
|
||||||
|
|
||||||
对接 issue #41「模型模板注册 / 加载 / 版本机制」的雏形——同一模型名下
|
|
||||||
可注册多个版本,``latest`` 指向最新,``stable`` 可手动标记。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._store: Dict[str, Dict[str, ModelArtifact]] = {}
|
|
||||||
self._aliases: Dict[str, Dict[str, str]] = {} # name -> {alias: version}
|
|
||||||
|
|
||||||
def register(self, artifact: ModelArtifact) -> ModelArtifact:
|
|
||||||
if not artifact.name or not artifact.version:
|
|
||||||
raise PipelineError("ModelArtifact 需要 name 和 version")
|
|
||||||
versions = self._store.setdefault(artifact.name, {})
|
|
||||||
versions[artifact.version] = artifact
|
|
||||||
# latest 自动指向最新注册
|
|
||||||
self._aliases.setdefault(artifact.name, {})["latest"] = artifact.version
|
|
||||||
return artifact
|
|
||||||
|
|
||||||
def get(self, name: str, version: Optional[str] = None) -> ModelArtifact:
|
|
||||||
versions = self._store.get(name)
|
|
||||||
if not versions:
|
|
||||||
raise PipelineError(f"模型 {name!r} 未注册")
|
|
||||||
if version is None:
|
|
||||||
version = self._aliases.get(name, {}).get("latest")
|
|
||||||
if version is None:
|
|
||||||
version = sorted(versions.keys())[-1]
|
|
||||||
elif version in self._aliases.get(name, {}):
|
|
||||||
# version 实际是别名
|
|
||||||
version = self._aliases[name][version]
|
|
||||||
if version not in versions:
|
|
||||||
raise PipelineError(
|
|
||||||
f"模型 {name!r} 无版本 {version!r}(可用:{sorted(versions)})")
|
|
||||||
return versions[version]
|
|
||||||
|
|
||||||
def set_alias(self, name: str, alias: str, version: str) -> None:
|
|
||||||
versions = self._store.get(name)
|
|
||||||
if not versions or version not in versions:
|
|
||||||
raise PipelineError(f"无法设置别名:{name!r}@{version!r} 不存在")
|
|
||||||
self._aliases.setdefault(name, {})[alias] = version
|
|
||||||
|
|
||||||
def list_versions(self, name: str) -> List[str]:
|
|
||||||
return sorted(self._store.get(name, {}).keys())
|
|
||||||
|
|
||||||
def list_models(self) -> List[str]:
|
|
||||||
return sorted(self._store.keys())
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 估计器(可插拔训练算法)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class Estimator:
|
|
||||||
"""估计器抽象基类:fit / predict,与具体库无关。"""
|
|
||||||
|
|
||||||
name: str = "base"
|
|
||||||
|
|
||||||
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> None:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
def predict(self, X: Sequence[Sequence[float]]) -> List[float]:
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
def get_params(self) -> Dict[str, Any]:
|
|
||||||
return {"name": self.name}
|
|
||||||
|
|
||||||
|
|
||||||
class MeanRegressor(Estimator):
|
|
||||||
"""均值回归器(stub):预测值恒为训练集 y 的均值。无外部依赖。"""
|
|
||||||
|
|
||||||
name = "mean_regressor"
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._mean: float = 0.0
|
|
||||||
|
|
||||||
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> None:
|
|
||||||
if not y:
|
|
||||||
raise PipelineError("MeanRegressor 训练数据为空")
|
|
||||||
self._mean = sum(y) / len(y)
|
|
||||||
|
|
||||||
def predict(self, X: Sequence[Sequence[float]]) -> List[float]:
|
|
||||||
return [self._mean for _ in X]
|
|
||||||
|
|
||||||
|
|
||||||
class MajorityClassifier(Estimator):
|
|
||||||
"""多数分类器(stub):预测值恒为训练集 y 中出现最多的类别。"""
|
|
||||||
|
|
||||||
name = "majority_classifier"
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
|
||||||
self._majority: float = 0.0
|
|
||||||
|
|
||||||
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> None:
|
|
||||||
if not y:
|
|
||||||
raise PipelineError("MajorityClassifier 训练数据为空")
|
|
||||||
counts: Dict[float, int] = {}
|
|
||||||
for v in y:
|
|
||||||
counts[v] = counts.get(v, 0) + 1
|
|
||||||
self._majority = max(counts, key=counts.get)
|
|
||||||
|
|
||||||
def predict(self, X: Sequence[Sequence[float]]) -> List[float]:
|
|
||||||
return [self._majority for _ in X]
|
|
||||||
|
|
||||||
|
|
||||||
ESTIMATORS: Dict[str, Callable[[], Estimator]] = {
|
|
||||||
"mean_regressor": MeanRegressor,
|
|
||||||
"majority_classifier": MajorityClassifier,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def register_estimator(name: str, factory: Callable[[], Estimator]) -> None:
|
|
||||||
"""注册自定义估计器(插件式,对齐 PRD 5.3 模板化理念)。"""
|
|
||||||
ESTIMATORS[name] = factory
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 步骤(Step):流水线的可插拔单元
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class StepResult:
|
|
||||||
"""单步执行结果。"""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
success: bool
|
|
||||||
duration_s: float = 0.0
|
|
||||||
output_keys: List[str] = field(default_factory=list)
|
|
||||||
error: Optional[str] = None
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"name": self.name, "success": self.success,
|
|
||||||
"duration_s": round(self.duration_s, 4),
|
|
||||||
"output_keys": self.output_keys, "error": self.error,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class Step:
|
|
||||||
"""步骤抽象基类:``prepare`` / ``run`` / ``teardown`` 三段式生命周期。
|
|
||||||
|
|
||||||
子类实现 ``run(ctx)``,通过 ``ctx.set`` 写产物、``ctx.get`` 读上游产物。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, name: str, params: Optional[Dict[str, Any]] = None):
|
|
||||||
if not name:
|
|
||||||
raise PipelineError("Step 需要 name")
|
|
||||||
self.name = name
|
|
||||||
self.params: Dict[str, Any] = dict(params or {})
|
|
||||||
|
|
||||||
def prepare(self, ctx: Context) -> None:
|
|
||||||
"""可选的预处理(校验配置 / 加载资源)。默认空。"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult: # noqa: D401
|
|
||||||
raise NotImplementedError
|
|
||||||
|
|
||||||
def teardown(self, ctx: Context, success: bool) -> None:
|
|
||||||
"""可选的清理。默认空。"""
|
|
||||||
|
|
||||||
def execute(self, ctx: Context) -> StepResult:
|
|
||||||
"""模板方法:prepare → run → teardown,统一定时与异常捕获。"""
|
|
||||||
self.prepare(ctx)
|
|
||||||
start = time.time()
|
|
||||||
success = True
|
|
||||||
try:
|
|
||||||
result = self.run(ctx)
|
|
||||||
return result
|
|
||||||
except Exception as exc: # noqa: BLE001
|
|
||||||
success = False
|
|
||||||
return StepResult(name=self.name, success=False,
|
|
||||||
duration_s=time.time() - start, error=str(exc))
|
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
self.teardown(ctx, success)
|
|
||||||
except Exception: # noqa: BLE001 - teardown 失败不影响主流程
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class LoadDataStep(Step):
|
|
||||||
"""加载训练 / 推理数据:从 CSV 或内存 list 加载到 ``ctx[data_key]``。"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
data_key = self.params.get("data_key", "dataset")
|
|
||||||
source = self.params.get("source")
|
|
||||||
if source is None:
|
|
||||||
raise PipelineError("LoadDataStep 缺少 source")
|
|
||||||
if isinstance(source, str) and source.endswith(".csv"):
|
|
||||||
# 简易 CSV 加载(首行表头,其余数值)
|
|
||||||
rows: List[List[float]] = []
|
|
||||||
with open(source, "r", encoding="utf-8") as fh:
|
|
||||||
lines = [ln.strip() for ln in fh if ln.strip()]
|
|
||||||
if not lines:
|
|
||||||
raise PipelineError(f"CSV 为空:{source}")
|
|
||||||
for ln in lines[1:]: # 跳过表头
|
|
||||||
parts = ln.split(",")
|
|
||||||
rows.append([float(p) for p in parts])
|
|
||||||
ctx.set(data_key, rows)
|
|
||||||
elif isinstance(source, (list, tuple)):
|
|
||||||
ctx.set(data_key, [list(r) for r in source])
|
|
||||||
else:
|
|
||||||
raise PipelineError(f"不支持的 source 类型:{type(source)}")
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[data_key])
|
|
||||||
|
|
||||||
|
|
||||||
class TrainStep(Step):
|
|
||||||
"""训练步骤:用可插拔 ``Estimator`` 在 ``ctx[train_key]`` 上训练。
|
|
||||||
|
|
||||||
训练数据格式:``[(X_row..., y), ...]`` 或分别 ``X`` / ``y``。
|
|
||||||
产物写入 ``ctx[model_key]``。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
estimator_name = self.params.get("estimator", "mean_regressor")
|
|
||||||
factory = ESTIMATORS.get(estimator_name)
|
|
||||||
if factory is None:
|
|
||||||
raise PipelineError(f"未注册的估计器:{estimator_name!r}")
|
|
||||||
est = factory()
|
|
||||||
|
|
||||||
X, y = self._extract_xy(ctx)
|
|
||||||
est.fit(X, y)
|
|
||||||
|
|
||||||
model_key = self.params.get("model_key", "model")
|
|
||||||
ctx.set(model_key, est)
|
|
||||||
ctx.metadata["estimator"] = estimator_name
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[model_key])
|
|
||||||
|
|
||||||
def _extract_xy(self, ctx: Context) -> Tuple[List[List[float]], List[float]]:
|
|
||||||
train_key = self.params.get("train_key", "dataset")
|
|
||||||
target_col = int(self.params.get("target_col", -1))
|
|
||||||
data = ctx.get(train_key)
|
|
||||||
if data is None:
|
|
||||||
raise PipelineError(f"训练数据不存在:{train_key}")
|
|
||||||
X: List[List[float]] = []
|
|
||||||
y: List[float] = []
|
|
||||||
for row in data:
|
|
||||||
row = list(row)
|
|
||||||
if not row:
|
|
||||||
continue
|
|
||||||
yv = row.pop(target_col)
|
|
||||||
X.append([float(v) for v in row])
|
|
||||||
y.append(float(yv))
|
|
||||||
if not X:
|
|
||||||
raise PipelineError("训练数据为空")
|
|
||||||
return X, y
|
|
||||||
|
|
||||||
|
|
||||||
class EvaluateStep(Step):
|
|
||||||
"""评估步骤:在 ``ctx[eval_key]`` 上用 ``ctx[model_key]`` 计算指标。
|
|
||||||
|
|
||||||
指标:回归(MAE / RMSE)、分类(accuracy)。产物写入 ``ctx[metrics_key]``。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
model_key = self.params.get("model_key", "model")
|
|
||||||
eval_key = self.params.get("eval_key", "dataset")
|
|
||||||
metrics_key = self.params.get("metrics_key", "metrics")
|
|
||||||
est = ctx.get(model_key)
|
|
||||||
if est is None:
|
|
||||||
raise PipelineError(f"模型不存在:{model_key}")
|
|
||||||
|
|
||||||
# 复用 TrainStep 的 X/y 提取逻辑
|
|
||||||
helper = TrainStep("helper", {"train_key": eval_key})
|
|
||||||
X, y = helper._extract_xy(ctx)
|
|
||||||
preds = est.predict(X)
|
|
||||||
|
|
||||||
metrics: Dict[str, float] = {}
|
|
||||||
n = len(y)
|
|
||||||
# 判断分类 / 回归:y 取值种类少视为分类
|
|
||||||
unique = set(y)
|
|
||||||
if len(unique) <= max(10, n * 0.1):
|
|
||||||
correct = sum(1 for p, t in zip(preds, y) if abs(p - t) < 1e-6)
|
|
||||||
metrics["accuracy"] = correct / n if n else 0.0
|
|
||||||
mae = sum(abs(p - t) for p, t in zip(preds, y)) / n if n else 0.0
|
|
||||||
rmse = math.sqrt(sum((p - t) ** 2 for p, t in zip(preds, y)) / n) if n else 0.0
|
|
||||||
metrics["mae"] = mae
|
|
||||||
metrics["rmse"] = rmse
|
|
||||||
|
|
||||||
ctx.set(metrics_key, metrics)
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[metrics_key])
|
|
||||||
|
|
||||||
|
|
||||||
class RegisterStep(Step):
|
|
||||||
"""注册步骤:把 ``ctx[model_key]`` 注册到 ``ModelRegistry``(版本化)。
|
|
||||||
|
|
||||||
registry 通过 ``ctx[registry_key]`` 获取(若不存在则新建)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
registry_key = self.params.get("registry_key", "registry")
|
|
||||||
model_key = self.params.get("model_key", "model")
|
|
||||||
name = self.params.get("model_name", "default-model")
|
|
||||||
version = self.params.get("version")
|
|
||||||
if version in (None, ""):
|
|
||||||
version = "v" + uuid.uuid4().hex[:8]
|
|
||||||
|
|
||||||
registry = ctx.get(registry_key)
|
|
||||||
if registry is None:
|
|
||||||
registry = ModelRegistry()
|
|
||||||
ctx.set(registry_key, registry)
|
|
||||||
|
|
||||||
est = ctx.get(model_key)
|
|
||||||
if est is None:
|
|
||||||
raise PipelineError(f"模型不存在:{model_key}")
|
|
||||||
metrics = ctx.get(self.params.get("metrics_key", "metrics"), {})
|
|
||||||
artifact = ModelArtifact(
|
|
||||||
name=name, version=version, model=est,
|
|
||||||
metrics=dict(metrics) if isinstance(metrics, dict) else {},
|
|
||||||
extra={"estimator": ctx.metadata.get("estimator", "")},
|
|
||||||
)
|
|
||||||
registry.register(artifact)
|
|
||||||
ctx.metadata["registered_version"] = version
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[registry_key])
|
|
||||||
|
|
||||||
|
|
||||||
class LoadModelStep(Step):
|
|
||||||
"""加载步骤:从 ``ModelRegistry`` 按 name/version 加载模型到 ctx。"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
registry_key = self.params.get("registry_key", "registry")
|
|
||||||
model_key = self.params.get("model_key", "serving_model")
|
|
||||||
name = self.params.get("model_name", "")
|
|
||||||
version = self.params.get("version") # 可为别名 latest/stable
|
|
||||||
|
|
||||||
registry = ctx.get(registry_key)
|
|
||||||
if not isinstance(registry, ModelRegistry):
|
|
||||||
raise PipelineError(f"registry 不存在或类型错误:{registry_key}")
|
|
||||||
artifact = registry.get(name, version)
|
|
||||||
ctx.set(model_key, artifact.model)
|
|
||||||
ctx.metadata["serving_version"] = artifact.version
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[model_key])
|
|
||||||
|
|
||||||
|
|
||||||
class PredictStep(Step):
|
|
||||||
"""推理步骤:用 ``ctx[model_key]`` 对 ``ctx[input_key]`` 批量预测。
|
|
||||||
|
|
||||||
产物写入 ``ctx[predictions_key]``。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
model_key = self.params.get("model_key", "serving_model")
|
|
||||||
input_key = self.params.get("input_key", "input")
|
|
||||||
predictions_key = self.params.get("predictions_key", "predictions")
|
|
||||||
|
|
||||||
est = ctx.get(model_key)
|
|
||||||
if est is None:
|
|
||||||
raise PipelineError(f"模型不存在:{model_key}")
|
|
||||||
data = ctx.get(input_key)
|
|
||||||
if data is None:
|
|
||||||
raise PipelineError(f"输入数据不存在:{input_key}")
|
|
||||||
X = [list(row) for row in data]
|
|
||||||
preds = est.predict(X)
|
|
||||||
ctx.set(predictions_key, preds)
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=[predictions_key])
|
|
||||||
|
|
||||||
|
|
||||||
class CustomStep(Step):
|
|
||||||
"""自定义步骤:用 ``params["handler"]``(可调用对象)执行任意逻辑。
|
|
||||||
|
|
||||||
便于在不新建子类的情况下快速接入业务代码。注意:handler 无法序列化,
|
|
||||||
仅在 Python 构造时使用,不进入 JSON 配置。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def run(self, ctx: Context) -> StepResult:
|
|
||||||
start = time.time()
|
|
||||||
handler = self.params.get("handler")
|
|
||||||
if not callable(handler):
|
|
||||||
raise PipelineError("CustomStep 缺少可调用 handler")
|
|
||||||
output = handler(ctx)
|
|
||||||
out_keys = []
|
|
||||||
if isinstance(output, dict):
|
|
||||||
for k, v in output.items():
|
|
||||||
ctx.set(k, v)
|
|
||||||
out_keys.append(k)
|
|
||||||
return StepResult(name=self.name, success=True,
|
|
||||||
duration_s=time.time() - start,
|
|
||||||
output_keys=out_keys)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 流水线(Pipeline):顺序编排若干 Step
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
#: 步骤类型名 → 工厂(用于从配置反序列化构建 Step)
|
|
||||||
STEP_TYPES: Dict[str, Callable[[str, Dict[str, Any]], Step]] = {
|
|
||||||
"load_data": lambda n, p: LoadDataStep(n, p),
|
|
||||||
"train": lambda n, p: TrainStep(n, p),
|
|
||||||
"evaluate": lambda n, p: EvaluateStep(n, p),
|
|
||||||
"register": lambda n, p: RegisterStep(n, p),
|
|
||||||
"load_model": lambda n, p: LoadModelStep(n, p),
|
|
||||||
"predict": lambda n, p: PredictStep(n, p),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def register_step_type(type_name: str, factory: Callable[[str, Dict[str, Any]], Step]) -> None:
|
|
||||||
"""注册自定义步骤类型(配置驱动构建)。"""
|
|
||||||
STEP_TYPES[type_name] = factory
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class PipelineConfig:
|
|
||||||
"""声明式流水线配置(可序列化往返,便于配置台展示与审计)。"""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
steps: List[Dict[str, Any]] = field(default_factory=list)
|
|
||||||
params: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {"name": self.name, "steps": list(self.steps),
|
|
||||||
"params": dict(self.params)}
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_dict(cls, data: Dict[str, Any]) -> "PipelineConfig":
|
|
||||||
return cls(name=data["name"], steps=list(data.get("steps", [])),
|
|
||||||
params=dict(data.get("params", {})))
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class PipelineResult:
|
|
||||||
"""流水线执行结果:各步骤结果 + 是否整体成功 + 总耗时。"""
|
|
||||||
|
|
||||||
name: str
|
|
||||||
success: bool
|
|
||||||
step_results: List[StepResult] = field(default_factory=list)
|
|
||||||
total_duration_s: float = 0.0
|
|
||||||
failed_step: Optional[str] = None
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"name": self.name, "success": self.success,
|
|
||||||
"steps": [s.to_dict() for s in self.step_results],
|
|
||||||
"total_duration_s": round(self.total_duration_s, 4),
|
|
||||||
"failed_step": self.failed_step,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class Pipeline:
|
|
||||||
"""流水线编排器:顺序执行 ``Step`` 列表,自动传递 ``Context``。
|
|
||||||
|
|
||||||
用法::
|
|
||||||
|
|
||||||
pipe = Pipeline("demo", [
|
|
||||||
LoadDataStep("load", {"source": rows}),
|
|
||||||
TrainStep("train", {"estimator": "mean_regressor"}),
|
|
||||||
EvaluateStep("eval", {}),
|
|
||||||
RegisterStep("register", {"model_name": "demo"}),
|
|
||||||
])
|
|
||||||
result = pipe.run()
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, name: str, steps: Sequence[Step],
|
|
||||||
params: Optional[Dict[str, Any]] = None):
|
|
||||||
if not name:
|
|
||||||
raise PipelineError("Pipeline 需要 name")
|
|
||||||
self.name = name
|
|
||||||
self.steps: List[Step] = list(steps)
|
|
||||||
self.params: Dict[str, Any] = dict(params or {})
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def from_config(cls, config: PipelineConfig) -> "Pipeline":
|
|
||||||
"""从声明式配置构建流水线(配置驱动,切换模型 / 数据源只改配置)。"""
|
|
||||||
steps: List[Step] = []
|
|
||||||
for sd in config.steps:
|
|
||||||
stype = sd.get("type")
|
|
||||||
sname = sd.get("name", stype)
|
|
||||||
sparams = dict(sd.get("params", {}))
|
|
||||||
factory = STEP_TYPES.get(stype or "")
|
|
||||||
if factory is None:
|
|
||||||
raise PipelineError(f"未知步骤类型:{stype!r}")
|
|
||||||
steps.append(factory(sname, sparams))
|
|
||||||
return cls(config.name, steps, config.params)
|
|
||||||
|
|
||||||
def run(self, initial_ctx: Optional[Context] = None,
|
|
||||||
dry_run: bool = False) -> PipelineResult:
|
|
||||||
"""顺序执行所有步骤;``dry_run`` 时只校验配置不执行 run。"""
|
|
||||||
ctx = initial_ctx or Context()
|
|
||||||
for k, v in self.params.items():
|
|
||||||
ctx.params.setdefault(k, v)
|
|
||||||
|
|
||||||
results: List[StepResult] = []
|
|
||||||
start = time.time()
|
|
||||||
if dry_run:
|
|
||||||
for st in self.steps:
|
|
||||||
st.prepare(ctx)
|
|
||||||
results.append(StepResult(name=st.name, success=True))
|
|
||||||
return PipelineResult(name=self.name, success=True,
|
|
||||||
step_results=results,
|
|
||||||
total_duration_s=time.time() - start)
|
|
||||||
|
|
||||||
for st in self.steps:
|
|
||||||
r = st.execute(ctx)
|
|
||||||
results.append(r)
|
|
||||||
if not r.success:
|
|
||||||
return PipelineResult(name=self.name, success=False,
|
|
||||||
step_results=results,
|
|
||||||
total_duration_s=time.time() - start,
|
|
||||||
failed_step=st.name)
|
|
||||||
return PipelineResult(name=self.name, success=True,
|
|
||||||
step_results=results,
|
|
||||||
total_duration_s=time.time() - start)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""测试引导:把连字符目录 ``core/model-framework`` 加载为可导入包
|
|
||||||
``model_framework``,使测试可 ``from model_framework import ...``。
|
|
||||||
"""
|
|
||||||
import importlib.util
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
PKG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
|
|
||||||
|
|
||||||
def _load_package(name: str, path: str) -> None:
|
|
||||||
if name in sys.modules:
|
|
||||||
return
|
|
||||||
init_py = os.path.join(path, "__init__.py")
|
|
||||||
spec = importlib.util.spec_from_file_location(
|
|
||||||
name, init_py, submodule_search_locations=[path])
|
|
||||||
module = importlib.util.module_from_spec(spec)
|
|
||||||
sys.modules[name] = module
|
|
||||||
spec.loader.exec_module(module)
|
|
||||||
|
|
||||||
|
|
||||||
_load_package("model_framework", PKG_DIR)
|
|
||||||
@@ -1,301 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""训练 / 推理流水线编排单元测试(issue #40)。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
- Context 读写与快照;
|
|
||||||
- ModelRegistry 注册 / 版本 / 别名(latest / stable);
|
|
||||||
- 估计器(MeanRegressor / MajorityClassifier)训练与预测;
|
|
||||||
- 各 Step(LoadData / Train / Evaluate / Register / LoadModel / Predict / Custom)
|
|
||||||
的执行与产物传递;
|
|
||||||
- Pipeline 顺序编排、失败短路、dry_run;
|
|
||||||
- PipelineConfig 声明式配置往返与 from_config 构建。
|
|
||||||
"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
if HERE not in sys.path:
|
|
||||||
sys.path.insert(0, HERE)
|
|
||||||
|
|
||||||
import _bootstrap # noqa: E402 加载 model_framework 包
|
|
||||||
|
|
||||||
from model_framework import ( # noqa: E402
|
|
||||||
Context,
|
|
||||||
CustomStep,
|
|
||||||
ESTIMATORS,
|
|
||||||
EvaluateStep,
|
|
||||||
LoadDataStep,
|
|
||||||
LoadModelStep,
|
|
||||||
MajorityClassifier,
|
|
||||||
MeanRegressor,
|
|
||||||
ModelArtifact,
|
|
||||||
ModelRegistry,
|
|
||||||
Pipeline,
|
|
||||||
PipelineConfig,
|
|
||||||
PipelineError,
|
|
||||||
PredictStep,
|
|
||||||
RegisterStep,
|
|
||||||
StepResult,
|
|
||||||
TrainStep,
|
|
||||||
register_estimator,
|
|
||||||
register_step_type,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestContext(unittest.TestCase):
|
|
||||||
def test_get_set(self):
|
|
||||||
ctx = Context(params={"lr": 0.1})
|
|
||||||
ctx.set("x", 1)
|
|
||||||
self.assertEqual(ctx.get("x"), 1)
|
|
||||||
self.assertEqual(ctx.get("missing", "d"), "d")
|
|
||||||
self.assertEqual(ctx.params["lr"], 0.1)
|
|
||||||
|
|
||||||
def test_snapshot(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("a", 1)
|
|
||||||
ctx.set("b", 2)
|
|
||||||
snap = ctx.snapshot()
|
|
||||||
self.assertEqual(snap["artifacts_keys"], ["a", "b"])
|
|
||||||
|
|
||||||
|
|
||||||
class TestModelRegistry(unittest.TestCase):
|
|
||||||
def test_register_and_latest(self):
|
|
||||||
reg = ModelRegistry()
|
|
||||||
a1 = ModelArtifact("m", "v1", object())
|
|
||||||
a2 = ModelArtifact("m", "v2", object())
|
|
||||||
reg.register(a1)
|
|
||||||
reg.register(a2)
|
|
||||||
self.assertEqual(reg.get("m").version, "v2") # latest
|
|
||||||
self.assertEqual(reg.get("m", "v1").version, "v1")
|
|
||||||
self.assertEqual(reg.list_versions("m"), ["v1", "v2"])
|
|
||||||
|
|
||||||
def test_alias(self):
|
|
||||||
reg = ModelRegistry()
|
|
||||||
reg.register(ModelArtifact("m", "v1", object()))
|
|
||||||
reg.register(ModelArtifact("m", "v2", object()))
|
|
||||||
reg.set_alias("m", "stable", "v1")
|
|
||||||
self.assertEqual(reg.get("m", "stable").version, "v1")
|
|
||||||
self.assertEqual(reg.get("m", "latest").version, "v2")
|
|
||||||
|
|
||||||
def test_missing_raises(self):
|
|
||||||
reg = ModelRegistry()
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
reg.get("nope")
|
|
||||||
reg.register(ModelArtifact("m", "v1", object()))
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
reg.get("m", "v99")
|
|
||||||
|
|
||||||
def test_register_requires_name_version(self):
|
|
||||||
reg = ModelRegistry()
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
reg.register(ModelArtifact("", "v1", object()))
|
|
||||||
|
|
||||||
|
|
||||||
class TestEstimators(unittest.TestCase):
|
|
||||||
def test_mean_regressor(self):
|
|
||||||
est = MeanRegressor()
|
|
||||||
est.fit([[1], [2], [3]], [10, 20, 30])
|
|
||||||
self.assertEqual(est.predict([[99], [100]]), [20.0, 20.0])
|
|
||||||
|
|
||||||
def test_majority_classifier(self):
|
|
||||||
est = MajorityClassifier()
|
|
||||||
est.fit([[1], [2], [3]], [0, 1, 1])
|
|
||||||
self.assertEqual(est.predict([[9], [10]]), [1.0, 1.0])
|
|
||||||
|
|
||||||
def test_empty_fit_raises(self):
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
MeanRegressor().fit([], [])
|
|
||||||
|
|
||||||
def test_register_estimator(self):
|
|
||||||
class MyEst(MeanRegressor):
|
|
||||||
name = "my_est"
|
|
||||||
register_estimator("my_est", MyEst)
|
|
||||||
self.assertIn("my_est", ESTIMATORS)
|
|
||||||
|
|
||||||
|
|
||||||
class TestSteps(unittest.TestCase):
|
|
||||||
def test_load_data_from_list(self):
|
|
||||||
ctx = Context()
|
|
||||||
r = LoadDataStep("load", {"source": [[1, 2], [3, 4]]}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(ctx.get("dataset"), [[1.0, 2.0], [3.0, 4.0]])
|
|
||||||
|
|
||||||
def test_load_data_from_csv(self):
|
|
||||||
with tempfile.NamedTemporaryFile(
|
|
||||||
mode="w", suffix=".csv", delete=False, encoding="utf-8") as fh:
|
|
||||||
fh.write("a,b,y\n1,2,3\n4,5,6\n")
|
|
||||||
path = fh.name
|
|
||||||
try:
|
|
||||||
ctx = Context()
|
|
||||||
r = LoadDataStep("load", {"source": path}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(ctx.get("dataset"), [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
|
|
||||||
finally:
|
|
||||||
os.unlink(path)
|
|
||||||
|
|
||||||
def test_load_data_missing_source(self):
|
|
||||||
ctx = Context()
|
|
||||||
r = LoadDataStep("load", {}).execute(ctx)
|
|
||||||
self.assertFalse(r.success)
|
|
||||||
self.assertIn("source", r.error or "")
|
|
||||||
|
|
||||||
def test_train_step(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 10], [2, 20], [3, 30]]) # 最后一列 target
|
|
||||||
r = TrainStep("train", {"estimator": "mean_regressor"}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
est = ctx.get("model")
|
|
||||||
self.assertEqual(est.predict([[9]]), [20.0])
|
|
||||||
|
|
||||||
def test_train_unknown_estimator(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 10]])
|
|
||||||
r = TrainStep("train", {"estimator": "voodoo"}).execute(ctx)
|
|
||||||
self.assertFalse(r.success)
|
|
||||||
|
|
||||||
def test_evaluate_step_regression(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 10], [2, 20], [3, 30]])
|
|
||||||
TrainStep("train", {}).execute(ctx)
|
|
||||||
r = EvaluateStep("eval", {}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
m = ctx.get("metrics")
|
|
||||||
# 均值预测:mae 为各 |y-20| 的均值
|
|
||||||
self.assertAlmostEqual(m["mae"], (10 + 0 + 10) / 3)
|
|
||||||
self.assertGreaterEqual(m["rmse"], 0)
|
|
||||||
|
|
||||||
def test_evaluate_step_classification(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 0], [2, 1], [3, 1]])
|
|
||||||
TrainStep("train", {"estimator": "majority_classifier"}).execute(ctx)
|
|
||||||
EvaluateStep("eval", {}).execute(ctx)
|
|
||||||
m = ctx.get("metrics")
|
|
||||||
self.assertIn("accuracy", m)
|
|
||||||
self.assertGreaterEqual(m["accuracy"], 0.0)
|
|
||||||
|
|
||||||
def test_register_and_load_model(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 10], [2, 20]])
|
|
||||||
TrainStep("train", {}).execute(ctx)
|
|
||||||
reg_r = RegisterStep("reg", {"model_name": "demo", "version": "v1"}).execute(ctx)
|
|
||||||
self.assertTrue(reg_r.success)
|
|
||||||
registry = ctx.get("registry")
|
|
||||||
self.assertIsInstance(registry, ModelRegistry)
|
|
||||||
self.assertEqual(registry.list_versions("demo"), ["v1"])
|
|
||||||
|
|
||||||
load_r = LoadModelStep("load", {"model_name": "demo", "version": "v1"}).execute(ctx)
|
|
||||||
self.assertTrue(load_r.success)
|
|
||||||
serving = ctx.get("serving_model")
|
|
||||||
self.assertEqual(serving.predict([[9]]), [15.0])
|
|
||||||
|
|
||||||
def test_load_model_missing_registry(self):
|
|
||||||
ctx = Context()
|
|
||||||
r = LoadModelStep("load", {"model_name": "x"}).execute(ctx)
|
|
||||||
self.assertFalse(r.success)
|
|
||||||
|
|
||||||
def test_predict_step(self):
|
|
||||||
ctx = Context()
|
|
||||||
ctx.set("dataset", [[1, 10], [2, 20]])
|
|
||||||
TrainStep("train", {}).execute(ctx)
|
|
||||||
RegisterStep("reg", {"model_name": "demo", "version": "v1"}).execute(ctx)
|
|
||||||
LoadModelStep("load", {"model_name": "demo"}).execute(ctx)
|
|
||||||
ctx.set("input", [[5], [6]])
|
|
||||||
r = PredictStep("predict", {}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(ctx.get("predictions"), [15.0, 15.0])
|
|
||||||
|
|
||||||
def test_custom_step(self):
|
|
||||||
ctx = Context()
|
|
||||||
r = CustomStep("c", {"handler": lambda c: {"out": 42}}).execute(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(ctx.get("out"), 42)
|
|
||||||
|
|
||||||
def test_custom_step_bad_handler(self):
|
|
||||||
ctx = Context()
|
|
||||||
r = CustomStep("c", {"handler": "not_callable"}).execute(ctx)
|
|
||||||
self.assertFalse(r.success)
|
|
||||||
|
|
||||||
def test_step_requires_name(self):
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
TrainStep("", {})
|
|
||||||
|
|
||||||
|
|
||||||
class TestPipeline(unittest.TestCase):
|
|
||||||
def _full_pipeline(self):
|
|
||||||
return Pipeline("demo", [
|
|
||||||
LoadDataStep("load", {"source": [[1, 10], [2, 20], [3, 30]]}),
|
|
||||||
TrainStep("train", {"estimator": "mean_regressor"}),
|
|
||||||
EvaluateStep("eval", {}),
|
|
||||||
RegisterStep("register", {"model_name": "demo", "version": "v1"}),
|
|
||||||
LoadModelStep("load_model", {"model_name": "demo", "version": "v1"}),
|
|
||||||
PredictStep("predict", {"input_key": "dataset"}),
|
|
||||||
])
|
|
||||||
|
|
||||||
def test_full_pipeline_success(self):
|
|
||||||
result = self._full_pipeline().run()
|
|
||||||
self.assertTrue(result.success)
|
|
||||||
self.assertEqual(len(result.step_results), 6)
|
|
||||||
self.assertIsNone(result.failed_step)
|
|
||||||
|
|
||||||
def test_pipeline_context_shared(self):
|
|
||||||
pipe = Pipeline("p", [
|
|
||||||
CustomStep("a", {"handler": lambda c: {"v": 7}}),
|
|
||||||
CustomStep("b", {"handler": lambda c: {"v2": c.get("v") * 2}}),
|
|
||||||
])
|
|
||||||
r = pipe.run()
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(pipe is not None, True)
|
|
||||||
|
|
||||||
def test_pipeline_failure_short_circuits(self):
|
|
||||||
# 第二步失败(无 dataset),应短路不执行后续
|
|
||||||
pipe = Pipeline("p", [
|
|
||||||
CustomStep("a", {"handler": lambda c: {}}),
|
|
||||||
EvaluateStep("bad_eval", {}), # 缺 model → 失败
|
|
||||||
CustomStep("c", {"handler": lambda c: {"never": 1}}),
|
|
||||||
])
|
|
||||||
r = pipe.run()
|
|
||||||
self.assertFalse(r.success)
|
|
||||||
self.assertEqual(r.failed_step, "bad_eval")
|
|
||||||
self.assertEqual(len(r.step_results), 2) # a + bad_eval
|
|
||||||
|
|
||||||
def test_dry_run(self):
|
|
||||||
r = self._full_pipeline().run(dry_run=True)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
# dry_run 不真正 run,predictions 不存在
|
|
||||||
# (dry_run 不产出 artifacts)
|
|
||||||
|
|
||||||
def test_pipeline_requires_name(self):
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
Pipeline("", [])
|
|
||||||
|
|
||||||
def test_register_step_type_and_from_config(self):
|
|
||||||
register_step_type("double", lambda n, p: CustomStep(
|
|
||||||
n, {"handler": lambda c: {"doubled": c.params.get("x", 0) * 2}}))
|
|
||||||
cfg = PipelineConfig("cfg", steps=[
|
|
||||||
{"type": "double", "name": "d", "params": {}},
|
|
||||||
], params={"x": 21})
|
|
||||||
pipe = Pipeline.from_config(cfg)
|
|
||||||
ctx = Context()
|
|
||||||
r = pipe.run(ctx)
|
|
||||||
self.assertTrue(r.success)
|
|
||||||
self.assertEqual(ctx.get("doubled"), 42)
|
|
||||||
|
|
||||||
def test_from_config_unknown_type(self):
|
|
||||||
cfg = PipelineConfig("cfg", steps=[{"type": "voodoo"}])
|
|
||||||
with self.assertRaises(PipelineError):
|
|
||||||
Pipeline.from_config(cfg)
|
|
||||||
|
|
||||||
def test_config_roundtrip(self):
|
|
||||||
cfg = PipelineConfig("c", steps=[{"type": "train", "name": "t", "params": {}}],
|
|
||||||
params={"k": 1})
|
|
||||||
d = cfg.to_dict()
|
|
||||||
cfg2 = PipelineConfig.from_dict(json.loads(json.dumps(d)))
|
|
||||||
self.assertEqual(cfg2.name, "c")
|
|
||||||
self.assertEqual(cfg2.params, {"k": 1})
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
Reference in New Issue
Block a user