253 lines
13 KiB
Python
253 lines
13 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
模拟生成 100 份市场价/信息价批次(每份 >=500 条价格明细),每份挂一个随机附件。
|
||
|
||
口径说明(务必与软件一致):
|
||
- 价格明细的 材料编码/名称/规格/单位 取自现有项目 lmes 去重池("根据现有项目工料机");
|
||
价格随机生成(按材料关键词给合理区间),其余字段按 api_server 入库口径填。
|
||
- 归一化与 x_hash_exact 完全复刻 api_server._norm / _md5,保证进库后能被软件比对命中。
|
||
- 附件走 batches.x_attach_sha -> attachments 表(= 市场价原件/信息价原件)。
|
||
与 inquiry_files/lme_attach(项目专属询价附件)无关,不破坏"询价附件=项目专属"规则。
|
||
每份批次生成一个真实小文件存入 data/attachments/<sha[:2]>/。
|
||
- 幂等:运行前先清掉 Name 以"模拟"开头的旧批次(含其价格、附件文件、attachments 行)。
|
||
|
||
运行:python gen_price_mock.py (默认 100 份,每份 500~900 条)
|
||
python gen_price_mock.py 30 400 600 (30 份,每份 400~600 条)
|
||
"""
|
||
import sqlite3, os, re, hashlib, random, sys, time
|
||
|
||
def _resolve_db():
|
||
cands = []
|
||
try:
|
||
here = os.path.dirname(os.path.abspath(__file__))
|
||
cands.append(os.path.normpath(os.path.join(here, "..", "..", "data", "history.db")))
|
||
except Exception:
|
||
pass
|
||
cands.append(os.path.normpath(os.path.join(os.getcwd(), "造价审核", "data", "history.db")))
|
||
cands.append(os.path.normpath(os.path.join(os.getcwd(), "data", "history.db")))
|
||
cands.append("造价审核/data/history.db")
|
||
seen = set()
|
||
for c in cands:
|
||
if c in seen:
|
||
continue
|
||
seen.add(c)
|
||
if os.path.exists(c):
|
||
return c
|
||
return cands[0]
|
||
|
||
DB = _resolve_db()
|
||
DATA_DIR = os.path.dirname(DB) # .../造价审核/data
|
||
ATTACH_DIR = os.path.join(DATA_DIR, "attachments")
|
||
PARSER_VER = "2026.10.02-1"
|
||
|
||
# ---- 复刻 api_server 归一化(必须与软件一致,否则比对命中不了)----
|
||
def _norm(s):
|
||
s = (s or "").strip().replace("(", "(").replace(")", ")").replace("×", "*")
|
||
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 guess_price(name, unit):
|
||
n = name or ""
|
||
if "人工" in n or "工日" in (unit or ""):
|
||
return round(random.uniform(80, 260), 2)
|
||
if any(k in n for k in ("水泥", "砂", "石", "砖", "混凝土", "砂浆", "砌块", "墙材")):
|
||
return round(random.uniform(20, 600), 2)
|
||
if any(k in n for k in ("钢筋", "型钢", "钢管", "钢板", "钢带", "镀锌", "钢材")):
|
||
return round(random.uniform(3000, 6500), 2)
|
||
if any(k in n for k in ("电缆", "电线", "母线", "导线")):
|
||
return round(random.uniform(5, 400), 2)
|
||
if any(k in n for k in ("柴油", "汽油", "电", "水", "燃气")):
|
||
return round(random.uniform(0.5, 12), 2)
|
||
if any(k in n for k in ("机械", "台班", "挖掘机", "起重机", "泵车", "装载机", "打桩")):
|
||
return round(random.uniform(150, 3000), 2)
|
||
if any(k in n for k in ("门", "窗", "玻璃", "涂料", "防水", "卷材", "管材")):
|
||
return round(random.uniform(15, 800), 2)
|
||
if any(k in n for k in ("乔木", "灌木", "苗木", "地被", "草坪", "棕榈", "竹")):
|
||
return round(random.uniform(5, 1500), 2)
|
||
return round(random.uniform(2, 2000), 2)
|
||
|
||
CLASSES = [
|
||
"一、黑色及有色金属", "二、安全网、施工围挡",
|
||
"三、水泥、砖、石、混凝土制品、墙材、瓷砖", "四、PC装配式构件",
|
||
"五、木材料及其制品、装饰板材", "六、玻璃及玻璃制品", "七、防火门",
|
||
"八、涂料及防腐、防水材料", "十二、开关、插座", "十三、电线、电缆",
|
||
"十四、电线电缆敷设管材", "十五、电线电缆桥架(国标厚度)",
|
||
"十六、密集型铜导体母线槽(外壳防护等级IP65)",
|
||
"一、假植乔木", "二、假植棕榈科植物", "三、观赏竹类", "四、藤本植物",
|
||
"五、袋装灌木", "六、袋装地被", "七、水生植物", "八、时花", "九、红树林植物",
|
||
"横琴粤澳深度合作区材料市场综合价", "万山各岛建设工程人工、机械、材料市场参考价",
|
||
]
|
||
BLOCKS = [
|
||
"珠海市建材设备市场综合价", "珠海市2026年4-6月园林苗木市场信息",
|
||
"横琴粤澳深度合作区材料市场综合价", "万山各岛建设工程人工、机械、材料市场参考价",
|
||
]
|
||
# 各区块对应的真实分类集合(让模拟数据看起来像真实导入,而不是乱配)
|
||
BLOCK_CLASSES = {
|
||
"珠海市建材设备市场综合价": [
|
||
"一、黑色及有色金属", "二、安全网、施工围挡",
|
||
"三、水泥、砖、石、混凝土制品、墙材、瓷砖", "四、PC装配式构件",
|
||
"五、木材料及其制品、装饰板材", "六、玻璃及玻璃制品", "七、防火门",
|
||
"八、涂料及防腐、防水材料", "十二、开关、插座", "十三、电线、电缆",
|
||
"十四、电线电缆敷设管材", "十五、电线电缆桥架(国标厚度)",
|
||
"十六、密集型铜导体母线槽(外壳防护等级IP65)",
|
||
],
|
||
"珠海市2026年4-6月园林苗木市场信息": [
|
||
"一、假植乔木", "二、假植棕榈科植物", "三、观赏竹类", "四、藤本植物",
|
||
"五、袋装灌木", "六、袋装地被", "七、水生植物", "八、时花", "九、红树林植物",
|
||
],
|
||
"横琴粤澳深度合作区材料市场综合价": ["横琴粤澳深度合作区材料市场综合价"],
|
||
"万山各岛建设工程人工、机械、材料市场参考价": ["万山各岛建设工程人工、机械、材料市场参考价"],
|
||
}
|
||
REGIONS = [
|
||
("广东省", "珠海市", "香洲区"), ("广东省", "珠海市", "横琴"),
|
||
("广东省", "珠海市", "万山镇"), ("福建省", "福州市", "漳州区"),
|
||
("广西", "桂林市", "桂林区"),
|
||
]
|
||
PUBS = ["珠海市住房和城乡建设局", "珠海市建设工程造价管理站", "广东省建设工程标准定额站"]
|
||
EXTS = ["pdf", "zip", "rar", "txt", "xlsx", "docx"]
|
||
ATTACH_NAMES = ["询价单", "报价函", "市场调研记录", "厂商回复", "价格确认表", "采购公告", "成交公示"]
|
||
|
||
|
||
def make_attachment(cur, bid, kind, bname):
|
||
"""生成真实小文件 + 写 attachments 行 + 关联 batches.x_attach_sha。返回 sha。
|
||
|
||
文件名按 bname 确定性生成(sha 取 bname 的散列、ext 由 sha 推导),
|
||
因此重跑会原地覆盖同一文件,不会累积孤儿文件,也不必批量删文件(避免触发安全删除护栏)。
|
||
"""
|
||
sha = hashlib.sha256(("mock-price|%s" % bname).encode("utf-8")).hexdigest()
|
||
ext = EXTS[int(sha, 16) % len(EXTS)]
|
||
ori = "%s.%s" % (bname, ext)
|
||
if ext == "pdf":
|
||
content = b"%PDF-1.4\n" + ("%% mock attachment for %s\n" % bname).encode("utf-8") \
|
||
+ os.urandom(random.randint(1024, 4096))
|
||
elif ext in ("zip", "rar"):
|
||
hdr = b"PK\x03\x04" if ext == "zip" else b"Rar!\x1a\x07"
|
||
content = hdr + os.urandom(random.randint(2048, 8192))
|
||
else:
|
||
content = ("模拟附件(%s)\n本文件为造价审核自动生成的测试样本,无实际业务内容。\n"
|
||
% bname).encode("utf-8") + os.urandom(random.randint(512, 2048))
|
||
prefix = sha[:2]
|
||
stored_name = "%s_%s" % (sha, ori)
|
||
d = os.path.join(ATTACH_DIR, prefix)
|
||
os.makedirs(d, exist_ok=True)
|
||
with open(os.path.join(d, stored_name), "wb") as f:
|
||
f.write(content)
|
||
stored_path = os.path.join("attachments", prefix, stored_name)
|
||
cur.execute("INSERT OR IGNORE INTO attachments(sha256, stored_path, original_name, size, uploaded_at)"
|
||
" VALUES(?,?,?,?,?)",
|
||
(sha, stored_path, ori, len(content), time.strftime("%Y-%m-%d %H:%M:%S")))
|
||
cur.execute("UPDATE batches SET x_attach_sha=? WHERE id=?", (sha, bid))
|
||
return sha
|
||
|
||
|
||
def cleanup_old(con, cur):
|
||
"""清掉上一轮生成的模拟批次,保证幂等。"""
|
||
# 2026-10-07:只清价格类模拟(模拟市场价/模拟信息价)——别把项目模拟(模拟项目××)误删
|
||
old = [r[0] for r in cur.execute(
|
||
"SELECT id FROM batches WHERE Name LIKE '模拟市场价%' OR Name LIKE '模拟信息价%'").fetchall()]
|
||
if not old:
|
||
return 0
|
||
ph = ",".join("?" * len(old))
|
||
shas = [r[0] for r in cur.execute(
|
||
"SELECT DISTINCT x_attach_sha FROM batches WHERE id IN (%s)" % ph, old) if r[0]]
|
||
# 仅删库内行;附件物理文件交由 make_attachment 按确定性文件名覆盖,
|
||
# 不在脚本里批量删文件(会触发安全删除护栏)。
|
||
if shas:
|
||
cur.execute("DELETE FROM attachments WHERE sha256 IN (%s)" % ",".join("?" * len(shas)), shas)
|
||
cur.execute("DELETE FROM prices WHERE batch_id IN (%s)" % ph, old)
|
||
cur.execute("DELETE FROM batches WHERE id IN (%s)" % ph, old)
|
||
return len(old)
|
||
|
||
|
||
def main():
|
||
n_batches = int(sys.argv[1]) if len(sys.argv) > 1 else 100
|
||
lo = int(sys.argv[2]) if len(sys.argv) > 2 else 500
|
||
hi = int(sys.argv[3]) if len(sys.argv) > 3 else 900
|
||
|
||
con = sqlite3.connect(DB)
|
||
con.execute("PRAGMA foreign_keys = OFF")
|
||
cur = con.cursor()
|
||
|
||
# 去重工料机池
|
||
cur.execute("SELECT DISTINCT Number, Name, Specification, Unit FROM lmes "
|
||
"WHERE Name IS NOT NULL AND Name <> ''")
|
||
pool = [(r[0], r[1], r[2], r[3]) for r in cur.fetchall()]
|
||
if len(pool) < lo:
|
||
print("工料机池只有 %d 条,不足以支撑每份 %d 条,退出。" % (len(pool), lo))
|
||
return
|
||
print("工料机去重池:%d 条;准备生成 %d 份,每份 %d~%d 条。" % (len(pool), n_batches, lo, hi))
|
||
|
||
removed = cleanup_old(con, cur)
|
||
if removed:
|
||
print("已清理上一轮模拟批次:%d 份。" % removed)
|
||
|
||
random.seed(20261007)
|
||
kinds = []
|
||
for i in range(n_batches):
|
||
kinds.append("market" if i % 2 == 0 else "info")
|
||
random.shuffle(kinds)
|
||
|
||
total_prices = 0
|
||
t0 = time.time()
|
||
for i in range(n_batches):
|
||
kind = kinds[i]
|
||
n = random.randint(lo, hi)
|
||
sample = random.sample(pool, n)
|
||
y = random.choice([2025, 2026])
|
||
mo = random.randint(1, 12)
|
||
m_idx = y * 12 + mo
|
||
prov, city, dist = random.choice(REGIONS)
|
||
pub = random.choice(PUBS) if kind == "info" else ""
|
||
block = random.choice(BLOCKS)
|
||
bname = "模拟%s-%03d" % ("市场价" if kind == "market" else "信息价", i + 1)
|
||
now = time.strftime("%Y-%m-%d %H:%M:%S")
|
||
cur.execute(
|
||
"""INSERT INTO batches(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)
|
||
VALUES(?,?,?,?,?,?,?,?,?,1,?,?,?,?,?,?,?,?,1)""",
|
||
(kind, bname[:200], None, "", prov, city, dist, m_idx, m_idx, None, 0, 0,
|
||
now, "mock://%s/%03d" % (kind, i + 1), "自动模拟生成", pub, PARSER_VER))
|
||
bid = cur.lastrowid
|
||
|
||
rows = []
|
||
for (code, name, spec, unit) in sample:
|
||
nt = guess_price(name, unit)
|
||
rate = random.choice([0.13, 0.09, 0.03, None])
|
||
tp = round(nt * (1 + rate), 2) if rate else None
|
||
cls = random.choice(BLOCK_CLASSES[block])
|
||
h = _md5(name, spec, unit)
|
||
rows.append((bid, code, name, spec, unit, nt, rate, tp, cls,
|
||
"模拟区间价", block, _norm(name), _norm(spec), _norm(unit), h, 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, bid))
|
||
make_attachment(cur, bid, kind, bname)
|
||
total_prices += n
|
||
if (i + 1) % 10 == 0:
|
||
print(" ...已生成 %d/%d 份(累计 %d 条价格)" % (i + 1, n_batches, total_prices))
|
||
|
||
con.commit()
|
||
dt = time.time() - t0
|
||
print("完成:%d 份批次,%d 条价格,%.1fs。" % (n_batches, total_prices, dt))
|
||
# 校验
|
||
cur.execute("SELECT COUNT(*) FROM batches WHERE Name LIKE '模拟%'")
|
||
print("校验 batches(模拟):", cur.fetchone()[0])
|
||
cur.execute("SELECT COUNT(*) FROM prices p JOIN batches b ON b.id=p.batch_id WHERE b.Name LIKE '模拟%'")
|
||
print("校验 prices(模拟):", cur.fetchone()[0])
|
||
cur.execute("SELECT MIN(x_rows_price), MAX(x_rows_price) FROM batches WHERE Name LIKE '模拟%'")
|
||
print("校验 每份条数范围:", cur.fetchone())
|
||
cur.execute("SELECT COUNT(*) FROM attachments a JOIN batches b ON b.x_attach_sha=a.sha256 WHERE b.Name LIKE '模拟%'")
|
||
print("校验 已挂附件的模拟批次:", cur.fetchone()[0])
|
||
con.close()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|