基于 1.0.71 合入:model_sync/local_cls/assist 本地模型自动更新(版本比对/下载/sha+加载校验/替换失败回滚);review_queue 入库照先落队列、成功才送审、回执 image_sha256 核对;build_exe/installer 有 models/cls 就打包;版本 1.0.72;补工具脚本、文档与 config.sanitized.json。
279 lines
11 KiB
Python
279 lines
11 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""数据飞轮体检(只读):看看秤端到底有没有把照片/样本记下来
|
||
|
||
跑法(在 windows-fenjian 目录下):
|
||
python tools\\_flywheel_status.py # 打印体检报告
|
||
python tools\\_flywheel_status.py --open # 顺手用资源管理器打开 data 目录
|
||
|
||
飞轮在代码里是三段,本脚本逐段查盘(不写任何文件):
|
||
① 本地样本库 data/learn/<品名>/<时间>_<来源>_<sha8>.jpg + index.json
|
||
→ 下次识别当「样例图」喂给模型(few-shot)
|
||
落盘时机:人点头记账那一刻;camera.simulate=true 时跳过
|
||
② 入库照片送审 data/review_pending/<操作号>/meta.json + photo.jpg
|
||
→ 入库成功后台线程送 /mobile/recognition/samples 待人工审核
|
||
落盘时机:发入库请求之前;server.mock 或模拟相机时跳过
|
||
③ 抓拍留档 data/snapshots/xxx.jpg(滚动清理,不是训练库)
|
||
台账 data/records*.csv 记着「哪一笔对应哪张图」
|
||
|
||
结论怎么看:① 有张数才是真攒到样本;② 有目录才是真排上了送审。
|
||
"""
|
||
import argparse
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
APP = os.path.dirname(HERE)
|
||
os.chdir(APP)
|
||
sys.path.insert(0, APP)
|
||
|
||
LEARN_INDEX = os.path.join('data', 'learn', 'index.json')
|
||
LEARN_DIR = os.path.join('data', 'learn')
|
||
PENDING_DIR = os.path.join('data', 'review_pending')
|
||
REJECTED = os.path.join('data', 'review_rejected.json')
|
||
SNAP_DIR = os.path.join('data', 'snapshots')
|
||
|
||
ON, OFF = '开', '关'
|
||
|
||
|
||
def _w(s):
|
||
"""显示宽度:CJK 算 2 列"""
|
||
return sum(2 if ord(ch) > 0x2E80 else 1 for ch in s)
|
||
|
||
|
||
def col(s, n):
|
||
s = str(s)
|
||
return s + ' ' * max(1, n - _w(s))
|
||
|
||
|
||
def sec(title):
|
||
print('')
|
||
print('=' * 74)
|
||
print(title)
|
||
print('=' * 74)
|
||
|
||
|
||
def kv(k, v):
|
||
print(' %s%s%s' % (k, ' ' * max(2, 18 - _w(k)), v))
|
||
|
||
|
||
def fmt_size(n):
|
||
return '%.1f MB' % (n / 1048576.0) if n >= 1048576 else '%d KB' % (n / 1024)
|
||
|
||
|
||
def fmt_at(ts):
|
||
try:
|
||
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(float(ts)))
|
||
except (TypeError, ValueError):
|
||
return '-'
|
||
|
||
|
||
def load_json(path, default=None):
|
||
try:
|
||
with open(path, encoding='utf-8') as f:
|
||
return json.load(f)
|
||
except (OSError, ValueError):
|
||
return default
|
||
|
||
|
||
# ---------------------------------------------------------------- 现场条件
|
||
def gates():
|
||
cfg = load_json('config.json', {}) or {}
|
||
cam = cfg.get('camera') or {}
|
||
return {
|
||
'mock': bool((cfg.get('server') or {}).get('mock')),
|
||
'role': (cfg.get('account') or {}).get('role') or '',
|
||
'cam_sim': bool(cam.get('simulate')),
|
||
'replay': str(cam.get('replay_dir') or '').strip(),
|
||
'api_key': str((cfg.get('vision') or {}).get('api_key') or '').strip(),
|
||
'scale_sim': bool((cfg.get('scale') or {}).get('simulate')),
|
||
}
|
||
|
||
|
||
def show_gates(g):
|
||
sec('现场条件:三段飞轮各自被什么挡着')
|
||
kv('server.mock', '%s(%s)' % ('True' if g['mock'] else 'False',
|
||
'提交不走真服务端' if g['mock'] else '真服务端'))
|
||
kv('account.role', g['role'] or '(未配)')
|
||
kv('camera.simulate', '%s(%s)' % ('True' if g['cam_sim'] else 'False',
|
||
'画面是模拟的' if g['cam_sim'] else '真相机'))
|
||
kv('camera.replay_dir', g['replay'] or '(空)')
|
||
kv('scale.simulate', 'True' if g['scale_sim'] else 'False')
|
||
kv('vision.api_key', '(空)' if not g['api_key'] else '已填(%d 位)'
|
||
% len(g['api_key']))
|
||
print('')
|
||
ok1 = not (g['cam_sim'] or g['replay'])
|
||
kv('① 本地样本库落盘', '%s%s' % (ON if ok1 else OFF,
|
||
'' if ok1 else ' camera.simulate/replay 开着 → _learn_sample 直接 return'))
|
||
ok2 = (not g['mock']) and (not (g['cam_sim'] or g['replay'])) \
|
||
and g['role'] == 'inspector'
|
||
kv('② 入库照片送审', '%s%s' % (ON if ok2 else OFF,
|
||
'' if ok2 else ' _review_stage 前置条件不满足 → 不登记'))
|
||
kv('③ 抓拍留档', '%s(不管什么模式都会存)' % ON)
|
||
|
||
|
||
|
||
# ---------------------------------------------------------------- ① 样本库
|
||
def show_learn():
|
||
sec('① 本地样本库 data/learn(识别时当样例图,反哺模型)')
|
||
idx = load_json(LEARN_INDEX, {})
|
||
items = (idx or {}).get('items') or {}
|
||
rows = []
|
||
for name, lst in items.items():
|
||
for r in (lst or []):
|
||
if isinstance(r, dict) and r.get('file'):
|
||
rows.append((str(name), r))
|
||
if not rows:
|
||
kv('索引', '没有 %s' % LEARN_INDEX.replace(os.sep, '/'))
|
||
kv('样本', '0 张')
|
||
if not os.path.isdir(LEARN_DIR):
|
||
kv('目录', 'data/learn 还不存在')
|
||
print(' → 没有任何一张图进过样本库,模型下次识别不会看到任何现场样例')
|
||
return
|
||
kv('索引', LEARN_INDEX.replace(os.sep, '/'))
|
||
kv('样本', '%d 张 / %d 个品名' % (len(rows), len(items)))
|
||
stat = {}
|
||
for name, r in rows:
|
||
src = r.get('source') or 'weak'
|
||
stat.setdefault(name, {}).setdefault(src, 0)
|
||
stat[name][src] += 1
|
||
print('')
|
||
print(' ' + col('品名', 14) + col('weak(AI+人确认)', 18)
|
||
+ col('fix(人改判)', 14) + '合计')
|
||
for name in sorted(stat, key=lambda n: -sum(stat[n].values())):
|
||
s = stat[name]
|
||
print(' ' + col(name, 14) + col(s.get('weak', 0), 18)
|
||
+ col(s.get('fix', 0), 14) + str(sum(s.values())))
|
||
rows.sort(key=lambda x: -(x[1].get('at') or 0))
|
||
print('')
|
||
print(' 最近 5 张:')
|
||
for name, r in rows[:5]:
|
||
print(' ' + col(fmt_at(r.get('at')), 21) + col(name, 12)
|
||
+ col(r.get('source') or 'weak', 7) + (r.get('file') or '')
|
||
+ ((' (原认成 %s)' % r.get('was')) if r.get('was') else ''))
|
||
|
||
|
||
# ---------------------------------------------------------------- ② 送审
|
||
def show_pending():
|
||
sec('② 入库照片送审 data/review_pending(秤 → 后台「识别样本」待审核)')
|
||
try:
|
||
ops = sorted(x for x in os.listdir(PENDING_DIR) if not x.startswith('.'))
|
||
except OSError:
|
||
ops = []
|
||
if not ops:
|
||
kv('队列', '没有 %s' % PENDING_DIR.replace(os.sep, '/'))
|
||
kv('待审', '0 条')
|
||
else:
|
||
kv('队列', PENDING_DIR.replace(os.sep, '/'))
|
||
kv('待审', '%d 条' % len(ops))
|
||
print('')
|
||
for op in ops:
|
||
d = os.path.join(PENDING_DIR, op)
|
||
meta = load_json(os.path.join(d, 'meta.json'), {}) or {}
|
||
photo = os.path.join(d, 'photo.jpg')
|
||
size = os.path.getsize(photo) if os.path.isfile(photo) else 0
|
||
fld = meta.get('fields') or {}
|
||
print(' ' + col(op, 34) + col(fld.get('label_name') or '-', 12)
|
||
+ col(fld.get('order_code') or '-', 14)
|
||
+ col(('%d KB' % (size / 1024)) if size else '缺图', 8)
|
||
+ 'tries=%s %s' % (meta.get('tries', 0),
|
||
meta.get('error') or ''))
|
||
rej = load_json(REJECTED, [])
|
||
kv('被永久拒收', '%d 条(%s)' % (len(rej or []), REJECTED.replace(os.sep, '/')))
|
||
|
||
|
||
# ---------------------------------------------------------------- ③ 抓拍
|
||
def show_snapshots():
|
||
sec('③ 抓拍留档 data/snapshots(不是训练库,滚到一定数量会被清)')
|
||
files = []
|
||
try:
|
||
files = [os.path.join(SNAP_DIR, f) for f in os.listdir(SNAP_DIR)]
|
||
files = [p for p in files if os.path.isfile(p)]
|
||
except OSError:
|
||
pass
|
||
files.sort(key=lambda p: os.path.getmtime(p))
|
||
kv('张数', '%d 张 / %s' % (len(files),
|
||
fmt_size(sum(os.path.getsize(p) for p in files))
|
||
if files else '0 KB'))
|
||
print('')
|
||
print(' 最近 6 张:')
|
||
for p in files[-6:]:
|
||
print(' ' + col(time.strftime('%Y-%m-%d %H:%M:%S',
|
||
time.localtime(os.path.getmtime(p))), 21)
|
||
+ col(os.path.basename(p), 34)
|
||
+ '%7d KB' % (os.path.getsize(p) / 1024))
|
||
|
||
|
||
def show_records():
|
||
sec('记账留痕 data/records*.csv(和飞轮不是一回事,但能对上「哪笔对应哪张图」)')
|
||
for name in ('records.csv', 'records_demo.csv'):
|
||
p = os.path.join('data', name)
|
||
if not os.path.isfile(p):
|
||
kv(name, '没有')
|
||
continue
|
||
try:
|
||
with open(p, encoding='utf-8-sig') as f:
|
||
lines = [x for x in f.read().splitlines() if x.strip()]
|
||
except OSError:
|
||
lines = []
|
||
kv(name, '%d 行(含表头)' % len(lines))
|
||
if len(lines) > 1:
|
||
print(' 最后一行:' + lines[-1])
|
||
|
||
|
||
def conclude(g):
|
||
sec('结论')
|
||
idx = load_json(LEARN_INDEX, {})
|
||
items = (idx or {}).get('items') or {}
|
||
n_learn = sum(len(v or []) for v in items.values())
|
||
try:
|
||
n_pend = len([x for x in os.listdir(PENDING_DIR) if not x.startswith('.')])
|
||
except OSError:
|
||
n_pend = 0
|
||
try:
|
||
n_snap = len([x for x in os.listdir(SNAP_DIR)
|
||
if os.path.isfile(os.path.join(SNAP_DIR, x))])
|
||
except OSError:
|
||
n_snap = 0
|
||
kv('样本库里的图', '%d 张' % n_learn)
|
||
kv('排队等送审', '%d 条' % n_pend)
|
||
kv('抓拍留档', '%d 张' % n_snap)
|
||
print('')
|
||
if n_learn or n_pend:
|
||
print(' → 飞轮有记录,见上面 ① / ② 的明细')
|
||
return
|
||
print(' → 飞轮一条也没进来:图只落在 data/snapshots 和 records*.csv 里,')
|
||
print(' 那是「对账留痕」,不会变成训练样本。')
|
||
if g['cam_sim'] or g['replay']:
|
||
print(' 原因:camera.simulate=True —— 模拟画面存进去等于拿占位图当教材')
|
||
if g['mock']:
|
||
print(' 原因:server.mock=True —— 送审要发到后台,模拟服务端没有收图的地方')
|
||
print(' 想看飞轮真转起来:真相机(camera.simulate=false)+ 真服务端'
|
||
'(server.mock=false)+ 入库站(account.role=inspector)')
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument('--open', action='store_true', help='顺手打开 data 目录')
|
||
args = ap.parse_args()
|
||
print('#' * 74)
|
||
print('# 数据飞轮体检 %s' % time.strftime('%Y-%m-%d %H:%M:%S'))
|
||
print('#' * 74)
|
||
g = gates()
|
||
show_gates(g)
|
||
show_learn()
|
||
show_pending()
|
||
show_snapshots()
|
||
show_records()
|
||
conclude(g)
|
||
print('')
|
||
if args.open:
|
||
subprocess.Popen(['explorer', os.path.join(APP, 'data')])
|
||
print(' 已在资源管理器打开 data 目录')
|
||
|
||
|
||
if __name__ == '__main__':
|
||
main()
|