Files
pricing_review/_merge_exp/run_exp.py

155 lines
8.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""合并工料机三场景真机实验(隔离实例,生产库零接触):
S0=基线不合并 / S1=只合子级 / S2=只合一级 / S3=两级都合;各自导出原格式真件。"""
import os, shutil, socket, subprocess, sys, time, json, sqlite3
APP_SRC = r"D:\PricingReview\CostReview\app"
SAMPLE = r"D:\PricingReview\后台需要导入的项目\合并工料机测试(原).cos4"
ROOT = r"D:\PricingReview\_merge_exp\iso"
TWN = [7]
def free_port():
s = socket.socket(); s.bind(("127.0.0.1", 0)); p = s.getsockname()[1]; s.close(); return p
def main():
shutil.rmtree(ROOT, ignore_errors=True)
app_dst = os.path.join(ROOT, "CostReview", "app")
shutil.copytree(APP_SRC, app_dst, ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
src_dir = os.path.join(ROOT, "后台需要导入的项目"); os.makedirs(src_dir)
lic = os.path.join(ROOT, "lic"); os.makedirs(lic)
open(os.path.join(lic, "config.json"), "w", encoding="utf-8").write('{"enforce": false}')
port = free_port()
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=lic)
log = open(os.path.join(ROOT, "server.log"), "wb")
proc = subprocess.Popen([sys.executable, "run_server_headless.py"], cwd=app_dst, env=env,
stdout=log, stderr=subprocess.STDOUT)
import atexit
atexit.register(lambda: (proc.terminate(), log.close()))
import urllib.request
base = "http://127.0.0.1:%d" % port
for _ in range(100):
try:
if urllib.request.urlopen(base + "/api/license/status", timeout=2).status == 200:
break
except Exception:
time.sleep(0.3)
else:
proc.terminate(); raise RuntimeError("服务未就绪")
import httpx
c = httpx.Client(base_url=base, timeout=180)
def post(path, body):
r = c.post(path, json=body); assert r.status_code == 200, (path, r.status_code, r.text[:200])
return r.json()
def getj(path, **params):
r = c.get(path, params=params); assert r.status_code == 200, (path, r.status_code, r.text[:200])
return r.json()
audit_body = {"path": "", "name": "x", "period_from": 24319, "period_to": 24319,
"province": "广东省", "city": "珠海市", "district": "香洲区",
"bulid_unit": "实验建设单位", "file_kind": 1}
def fresh_session(name):
# 每会话双胞胎件:zip 时间戳平移 → sha 不同(242 同文件禁令放行)
import hashlib, zipfile, io as _io
TWN[0] += 2 # zip DOS 时间的秒按 2 整除:步长必须 ≥2 才真的变哈希
zi_ = zipfile.ZipFile(SAMPLE)
buf = _io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
for nm in zi_.namelist():
info = zipfile.ZipInfo(nm, date_time=(2026, 1, 1, 0, 0, TWN[0]))
info.compress_type = zipfile.ZIP_DEFLATED
zo.writestr(info, zi_.read(nm))
raw = buf.getvalue()
sample_dst = os.path.join(src_dir, "exp_t%d.cos4" % TWN[0])
open(sample_dst, "wb").write(raw)
sha_name = hashlib.sha256(raw).hexdigest() + "_exp_t%d.cos4" % TWN[0]
b = dict(audit_body); b["name"] = name; b["path"] = sample_dst
j = post("/api/audit", b); assert j.get("ok"), j
sid = j["session_id"]
# 补源件落位(生产同构:source_files/<sha>_<名>,会话 src_name 指它)——审计入口不搬文件
sf = os.path.join(ROOT, "CostReview", "data", "source_files"); os.makedirs(sf, exist_ok=True)
if not os.path.exists(os.path.join(sf, sha_name)):
open(os.path.join(sf, sha_name), "wb").write(raw)
scf = sqlite3.connect(os.path.join(ROOT, "CostReview", "data", "session.db"))
scf.execute("UPDATE sessions SET src_name=? WHERE id=?", (sha_name, sid)); scf.commit(); scf.close()
return sid
def merge_all(sid, sub):
g = getj("/api/session/lme/merge/groups", session_id=sid, **({"view": "sub"} if sub else {}))
for grp in g.get("groups", []):
members = ["%s@%s(量%s%s)" % (r["code"], r["ntp"], round(r["qty"] or 0, 3), "*默认" if r.get("def") else "") for r in grp["rows"]]
print(" 组[%s|%s] %d成员: %s" % (grp["name"], grp["unit"], len(grp["rows"]), " ".join(members)))
groups = []
for grp in g.get("groups", []):
sel = next(r for r in grp["rows"] if r.get("def"))
hide = [r for r in grp["rows"] if r is not sel]
for d in [sel] + hide:
if d.get("lvl") == "uw":
d["uw"] = 1
groups.append({"sel": sel, "hide": hide})
if groups:
j = post("/api/session/lme/merge", {"session_id": sid, "groups": groups})
assert j.get("ok"), j
return len(groups)
def snapshot(sid, tag):
proj = getj("/api/session/raw/proj", session_id=sid, tab="lme")
g1 = getj("/api/session/lme/merge/groups", session_id=sid)
gs = getj("/api/session/lme/merge/groups", session_id=sid, view="sub")
sc = sqlite3.connect(os.path.join(ROOT, "CostReview", "data", "session.db"))
sc.row_factory = sqlite3.Row
nres = dict(sc.execute(
"SELECT nr.res_code, COUNT(*) FROM s_norm_res nr JOIN s_norms n ON n.id=nr.norm_id "
"JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=? GROUP BY nr.res_code", (sid,)).fetchall())
lres = sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=?", (sid,)).fetchone()[0]
n990 = sc.execute("SELECT COUNT(*) FROM s_lme_res WHERE session_id=? AND p_code='990401025'", (sid,)).fetchone()[0]
nres_h = sc.execute("SELECT COUNT(*) FROM s_norm_res nr JOIN s_norms n ON n.id=nr.norm_id "
"JOIN s_bills b ON b.id=n.bill_id WHERE b.session_id=? AND nr.res_code LIKE '%-0%'", (sid,)).fetchone()[0]
sc.close()
hits = {r[1]: r[5] for r in proj["rows"] if r[1] in ("990401025", "99450630", "99450700", "00010010", "05030060", "34110010")}
print("[%s] 项目级行=%d 折旧费=%s 载货汽车=%s 电=%s 人工费=%s 板枋材=%s 水=%s" %
(tag, len(proj["rows"]), hits.get("99450630"), hits.get("990401025"), hits.get("99450700"),
hits.get("00010010"), hits.get("05030060"), hits.get("34110010")))
print("[%s] 弹框一级组=%d 子级组=%d | s_lme_res=%d(990401025子级%d) 变体码定额引用=%d" %
(tag, len(g1["groups"]), len(gs["groups"]), lres, n990, nres_h))
return {"proj_rows": len(proj["rows"]), "g1": len(g1["groups"]), "gs": len(gs["groups"]),
"lres": lres, "n990": n990, "nres_variants": nres_h, "hits": {k: hits.get(k) for k in ("990401025","99450630","99450700","00010010")}}
def export(sid, tag):
r = c.get("/api/session/export", params={"session_id": sid})
assert r.status_code == 200, (r.status_code, r.text[:200])
fn = r.headers.get("content-disposition", "")
out = os.path.join(ROOT, "export_%s%s" % (tag, ".xml" if r.content[:5] == b"<?xml" or r.content[:1] == b"<" else ".zip"))
open(out, "wb").write(r.content)
print("[导出 %s] %d 字节 -> %s | disposition=%s" % (tag, len(r.content), os.path.basename(out), fn[:80]))
return out
TWN[0] = 7
print("=== 导入 4 个新会话 ===")
sids = {}
for tag, name in (("S0", "实验S0基线不合并"), ("S1", "实验S1只合子级"), ("S2", "实验S2只合一级"), ("S3", "实验S3两级都合")):
sids[tag] = fresh_session(name)
print(" %s = 会话 %d" % (tag, sids[tag]))
snapshot(sids["S0"], "S0基线")
print("=== S1 只合子级 ===")
n = merge_all(sids["S1"], sub=True); print(" 子级合并组数:", n)
snapshot(sids["S1"], "S1只合子级")
print("=== S2 只合一级 ===")
n = merge_all(sids["S2"], sub=False); print(" 一级合并组数:", n)
snapshot(sids["S2"], "S2只合一级")
print("=== S3 两级都合 ===")
n1 = merge_all(sids["S3"], sub=False); n2 = merge_all(sids["S3"], sub=True)
print(" 一级组数:", n1, "子级组数:", n2)
snapshot(sids["S3"], "S3都合")
print("=== 导出 ===")
for tag in ("S0", "S1", "S2", "S3"):
export(sids[tag], tag)
json.dump({k: v for k, v in sids.items()}, open(os.path.join(ROOT, "sids.json"), "w"))
print("DONE")
if __name__ == "__main__":
main()