# -*- coding: utf-8 -*- """ M1 最后半步:建索引 + 检索演示 + 测速度 方案 §3.3(L0 精确 / L1 次精确 / L2 模糊)+ §5.4(时间邻近 先近后远) """ import io, os, re, time, json, random, sqlite3 from openpyxl import Workbook from openpyxl.styles import Font, PatternFill from openpyxl.cell import WriteOnlyCell # 路径由本文件位置推导(换台电脑直接能跑,不写死绝对路径) _PRJ = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # .../造价审核 DB = os.path.join(_PRJ, "data", "history.db") OUT = os.path.join(_PRJ, "data", "检索演示.xlsx") REPORT = os.path.join(_PRJ, "data", "检索报告.md") BASE_PERIOD = 2026 * 12 + 6 # 基准期次 2026-06(演示用) SIM_MIN = 0.60 def norm(s): s = (s or "").strip() s = s.replace("(", "(").replace(")", ")").replace(",", ",").replace(";", ";") s = s.replace("×", "*").replace("*", "*").replace("X", "*").replace("x", "*") s = re.sub(r"\s+", "", s) return s.lower() def bigrams(s): s = norm(s) return set(s[i:i + 2] for i in range(len(s) - 1)) or {s} def jaccard(a, b): A, B = bigrams(a), bigrams(b) return len(A & B) / max(len(A | B), 1) def dist(start, end, base): if start is None: return 9999 if start <= base <= end: return 0 return start - base if base < start else base - end DIST = """(CASE WHEN ?1 BETWEEN {t}.x_period_start_m AND {t}.x_period_end_m THEN 0 WHEN ?1 < {t}.x_period_start_m THEN {t}.x_period_start_m - ?1 ELSE ?1 - {t}.x_period_end_m END)""" def build(con): c = con.cursor() for t in ("bills", "lmes"): cols = [r[1] for r in c.execute("PRAGMA table_info(%s)" % t)] if "x_period_start_m" not in cols: c.execute("ALTER TABLE %s ADD COLUMN x_period_start_m INTEGER" % t) c.execute("ALTER TABLE %s ADD COLUMN x_period_end_m INTEGER" % t) c.execute("""UPDATE {t} SET x_period_start_m=(SELECT x_period_start_m FROM batches WHERE id={t}.batch_id), x_period_end_m=(SELECT x_period_end_m FROM batches WHERE id={t}.batch_id)""".format(t=t)) for s in ["CREATE INDEX IF NOT EXISTS ix_bill_exact_pe ON bills(x_hash_exact, x_period_end_m)", "CREATE INDEX IF NOT EXISTS ix_bill_exact_ps ON bills(x_hash_exact, x_period_start_m)", "CREATE INDEX IF NOT EXISTS ix_bill_semi_pe ON bills(x_hash_semi, x_period_end_m)", "CREATE INDEX IF NOT EXISTS ix_bill_semi_ps ON bills(x_hash_semi, x_period_start_m)", "CREATE INDEX IF NOT EXISTS ix_lme_exact_pe ON lmes(x_hash_exact, x_period_end_m)", "CREATE INDEX IF NOT EXISTS ix_lme_exact_ps ON lmes(x_hash_exact, x_period_start_m)"]: c.execute(s) fts = True try: c.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS bills_fts USING fts5(Name, Attr, content='bills', content_rowid='id', tokenize='trigram')""") c.execute("INSERT INTO bills_fts(bills_fts) VALUES('rebuild')") c.execute("""CREATE VIRTUAL TABLE IF NOT EXISTS lmes_fts USING fts5(Name, Specification, content='lmes', content_rowid='id', tokenize='trigram')""") c.execute("INSERT INTO lmes_fts(lmes_fts) VALUES('rebuild')") except Exception as e: print("FTS5 不可用:", e); fts = False con.commit() return fts def search_bill(con, r, base, fts, limit=10): c = con.cursor(); out = [] sql = """SELECT '精确' tier, b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name proj, bt.x_period_start_m ps, bt.x_period_end_m pe, %s dist FROM bills b JOIN batches bt ON bt.id=b.batch_id WHERE b.x_hash_exact=? AND b.batch_id<>? ORDER BY dist, b.id LIMIT ?""" % DIST.format(t="b") out += [list(x) for x in c.execute(sql, (base, r["x_hash_exact"], r["batch_id"], limit))] if len(out) < limit: sql2 = """SELECT '次精确', b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name, bt.x_period_start_m, bt.x_period_end_m, %s dist FROM bills b JOIN batches bt ON bt.id=b.batch_id WHERE b.x_hash_semi=? AND b.x_hash_exact<>? AND b.batch_id<>? ORDER BY dist, b.id LIMIT ?""" % DIST.format(t="b") out += [list(x) for x in c.execute(sql2, (base, r["x_hash_semi"], r["x_hash_exact"], r["batch_id"], limit - len(out)))] if fts and len(out) < limit: q = norm(r["Name"])[:24] or norm(r["Attr"])[:24] if q: try: cand = c.execute("""SELECT b.id, b.Number, b.Name, b.Attr, b.Unit, b.Price, bt.Name, bt.x_period_start_m, bt.x_period_end_m FROM bills_fts f JOIN bills b ON b.id=f.rowid JOIN batches bt ON bt.id=b.batch_id WHERE bills_fts MATCH ? AND b.batch_id<>? LIMIT 200""", ('"' + q + '"', r["batch_id"])).fetchall() except Exception: cand = [] sc = [] used = set(x[1] for x in out) for x in cand: if x[0] in used: continue if norm(x[4]) != norm(r["Unit"]): continue sim = jaccard((r["Name"] or "") + (r["Attr"] or ""), (x[2] or "") + (x[3] or "")) if sim >= SIM_MIN: sc.append(["模糊", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], dist(x[7], x[8], base), round(sim, 3)]) sc.sort(key=lambda z: (z[9], -z[10])) out += sc[:limit - len(out)] return out[:limit] def search_lme(con, r, base, fts, limit=10): c = con.cursor(); out = [] sql = """SELECT '精确', l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, bt.Name, bt.x_period_start_m, bt.x_period_end_m, %s dist FROM lmes l JOIN batches bt ON bt.id=l.batch_id WHERE l.x_hash_exact=? AND l.batch_id<>? ORDER BY dist, l.id LIMIT ?""" % DIST.format(t="l") out += [list(x) for x in c.execute(sql, (base, r["x_hash_exact"], r["batch_id"], limit))] if fts and len(out) < limit: q = norm(r["Name"])[:20] if q: try: cand = c.execute("""SELECT l.id, l.Name, l.Specification, l.Unit, l.NoTaxPrice, l.TaxRate, l.TaxPrice, bt.Name, bt.x_period_start_m, bt.x_period_end_m FROM lmes_fts f JOIN lmes l ON l.id=f.rowid JOIN batches bt ON bt.id=l.batch_id WHERE lmes_fts MATCH ? AND l.batch_id<>? LIMIT 200""", ('"' + q + '"', r["batch_id"])).fetchall() except Exception: cand = [] sc = [] used = set(x[1] for x in out) for x in cand: if x[0] in used: continue if norm(x[3]) != norm(r["Unit"]): continue sim = jaccard((r["Name"] or "") + (r["Specification"] or ""), (x[1] or "") + (x[2] or "")) if sim >= SIM_MIN: sc.append(["模糊", x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], dist(x[8], x[9], base), round(sim, 3)]) sc.sort(key=lambda z: (z[10], -z[11])) out += sc[:limit - len(out)] return out[:limit] def main(): con = sqlite3.connect(DB); con.row_factory = sqlite3.Row t0 = time.time(); fts = build(con); t_idx = time.time() - t0 random.seed(42) bills = con.execute("""SELECT b.*, bt.Name proj FROM bills b JOIN batches bt ON bt.id=b.batch_id""").fetchall() lmes = con.execute("""SELECT l.*, bt.Name proj FROM lmes l JOIN batches bt ON bt.id=l.batch_id""").fetchall() sb = random.sample(bills, min(30, len(bills))) sl = random.sample(lmes, min(30, len(lmes))) times, rb, rl = [], [], [] first_tier, have_res = [], 0 for r in sb: t = time.time(); res = search_bill(con, r, BASE_PERIOD, fts); times.append((time.time() - t) * 1000) if res: have_res += 1; first_tier.append(res[0][0]) for x in res[:5]: rb.append([(r["Name"] or "")[:24], r["Price"], x[0], (x[3] or "")[:24], x[6], x[5], (x[7] or "")[:20], x[10]]) for r in sl: t = time.time(); res = search_lme(con, r, BASE_PERIOD, fts); times.append((time.time() - t) * 1000) if res: have_res += 1; first_tier.append(res[0][0]) for x in res[:5]: rl.append([(r["Name"] or "")[:24], r["NoTaxPrice"], x[0], (x[2] or "")[:24], x[5], (x[8] or "")[:20], x[11]]) def pct(p): s = sorted(times); return s[min(int(len(s) * p / 100), len(s) - 1)] tier_cnt = {} for x in rb: tier_cnt[x[2]] = tier_cnt.get(x[2], 0) + 1 for x in rl: tier_cnt[x[2]] = tier_cnt.get(x[2], 0) + 1 ft = {k: first_tier.count(k) for k in ("精确", "次精确", "模糊")} stat = [("数据库", DB), ("基准期次", "2026-06"), ("建索引耗时(秒)", round(t_idx, 1)), ("查询有结果的比例", "%d/%d" % (have_res, len(times))), ("结果档位分布", " ".join("%s=%d" % kv for kv in sorted(tier_cnt.items()))), ("首条命中档位", " ".join("%s=%d" % kv for kv in ft.items())), ("清单总量", len(bills)), ("工料机总量", len(lmes)), ("查询次数", len(times)), ("平均耗时(毫秒)", round(sum(times) / len(times), 2)), ("P50(毫秒)", round(pct(50), 2)), ("P95(毫秒)", round(pct(95), 2)), ("P99(毫秒)", round(pct(99), 2)), ("最慢一次(毫秒)", round(max(times), 2))] wb = Workbook(write_only=True) hf, hfill = Font(bold=True, color="FFFFFF"), PatternFill("solid", fgColor="1F5FAE") def sheet(name, head, rows): ws = wb.create_sheet(name) hr = [WriteOnlyCell(ws, value=v) for v in head] for cc in hr: cc.font = hf; cc.fill = hfill ws.append(hr) for r in rows: ws.append(list(r)) sheet("性能", ["指标", "值"], stat) sheet("清单检索样例", ["被审清单", "本工程单价", "档位", "历史清单", "历史单价", "单位", "来源项目", "距基准(月)"], rb) sheet("工料机检索样例", ["被审工料机", "本工程除税价", "档位", "历史工料机", "历史除税价", "来源项目", "距基准(月)"], rl) out_path = OUT if os.path.exists(OUT): try: open(OUT, "a+b").close() except PermissionError: out_path = OUT.replace(".xlsx", "_v2.xlsx") wb.save(out_path) o = ["# 检索演示报告(M1 最后半步)", "", "- 基准期次:2026-06(演示用)", "- 数据库:%s" % DB, "", "## 一、性能", "", "| 指标 | 值 |", "|---|---|"] o += ["| %s | %s |" % kv for kv in stat] o += ["", "## 二、清单检索样例(前 15 行)", "", "| 被审清单 | 本工程单价 | 档位 | 历史清单 | 历史单价 | 单位 | 来源项目 | 距基准(月) |", "|---|---:|---|---|---:|---|---|---:|"] o += ["| %s | %s | %s | %s | %s | %s | %s | %s |" % tuple(r) for r in rb[:15]] o += ["", "## 三、工料机检索样例(前 15 行)", "", "| 被审工料机 | 本工程除税价 | 档位 | 历史工料机 | 历史除税价 | 来源项目 | 距基准(月) |", "|---|---:|---|---|---:|---|---:|"] o += ["| %s | %s | %s | %s | %s | %s | %s |" % tuple(r) for r in rl[:15]] io.open(REPORT, "w", encoding="utf-8").write("\n".join(o)) print("OK ->", out_path) print(json.dumps(dict(stat), ensure_ascii=False)) if __name__ == "__main__": main()