# -*- coding: utf-8 -*- """testdata —— 造价审核 测试数据生成器(核心引擎,2026-10-09)。 定位:放在 release/ 下的独立工具,**不改任何软件代码、不碰真实库**。 写入目标是独立测试库文件 history-test.db(后台)与 session-test.db(工作台); 测试库首次生成时从同名真实库克隆底子(schema/设置随带)。主人对接软件时 自行把测试库改名换上去即可,真实数据零污染。所有数据 Name 带「测试」前缀 + is_mock=1(批次库)双标记。删除走本文件的分块循环(每块 2 万个批次 id), **不依赖后台内置「清空模拟数据」按钮**——那条 SQL 一次绑定全部 id,批次数超过 SQLite 变量上限(32766)会直接报错。 随母体变化目录:全部相对定位。从本文件位置逐级向上找 <某级>/造价审核/data/history.db (工作区或包内) <某级>/PricingReview*/造价审核/data/history.db(绿色包改名也能找到) 找到即随包整体挪走照常用;界面里也可手动指定数据目录(存 config.json)。 命令行: python gen_testdata.py --check # 统计现有测试数据 python gen_testdata.py --run run_cfg.json # 按参数生成(控制台写这份 json) python gen_testdata.py --delete --yes # 分块删除全部测试数据(含附件文件) python gen_testdata.py --delete --yes --keep-files # 只删库行不删附件文件 """ import argparse import glob import hashlib import json import os import random import re import sqlite3 import sys import time def _safe_stdio(): """Windows GBK 控制台兜底:路径里的 U+200C 等字符编码不了时替换成 ?,不崩。""" for s in (sys.stdout, sys.stderr): try: s.reconfigure(errors="replace") except Exception: pass _safe_stdio() def _disp(p): """仅用于显示的路径:剔掉零宽字符(工作区路径 review 后带 U+200C)。""" return (p or "").replace("\u200c", "") HERE = os.path.dirname(os.path.abspath(__file__)) CFG_PATH = os.path.join(HERE, "config.json") RUN_CFG = os.path.join(HERE, "run_cfg.json") PAUSE_FLAG = os.path.join(HERE, "pause.flag") CHUNK = 20000 # 每块删除的批次/会话 id 数(远离 32766 上限) PARSER_VER_FALLBACK = "2026.10.08-1" # ---------------- 定位数据目录(随母体变化目录) ---------------- REAL_H = "history.db" TEST_H = "history-test.db" # 后台测试库(主人定的隔离文件名) TEST_S = "session-test.db" # 工作台测试库 def _has_anchor(d): return (os.path.exists(os.path.join(d, REAL_H)) or os.path.exists(os.path.join(d, TEST_H))) REF_DIR = None # 参考库目录(None = 与数据目录同目录) def db_paths(dd): """返回 (真实history, 测试history, 真实session, 测试session) 四个绝对路径。 参考库可在独立目录(REF_DIR);测试库与附件一律落在数据目录 dd。""" rd = REF_DIR or dd return (os.path.join(rd, REAL_H), os.path.join(dd, TEST_H), os.path.join(rd, "session.db"), os.path.join(dd, TEST_S)) def ensure_test_dbs(dd, log=print): """测试库不存在时从同名真实库克隆(schema/索引/设置随底子带上)。 真实库本体绝不打开写。返回 (测试history路径, 测试session路径)。""" rh, th, rs, ts = db_paths(dd) if not os.path.exists(th): if not os.path.exists(rh): raise SystemExit("!! 参考目录里没有 %s(参考目录:%s),无法建测试库" % (REAL_H, _disp(os.path.dirname(rh) or dd))) os.makedirs(dd, exist_ok=True) # 测试库独立目录可能还不存在 s = sqlite3.connect(rh) d = sqlite3.connect(th) s.backup(d) d.close() s.close() log("已从 %s 克隆出测试库 %s(真实库未动)" % (REAL_H, TEST_H)) if not os.path.exists(ts) and os.path.exists(rs): s = sqlite3.connect(rs) d = sqlite3.connect(ts) s.backup(d) d.close() s.close() log("已从 session.db 克隆出测试库 %s(真实库未动)" % TEST_S) return th, ts def find_data_dir(): if os.path.exists(CFG_PATH): try: with open(CFG_PATH, encoding="utf-8") as f: p = (json.load(f) or {}).get("data_dir") or "" if p and _has_anchor(p): return os.path.normpath(p) except Exception: pass d = HERE for _ in range(8): cand = os.path.join(d, "造价审核", "data") if _has_anchor(cand): return cand pat = os.path.join(d, "PricingReview*", "造价审核", "data") for g in glob.glob(pat): if _has_anchor(g): return g nd = os.path.dirname(d) if nd == d: break d = nd return None def set_data_dir(p, ref_dir=None): cfg = {} if os.path.exists(CFG_PATH): try: with open(CFG_PATH, encoding="utf-8") as f: cfg = json.load(f) or {} except Exception: cfg = {} cfg["data_dir"] = p if ref_dir is not None: cfg["ref_dir"] = ref_dir tmp = CFG_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) os.replace(tmp, CFG_PATH) # ---------------- 归一化 / 哈希(复刻 core/import_job.py 口径) ---------------- def norm(s): s = (s or "").strip() s = s.replace("(", "(").replace(")", ")").replace(",", ",").replace(";", ";") s = s.replace("×", "*").replace("*", "*").replace("X", "*").replace("x", "*") s = s.replace("㎡", "m2").replace("m²", "m2").replace("m2", "m2") s = re.sub(r"\s+", "", s) return s.lower() def md5(*parts): return hashlib.md5("|".join(norm(p) for p in parts).encode("utf-8")).hexdigest() def clean_attr(s): t = norm(s) t = re.sub(r"(?= 6] except Exception: out["stems"] = [] try: rows = con.execute("SELECT Number, Name, Unit FROM norms LIMIT 4000").fetchall() seen, nm = set(), [] for r in rows: if r[0] and r[1] and r[0] not in seen: seen.add(r[0]) nm.append((r[0], r[1], r[2] or "项")) out["norms"] = nm except Exception: out["norms"] = [] try: rows = con.execute( "SELECT Number, Name, Specification, Unit, Kind, TaxPrice FROM lmes " "WHERE Name IS NOT NULL AND Name <> '' LIMIT 60000").fetchall() seen, lm = set(), [] for r in rows: if r[1] and r[1] not in seen: seen.add(r[1]) lm.append((r[0] or "", r[1], r[2] or "", r[3] or "项", r[4] or 2, r[5] or 0)) out["lmes"] = lm except Exception: out["lmes"] = [] try: rows = con.execute( "SELECT DISTINCT BulidUnit FROM batches WHERE BulidUnit IS NOT NULL " "AND BulidUnit <> '' AND is_mock=0 LIMIT 300").fetchall() out["builders"] = [r[0] for r in rows] except Exception: out["builders"] = [] return out class Words: """词料聚合:真实优先、内置兜底。""" def __init__(self, con): h = harvest(con) self.stems = h["stems"] or PROJECT_STEMS self.norms = (h["norms"] if len(h["norms"]) >= 12 else []) or NORM_ITEMS self.lmes = (h["lmes"] if len(h["lmes"]) >= 60 else []) or LME_BUILTIN self.builders = h["builders"] or [gen_builder(random.Random(i)) for i in range(80)] # ---------------- 附件文件(名字确定性 → 重跑原地覆盖,不累积孤儿文件) ---------------- def _fake_bytes(fname, lo=1024, hi=6144): ext = fname.rsplit(".", 1)[-1].lower() if ext == "pdf": head = b"%PDF-1.4\n" elif ext in ("zip", "rar", "xlsx", "docx"): head = b"PK\x03\x04" if ext != "rar" else b"Rar!\x1a\x07" else: head = b"" return head + (b"\ntestdata sample: " + fname.encode("utf-8") + b"\n") \ + os.urandom(random.randint(lo, hi)) def write_file_rel(data_dir, subdir, sha, fname): d = os.path.join(data_dir, subdir, sha[:2]) os.makedirs(d, exist_ok=True) fn = "%s_%s" % (sha, fname) p = os.path.join(d, fn) if not os.path.exists(p): with open(p, "wb") as f: f.write(_fake_bytes(fname)) return os.path.join(subdir, sha[:2], fn) def del_file(data_dir, rel): """安全删文件:只动 data 目录内、且文件名以 sha 前缀开头的生成物。""" try: p = os.path.join(data_dir, rel) if os.path.isfile(p) and os.path.basename(p)[:2] == os.path.basename(os.path.dirname(p)) \ and "_" in os.path.basename(p): os.remove(p) except Exception: pass # ---------------- 默认参数 ---------------- DEFAULTS = { "n_project": 10, "bill_lo": 300, "bill_hi": 800, "norm_lo": 3, "norm_hi": 5, "res_lo": 3, "res_hi": 5, "inq_per_project": 4, "bind_rate": 50, "n_market": 20, "market_lo": 500, "market_hi": 800, "market_attach_rate": 80, "n_info": 20, "info_lo": 500, "info_hi": 800, "info_attach_rate": 90, "session_linked": True, "n_session": 5, "sbill_lo": 150, "sbill_hi": 400, "from_ym": "2024-01", "to_ym": "2026-10", } # ---------------- 小工具 ---------------- def _ym_range(cfg): def _m(s): y, mo = str(s).split("-") return int(y) * 12 + int(mo) a, b = _m(cfg["from_ym"]), _m(cfg["to_ym"]) if a > b: a, b = b, a return a, b def _rand_ym(rng, a, b): m = rng.randint(a, b) return (m // 12, m % 12, m) def _rand_dt(rng, a, b): y, mo, _ = _rand_ym(rng, a, b) return "%04d-%02d-%02d %02d:%02d:%02d" % ( y, mo, rng.randint(1, 28), rng.randint(8, 18), rng.randint(0, 59), rng.randint(0, 59)) def _qty_for_unit(rng, unit): u = unit or "" if u in ("m2", "m²", "㎡"): return round(rng.uniform(50, 2600), 2) if u == "m3": return round(rng.uniform(20, 900), 2) if u == "m": return round(rng.uniform(10, 1200), 2) if u == "t": return round(rng.uniform(0.5, 220), 2) return round(rng.uniform(1, 80), 2) def _res_qty(rng, kind): if kind == 1: return round(rng.uniform(0.05, 2.5), 3) if kind == 3: return round(rng.uniform(0.02, 1.2), 3) return round(rng.uniform(0.1, 150), 2) PARSER_VER_PRICE_FALLBACK = "2026.10.02-1" # 价格解析器兜底(读不到母体源码时用) def _parser_vers(dd): """从母体 app 源码读当前解析器版本(工程/价格两条线)。 stale_batches() 按 kind 分开比,生成器必须同样分开盖版本号,否则全部误报过期。""" proj, price = PARSER_VER_FALLBACK, PARSER_VER_PRICE_FALLBACK bases = [os.path.dirname(dd)] if REF_DIR: rb = os.path.dirname(REF_DIR) if rb not in bases: bases.append(rb) # 测试库在自定义目录时,参考库旁才是母体 for base in bases: core = os.path.join(base, "app", "core") for fname, defv in (("import_job.py", "proj"), ("price_html.py", "price")): try: txt = open(os.path.join(core, fname), encoding="utf-8").read() m = re.search(r"PARSER_VER\s*=\s*['\"]([^'\"]+)", txt) if m: if defv == "proj": proj = m.group(1) else: price = m.group(1) except Exception: pass if proj != PARSER_VER_FALLBACK and price != PARSER_VER_PRICE_FALLBACK: break return proj, price def _paused(): return os.path.exists(PAUSE_FLAG) def _open_db(path): con = sqlite3.connect(path, timeout=60) con.execute("PRAGMA busy_timeout=30000") return con # ---------------- 结构级插入(history 与 session 两库共用一份逻辑数据) ---------------- # 逻辑行里的 owner 索引是本地序号,插入时映射为真实 id。 SQL_H = { "sec": "INSERT INTO sections(batch_id, Number, Name, Total, Ratios) VALUES(?,?,?,?,?)", "uw": "INSERT INTO unit_works(batch_id, Number, Name, Specialty, Total, section_id," " Construction, DivisionalAndElementalWorks, Preliminaries, CostForHSE," " SundryCosts, Tax) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", "div": "INSERT INTO divides(batch_id, uw_id, parent_id, Kind, Number, Name, Total," " Code, x_seq) VALUES(?,?,?,?,?,?,?,?,?)", "bill": "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, x_period_start_m, x_period_end_m)" " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "norm": "INSERT INTO norms(bill_id, Number, Name, Unit, Quantity, Price, Total)" " VALUES(?,?,?,?,?,?,?)", "res": "INSERT INTO norm_res(norm_id, res_code, qty) VALUES(?,?,?)", "lme": "INSERT 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_period_start_m, x_period_end_m) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "lib": "INSERT INTO lme_lib(batch_id, code, name, spec, unit, kind, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?)", "proj": "INSERT INTO lme_proj(batch_id, code, name, spec, unit, kind, qty, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?,?)", } SQL_S = { "sec": "INSERT INTO s_sections(session_id, Number, Name, Total, Ratios) VALUES(?,?,?,?,?)", "uw": "INSERT INTO s_unit_works(session_id, Number, Name, Specialty, Total, section_id," " Construction, DivisionalAndElementalWorks, Preliminaries, CostForHSE," " SundryCosts, Tax) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", "div": "INSERT INTO s_divides(session_id, uw_id, parent_id, Kind, Number, Name, Total," " Code, x_seq) VALUES(?,?,?,?,?,?,?,?,?)", "bill": "INSERT INTO s_bills(session_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(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "norm": "INSERT INTO s_norms(bill_id, Number, Name, Unit, Quantity, Price, Total)" " VALUES(?,?,?,?,?,?,?)", "res": "INSERT INTO s_norm_res(norm_id, res_code, qty) VALUES(?,?,?)", "lme": "INSERT INTO s_lmes(session_id, Number, Name, Specification, Unit, Quantity," " NoTaxPrice, TaxRate, TaxPrice, Kind, x_name_norm, x_spec_norm, x_unit_norm," " x_hash_exact) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", "lib": "INSERT INTO s_lme_lib(session_id, code, name, spec, unit, kind, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?)", "proj": "INSERT INTO s_lme_proj(session_id, code, name, spec, unit, kind, qty, ntp, taxp)" " VALUES(?,?,?,?,?,?,?,?,?)", } def _cols(con, t): return {r[1] for r in con.execute("PRAGMA table_info(%s)" % t)} def _dyn_sql(con, pfx, what, ym): """按库实际列拼 bills/lmes 的 INSERT —— 兼容新旧母体(如旧库无 src_remark)。""" t = pfx + "bills" if what == "bill" else pfx + "lmes" have = _cols(con, t) owner = "batch_id" if pfx == "" else "session_id" if what == "bill": cols = [owner, "uw_id", "div_id", "Number", "Name", "Attr", "Unit", "Quantity", "Price", "Total", "Kind"] nfixed = 11 if "src_remark" in have: cols.append("src_remark") nfixed = 12 cols += ["x_name_norm", "x_attr_norm", "x_unit_norm", "x_hash_exact", "x_hash_semi", "x_seq"] nfixed += 6 if pfx == "" and "x_period_start_m" in have: cols += ["x_period_start_m", "x_period_end_m"] nfixed += 2 else: cols = [owner, "Number", "Name", "Specification", "Unit", "Quantity", "NoTaxPrice", "TaxRate", "TaxPrice", "Kind", "x_name_norm", "x_spec_norm", "x_unit_norm", "x_hash_exact"] nfixed = 14 if pfx == "" and "x_period_start_m" in have: cols += ["x_period_start_m", "x_period_end_m"] nfixed += 2 has_srcrem = "src_remark" in cols has_period = "x_period_start_m" in cols return ("INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(cols), ",".join("?" * len(cols)))), has_srcrem, has_period def insert_tree(con, sqls, owner_id, data, ym=None): """把一份逻辑结构写进指定库(列按库实际情况自适应)。 history 传 ym;session 不传。bill_ids 顺序与 data["norms"] 一一对应。""" cur = con.cursor() pfx = "" if sqls is SQL_H else "s_" bill_sql, sr, pd = _dyn_sql(con, pfx, "bill", ym) lme_sql, _, pdl = _dyn_sql(con, pfx, "lme", ym) sec_map, uw_map, div_map = {}, {}, {} for row in data["secs"]: # (本地序号, Number, Name, Total, Ratios) cur.execute(sqls["sec"], (owner_id,) + tuple(row[1:])) sec_map[row[0]] = cur.lastrowid for row in data["uws"]: vals = [owner_id, row[1], row[2], row[3], row[4], sec_map.get(row[5])] + list(row[6:]) cur.execute(sqls["uw"], vals) uw_map[row[0]] = cur.lastrowid for row in data["divs"]: cur.execute(sqls["div"], (owner_id, uw_map.get(row[0]), 0, row[1], row[2], row[3], row[4], row[5], row[6])) div_map[(row[0], row[6])] = cur.lastrowid bill_ids = [] for row in data["bills"]: # 逻辑行:(本地uw, (本地uw,div序号), Number, Name, Attr, Unit, Qty, Price, # Total, Kind, src_remark, x_seq) vals = [owner_id, uw_map.get(row[0]), div_map.get(row[1]), row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9]] if sr: # 库里有 src_remark vals.append(row[10]) vals += [norm(row[3]), clean_attr(row[4]), norm(row[5]), md5(row[2], row[3], row[5]), md5(row[2], row[5]), row[11]] if pd: # history 库带期次两列 vals += [ym, ym] cur.execute(bill_sql, vals) bill_ids.append(cur.lastrowid) data["bill_ids"] = bill_ids for bi, norms in enumerate(data["norms"]): for nrow in norms: cur.execute(sqls["norm"], (bill_ids[bi],) + tuple(nrow[:6])) nid = cur.lastrowid for (res_code, rq) in nrow[6]: cur.execute(sqls["res"], (nid, res_code, rq)) for row in data["lmes"]: vals = [owner_id] + list(row[:13]) if pdl: vals += [ym, ym] cur.execute(lme_sql, vals) for row in data["lib"]: cur.execute(sqls["lib"], [owner_id] + list(row)) for row in data["proj"]: cur.execute(sqls["proj"], [owner_id] + list(row)) return {"sec": sec_map, "uw": uw_map, "div": div_map} # ---------------- 单个项目(逻辑数据生成,两库共用) ---------------- def build_project_data(rng, cfg, words, m_idx, bid_local=True): """生成一份项目的完整逻辑数据(不落库)。结构键: secs/uws/divs/bills/norms/norms_of_bill/lmes/lib/proj""" n_sec = rng.randint(1, 2) secs, uws, divs, bills, norms, bill_ids = [], [], [], [], [], [] uw_ix = 0 for s in range(1, n_sec + 1): sname = rng.choice(SECTION_NAMES) if n_sec > 1 else "" secs.append((s, str(s), sname, 0.0, rng.choice([0, 0, round(rng.uniform(0.5, 3.2), 2)]))) # 先铺单位工程与分部 div_local = 0 for s in range(1, n_sec + 1): for _ in range(rng.randint(2, 4)): uw_ix += 1 uwn = rng.choice(UW_NAMES) uws.append((uw_ix, "%d.%d" % (s, uw_ix), uwn, rng.randint(1, 5), 0.0, s, 0, 0, 0, 0, 0, 0)) # 费用构成列先置 0, bills 后回填 pool_d = DIV_NAMES[:8] if uwn in ("土建工程", "装饰装修工程") else DIV_NAMES[8:] chosen = rng.sample(pool_d, min(len(pool_d), rng.randint(2, 5))) for di, dvn in enumerate(chosen, 1): div_local += 1 divs.append((uw_ix, "item", "%d.%d" % (s, div_local), dvn, 0.0, "", di)) if rng.random() < 0.75: divs.append((uw_ix, "prelim", "%d.%d" % (s, div_local + 1), "措施项目", 0.0, "", len(chosen) + 1)) # 清单 bill_target = rng.randint(int(cfg["bill_lo"]), max(int(cfg["bill_lo"]), int(cfg["bill_hi"]))) uw_ids = [u[0] for u in uws] seq = 0 for i in range(bill_target): uw_l = rng.choice(uw_ids) ds = [d for d in divs if d[0] == uw_l] if not ds: continue d = rng.choice(ds) if d[1] == "prelim": code10, bnm, unit, attr = rng.choice(PRELIM_ITEMS) kind = "prelim" else: code10, bnm, unit, attr = rng.choice(BILL_ITEMS) kind = None num = "%s%03d" % (code10, rng.randint(1, 999)) qty = _qty_for_unit(rng, unit) price = guess_price(bnm, unit, m_idx) total = round(qty * price, 2) seq += 1 bills.append((uw_l, (d[0], d[6]), num, bnm, attr, unit, qty, price, total, kind, "", seq)) # 每条清单的定额 + 每条定额的工料机 nrm_lo, nrm_hi = int(cfg["norm_lo"]), max(int(cfg["norm_lo"]), int(cfg["norm_hi"])) res_lo, res_hi = int(cfg["res_lo"]), max(int(cfg["res_lo"]), int(cfg["res_hi"])) _u = {} # 真实库同 code 跨批次重复,lme_lib 有 for it in words.lmes: # (batch_id, code) 唯一约束 → 先去重再抽样 _u.setdefault(it[0], it) _uniq = list(_u.values()) lme_pool = rng.sample(_uniq, min(len(_uniq), rng.randint(260, 520))) lme_by_kind = {1: [], 2: [], 3: []} for it in lme_pool: lme_by_kind.setdefault(it[4] or 2, []).append(it) # 语义匹配:清单名关键词 → 同族定额;定额名 → 人工/材料/机械构成 NKEYS = ["土方", "土", "混凝土", "钢筋", "砌", "防水", "卷材", "抹灰", "油漆", "涂料", "窗", "门", "脚手", "道路", "沥青", "人行", "井", "给水", "排水", "电缆", "桥架", "灯", "管", "乔木", "灌木", "草", "绿地", "面层", "基层", "钢结构"] MKEYS = ["挖掘", "运输", "汽车", "泵", "压路", "起重", "搅拌", "切断", "装载", "吊装", "夯实", "打桩", "机械"] # 点名映射:内置池语料有限,专有清单直接指族(命中不了再走通用关键词) HINTS = [("措施项目费", ["脚手", "安全文明"]), ("安全文明", ["脚手", "安全文明"]), ("综合脚手架", ["脚手"]), ("栽植", ["乔木", "灌木"]), ("棕榈", ["乔木", "灌木"]), ("绿地", ["绿地"]), ("喷播", ["草", "喷播"]), ("路灯", ["灯", "路灯"]), ("灯具", ["灯"]), ("变压器", ["电缆", "变压器"]), ("检查井", ["井"]), ("桥架", ["桥架"]), ("电缆", ["电缆"]), ("井盖", ["井"])] for b in bills: cand = None for hint, hs in HINTS: if hint in b[3]: cand = [n for n in words.norms if any(h in n[1] for h in hs)] break if not cand: keys = [kk for kk in NKEYS if kk in b[3]] cand = [n for n in words.norms if any(kk in n[1] for kk in keys)] or list(words.norms) k = rng.randint(nrm_lo, nrm_hi) bl = [] used = set() for _ in range(k): pickable = [n for n in cand if n[0] not in used] or cand ncode, nname, nunit = rng.choice(pickable) used.add(ncode) nqty = max(round(b[6] * rng.uniform(0.05, 0.6), 2), 0.01) nprice = guess_price(nname, nunit, m_idx) rlist = [] # 人工必配 1 条 lab = lme_by_kind.get(1) or lme_pool it = rng.choice(lab) rlist.append((it[0], _res_qty(rng, 1))) # 材料按剩余名额 nmat = max(1, rng.randint(res_lo, res_hi) - 1) mats = [n for n in words.norms] # 占位避免歧义 mat_pool = lme_by_kind.get(2) or lme_pool for _ in range(nmat): it = rng.choice(mat_pool) rlist.append((it[0], _res_qty(rng, 2))) # 定额名含机械词才配机械(更贴近真实消耗结构) if any(mk in nname for mk in MKEYS) and lme_by_kind.get(3): it = rng.choice(lme_by_kind[3]) rlist.append((it[0], _res_qty(rng, 3))) bl.append((ncode, nname, nunit, nqty, nprice, round(nqty * nprice, 2), rlist)) norms.append(bl) # 工料机主表 / lib / proj lmes, lib, proj = [], [], [] agg = {} for (code, nm2, spec, unit, kind, price0) in lme_pool: if not price0: price0 = guess_price(nm2, unit, m_idx) rate = rng.choice([0.13, 0.09, 0.03]) ntp = round(price0, 2) taxp = round(price0 * (1 + rate), 2) lmes.append((code, nm2, spec, unit, round(rng.uniform(1, 500), 2), ntp, rate, taxp, kind, norm(nm2), norm(spec), norm(unit), md5(nm2, spec, unit))) lib.append((code, nm2, spec, unit, kind, ntp, taxp)) agg[code] = [nm2, spec, unit, kind, 0.0, ntp, taxp] for bl in norms: for nrow in bl: for (rc, rq) in nrow[6]: if rc in agg: agg[rc][4] += rq for code, (nm2, spec, unit, kind, q, ntp, taxp) in agg.items(): proj.append((code, nm2, spec, unit, kind, round(q, 2), ntp, taxp)) # 单位工程费用构成 + 分部/单项合计 uw_sum = {} prelim_sum = {} for b in bills: uw_sum[b[0]] = uw_sum.get(b[0], 0) + b[8] if b[9] == "prelim": prelim_sum[b[0]] = prelim_sum.get(b[0], 0) + b[8] uws2 = [] for u in uws: item = uw_sum.get(u[0], 0.0) pre = prelim_sum.get(u[0], 0.0) hse = round(item * rng.uniform(0.02, 0.04), 2) tax = round((item + pre) * 0.09, 2) sund = round(item * 0.01, 2) total = round(item + pre + hse + tax + sund, 2) uws2.append((u[0], u[1], u[2], u[3], total, u[5], round(item + pre + hse + sund, 2), item, pre, hse, sund, tax)) # 分部合计 dsum = {} for b in bills: dsum[b[1]] = dsum.get(b[1], 0) + b[8] return { "secs": secs, "uws": uws2, "divs": divs, "bills": bills, "norms": norms, "bill_ids": bill_ids, "lmes": lmes, "lib": lib, "proj": proj, "div_sum": dsum, } # ---------------- 项目主循环 ---------------- def gen_projects(hc, sc, dd, cfg, rng, words, log): y_a, y_b = _ym_range(cfg) pver = _parser_vers(dd)[0] # 工程线版本 n = int(cfg["n_project"]) linked = bool(cfg.get("session_linked")) stats = {"project": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0, "inq": 0, "binds": 0, "sessions": 0} for i in range(n): if _paused(): log(" 软暂停:第 %d/%d 个项目处停止(已生成的保留)。" % (i + 1, n)) break stem = rng.choice(words.stems).strip()[:22] name = "测试项目%03d-%s" % (i + 1, stem) sha_src = hashlib.sha256(("testdata-src|%s" % name).encode("utf-8")).hexdigest() src_name = "%s_%s.cos4" % (sha_src, name) _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) bu = rng.choice(words.builders) dt = _rand_dt(rng, y_a, y_b) data = build_project_data(rng, cfg, words, m_idx) total = round(sum(u[4] for u in data["uws"]), 2) info = {"编号": "TC-%04d-%02d" % (m_idx // 12, m_idx % 12), "专业": rng.choice(["市政", "建筑", "安装", "园林"]), "计价标准": "2025造价数据标准", "建设单位": bu} feat = [{"n": "合同工期", "v": "%d 日历天" % rng.randint(120, 900)}, {"n": "质量要求", "v": rng.choice(["合格", "市优", "省优"])}] cur = hc.cursor() bcols = ("kind Name FileKind BulidUnit x_province x_city x_district" " x_period_start_m x_period_end_m x_enabled x_total x_rows_bill" " x_rows_lme x_imported_at x_src_hash x_note x_parser_ver x_info" " x_feat is_mock").split() bvals = ["project", name, rng.choice([1, 2, 3, 4]), bu, prov, city, dist, m_idx, m_idx, 1, total, len(data["bills"]), len(data["lmes"]), dt, src_name, "testdata 自动生成", pver, json.dumps(info, ensure_ascii=False), json.dumps(feat, ensure_ascii=False), 1] assert len(bcols) == len(bvals), (len(bcols), len(bvals)) cur.execute("INSERT INTO batches(%s) VALUES(%s)" % (",".join(bcols), ",".join("?" * len(bcols))), bvals) bid = cur.lastrowid maps = insert_tree(hc, SQL_H, bid, data, ym=m_idx) # 分部 / 单项合计回填 cur.executemany("UPDATE divides SET Total=? WHERE id=?", [(t, maps["div"][k]) for k, t in data["div_sum"].items() if k in maps["div"]]) sec_sum = {} for u in data["uws"]: sec_sum[u[5]] = round(sec_sum.get(u[5], 0) + u[4], 2) cur.executemany("UPDATE sections SET Total=? WHERE id=?", [(t, maps["sec"][s]) for s, t in sec_sum.items() if s in maps["sec"]]) # 询价附件 inq_n = max(0, int(cfg.get("inq_per_project", 0))) inq_ids = [] for k in range(inq_n): fname = "%s-%d%s.%s" % (name, k + 1, rng.choice(INQ_NAMES), rng.choice(INQ_EXT)) sha = hashlib.sha256(("testdata-inq|%s|%d" % (name, k)).encode("utf-8")).hexdigest() rel = write_file_rel(dd, "inquiry", sha, fname) sz = os.path.getsize(os.path.join(dd, rel)) cur.execute( """INSERT INTO inquiry_files(batch_id, sha256, original_name, stored_path, size, ext, uploaded_at) VALUES(?,?,?,?,?,?,?)""", (bid, sha, fname, rel, sz, fname.rsplit(".", 1)[-1], time.strftime("%Y-%m-%d %H:%M:%S"))) inq_ids.append(cur.lastrowid) stats["inq"] += len(inq_ids) # 工料机绑定率 bind_rate = max(0, min(100, int(cfg.get("bind_rate", 0)))) lme_ids = [r[0] for r in cur.execute( "SELECT id FROM lmes WHERE batch_id=?", (bid,)).fetchall()] if inq_ids and bind_rate and lme_ids: bind_n = max(1, int(round(len(lme_ids) * bind_rate / 100.0))) picks = rng.sample(lme_ids, min(bind_n, len(lme_ids))) cur.executemany( "INSERT OR REPLACE INTO lme_attach(lme_id, batch_id, file_id) VALUES(?,?,?)", [(l, bid, rng.choice(inq_ids)) for l in picks]) stats["binds"] += len(picks) # uploads 源文件占位(联动/重新解析不缺文件) write_file_rel(dd, "uploads", sha_src, "%s.cos4" % name) hc.commit() stats["project"] += 1 stats["bills"] += len(data["bills"]) stats["norms"] += sum(len(x) for x in data["norms"]) stats["res"] += sum(len(n2[6]) for x in data["norms"] for n2 in x) stats["lmes"] += len(data["lmes"]) # 联动会话:同一份逻辑数据镜像进 session.db if linked and sc is not None: scur = sc.cursor() scur.execute( """INSERT INTO sessions(name, base_period_m, period_from, period_to, x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_total, x_info, x_feat, x_batch_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (name, m_idx, m_idx, m_idx, prov, city, dist, bu, src_name, dt, total, json.dumps(info, ensure_ascii=False), json.dumps(feat, ensure_ascii=False), bid)) sid = scur.lastrowid insert_tree(sc, SQL_S, sid, data, ym=None) sc.commit() stats["sessions"] += 1 log(" [%d/%d] %s:清单 %d、定额 %d、工料机 %d 种、附件 %d 份%s" % ( i + 1, n, name, len(data["bills"]), sum(len(x) for x in data["norms"]), len(data["lmes"]), len(inq_ids), "(+镜像会话)" if linked else "")) return stats # ---------------- 独立工作台会话 ---------------- def gen_sessions_standalone(sc, cfg, rng, words, log): y_a, y_b = _ym_range(cfg) n = int(cfg.get("n_session", 0)) sub = dict(cfg) sub["bill_lo"], sub["bill_hi"] = cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400) stats = {"sessions": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0} for i in range(n): if _paused(): log(" 软暂停:第 %d/%d 份会话处停止。" % (i + 1, n)) break name = "测试工作台-%03d-%s" % (i + 1, rng.choice(words.stems).strip()[:18]) sha_src = hashlib.sha256(("testdata-src|%s" % name).encode("utf-8")).hexdigest() src_name = "%s_%s.cos4" % (sha_src, name) _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) bu = rng.choice(words.builders) dt = _rand_dt(rng, y_a, y_b) data = build_project_data(rng, sub, words, m_idx) total = round(sum(u[4] for u in data["uws"]), 2) scur = sc.cursor() scur.execute( """INSERT INTO sessions(name, base_period_m, period_from, period_to, x_province, x_city, x_district, bulid_unit, src_name, imported_at, x_total, x_info, x_feat, x_batch_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,0)""", (name, m_idx, m_idx, m_idx, prov, city, dist, bu, src_name, dt, total, json.dumps({"编号": "TC-%04d-%02d" % (m_idx // 12, m_idx % 12)}, ensure_ascii=False), "[]")) sid = scur.lastrowid insert_tree(sc, SQL_S, sid, data, ym=None) sc.commit() stats["sessions"] += 1 stats["bills"] += len(data["bills"]) stats["norms"] += sum(len(x) for x in data["norms"]) log(" [%d/%d] %s:清单 %d(独立会话)" % (i + 1, n, name, len(data["bills"]))) return stats # ---------------- 市场价 / 信息价 ---------------- def gen_prices(hc, dd, cfg, rng, words, log): y_a, y_b = _ym_range(cfg) pver = _parser_vers(dd)[1] # 价格线版本 seen, pool = set(), [] for it in words.lmes: key = (it[1], it[2], it[3]) if key not in seen: seen.add(key) pool.append(it) stats = {"market": 0, "info": 0, "price_rows": 0, "price_attach": 0} plan = [ ("market", "测试市场价", int(cfg.get("n_market", 0)), int(cfg.get("market_lo", 500)), int(cfg.get("market_hi", 800)), int(cfg.get("market_attach_rate", 80))), ("info", "测试信息价", int(cfg.get("n_info", 0)), int(cfg.get("info_lo", 500)), int(cfg.get("info_hi", 800)), int(cfg.get("info_attach_rate", 90))), ] for kind, prefix, cnt, lo, hi, rate in plan: if cnt <= 0: continue lo = max(1, min(lo, len(pool))) hi = max(lo, min(hi, len(pool))) for i in range(cnt): if _paused(): log(" 软暂停:%s 第 %d/%d 份处停止。" % (prefix, i + 1, cnt)) break _, _, m_idx = _rand_ym(rng, y_a, y_b) prov, city, dist = rng.choice(REGIONS) pub = rng.choice(PUBLISHERS) if kind == "info" else "" bname = "%s-%s%03d" % (prefix, rng.choice(BLOCKS)[:6], i + 1) dt = _rand_dt(rng, y_a, y_b) cur = hc.cursor() bcols = ("kind Name FileKind BulidUnit x_province x_city x_district" " x_period_start_m x_period_end_m x_enabled x_total x_rows_bill" " x_rows_lme x_imported_at x_src_hash x_note x_publisher" " x_parser_ver is_mock").split() bvals = [kind, bname[:200], None, "", prov, city, dist, m_idx, m_idx, 1, 0, 0, 0, dt, "mock://%s" % sha_src_of(bname), "testdata 自动生成", pub, pver, 1] assert len(bcols) == len(bvals), (len(bcols), len(bvals)) cur.execute("INSERT INTO batches(%s) VALUES(%s)" % (",".join(bcols), ",".join("?" * len(bcols))), bvals) bid = cur.lastrowid n_rows = rng.randint(lo, hi) sample = rng.sample(pool, n_rows) block = rng.choice(BLOCKS) rows = [] for (code, nm2, spec, unit, kindl, price0) in sample: nt = guess_price(nm2, unit, m_idx) rate2 = rng.choice([0.13, 0.09, 0.03, None]) tp = round(nt * (1 + rate2), 2) if rate2 else None rows.append((bid, code, nm2, spec, unit, nt, rate2, tp, rng.choice(BLOCK_CLASSES[block]), "testdata 模拟区间价", block, norm(nm2), norm(spec), norm(unit), md5(nm2, spec, unit), m_idx, m_idx)) cur.executemany( """INSERT INTO prices(batch_id, Code, Name, Specification, Unit, NoTaxPrice, TaxRate, TaxPrice, Class, Note, Block, x_name_norm, x_spec_norm, x_unit_norm, x_hash_exact, x_period_start_m, x_period_end_m) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", rows) cur.execute("UPDATE batches SET x_rows_price=? WHERE id=?", (n_rows, bid)) # 附件率:命中才挂价格原件 if rng.random() * 100 < rate: fname = "%s-%s.%s" % (bname, rng.choice(INQ_NAMES), rng.choice(INQ_EXT)) sha = hashlib.sha256(("testdata-att|%s" % bname).encode("utf-8")).hexdigest() rel = write_file_rel(dd, "attachments", sha, fname) sz = os.path.getsize(os.path.join(dd, rel)) cur.execute( """INSERT OR IGNORE INTO attachments(sha256, stored_path, original_name, size, uploaded_at) VALUES(?,?,?,?,?)""", (sha, rel, fname, sz, time.strftime("%Y-%m-%d %H:%M:%S"))) cur.execute("UPDATE batches SET x_attach_sha=? WHERE id=?", (sha, bid)) stats["price_attach"] += 1 hc.commit() stats[kind] += 1 stats["price_rows"] += n_rows log(" %s:%d 份完成(每份 %d~%d 条,附件率 %d%%)" % (prefix, cnt, lo, hi, rate)) return stats def sha_src_of(s): return hashlib.sha256(("testdata-price|%s" % s).encode("utf-8")).hexdigest() # ---------------- 版本对齐(测试库搬到别的母体后用) ---------------- def align_testdata(dd, log=print): """把「测试」批次的解析器版本对齐到本数据目录旁母体 app 的当前版本。 测试库从 A 母体生成、换到 B 母体(如工作区)使用时,stale_batches 会误报过期—— 跑一次本函数即可。只动 Name LIKE '测试%' 的行。""" proj, price = _parser_vers(dd) log("母体当前解析器:工程=%s / 价格=%s" % (proj, price)) total = 0 for path in (db_paths(dd)[1], db_paths(dd)[0]): # 优先测试库;已换名成 history.db 的也认 if not os.path.exists(path): continue con = _open_db(path) try: n = con.execute("SELECT COUNT(*) FROM batches WHERE Name LIKE '测试%'").fetchone()[0] except Exception: con.close() continue if not n: con.close() continue a = con.execute( "UPDATE batches SET x_parser_ver=? WHERE kind='project' AND Name LIKE '测试%' " "AND (x_parser_ver IS NULL OR x_parser_ver<>?)", (proj, proj)).rowcount b = con.execute( "UPDATE batches SET x_parser_ver=? WHERE kind<>'project' AND Name LIKE '测试%' " "AND (x_parser_ver IS NULL OR x_parser_ver<>?)", (price, price)).rowcount con.commit() con.close() log("%s:对齐 %d 个批次(工程 %d / 价格 %d)" % (os.path.basename(path), a + b, a, b)) total += a + b if not total: log("没有需要改版本的测试批次。") return total # ---------------- 统计 ---------------- def stats_of(dd): out = {"data_dir": dd, "db_file": TEST_H} th, ts = db_paths(dd)[1], db_paths(dd)[3] if not os.path.exists(th): out["note"] = "测试库尚未生成(%s 不存在),真实库从未被本工具写过" % TEST_H return out hc = _open_db(th) q = "FROM batches WHERE is_mock=1 AND Name LIKE '测试%'" for k in ("project", "market", "info"): out["b_%s" % k] = hc.execute("SELECT COUNT(*) " + q + " AND kind=?", (k,)).fetchone()[0] joins = { "bills": "FROM bills b JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "norms": "FROM norms n JOIN bills b ON b.id=n.bill_id JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "norm_res": "FROM norm_res r JOIN norms n ON n.id=r.norm_id JOIN bills b ON b.id=n.bill_id JOIN batches bt ON bt.id=b.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lmes": "FROM lmes l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "prices": "FROM prices p JOIN batches bt ON bt.id=p.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "inquiry_files": "FROM inquiry_files f JOIN batches bt ON bt.id=f.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_attach": "FROM lme_attach a JOIN batches bt ON bt.id=a.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_lib": "FROM lme_lib l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", "lme_proj": "FROM lme_proj l JOIN batches bt ON bt.id=l.batch_id WHERE bt.is_mock=1 AND bt.Name LIKE '测试%'", } for t, sql in joins.items(): try: out[t] = hc.execute("SELECT COUNT(*) " + sql).fetchone()[0] except Exception: out[t] = -1 out["price_attach_batches"] = hc.execute( "SELECT COUNT(*) " + q + " AND x_attach_sha IS NOT NULL").fetchone()[0] hc.close() sp = ts if os.path.exists(sp): sc = _open_db(sp) out["s_sessions"] = sc.execute( "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] for t in ("s_bills", "s_norms", "s_lmes"): try: if t == "s_norms": # s_norms.bill_id 挂在 s_bills 上,要经两层 out[t] = sc.execute( "SELECT COUNT(*) FROM s_norms WHERE bill_id IN (SELECT id FROM s_bills " "WHERE session_id IN (SELECT id FROM sessions WHERE name LIKE '测试%'))" ).fetchone()[0] else: out[t] = sc.execute( "SELECT COUNT(*) FROM %s WHERE session_id IN " "(SELECT id FROM sessions WHERE name LIKE '测试%%')" % t).fetchone()[0] except Exception: out[t] = -1 sc.close() return out # ---------------- 分块删除 ---------------- def delete_testdata(dd, keep_files=False, log=print): th, ts = db_paths(dd)[1], db_paths(dd)[3] if not os.path.exists(th): log("测试库 %s 不存在——没有可删的测试数据(真实库从未被本工具写过)。" % TEST_H) return {"batches": 0, "_remaining": stats_of(dd)} hc = _open_db(th) cur = hc.cursor() n0 = cur.execute( "SELECT COUNT(*) FROM batches WHERE is_mock=1 AND Name LIKE '测试%'").fetchone()[0] log("待删除测试批次:%d 份(分块 %d/块)" % (n0, CHUNK)) st = {} del_files = [] t0 = time.time() def rec(key, n): st[key] = st.get(key, 0) + max(n or 0, 0) while True: ids = [r[0] for r in cur.execute( "SELECT id FROM batches WHERE is_mock=1 AND Name LIKE '测试%' LIMIT ?", (CHUNK,)).fetchall()] if not ids: break ph = ",".join("?" * len(ids)) # 先收集要删的物理文件(询价附件 / 价格原件 / uploads 源文件占位) for (rel,) in cur.execute( "SELECT stored_path FROM inquiry_files WHERE batch_id IN (%s)" % ph, ids): del_files.append(rel) shas = [r[0] for r in cur.execute( "SELECT DISTINCT x_attach_sha FROM batches WHERE id IN (%s)" % ph, ids) if r[0]] if shas: for (rel,) in cur.execute( "SELECT stored_path FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas): del_files.append(rel) for (src,) in cur.execute( "SELECT x_src_hash FROM batches WHERE id IN (%s) AND x_src_hash LIKE '%%_%%'" % ph, ids): sha = src.split("_", 1)[0] if len(sha) == 64: del_files.append(os.path.join("uploads", sha[:2], src)) # 子查询链:norm_res → norms → bills(bills 删之前删) rec("norm_res", cur.execute( "DELETE FROM norm_res WHERE norm_id IN (SELECT n.id FROM norms n " "JOIN bills b ON b.id=n.bill_id WHERE b.batch_id IN (%s))" % ph, ids).rowcount) rec("norms", cur.execute( "DELETE FROM norms WHERE bill_id IN " "(SELECT id FROM bills WHERE batch_id IN (%s))" % ph, ids).rowcount) for t in ("bills", "lmes", "lme_res", "lme_lib", "lme_proj", "divides", "unit_works", "sections", "prices", "inquiry_files", "lme_attach"): rec(t, cur.execute("DELETE FROM %s WHERE batch_id IN (%s)" % (t, ph), ids).rowcount) if shas: rec("attachments", cur.execute( "DELETE FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas).rowcount) rec("batches", cur.execute( "DELETE FROM batches WHERE id IN (%s)" % ph, ids).rowcount) hc.commit() log(" 已删 %d 份(累计)" % (n0 - cur.execute( "SELECT COUNT(*) FROM batches WHERE is_mock=1 AND Name LIKE '测试%'").fetchone()[0])) hc.close() # 工作台(测试库) sp = ts s0 = 0 if os.path.exists(sp): sc = _open_db(sp) scur = sc.cursor() s0 = scur.execute( "SELECT COUNT(*) FROM sessions WHERE name LIKE '测试%'").fetchone()[0] if s0: log("工作台测试会话:%d 份" % s0) while True: ids = [r[0] for r in scur.execute( "SELECT id FROM sessions WHERE name LIKE '测试%' LIMIT ?", (CHUNK,)).fetchall()] if not ids: break ph = ",".join("?" * len(ids)) rec("s_remarks", scur.execute( "DELETE FROM s_remarks WHERE src_key IN " "(SELECT src_name FROM sessions WHERE id IN (%s))" % ph, ids).rowcount) rec("s_norm_res", scur.execute( "DELETE FROM s_norm_res WHERE norm_id IN (SELECT n.id FROM s_norms n " "JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id IN (%s))" % ph, ids).rowcount) rec("s_norms", scur.execute( "DELETE FROM s_norms WHERE bill_id IN " "(SELECT id FROM s_bills WHERE session_id IN (%s))" % ph, ids).rowcount) for t in ("s_bills", "s_lmes", "s_lme_res", "s_lme_lib", "s_lme_proj", "s_divides", "s_unit_works", "s_sections"): rec(t, scur.execute( "DELETE FROM %s WHERE session_id IN (%s)" % (t, ph), ids).rowcount) rec("sessions", scur.execute( "DELETE FROM sessions WHERE id IN (%s)" % ph, ids).rowcount) sc.commit() sc.close() # 物理文件 n_files = 0 if not keep_files: for rel in del_files: del_file(dd, rel) n_files += 1 log("删除完成,用时 %.1fs。物理文件:%s(%d 个路径)" % ( time.time() - t0, "已删" if not keep_files else "保留(--keep-files)", len(del_files))) # 统计:删了多少 / 还剩多少 st["batches_total"] = st.get("batches", 0) st["_remaining"] = stats_of(dd) return st # ---------------- 编排入口 ---------------- def run(cfg, log=print): global REF_DIR REF_DIR = (cfg.get("ref_dir") or "").strip() or None dd = cfg.get("data_dir") or find_data_dir() if not dd: log("!! 找不到数据目录(history.db)。请在控制台里手动指定数据目录。") return False th, ts = ensure_test_dbs(dd, log) hc = _open_db(th) sc = _open_db(ts) if os.path.exists(ts) else None rng = random.Random() # 每次运行真随机(不固定种子) words = Words(hc) log("参考库目录:%s" % _disp(os.path.dirname(db_paths(dd)[0]))) log("测试库目录:%s" % _disp(dd)) log("词料:项目名 %d / 定额 %d / 工料机 %d / 建设单位 %d" % ( len(words.stems), len(words.norms), len(words.lmes), len(words.builders))) t0 = time.time() st = {} if int(cfg.get("n_project", 0)) > 0: log("== 后台项目(%d 份,清单 %d~%d/项目,定额 %d~%d/清单,工料机 %d~%d/定额)==" % ( cfg["n_project"], cfg["bill_lo"], cfg["bill_hi"], cfg["norm_lo"], cfg["norm_hi"], cfg["res_lo"], cfg["res_hi"])) st.update(gen_projects(hc, sc, dd, cfg, rng, words, log)) if int(cfg.get("n_market", 0)) or int(cfg.get("n_info", 0)): log("== 市场价/信息价 ==") st.update(gen_prices(hc, dd, cfg, rng, words, log)) if sc is not None and not cfg.get("session_linked") and int(cfg.get("n_session", 0)) > 0: log("== 独立工作台会话(%d 份,清单 %d~%d/份)==" % ( cfg["n_session"], cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400))) st.update(gen_sessions_standalone(sc, cfg, rng, words, log)) hc.close() if sc is not None: sc.close() log("== 汇总 ==") for k, v in sorted(st.items()): log(" %s: %s" % (k, v)) log("完成,用时 %.1fs。" % (time.time() - t0)) return True def main(): ap = argparse.ArgumentParser(description="testdata 测试数据生成器") ap.add_argument("--check", action="store_true", help="统计现有测试数据") ap.add_argument("--run", metavar="CFG_JSON", help="按参数 json 生成") ap.add_argument("--align-ver", action="store_true", help="把测试批次的解析器版本对齐到本母体当前版本(换母体使用后跑一次)") ap.add_argument("--delete", action="store_true", help="分块删除全部测试数据") ap.add_argument("--yes", action="store_true", help="跳过删除确认") ap.add_argument("--keep-files", action="store_true", help="删除时保留附件物理文件") args = ap.parse_args() dd = find_data_dir() if args.check: if not dd: print("!! 找不到数据目录(history.db)") sys.exit(1) s = stats_of(dd) print("数据目录:%s" % _disp(dd)) for k, v in s.items(): print(" %s: %s" % (k, v)) return if args.delete: if not dd: print("!! 找不到数据目录(history.db)") sys.exit(1) if not args.yes: ans = input("确认真删除全部测试数据?(输入 yes 继续)").strip().lower() if ans != "yes": print("已取消。") return st = delete_testdata(dd, keep_files=args.keep_files) print("== 删除统计 ==") for k, v in sorted(st.items()): if k != "_remaining": print(" 已删 %s: %s" % (k, v)) r = st.get("_remaining", {}) print("== 现在还剩(测试数据)==") for k, v in r.items(): print(" %s: %s" % (k, v)) return if args.align_ver: if not dd: print("!! 找不到数据目录") sys.exit(1) align_testdata(dd) return if args.run: with open(args.run, encoding="utf-8") as f: cfg = json.load(f) run(cfg) return print("用法:gen_testdata.py --check | --run cfg.json | --delete [--yes] [--keep-files]") if __name__ == "__main__": main()