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

@@ -4,6 +4,8 @@ M3-1 后端服务:零依赖(Python 标准库 http.server)
提供后台管理界面需要的接口,并托管前端页面。
"""
import io, os, re, json, sqlite3, urllib.parse, mimetypes, hashlib, time, threading, base64
from itertools import combinations
from collections import Counter
from http.server import ThreadingHTTPServer, SimpleHTTPRequestHandler
# ---- 路径:**一律由本文件位置推导**,不写死绝对路径 ----
@@ -117,6 +119,12 @@ def ensure_attach_schema():
con.execute("ALTER TABLE lmes ADD COLUMN x_hash_semi TEXT")
if "x_hash_semi" not in pcols:
con.execute("ALTER TABLE prices ADD COLUMN x_hash_semi TEXT")
# 2026-10-10 决策 27:字集键列(回填与索引在 migrate_match_keys,连 bills 一起)
bcols = [r[1] for r in con.execute("PRAGMA table_info(bills)")]
if "x_setkey" not in bcols:
con.execute("ALTER TABLE bills ADD COLUMN x_setkey TEXT")
if "x_setkey" not in lcols:
con.execute("ALTER TABLE lmes ADD COLUMN x_setkey TEXT")
# 2026-10-06:价格条数从 x_rows_lme 拆出来,单独一列。
# x_rows_lme 此前被复用(项目=工料机数 / 价格批次=价格数),
# 导致「x_rows_lme>0 ⇒ 有工料机」的写法会把信息价批次误判。
@@ -130,6 +138,65 @@ def ensure_attach_schema():
con.commit(); con.close()
def _hash9_current(con, table):
"""探针:库存清单哈希是否已是「编码前 9 位」口径(决策 27)。整库任取一行重算比对。"""
row = con.execute("""SELECT Number, Name, Unit, x_hash_exact FROM %s
WHERE Number IS NOT NULL AND Length(Number) >= 9 LIMIT 1""" % table).fetchone()
if not row:
return True # 没有长编码行:两种口径结果相同,视为已迁移
num, name, unit, h0 = row
return job.md5(job.norm(num)[:9], name, unit) == h0
def _rehash_bills_9(con, table):
"""整表按「编码前 9 位」重算精确/次精确哈希(决策 27)。返回改动行数。"""
rows = con.execute("SELECT id, Number, Name, Unit, x_hash_exact, x_hash_semi FROM %s" % table).fetchall()
ups = []
for rid, num, name, unit, h0, hs0 in rows:
num9 = job.norm(num)[:9]
h, hs = job.md5(num9, name, unit), job.md5(num9, unit)
if h != h0 or hs != hs0:
ups.append((h, hs, rid))
if ups:
con.executemany("UPDATE %s SET x_hash_exact=?, x_hash_semi=? WHERE id=?" % table, ups)
return len(ups)
def migrate_match_keys():
"""决策 27(2026-10-10)一次性迁移,幂等(探针不匹配才动手,平时启动零成本跳过):
① bills 哈希改「编码前 9 位」口径——history.db.bills 与 session.db.s_bills 全量重算
x_hash_exact / x_hash_semi(编码后 3 位是项目内顺序码,跨项目没有对比意义);
② bills / lmes 回填 x_setkey 字集键 + 建索引(老库补列在 ensure_attach_schema,新库 schema.sql 自带)。"""
con = sqlite3.connect(DB)
try:
if not _hash9_current(con, "bills"):
print("迁移:bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(con, "bills"))
nb = con.execute("SELECT COUNT(*) FROM bills WHERE x_setkey IS NULL").fetchone()[0]
if nb:
con.executemany("UPDATE bills SET x_setkey=? WHERE id=?",
[(match.bill_setkey(nm, un), rid) for rid, nm, un in
con.execute("SELECT id, Name, Unit FROM bills WHERE x_setkey IS NULL")])
print("迁移:bills 字集键回填 %d 行" % nb)
nl = con.execute("SELECT COUNT(*) FROM lmes WHERE x_setkey IS NULL").fetchone()[0]
if nl:
con.executemany("UPDATE lmes SET x_setkey=? WHERE id=?",
[(match.lme_setkey(nm, sp, un), rid) for rid, nm, sp, un in
con.execute("SELECT id, Name, Specification, Unit FROM lmes WHERE x_setkey IS NULL")])
print("迁移:lmes 字集键回填 %d 行" % nl)
con.execute("CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey)")
con.execute("CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey)")
con.commit()
finally:
con.close()
scon = sess.connect()
try:
if not _hash9_current(scon, "s_bills"):
print("迁移:s_bills 哈希重算(编码前 9 位,决策 27)……%d 行改动" % _rehash_bills_9(scon, "s_bills"))
scon.commit()
finally:
scon.close()
# ---------------------------------------------------------------------------
# 数据源字典 / 后台设置(2026-10-06)
# ⚠️ 2026-10-06 重构:dict_region / dict_org / settings 三张表的建表 SQL 已全部收口到
@@ -764,13 +831,15 @@ def api_adopt_record(body):
(sha, kind, ref, name, ext, size, now))
sid = int(body.get("session_id") or 0)
lmid = int(body.get("lme_id") or 0)
if not sid or not lmid:
# 决策 28(2026-10-10):目录按会话展示,没有会话的事件永远不可见 → 干脆不收
return {"ok": False, "msg": "未打开项目(无会话),不收集附件"}
proj = (body.get("proj") or "").strip()
if sid and lmid: # 该行的旧事件先撤(换绑:再采纳即替换)
c.execute("DELETE FROM adopt_hits WHERE sid=? AND lme_id=?", (sid, lmid))
if proj:
c.execute("""INSERT INTO adopt_hits(sha256, proj, adopted_at, sid, lme_id)
VALUES(?,?,?,?,?)""", (sha, proj, now,
sid or None, lmid or None))
VALUES(?,?,?,?,?)""", (sha, proj, now, sid, lmid))
c.commit()
n_att = c.execute("SELECT COUNT(*) FROM adopt_files").fetchone()[0]
return {"ok": True, "n_att": n_att}
@@ -807,9 +876,11 @@ def api_adopt_cancel(body):
c.close()
def api_adopt_list():
"""「询价附件」弹框数据:附件目录(按内容去重)+ 每个附件被哪些项目采纳过。
顺带懒清理:磁盘原件已随批次删除的条目,这里从注册表摘掉,不留死链接。"""
def api_adopt_list(sid=0):
"""「询价附件」弹框数据(2026-10-10 主人定:**会话级**)——只看当前会话收进的附件:
过滤 adopt_hits 里 sid 匹配的事件;没打开项目(无 sid)→ 空目录。
会话不删,事件就在,切回来附件还在;删会话连带撤事件(api_session_delete 已有)。
仍顺带懒清理:磁盘原件已随批次删除的条目,从注册表摘掉,不留死链接(对全表做,别留死角)。"""
c = conn()
try:
atts, dead = [], []
@@ -820,13 +891,21 @@ def api_adopt_list():
if not rel or not os.path.exists(os.path.join(DATA_DIR, rel)):
dead.append(sha)
continue
if sid:
n = c.execute("SELECT COUNT(*) FROM adopt_hits WHERE sha256=? AND sid=?",
(sha, sid)).fetchone()[0]
if not n:
continue # 别的会话收的:本会话目录里不显示(行保留)
projs = [h[0] for h in c.execute(
"""SELECT DISTINCT proj FROM adopt_hits WHERE sha256=? AND sid=?
ORDER BY proj""", (sha, sid)).fetchall()]
else:
continue # 没打开项目:不给任何附件(主人 2026-10-10 定)
atts.append({"sha": sha, "kind": kind, "ref": ref2, "name": name, "ext": ext,
"size": size, "adopted_at": at,
"url": ("/api/admin/inq/file/%s" % ref2) if kind == "inq"
else ("/api/admin/file/%s" % sha),
"projs": [h[0] for h in c.execute(
"""SELECT DISTINCT proj FROM adopt_hits WHERE sha256=?
ORDER BY proj""", (sha,)).fetchall()]})
"projs": projs})
if dead:
c.executemany("DELETE FROM adopt_files WHERE sha256=?", [(s,) for s in dead])
c.executemany("DELETE FROM adopt_hits WHERE sha256=?", [(s,) for s in dead])
@@ -2066,68 +2145,11 @@ def api_session_groups(sid, kind):
if kind == "inconsistent":
return _inconsistent(rows, BILLROW)
# ---- similar ----
# 系统内置专业:走固定的「前 4 字 + bigram」自动聚类(与后台同一实现 _group_by_prefix)
if _setting_get("session:%d" % sid, "profession") == SYS_PROF:
gs, rest = _group_by_prefix(rows)
out = []
for g in gs:
d = _grpstat(g["rows"]); d["sim"] = g["sim"]
d["rows"] = [BILLROW(x) for x in g["rows"]]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0))
return {"total": len(out), "groups": out,
"extra": _extra_by_cat(rest, BILLROW), "group_mode": True}
# 优先用「关键字分组」配置;无配置走原「前 6 字」逻辑
cfg = _load_similar_groups(sid)
if cfg:
groups, other = _group_by_keywords(rows, cfg)
out = []
for gname, rs in groups:
d = _grpstat(rs); d["cat"] = gname; d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0))
extra = []
if other:
d = _grpstat(other); d["cat"] = "其他"; d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in other]
extra = [d]
return {"total": len(groups), "groups": out, "extra": extra, "group_mode": True}
# 原行为:按名称前 6 字分桶
g = {}
for r in rows:
key = r["x_name_norm"][:6]
if not key:
continue
g.setdefault(key, []).append(r)
out = []
for key, rs in g.items():
names = {x["Name"] for x in rs}
if len(names) < 2:
continue
d = _grpstat(rs)
d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
# 2026-09-29 决策 19:similar 组按「差距%」从大到小排
out.sort(key=lambda x: -(x.get("spread") or 0))
# 2026-09-29 决策 18:没进任何组的合规清单按类别归并,保证一条不漏
extra = []
shown = {r[0] for grp in out for r in grp["rows"]}
rest = [r for r in rows if r["id"] not in shown]
buckets = {}
for r in rest:
buckets.setdefault(cat_of(r["Name"]) or "其他", []).append(r)
for lab, rs in sorted(buckets.items(), key=lambda x: (-len(x[1]), x[0])):
d = _grpstat(rs)
d["cat"] = lab
d["rows"] = [BILLROW(x) for x in rs]
extra.append(d)
return {"total": len(out), "groups": out, "extra": extra}
# ---- similar:v2 七点顺序管线(决策 29,2026-10-10 主人定)----
# 关键词层仍读本工程专业的配置(后期专业取消后 kw_cfg 恒 None,管线自动只剩名称层+特征层)
prof = _setting_get("session:%d" % sid, "profession")
kw_cfg = _load_similar_groups(sid) if (prof and prof != SYS_PROF) else None
return _group_v2_output(rows, kw_cfg)
def api_session_bill_norms(bill_id):
@@ -3006,6 +3028,207 @@ def norm_txt(s):
return s.lower()
# ---------- 类似清单分组 v2(2026-10-10 决策 29 主人定:7 点顺序管线) ----------
# 顺序语义(主人定,顺序不可颠倒):逐级实施,**上一级分走的行不再进入下一级**。
# 第3点 关键词层:本工程专业配置的关键词组(首匹配+排除词);**不按单位拆**——取值范围=名称+特征。
# 第4点 名称层:名称字集 交集≥min(4, 短方全长) 并查集聚类(字集等效换序无关:钢混凝土=混凝土钢;
# 短名按全长处理:土=钢混凝土)。
# 第5点 特征层:剩余落单按特征"数字字母签名"(剥换行排序序号后提取字母数字的字符集合)等值成组。
# 第6点 其他:仍没进组的全部按类别归并展示(一条不漏,决策 18)。
# 第7点 池化合并(2026-10-10 主人定修订):1~6 步的组**完全对等**——三层组倒进同一个池,
# 组代表(组内最高频名称的中文主干字集)Jaccard≥grp_merge_thr 即合并;
# **不设条数上限、无跨块限制**(初版"按块+累计上限50"已废,主人拍板池化)。
# 保险丝(防串联巨组,实测 2099/3511 条巨组的解):任何一层产生的组超过 grp_big 条 → 组内按特征签名
# 星形细分(阈值 grp_sig_thr)。
# 规则参数读 global 设置(缺省用默认):grp_big=50 / grp_sig_thr=0.6 / grp_merge_on=1 /
# grp_merge_thr=0.85。专业/组名称配置仍作关键词层来源(后期取消)。
def _grp_rule():
def _i(k, d):
try:
return int(float(_setting_get("global", k) or d))
except Exception:
return d
def _f(k, d):
try:
return float(_setting_get("global", k) or d)
except Exception:
return d
return {"big": _i("grp_big", 50),
"sig_thr": _f("grp_sig_thr", 0.6),
"merge_on": (_setting_get("global", "grp_merge_on") or "1") not in ("0", "false", "off"),
"merge_thr": _f("grp_merge_thr", 0.85)}
def _grp_signature(s):
"""特征「数字字母签名」:norm_attr 剥排序序号后,全部字母数字段的字符集合(排序串)。"""
s = match.norm_attr(s or "")
return "".join(sorted(set("".join(match._TOK.findall(s)))))
def _grp_stem_set(names):
"""组代表(第7点合并判据):组内最高频名称的**中文主干**字集——编号字母不掺进相似度。"""
c = Counter((match.norm_attr(n or "")) for n in names)
if not c:
return set()
best = c.most_common(1)[0][0]
s = match._TOK.sub(" ", best)
s = "".join(re.sub(r"[^一-鿿]+", " ", s).split())
return set(match.set_norm(s)) if s else set()
def _grp_fuse(mem_rows, thr):
"""巨组保险丝:组内按特征签名**星形**细分——锚=先到的签名,行只跟锚比,杜绝串联。
返回子组列表(可能含单行子组,调用方分流到下一层)。"""
reps = []
for r in sorted(mem_rows, key=lambda x: _col(x, "id")):
s = _grp_signature(_col(r, "Attr"))
placed = False
if s:
for rs, m2 in reps:
u = len(set(s) | set(rs))
if u and len(set(s) & set(rs)) / u >= thr:
m2.append(r); placed = True; break
if not placed:
reps.append((s, [r]))
return [m2 for rs, m2 in reps]
def _grp_block_merge(groups, thr):
"""第7点池化合并(2026-10-10 主人定:1~6 步的组看作**完全对等**的待合并组,跨块池化;
**不设条数上限**):组代表(最高频名称的中文主干字集)Jaccard≥thr 即合并。"""
reps = [_grp_stem_set([_col(x, "Name") for x in g]) for g in groups]
par2 = list(range(len(groups)))
def f2(x):
while par2[x] != x: par2[x] = par2[par2[x]]; x = par2[x]
return x
for i in range(len(groups)):
for j in range(len(groups)):
if i == j:
continue
a, b = reps[i], reps[j]
if not a or not b:
continue
ri, rj = f2(i), f2(j)
if ri == rj:
continue
u = len(a | b)
if u and len(a & b) / u >= thr:
par2[ri] = rj
mg = {}
for i in range(len(groups)): mg.setdefault(f2(i), []).extend(groups[i])
return [v for v in mg.values() if len(v) > 1]
def _group_v2(rows, kw_cfg):
"""决策 29 七点顺序管线。kw_cfg=本工程专业关键词配置(无/后期取消=跳过关键词层)。
返回 (blocks, rest):blocks=[(组名或None, 行列表)] 按块顺序(关键词→名称→特征),
rest=未进组的行(调用方交 _extra_by_cat 归并)。"""
rule = _grp_rule()
used = set()
# ---- 第3点 关键词层 ----
kw_blocks = []
if kw_cfg:
for g in kw_cfg:
kws = [match.norm(k) for k in (g.get("keywords") or []) if k]
if not kws:
continue
mem = []
for r in rows:
if _col(r, "id") in used:
continue
nm = match.norm("%s %s" % (_col(r, "Name") or "", _col(r, "Attr") or ""))
if any(k in nm for k in kws) and not any(
match.norm(x) in nm for x in (g.get("exclude") or []) if x):
mem.append(r)
if not mem:
continue
subs = _grp_fuse(mem, rule["sig_thr"]) if len(mem) > rule["big"] else [mem]
for m in subs:
if len(m) > 1: # 单行子组不算"已分组",落回名称层
kw_blocks.append((g.get("name") or "关键词组", m))
used.update(_col(x, "id") for x in m)
# ---- 第4点 名称层:字集 交集≥min(4,短方全长) ----
rest0 = [r for r in rows if _col(r, "id") not in used]
par = list(range(len(rest0)))
def find(x):
while par[x] != x: par[x] = par[par[x]]; x = par[x]
return x
keys = [set(match.set_norm(match.norm_attr(_col(r, "Name") or ""))) for r in rest0]
inv = {}
for i, k in enumerate(keys):
for ch in k:
inv.setdefault(ch, []).append(i)
for ch, lst in inv.items():
for i, j in combinations(lst, 2):
if len(keys[i] & keys[j]) >= min(4, min(len(keys[i]), len(keys[j]))):
ra, rb = find(i), find(j)
if ra != rb:
par[ra] = rb
clus = {}
for i in range(len(rest0)):
clus.setdefault(find(i), []).append(i)
name_blocks = []
rest = []
for root, mem in clus.items():
mrows = sorted((rest0[i] for i in mem), key=lambda x: _col(x, "id"))
if len(mrows) == 1:
rest.append(mrows[0]); continue
subs = _grp_fuse(mrows, rule["sig_thr"]) if len(mrows) > rule["big"] else [mrows]
for m in subs:
if len(m) > 1:
name_blocks.append((None, m))
else:
rest.append(m[0])
# ---- 第5点 特征层:落单按签名等值(签名不足 4 字符的行不参与,留在 rest——条数守恒)----
sigb = {}
for r in rest:
s = _grp_signature(_col(r, "Attr"))
if len(s) >= 4:
sigb.setdefault(s, []).append(r)
attr_blocks = [(None, v) for v in sigb.values() if len(v) >= 2]
taken = set()
for v in sigb.values():
if len(v) >= 2:
taken.update(_col(x, "id") for x in v)
rest = [r for r in rest if _col(r, "id") not in taken]
# ---- 第7点 池化合并(2026-10-10 主人定修订:1~6 步的组**完全对等**,三层组倒进同一个池,
# 组代表主干字集 J≥merge_thr 即并,**不设条数上限、不跨块限制已随池化取消**)----
if rule["merge_on"] and len(kw_blocks) + len(name_blocks) + len(attr_blocks) > 1:
pool = kw_blocks + name_blocks + attr_blocks
merged = _grp_block_merge([b[1] for b in pool], rule["merge_thr"])
lbl_of = {}
for lbl0, g0 in pool:
for x in g0:
lbl_of[id(x)] = lbl0
kw_blocks, name_blocks, attr_blocks = [], [], []
for g in merged:
cnt = Counter(lbl_of.get(id(x)) for x in g if lbl_of.get(id(x)))
lbl = max(cnt, key=lambda l: cnt[l]) if cnt else None # 沿用簇内多数的关键词组名
kw_blocks.append((lbl, g))
return kw_blocks + name_blocks + attr_blocks, rest
def _group_v2_output(rows, kw_cfg):
"""v2 管线 → 前端响应(结构与原 similar 完全同构:total/groups/extra/group_mode)。"""
blocks, rest = _group_v2(rows, kw_cfg)
out = []
for label, rs in blocks:
d = _grpstat(rs)
if label:
d["cat"] = label
d["sim"] = 1.0
d["rows"] = [BILLROW(x) for x in rs]
out.append(d)
out.sort(key=lambda x: -(x.get("spread") or 0)) # 决策 19:组按差% 从大到小
return {"total": len(out), "groups": out,
"extra": _extra_by_cat(rest, BILLROW), "group_mode": True}
# 行适配统一用上面的 BILLROW(两侧唯一实现,原 _billrow 已删 —— 2026-10-08 收编)。
@@ -3351,8 +3574,8 @@ class Handler(SimpleHTTPRequestHandler):
return self._json(api_raw_uw(one))
if p == "/api/session/inq": # 工作台:询价附件(只读,来源=后台项目批次)
return self._json(api_session_inq(int(one.get("session_id", 0) or 0)))
if p == "/api/adopt/list": # 工作台「询价附件」:采纳收集的附件目录
return self._json(api_adopt_list())
if p == "/api/adopt/list": # 工作台「询价附件」:当前会话收进的附件目录(会话级,决策 28)
return self._json(api_adopt_list(int((q.get("sid") or ["0"])[0] or 0)))
if p == "/api/session/rows": # 会话数据(工作台三个标签)
return self._json(api_session_rows(one))
if p == "/api/session/inconsistent": # 会话内:组价不一致
@@ -3668,7 +3891,8 @@ def run():
pass
ensure_adopt_schema() # 采纳收集表形状检查(旧去重版 → 事件模型重建)
_ensure_batch_schema() # 唯一建表入口:执行 schema.sql(含 attachments/dict/settings/inquiry 全部表)
ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block)
ensure_attach_schema() # 老库补列 + 回填(x_attach_sha / x_publisher / x_rows_price / prices.Block / x_setkey)
migrate_match_keys() # 决策 27:清单哈希改编码前9位 + 字集键回填(幂等,探针跳过)
ensure_dict_schema() # 数据源字典(首次用库里已有值播种)
backfill_session_batch() # 老会话补 x_batch_id → 工作台才能看到该项目的询价附件
cleanup_sessions() # 启动时清掉超过保留天数的会话(只碰 session.db)