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.
@@ -0,0 +1,103 @@
1
+ # src/darwin_cleaner/rules.py
2
+
3
+ """
4
+ 规则值对象:描述"原始字段如何映射到契约"。
5
+
6
+ 由上层解析后注入,替代 middleware 内的全局配置读取。
7
+ 本模块不含任何数据源标识、业务类型标识。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Literal, Mapping
14
+
15
+ TransformKind = Literal["value", "factor", "action"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class TransformSpec:
20
+ """
21
+ 字段转换声明,kind 决定读取哪个参数。
22
+
23
+ value —— 常量赋值,可创建新列
24
+ factor —— 乘以系数,要求字段已存在
25
+ action —— 调用注册的转换动作,要求字段已存在
26
+ """
27
+
28
+ kind: TransformKind
29
+ value: Any = None
30
+ factor: float | None = None
31
+ action: str | None = None
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class JsonExtractSpec:
36
+ """从 dict / JSON 列按路径提取字段。"""
37
+
38
+ column: str
39
+ path: tuple[str, ...] = ()
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class RowForkSpec:
44
+ """
45
+ 行分叉组。
46
+
47
+ field 指向的列不存在时不过滤(全量通过)。
48
+ regex 与 exclude_regex 可同时存在:两者都满足才算命中。
49
+ outputs 是输出名(对应请求中 contracts 的键),不是业务类型。
50
+ """
51
+
52
+ key: str
53
+ outputs: tuple[str, ...] = ()
54
+ field: str | None = None
55
+ regex: str | None = None
56
+ exclude_regex: str | None = None
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class ForkPlan:
61
+ """单个分叉的显式执行规格。"""
62
+
63
+ key: str
64
+ output_names: tuple[str, ...]
65
+ row_filter: RowForkSpec | None = None
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class Rules:
70
+ """一组通用清洗规则。"""
71
+
72
+ mapping: Mapping[str, str] = field(default_factory=dict)
73
+ value_map: Mapping[str, Mapping[str, str]] = field(default_factory=dict)
74
+ transform: Mapping[str, TransformSpec] = field(default_factory=dict)
75
+ json_extract: Mapping[str, JsonExtractSpec] = field(default_factory=dict)
76
+ filters: Mapping[str, RowForkSpec] = field(default_factory=dict)
77
+ outputs: tuple[str, ...] = ()
78
+
79
+ def to_fork_plans(self) -> tuple[ForkPlan, ...]:
80
+ """
81
+ 把 filters / outputs 解析为有序分叉计划。
82
+
83
+ - 有 filters:每个非空 outputs 的 RowForkSpec 生成一个计划(保持插入顺序);
84
+ - 无 filters 但有 outputs:退化为单组 "all" 的纯列分叉。
85
+ """
86
+ plans: list[ForkPlan] = []
87
+ if self.filters:
88
+ for key, spec in self.filters.items():
89
+ if spec.outputs:
90
+ plans.append(ForkPlan(key=key, output_names=spec.outputs, row_filter=spec))
91
+ elif self.outputs:
92
+ plans.append(ForkPlan(key="all", output_names=self.outputs, row_filter=None))
93
+ return tuple(plans)
94
+
95
+
96
+ __all__ = [
97
+ "TransformKind",
98
+ "TransformSpec",
99
+ "JsonExtractSpec",
100
+ "RowForkSpec",
101
+ "ForkPlan",
102
+ "Rules",
103
+ ]
@@ -0,0 +1,501 @@
1
+ # src/darwin_cleaner/steps.py
2
+
3
+ """
4
+ 库内置的 12 个通用清洗步骤。
5
+
6
+ 从 darwin-fetch 的 middlewares/steps.py 迁移并强化:
7
+ - 参数从 ctx.rules / ctx.contract / params 读取,不再读全局配置树;
8
+ - 错误在严格模式下抛出,不再静默降级为 warning;
9
+ - 新增 dedupe(70),默认关闭。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ from typing import Any, Mapping, TYPE_CHECKING
16
+
17
+ import pandas as pd
18
+
19
+ from darwin_cleaner.context import CleanContext
20
+ from darwin_cleaner.exceptions import CleanerConfigError
21
+ from darwin_cleaner.middleware import middleware
22
+
23
+ if TYPE_CHECKING:
24
+ pass
25
+
26
+ DEFAULT_REL_DIFF = 0.003
27
+ DEFAULT_ABS_DIFF = 0.01
28
+
29
+ _FORMULA_IDENT_RE = re.compile(r"\b([a-zA-Z_][a-zA-Z0-9_]*)\b")
30
+ _FORMULA_KEYWORDS = {
31
+ "and", "or", "not", "in", "is", "if", "else", "True", "False", "None",
32
+ "abs", "min", "max", "round", "int", "float", "str", "bool",
33
+ "where", "index", "columns",
34
+ }
35
+
36
+ CONSISTENCY_RULES = {
37
+ "high_ge_low": ("high", ">=", "low"),
38
+ "high_ge_open": ("high", ">=", "open"),
39
+ "high_ge_close": ("high", ">=", "close"),
40
+ "low_le_open": ("low", "<=", "open"),
41
+ "low_le_close": ("low", "<=", "close"),
42
+ }
43
+
44
+
45
+ # ============================================================
46
+ # transform 动作
47
+ # ============================================================
48
+
49
+ def _symbol_to_standard(s: pd.Series) -> pd.Series:
50
+ def norm(x: Any) -> Any:
51
+ if pd.isna(x):
52
+ return x
53
+ text = str(x).strip()
54
+ m = re.match(r"^(sh|sz|bj)\.(\w+)$", text, re.IGNORECASE)
55
+ return f"{m.group(2)}.{m.group(1).upper()}" if m else text
56
+
57
+ return s.astype(str).apply(norm)
58
+
59
+
60
+ def _date_to_compact(s: pd.Series) -> pd.Series:
61
+ return (
62
+ s.astype(str)
63
+ .str.replace("-", "", regex=False)
64
+ .str.replace("/", "", regex=False)
65
+ )
66
+
67
+
68
+ def _zero_to_nan(s: pd.Series) -> pd.Series:
69
+ s_num = pd.to_numeric(s, errors="coerce")
70
+ return s.mask(s_num == 0, None)
71
+
72
+
73
+ def _datetime_to_compact(s: pd.Series) -> pd.Series:
74
+ def norm(x: Any) -> Any:
75
+ if pd.isna(x):
76
+ return x
77
+ text = str(x).strip()
78
+ if text.isdigit():
79
+ return text.zfill(17)
80
+ dt = pd.to_datetime(text, errors="coerce")
81
+ if pd.isna(dt):
82
+ return x
83
+ return dt.strftime("%Y%m%d%H%M%S") + "000"
84
+
85
+ return s.apply(norm)
86
+
87
+
88
+ def _symbol_suffix(s: pd.Series) -> pd.Series:
89
+ def norm(x: Any) -> Any:
90
+ if pd.isna(x):
91
+ return x
92
+ code = str(x).strip()
93
+ if "." in code:
94
+ return code
95
+ if code.startswith(("60", "68", "900")):
96
+ return f"{code}.SH"
97
+ if code.startswith(("00", "30", "200", "201")):
98
+ return f"{code}.SZ"
99
+ if code.startswith(("8", "4", "92")):
100
+ return f"{code}.BJ"
101
+ return code
102
+
103
+ return s.apply(norm)
104
+
105
+
106
+ def _us_symbol_suffix(s: pd.Series) -> pd.Series:
107
+ def norm(x: Any) -> Any:
108
+ if pd.isna(x):
109
+ return x
110
+ code = str(x).strip()
111
+ return code if code.endswith(".US") else f"{code}.US"
112
+
113
+ return s.apply(norm)
114
+
115
+
116
+ def _float_to_compact(s: pd.Series) -> pd.Series:
117
+ def norm(x: Any) -> Any:
118
+ if pd.isna(x):
119
+ return None
120
+ try:
121
+ return str(int(x))
122
+ except (ValueError, OverflowError):
123
+ return None
124
+
125
+ return s.apply(norm)
126
+
127
+
128
+ DEFAULT_ACTIONS: dict[str, Any] = {
129
+ "symbol_to_standard": _symbol_to_standard,
130
+ "date_to_compact": _date_to_compact,
131
+ "datetime_to_compact": _datetime_to_compact,
132
+ "zero_to_nan": _zero_to_nan,
133
+ "symbol_suffix": _symbol_suffix,
134
+ "us_symbol_suffix": _us_symbol_suffix,
135
+ "float_to_compact": _float_to_compact,
136
+ }
137
+
138
+
139
+ _CONVERTERS = {
140
+ "numeric": lambda s: s.astype("Int64") if s.dtype == bool else pd.to_numeric(s, errors="coerce"),
141
+ "string": lambda s: s.astype(str),
142
+ "datetime": lambda s: pd.to_datetime(s, errors="coerce"),
143
+ "timestamp_ms": lambda s: pd.to_numeric(s, errors="coerce").astype("Int64"),
144
+ }
145
+
146
+
147
+ def _eval_formula(df: pd.DataFrame, formula: str) -> pd.Series:
148
+ result = df.eval(formula)
149
+ if isinstance(result, pd.Series):
150
+ return result
151
+ return pd.Series(result, index=df.index)
152
+
153
+
154
+ def _extract_formula_fields(formula: str) -> set[str]:
155
+ if not formula:
156
+ return set()
157
+ return set(_FORMULA_IDENT_RE.findall(formula)) - _FORMULA_KEYWORDS
158
+
159
+
160
+ # ============================================================
161
+ # 12 个内置步骤
162
+ # ============================================================
163
+
164
+ @middleware(order=10)
165
+ def field_mapping(
166
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
167
+ ) -> pd.DataFrame:
168
+ """按 ctx.rules.mapping 做字段改名。"""
169
+ mapping = ctx.rules.mapping
170
+ if not mapping:
171
+ return df
172
+ rename = {k: v for k, v in mapping.items() if k in df.columns}
173
+ return df.rename(columns=rename)
174
+
175
+
176
+ @middleware(order=12)
177
+ def value_mapping(
178
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
179
+ ) -> pd.DataFrame:
180
+ """按 ctx.rules.value_map 做值替换。"""
181
+ value_map = ctx.rules.value_map
182
+ if not value_map:
183
+ return df
184
+ for field, mapping in value_map.items():
185
+ if field in df.columns:
186
+ df[field] = df[field].replace(mapping)
187
+ return df
188
+
189
+
190
+ @middleware(order=15)
191
+ def field_transform(
192
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
193
+ ) -> pd.DataFrame:
194
+ """按 ctx.rules.transform 做常量赋值 / 乘法 / 动作。"""
195
+ actions = dict(DEFAULT_ACTIONS)
196
+ # 允许通过 params["actions"] 注入自定义动作(强类型 Options 的轻量替代)
197
+ actions.update(params.get("actions", {}) or {})
198
+
199
+ for field, spec in ctx.rules.transform.items():
200
+ if spec.kind == "value":
201
+ df[field] = spec.value
202
+ continue
203
+ if field not in df.columns:
204
+ continue
205
+ if spec.kind == "factor":
206
+ if spec.factor is None:
207
+ raise CleanerConfigError(f"transform factor 缺少 factor 值: {field}")
208
+ df[field] = df[field] * spec.factor
209
+ elif spec.kind == "action":
210
+ if not spec.action:
211
+ raise CleanerConfigError(f"transform action 缺少 action 名: {field}")
212
+ action = actions.get(spec.action)
213
+ if action is None:
214
+ raise CleanerConfigError(f"未知 transform 动作: {spec.action}")
215
+ df[field] = action(df[field])
216
+ return df
217
+
218
+
219
+ @middleware(order=20)
220
+ def type_conversion(
221
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
222
+ ) -> pd.DataFrame:
223
+ """按契约字段类型的 converter 统一 dtype。"""
224
+ for field, spec in ctx.contract.fields.items():
225
+ if field not in df.columns:
226
+ continue
227
+ type_spec = ctx.contract.types.get(spec.type)
228
+ conv_name = type_spec.converter if type_spec else "string"
229
+ handler = _CONVERTERS.get(conv_name)
230
+ if handler is not None:
231
+ df[field] = handler(df[field])
232
+ return df
233
+
234
+
235
+ @middleware(order=30)
236
+ def fill(df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]) -> pd.DataFrame:
237
+ """按字段的 fill 规则分组填充,统计写入 nulls_filled。"""
238
+ group_field = params.get("group_field", "symbol")
239
+ for field, spec in ctx.contract.fields.items():
240
+ if spec.fill is None or field not in df.columns:
241
+ continue
242
+ strategy = spec.fill.strategy
243
+ if strategy == "none":
244
+ continue
245
+ if strategy == "value":
246
+ before = int(df[field].isna().sum())
247
+ df[field] = df[field].fillna(spec.fill.value)
248
+ filled = before - int(df[field].isna().sum())
249
+ if filled:
250
+ ctx.report.bump_mapping("nulls_filled", field, filled)
251
+ elif strategy == "ffill":
252
+ if group_field not in df.columns:
253
+ continue
254
+ before = int(df[field].isna().sum())
255
+ df[field] = df.groupby(group_field)[field].ffill(limit=spec.fill.max_days)
256
+ filled = before - int(df[field].isna().sum())
257
+ if filled:
258
+ ctx.report.bump_mapping("nulls_filled", field, filled)
259
+ return df
260
+
261
+
262
+ @middleware(order=40)
263
+ def formula_compute(
264
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
265
+ ) -> pd.DataFrame:
266
+ """全空列按 formula 计算;部分缺失只告警。"""
267
+ for field, spec in ctx.contract.fields.items():
268
+ if not spec.formula:
269
+ continue
270
+ if field not in df.columns:
271
+ df[field] = None
272
+ null_count = int(df[field].isna().sum())
273
+ total = len(df)
274
+ if null_count == 0:
275
+ continue
276
+ if null_count == total:
277
+ try:
278
+ df[field] = _eval_formula(df, spec.formula)
279
+ ctx.report.bump_mapping("computed_fields", field, int(df[field].notna().sum()))
280
+ except Exception as exc:
281
+ ctx.report.add_warning(f"计算 {field} 失败: {exc}")
282
+ else:
283
+ ctx.report.add_warning(
284
+ f"{field}: {null_count}/{total} 行缺失,不计算(部分缺失)"
285
+ )
286
+ return df
287
+
288
+
289
+ @middleware(order=45)
290
+ def formula_validate(
291
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
292
+ ) -> pd.DataFrame:
293
+ """双容差校验:rel_diff 与 abs_diff 同时超才算不符。"""
294
+ for field, spec in ctx.contract.fields.items():
295
+ if not spec.formula or field not in df.columns:
296
+ continue
297
+ required = _extract_formula_fields(spec.formula)
298
+ missing = required - set(df.columns)
299
+ if missing:
300
+ ctx.report.add_warning(f"{field}: formula 依赖字段不存在: {sorted(missing)}")
301
+ continue
302
+
303
+ type_spec = ctx.contract.types.get(spec.type)
304
+ rel_tol = type_spec.rel_diff if type_spec else DEFAULT_REL_DIFF
305
+ abs_tol = type_spec.abs_diff if type_spec else DEFAULT_ABS_DIFF
306
+
307
+ valid = df[field].notna()
308
+ if not bool(valid.any()):
309
+ continue
310
+ try:
311
+ expected = _eval_formula(df, spec.formula)
312
+ except Exception as exc:
313
+ ctx.report.add_warning(f"{field}: formula 求值失败: {exc}")
314
+ continue
315
+ if not isinstance(expected, pd.Series):
316
+ expected = pd.Series(expected, index=df.index)
317
+
318
+ if bool(expected.isin([float("inf"), float("-inf")]).any()):
319
+ ctx.report.add_warning(f"{field}: formula 计算出 inf,跳过验证")
320
+ continue
321
+ if pd.api.types.is_bool_dtype(expected) or pd.api.types.is_bool_dtype(df[field]):
322
+ continue
323
+
324
+ diff = (df[field] - expected).abs()
325
+ denom = expected.abs().replace(0, pd.NA)
326
+ rel_diff = (diff / denom).fillna(0.0)
327
+ bad = valid & (rel_diff > rel_tol) & (diff > abs_tol)
328
+ bad_count = int(bad.sum())
329
+ if bad_count:
330
+ ctx.report.bump_mapping("validated_fields", field, bad_count)
331
+ ctx.report.add_warning(
332
+ f"{field}: {bad_count} 行与公式不符 (rel_tol={rel_tol}, abs_tol={abs_tol})"
333
+ )
334
+ return df
335
+
336
+
337
+ @middleware(order=50)
338
+ def consistency(
339
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
340
+ ) -> pd.DataFrame:
341
+ """字段间一致性规则(如 high >= low),违规置空。"""
342
+ for field, spec in ctx.contract.fields.items():
343
+ for rule_name in spec.consistency:
344
+ rule = CONSISTENCY_RULES.get(rule_name)
345
+ if rule is None:
346
+ ctx.report.add_warning(f"未知一致性规则: {rule_name}")
347
+ continue
348
+ a, op, b = rule
349
+ if a not in df.columns or b not in df.columns:
350
+ continue
351
+ both = df[a].notna() & df[b].notna()
352
+ if op == ">=":
353
+ bad = (df[a] < df[b]) & both
354
+ elif op == "<=":
355
+ bad = (df[a] > df[b]) & both
356
+ else:
357
+ continue
358
+ bad_count = int(bad.sum())
359
+ if bad_count:
360
+ ctx.report.bump_mapping("outliers_corrected", rule_name, bad_count)
361
+ ctx.report.add_warning(f"一致性规则 {rule_name} 违规: {bad_count} 行")
362
+ df[field] = df[field].mask(bad, None)
363
+ return df
364
+
365
+
366
+ @middleware(order=60)
367
+ def type_validate(
368
+ df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]
369
+ ) -> pd.DataFrame:
370
+ """inf / min / max 越界置空。"""
371
+ for field, spec in ctx.contract.fields.items():
372
+ if field not in df.columns:
373
+ continue
374
+ type_spec = ctx.contract.types.get(spec.type)
375
+ series = df[field]
376
+
377
+ inf_mask = series.isin([float("inf"), float("-inf")])
378
+ n_inf = int(inf_mask.sum())
379
+ if n_inf:
380
+ ctx.report.bump_mapping("outliers_corrected", f"{field}.inf", n_inf)
381
+ df[field] = series.mask(inf_mask, None)
382
+ series = df[field]
383
+
384
+ if type_spec is None:
385
+ continue
386
+ if type_spec.min is not None:
387
+ bad = series.notna() & (series < type_spec.min)
388
+ n = int(bad.sum())
389
+ if n:
390
+ ctx.report.bump_mapping("outliers_corrected", f"{field}.min", n)
391
+ df[field] = series.mask(bad, None)
392
+ series = df[field]
393
+ if type_spec.max is not None:
394
+ bad = series.notna() & (series > type_spec.max)
395
+ n = int(bad.sum())
396
+ if n:
397
+ ctx.report.bump_mapping("outliers_corrected", f"{field}.max", n)
398
+ df[field] = series.mask(bad, None)
399
+ return df
400
+
401
+
402
+ @middleware(order=70, enabled=False)
403
+ def dedupe(df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]) -> pd.DataFrame:
404
+ """按 keys 去重;默认关闭,由 params 定义重复的含义与处理方式。"""
405
+ keys = tuple(params.get("keys") or ()) or ctx.contract.dedupe_keys()
406
+ if not keys:
407
+ raise CleanerConfigError("dedupe 开启但未指定 keys:无法定义重复行")
408
+ missing = [k for k in keys if k not in df.columns]
409
+ if missing:
410
+ raise CleanerConfigError(f"dedupe 的 keys 列不存在: {missing}")
411
+
412
+ scope = params.get("scope", "keys")
413
+ strategy = params.get("strategy", "first")
414
+ if strategy not in ("first", "last", "error"):
415
+ raise CleanerConfigError(f"未知的 dedupe strategy: {strategy}")
416
+
417
+ subset = list(df.columns) if scope == "all_columns" else list(keys)
418
+ duplicated = df.duplicated(subset=subset, keep=False)
419
+ n_dup = int(duplicated.sum())
420
+
421
+ if strategy == "error":
422
+ if n_dup:
423
+ raise CleanerConfigError(f"发现 {n_dup} 行重复(keys={keys})")
424
+ return df
425
+
426
+ before = len(df)
427
+ result = df.drop_duplicates(subset=subset, keep="last" if strategy == "last" else "first")
428
+ result = result.reset_index(drop=True)
429
+ removed = before - len(result)
430
+ if removed:
431
+ ctx.report.bump_stat("duplicates_removed", removed)
432
+ if params.get("warn", False):
433
+ ctx.report.add_warning(f"dedupe 移除 {removed} 行重复(strategy={strategy})")
434
+ return result
435
+
436
+
437
+ @middleware(order=90)
438
+ def output(df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]) -> pd.DataFrame:
439
+ """按契约 output 选列;required 缺失报错,非 required 补空。"""
440
+ output_fields = ctx.contract.output
441
+ missing_def = [f for f in output_fields if f not in ctx.contract.fields]
442
+ if missing_def:
443
+ raise CleanerConfigError(f"output 字段未在 fields 中定义: {missing_def}")
444
+
445
+ warn_on_missing = bool(params.get("warn_on_missing", False))
446
+ for field in output_fields:
447
+ if field in df.columns:
448
+ continue
449
+ if ctx.contract.is_required(field):
450
+ raise CleanerConfigError(f"required 列缺失: {field}")
451
+ df[field] = None
452
+ if warn_on_missing:
453
+ ctx.report.add_warning(f"非 required 列缺失,已补空: {field}")
454
+ return df[list(output_fields)]
455
+
456
+
457
+ @middleware(order=95)
458
+ def sort(df: pd.DataFrame, ctx: CleanContext, params: Mapping[str, Any]) -> pd.DataFrame:
459
+ """按契约 sort 多字段排序。"""
460
+ specs = ctx.contract.sort
461
+ if not specs:
462
+ return df
463
+ fields = [s.field for s in specs if s.field in df.columns]
464
+ if not fields:
465
+ return df
466
+ ascending = [s.direction == "ascending" for s in specs if s.field in df.columns]
467
+ return df.sort_values(fields, ascending=ascending).reset_index(drop=True)
468
+
469
+
470
+ BUILTIN_FNS = (
471
+ field_mapping,
472
+ value_mapping,
473
+ field_transform,
474
+ type_conversion,
475
+ fill,
476
+ formula_compute,
477
+ formula_validate,
478
+ consistency,
479
+ type_validate,
480
+ dedupe,
481
+ output,
482
+ sort,
483
+ )
484
+
485
+
486
+ __all__ = [
487
+ "BUILTIN_FNS",
488
+ "DEFAULT_ACTIONS",
489
+ "field_mapping",
490
+ "value_mapping",
491
+ "field_transform",
492
+ "type_conversion",
493
+ "fill",
494
+ "formula_compute",
495
+ "formula_validate",
496
+ "consistency",
497
+ "type_validate",
498
+ "dedupe",
499
+ "output",
500
+ "sort",
501
+ ]