Files

567 lines
23 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""入库分拣系统 - 主程序
流程:秤上重量稳定 -> 摄像头截图 -> 视觉大模型识别商品名
-> 匹配商品名单 -> 不匹配则大模型核查"同物异名" -> 人工确认
入库模式:确认后仅记录
分拣模式:确认后记录 + 打印标签
运行:python app.py (Esc 退出全屏)
"""
import csv
import json
import os
import queue
import threading
import datetime
import difflib
import tkinter as tk
from tkinter import ttk, messagebox
import cv2
from PIL import Image, ImageTk, ImageDraw, ImageFont
from core import scale as core_scale
from core import camera as core_camera
from core import vision_api
from core import products as core_products
from core import label_printer
CONFIG_FILE = 'config.json'
FONT_BIG = ('Microsoft YaHei', 16)
FONT_HUGE = ('Microsoft YaHei', 44, 'bold')
FONT_MID = ('Microsoft YaHei', 13)
FONT_BTN = ('Microsoft YaHei', 14, 'bold')
def load_config():
with open(CONFIG_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
def save_config(cfg):
with open(CONFIG_FILE, 'w', encoding='utf-8') as f:
json.dump(cfg, f, ensure_ascii=False, indent=2)
class App:
def __init__(self, root):
self.root = root
root.title('入库分拣系统')
root.attributes('-fullscreen', True)
root.configure(bg='#f2f4f7')
root.bind('<Escape>', lambda e: root.attributes('-fullscreen', False))
self.cfg = load_config()
self.q_ui = queue.Queue()
self.state = 'idle' # idle | busy | confirming
self.need_clear_scale = False # 边沿触发:取走货后才能触发下一次
self.mode = tk.StringVar(value='inbound') # inbound | sorting
self.scale = core_scale.ScaleReader(self.cfg)
self.camera = core_camera.Camera(self.cfg)
self.store = core_products.ProductStore(self.cfg)
self.printer = label_printer.LabelPrinter(self.cfg)
self._build_ui()
self.scale.start()
self.camera.start()
self._cleanup_old_snapshots()
self.root.after(300, self._poll_scale)
self.root.after(150, self._poll_queue)
self._schedule_products_refresh()
self.log('系统启动。商品库 %d 条(缓存)' % len(self.store.names))
if self.scale.cfg.get('simulate'):
self.log('提示:当前为模拟秤模式(设置里可切换真实串口)')
# ================= 界面 =================
def _build_ui(self):
main = tk.Frame(self.root, bg='#f2f4f7')
main.pack(fill='both', expand=True, padx=12, pady=10)
# ---------- 左侧:重量 + 画面 ----------
left = tk.Frame(main, bg='#ffffff')
left.pack(side='left', fill='both', expand=True, padx=(0, 10))
top = tk.Frame(left, bg='#ffffff')
top.pack(fill='x', pady=8)
tk.Label(top, text='重量', font=FONT_MID, bg='#ffffff',
fg='#666').pack(side='left')
self.weight_var = tk.StringVar(value='0.000 kg')
tk.Label(top, textvariable=self.weight_var, font=FONT_HUGE,
bg='#ffffff', fg='#0a6cf1').pack(side='left', padx=20)
self.status_var = tk.StringVar(value='待机中…')
self.status_lbl = tk.Label(left, textvariable=self.status_var,
font=FONT_BIG, bg='#ffffff', fg='#333',
anchor='w')
self.status_lbl.pack(fill='x', pady=(0, 6))
self.preview_lbl = tk.Label(left, bg='#1a1a1a')
self.preview_lbl.pack(fill='both', expand=True)
self.root.after(80, self._poll_camera)
# ---------- 右侧:模式 + 操作 + 日志 ----------
right = tk.Frame(main, width=380, bg='#f2f4f7')
right.pack(side='right', fill='y')
right.pack_propagate(False)
# 模式切换(大按钮,触摸友好)
modef = tk.Frame(right, bg='#f2f4f7')
modef.pack(fill='x', pady=(0, 10))
self.mode_btn_in = tk.Button(
modef, text='入库模式', font=FONT_BTN, bd=0, cursor='hand2',
command=lambda: self._set_mode('inbound'), height=3)
self.mode_btn_in.pack(side='left', fill='x', expand=True, ipadx=8)
self.mode_btn_sort = tk.Button(
modef, text='分拣模式\n(打印标签)', font=FONT_BTN, bd=0,
cursor='hand2', command=lambda: self._set_mode('sorting'),
height=3)
self.mode_btn_sort.pack(side='left', fill='x', expand=True,
ipadx=8, padx=(8, 0))
self._set_mode('inbound')
btns = [
('手动抓拍识别', self.manual_flow, '#0a6cf1'),
('模拟上货(测试)', self.sim_put_item, '#7a5af8'),
('刷新商品库', self.refresh_products, '#0e9f6e'),
('设置', self.open_settings, '#5b6472'),
]
for text, cmd, color in btns:
b = tk.Button(right, text=text, font=FONT_BTN, bd=0,
bg=color, fg='white', activebackground=color,
activeforeground='white', cursor='hand2',
command=cmd, height=2)
b.pack(fill='x', pady=4)
tk.Label(right, text='运行日志', font=FONT_MID,
bg='#f2f4f7', fg='#666').pack(anchor='w', pady=(10, 2))
self.log_text = tk.Text(right, font=('Consolas', 11), height=12,
bg='#ffffff', bd=0, state='disabled',
wrap='word')
self.log_text.pack(fill='both', expand=True)
def _set_mode(self, m):
self.mode.set(m)
if m == 'inbound':
self.mode_btn_in.configure(bg='#0a6cf1', fg='white')
self.mode_btn_sort.configure(bg='#e3e7ee', fg='#333')
self.log('切换到【入库模式】:确认商品后仅记录,不打印标签')
else:
self.mode_btn_sort.configure(bg='#f59f0a', fg='white')
self.mode_btn_in.configure(bg='#e3e7ee', fg='#333')
self.log('切换到【分拣模式】:确认商品后将打印标签')
def _poll_camera(self):
frame = self.camera.get_frame()
if frame is not None:
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
h, w = rgb.shape[:2]
tw = 640
th = int(h * tw / w)
img = Image.fromarray(rgb).resize((tw, th))
self._tkimg = ImageTk.PhotoImage(img)
self.preview_lbl.configure(image=self._tkimg)
self.preview_lbl.image = self._tkimg
self.root.after(80, self._poll_camera)
def _poll_scale(self):
st = self.scale.state()
self.weight_var.set('%.3f kg' % st['weight'])
if st['error']:
self.status_var.set('秤连接异常:%s' % st['error'])
if self.state == 'idle' and self.cfg.get('auto_capture', True):
if st['stable'] and not self.need_clear_scale:
self.need_clear_scale = True
self.start_flow()
elif not st['present']:
self.need_clear_scale = False
self.root.after(300, self._poll_scale)
def _poll_queue(self):
try:
while True:
kind, payload = self.q_ui.get_nowait()
if kind == 'log':
self.log(payload)
elif kind == 'status':
self.status_var.set(payload)
elif kind == 'status_color':
self.status_lbl.configure(fg=payload)
elif kind == 'confirm':
self.show_confirm(payload)
elif kind == 'idle':
self.state = 'idle'
except queue.Empty:
pass
self.root.after(150, self._poll_queue)
def log(self, s):
ts = datetime.datetime.now().strftime('%H:%M:%S')
self.log_text.configure(state='normal')
self.log_text.insert('end', '[%s] %s\n' % (ts, s))
self.log_text.see('end')
self.log_text.configure(state='disabled')
def set_status(self, s, color='#333333'):
self.q_ui.put(('status', s))
self.q_ui.put(('status_color', color))
# ================= 业务流程 =================
def start_flow(self, manual=False):
if self.state != 'idle':
return
self.state = 'busy'
threading.Thread(target=self._flow_worker, daemon=True).start()
def manual_flow(self):
if self.state != 'idle':
return
self.need_clear_scale = True # 手动触发后同样等取货复位
self.start_flow()
def sim_put_item(self):
import random
self.scale.sim_put(round(random.uniform(0.5, 8.0), 3))
self.log('模拟:已放上一件货物,等待称重稳定…')
def _flow_worker(self):
st = self.scale.state()
weight = st['weight']
self.set_status('① 重量 %.3f kg 稳定,抓拍中…' % weight, '#0a6cf1')
# 识别图降采样到 1280(快速模式):缩短上传+推理时间
path = self.camera.snapshot(
max_px=int(self.cfg['vision'].get('recognition_image_max_px', 1280)))
if not path:
self.set_status('抓拍失败:无摄像头画面', '#e02424')
self.q_ui.put(('idle', None))
return
self.q_ui.put(('log', '已截图: %s' % path))
self.set_status('② AI 识别商品中…', '#0a6cf1')
vcfg = self.cfg['vision']
if not vcfg.get('api_key'):
self.set_status('未配置识别 API Key(请到 设置 -> 识别API)', '#e02424')
self.q_ui.put(('idle', None))
return
try:
detected = vision_api.vision_identify(vcfg, path)
except Exception as e:
self.set_status('识别失败:%s' % e, '#e02424')
self.q_ui.put(('idle', None))
return
if not detected:
self.set_status('AI 未识别出商品名称', '#e02424')
self.q_ui.put(('idle', None))
return
self.q_ui.put(('log', 'AI 识别结果: %s' % detected))
# ③ 精确匹配
self.set_status('③ 匹配商品名单中…', '#0a6cf1')
hit = self.store.match_exact(detected)
if hit:
self._finish_confirmed(weight, detected, hit, '自动匹配', path)
return
# ④ 大模型核查同物异名(先模糊预筛候选,控制 token)
candidates = self.store.fuzzy(detected, topn=8)
if not candidates:
candidates = self.store.names[:int(
self.cfg['products'].get('llm_candidate_limit', 80))]
self.set_status('④ 大模型核查"同物异名"中…', '#0a6cf1')
try:
m2, reason = vision_api.llm_match_name(vcfg, detected, candidates)
except Exception as e:
m2, reason = None, '大模型核查失败: %s' % e
if m2:
self.q_ui.put(('log', '大模型核查: %s ≈ %s(%s)' % (detected, m2, reason)))
self._finish_confirmed(weight, detected, m2, '大模型核查', path)
return
# ⑤ 人工确认
self.q_ui.put(('log', '未能自动匹配(%s),转人工确认' % reason))
self.set_status('⑤ 需要人工确认', '#f59f0a')
self.q_ui.put(('confirm', {
'weight': weight, 'detected': detected,
'snapshot': path, 'candidates': self.store.fuzzy(detected, topn=12),
}))
def _finish_confirmed(self, weight, detected, matched, method, snapshot):
self.q_ui.put(('log', '✔ 确认商品: %s(方式: %s)' % (matched, method)))
self._record(weight, detected, matched, method, snapshot)
self.set_status('完成:%s,请取走货物' % matched, '#0e9f6e')
self.q_ui.put(('idle', None))
def _record(self, weight, detected, matched, method, snapshot):
rf = self.cfg.get('record_file', 'data/records.csv')
os.makedirs(os.path.dirname(rf) or '.', exist_ok=True)
new = not os.path.exists(rf)
with open(rf, 'a', newline='', encoding='utf-8-sig') as f:
w = csv.writer(f)
if new:
w.writerow(['时间', '模式', '重量kg', 'AI识别名称',
'确认商品', '确认方式', '截图'])
w.writerow([datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'分拣' if self.mode.get() == 'sorting' else '入库',
weight, detected, matched, method, snapshot])
# 分拣模式才打印标签
if self.mode.get() == 'sorting':
ok, msg = self.printer.print_label(matched, weight)
self.q_ui.put(('log', '标签打印: %s' % msg))
else:
self.q_ui.put(('log', '入库模式:不打印标签'))
# ---------- 人工确认弹窗 ----------
def show_confirm(self, payload):
self.state = 'confirming'
top = tk.Toplevel(self.root)
top.title('人工确认')
top.attributes('-fullscreen', True)
top.configure(bg='#f2f4f7')
left = tk.Frame(top, bg='#ffffff')
left.pack(side='left', fill='both', expand=True, padx=12, pady=12)
tk.Label(left, text='AI 识别结果不确定,请人工确认', font=FONT_BIG,
bg='#ffffff', fg='#e02424').pack(pady=8)
img_lbl = tk.Label(left, bg='#1a1a1a')
img_lbl.pack(pady=6)
try:
img = Image.open(payload['snapshot'])
w, h = img.size
tw = 560
img = img.resize((tw, int(h * tw / w)))
tkimg = ImageTk.PhotoImage(img)
img_lbl.configure(image=tkimg)
img_lbl.image = tkimg
except Exception:
pass
tk.Label(left, text='AI识别: %s 重量: %.3f kg'
% (payload['detected'], payload['weight']),
font=FONT_BIG, bg='#ffffff').pack(pady=6)
right = tk.Frame(top, bg='#f2f4f7')
right.pack(side='right', fill='both', padx=12, pady=12)
tk.Label(right, text='从商品名单选择(点击候选直接确认):',
font=FONT_MID, bg='#f2f4f7').pack(anchor='w')
search_var = tk.StringVar()
e = tk.Entry(right, textvariable=search_var, font=FONT_BIG,
width=22, relief='solid')
e.pack(fill='x', pady=6, ipady=6)
listbox = tk.Listbox(right, font=FONT_BIG, selectmode='single',
activestyle='none')
listbox.pack(fill='both', expand=True, pady=6)
def fill_list():
q = core_products.normalize(search_var.get())
names = self.store.names
if q:
names = [n for n in names
if q in core_products.normalize(n)][:50]
elif payload['candidates']:
names = payload['candidates'] + \
[n for n in self.store.names
if n not in payload['candidates']][:50]
else:
names = names[:50]
listbox.delete(0, 'end')
for n in names:
listbox.insert('end', n)
search_var.trace_add('write', lambda *a: fill_list())
fill_list()
def do_confirm(_event=None):
sel = listbox.curselection()
if sel:
name = listbox.get(sel[0])
elif search_var.get().strip():
name = search_var.get().strip()
else:
messagebox.showwarning('提示', '请先选择或输入商品名称',
parent=top)
return
self._finish_confirmed(payload['weight'], payload['detected'],
name, '人工确认', payload['snapshot'])
top.destroy()
def do_cancel():
self.q_ui.put(('log', '人工确认:已放弃(%s)' % payload['detected']))
self.set_status('已放弃,请取走货物', '#5b6472')
self.q_ui.put(('idle', None))
top.destroy()
btnf = tk.Frame(right, bg='#f2f4f7')
btnf.pack(fill='x', pady=8)
tk.Button(btnf, text='✔ 确认入库', font=FONT_BTN, bd=0,
bg='#0e9f6e', fg='white', height=3, cursor='hand2',
command=do_confirm).pack(side='left', fill='x',
expand=True, ipadx=10)
tk.Button(btnf, text='✘ 放弃', font=FONT_BTN, bd=0,
bg='#e02424', fg='white', height=3, cursor='hand2',
command=do_cancel).pack(side='left', fill='x',
expand=True, ipadx=10,
padx=(10, 0))
listbox.bind('<Double-Button-1>', do_confirm)
e.bind('<Return>', do_confirm)
# ---------- 商品库 ----------
def refresh_products(self):
self.log('正在从系统接口刷新商品库…')
def worker():
try:
n = self.store.refresh()
self.q_ui.put(('log', '商品库刷新成功,共 %d 条' % n))
except Exception as e:
self.q_ui.put(('log', '商品库刷新失败: %s(使用本地缓存 %d 条)'
% (e, len(self.store.names))))
threading.Thread(target=worker, daemon=True).start()
def _schedule_products_refresh(self):
mins = int(self.cfg['products'].get('refresh_minutes', 30))
if mins > 0 and self.cfg['products'].get('api_url'):
self.refresh_products()
self.root.after(max(mins, 1) * 60000, self._schedule_products_refresh)
# ---------- 设置 ----------
def open_settings(self):
s = tk.Toplevel(self.root)
s.title('设置')
s.geometry('560x640')
s.configure(bg='#f2f4f7')
rows = []
def add(label, key_path, default='', secret=False, choice=None):
tk.Label(s, text=label, font=FONT_MID, bg='#f2f4f7').pack(
anchor='w', padx=16, pady=(8, 0))
var = tk.StringVar(value=str(self._cfg_get(key_path, default)))
if choice:
w = ttk.Combobox(s, textvariable=var, values=choice,
state='readonly', font=FONT_MID)
else:
w = tk.Entry(s, textvariable=var, font=FONT_MID,
show='*' if secret else '', relief='solid')
w.pack(fill='x', padx=16, ipady=4)
rows.append((key_path, var))
def add_bool(label, key_path):
tk.Label(s, text=label, font=FONT_MID, bg='#f2f4f7').pack(
anchor='w', padx=16, pady=(8, 0))
var = tk.BooleanVar(value=bool(self._cfg_get(key_path, False)))
tk.Checkbutton(s, text='启用', variable=var,
font=FONT_MID, bg='#f2f4f7').pack(anchor='w', padx=16)
rows.append((key_path, var))
tk.Label(s, text='—— 电子秤 ——', font=FONT_MID, fg='#0a6cf1',
bg='#f2f4f7').pack(anchor='w', padx=16, pady=(10, 0))
add_bool('模拟秤模式(无秤调试用)', 'scale.simulate')
add('串口号', 'scale.port')
add('波特率', 'scale.baudrate')
add('最小触发重量(kg)', 'scale.min_weight_kg')
tk.Label(s, text='—— 摄像头 ——', font=FONT_MID, fg='#0a6cf1',
bg='#f2f4f7').pack(anchor='w', padx=16, pady=(10, 0))
add_bool('模拟摄像头模式', 'camera.simulate')
add('摄像头序号', 'camera.index')
tk.Label(s, text='—— 识别API ——', font=FONT_MID, fg='#0a6cf1',
bg='#f2f4f7').pack(anchor='w', padx=16, pady=(10, 0))
add('厂商(选择后自动填地址/模型)', 'vision.provider',
choice=['qwen', 'glm', 'doubao', 'custom'])
add('API Key', 'vision.api_key', secret=True)
add('接口地址', 'vision.base_url')
add('视觉模型', 'vision.vision_model')
add('文本模型', 'vision.text_model')
tk.Label(s, text='—— 商品接口 ——', font=FONT_MID, fg='#0a6cf1',
bg='#f2f4f7').pack(anchor='w', padx=16, pady=(10, 0))
add('接口地址(GET)', 'products.api_url')
add('名称字段', 'products.name_field')
add('数据路径(如 data.list,可空)', 'products.data_path')
tk.Label(s, text='—— 标签打印机 ——', font=FONT_MID, fg='#0a6cf1',
bg='#f2f4f7').pack(anchor='w', padx=16, pady=(10, 0))
add_bool('启用打印(仅分拣模式生效)', 'printer.enabled')
add('指令类型', 'printer.type', choice=['tspl', 'zpl'])
add('Windows打印机名称(控制面板里查看)', 'printer.printer_name')
add('标签宽mm', 'printer.width_mm')
add('标签高mm', 'printer.height_mm')
def do_save():
for key_path, var in rows:
v = var.get()
if isinstance(v, bool):
pass
elif v in ('True', 'False'):
pass
self._cfg_set(key_path, v)
# 类型修正
for path, typ in [('scale.baudrate', int),
('scale.min_weight_kg', float),
('camera.index', int),
('printer.width_mm', int),
('printer.height_mm', int)]:
try:
self._cfg_set(path, typ(self._cfg_get(path)))
except Exception:
pass
for path in ['scale.simulate', 'camera.simulate', 'printer.enabled']:
self._cfg_set(path, bool(self._cfg_get(path)))
if self._cfg_get('vision.provider') != 'custom':
vision_api.apply_provider(self.cfg['vision'],
self._cfg_get('vision.provider'))
save_config(self.cfg)
messagebox.showinfo('已保存',
'设置已保存。串口/摄像头等硬件参数重启程序后生效。',
parent=s)
s.destroy()
tk.Button(s, text='保 存', font=FONT_BTN, bd=0, bg='#0a6cf1',
fg='white', height=2, cursor='hand2',
command=do_save).pack(fill='x', padx=16, pady=14)
def _cfg_get(self, path, default=None):
cur = self.cfg
for p in path.split('.'):
if isinstance(cur, dict) and p in cur:
cur = cur[p]
else:
return default
return cur
def _cfg_set(self, path, value):
parts = path.split('.')
cur = self.cfg
for p in parts[:-1]:
cur = cur.setdefault(p, {})
cur[parts[-1]] = value
# ---------- 杂项 ----------
def _cleanup_old_snapshots(self):
days = int(self.cfg.get('snapshot_keep_days', 30))
if days <= 0:
return
cutoff = datetime.datetime.now().timestamp() - days * 86400
d = self.cfg.get('capture_dir', 'data/snapshots')
if not os.path.isdir(d):
return
n = 0
for fn in os.listdir(d):
p = os.path.join(d, fn)
try:
if os.path.getmtime(p) < cutoff:
os.remove(p)
n += 1
except OSError:
pass
if n:
self.log('已清理 %d 张超过 %d 天的历史截图' % (n, days))
if __name__ == '__main__':
root = tk.Tk()
App(root)
root.mainloop()