detail_deps.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""`/detail` 详细分析工作台 · 页面 → 取数接口 → 产物 → 来源 的**可复算**台账 (2026-09-18 用户令)。
  4. 用户令: 「http://127.0.0.1:28084/detail 下的各页面, 不能用旧版的产出补, 只能参照旧版产物的呈现
  5. 样式内容, 必须基于输入数据重算」。本器把这条令变成一份**每次都能重跑出来的清单**:
  6. 页面(页签) ← 取数接口(在线 /api/*) ← 产物件 → 来源(台账) + 生成端(族表) + 缺口处置
  7. 证据不是印象, 两头都对着源码核:
  8. · 页面 → 接口: 在 `src/windscada/ui/app.js` 里逐个搜到该接口 (页签表 TABS 与各 fetch 调用);
  9. · 接口 → 产物: 声明时给出 `scripts/windscada_serve.py` 里的函数名, 本器逐一核对该符号存在;
  10. · 产物 → 来源: 读 `outputs/<场>/_provenance.json`(逐件来源台账, 由 products_restore_missing
  11. --refresh 维护) 与 `scripts/products_reverse_audit.py` 的族表(生成端)。
  12. 任一条核不上 → 本器报 `[核不上]` 并 rc=5 —— 页面改了接口而清单没跟, 或产物换了生成端, 当场露出来。
  13. `/detail` 是**网关**(scripts/guanlan_gateway.py, 默认 28084)把请求转到**组件服务**
  14. (scripts/windscada_serve.py, 默认 18033)的 `/v2` 前端; 两边都是同一套 `/api/*`, 所以本清单对
  15. 在线页与单文件快照 (src/windscada/ui/snapshot.py) 同时成立。
  16. 用法:
  17. python scripts/detail_deps.py # 打印清单 (人看)
  18. python scripts/detail_deps.py --probe # 额外实测在线接口 (需服务在跑; 只打印, 不写盘)
  19. python scripts/detail_deps.py --write # 写 docs/detail_页面依赖与重算台账_v0.1.md
  20. python scripts/detail_deps.py --check # 文档是否与现场一致 (rc=5 = 该重写)
  21. """
  22. from __future__ import annotations
  23. import argparse
  24. import fnmatch
  25. import json
  26. import pathlib
  27. import re
  28. import sys
  29. ROOT = pathlib.Path(__file__).resolve().parents[1]
  30. sys.path.insert(0, str(ROOT))
  31. sys.path.insert(0, str(ROOT / 'scripts'))
  32. from src import paths as P # noqa: E402
  33. APPJS = ROOT / 'src' / 'windscada' / 'ui' / 'app.js'
  34. SERVE = ROOT / 'scripts' / 'windscada_serve.py'
  35. DOC = ROOT / 'docs' / 'detail_页面依赖与重算台账_v0.1.md'
  36. BEGIN, END = '<!-- DETAIL-DEPS:BEGIN -->', '<!-- DETAIL-DEPS:END -->'
  37. PBEGIN, PEND = '<!-- DETAIL-PROBE:BEGIN -->', '<!-- DETAIL-PROBE:END -->'
  38. # ── 页签 → 取数接口 (证据: app.js 里能搜到该接口) ────────────────────────────────
  39. # ★实测校准 (2026-09-18): 所有页签的**底数**都是 `/api/fleet` (app.js:1029 `load()`), 其余按页签
  40. # 各自取: decision→ont_chain(403) · report→rpt_compose/facts(586) · system→maint_survey(728)
  41. # · generation→curves(752) · vibration/cms→vibcms(931) · assistant→ask*/facts(425/413)。
  42. # 下钻浮层 (`/api/problem` `/api/turbine`, app.js:995) 从任意页签都能触发, 挂在部件页。
  43. PAGES: list[tuple[str, str, list[str]]] = [
  44. ('overview', '总览', ['/api/fleet']),
  45. ('energy', '发电与损失', ['/api/fleet']),
  46. ('component', '部件与系统', ['/api/fleet', '/api/problem', '/api/turbine']),
  47. ('vibration', '振动评估(CMS)', ['/api/fleet', '/api/vibcms']),
  48. ('generation', '特性曲线', ['/api/curves']),
  49. ('fault', '故障与可用率', ['/api/fleet']),
  50. ('decision', '决策链', ['/api/fleet', '/api/ont_chain']),
  51. ('assistant', '问答', ['/api/fleet', '/api/ask', '/api/ask_status', '/api/ask_models',
  52. '/api/facts', '/api/facts/claim']),
  53. ('report', '报告', ['/api/fleet', '/api/facts', '/api/rpt_compose']),
  54. ('system', '系统自查', ['/api/fleet', '/api/maint_survey']),
  55. ]
  56. # ── 接口 → 产物 → 生成端 (证据: windscada_serve.py 里的符号名, 本器核对存在) ──────
  57. # req=True = 缺了这页就出不来 (接口回 no_products / err);
  58. # req=False = 接口内有 .exists() 兜底, 缺了只是少一块 (页面仍出, 但内容不全)。
  59. APIS: list[dict] = [
  60. dict(path='/api/fleet', fn='fleet_view', req=[
  61. 'windscada/temp_monthly.parquet', 'windscada/alarms.parquet', 'windscada/loss_monthly.parquet',
  62. 'windscada/powercurve_bins.parquet', 'windscada/powercurve_dev.parquet'],
  63. opt=['windscada/*.parquet', 'ontology/turbine_params.parquet',
  64. 'm5_cms_tcm/handoff_vibration_v2.json', 'm5_cms_tcm/fleet_scalar_z.parquet',
  65. 'pitch/pitch_daily.parquet', 'pitch/pitch_zero_monthly.parquet'],
  66. note='硬缺件在 `_load()` 里直接抛 ProductsMissing ⇒ 接口回 err=no_products'),
  67. dict(path='/api/curves', fn='curve_view',
  68. req=['windscada/powercurve_bins.parquet'],
  69. opt=['windscada/curve_lenses.parquet', 'windscada/curve_liveness.parquet',
  70. 'windscada/control_profile.parquet', 'windscada/hydraulic_accum.parquet'],
  71. note='曲线镜头读 10min 原始档 + 已重算的派生件'),
  72. dict(path='/api/problem', fn='single_problem', req=['windscada/alarms.parquet'],
  73. opt=['ontology/objects.json', 'windscada/workorders.parquet'], note='部件下钻浮层'),
  74. dict(path='/api/turbine', fn='turbine_problems', req=['windscada/alarms.parquet'],
  75. opt=['ontology/objects.json', 'windscada/workorders.parquet'], note='逐台下钻浮层'),
  76. dict(path='/api/vibcms', fn='vibcms_results',
  77. req=['windcms/报告_CMS振动状态评估报告_*.md'],
  78. opt=['m5_cms_tcm/handoff_vibration_v2.json', 'windcms/cache/*'],
  79. note='报告是振动六层链 report 步的出件; 缺它本接口如实回 no_report(不再抛 IndexError)'),
  80. dict(path='/api/maint_survey', fn='maint_framework_view', req=['ontology/objects.json'], opt=[],
  81. note='维护面盘点读本体对象库 (/v2 的「系统自查」页签取它)'),
  82. dict(path='/api/maint_std', fn='maint_framework_view', ui='classic', req=['ontology/objects.json'],
  83. opt=[], note='四判据+成熟度 (经典页 `/?…` 用, /v2 不取)'),
  84. dict(path='/api/maint_framework', fn='maint_framework_view', ui='classic', req=['ontology/objects.json'],
  85. opt=[], note='运维体系三维 (经典页用, /v2 不取)'),
  86. dict(path='/api/dq_findings', fn='dq_findings_view', ui='classic', req=['ontology/objects.json'], opt=[],
  87. note='只认 finding/data_quality|caliber|system_coverage|tier_trend 四族对象; 这四族**不在重算链上** '
  88. '(唯一写方 scripts/ingest_ops_2025.py 读 data/raw/工作库, 该目录不在现场数据里)'),
  89. dict(path='/api/ont_chain', fn='ontology_view', req=['ontology/objects.json'], opt=[], note='故障链/预防链/故障树'),
  90. dict(path='/api/ontology', fn='ontology_view', ui='classic', req=['ontology/objects.json'], opt=[],
  91. note='本体总表 (经典页用, /v2 用 fleet 里的本体投影)'),
  92. dict(path='/api/facts', fn=None,
  93. req=['guanlan/facts_contract_v0.json', 'guanlan/derived/detail_cards.json'],
  94. opt=['guanlan/derived/qa_refs.json', 'guanlan/derived/portal_claims.json'],
  95. note='契约链: 输入是 sop/findings.json + paradigm_r1 三份**人裁底稿** ⇒ 与 data/raw 隔着不止一跳'),
  96. dict(path='/api/ask', fn=None, req=[], opt=[], note='本机 Ollama; 无产物依赖'),
  97. dict(path='/api/ask_status', fn=None, req=[], opt=[], note='本机 Ollama; 无产物依赖'),
  98. dict(path='/api/ask_models', fn=None, req=[], opt=[], note='本机 Ollama; 无产物依赖'),
  99. dict(path='/api/rpt_compose', fn=None, req=[], opt=[], note='本机 Ollama; 无产物依赖'),
  100. ]
  101. def _expand_braces(glob) -> list[str]:
  102. """族 glob (str 或 list) → 展开 `{a,b}` 后的模式列表 (与 products_reverse_audit._files_of 同规则)。"""
  103. out = []
  104. for g in ([glob] if isinstance(glob, str) else list(glob)):
  105. if '{' in g:
  106. head, tail = g.split('{', 1)
  107. opts, rest = tail.split('}', 1)
  108. out += [head + o + rest for o in opts.split(',')]
  109. else:
  110. out.append(g)
  111. return out
  112. def _pat_match(rel: str, glob) -> bool:
  113. """rel 是否落在族 glob 里 (深度对齐: 模式无 `**` 时 `/` 个数必须相等 —— fnmatch 的 `*` 跨 `/`)。"""
  114. for pt in _expand_braces(glob):
  115. if '**' not in pt and rel.count('/') != pt.count('/'):
  116. continue
  117. if rel == pt or fnmatch.fnmatch(rel, pt):
  118. return True
  119. return False
  120. # ── 环境读取 ────────────────────────────────────────────────────────────────────
  121. def load_env(farm: str | None = None):
  122. root = P.out_root(farm)
  123. ledger = {}
  124. lf = root / '_provenance.json'
  125. if lf.is_file():
  126. try:
  127. ledger = (json.loads(lf.read_text(encoding='utf-8')) or {}).get('files') or {}
  128. except Exception:
  129. ledger = {}
  130. disk = {p.relative_to(root).as_posix(): p.stat().st_size
  131. for p in root.rglob('*') if p.is_file()}
  132. try:
  133. from products_reverse_audit import FAMILIES
  134. except Exception:
  135. FAMILIES = []
  136. def family_of(rel: str):
  137. for fam in FAMILIES:
  138. if _pat_match(rel, fam['glob']):
  139. return fam
  140. return None
  141. return dict(farm=farm or P.farm(), root=root, ledger=ledger, disk=disk, family_of=family_of,
  142. fams=FAMILIES)
  143. def expand(pat: str, env) -> list[str]:
  144. got = [r for r in env['disk'] if fnmatch.fnmatch(r, pat)]
  145. return sorted(got)
  146. def row_of(pat: str, env) -> dict:
  147. """一条产物声明 → 在位情况 + 来源 + 生成端。"""
  148. hits = expand(pat, env)
  149. if hits:
  150. srcs = sorted({(env['ledger'].get(r) or {}).get('source', '(未登记)') for r in hits})
  151. fams = []
  152. for r in hits[:40]:
  153. f = env['family_of'](r)
  154. if f and f['id'] not in fams:
  155. fams.append(f['id'])
  156. gen = next((env['family_of'](r) for r in hits if env['family_of'](r)), None)
  157. return dict(pat=pat, n=len(hits), bytes=sum(env['disk'][r] for r in hits),
  158. src='·'.join(srcs), builder=(gen or {}).get('gen') or '—',
  159. family='·'.join(fams) or '—', ok=True)
  160. f = env['family_of'](pat) if '*' not in pat else None
  161. return dict(pat=pat, n=0, bytes=0, src='—', builder='—',
  162. family=(f or {}).get('id') or '—', ok=False)
  163. def main() -> int:
  164. ap = argparse.ArgumentParser()
  165. ap.add_argument('--probe', action='store_true', help='实测在线接口 (需服务在跑; 只打印)')
  166. ap.add_argument('--write', action='store_true', help='写回文档')
  167. ap.add_argument('--check', action='store_true', help='核对文档与现场一致 (rc=5 = 该重写)')
  168. ap.add_argument('--farm', default=None)
  169. a = ap.parse_args()
  170. env = load_env(a.farm)
  171. appjs = APPJS.read_text(encoding='utf-8')
  172. serve = SERVE.read_text(encoding='utf-8')
  173. # ① 证据核对: 页面端接口在 app.js 里找得到吗; 接口函数在 serve 里找得到吗
  174. bad = []
  175. for pid, name, eps in PAGES:
  176. if f"'{pid}'" not in appjs:
  177. bad.append(f'页签 {pid} 不在 app.js 的 TABS 里')
  178. for ep in eps:
  179. if f"'{ep}'" not in appjs and f"`{ep}" not in appjs and ep not in appjs:
  180. bad.append(f'页签 {pid} 声明的 {ep} 在 app.js 里搜不到')
  181. for it in APIS:
  182. if it.get('ui') == 'classic':
  183. # 经典页 (/ 老前端) 的接口: 出处是 serve 里的路由分支, 不是 app.js
  184. if f"'{it['path']}'" not in serve:
  185. bad.append(f"经典页接口 {it['path']} 在 windscada_serve.py 的路由里搜不到")
  186. elif f"'{it['path']}'" not in appjs and it['path'] not in appjs:
  187. bad.append(f"{it['path']} 声明给 /v2 用, 但 app.js 里搜不到它")
  188. if it['fn'] and f"def {it['fn']}(" not in serve:
  189. bad.append(f"{it['path']} 声明的实现函数 {it['fn']}() 在 windscada_serve.py 里不存在")
  190. probe = {}
  191. if a.probe:
  192. probe = {it['path']: _probe(it['path']) for it in APIS}
  193. L = []
  194. L.append(f'# /detail 页面依赖与重算台账 (自动生成, 禁手改)')
  195. L.append('')
  196. L.append(f'> 生成端: `python scripts/detail_deps.py --write`|场站 `{env["farm"]}`|'
  197. f'产物仓 `{P.rel(env["root"])}`|盘上 {len(env["disk"]):,} 件')
  198. L.append('>')
  199. L.append('> 用户令 (2026-09-18): **/detail 各页面不许用旧版产出补**, 只能参照旧版产物的呈现样式与内容, '
  200. '数值必须由 `data/raw` 重算。本表把每页的取数接口与产物件逐条列清, 缺的写明怎么补。')
  201. L.append('')
  202. L.append('## 1 页面 → 取数接口')
  203. L.append('')
  204. L.append('| 页签 | 页面 | 取数接口 |')
  205. L.append('|---|---|---|')
  206. for pid, name, eps in PAGES:
  207. for i, ep in enumerate(eps):
  208. L.append(f'| {pid if i == 0 else ""} | {name if i == 0 else ""} | `{ep}` |')
  209. L.append('')
  210. L.append('注: `/api/maint_std` `/api/maint_framework` `/api/dq_findings` `/api/ontology` 属**经典页** '
  211. '(`/?…`, 组件根), `/v2` 工作台不取它们 —— 但同一批本体产物 (ontology/objects.json) 仍然决定着'
  212. '它们能不能出数, 故一并列在 §2。')
  213. L.append('')
  214. L.append('## 2 接口 → 产物 → 来源 / 生成端')
  215. L.append('')
  216. L.append('| 接口 | 产物 | 件 | 大小 | 台账来源 | 生成端(族) | 判定 |')
  217. L.append('|---|---|---:|---:|---|---|---|')
  218. gaps = []
  219. for it in APIS:
  220. for kind, label in (('req', '✅必需'), ('opt', '○可选')):
  221. for pat in it[kind]:
  222. r = row_of(pat, env)
  223. verdict = ('在位' if r['ok'] else ('**缺**' if kind == 'req' else '缺(页面降级)'))
  224. if not r['ok']:
  225. gaps.append((it['path'], pat, kind, r['family']))
  226. L.append(f"| {it['path'] if pat == it[kind][0] else ''} | `{pat}` {label} | {r['n']} | "
  227. f"{r['bytes'] / 1e6:.1f} MB | {r['src']} | {r['builder']} ({r['family']}) | {verdict} |")
  228. L.append('')
  229. L.append('## 3 缺口与处置 (缺的件谁生成、能不能从 data/raw 重算)')
  230. L.append('')
  231. if not gaps:
  232. L.append('无缺口: 表内每件产物都在位且来源已登记。')
  233. else:
  234. L.append('| 接口 | 缺件 | 必需 | 生成端 | 能否由 data/raw 重算 |')
  235. L.append('|---|---|---|---|---|')
  236. for ep, pat, kind, fam in gaps:
  237. g = _gen_of(env, pat)
  238. L.append(f"| `{ep}` | `{pat}` | {'是' if kind == 'req' else '否'} | {g['gen']} | {g['how']} |")
  239. L.append('')
  240. L.append('## 4 与输入数据的对应 (重算口径)')
  241. L.append('')
  242. L.append('| 产物族 | 输入 (data/raw/<场站>/…) | 生成端 |')
  243. L.append('|---|---|---|')
  244. seen = set()
  245. for it in APIS:
  246. for pat in it['req'] + it['opt']:
  247. f = env['family_of'](pat) if '*' not in pat else None
  248. if not f or f['id'] in seen:
  249. continue
  250. seen.add(f['id'])
  251. L.append(f"| {f['id']} | {f.get('input') or '—'} | `{f.get('gen') or '—'}` |")
  252. L.append('')
  253. L.append('## 5 复现')
  254. L.append('')
  255. L.append('```')
  256. L.append('python scripts/detail_deps.py --probe # 实测在线接口 (页面同路径: 网关 → 组件 /v2)')
  257. L.append('python scripts/products_restore_missing.py --refresh # 重算后维护逐件来源台账')
  258. L.append('python scripts/rebuild_all.py # 全量重算 (链上含 ⑤a 台账维护 → ⑤ 反向呼应审计)')
  259. L.append('```')
  260. body = '\n'.join(L)
  261. text = f'{BEGIN}\n{body}\n{END}\n'
  262. # ── 实测段: 与"清单"分开标记 —— 它的数随服务在场与否变, 不该让 --check 抖动 ─────────
  263. ptext = ''
  264. if probe:
  265. P_ = ['## P 实测 (本次运行, 走网关 28084 → 组件 /v2)', '',
  266. '| 页签 | 接口 | 判定 | 实测 |', '|---|---|---|---|']
  267. for pid, name, eps in PAGES:
  268. for i, ep in enumerate(eps):
  269. r = probe.get(ep) or {}
  270. st = (f"HTTP {r['http']}" if r.get('http') else '—') + \
  271. (f" · {r['err'][:70]}" if r.get('err') else (f" · {r['n']:,} B" if r.get('n') else ''))
  272. P_.append(f"| {pid if i == 0 else ''} | `{ep}` | {r.get('verdict', '—')} | {st} |")
  273. P_ += ['', '判读口径: 只认响应**顶层**的 `err`/`error`/`no_products`/`no_report`; '
  274. '`/api/ask*` `/api/rpt_compose` 依赖本机模型, 未启动时记「不适用」不算缺件。']
  275. ptext = f'{PBEGIN}\n' + '\n'.join(P_) + f'\n{PEND}\n'
  276. if bad:
  277. print('证据核对不通过 —— 清单与源码/现场脱节:')
  278. for b in bad:
  279. print(' [核不上] ' + b)
  280. print(f'清单: {len(PAGES)} 页签 · {len(APIS)} 接口 · 缺口 {len(gaps)} 件 · '
  281. f'产物仓 {len(env["disk"]):,} 件')
  282. if a.write:
  283. old = DOC.read_text(encoding='utf-8') if DOC.is_file() else ''
  284. if PBEGIN in old and PEND in old: # 旧实测段先整段摘掉, 再按需重写
  285. old = old[:old.index(PBEGIN)].rstrip() + '\n' + old[old.index(PEND) + len(PEND):].lstrip('\n')
  286. if BEGIN in old and END in old:
  287. new = old[:old.index(BEGIN)] + text + old[old.index(END) + len(END):].lstrip('\n')
  288. else:
  289. new = (old.rstrip() + '\n\n' if old.strip() else
  290. '# /detail 页面依赖与重算台账 v0.1\n\n'
  291. '用户令 (2026-09-18): `/detail` 各页面不许用旧版产出补, 必须由 `data/raw` 重算;\n'
  292. '旧版产物只可参照**呈现样式与内容**。逐页依赖见下表 (自动生成段)。\n\n') + text
  293. new = new.rstrip() + '\n\n' + ptext if ptext else new
  294. DOC.write_text(new, encoding='utf-8')
  295. print(f'已写 {P.rel(DOC)}' + ('' if ptext else ' (未带实测段; 加 --probe 可一并写入)'))
  296. if a.check:
  297. cur = DOC.read_text(encoding='utf-8') if DOC.is_file() else ''
  298. seg = cur[cur.index(BEGIN):cur.index(END) + len(END)] if (BEGIN in cur and END in cur) else ''
  299. if seg.strip() != text.strip():
  300. print('[X] 文档与现场不一致 ⇒ 跑 --write 重写')
  301. return 5
  302. print('[OK] 文档与现场一致 (清单段; 实测段随服务状态变, 不参与比对)')
  303. return 5 if bad else 0
  304. def _gen_of(env, pat: str) -> dict:
  305. """缺口件 → 生成端与"能否从 data/raw 重算"的如实判断 (依据: 族表的 kind/algo/why)。"""
  306. f = next((fam for fam in env['fams'] if _pat_match(pat, fam['glob'])), None)
  307. if not f:
  308. return dict(gen='—', how='族表里没有这一族 ⇒ 需人工归口')
  309. if f.get('gen'):
  310. return dict(gen=f"`{f['gen']}`", how='能: 放原始件到 data/raw 后 `rebuild_all.py`')
  311. return dict(gen='(无生成端)', how=f"**不能**: {str(f.get('why') or '')[:60]} ⇒ 需研发补生成端")
  312. def _probe(ep: str) -> dict:
  313. """实测一个接口 (走网关, 与页面同路径)。判读只认**顶层**的 err/error/no_products/no_report ——
  314. ★2026-09-18 首版按正则全文搜 `"err":` 判读, 结果把 fleet 响应里某个以 err 结尾的字段的**值**
  315. (per_turbine) 当成了报错, 页面明明好着却显示"有缺件痕迹"。判读不许靠猜文本。"""
  316. import urllib.error
  317. import urllib.request
  318. base = 'http://127.0.0.1:28084/detail'
  319. q = {'/api/fleet': '?win=2026%E5%B9%B4',
  320. '/api/turbine': '?t=WTG01&win=2026%E5%B9%B4',
  321. '/api/problem': '?t=WTG01&sys=%E5%8F%98%E6%A1%A8%E7%B3%BB%E7%BB%9F&win=2026%E5%B9%B4',
  322. '/api/ont_chain': '?kind=prev&system=%E5%8F%98%E6%A1%A8%E7%B3%BB%E7%BB%9F',
  323. '/api/facts/claim': '?id=RD-000'}.get(ep, '')
  324. try:
  325. with urllib.request.urlopen(base + ep + q, timeout=60) as r:
  326. raw, code = r.read(), r.status
  327. except urllib.error.HTTPError as e:
  328. raw, code = e.read(), e.code
  329. except Exception as e:
  330. return dict(http=None, n=0, err=f'{type(e).__name__}: {e}', verdict='连不上')
  331. try:
  332. obj = json.loads(raw.decode('utf-8', 'replace'))
  333. except Exception:
  334. return dict(http=code, n=len(raw), err='(非 JSON)', verdict='?')
  335. if not isinstance(obj, dict):
  336. return dict(http=code, n=len(raw), err='', verdict='有数')
  337. msg = next((str(obj[k]) for k in ('err', 'error') if obj.get(k)), '')
  338. if ep == '/api/ask': # 只收 POST (页面上是表单提交), GET 探测必 404 —— 不是缺件
  339. return dict(http=code, n=len(raw), err='', verdict='不适用(POST 接口)')
  340. # 本机模型 (Ollama) 没起 / 未接: 这不是"重算缺件", 标成不适用 —— 与 `guanlan.py check` 的口径一致
  341. if ep in ('/api/ask_status', '/api/ask_models', '/api/rpt_compose'):
  342. return dict(http=code, n=len(raw), err=msg,
  343. verdict='不适用(本机模型未启动)' if msg or code >= 400 else '有数')
  344. if obj.get('no_products') or obj.get('no_report') or (ep == '/api/facts/claim' and code >= 400):
  345. return dict(http=code, n=len(raw), err=msg or 'no_products', verdict='无产物(如实)')
  346. if msg:
  347. return dict(http=code, n=len(raw), err=msg, verdict='报错')
  348. return dict(http=code, n=len(raw), err='', verdict='有数')
  349. if __name__ == '__main__':
  350. sys.exit(main())