raw_data_check.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""输入数据放置体检 + 增量放置指导 (2026-09-17 用户令 3)。
  4. 用户要的是两件事:
  5. ① **检查**放进去的输入数据(特别是**增量**放的)是否符合规则;
  6. ② 给出**放置指导**(该放哪、命名怎么写、放完跑什么)。
  7. ## 规则 (每条都能指到具体文件, 依据 = 数据目录约定 + 各摄入脚本的真实读法)
  8. R1 顶层只许 场站目录 / 共享资料(西门子4.0技术资料) / 说明文件(*.txt|*.md);
  9. 常见错误: 把 10 个 csv 直接解到 data/raw 根下, 或把整包 zip 丢在根上。
  10. R2 场站目录下只许约定子目录 (src/windscada/config.py::STATION_SUBDIRS);
  11. 常见错误: 解压时多套一层包名目录 (如 `10分钟数据/10分钟数据/WTG01.csv`)。
  12. R3 各源类的结构与命名:
  13. scada_10min/ scada_1min/ 平铺 `<机组>.csv`, 机组集合要与场配置一致
  14. 故障报警/ .xls/.xlsx/.xml, 不许多套层
  15. 风机故障记录/ 年目录 + .xls/.xlsx/.rar/.jpg
  16. 油样报告/ 两级 `台号/部件/*.pdf` (维护页按此分目录)
  17. windcms/ 含 CMS 原始导出: `*_decode.json` 或 `<包名>/measurement/**`
  18. m5_cms_tcm/ 含 handoff 正本 (handoff_vibration_v2.json / component_history.json) + 厂家报告/
  19. R4 可读性抽样: CSV 能按 utf-8/gbk 解出非空表头; TCM `*_decode.json` 能解析出场站/机组字段。
  20. (`--deep` 才做, 默认只查结构与命名, 免得在 GB 级目录上耗时)
  21. R5 **增量语义** (给了 --src 时): 逐件对比"源包会落到哪"与"现在有什么", 出三清单:
  22. 新增 / 相同(将跳过) / **冲突**(同名不同大小 ⇒ 会覆盖已摄入的数据, 必须人来定夺)。
  23. R6 时间空洞: scada_* 的文件名里若带年月, 检查是否缺月/重月 (数据层页面的时间轴会缺一段)。
  24. R7 体量提示: 单文件 > 2 GB、目录 > 60 GB、或混进 zip/rar (应先解压再放)。
  25. R8 放置指导: 按"新增了哪类源"给出该跑的重算命令 (台账/SCADA/振动/全量)。
  26. ## 退出码
  27. 0 合规(可能带提示) · 5 结构或命名违例 · 6 增量冲突(同名不同大小) · 7 缺源类/时间空洞 · 8 仅有提示
  28. ## 用法
  29. python scripts/raw_data_check.py # 体检现有 data/raw/<场站>
  30. python scripts/raw_data_check.py --deep # 加可读性抽样
  31. python scripts/raw_data_check.py --src <现场包目录> # 增量体检: 出新增/相同/冲突三清单
  32. python scripts/raw_data_check.py --src <现场包> --json
  33. python scripts/raw_data_check.py --write-doc # 把规则表与结论写进放置指导文档
  34. """
  35. from __future__ import annotations
  36. try:
  37. from app_common.app_common_guanlan.api import install_root as _install_root
  38. except ImportError: # 理论不可达;包结构异常时回退到按位置上跳
  39. from pathlib import Path as _P
  40. def _install_root(_f): return _P(_f).resolve().parents[3]
  41. import argparse
  42. import json
  43. import os
  44. import pathlib
  45. import re
  46. import sys
  47. import zipfile
  48. ROOT = _install_root(__file__) # 模块化后按标记找安装根(原 parents[1] 已不成立)
  49. sys.path.insert(0, str(ROOT))
  50. from src import paths as P # noqa: E402
  51. RC_OK, RC_STRUCT, RC_CLASH, RC_GAP, RC_NOTE = 0, 5, 6, 7, 8
  52. TOP_OK_DIRS = ('西门子4.0技术资料',) # data/raw 下与"场站目录"并列的共享资料
  53. TOP_OK_FILES = ('.txt', '.md', '.pdf') # 说明类文件
  54. ZIP_MOD = {'.zip', '.rar', '.7z', '.tar', '.gz', '.zst'}
  55. # Access 读写 .mdb 时留下的锁/临时文件 (不是源数据; 2026-09-19 实逮: MDB 重建期间 scada_mdb 下出现 .laccdb)
  56. ACCESS_TMP_SUFFIX = {".laccdb", ".ldb", ".tmp"}
  57. BIG_FILE = 2 * 1024 ** 3
  58. BIG_DIR = 60 * 1024 ** 3
  59. # 各类源的期望 (后缀集合, 说明) —— 与摄入脚本的真实读法一致 (见 place_raw_data.py 的映射表注释)
  60. EXPECT = {
  61. 'scada_10min': ({'.csv'}, '平铺 <机组>.csv (每台一个文件, 不许再套层)'),
  62. 'scada_1min': ({'.csv'}, '平铺 <机组>.csv'),
  63. '故障报警': ({'.xls', '.xlsx', '.xml'}, '年度/季度报警导出 (.xls) + XML 报警导出'),
  64. '风机故障记录': ({'.xls', '.xlsx', '.rar', '.jpg', '.png'}, '年目录 + 月度汇总表/现场照片'),
  65. '油样报告': ({'.pdf'}, '两级: <台号>/<部件>/*.pdf'),
  66. 'windcms': ({'.json', '.pdf', '.docx'}, 'CMS 原始导出 *_decode.json(可套 <包名>/measurement/ 层) + 厂家报告/'),
  67. 'm5_cms_tcm': ({'.json', '.docx', '.pdf', '.md'}, 'handoff 正本 + 厂家报告/'),
  68. # 2026-09-17 用户令: 现场交来的年度 MDB 归档(25年.zip / 26年.zip)就地放在这里 —— 它就是
  69. # 原始收资(Access 按月分类),取代此前的"已导出 CSV"两个 zip(10分钟数据.zip / 1分钟数据.zip)。
  70. # 允许 .zip(原样归档)+ .mdb(已解出时);解出的目录层次 `<年>/<月>/` 由 R2 的子目录规则放行。
  71. 'scada_mdb': ({'.zip', '.mdb'}, '年度归档 <年>年.zip(内层 <年>/<月>/<年-月-类>.zip → .mdb)'),
  72. }
  73. DATE_RE = re.compile(r'(20\d{2})[-_年]?(0[1-9]|1[0-2])')
  74. def station_dir(farm: str | None = None) -> pathlib.Path:
  75. """当前场的原始件目录: data/raw/<场站目录名>。"""
  76. from src.windscada import config as C
  77. try:
  78. d = C.raw_station_dir(farm)
  79. except BaseException:
  80. d = P.RAW_ROOT / (farm or P.farm())
  81. return pathlib.Path(d)
  82. def sizes_map(base: pathlib.Path) -> dict:
  83. """{相对路径: 字节数} —— 只算文件。"""
  84. out = {}
  85. if base.is_dir():
  86. for f in base.rglob('*'):
  87. if f.is_file():
  88. out[f.relative_to(base).as_posix()] = f.stat().st_size
  89. return out
  90. def check_tree(st: pathlib.Path, deep=False) -> tuple[list, list, dict]:
  91. """规则体检 → (问题列表[(level, 项, 说明, rc)], 提示列表, 统计)。"""
  92. res, notes = [], []
  93. stat = dict(exists=st.is_dir(), files=0, bytes=0, subdirs={}, units=[])
  94. # R1 data/raw 顶层
  95. if P.RAW_ROOT.is_dir():
  96. for p in sorted(P.RAW_ROOT.iterdir()):
  97. if p.is_dir():
  98. if p.name != st.name and p.name not in TOP_OK_DIRS:
  99. res.append(('!', f'data/raw/{p.name}', f'顶层目录未在约定内 (场站目录应为 {st.name}/; '
  100. f'共享资料放 {TOP_OK_DIRS})', RC_STRUCT))
  101. elif p.suffix.lower() not in TOP_OK_FILES:
  102. res.append(('!', f'data/raw/{p.name}', 'data/raw 顶层只放场站目录与说明文件; '
  103. '源件要放进 <场站>/<源类>/', RC_STRUCT))
  104. if not st.is_dir():
  105. notes.append(('i', f'{P.rel(st)}', '尚未放置输入数据 —— 页面会显示"无产物/无数据" (属预期); '
  106. '放置见 docs/输入数据放置指导_v0.1.md', RC_OK))
  107. return res, notes, stat
  108. # R2 场站内子目录 + R3 各源类
  109. from src.windscada import config as C
  110. allowed = set(C.STATION_SUBDIRS)
  111. for d in sorted(st.iterdir()):
  112. if d.is_file():
  113. if d.suffix.lower() in ZIP_MOD:
  114. res.append(('!', P.rel(d), '压缩包直接放在场站目录下 —— 先解压再按源类落位', RC_NOTE))
  115. else:
  116. notes.append(('i', P.rel(d), '场站目录下的散装文件 (多半是现场随手拷的; 建议归入对应源类子目录)', RC_OK))
  117. continue
  118. if d.name not in allowed:
  119. res.append(('!', f'{P.rel(d)}', f'未约定的子目录 (约定: {sorted(allowed)})'
  120. ' —— 常见成因: 解压时多套了一层包名', RC_STRUCT))
  121. continue
  122. files = [f for f in d.rglob('*') if f.is_file()]
  123. nbytes = sum(f.stat().st_size for f in files)
  124. stat['subdirs'][d.name] = dict(files=len(files), bytes=nbytes)
  125. stat['files'] += len(files)
  126. stat['bytes'] += nbytes
  127. exts, bad = {}, []
  128. for f in files:
  129. e = f.suffix.lower()
  130. exts[e] = exts.get(e, 0) + 1
  131. want = EXPECT.get(d.name, (None, ''))[0]
  132. # ★2026-09-19: Access 的**锁文件/临时文件**(.laccdb/.ldb/~$*) 不是源数据 ——
  133. # 读/写 .mdb 时 Access 会在同目录留下它(实测: MDB 重建期间 scada_mdb 下出现 .laccdb),
  134. # 按"后缀不在约定内"报结构问题会把人引到错的地方。忽略并如实注明。
  135. if e in ACCESS_TMP_SUFFIX or f.name.startswith('~$'):
  136. notes.append(('i', P.rel(f), 'Access 锁/临时文件 (读写 .mdb 时产生), 不算源件', RC_OK))
  137. continue
  138. if want and e not in want and e not in ZIP_MOD:
  139. bad.append(f)
  140. if bad:
  141. sample = ', '.join(sorted({f.suffix.lower() for f in bad})[:4])
  142. res.append(('!', P.rel(d), f'{len(bad)} 个文件后缀不在该源类的约定内 ({sample}); '
  143. f'约定: {sorted(EXPECT[d.name][0])}', RC_STRUCT))
  144. if not files:
  145. notes.append(('i', P.rel(d), '目录是空的 (放了数据才有用)', RC_OK))
  146. # 各类专项
  147. if d.name in ('scada_10min', 'scada_1min'):
  148. names = {f.name for f in files}
  149. nested = [f for f in files if len(f.relative_to(d).parts) > 1]
  150. if nested:
  151. res.append(('!', P.rel(d), f'{len(nested)} 个文件在子目录里 —— 摄入按 <源类>/<机组>.csv 平铺读, '
  152. f'多一层就读不到', RC_STRUCT))
  153. try:
  154. want = set(C.farm(None)['turbines'])
  155. n_want = len(want)
  156. except BaseException:
  157. want, n_want = set(), 0
  158. got = {f.stem for f in files if f.parent == d}
  159. # ★ 两类命名都对: scada_10min 用显示机组号 (WTG01.csv); scada_1min 的现场导出用的是
  160. # **内部台号** (01E.csv…37B.csv, 见 place_raw_data.py 的映射说明) —— 后者按"台数一致"判完整,
  161. # 不再按名字判 (2026-09-17 实测: 按 WTG 名字判会把 38/38 齐全的 1min 目录误报成"缺 38 台")。
  162. # ★2026-09-20 用户令「把新月份的 10min 件吃进来」: 同台**补充件**(`WTG01-B2.csv`)现在由
  163. # 取数层一并读入(按列名对齐 + 时间戳去重)⇒ 台号判定要按"主件名"归一, 否则 38 个补充件
  164. # 会被报成"文件名不是本场机组"(假告警), 而它们恰恰是要吃的数据。
  165. if d.name == 'scada_10min':
  166. stem_of = lambda s: s.split('-')[0].split('_')[0] # noqa: E731 WTG01-B2 → WTG01
  167. got_main = {stem_of(s) for s in got}
  168. extra_main = sorted({s for s in got if stem_of(s) not in want} if want else set())
  169. miss = sorted(want - got_main) if want else []
  170. sup = sorted(s for s in got if s != stem_of(s))
  171. stat['units'].append((d.name, len(got_main)))
  172. if miss:
  173. res.append(('!', P.rel(d), f'缺 {len(miss)} 台机组的数据: {miss[:6]}'
  174. f'{" …" if len(miss) > 6 else ""} (页面按台取数, 缺台就是空白)', RC_GAP))
  175. if extra_main:
  176. res.append(('!', P.rel(d), f'{len(extra_main)} 个文件名不是本场机组: {extra_main[:6]}', RC_STRUCT))
  177. if sup:
  178. res.append(('i', P.rel(d), f'{len(sup)} 个同台补充件将被一并读入'
  179. f'(<台号>-*.csv, 如 {sup[:3]}): 按列名对齐 + 时间戳去重, 主件优先', 0))
  180. else:
  181. stat['units'].append((d.name, len(got)))
  182. if n_want and len(got) != n_want:
  183. res.append(('!', P.rel(d), f'台数不符: 现有 {len(got)} 个 <台号>.csv, 场配置是 {n_want} 台'
  184. f' (1min 导出用内部台号 01E/37B 这类, 按台数判完整)', RC_GAP))
  185. # R6 时间空洞 (文件名带年月时才判)
  186. months = sorted({m.group(0) for m in (DATE_RE.search(f.stem) for f in files) if m})
  187. if months:
  188. stat['months'] = months
  189. if d.name == '油样报告':
  190. flat = [f for f in files if len(f.relative_to(d).parts) < 2]
  191. if flat:
  192. res.append(('!', P.rel(d), f'{len(flat)} 个 PDF 直接躺在源类目录下 —— 约定是 <台号>/<部件>/*.pdf '
  193. f'(维护页按此分组)', RC_STRUCT))
  194. if d.name == 'windcms':
  195. js = [f for f in files if f.suffix.lower() == '.json']
  196. dec = [f for f in js if f.name.endswith('_decode.json')] # TCM 导出本体
  197. if not dec:
  198. res.append(('!', P.rel(d), '没有 *_decode.json (CMS 原始导出) —— 振动侧就没有可重算的源件', RC_GAP))
  199. if deep and dec:
  200. # 抽样核对"摄入脚本真正要的结构" —— 依据 scripts/rudong_tcm_index.py:
  201. # doc['body']['body'][<ISO时间戳>] = [ {Record: {...}}, … ], 机组取 Record.Location / Record.LocationName
  202. # (顶层还有 method/controller/buildId 等信封字段, 别拿它们当判据 —— 2026-09-17 实测踩过这个坑)
  203. import random as _rnd
  204. _rnd.seed(0)
  205. sample = _rnd.sample(dec, min(12, len(dec)))
  206. ok_n, bad_n, shapes = 0, 0, {}
  207. for f in sample:
  208. try:
  209. o = json.loads(f.read_text(encoding='utf-8', errors='replace'))
  210. body = ((o or {}).get('body') or {}).get('body') if isinstance(o, dict) else None
  211. if not isinstance(body, dict) or not body:
  212. shapes[str(sorted(o)[:4]) if isinstance(o, dict) else type(o).__name__] = \
  213. shapes.get(str(sorted(o)[:4]) if isinstance(o, dict) else type(o).__name__, 0) + 1
  214. bad_n += 1
  215. continue
  216. recs = next((v for v in body.values() if isinstance(v, list) and v), None)
  217. keys = sorted((recs[0] or {}).get('Record', {}) or {}) if recs else []
  218. if recs and (('Location' in keys) or ('LocationName' in keys)):
  219. ok_n += 1
  220. else:
  221. shapes[f'Record 缺 Location/LocationName: {keys[:6]}'] = \
  222. shapes.get(f'Record 缺 Location/LocationName: {keys[:6]}', 0) + 1
  223. bad_n += 1
  224. except Exception as e:
  225. shapes[f'解析失败 {type(e).__name__}'] = shapes.get(f'解析失败 {type(e).__name__}', 0) + 1
  226. bad_n += 1
  227. stat['tcm_sample'] = dict(ok=ok_n, bad=bad_n, shapes=shapes)
  228. if bad_n:
  229. res.append(('!', P.rel(d), f'TCM 抽样 {len(sample)} 件里 {bad_n} 件结构对不上摄入脚本的取法 '
  230. f'(body.body[时间戳]=[{{Record:…}}], 机组取 Record.Location/LocationName): '
  231. f'{list(shapes.items())[:3]}', RC_STRUCT))
  232. else:
  233. stat['tcm_ok'] = True
  234. if d.name == 'm5_cms_tcm':
  235. hand = [f for f in files if f.name in ('handoff_vibration_v2.json', 'component_history.json')]
  236. if not hand:
  237. notes.append(('i', P.rel(d), '缺 handoff 正本 (handoff_vibration_v2.json / component_history.json) —— '
  238. '融合面判级与 /cms/ 只能用随包快照 (docs §7 的已知缺口)', RC_OK))
  239. # R4 可读性抽样 (CSV 编码/表头)
  240. if deep:
  241. for name in ('scada_10min', 'scada_1min'):
  242. d = st / name
  243. if d.is_dir():
  244. f = next(iter(sorted(x for x in d.glob('*.csv'))), None)
  245. if f:
  246. head = None
  247. for enc in ('utf-8-sig', 'gbk'):
  248. try:
  249. with f.open(encoding=enc, errors='strict') as fh:
  250. head = fh.readline().strip()
  251. stat[f'{name}_enc'] = enc
  252. break
  253. except Exception:
  254. continue
  255. if not head:
  256. res.append(('!', P.rel(f), 'CSV 表头读不出来 (utf-8/gbk 都不行)', RC_STRUCT))
  257. elif len(head.split(',')) < 5:
  258. res.append(('!', P.rel(f), f'表头列数异常 ({len(head.split(","))} 列): {head[:60]}', RC_STRUCT))
  259. # R7 体量
  260. if stat['bytes'] > BIG_DIR:
  261. notes.append(('?', P.rel(st), f'源件合计 {stat["bytes"]/2**30:.1f} GB —— 摄入与重算会很慢, 建议分批', RC_NOTE))
  262. return res, notes, stat
  263. def increment_findings(plan: dict, src_name: str = '') -> list:
  264. """把增量三清单里的**冲突**变成一条可拦人的问题 (供本模块与 place_raw_data 共用)。"""
  265. out = []
  266. if plan.get('clash'):
  267. c = plan['clash'][0]
  268. out.append(('!', f'--src {src_name}'.strip(), f'{len(plan["clash"])} 件**同名不同大小**: 直接放会覆盖已摄入的源件 '
  269. f'(示例 {c["path"]}: 现有 {c.get("now", 0):,} B → 源包 '
  270. f'{c["size"]:,} B) —— 先确认哪一份是对的, 再决定 --force 覆盖还是改名并存',
  271. RC_CLASH))
  272. return out
  273. def increment_src(src: pathlib.Path, st: pathlib.Path) -> tuple[list, dict]:
  274. """R5 增量三清单: 遍历源包 zip 成员/散件, 算出它们会落到哪, 与现有树对比。"""
  275. res, plan = [], dict(new=[], same=[], clash=[], unmapped=[])
  276. import importlib.util
  277. spec = importlib.util.spec_from_file_location('_place', ROOT / 'scripts' / 'place_raw_data.py')
  278. place = importlib.util.module_from_spec(spec)
  279. try:
  280. spec.loader.exec_module(place)
  281. except SystemExit:
  282. pass
  283. rules = list(getattr(place, 'RULES', [])) + list(getattr(place, 'RULES_MECH', [])) + list(getattr(place, 'RULES_VIB', []))
  284. loose = list(getattr(place, 'RULES_VIB_LOOSE', []))
  285. have = sizes_map(st)
  286. have_root = sizes_map(P.RAW_ROOT)
  287. def classify(rel_path: str, size: int, base: pathlib.Path):
  288. target = base / rel_path
  289. cur = have.get(rel_path) if base == st else have_root.get(rel_path)
  290. item = dict(path=rel_path, size=size)
  291. if cur is None:
  292. plan['new'].append(item)
  293. elif cur == size:
  294. plan['same'].append(item)
  295. else:
  296. item['now'] = cur
  297. plan['clash'].append(item)
  298. for zname, prefix, target, strip, root_kind in rules:
  299. zp = src / zname if src.is_dir() else None
  300. if not zp or not zp.is_file():
  301. continue
  302. base = st if root_kind == 'station' else P.RAW_ROOT
  303. try:
  304. with zipfile.ZipFile(zp) as z:
  305. for info in z.infolist():
  306. if info.is_dir():
  307. continue
  308. nm = place.gbk_name(info)
  309. if prefix and not nm.startswith(prefix):
  310. continue
  311. tail = nm[len(prefix):] if prefix else nm
  312. if strip:
  313. tail = tail.split('/', 1)[1] if '/' in tail else tail
  314. rel = f'{target}/{tail}'
  315. if prefix and nm == prefix.rstrip('/'):
  316. continue
  317. classify(rel, info.file_size, base)
  318. except zipfile.BadZipFile:
  319. res.append(('!', zp.name, '不是合法 zip (现场包常被截断; 重新拷一份)', RC_STRUCT))
  320. for fn, target in loose:
  321. fp = src / fn
  322. if fp.is_file():
  323. classify(f'{target}/{fn}', fp.stat().st_size, st)
  324. return res, plan
  325. def guidance(plan: dict, stat: dict) -> list[str]:
  326. """R8 放置指导: 按新增源类给出该跑的重算命令与预期变化。"""
  327. out = []
  328. new = [x['path'] for x in plan.get('new', [])]
  329. kinds = {p.split('/', 1)[0] for p in new}
  330. if not new:
  331. out.append('没有新增源件: 不必重算 (若刚换过数据, 用 scripts/rebuild_all.py --dry-run 看计划)')
  332. return out
  333. out.append(f'新增 {len(new)} 件, 涉及源类: {sorted(kinds)}')
  334. if 'scada_10min' in kinds or 'scada_1min' in kinds:
  335. out.append('· SCADA 侧变了 → `python scripts/rebuild_all.py` (含 10 个构建器, 约 15 分钟); '
  336. '台账/报警/油样一起换时同一条命令即可')
  337. if kinds & {'故障报警', '风机故障记录', '油样报告'}:
  338. out.append('· 台账类变了 → `python scripts/rebuild_all.py --skip-scada` (约 2 分钟)')
  339. if kinds & {'windcms', 'm5_cms_tcm'}:
  340. out.append('· 振动侧变了 → 重算链第 ④b 步会自动摄入 (`scripts/vib_raw_build.py`); '
  341. '注意它只做索引/谱, 不会重生成报告 (本包缺六层链, 见 docs §7)')
  342. out.append('· 放完先自检: `python scripts/raw_data_check.py --deep` → 再看 `/detail/` 左栏「系统维护」两屏')
  343. out.append('· 重算后核对锚点: 报警 39211 · 工单 5876 · 油样 404 · temp_monthly 19494 · 本体 9702 对象')
  344. return out
  345. def main() -> int:
  346. ap = argparse.ArgumentParser()
  347. ap.add_argument('--farm', default=None)
  348. ap.add_argument('--src', default=None, help='现场数据包目录 (给了就做增量体检: 新增/相同/冲突三清单)')
  349. ap.add_argument('--deep', action='store_true', help='加可读性抽样 (CSV 编码/表头, TCM json 字段)')
  350. ap.add_argument('--json', action='store_true')
  351. ap.add_argument('--write-doc', action='store_true', help='把结论写进 docs/输入数据放置指导_v0.1.md')
  352. a = ap.parse_args()
  353. st = station_dir(a.farm)
  354. res, notes, stat = check_tree(st, deep=a.deep)
  355. plan = {}
  356. if a.src:
  357. src = pathlib.Path(a.src)
  358. if not src.is_dir():
  359. print(f'[X] --src 不是目录: {src}')
  360. return RC_STRUCT
  361. r2, plan = increment_src(src, st)
  362. res += r2 + increment_findings(plan, src.name)
  363. guide = guidance(plan, stat)
  364. if a.json:
  365. print(json.dumps(dict(station=P.rel(st), results=[dict(level=x[0], item=x[1], note=x[2], rc=x[3]) for x in res],
  366. notes=[dict(level=x[0], item=x[1], note=x[2]) for x in notes], stat=stat, plan=plan,
  367. guidance=guide), ensure_ascii=False, indent=1, default=str))
  368. else:
  369. print(f'== 输入数据放置体检 · {P.rel(st)} ==')
  370. if stat.get('exists'):
  371. print(f' {stat["files"]:,} 件 / {stat["bytes"]/2**30:.2f} GB')
  372. for k, v in sorted(stat['subdirs'].items()):
  373. print(f' {k:14s} {v["files"]:7,d} 件 {v["bytes"]/2**20:9.1f} MB')
  374. for level, item, note, rc in res:
  375. print(f' [{level}] {item}: {note}')
  376. seen = set()
  377. for level, item, note, rc in notes:
  378. if note in seen:
  379. continue
  380. seen.add(note)
  381. print(f' [{level}] {item}: {note}')
  382. if plan:
  383. print('\n== 增量放置三清单 (源包 → data/raw) ==')
  384. print(f' 新增 {len(plan["new"]):,} 件 (将拷入) · 相同 {len(plan["same"]):,} 件 (同尺寸, 跳过) · '
  385. f'冲突 {len(plan["clash"]):,} 件 (同名不同大小, **需人确认**)')
  386. for k, label in (('new', '新增'), ('clash', '冲突')):
  387. for x in plan[k][:5]:
  388. extra = f' (现有 {x.get("now"):,} B)' if k == 'clash' else ''
  389. print(f' [{label}] {x["path"]} {x["size"]:,} B{extra}')
  390. if len(plan[k]) > 5:
  391. print(f' … 另有 {len(plan[k]) - 5} 件{label}')
  392. print('\n== 放置指导 ==')
  393. for g in guide:
  394. print(f' {g}')
  395. rc_map = {x[3] for x in res if x[0] in ('X', '!') and x[3]}
  396. rc = max(rc_map) if rc_map else (RC_NOTE if notes else RC_OK)
  397. if not a.json:
  398. print(f'\n结论: {"合规" if rc == 0 else "见上"}; 退出码 {rc}')
  399. if a.write_doc:
  400. write_doc(res, notes, stat, plan, guide)
  401. return rc
  402. DOC = P.ROOT / 'docs' / '输入数据放置指导_v0.1.md'
  403. BEGIN, END = '<!-- RAWCHECK:BEGIN -->', '<!-- RAWCHECK:END -->'
  404. def write_doc(res, notes, stat, plan, guide) -> None:
  405. body = [BEGIN, '### 体检结论(自动生成,勿手改)', '',
  406. f'· 源件目录 `{P.rel(station_dir())}`:{stat.get("files", 0):,} 件 / {stat.get("bytes", 0)/2**30:.2f} GB']
  407. for k, v in sorted((stat.get('subdirs') or {}).items()):
  408. body.append(f' - `{k}/`:{v["files"]:,} 件 / {v["bytes"]/2**20:.1f} MB')
  409. if res:
  410. body += ['', '| 级别 | 项 | 说明 |', '|---|---|---|']
  411. body += [f'| `{x[0]}` | `{x[1]}` | {x[2]} |' for x in res[:40]]
  412. else:
  413. body += ['', '· 结构与命名检查:**无不一致**(提示见下)']
  414. for x in notes[:12]:
  415. body.append(f'· `{x[0]}` {x[1]}:{x[2]}')
  416. if plan:
  417. body += ['', f'· 增量(源包 → data/raw):新增 {len(plan["new"]):,} · 相同 {len(plan["same"]):,} · '
  418. f'冲突 {len(plan["clash"]):,}']
  419. body += ['', '**放置后该做什么**:'] + [f'· {g}' for g in guide] + ['', END]
  420. block = '\n'.join(body)
  421. if DOC.is_file():
  422. t = DOC.read_text(encoding='utf-8')
  423. if BEGIN in t and END in t:
  424. t = re.sub(re.escape(BEGIN) + r'.*?' + re.escape(END), lambda m: block, t, flags=re.S)
  425. else:
  426. t = t.rstrip() + '\n\n' + block + '\n'
  427. else:
  428. t = '# 输入数据放置指导\n\n' + block + '\n'
  429. DOC.write_text(t, encoding='utf-8')
  430. print(f' 已写入 {P.rel(DOC)}')
  431. if __name__ == '__main__':
  432. from src import console
  433. console.soft()
  434. sys.exit(main())