raw_scan.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""输入数据自动扫描识别 —— 发现 `<安装目录>/data/raw` 下的**新增/变化**,并给出"该重跑哪几步"。
  4. ## 为什么要有它(用户令 2026-09-19)
  5. 用户令:「对 `<安装目录>/data/raw` 目录下的接入数据处理,增加自动扫描识别机制,以能发现新增数据,并纳入重算。」
  6. 在此之前,"放了新数据要不要重算"全靠人记:`place_raw_data.py` 只管把现场包落位,`raw_data_check.py`
  7. 只管结构与命名对不对,`rebuild_all.py` 无脑全跑(或按人给的 `--skip-*` 跳过)——
  8. **没有任何一处回答"这回新来了什么、因此必须重跑哪几步"**。本脚本补这一环:
  9. 逐族指纹 (件数/体积/最新时间/清单摘要) → 与上次快照比 → 报【新增/变化】 → 映射到链上步骤
  10. ## 三档用法
  11. python scripts/raw_scan.py # 只报当前状态(不写快照)
  12. python scripts/raw_scan.py --write # 写/更新快照 outputs/<场>/_raw_scan.json
  13. python scripts/raw_scan.py --check # 与快照比: rc=0 无变化 · rc=4 有新增/变化 · rc=5 没有快照
  14. python scripts/raw_scan.py --check --write # 比完就把新快照记下(重算链第 ①b 步就是这条)
  15. python scripts/raw_scan.py --plan # 只打印"有变化时该跑哪些步"
  16. python scripts/raw_scan.py --json # 机器可读(rebuild_all 用它做"跳过了该跑的步"提醒)
  17. python scripts/raw_scan.py --deep # 变化判定加上**内容**哈希(默认只比 名字/大小/时间)
  18. python scripts/raw_scan.py --root <别的 raw> # 换个根扫(自测/多场)
  19. python scripts/raw_scan.py --selftest # 族表覆盖自检(与族表/链上步骤对账,防两处漂移)
  20. ## 口径与纪律
  21. · **指纹**默认 = 每族逐件 `相对路径|字节数|mtime(ns)` 排序后串起来取 sha1 —— 快、且"加了一件/改了一件/
  22. 删了一件"都会变;`--deep` 再叠一层内容 sha1(小文件才做,避免拿 153 GB 的 CMS 导出拼哈希)。
  23. · **未归类**:`data/raw/<场>/` 下出现族表里没有的子目录(新来的数据总会有第一次)→ 如实列进
  24. `unclassified` 并给出"没有消费者/需要认领"的话,**不猜**它是哪一族。
  25. · 这里只**发现与建议**,不改数据、不搬文件、不自动重算(要不要跑由 `rebuild_all.py` 或运维决定;
  26. 自动重算的开关见 `configs/serve.json` 的 `raw_watch`)。rc=4 是"有变化",不是失败。
  27. """
  28. from __future__ import annotations
  29. import argparse
  30. import hashlib
  31. import json
  32. import os
  33. import pathlib
  34. import sys
  35. import time
  36. ROOT = pathlib.Path(__file__).resolve().parents[1]
  37. sys.path.insert(0, str(ROOT))
  38. try: # GBK 控制台/日志重定向不再因 '²' 这类字符抛 UnicodeEncodeError
  39. sys.stdout.reconfigure(errors='replace')
  40. except Exception:
  41. pass
  42. SNAP_NAME = '_raw_scan.json'
  43. # ── 族表:raw 子目录 → (计件 glob, 链上步骤, 消费者说明) ──────────────────────────────
  44. # ★步骤标签与 `scripts/rebuild_all.py` 的计划名一一对应(人看到"③ SCADA 侧"就知道去跑哪一步)。
  45. FAMILIES: tuple[tuple[str, tuple[str, ...], tuple[str, ...], str], ...] = (
  46. ('故障报警', ('*.xls', '*.xlsx', '*.csv'), ('② 三门台账',),
  47. '报警事件导出 → windscada/alarms.parquet(报警集中/停机账)。缺 TimeOn/Alarmcode 的统计报表件会被摄入器跳过'),
  48. ('风机故障记录', ('*.xls', '*.xlsx', '*.csv'), ('② 三门台账',),
  49. '检修工单台账 → windscada/workorders.parquet(重复检修/停机损失)'),
  50. ('油样报告', ('*.pdf',), ('② 三门台账',),
  51. '油液化验报告 → windscada/oil_samples_index.parquet(油液面)'),
  52. ('scada_10min', ('*.csv',), ('③ SCADA 侧 10 个构建器', '④ 月度派生件', '④c 变桨面', '⑤b 事实契约 claim'),
  53. '10min 导出 → 功率曲线/损失/温度/停机/偏航/液压等 + 变桨面日粒度(温度/性能/变桨面)'),
  54. ('scada_1min', ('*.csv',), ('④c 变桨面',),
  55. '1min 导出(内部台号 01E…38B)→ 变桨面零位三口径与越线计数'),
  56. ('scada_mdb', ('*.mdb', '*.zip'), ('③ SCADA 侧 10 个构建器', '④ 月度派生件', '④c 变桨面'),
  57. '现场年度归档 Access 库(按月的 10min/1min)—— CSV 缺失时由 scada_source 回落到它'),
  58. ('windcms', ('*_decode.json',), ('④b 振动侧摄入 + CMS 报告 + 标量 z', '④d 振动在升/换件闭环', '④e 三层基线'),
  59. 'Brande TCM 导出 → 窗索引/谱库/CMS 报告/逐台页 + 在升闭环 + 三层基线(振动面)'),
  60. ('m5_cms_tcm', ('*.json', '*.docx', '*.pdf', '*.md'), ('④b 振动侧摄入 + CMS 报告 + 标量 z',),
  61. '现场给的正本(handoff_vibration_v2.json / component_history.json)与厂家报告——正本在位时优先于观澜自算'),
  62. )
  63. # 机理层资料不在场站目录下(A2 约定): data/raw/西门子4.0技术资料
  64. TECH_DIR, TECH_PATTERNS = '西门子4.0技术资料', ('*.xlsx', '*.xls', '*.pdf', '*.docx', '*.doc', '*.txt', '*.csv')
  65. TECH_STEPS = ('⑦ 本体: 码表/手册/文档',)
  66. TECH_NOTE = '厂商技术资料(故障处理手册/维护 WI/图纸/对译表)→ 本体对象库/检索索引/实机参数表'
  67. def _digest(entries: list[tuple[str, int, int]], deep: bool, base: pathlib.Path, files: list[pathlib.Path],
  68. deep_max: int) -> str:
  69. h = hashlib.sha1()
  70. for rel, size, mt in entries:
  71. h.update(f'{rel}|{size}|{mt}\n'.encode('utf-8', 'replace'))
  72. if deep:
  73. for p, (rel, size, _mt) in zip(files, entries):
  74. if size > deep_max:
  75. continue
  76. try:
  77. fh = hashlib.sha1()
  78. with open(p, 'rb') as f:
  79. for blk in iter(lambda: f.read(1 << 20), b''):
  80. fh.update(blk)
  81. h.update(rel.encode('utf-8', 'replace') + b'=' + fh.digest())
  82. except OSError:
  83. pass
  84. return h.hexdigest()
  85. def fingerprint(d: pathlib.Path, patterns: tuple[str, ...], deep: bool = False, deep_max: int = 8 << 20) -> dict:
  86. """一族目录的指纹:件数/体积/最新时间/清单摘要(--deep 再叠内容哈希)。目录不在 ⇒ files=0。"""
  87. files: list[pathlib.Path] = []
  88. if d.is_dir():
  89. for pat in patterns:
  90. files += [p for p in d.rglob(pat) if p.is_file()]
  91. files = sorted(set(files))
  92. entries: list[tuple[str, int, int]] = []
  93. for p in files:
  94. try:
  95. st = p.stat()
  96. except OSError:
  97. continue
  98. entries.append((p.relative_to(d).as_posix(), st.st_size, st.st_mtime_ns))
  99. entries.sort()
  100. newest = ''
  101. if entries:
  102. newest = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(max(e[2] for e in entries) / 1e9))
  103. return dict(files=len(entries), bytes=sum(e[1] for e in entries), newest=newest,
  104. digest=_digest(entries, deep, d, files, deep_max),
  105. top=[e[0] for e in sorted(entries, key=lambda x: -x[2])[:3]])
  106. def scan(raw_root: pathlib.Path, deep: bool = False, station_dir: pathlib.Path | None = None) -> dict:
  107. """扫一个 raw 根:逐族指纹 + 别处不认识的子目录(未归类)。
  108. `station_dir` 不给时按**场配置的辨识结果**定场站目录(`raw_station_dir()`,与摄入侧同一口径);
  109. 显式 `--root` 自测时可传入 `<root>/<场站名>` 之外的位置。
  110. """
  111. from src.windscada.config import raw_station_dir
  112. station = pathlib.Path(station_dir) if station_dir else raw_station_dir()
  113. fam: dict[str, dict] = {}
  114. for name, pats, steps, note in FAMILIES:
  115. fp = fingerprint(station / name, pats, deep)
  116. fp.update(steps=list(steps), note=note, where=str((station / name)))
  117. fam[name] = fp
  118. fp = fingerprint(raw_root / TECH_DIR, TECH_PATTERNS, deep)
  119. fp.update(steps=list(TECH_STEPS), note=TECH_NOTE, where=str(raw_root / TECH_DIR))
  120. fam[TECH_DIR] = fp
  121. known = {n for n, *_ in FAMILIES} | {TECH_DIR}
  122. unclassified = []
  123. if station.is_dir():
  124. for sub in sorted(station.iterdir()):
  125. if sub.is_dir() and sub.name not in known:
  126. unclassified.append(dict(dir=sub.name, files=sum(1 for p in sub.rglob('*') if p.is_file())))
  127. for sub in sorted(raw_root.iterdir()) if raw_root.is_dir() else []:
  128. if sub.is_dir() and sub.name not in known and sub != station:
  129. unclassified.append(dict(dir=sub.name, files=sum(1 for p in sub.rglob('*') if p.is_file()),
  130. note='raw 根下(非场站目录)'))
  131. return dict(at=time.strftime('%Y-%m-%d %H:%M:%S'), root=str(raw_root), station=str(station),
  132. deep=deep, families=fam, unclassified=unclassified)
  133. def diff(old: dict, new: dict) -> list[dict]:
  134. """逐族比:新增/减少/内容变化(`files` 与 `digest` 分开说,便于人看懂)。"""
  135. out = []
  136. of = (old or {}).get('families') or {}
  137. for name, cur in (new.get('families') or {}).items():
  138. prev = of.get(name)
  139. if not prev:
  140. if cur['files']:
  141. out.append(dict(family=name, kind='首次记录', files=cur['files'], steps=cur['steps'],
  142. note=cur['note'], newest=cur['newest']))
  143. continue
  144. d_files = cur['files'] - prev['files']
  145. same_list = cur['digest'] == prev['digest']
  146. if d_files == 0 and same_list:
  147. continue
  148. kind = ('新增 %+d 件' % d_files) if d_files else '内容变化(件数不变)'
  149. out.append(dict(family=name, kind=kind, files=cur['files'], delta=d_files,
  150. bytes_delta=cur['bytes'] - prev['bytes'], newest=cur['newest'],
  151. top=cur.get('top'), steps=cur['steps'], note=cur['note']))
  152. for u in new.get('unclassified') or []:
  153. out.append(dict(family=u['dir'], kind='未归类(族表里没有这个目录)', files=u['files'],
  154. steps=[], note='没有已知消费者 ⇒ 先认领:是新的输入族就得给它配摄入器;否则清出 data/raw'))
  155. return out
  156. def _steps_of(changes: list[dict]) -> list[str]:
  157. seen, out = set(), []
  158. for c in changes:
  159. for s in c.get('steps') or []:
  160. if s not in seen:
  161. seen.add(s)
  162. out.append(s)
  163. return out
  164. def snap_path(raw_root: pathlib.Path) -> pathlib.Path:
  165. from src import paths as P
  166. return P.out_root() / SNAP_NAME
  167. def main() -> int:
  168. ap = argparse.ArgumentParser(description='输入数据自动扫描识别(发现新增 → 指明该重跑哪几步)')
  169. ap.add_argument('--farm', default=None)
  170. ap.add_argument('--root', default=None, help='覆盖 data/raw 根(自测/多场)')
  171. ap.add_argument('--write', action='store_true', help='把本次指纹写进快照')
  172. ap.add_argument('--check', action='store_true', help='与快照比:rc=0 无变化 · 4 有新增/变化 · 5 无快照')
  173. ap.add_argument('--plan', action='store_true', help='只打印"该跑哪些步"')
  174. ap.add_argument('--json', action='store_true', help='输出机器可读 JSON')
  175. ap.add_argument('--deep', action='store_true', help='变化判定叠内容哈希(小文件)')
  176. ap.add_argument('--selftest', action='store_true', help='族表/步骤覆盖自检(防与族表、链上步骤漂移)')
  177. a = ap.parse_args()
  178. from src import paths as P
  179. from src.windscada import config as C
  180. if a.farm:
  181. os.environ['WINDSCADA_FARM'] = a.farm # 与其它脚本同一口径(场由环境变量选)
  182. raw = pathlib.Path(a.root) if a.root else pathlib.Path(C.RAW_ROOT)
  183. # --root 换成别的 raw 根时,场站目录按"根下唯一/同名"识别,避免拿本场辨识结果去别处找
  184. st_dir = None
  185. if a.root:
  186. from src.windscada.config import station_scan
  187. sc = station_scan(root=raw)
  188. st_dir = (raw / sc['matched']) if sc.get('matched') else None
  189. now = scan(raw, deep=a.deep, station_dir=st_dir)
  190. sp = snap_path(raw)
  191. old = None
  192. if sp.is_file():
  193. try:
  194. old = json.loads(sp.read_text(encoding='utf-8'))
  195. except Exception:
  196. old = None
  197. changes = diff(old, now)
  198. if a.selftest:
  199. return selftest()
  200. if a.json:
  201. print(json.dumps(dict(scan=now, changes=changes, snapshot=str(sp),
  202. steps=_steps_of(changes), has_snapshot=bool(old)), ensure_ascii=False, indent=1))
  203. if a.write:
  204. sp.parent.mkdir(parents=True, exist_ok=True)
  205. sp.write_text(json.dumps(now, ensure_ascii=False, indent=1), encoding='utf-8')
  206. if a.check:
  207. return 0 if (old and not changes) else (4 if old else 5)
  208. return 0
  209. print(f'输入数据扫描 · {now["root"]} ({now["at"]}{" · deep" if a.deep else ""})')
  210. tot_f = sum(f['files'] for f in now['families'].values())
  211. tot_b = sum(f['bytes'] for f in now['families'].values())
  212. print(f' 共 {len(now["families"])} 族 · {tot_f} 件 · {tot_b / 1024 / 1024 / 1024:.1f} GB')
  213. for name, f in now['families'].items():
  214. flag = ''
  215. for c in changes:
  216. if c['family'] == name:
  217. flag = f" ← {c['kind']}"
  218. print(f' {name:16s} {f["files"]:6d} 件 {f["bytes"] / 1024 / 1024:9.1f} MB 最新 {f["newest"] or "—"}{flag}')
  219. if now['unclassified']:
  220. print(' 未归类(族表里没有,先认领):')
  221. for u in now['unclassified']:
  222. print(f' {u["dir"]:16s} {u["files"]:6d} 件 {u.get("note", "没有已知消费者")}')
  223. if changes:
  224. print(f'\n== 本次发现 {len(changes)} 处新增/变化 ==')
  225. for c in changes:
  226. print(f' · {c["family"]}: {c["kind"]}'
  227. + (f'(体积 {c["bytes_delta"] / 1024 / 1024:+.1f} MB)' if c.get('bytes_delta') else '')
  228. + f' 最新 {c.get("newest") or "—"}')
  229. if c.get('top'):
  230. print(f' 最近落盘: ' + '、'.join(c['top']))
  231. if c.get('steps'):
  232. print(f' 该跑: ' + ' / '.join(c['steps']))
  233. print('\n 建议: 跑一次重算把新数据纳入产物 —— python scripts/rebuild_all.py'
  234. '(默认全跑;若你用了 --skip-*,请确认没跳过上面列出的步)')
  235. else:
  236. print('\n== 与上次快照一致,没有新数据 ==' if old else '\n== 还没有快照(跑 --write 记一次基线)==')
  237. if a.write:
  238. sp.parent.mkdir(parents=True, exist_ok=True)
  239. sp.write_text(json.dumps(now, ensure_ascii=False, indent=1), encoding='utf-8')
  240. print(f'\n快照已更新 → {P.rel(sp)}')
  241. if a.check:
  242. if not old:
  243. print(f'[?] 没有快照可比({P.rel(sp)})—— 先跑 --write 记基线; rc=5')
  244. return 5
  245. return 4 if changes else 0
  246. return 0
  247. def selftest() -> int:
  248. """自检:① 族表覆盖 `products_reverse_audit.FAMILIES` 里所有 raw 输入目录 ② 步骤名都能在链上找到。"""
  249. import importlib.util
  250. import re
  251. spec = importlib.util.spec_from_file_location('_pra', ROOT / 'scripts' / 'products_reverse_audit.py')
  252. mod = importlib.util.module_from_spec(spec)
  253. spec.loader.exec_module(mod)
  254. inputs = {f['input'] for f in mod.FAMILIES if f.get('input')}
  255. mine = {n for n, *_ in FAMILIES} | {TECH_DIR}
  256. missing = sorted(inputs - mine)
  257. chain = (ROOT / 'scripts' / 'rebuild_all.py').read_text(encoding='utf-8')
  258. steps = {s for _n, _p, ss, _note in FAMILIES for s in ss} | set(TECH_STEPS)
  259. bad_steps = sorted(s for s in steps if s.split()[0] not in chain)
  260. print(f'族表覆盖: 反向呼应族表的 raw 输入 {len(inputs)} 个 · 本器覆盖 {len(mine)} 个 · 缺 {missing or "无"}')
  261. print(f'步骤标签: {len(steps)} 个 · 在 rebuild_all 里找不到的 {bad_steps or "无"}')
  262. ok = not missing and not bad_steps
  263. print('[OK] 自检通过' if ok else '[X] 自检不过 —— 族表或步骤标签与链上漂移了')
  264. return 0 if ok else 5
  265. if __name__ == '__main__':
  266. sys.exit(main())