204 lines
7.2 KiB
Python
204 lines
7.2 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""匹配引擎:单位换算 / 商品身份 / 候选行选择 / 容差 / 同义词预筛。
|
||
|
||
对齐安卓版 WeighStationMatcher + NameMatcher:
|
||
- 斤×2、克×1000、公斤×1、空单位默认按斤(现场约定)
|
||
- 双非空 SKU 必须精确相等;一方有一方无 → 不是同一商品
|
||
- 应量不同 → 重量误差最小优先;相同 → order_code → sort_order
|
||
- 非重量单位(件/箱/桶…)canScaleDetermineQty=False,禁止用秤读数
|
||
"""
|
||
|
||
# 现场同义词条(大模型核查前预筛候选,保证 土豆→马铃薯 可召回)
|
||
SYNONYMS = {
|
||
'土豆': ['马铃薯', '洋芋'], '马铃薯': ['土豆', '洋芋'],
|
||
'洋芋': ['土豆', '马铃薯'],
|
||
'番茄': ['西红柿'], '西红柿': ['番茄'],
|
||
'包菜': ['卷心菜', '圆白菜', '包心菜'],
|
||
'卷心菜': ['包菜', '圆白菜'], '圆白菜': ['包菜', '卷心菜'],
|
||
'包心菜': ['包菜', '卷心菜'],
|
||
'奇异果': ['猕猴桃'], '猕猴桃': ['奇异果'],
|
||
'地瓜': ['红薯', '番薯'], '红薯': ['地瓜', '番薯'], '番薯': ['地瓜', '红薯'],
|
||
'玉米': ['苞谷', '苞米'], '苞谷': ['玉米'], '苞米': ['玉米'],
|
||
'香菜': ['芫荽'], '芫荽': ['香菜'],
|
||
'凤梨': ['菠萝'], '菠萝': ['凤梨'],
|
||
'菜花': ['花菜', '花椰菜'], '花菜': ['菜花', '花椰菜'],
|
||
'花椰菜': ['菜花', '花菜'],
|
||
}
|
||
|
||
NON_WEIGHT_UNITS = ('件', '箱', '桶', '包', '袋', '只', '个', '瓶', '盒', '扎')
|
||
|
||
|
||
def normalize(s):
|
||
return ''.join(str(s or '').split()).lower()
|
||
|
||
|
||
def is_jin_unit(unit):
|
||
return normalize(unit) in ('斤', '市斤')
|
||
|
||
|
||
def is_gram_unit(unit):
|
||
return normalize(unit) in ('克', 'g')
|
||
|
||
|
||
def is_weight_unit(unit):
|
||
u = normalize(unit)
|
||
if not u:
|
||
return True # 空单位默认按斤(现场约定)
|
||
if is_jin_unit(unit) or is_gram_unit(unit):
|
||
return True
|
||
return u in ('kg', '公斤', '千克', 'kilogram')
|
||
|
||
|
||
def unit_not_weighable_reason(unit):
|
||
if can_scale_determine_qty(unit):
|
||
return None
|
||
return '商品单位为「%s」,不能用秤读数当数量(否则 0.8kg 会提交成 0.8 %s)' \
|
||
% (unit, unit)
|
||
|
||
|
||
def can_scale_determine_qty(unit):
|
||
return is_weight_unit(unit)
|
||
|
||
|
||
def is_independent_inbound(row):
|
||
"""这一行是不是「独立入库 / 无单入库」(没有订单收货链)
|
||
|
||
服务端在待验行里就是这么标的:
|
||
processing_details: {"purchase_code": "RAW...", "independent_inbound": true}
|
||
order_code: null
|
||
这类行走的是另一个接口(/mobile/inventory/stock-in,按 SKU 直接进库存),
|
||
拿它去调「有单验收」的 merge-scope-preview / complete-merge-strict,
|
||
服务端会回 400 independent_inbound_not_mergeable。
|
||
客户端不做这个区分时,现场的表现就是:称重→识别→提交→被拒→超时→
|
||
再称→再提交,每 12 秒一轮死循环,整台机连正常有单的货也收不了。
|
||
"""
|
||
if not isinstance(row, dict):
|
||
return False
|
||
d = row.get('processing_details')
|
||
if isinstance(d, dict) and d.get('independent_inbound'):
|
||
return True
|
||
if isinstance(d, str) and 'independent_inbound' in d:
|
||
# 少数环境这个字段是 JSON 字符串
|
||
return '"independent_inbound":true' in d.replace(' ', '')
|
||
# 兜底:没有任何订单号、来源是采购直入
|
||
if row.get('independent_inbound'):
|
||
return True
|
||
return False
|
||
|
||
|
||
def scale_kg_to_business(weight_kg, unit):
|
||
if not weight_kg or weight_kg <= 0:
|
||
return 0.0
|
||
if is_jin_unit(unit):
|
||
return weight_kg * 2.0
|
||
if is_gram_unit(unit):
|
||
return weight_kg * 1000.0
|
||
if not normalize(unit):
|
||
return weight_kg * 2.0
|
||
return weight_kg
|
||
|
||
|
||
def same_product_identity(a, b):
|
||
"""a/b 为行 dict,含 sku_code / item_name"""
|
||
sa, sb = (a.get('sku_code') or '').strip(), (b.get('sku_code') or '').strip()
|
||
if sa and sb:
|
||
return sa == sb
|
||
if sa or sb:
|
||
return False # 一边有 SKU 一边没有:不猜
|
||
return normalize(a.get('item_name')) == normalize(b.get('item_name'))
|
||
|
||
|
||
def required_qty_of(row, mode=None):
|
||
"""本行“还差多少”:待验行优先 remaining_qty(分批累计后剩余待收),
|
||
没有才退回 required_qty / prepare_qty;待拣行一般只有 required_qty。
|
||
|
||
用 prepare_qty 判超差会在“第二次分批收货”时必然超差(计划 100 斤、
|
||
已收 60 斤、这次称 40 斤 → 拿 40 比 100),现场表现为误拦自动提交。
|
||
"""
|
||
for k in ('remaining_qty', 'required_qty', 'prepare_qty'):
|
||
v = row.get(k)
|
||
if v is None or v == '':
|
||
continue
|
||
try:
|
||
return float(v)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
return 0.0
|
||
|
||
|
||
def pick_best(rows, business_weight):
|
||
"""候选行选择:误差最小优先 → order_code 升序 → sort_order 升序"""
|
||
def key(r):
|
||
req = required_qty_of(r, None)
|
||
return (abs(req - business_weight),
|
||
str(r.get('order_code') or ''),
|
||
int(r.get('sort_order') or 0))
|
||
return sorted(rows, key=key)[0] if rows else None
|
||
|
||
|
||
def allowed_diff(mode, value, required_qty):
|
||
if not value or value <= 0:
|
||
return float('inf') # value<=0 = 服务端关闭校验
|
||
if mode == 'absolute':
|
||
return float(value)
|
||
return abs(required_qty) * (float(value) / 100.0)
|
||
|
||
|
||
def within_tolerance(required_qty, actual_qty, mode, value):
|
||
if not value or value <= 0:
|
||
return True
|
||
return abs(actual_qty - required_qty) <= \
|
||
allowed_diff(mode, value, required_qty) + 1e-9
|
||
|
||
|
||
def expand_terms(q):
|
||
"""查询词 + 同义词扩展"""
|
||
q = normalize(q)
|
||
terms = [q]
|
||
for k, vs in SYNONYMS.items():
|
||
if k in q or any(v in q for v in vs):
|
||
terms += [k] + vs
|
||
return [t for t in terms if t]
|
||
|
||
|
||
def match_rows_by_name(rows, detected_name):
|
||
"""名称匹配待办行:完全相同 > 互相包含(对齐 NameMatcher 分层)"""
|
||
q = normalize(detected_name)
|
||
if not q:
|
||
return []
|
||
exact, contains = [], []
|
||
for r in rows:
|
||
n = normalize(r.get('item_name'))
|
||
if n == q:
|
||
exact.append(r)
|
||
elif n and (q in n or n in q):
|
||
contains.append(r)
|
||
return exact + contains
|
||
|
||
|
||
def fuzzy_candidates(rows, detected_name, topn=12):
|
||
"""同义词/包含优先的候选行(供大模型核查与人工界面)"""
|
||
q = normalize(detected_name)
|
||
terms = expand_terms(detected_name)
|
||
contains = [r for r in rows
|
||
if any(t in normalize(r.get('item_name'))
|
||
or normalize(r.get('item_name')) in t
|
||
for t in terms)]
|
||
exact = match_rows_by_name(rows, detected_name)
|
||
seen, out = set(), []
|
||
for r in exact + contains:
|
||
if r.get('id') not in seen:
|
||
seen.add(r.get('id'))
|
||
out.append(r)
|
||
if len(out) < topn:
|
||
import difflib
|
||
names = {normalize(r.get('item_name')): r for r in rows}
|
||
close = difflib.get_close_matches(q, list(names.keys()),
|
||
n=topn, cutoff=0.4)
|
||
for c in close:
|
||
r = names[c]
|
||
if r.get('id') not in seen:
|
||
seen.add(r.get('id'))
|
||
out.append(r)
|
||
return out[:topn]
|