feat(match): 落地搜索匹配口径四件套与次精确名称护栏,同步字集键入库及测试面板改进

This commit is contained in:
lianjianwei2024
2026-10-10 14:58:13 +08:00
parent a3697ba271
commit 6de1370ce5
12 changed files with 940 additions and 286 deletions

View File

@@ -8,6 +8,7 @@ M1 原型:把「后台需要导入的项目」里的 15 个真实文件解析
- 只保留需要的字段,其余丢弃
"""
import io, os, re, sys, time, json, hashlib, zipfile, sqlite3
import match # 比对引擎:字集键 bill_setkey/lme_setkey 唯一实现(决策 27,口径不分叉)
from xml.etree import ElementTree as ET
# 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径)
@@ -492,8 +493,10 @@ def save(con, kind, out, fn, sha, mtime, meta=None):
seq = {"d": 0, "p": 0}
# bills 元组第 8 位 = 源文件备注(2026-10-08 主人定:只显示在「原数据」备注栏)
for i, (num, name, attr, unit, qty, price, total, srk) in enumerate(out["bills"]):
h = md5(num, name, unit) # 精确键:编码+名称+单位(特征写法太杂,不参与)
hs = md5(num, unit)
# 决策 27(2026-10-10):编码只取前 9 位参与哈希(后 3 位是项目内顺序码,无对比意义)
num9 = norm(num)[:9]
h = md5(num9, name, unit) # 精确键:编码9位+名称+单位(特征写法太杂,不参与)
hs = md5(num9, unit)
k = buw[i] if i < len(buw) else -1
uwid = uw_ids[k] if 0 <= k < len(uw_ids) else None
kb = bkd[i] if i < len(bkd) else None
@@ -505,10 +508,10 @@ def save(con, kind, out, fn, sha, mtime, meta=None):
divid = div_ids[_dv] if (_dv is not None and 0 <= _dv < len(div_ids)) else None
cur.execute("""INSERT INTO bills(batch_id, uw_id, div_id, Number, Name, Attr, Unit,
Quantity, Price, Total, Kind, src_remark,
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_seq)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_name_norm, x_attr_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey, x_seq)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, uwid, divid, num, name, attr, unit, qty, price, total, kb, srk,
norm(name), clean_attr(attr), norm(unit), h, hs, xseq))
norm(name), clean_attr(attr), norm(unit), h, hs, match.bill_setkey(name, unit), xseq))
n_bill += 1
bill_ids.append(cur.lastrowid)
seen_bill.add(h)
@@ -535,10 +538,11 @@ def save(con, kind, out, fn, sha, mtime, meta=None):
try:
cur.execute("""INSERT OR IGNORE INTO lmes(batch_id, Number, Name, Specification, Unit,
Quantity, NoTaxPrice, TaxRate, TaxPrice, Kind,
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_hash_semi, x_setkey)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(bid, num, name, spec, unit, qty, ntp, tax, tp, _kind,
norm(name), norm(spec), norm(unit), h, md5(name, unit)))
norm(name), norm(spec), norm(unit), h, md5(name, unit),
match.lme_setkey(name, spec, unit)))
n_lme += cur.rowcount
except Exception:
n_lme_errs += 1

View File

@@ -11,9 +11,14 @@
4. 结果按「距基准先近后远」排序,同距按档位(精确>次精确>模糊)
5. 信息价/市场价的结果行带**原文件字段**(可打开附件 PDF)
"""
import sqlite3, re, os, threading
import sqlite3, re, threading
SIM_MIN = 0.60
# 次精确名称护栏(2026-10-10 主人定):清单次精确 = 编码+单位,而国标编码末 3 位是项目内
# 顺序号,不同项目把不同设备编到同码同单位很常见(实例:030507008001/台 一边是高空抛物
# 摄像枪、一边是 LED 补光灯)。名称(匹配归一后)字符 Jaccard 低于该值的次精确命中不算
# 同一清单项,剔除。精确档哈希含名称、工料机/价格次精确 = 名称+单位,都不受影响。
SEMI_NAME_MIN = 0.2
def lme_list_where(prefix=""):
@@ -108,6 +113,64 @@ def jaccard(a, b):
return len(A & B) / len(A | B)
# ---------- 字集键 / 加权相似度(2026-10-10 决策 27 主人定) ----------
def set_norm(s):
"""字集归一:归一后按字符排序——顺序无关的等价串,「钢筋混凝土」与「混凝土钢筋」同串。"""
return "".join(sorted(norm(s)))
def bill_setkey(name, unit):
"""清单字集键(存 bills.x_setkey):名称字集 + 单位——名称不按排序等价、单位一致。"""
return set_norm(name) + "|" + norm(unit)
def lme_setkey(name, spec, unit):
"""工料机字集键(存 lmes.x_setkey):名称+规格**合并成一个池**再排序(主人 2026-10-10 定
「名称+规格型号作为一个整体、不按排序匹配」)+ 单位。"""
return set_norm((name or "") + (spec or "")) + "|" + norm(unit)
# 特征里的排序序号——只是排版顺序,剥掉不参与匹配(2026-10-10 主人定)。
# ⚠️ 在 norm() 之后套用(小写、全角括号已转半角、空白已去)。「前面的字符不是字母/数字/点」
# 负向断言保证 IP67、2.8mm、42.5 这类**正文数字**不被误剥——序号前的邻居是文字或开头。
_ORD = re.compile(r"[①-⑳]"
r"|([0-9]{1,3})|\([0-9]{1,3}\)"
r"|(?<![a-z0-9.])[0-9]{1,3}、"
r"|(?<![a-z0-9.])[0-9]{1,2}[..](?![0-9])"
r"|(?<![a-z0-9])[a-zA-Z][、))]")
def norm_attr(s):
"""项目特征/规格的匹配归一:norm 基础上剥掉**排序序号**(1、 2. (3) a) ①——
正文里的数字字母(IP67、2.8mm、C30)原样保留(小数点后跟数字不剥)。再剥过滤词。"""
s2 = _ORD.sub("", norm(s))
for w in getattr(_tls, "stopwords", ()):
if w:
s2 = s2.replace(w, "")
return s2
# 字母数字身份 token(含小数点/斜杠/连字符/乘号/直径符)
_TOK = re.compile(r"[a-z0-9φ][a-z0-9φ./*\-]*")
def sim_weighted(qname, hname, qattr, hattr):
"""模糊档加权相似度(2026-10-10 决策 27 主人定):
0.7×名称字集Jaccard + 0.3×特征字集Jaccard —— 名称优先于项目特征;
字母数字优于文字:查询**名称**里的字母数字 token(400、C30、IP67)在候选
(名称+特征)里找不到 → 一票否决返回 0;查询**特征**里的 token 缺失 → 特征得分减半。
中文按字符集合(不按排序)。入参都是归一后的串。"""
hay = hname + hattr
if any(t not in hay for t in _TOK.findall(qname)):
return 0.0
# 两边都没写特征 → 特征维度按满分(不惩罚);一边有一边没有才正常算
a = jaccard(qattr, hattr) if (qattr or hattr) else 1.0
if any(t not in hay for t in _TOK.findall(qattr)):
a *= 0.5
return 0.7 * jaccard(qname, hname) + 0.3 * a
def _filters(kinds, units, classes, prefix="bt", self_src=None, area=None, orgs=None):
"""生成批次级筛选 SQL(默认全选=不筛)
self_src:被审工程的源文件名 —— 同一个文件若也在历史库里,排除掉(避免自己跟自己比)
@@ -184,14 +247,43 @@ def _kw_like(col):
return "LOWER(%s)" % e
def _stem(name):
"""文件名去扩展名后的前 12 个字,用于判断"是不是同一工程"""
if not name:
return ""
b = os.path.basename(str(name))
b = re.sub(r"^[0-9a-f]{64}_", "", b) # 去掉上传时加的 sha256 前缀
b = os.path.splitext(b)[0]
return b[:12]
def _kw_conds(fields, kw, where_out, args_out):
"""关键字检索条件(2026-10-10 决策 27「不按排序匹配」):每个词拆成
字母数字段(C30、400、P.O——保持原样要求子串)+ 中文单字(逐字在场即可),
各要求之间 AND、字段之间 OR。「混凝土钢筋」从此能命中「钢筋混凝土」。"""
for t in (kw or "").split():
if not t:
continue
t = _kw_fold(t)
reqs = ["%" + r + "%" for r in _TOK.findall(t)]
reqs += ["%" + c + "%" for c in sorted({c for c in re.sub(r"[a-z0-9φ./*\-]", "", t)})]
per = []
for pat in reqs:
per.append("(" + " OR ".join("%s LIKE ?" % _kw_like(f) for f in fields) + ")")
args_out.extend([pat] * len(fields))
if per:
where_out.append("(" + " AND ".join(per) + ")")
def _self_filter(rows, self_name, self_src):
"""排除「被审工程自己」(2026-10-10 主人定收紧口径):只认
① 同一份文件 —— 批次 x_src_hash 与会话源文件名完全相同(同一文件导入两边);
② 项目名与会话名完全相同。
原「文件名主干前 12 字」启发式删除:同项目的另一版本(.cos / .cos4、改名副本)是
不同文件,正是最要比对的对象,不该整批隐藏(实例:SX-18 前台 cos 副本 vs 后台 cos4,
摄像枪真命中被藏,只剩另一项目的 LED 补光灯)。"""
nm = (self_name or "").strip()
src = (self_src or "").strip()
if not nm and not src:
return rows
out = []
for r in rows:
if src and (r.get("src_hash") or "").strip() == src:
continue
if nm and (r.get("proj") or "").strip() == nm:
continue
out.append(r)
return out
def _in_period(r, pfrom, pto):
@@ -218,15 +310,18 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
"""row: sqlite Row of s_bills"""
c = hist.cursor()
w, args = _filters(kinds, units, [], self_src=self_src, area=area) # classes 只对价格库有意义,清单比对不筛目录
out = []
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)
out, seen_ids, qn = [], set(), norm_match(row["Name"])
# L0 精确:编码+名称+单位(b.id 带回 → 前端展开定额 / 右栏「定额编码·名称」用)。
# 2026-10-10 决策 27:哈希里的编码只取前 9 位(后 3 位是项目内顺序码,没有对比意义),
# 口径变更由启动迁移 migrate_match_keys 重算存量,导入侧 import_job 同步。
sql = """SELECT '精确' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
bt.x_province, bt.x_city, bt.x_district
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE b.x_hash_exact=? AND bt.kind='project' AND %s LIMIT ?""" % w
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
# L1 次精确:编码+单位
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
d = dict(x); out.append(d); seen_ids.add(d["id"])
# L1 次精确:编码+单位(名称护栏 = SEMI_NAME_MIN,挡同码不同物)
if len(out) < limit:
sql2 = sql.replace("x_hash_exact", "x_hash_semi").replace("'精确'", "'次精确'")
seen = {(x["Name"], x["Attr"]) for x in out}
@@ -234,10 +329,27 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
d = dict(x)
if (d["Name"], d["Attr"]) in seen:
continue
if jaccard(qn, norm_match(d["Name"])) < SEMI_NAME_MIN:
continue
if len(out) >= limit:
break
out.append(d); seen.add((d["Name"], d["Attr"]))
# L2 模糊:名称+特征 相似度
out.append(d); seen.add((d["Name"], d["Attr"])); seen_ids.add(d["id"])
# L1.5 字集精确(2026-10-10 决策 27):名称字集+单位等价——「钢筋混凝土」=「混凝土钢筋」,
# 不按排序的严格命中;键 = bills.x_setkey(导入落列,老库启动迁移回填)。
if len(out) < limit:
sqlk = """SELECT '字集' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj,
bt.x_period_start_m p1, bt.x_period_end_m p2, bt.FileKind, bt.BulidUnit, bt.x_src_hash src,
bt.x_province, bt.x_city, bt.x_district
FROM bills b JOIN batches bt ON bt.id=b.batch_id
WHERE b.x_setkey=? AND bt.kind='project' AND %s LIMIT ?""" % w
for x in c.execute(sqlk, [bill_setkey(row["Name"], row["Unit"])] + args + [limit]):
d = dict(x)
if d["id"] in seen_ids:
continue
if len(out) >= limit:
break
out.append(d); seen_ids.add(d["id"])
# L2 模糊:加权相似度(0.7×名称 + 0.3×特征,字母数字身份规则见 sim_weighted)
if len(out) < limit:
q = norm_match(row["Name"])[:6]
if q:
@@ -249,10 +361,13 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
for x in c.execute(sql3, args + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
sim = jaccard(norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(x["Name"]) + norm_match(x["Attr"]))
if x["id"] in seen_ids:
continue
sim = sim_weighted(qn, norm_match(x["Name"]),
norm_attr(row["Attr"]), norm_attr(x["Attr"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"
out.append(d)
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
out.append(d); seen_ids.add(x["id"])
if len(out) >= limit:
break
res = []
@@ -265,17 +380,14 @@ def match_bill(hist, row, base, kinds, units, classes, limit=20, srcs=None, pfro
"period": ym(nearest(d["p1"], d["p2"], bf)),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": 1.0 if d["tier"] != "模糊" else round(jaccard(
norm_match(row["Name"]) + norm_match(row["Attr"]), norm_match(d["Name"]) + norm(d["Attr"])), 2),
"sim": (1.0 if d["tier"] in ("精确", "字集") else
round(d["_sim"], 2) if "_sim" in d else
round(jaccard(qn, norm_match(d["Name"])), 2)), # 次精确=真实名称相似度(决策 27 E)
"src": "工程", "file": "", "src_hash": d.get("src") or "",
})
res = [r for r in res if _in_period(r, pfrom, pto)]
ss = _stem(self_src) # 被审工程源文件名主干(前 12 字)
if ss or self_name: # 排除"被审工程自己"
res = [r for r in res
if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss)
and not (self_name and (r["proj"] or "").strip() == self_name.strip())]
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[r["tier"]]))
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
return res[:limit]
@@ -287,27 +399,22 @@ def hist_search(hist, kinds, units, area, pfrom, pto, kw, limit=200, self_name=N
· dist=0、排序由本函数做好(期次先近后远),前端不再按 dist 重排。
期次条件=区间重叠语义:批次的 [起,止] 与所选 [起,止] 有交集即命中(检索没有"基准期")。
self_name/self_src:被审工程自己(若它也入库了)**排除**(2026-10-08 主人定),
判定与 match_bill/match_lme 同一套:源文件主干相同(_stem 前 12 字)或项目名相同。
判定与 match_bill/match_lme 同一套(_self_filter 口径):同一份文件(x_src_hash 相同)
或项目名相同。
page:分页(2026-10-08 主人定,每页=limit 条,第 N 页 OFFSET (N-1)×limit)。"""
c = hist.cursor()
cond, args = _filters(kinds, units, [], prefix="bt") # 批次级条件(拼好的 SQL 串 + 参数)
extra = []
ss = _stem(self_src) if self_src else ""
nm = (self_name or "").strip()
if ss or nm:
src = (self_src or "").strip()
if src or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches WHERE kind='project'").fetchall()
if (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)]
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
if self_ids:
extra.append("bt.id NOT IN (%s)" % ",".join("?" * len(self_ids)))
args = args + self_ids
for t in (kw or "").split():
if not t:
continue
pat = "%" + _kw_fold(t) + "%" # 检索词折叠(同 hist_search_lme,符号变体一视同仁)
extra.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)"
% (_kw_like("b.Name"), _kw_like("b.Attr"), _kw_like("b.Unit")))
args = args + [pat] * 3
_kw_conds(["b.Name", "b.Attr", "b.Unit"], kw, extra, args) # 不按排序(决策 27):φ 等折叠在 _kw_conds 内
if pfrom is not None:
extra.append("bt.x_period_end_m >= ?")
args = args + [pfrom]
@@ -363,22 +470,16 @@ def hist_search_lme(hist, orgs=None, area=None, pfrom=None, pto=None, kw="", pmi
cond, cargs = _filters(kinds or [], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs)
condp, cargsp = _filters([], [], [], prefix="bt", self_src=self_src, area=area, orgs=orgs)
outer, oargs = [], []
ss = _stem(self_src) if self_src else ""
nm = (self_name or "").strip()
if ss or nm:
src = (self_src or "").strip()
if src or nm:
self_ids = [r[0] for r in c.execute(
"SELECT id, Name, x_src_hash FROM batches").fetchall()
if (ss and _stem(r[2] or "") == ss) or (nm and (r[1] or "").strip() == nm)]
if (src and (r[2] or "").strip() == src) or (nm and (r[1] or "").strip() == nm)]
if self_ids:
outer.append("batch_id NOT IN (%s)" % ",".join("?" * len(self_ids)))
oargs += self_ids
for t in (kw or "").split():
if not t:
continue
pat = "%" + _kw_fold(t) + "%" # 检索词折叠(φ/Φ/ϕ/⌀/Ø 一视同仁)
outer.append("(%s LIKE ? OR %s LIKE ? OR %s LIKE ?)"
% (_kw_like("name"), _kw_like("spec"), _kw_like("unit")))
oargs += [pat] * 3
_kw_conds(["name", "spec", "unit"], kw, outer, oargs) # 不按排序(决策 27)
if pfrom is not None:
outer.append("p2 >= ?"); oargs.append(pfrom)
if pto is not None:
@@ -467,7 +568,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
bf, bt = span(base) # 基准期次:单月 int 或 (起, 止) 区间
srcs = srcs or ["project", "info", "market"]
c = hist.cursor()
out = []
out, seen_ids = [], set()
# ---- 历史工程工料机 ----
w, args = _filters(kinds or [], [], [], self_src=self_src, area=area, orgs=orgs)
wpr, apr = _price_range("l.NoTaxPrice", pmin, pmax)
@@ -479,7 +580,7 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
# 带 l. 前缀,见 lme_list_where 的说明。
# ⚠️ **信息价/市场价分支永远不过滤任何单位/类别**(主人 2026-10-09 明示"永远不能
# 屏蔽信息价/市场价的任何单位")—— 别把 lme_list_where 加到下面价格查询上。
sql = """SELECT '精确' tier, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
sql = """SELECT '精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
@@ -488,11 +589,12 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE l.x_hash_exact=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
out += [dict(x) for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit])]
for x in c.execute(sql, [row["x_hash_exact"]] + args + [limit]):
d = dict(x); out.append(d); seen_ids.add(d["id"])
if len(out) < limit:
# 次精确:名称+单位一致、规格不同(2026-10-08 主人定)——同名材料不同规格正是常比对象
seen_semi = {(x["Name"], x["Specification"]) for x in out}
sql2 = """SELECT '次精确' tier, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
sql2 = """SELECT '次精确' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
@@ -507,11 +609,30 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
continue
if len(out) >= limit:
break
out.append(d); seen_semi.add((d["Name"], d["Specification"]))
out.append(d); seen_semi.add((d["Name"], d["Specification"])); seen_ids.add(d["id"])
# 字集精确(2026-10-10 决策 27):名称+规格**合并字集**+单位等价——「P.O 42.5 水泥」
# =「水泥 42.5 P.O」这类不按排序的整体命中;键 = lmes.x_setkey(导入落列,老库迁移回填)。
if len(out) < limit:
sqlk = """SELECT '字集' tier, l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
f.id fid, f.original_name fname
FROM lmes l JOIN batches bt ON bt.id=l.batch_id
LEFT JOIN lme_attach la ON la.lme_id=l.id
LEFT JOIN inquiry_files f ON f.id=la.file_id
WHERE l.x_setkey=? AND bt.kind='project' AND %s AND %s LIMIT ?""" % (w, lme_list_where("l"))
for x in c.execute(sqlk, [lme_setkey(row["Name"], row["Specification"], row["Unit"])] + args + [limit]):
d = dict(x)
if d["id"] in seen_ids:
continue
if len(out) >= limit:
break
out.append(d); seen_ids.add(d["id"])
if len(out) < limit:
q = norm_match(row["Name"])[:6]
if q:
sql3 = """SELECT l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
sql3 = """SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice,
bt.Name proj, bt.BulidUnit bunit, bt.FileKind,
bt.x_province, bt.x_city, bt.x_district,
bt.x_period_start_m p1, bt.x_period_end_m p2,
@@ -523,11 +644,13 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
for x in c.execute(sql3, args + ["%" + q + "%"]):
if norm(x["Unit"]) != norm(row["Unit"]):
continue
sim = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(x["Name"]) + norm_match(x["Specification"]))
if x["id"] in seen_ids:
continue
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
if sim >= SIM_MIN:
d = dict(x); d["tier"] = "模糊"
out.append(d)
d = dict(x); d["tier"] = "模糊"; d["_sim"] = sim
out.append(d); seen_ids.add(x["id"])
if len(out) >= limit:
break
for d in out:
@@ -538,9 +661,9 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
"fkind": d["FileKind"], "region": _region3(d.get("x_province"), d.get("x_city"), d.get("x_district")),
"period_m": nearest(d["p1"], d["p2"], bf),
"dist": dist(d["p1"], d["p2"], bf, bt),
"sim": 1.0 if d["tier"] != "模糊" else round(jaccard(
norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(d["Name"]) + norm_match(d["Specification"])), 2),
"sim": (1.0 if d["tier"] in ("精确", "字集") else
round(d["_sim"], 2) if "_sim" in d else
round(jaccard(norm_match(row["Name"]), norm_match(d["Name"])), 2)),
"src": "工程", "file": d.get("fname") or "",
"file_url": ("/api/admin/inq/file/%d" % d["fid"]) if d.get("fid") else "",
})
@@ -627,8 +750,8 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
key = (x["Name"], x["Specification"], x["Unit"])
if key in seen_p:
continue
sim = jaccard(norm_match(row["Name"]) + norm_match(row["Specification"]),
norm_match(x["Name"]) + norm_match(x["Specification"]))
sim = sim_weighted(norm_match(row["Name"]), norm_match(x["Name"]),
norm_attr(row["Specification"]), norm_attr(x["Specification"]))
if sim < SIM_MIN:
continue
seen_p.add(key)
@@ -654,10 +777,6 @@ def match_lme(hist, row, base, orgs=None, limit=20, srcs=None, pfrom=None, pto=N
res = [r for r in res if r.get("file")]
elif att == "no":
res = [r for r in res if not r.get("file")]
ss = _stem(self_src) # 被审工程源文件名主干(前 12 字)
if ss or self_name: # 排除"被审工程自己"
res = [r for r in res
if not (ss and _stem(r.get("src_hash") or r["proj"]) == ss)
and not (self_name and (r["proj"] or "").strip() == self_name.strip())]
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "模糊": 2}[r["tier"]]))
res = _self_filter(res, self_name, self_src) # 排除"被审工程自己"(同一文件/同名项目)
res.sort(key=lambda r: (r["dist"], {"精确": 0, "次精确": 1, "字集": 2, "模糊": 3}[r["tier"]]))
return res[:limit]

View File

@@ -386,7 +386,9 @@ def open_project(con, files, meta, job, sid=None):
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
(sid, uwid, divid, num, nm, attr, unit, qty, price, total, kb, srk,
norm(nm), norm(attr), norm(unit),
md5(num, nm, unit), md5(num, unit), xseq))
md5(norm(num)[:9], nm, unit), md5(norm(num)[:9], unit), xseq))
# 决策 27(2026-10-10):编码只取前 9 位(后 3 位是项目内顺序码,无对比意义);
# 与 history.db.bills(import_job)同口径,启动迁移重算老数据
bill_ids.append(cur.lastrowid)
stat["bill"] += 1