darwin-cleaner 0.4.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- darwin_cleaner/__init__.py +111 -0
- darwin_cleaner/context.py +51 -0
- darwin_cleaner/contract.py +139 -0
- darwin_cleaner/engine.py +410 -0
- darwin_cleaner/exceptions.py +47 -0
- darwin_cleaner/middleware.py +310 -0
- darwin_cleaner/request.py +72 -0
- darwin_cleaner/results.py +227 -0
- darwin_cleaner/rules.py +103 -0
- darwin_cleaner/steps.py +501 -0
- darwin_cleaner-0.4.0.dev0.dist-info/METADATA +120 -0
- darwin_cleaner-0.4.0.dev0.dist-info/RECORD +15 -0
- darwin_cleaner-0.4.0.dev0.dist-info/WHEEL +5 -0
- darwin_cleaner-0.4.0.dev0.dist-info/licenses/LICENSE +21 -0
- darwin_cleaner-0.4.0.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# src/darwin_cleaner/__init__.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
darwin-cleaner:契约与规则驱动的单文件清洗引擎。
|
|
5
|
+
|
|
6
|
+
边界:读取单个 parquet -> 行分叉/列分叉 -> 按 order 跑 middleware ->
|
|
7
|
+
返回数据与 meta。无 source / clean_type 等业务概念;
|
|
8
|
+
不含配置加载、文件发现、调度、断点、CLI 与落盘。
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from darwin_cleaner.contract import (
|
|
14
|
+
Contract,
|
|
15
|
+
FieldSpec,
|
|
16
|
+
FillSpec,
|
|
17
|
+
SortDirection,
|
|
18
|
+
SortSpec,
|
|
19
|
+
TypeSpec,
|
|
20
|
+
ViolationAction,
|
|
21
|
+
)
|
|
22
|
+
from darwin_cleaner.context import CleanContext, Logger
|
|
23
|
+
from darwin_cleaner.engine import CleanPlan, CleanStep, CleaningEngine, clean
|
|
24
|
+
from darwin_cleaner.exceptions import (
|
|
25
|
+
CleanerConfigError,
|
|
26
|
+
CleanerDataEmptyError,
|
|
27
|
+
CleanerDataNotFoundError,
|
|
28
|
+
CleanerError,
|
|
29
|
+
CleanerRuleError,
|
|
30
|
+
CleanerValidationError,
|
|
31
|
+
)
|
|
32
|
+
from darwin_cleaner.middleware import (
|
|
33
|
+
ActionFn,
|
|
34
|
+
MiddlewareFn,
|
|
35
|
+
MiddlewareRegistry,
|
|
36
|
+
MiddlewareRegistryImpl,
|
|
37
|
+
MiddlewareOverride,
|
|
38
|
+
MiddlewareSpec,
|
|
39
|
+
builtin_middlewares,
|
|
40
|
+
load_middlewares_from_dir,
|
|
41
|
+
middleware,
|
|
42
|
+
)
|
|
43
|
+
from darwin_cleaner.request import CleanOptions, CleanRequest, InputData, ReadOptions
|
|
44
|
+
from darwin_cleaner.results import (
|
|
45
|
+
CleanMeta,
|
|
46
|
+
CleanOutput,
|
|
47
|
+
CleanReport,
|
|
48
|
+
CleanResult,
|
|
49
|
+
CleaningStats,
|
|
50
|
+
Status,
|
|
51
|
+
ValidationIssue,
|
|
52
|
+
)
|
|
53
|
+
from darwin_cleaner.rules import (
|
|
54
|
+
ForkPlan,
|
|
55
|
+
JsonExtractSpec,
|
|
56
|
+
RowForkSpec,
|
|
57
|
+
Rules,
|
|
58
|
+
TransformKind,
|
|
59
|
+
TransformSpec,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
__version__ = "0.4.0.dev0"
|
|
63
|
+
|
|
64
|
+
__all__ = [
|
|
65
|
+
"__version__",
|
|
66
|
+
"Contract",
|
|
67
|
+
"FieldSpec",
|
|
68
|
+
"FillSpec",
|
|
69
|
+
"SortDirection",
|
|
70
|
+
"SortSpec",
|
|
71
|
+
"TypeSpec",
|
|
72
|
+
"ViolationAction",
|
|
73
|
+
"CleanContext",
|
|
74
|
+
"Logger",
|
|
75
|
+
"CleanPlan",
|
|
76
|
+
"CleanStep",
|
|
77
|
+
"CleaningEngine",
|
|
78
|
+
"clean",
|
|
79
|
+
"CleanerError",
|
|
80
|
+
"CleanerConfigError",
|
|
81
|
+
"CleanerRuleError",
|
|
82
|
+
"CleanerDataNotFoundError",
|
|
83
|
+
"CleanerDataEmptyError",
|
|
84
|
+
"CleanerValidationError",
|
|
85
|
+
"ActionFn",
|
|
86
|
+
"MiddlewareFn",
|
|
87
|
+
"MiddlewareRegistry",
|
|
88
|
+
"MiddlewareRegistryImpl",
|
|
89
|
+
"MiddlewareOverride",
|
|
90
|
+
"MiddlewareSpec",
|
|
91
|
+
"middleware",
|
|
92
|
+
"builtin_middlewares",
|
|
93
|
+
"load_middlewares_from_dir",
|
|
94
|
+
"CleanOptions",
|
|
95
|
+
"CleanRequest",
|
|
96
|
+
"InputData",
|
|
97
|
+
"ReadOptions",
|
|
98
|
+
"CleanMeta",
|
|
99
|
+
"CleanOutput",
|
|
100
|
+
"CleanReport",
|
|
101
|
+
"CleanResult",
|
|
102
|
+
"CleaningStats",
|
|
103
|
+
"Status",
|
|
104
|
+
"ValidationIssue",
|
|
105
|
+
"ForkPlan",
|
|
106
|
+
"JsonExtractSpec",
|
|
107
|
+
"RowForkSpec",
|
|
108
|
+
"Rules",
|
|
109
|
+
"TransformKind",
|
|
110
|
+
"TransformSpec",
|
|
111
|
+
]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# src/darwin_cleaner/context.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
执行上下文:middleware 从 ctx 读取契约、规则与报告。
|
|
5
|
+
|
|
6
|
+
不含任何业务标识(source / clean_type / date / filename),
|
|
7
|
+
不含 IO 选项(output_path / overwrite / check_only / csv_mode)。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import Any, Protocol, TYPE_CHECKING
|
|
14
|
+
|
|
15
|
+
from darwin_cleaner.contract import Contract
|
|
16
|
+
from darwin_cleaner.results import CleanReport
|
|
17
|
+
from darwin_cleaner.rules import Rules
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
import pandas as pd
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Logger(Protocol):
|
|
24
|
+
"""最小日志协议,避免绑定具体日志库。"""
|
|
25
|
+
|
|
26
|
+
def debug(self, msg: str, *args: Any) -> None: ...
|
|
27
|
+
|
|
28
|
+
def info(self, msg: str, *args: Any) -> None: ...
|
|
29
|
+
|
|
30
|
+
def warning(self, msg: str, *args: Any) -> None: ...
|
|
31
|
+
|
|
32
|
+
def error(self, msg: str, *args: Any) -> None: ...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class CleanContext:
|
|
37
|
+
"""
|
|
38
|
+
单个分叉的运行时上下文。
|
|
39
|
+
|
|
40
|
+
output_key 只是本次产出的标识,供报告使用,不携带业务语义。
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
output_key: str
|
|
44
|
+
contract: Contract
|
|
45
|
+
rules: Rules
|
|
46
|
+
report: CleanReport
|
|
47
|
+
logger: Logger | None = None
|
|
48
|
+
data: "pd.DataFrame | None" = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
__all__ = ["Logger", "CleanContext"]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# src/darwin_cleaner/contract.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
契约值对象:描述"一份数据应该长什么样"。
|
|
5
|
+
|
|
6
|
+
这些类型由上层解析后注入引擎,引擎不负责读取文件。
|
|
7
|
+
所有对象均为 frozen,执行期间不可变。
|
|
8
|
+
|
|
9
|
+
注意:Contract.name 只是诊断用的标签,不是 clean_type / source 等业务概念。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Literal, Mapping
|
|
16
|
+
|
|
17
|
+
ViolationAction = Literal["null", "flag", "reject"]
|
|
18
|
+
SortDirection = Literal["ascending", "descending"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class FillSpec:
|
|
23
|
+
"""字段填充规则。"""
|
|
24
|
+
|
|
25
|
+
strategy: Literal["ffill", "value", "none"] = "ffill"
|
|
26
|
+
max_days: int = 5
|
|
27
|
+
value: Any = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class TypeSpec:
|
|
32
|
+
"""类型定义。"""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
converter: str | None = None
|
|
36
|
+
min: float | None = None
|
|
37
|
+
max: float | None = None
|
|
38
|
+
rel_diff: float = 0.003
|
|
39
|
+
abs_diff: float = 0.01
|
|
40
|
+
extra: Mapping[str, Any] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class FieldSpec:
|
|
45
|
+
"""
|
|
46
|
+
单个字段的契约。
|
|
47
|
+
|
|
48
|
+
type_def 保留原始定义字典,便于上层做兼容与诊断;
|
|
49
|
+
常用约束同时提升为显式字段,供规则直接读取。
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
name: str
|
|
53
|
+
type: str
|
|
54
|
+
type_def: Mapping[str, Any] = field(default_factory=dict)
|
|
55
|
+
help: str = ""
|
|
56
|
+
fill: FillSpec | None = None
|
|
57
|
+
formula: str | None = None
|
|
58
|
+
consistency: tuple[str, ...] = ()
|
|
59
|
+
on_violation: ViolationAction = "null"
|
|
60
|
+
required: bool | None = None
|
|
61
|
+
"""
|
|
62
|
+
该列是否必须存在于输出数据中(三态)。
|
|
63
|
+
|
|
64
|
+
True —— 缺失即报错;
|
|
65
|
+
False —— 显式允许缺失,补空列;
|
|
66
|
+
None —— 未声明,由 Contract 推导:sort / keys 字段为 True,其余为 False。
|
|
67
|
+
|
|
68
|
+
最终取值请用 Contract.is_required(field) 获取。
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True)
|
|
73
|
+
class SortSpec:
|
|
74
|
+
"""单字段排序声明;多个 SortSpec 的顺序即排序优先级。"""
|
|
75
|
+
|
|
76
|
+
field: str
|
|
77
|
+
direction: SortDirection = "ascending"
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class Contract:
|
|
82
|
+
"""
|
|
83
|
+
通用契约视图:字段、类型、输出列、排序。
|
|
84
|
+
|
|
85
|
+
fields / types 由上层完成合并后注入,本库只接收合并后的不可变视图。
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
name: str = ""
|
|
89
|
+
fields: Mapping[str, FieldSpec] = field(default_factory=dict)
|
|
90
|
+
types: Mapping[str, TypeSpec] = field(default_factory=dict)
|
|
91
|
+
output: tuple[str, ...] = ()
|
|
92
|
+
keys: tuple[str, ...] = ()
|
|
93
|
+
"""
|
|
94
|
+
区分唯一行的列(复合键)。空元组表示不区分唯一行,允许重复行。
|
|
95
|
+
|
|
96
|
+
非空时这些列必须出现在 output 中;其 required 由 is_required() 推导为 True。
|
|
97
|
+
是否/如何去重由 dedupe middleware 的 params 控制(默认关闭)。
|
|
98
|
+
"""
|
|
99
|
+
sort: tuple[SortSpec, ...] = ()
|
|
100
|
+
enabled: bool = True
|
|
101
|
+
help: str = ""
|
|
102
|
+
|
|
103
|
+
def output_specs(self) -> tuple[FieldSpec, ...]:
|
|
104
|
+
"""按 output 顺序返回字段定义。"""
|
|
105
|
+
return tuple(self.fields[name] for name in self.output if name in self.fields)
|
|
106
|
+
|
|
107
|
+
def is_required(self, field: str) -> bool:
|
|
108
|
+
"""
|
|
109
|
+
字段的最终必填性。
|
|
110
|
+
|
|
111
|
+
显式声明优先;未声明时,参与 sort 或 keys 的字段推导为 True,其余为 False。
|
|
112
|
+
"""
|
|
113
|
+
spec = self.fields.get(field)
|
|
114
|
+
if spec is not None and spec.required is not None:
|
|
115
|
+
return spec.required
|
|
116
|
+
if field in self.keys:
|
|
117
|
+
return True
|
|
118
|
+
if any(s.field == field for s in self.sort):
|
|
119
|
+
return True
|
|
120
|
+
return False
|
|
121
|
+
|
|
122
|
+
def dedupe_keys(self) -> tuple[str, ...]:
|
|
123
|
+
"""
|
|
124
|
+
返回契约声明的去重键。
|
|
125
|
+
|
|
126
|
+
仅供上层与 dedupe middleware 参考;dedupe 的 params.keys 优先级更高。
|
|
127
|
+
"""
|
|
128
|
+
return self.keys
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
__all__ = [
|
|
132
|
+
"ViolationAction",
|
|
133
|
+
"SortDirection",
|
|
134
|
+
"FillSpec",
|
|
135
|
+
"TypeSpec",
|
|
136
|
+
"FieldSpec",
|
|
137
|
+
"SortSpec",
|
|
138
|
+
"Contract",
|
|
139
|
+
]
|
darwin_cleaner/engine.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
# src/darwin_cleaner/engine.py
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
清洗引擎入口。
|
|
5
|
+
|
|
6
|
+
职责边界:读取单个 parquet -> 分叉 -> 按 order 跑链 -> 返回数据与 meta。
|
|
7
|
+
不做:配置加载、文件发现/合并、调度、断点、写 parquet/meta、CLI 退出码。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from typing import Any, Mapping, TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
import pandas as pd
|
|
17
|
+
|
|
18
|
+
from darwin_cleaner.context import CleanContext
|
|
19
|
+
from darwin_cleaner.exceptions import (
|
|
20
|
+
CleanerConfigError,
|
|
21
|
+
CleanerDataEmptyError,
|
|
22
|
+
CleanerDataNotFoundError,
|
|
23
|
+
CleanerValidationError,
|
|
24
|
+
)
|
|
25
|
+
from darwin_cleaner.middleware import MiddlewareRegistry, MiddlewareRegistryImpl
|
|
26
|
+
from darwin_cleaner.request import CleanRequest
|
|
27
|
+
from darwin_cleaner.results import (
|
|
28
|
+
CleanMeta,
|
|
29
|
+
CleanOutput,
|
|
30
|
+
CleanReport,
|
|
31
|
+
CleanResult,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
ENGINE_VERSION = "0.4.0.dev0"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class CleanStep:
|
|
42
|
+
"""执行计划中的一步(按 order 排列)。"""
|
|
43
|
+
|
|
44
|
+
name: str
|
|
45
|
+
order: int
|
|
46
|
+
version: str = ""
|
|
47
|
+
params: Mapping[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class CleanPlan:
|
|
52
|
+
"""单个分叉的可审查执行计划。"""
|
|
53
|
+
|
|
54
|
+
output_key: str
|
|
55
|
+
steps: tuple[CleanStep, ...]
|
|
56
|
+
read_columns: tuple[str, ...]
|
|
57
|
+
warnings: tuple[str, ...] = ()
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _input_hash(df: pd.DataFrame, algorithm: str) -> str:
|
|
61
|
+
"""基于 DataFrame 内容计算稳定 hash(与格式/压缩无关)。"""
|
|
62
|
+
import hashlib
|
|
63
|
+
|
|
64
|
+
h = hashlib.new(algorithm)
|
|
65
|
+
payload = pd.util.hash_pandas_object(df, index=True).values.tobytes()
|
|
66
|
+
h.update(payload)
|
|
67
|
+
return f"{algorithm}:{h.hexdigest()}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _signature(*parts: Any) -> str:
|
|
71
|
+
"""对契约 / 规则 / 注册表指纹生成稳定组合指纹。"""
|
|
72
|
+
import hashlib
|
|
73
|
+
import json
|
|
74
|
+
|
|
75
|
+
blob = json.dumps(parts, sort_keys=True, default=str, ensure_ascii=False)
|
|
76
|
+
return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class CleaningEngine:
|
|
80
|
+
"""
|
|
81
|
+
清洗引擎。
|
|
82
|
+
|
|
83
|
+
使用方式:
|
|
84
|
+
registry = MiddlewareRegistryImpl()
|
|
85
|
+
registry.builtins()
|
|
86
|
+
engine = CleaningEngine(registry)
|
|
87
|
+
result = engine.clean(request)
|
|
88
|
+
|
|
89
|
+
所有产出都在内存中;上层自行决定如何持久化。
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(self, registry: MiddlewareRegistry) -> None:
|
|
93
|
+
self._registry = registry
|
|
94
|
+
|
|
95
|
+
def build_plan(self, request: CleanRequest) -> tuple[CleanPlan, ...]:
|
|
96
|
+
"""构建并校验执行计划,不执行、不读数据。可用于审查与调试。"""
|
|
97
|
+
self._preflight(request)
|
|
98
|
+
resolved = self._registry.resolve(request.options.middleware_overrides)
|
|
99
|
+
steps = tuple(
|
|
100
|
+
CleanStep(name=s.name, order=s.order, version=s.version, params=dict(s.params))
|
|
101
|
+
for s in resolved
|
|
102
|
+
)
|
|
103
|
+
return tuple(
|
|
104
|
+
CleanPlan(
|
|
105
|
+
output_key=name,
|
|
106
|
+
steps=steps,
|
|
107
|
+
read_columns=request.contracts[name].output,
|
|
108
|
+
)
|
|
109
|
+
for name in request.contracts
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
def clean(self, request: CleanRequest) -> CleanResult:
|
|
113
|
+
"""
|
|
114
|
+
执行清洗。
|
|
115
|
+
|
|
116
|
+
流程:preflight 校验 -> 读取单个输入 -> 行分叉/列分叉 ->
|
|
117
|
+
逐分叉按 order 跑链 -> 生成 meta -> 汇总。
|
|
118
|
+
|
|
119
|
+
异常通过 darwin_cleaner.exceptions 抛出,不映射为退出码。
|
|
120
|
+
"""
|
|
121
|
+
started = datetime.now(timezone.utc).isoformat()
|
|
122
|
+
warnings: list[str] = []
|
|
123
|
+
errors: list[str] = []
|
|
124
|
+
outputs: list[CleanOutput] = []
|
|
125
|
+
|
|
126
|
+
try:
|
|
127
|
+
self._preflight(request)
|
|
128
|
+
df = self._read_input(request)
|
|
129
|
+
resolved = self._registry.resolve(request.options.middleware_overrides)
|
|
130
|
+
signature = _signature(
|
|
131
|
+
self._contract_signature(request),
|
|
132
|
+
self._rules_signature(request),
|
|
133
|
+
self._registry.signature(request.options.middleware_overrides),
|
|
134
|
+
)
|
|
135
|
+
plans = request.rules.to_fork_plans()
|
|
136
|
+
if not plans:
|
|
137
|
+
# 无 filters / outputs 时,退化为单组列分叉:产出全部已注入契约
|
|
138
|
+
from darwin_cleaner.rules import ForkPlan
|
|
139
|
+
|
|
140
|
+
plans = (ForkPlan(key="all", output_names=tuple(request.contracts)),)
|
|
141
|
+
|
|
142
|
+
for plan in plans:
|
|
143
|
+
group = self._apply_row_filter(df, plan)
|
|
144
|
+
for output_name in plan.output_names:
|
|
145
|
+
out = self._run_one(
|
|
146
|
+
group.copy(), request, output_name, resolved, signature
|
|
147
|
+
)
|
|
148
|
+
outputs.append(out)
|
|
149
|
+
except (CleanerConfigError, CleanerDataNotFoundError, CleanerDataEmptyError) as exc:
|
|
150
|
+
errors.append(str(exc))
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
errors.append(f"清洗失败: {exc}")
|
|
153
|
+
|
|
154
|
+
finished = datetime.now(timezone.utc).isoformat()
|
|
155
|
+
status = "failed" if errors else "success"
|
|
156
|
+
return CleanResult(
|
|
157
|
+
outputs=tuple(outputs),
|
|
158
|
+
status=status,
|
|
159
|
+
warnings=tuple(warnings),
|
|
160
|
+
errors=tuple(errors),
|
|
161
|
+
started_at=started,
|
|
162
|
+
finished_at=finished,
|
|
163
|
+
duration_seconds=0.0,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
# ------------------------------------------------------------
|
|
167
|
+
# preflight
|
|
168
|
+
# ------------------------------------------------------------
|
|
169
|
+
|
|
170
|
+
def _preflight(self, request: CleanRequest) -> None:
|
|
171
|
+
"""执行前校验请求的自洽性;失败即抛 CleanerConfigError。"""
|
|
172
|
+
if not request.contracts:
|
|
173
|
+
raise CleanerConfigError("contracts 不能为空")
|
|
174
|
+
for name, contract in request.contracts.items():
|
|
175
|
+
if not contract.output:
|
|
176
|
+
raise CleanerConfigError(f"契约 {name} 的 output 不能为空")
|
|
177
|
+
missing_def = [f for f in contract.output if f not in contract.fields]
|
|
178
|
+
if missing_def:
|
|
179
|
+
raise CleanerConfigError(
|
|
180
|
+
f"契约 {name} 的 output 字段未在 fields 中定义: {missing_def}"
|
|
181
|
+
)
|
|
182
|
+
missing_keys = [k for k in contract.keys if k not in contract.output]
|
|
183
|
+
if missing_keys:
|
|
184
|
+
raise CleanerConfigError(
|
|
185
|
+
f"契约 {name} 的 keys 字段不在 output 中: {missing_keys}"
|
|
186
|
+
)
|
|
187
|
+
for plan in request.rules.to_fork_plans():
|
|
188
|
+
unknown = [n for n in plan.output_names if n not in request.contracts]
|
|
189
|
+
if unknown:
|
|
190
|
+
raise CleanerConfigError(
|
|
191
|
+
f"分叉 {plan.key} 引用了未知输出名: {unknown}"
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
# ------------------------------------------------------------
|
|
195
|
+
# 读取与分叉
|
|
196
|
+
# ------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def _read_input(self, request: CleanRequest) -> pd.DataFrame:
|
|
199
|
+
"""
|
|
200
|
+
读取单个 parquet 或接收内存 DataFrame。
|
|
201
|
+
|
|
202
|
+
列裁剪只用于 parquet 读取优化:需求列与文件实际列取交集,
|
|
203
|
+
避免读取不存在的列报错。内存 DataFrame 不裁剪——字段映射、公式等
|
|
204
|
+
步骤可能依赖 output 之外的中间列,裁剪会破坏清洗链。
|
|
205
|
+
"""
|
|
206
|
+
source = request.input
|
|
207
|
+
if isinstance(source, pd.DataFrame):
|
|
208
|
+
df = source.copy()
|
|
209
|
+
else:
|
|
210
|
+
columns = request.options.read.columns
|
|
211
|
+
if columns is None:
|
|
212
|
+
columns = self._derive_columns(request)
|
|
213
|
+
read_cols = None
|
|
214
|
+
if columns:
|
|
215
|
+
try:
|
|
216
|
+
import pyarrow.parquet as pq
|
|
217
|
+
|
|
218
|
+
available = set(pq.read_schema(source).names)
|
|
219
|
+
read_cols = [c for c in columns if c in available]
|
|
220
|
+
except Exception:
|
|
221
|
+
read_cols = None
|
|
222
|
+
try:
|
|
223
|
+
df = pd.read_parquet(source, columns=read_cols)
|
|
224
|
+
except Exception as exc:
|
|
225
|
+
raise CleanerDataNotFoundError(f"读取 parquet 失败: {source}: {exc}") from exc
|
|
226
|
+
|
|
227
|
+
if df.empty:
|
|
228
|
+
raise CleanerDataEmptyError("输入数据为 0 行")
|
|
229
|
+
return df
|
|
230
|
+
|
|
231
|
+
def _derive_columns(self, request: CleanRequest) -> tuple[str, ...]:
|
|
232
|
+
"""按本次涉及契约的 output / keys / sort 与规则字段推导读取列。"""
|
|
233
|
+
needed: list[str] = []
|
|
234
|
+
for name in request.contracts:
|
|
235
|
+
contract = request.contracts[name]
|
|
236
|
+
for field in list(contract.output) + list(contract.keys):
|
|
237
|
+
if field not in needed:
|
|
238
|
+
needed.append(field)
|
|
239
|
+
for s in contract.sort:
|
|
240
|
+
if s.field not in needed:
|
|
241
|
+
needed.append(s.field)
|
|
242
|
+
for field in list(request.rules.mapping) + list(request.rules.transform):
|
|
243
|
+
if field not in needed:
|
|
244
|
+
needed.append(field)
|
|
245
|
+
for spec in request.rules.filters.values():
|
|
246
|
+
if spec.field and spec.field not in needed:
|
|
247
|
+
needed.append(spec.field)
|
|
248
|
+
return tuple(needed)
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def _apply_row_filter(df: pd.DataFrame, plan: Any) -> pd.DataFrame:
|
|
252
|
+
"""按 RowForkSpec 过滤行;无配置则全量。"""
|
|
253
|
+
spec = plan.row_filter
|
|
254
|
+
if spec is None or not spec.field:
|
|
255
|
+
return df
|
|
256
|
+
if not spec.regex and not spec.exclude_regex:
|
|
257
|
+
return df
|
|
258
|
+
if spec.field not in df.columns:
|
|
259
|
+
return df
|
|
260
|
+
series = df[spec.field].astype(str)
|
|
261
|
+
if spec.regex:
|
|
262
|
+
mask = series.str.match(spec.regex, na=False)
|
|
263
|
+
else:
|
|
264
|
+
mask = ~series.str.match(spec.exclude_regex, na=False)
|
|
265
|
+
return df[mask].reset_index(drop=True)
|
|
266
|
+
|
|
267
|
+
# ------------------------------------------------------------
|
|
268
|
+
# 单分叉执行
|
|
269
|
+
# ------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
def _run_one(
|
|
272
|
+
self,
|
|
273
|
+
df: pd.DataFrame,
|
|
274
|
+
request: CleanRequest,
|
|
275
|
+
output_name: str,
|
|
276
|
+
resolved: tuple[Any, ...],
|
|
277
|
+
signature: str,
|
|
278
|
+
) -> CleanOutput:
|
|
279
|
+
"""对单个分叉跑完整链,产出 CleanOutput。"""
|
|
280
|
+
contract = request.contracts[output_name]
|
|
281
|
+
report = CleanReport(
|
|
282
|
+
output_key=output_name,
|
|
283
|
+
max_validation_samples=request.options.collect_validation_samples,
|
|
284
|
+
)
|
|
285
|
+
ctx = CleanContext(
|
|
286
|
+
output_key=output_name,
|
|
287
|
+
contract=contract,
|
|
288
|
+
rules=request.rules,
|
|
289
|
+
report=report,
|
|
290
|
+
)
|
|
291
|
+
report.start()
|
|
292
|
+
report.bump_stat("rows_in", len(df))
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
current = df
|
|
296
|
+
for spec in resolved:
|
|
297
|
+
try:
|
|
298
|
+
result = spec.fn(current, ctx, spec.params)
|
|
299
|
+
except (CleanerConfigError, CleanerValidationError):
|
|
300
|
+
raise
|
|
301
|
+
except Exception as exc:
|
|
302
|
+
if request.options.strict:
|
|
303
|
+
raise CleanerValidationError(
|
|
304
|
+
f"middleware {spec.name} 失败: {exc}"
|
|
305
|
+
) from exc
|
|
306
|
+
report.add_warning(f"middleware {spec.name} 失败: {exc}")
|
|
307
|
+
report.degraded = True
|
|
308
|
+
continue
|
|
309
|
+
if result is not None:
|
|
310
|
+
current = result
|
|
311
|
+
|
|
312
|
+
if current.empty:
|
|
313
|
+
raise CleanerDataEmptyError(f"输出 {output_name} 为 0 行")
|
|
314
|
+
|
|
315
|
+
report.bump_stat("rows_out", len(current))
|
|
316
|
+
report.status = "success"
|
|
317
|
+
meta = CleanMeta(
|
|
318
|
+
output_key=output_name,
|
|
319
|
+
rows=len(current),
|
|
320
|
+
columns=tuple(current.columns),
|
|
321
|
+
data_hash=_input_hash(current, request.options.hash_algorithm),
|
|
322
|
+
rule_signature=signature,
|
|
323
|
+
engine_version=ENGINE_VERSION,
|
|
324
|
+
stats=report.stats,
|
|
325
|
+
warnings=tuple(report.warnings),
|
|
326
|
+
degraded=report.degraded,
|
|
327
|
+
)
|
|
328
|
+
return CleanOutput(
|
|
329
|
+
output_key=output_name,
|
|
330
|
+
status="success",
|
|
331
|
+
data=current,
|
|
332
|
+
meta=meta,
|
|
333
|
+
report=report,
|
|
334
|
+
)
|
|
335
|
+
except (CleanerConfigError, CleanerDataEmptyError, CleanerValidationError) as exc:
|
|
336
|
+
report.status = "failed"
|
|
337
|
+
report.add_error(str(exc))
|
|
338
|
+
return CleanOutput(
|
|
339
|
+
output_key=output_name,
|
|
340
|
+
status="failed",
|
|
341
|
+
data=None,
|
|
342
|
+
report=report,
|
|
343
|
+
)
|
|
344
|
+
finally:
|
|
345
|
+
report.finish()
|
|
346
|
+
|
|
347
|
+
# ------------------------------------------------------------
|
|
348
|
+
# 指纹
|
|
349
|
+
# ------------------------------------------------------------
|
|
350
|
+
|
|
351
|
+
@staticmethod
|
|
352
|
+
def _contract_signature(request: CleanRequest) -> list[dict[str, Any]]:
|
|
353
|
+
result = []
|
|
354
|
+
for name in sorted(request.contracts):
|
|
355
|
+
c = request.contracts[name]
|
|
356
|
+
result.append(
|
|
357
|
+
{
|
|
358
|
+
"name": name,
|
|
359
|
+
"output": list(c.output),
|
|
360
|
+
"keys": list(c.keys),
|
|
361
|
+
"sort": [[s.field, s.direction] for s in c.sort],
|
|
362
|
+
"fields": {
|
|
363
|
+
k: {
|
|
364
|
+
"type": v.type,
|
|
365
|
+
"required": v.required,
|
|
366
|
+
"formula": v.formula,
|
|
367
|
+
"fill": str(v.fill) if v.fill else None,
|
|
368
|
+
"consistency": list(v.consistency),
|
|
369
|
+
"on_violation": v.on_violation,
|
|
370
|
+
}
|
|
371
|
+
for k, v in sorted(c.fields.items())
|
|
372
|
+
},
|
|
373
|
+
"types": {
|
|
374
|
+
k: [v.converter, v.min, v.max, v.rel_diff, v.abs_diff]
|
|
375
|
+
for k, v in sorted(c.types.items())
|
|
376
|
+
},
|
|
377
|
+
}
|
|
378
|
+
)
|
|
379
|
+
return result
|
|
380
|
+
|
|
381
|
+
@staticmethod
|
|
382
|
+
def _rules_signature(request: CleanRequest) -> dict[str, Any]:
|
|
383
|
+
r = request.rules
|
|
384
|
+
return {
|
|
385
|
+
"mapping": dict(r.mapping),
|
|
386
|
+
"value_map": {k: dict(v) for k, v in r.value_map.items()},
|
|
387
|
+
"transform": {
|
|
388
|
+
k: [s.kind, s.value, s.factor, s.action] for k, s in r.transform.items()
|
|
389
|
+
},
|
|
390
|
+
"filters": {
|
|
391
|
+
k: [s.field, s.regex, s.exclude_regex, list(s.outputs)]
|
|
392
|
+
for k, s in r.filters.items()
|
|
393
|
+
},
|
|
394
|
+
"outputs": list(r.outputs),
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def clean(
|
|
399
|
+
request: CleanRequest,
|
|
400
|
+
*,
|
|
401
|
+
registry: MiddlewareRegistry | None = None,
|
|
402
|
+
) -> CleanResult:
|
|
403
|
+
"""便捷函数:使用默认(内置)注册表执行一次清洗。"""
|
|
404
|
+
if registry is None:
|
|
405
|
+
registry = MiddlewareRegistryImpl()
|
|
406
|
+
registry.builtins()
|
|
407
|
+
return CleaningEngine(registry).clean(request)
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
__all__ = ["CleanStep", "CleanPlan", "CleaningEngine", "clean"]
|