raw_scan.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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技术资料', ('*',) # 该族的消费者(kb_ingest)读整棵树 ⇒ 白名单就是"全部"
  65. TECH_STEPS = ('⑦ 本体: 码表/手册/文档',)
  66. TECH_NOTE = '厂商技术资料(故障处理手册/维护 WI/图纸/对译表)→ 本体对象库/检索索引/实机参数表'
  67. # raw 根下**随包发的说明件**(不是数据): 别把它们报成"未归类"。口径: 只有名字在白名单里且不参与摄入。
  68. IGNORE_FILES = {'README_把原始数据放这里.txt'}
  69. def _digest(entries: list[tuple[str, int, int]], deep: bool, base: pathlib.Path, files: list[pathlib.Path],
  70. deep_max: int, dirs: list[str] | None = None) -> str:
  71. h = hashlib.sha1()
  72. for rel, size, mt in entries:
  73. h.update(f'{rel}|{size}|{mt}\n'.encode('utf-8', 'replace'))
  74. for d in dirs or []: # 子目录清单也进指纹: "新建了空目录(数据还没落)"也能发现
  75. h.update(f'D:{d}\n'.encode('utf-8', 'replace'))
  76. if deep:
  77. for p, (rel, size, _mt) in zip(files, entries):
  78. if size > deep_max:
  79. continue
  80. try:
  81. fh = hashlib.sha1()
  82. with open(p, 'rb') as f:
  83. for blk in iter(lambda: f.read(1 << 20), b''):
  84. fh.update(blk)
  85. h.update(rel.encode('utf-8', 'replace') + b'=' + fh.digest())
  86. except OSError:
  87. pass
  88. return h.hexdigest()
  89. def fingerprint(d: pathlib.Path, patterns: tuple[str, ...], deep: bool = False, deep_max: int = 8 << 20) -> dict:
  90. """一族目录的指纹。
  91. ★口径 (用户令 2026-09-19/20「对 data/raw 目录(含嵌套子目录)下,文件的增减做到监听」):
  92. · **递归**统计该族目录下**全部文件**(不限扩展名) —— 只按摄入白名单(patterns)统计的话,
  93. 往族目录里丢一个 `.zip`/`.txt` 就"看不见"了, 那不算监听; 白名单命中的另记 `matched`
  94. (才是真进摄入的件数), 差额用 `unmatched` 列出来给人看;
  95. · 指纹里**还含子目录清单**(只放路径名, 不放 mtime —— 目录 mtime 会随子文件变动而变, 那是噪声),
  96. 于是"新建了一个空目录(数据还没落进去)"也动指纹。
  97. """
  98. all_files: list[pathlib.Path] = []
  99. dirs: list[str] = []
  100. if d.is_dir():
  101. for p in d.rglob('*'):
  102. if p.is_file():
  103. all_files.append(p)
  104. elif p.is_dir():
  105. dirs.append(p.relative_to(d).as_posix())
  106. all_files = sorted(set(all_files))
  107. dirs.sort()
  108. matched: list[pathlib.Path] = []
  109. for pat in patterns:
  110. matched += [p for p in d.rglob(pat) if p.is_file()]
  111. mset = {p.relative_to(d).as_posix() for p in set(matched)}
  112. entries: list[tuple[str, int, int]] = []
  113. for p in all_files:
  114. try:
  115. st = p.stat()
  116. except OSError:
  117. continue
  118. entries.append((p.relative_to(d).as_posix(), st.st_size, st.st_mtime_ns))
  119. entries.sort()
  120. newest = ''
  121. if entries:
  122. newest = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(max(e[2] for e in entries) / 1e9))
  123. _unm = [e[0] for e in entries if e[0] not in mset]
  124. return dict(files=len(entries), bytes=sum(e[1] for e in entries), newest=newest,
  125. matched=len(mset), dirs=len(dirs), unmatched=_unm[:10], unmatched_n=len(_unm),
  126. digest=_digest(entries, deep, d, all_files, deep_max, dirs),
  127. top=[e[0] for e in sorted(entries, key=lambda x: -x[2])[:3]])
  128. def scan(raw_root: pathlib.Path, deep: bool = False, station_dir: pathlib.Path | None = None) -> dict:
  129. """扫一个 raw 根:逐族指纹 + 别处不认识的子目录(未归类)。
  130. `station_dir` 不给时按**场配置的辨识结果**定场站目录(`raw_station_dir()`,与摄入侧同一口径);
  131. 显式 `--root` 自测时可传入 `<root>/<场站名>` 之外的位置。
  132. """
  133. from src.windscada.config import raw_station_dir
  134. station = pathlib.Path(station_dir) if station_dir else raw_station_dir()
  135. fam: dict[str, dict] = {}
  136. for name, pats, steps, note in FAMILIES:
  137. fp = fingerprint(station / name, pats, deep)
  138. fp.update(steps=list(steps), note=note, where=str((station / name)))
  139. fam[name] = fp
  140. fp = fingerprint(raw_root / TECH_DIR, TECH_PATTERNS, deep)
  141. fp.update(steps=list(TECH_STEPS), note=TECH_NOTE, where=str(raw_root / TECH_DIR))
  142. fam[TECH_DIR] = fp
  143. known = {n for n, *_ in FAMILIES} | {TECH_DIR}
  144. unclassified = []
  145. known_dirs = {str(station / n) for n, *_ in FAMILIES} | {str(raw_root / TECH_DIR)}
  146. # ★未归类 = 任何**不在已知族目录里**的文件 (递归找, 不只看一层): raw 根下、场站目录下、以及
  147. # 场站目录里嵌套的新子目录(例如新来了 `CMS_202701` 这种整包目录) 都跑不掉。
  148. for p in (sorted(raw_root.rglob('*')) if raw_root.is_dir() else []):
  149. if not p.is_file():
  150. continue
  151. if any(str(p).startswith(k + os.sep) for k in known_dirs):
  152. continue
  153. if p.name in IGNORE_FILES:
  154. continue # 随包的放置说明件: 不是数据, 不报"未归类"
  155. rel = p.relative_to(raw_root).as_posix()
  156. unclassified.append(dict(dir=rel, files=1,
  157. note='不在任何已知族的目录里 —— 没有消费者; 是新的输入族就得给它配摄入器'))
  158. # 已知族目录内**白名单没命中**的文件: 能进摄入的才计数, 这些是"放了但没人读"的
  159. stray = []
  160. for name, fp in fam.items():
  161. if fp.get('unmatched_n'):
  162. stray.append(dict(family=name, n=fp['unmatched_n'], example=fp.get('unmatched')[:5]))
  163. # 场站目录下**新增的未知子目录**(整目录级; 其文件已在上面逐件登记, 这里给个汇总便于人读)
  164. extra_dirs = []
  165. if station.is_dir():
  166. for sub in sorted(station.iterdir()):
  167. if sub.is_dir() and sub.name not in known:
  168. extra_dirs.append(dict(dir=f'{station.name}/{sub.name}',
  169. files=sum(1 for p in sub.rglob('*') if p.is_file()),
  170. note='场站目录下的新子目录(族表里没有)'))
  171. return dict(at=time.strftime('%Y-%m-%d %H:%M:%S'), root=str(raw_root), station=str(station),
  172. deep=deep, families=fam, unclassified=unclassified + extra_dirs, stray_in_families=stray)
  173. def diff(old: dict, new: dict) -> list[dict]:
  174. """逐族比:新增/减少/内容变化(`files` 与 `digest` 分开说,便于人看懂)。"""
  175. out = []
  176. of = (old or {}).get('families') or {}
  177. for name, cur in (new.get('families') or {}).items():
  178. prev = of.get(name)
  179. if not prev:
  180. if cur['files']:
  181. out.append(dict(family=name, kind='首次记录', files=cur['files'], steps=cur['steps'],
  182. note=cur['note'], newest=cur['newest']))
  183. continue
  184. d_files = cur['files'] - prev['files']
  185. same_list = cur['digest'] == prev['digest']
  186. if d_files == 0 and same_list:
  187. continue
  188. kind = ('新增 %+d 件' % d_files) if d_files else '内容变化(件数不变)'
  189. _dd = cur.get('dirs', 0) - prev.get('dirs', 0)
  190. if d_files == 0 and _dd:
  191. kind = f'目录结构变化({_dd:+d} 个子目录)'
  192. out.append(dict(family=name, kind=kind, files=cur['files'], delta=d_files,
  193. bytes_delta=cur['bytes'] - prev['bytes'], newest=cur['newest'],
  194. top=cur.get('top'), steps=cur['steps'], note=cur['note'],
  195. matched=cur.get('matched'), unmatched_n=cur.get('unmatched_n', 0)))
  196. for u in new.get('unclassified') or []:
  197. out.append(dict(family=u['dir'], kind='未归类(不在任何已知族的目录里)', files=u['files'],
  198. steps=[], note=u.get('note') or '没有已知消费者 ⇒ 先认领'))
  199. # ★族内"白名单外"的件**不计入变化**(信息而已): 实测族目录里本来就有大量正常但不被摄入器读的东西
  200. # (故障记录里的 .rar/.jpg、windcms 厂家报告 PDF、技术资料里的厂商软件 .exe/.lp …)。
  201. # 它们增删本身已经反映在 files/dirs/digest 上 ⇒ 该报的变化照报, 这里不再重复判一次。
  202. return out
  203. def _steps_of(changes: list[dict]) -> list[str]:
  204. seen, out = set(), []
  205. for c in changes:
  206. for s in c.get('steps') or []:
  207. if s not in seen:
  208. seen.add(s)
  209. out.append(s)
  210. return out
  211. def snap_path(raw_root: pathlib.Path) -> pathlib.Path:
  212. from src import paths as P
  213. return P.out_root() / SNAP_NAME
  214. def main() -> int:
  215. ap = argparse.ArgumentParser(description='输入数据自动扫描识别(发现新增 → 指明该重跑哪几步)')
  216. ap.add_argument('--farm', default=None)
  217. ap.add_argument('--root', default=None, help='覆盖 data/raw 根(自测/多场)')
  218. ap.add_argument('--write', action='store_true', help='把本次指纹写进快照')
  219. ap.add_argument('--check', action='store_true', help='与快照比:rc=0 无变化 · 4 有新增/变化 · 5 无快照')
  220. ap.add_argument('--plan', action='store_true', help='只打印"该跑哪些步"')
  221. ap.add_argument('--json', action='store_true', help='输出机器可读 JSON')
  222. ap.add_argument('--deep', action='store_true', help='变化判定叠内容哈希(小文件)')
  223. ap.add_argument('--selftest', action='store_true', help='族表/步骤覆盖自检(防与族表、链上步骤漂移)')
  224. a = ap.parse_args()
  225. from src import paths as P
  226. from src.windscada import config as C
  227. if a.farm:
  228. os.environ['WINDSCADA_FARM'] = a.farm # 与其它脚本同一口径(场由环境变量选)
  229. raw = pathlib.Path(a.root) if a.root else pathlib.Path(C.RAW_ROOT)
  230. # --root 换成别的 raw 根时,场站目录按"根下唯一/同名"识别,避免拿本场辨识结果去别处找
  231. st_dir = None
  232. if a.root:
  233. from src.windscada.config import station_scan
  234. sc = station_scan(root=raw)
  235. st_dir = (raw / sc['matched']) if sc.get('matched') else None
  236. now = scan(raw, deep=a.deep, station_dir=st_dir)
  237. sp = snap_path(raw)
  238. old = None
  239. if sp.is_file():
  240. try:
  241. old = json.loads(sp.read_text(encoding='utf-8'))
  242. except Exception:
  243. old = None
  244. changes = diff(old, now)
  245. if a.selftest:
  246. return selftest()
  247. if a.json:
  248. print(json.dumps(dict(scan=now, changes=changes, snapshot=str(sp),
  249. steps=_steps_of(changes), has_snapshot=bool(old)), ensure_ascii=False, indent=1))
  250. if a.write:
  251. sp.parent.mkdir(parents=True, exist_ok=True)
  252. sp.write_text(json.dumps(now, ensure_ascii=False, indent=1), encoding='utf-8')
  253. if a.check:
  254. return 0 if (old and not changes) else (4 if old else 5)
  255. return 0
  256. print(f'输入数据扫描 · {now["root"]} ({now["at"]}{" · deep" if a.deep else ""})')
  257. tot_f = sum(f['files'] for f in now['families'].values())
  258. tot_b = sum(f['bytes'] for f in now['families'].values())
  259. print(f' 共 {len(now["families"])} 族 · {tot_f} 件 · {tot_b / 1024 / 1024 / 1024:.1f} GB')
  260. for name, f in now['families'].items():
  261. flag = ''
  262. for c in changes:
  263. if c['family'] == name:
  264. flag = f" ← {c['kind']}"
  265. print(f' {name:16s} {f["files"]:6d} 件 {f["bytes"] / 1024 / 1024:9.1f} MB 最新 {f["newest"] or "—"}{flag}')
  266. if now['unclassified']:
  267. print(' 未归类(族表里没有,先认领):')
  268. for u in now['unclassified']:
  269. print(f' {u["dir"]:16s} {u["files"]:6d} 件 {u.get("note", "没有已知消费者")}')
  270. if now.get('stray_in_families'):
  271. print(' (信息,不计入"变化")族目录里**摄入白名单没命中**的件 —— 摄入器不会读它们:')
  272. for s in now['stray_in_families']:
  273. print(f' {s["family"]:16s} {s["n"]:5d} 件 例: ' + '、'.join(s['example'][:3]))
  274. if changes:
  275. print(f'\n== 本次发现 {len(changes)} 处新增/变化 ==')
  276. for c in changes:
  277. print(f' · {c["family"]}: {c["kind"]}'
  278. + (f'(体积 {c["bytes_delta"] / 1024 / 1024:+.1f} MB)' if c.get('bytes_delta') else '')
  279. + f' 最新 {c.get("newest") or "—"}')
  280. if c.get('top'):
  281. print(f' 最近落盘: ' + '、'.join(c['top']))
  282. if c.get('steps'):
  283. print(f' 该跑: ' + ' / '.join(c['steps']))
  284. print('\n 建议: 跑一次重算把新数据纳入产物 —— python scripts/rebuild_all.py'
  285. '(默认全跑;若你用了 --skip-*,请确认没跳过上面列出的步)')
  286. else:
  287. print('\n== 与上次快照一致,没有新数据 ==' if old else '\n== 还没有快照(跑 --write 记一次基线)==')
  288. if a.write:
  289. sp.parent.mkdir(parents=True, exist_ok=True)
  290. sp.write_text(json.dumps(now, ensure_ascii=False, indent=1), encoding='utf-8')
  291. print(f'\n快照已更新 → {P.rel(sp)}')
  292. if a.check:
  293. if not old:
  294. print(f'[?] 没有快照可比({P.rel(sp)})—— 先跑 --write 记基线; rc=5')
  295. return 5
  296. return 4 if changes else 0
  297. return 0
  298. def selftest() -> int:
  299. """自检:① 族表覆盖 `products_reverse_audit.FAMILIES` 里所有 raw 输入目录 ② 步骤名都能在链上找到。"""
  300. import importlib.util
  301. import re
  302. spec = importlib.util.spec_from_file_location('_pra', ROOT / 'scripts' / 'products_reverse_audit.py')
  303. mod = importlib.util.module_from_spec(spec)
  304. spec.loader.exec_module(mod)
  305. inputs = {f['input'] for f in mod.FAMILIES if f.get('input')}
  306. mine = {n for n, *_ in FAMILIES} | {TECH_DIR}
  307. missing = sorted(inputs - mine)
  308. chain = (ROOT / 'scripts' / 'rebuild_all.py').read_text(encoding='utf-8')
  309. steps = {s for _n, _p, ss, _note in FAMILIES for s in ss} | set(TECH_STEPS)
  310. bad_steps = sorted(s for s in steps if s.split()[0] not in chain)
  311. print(f'族表覆盖: 反向呼应族表的 raw 输入 {len(inputs)} 个 · 本器覆盖 {len(mine)} 个 · 缺 {missing or "无"}')
  312. print(f'步骤标签: {len(steps)} 个 · 在 rebuild_all 里找不到的 {bad_steps or "无"}')
  313. ok = not missing and not bad_steps
  314. print('[OK] 自检通过' if ok else '[X] 自检不过 —— 族表或步骤标签与链上漂移了')
  315. return 0 if ok else 5
  316. if __name__ == '__main__':
  317. sys.exit(main())