Merge commit 'd880392e5feebe49e0b89541008959852a64d972' into main_laptop_1

This commit is contained in:
2026-11-18 07:07:27 +09:00
18 changed files with 703 additions and 271 deletions
+109 -4
View File
@@ -22,7 +22,9 @@ from __future__ import annotations
import copy as cp
import hashlib
import json
import re
import sys
from decimal import Decimal
from pathlib import Path
from typing import Any
@@ -33,7 +35,6 @@ _SCRIPTS = str(Path(__file__).resolve().parents[1] / "resources/master_data/scri
if _SCRIPTS not in sys.path:
sys.path.insert(0, _SCRIPTS)
import master_auto as mau # noqa: E402
import master_doc as md # noqa: E402
import master_doc_calc as mc # noqa: E402
import master_doc_convert as cv # noqa: E402
@@ -262,17 +263,121 @@ def _apart(doc: dict, lines: list[dict], n: int) -> None:
later[slot] = md.text_of(_plus(node, cost, sym))
def given_of(whole: Any, code: str, given: Any) -> dict:
"""옛 `run_line` 과 같은 입력 — 빈 입력 = 자동값(M01 줄) › 받은 값."""
def given_of(whole: Any, code: str, given: Any, docs: dict | None = None) -> dict:
"""옛 `run_line` 과 같은 입력 — 빈 입력 = 자동값(`auto_of` · 문서 = `docs` › 값 사본 줄 문서) ›
받은 값."""
from M01_MasterData import M01_MasterData_Store as m01
try:
auto = {k: v for k, v in mau.values(whole, whole.logic(code)).items() if v is not None}
doc = (docs or {}).get(code) or doc_of(whole, code)
auto = {k: v for k, v in auto_of(doc, whole).items() if v is not None} if doc else {}
except _ERR:
auto = {}
return {**auto, **m01._dec(given or {})}
# ── 자동값(옛 `master_auto.values` 같은 규칙 · 문서에서 · 855-F B9-6) ──────────
_GUARD = re.compile(r"만약\(\s*(\w+)\s*>\s*0\s*,\s*\1\s*,")
_INPUTS = ("입력", "선택")
def _num(v: Any) -> Any:
try:
return Decimal(str(v)) if not isinstance(v, Decimal) else v
except ArithmeticError:
return v
def _fits(whole: Any, ref: str, cond: str) -> list:
"""표 `ref` 조건 칸 `cond` 에 드는 수 — 낮은 차례 · 범위 칸 = 줄마다 그 줄에 드는 끝."""
try:
table = whole.get(ref)
except _ERR:
return []
ranged = (table.get("조건") or {}).get(cond) == "범위"
out = set()
for r in table.get("줄") or []:
if r.get(cond) is None:
continue
low, high = r[cond] if ranged else (r[cond], None)
ends = [Decimal(0) if low is None else low, high]
out |= {v for v in ends if isinstance(v, Decimal) and ml._match(table, r, cond, v)}
return sorted(out)
def _lowest(whole: Any, uses: list) -> Any:
"""같은 입력을 여러 표가 쓰면 모두에 드는 가장 낮은 수 · 없으면 첫 표의 가장 낮은 수."""
sets = [_fits(whole, ref, cond) for ref, cond in uses]
both = sorted(set.intersection(*map(set, sets))) if sets else []
return (both or next((s for s in sets if s), [None]))[0]
def _divisors(doc: dict, ids: dict) -> set[str]:
"""나누는 자리에 든 이름 — 그 이름이 쓰는 이름(식 · 표 조건 · 단가산출 넘긴 입력)까지 ·
「만약(X > 0, X, 기본)」 의 X 는 안 퍼뜨림."""
texts = [x.get("식") for x in doc.get("식") or []]
texts += [(doc.get("결과") or {}).get("식") if isinstance(doc.get("결과"), dict) else None]
texts += [x.get(k) for x in doc.get("금액") or [] for k in ("수량", "단가")]
divs, guard = set(), set()
for text in (x for x in texts if x not in (None, "")):
guard |= set(_GUARD.findall(str(text)))
try:
divs |= {
n for p in md.walk(md.parse(text)) if p[:2] == ("bin", "/") for n in md.names(p[3])
}
except md.DocError:
continue
feeds: dict[str, list] = {}
for x in doc.get("식") or []:
feeds.setdefault(md.var_id(x), []).append(x.get("식"))
for vid, v in ids.items():
link = v.get("연결") or {}
part = {"표": "조건", "단가산출": "입력"}.get(str(link.get("갈래")))
if part:
feeds.setdefault(vid, []).extend((link.get(part) or {}).values())
todo = list(divs)
while todo:
for text in feeds.get(todo.pop(), []):
try:
more = set(md.names(md.parse(text))) - guard - divs
except md.DocError:
continue
divs |= more
todo += list(more)
return divs
def auto_of(doc: dict, whole: Any) -> dict:
"""문서 입력마다 자동값 — 고르기 = 목록 첫째 · 범위 = 아래 끝 · 표 조건 값 = 그 표 가장 낮은
수 · 나누는 자리 = 1 · 그 밖 0 · 가격(원) 입력 = None(1,521 문서 옛 `master_auto` 와 같음)."""
ids = {md.var_id(v): v for v in doc.get("변수") or []}
finds: dict[str, list] = {}
for v in ids.values():
link = v.get("연결") or {}
if link.get("갈래") == "표":
for col, arg in (link.get("조건") or {}).items():
if isinstance(arg, str) and arg in ids:
finds.setdefault(arg, []).append((link.get("표"), col))
divs = _divisors(doc, ids)
out: dict[str, Any] = {}
for vid, v in ids.items():
link = v.get("연결") or {}
if link.get("갈래") not in _INPUTS or not v.get("열쇠"):
continue
name = str(v["열쇠"])
if link.get("목록"):
out[name] = link["목록"][0]
elif link.get("범위"):
out[name] = _num(link["범위"][0])
else:
got = _lowest(whole, finds.get(vid, []))
if got is None and "원" in str(v.get("단위") or ""):
out[name] = None
else:
out[name] = got if got is not None else Decimal(1 if vid in divs else 0)
return out
def apart_of(marks: Any, mats: Any) -> list[int]:
"""별도계상 금액 줄 차례 — 옛 `drop_apart` 와 같은 판정(엔진 답 `재료` 의 차례 · 자재표시)."""
from M02_MasterTemplete import M02_Labor_Doc as labor
+11 -17
View File
@@ -22,6 +22,7 @@ from common_util.common_util_summary_item import GROUP_JOIN
from M02_MasterTemplete import M02_Item_Personal as personal
from M02_MasterTemplete import M02_Item_Prices as prices
from M02_MasterTemplete import M02_Template_Layers as layers
from M02_MasterTemplete.M02_Doc_B09 import FILE as FORMULA_FILE
from M02_MasterTemplete.M02_Item_Snapshot import (
FOLDER_PATTERN,
LOCAL_FILES,
@@ -191,12 +192,9 @@ def write_file(
# ── 새로 가져오기 · 미리 가져오기 ─────────────────────────────────────
def _kept_values(values: Any, labor: dict[str, Any]) -> dict[str, Any]:
"""같은 로직 · 같은 입력 이름만 살림."""
names = {
str(row.get("키")): {spec["이름"] for spec in row.get("입력", [])}
for row in labor.get("로직", [])
}
def _kept_values(values: Any, docs: dict[str, dict]) -> dict[str, Any]:
"""같은 로직 · 같은 입력 이름만 살림(입력 = 새 사본 수식 문서 · 855-F B9-6)."""
names = {key: set(prices.doc_inputs(doc)) for key, doc in docs.items()}
out: dict[str, Any] = {}
for logic, inputs in (values or {}).items():
kept = {k: v for k, v in (inputs or {}).items() if k in names.get(logic, set())}
@@ -205,14 +203,10 @@ def _kept_values(values: Any, labor: dict[str, Any]) -> dict[str, Any]:
return out
def _kept_picks(picks: Any, labor: dict[str, Any]) -> dict[str, Any]:
"""같은 로직 · 있는 호표 차례만 살림."""
lines = {str(row.get("키")): len(row.get("호표", [])) for row in labor.get("로직", [])}
slots = { # 흐름 로직 — 고른 자재는 재료 자리 이름(= 입력 이름)
str(row.get("키")): {s["이름"] for s in row.get("입력", [])}
for row in labor.get("로직", [])
if isinstance(row.get("흐름"), dict)
}
def _kept_picks(picks: Any, docs: dict[str, dict]) -> dict[str, Any]:
"""같은 로직 · 있는 줄 차례(문서 금액 줄) · 흐름 로직 재료 자리 이름(= 입력 이름)만 살림."""
lines = {key: len(doc.get("금액") or []) for key, doc in docs.items()}
slots = {key: set(prices.doc_inputs(doc)) for key, doc in docs.items()}
out: dict[str, Any] = {}
for logic, chosen in (picks or {}).items():
kept = {
@@ -238,12 +232,12 @@ def reapply(
picks = read_json(target / PICKS_FILE)
before = {name: read_json(target / file) for name, file in KINDS.items()}
files = build_snapshot(manifest["원본"])
labor = files.get(LABOR_FILE) or {}
docs = (files.get(FORMULA_FILE) or {}).get("문서") or {} # 새 사본 수식 문서
seeded = files[VALUES_FILE] # 새 원본의 첫 값 — 프로젝트에서 넣은 값이 같은 키면 이김
kept_values = _kept_values(values, labor)
kept_values = _kept_values(values, docs)
for logic, inputs in kept_values.items():
seeded[logic] = {**seeded.get(logic, {}), **inputs}
files[PICKS_FILE] = _kept_picks(picks, labor)
files[PICKS_FILE] = _kept_picks(picks, docs)
for old in target.glob("*.json"): # 원본에서 빠진 파일(도면 없앰 등)은 지움
if old.name != MANIFEST_NAME and old.name not in files:
old.unlink()
+33 -12
View File
@@ -303,22 +303,43 @@ def load_prices(prices: dict[str, Any]) -> Any:
def _logic_keys(labor: dict[str, Any]) -> list[str]:
"""담은 로직 키 — 참조 줄(로직 없음 · 50-3)은 뺌."""
return [key for key in mcb.logic_keys(labor.get("줄") or {}) if key]
lines = (labor.get("줄") or {}).get("담은로직") or []
return [str(one["로직"]) for one in lines if isinstance(one, dict) and one.get("로직")]
def missing_inputs(snapshot: Any, labor: dict[str, Any], values: dict[str, Any]) -> list[dict]:
"""담은 로직마다 값이 없는(null · 안 적음) 입력 — `{로직, 입력}`."""
def doc_inputs(doc: Any) -> list[str]:
"""수식 문서 입력 이름(입력 · 선택 변수 열쇠 · 옛 로직 줄 `입력` 이름 · 차례와 같음)."""
return [
str(v["열쇠"])
for v in (doc or {}).get("변수") or []
if (v.get("연결") or {}).get("갈래") in ("입력", "선택") and v.get("열쇠")
]
def doc_specs(doc: Any) -> list[dict[str, Any]]:
"""수식 문서 입력 꼴(옛 로직 줄 `입력` 자리) — {이름(열쇠), 단위, 설명, 출처, 고르기, 범위}."""
out = []
for v in (doc or {}).get("변수") or []:
link = v.get("연결") or {}
if link.get("갈래") not in ("입력", "선택") or not v.get("열쇠"):
continue
spec = {"이름": str(v["열쇠"]), **{k: v[k] for k in ("단위", "설명", "출처") if v.get(k)}}
spec |= {"고르기": list(link["목록"])} if link.get("목록") else {}
out.append(spec | ({"범위": list(link["범위"])} if link.get("범위") else {}))
return out
def missing_inputs(
docs: dict[str, dict], labor: dict[str, Any], values: dict[str, Any]
) -> list[dict]:
"""담은 로직마다 값이 없는(null · 안 적음) 입력 — `{로직, 입력}` · 입력 = 사본 수식 문서."""
out = []
for key in _logic_keys(labor):
try:
row = snapshot.logic(key)
except mf.FormulaError:
continue
mine = values.get(key) or {}
for spec in row.get("입력", []):
got = mine.get(spec["이름"])
for name in doc_inputs(docs.get(key)):
got = mine.get(name)
if not isinstance(got, dict) or got.get("값") in (None, ""):
out.append({"로직": key, "입력": spec["이름"]})
out.append({"로직": key, "입력": name})
return out
@@ -401,7 +422,7 @@ def line(whole: Any, docs: dict[str, dict] | None, one: dict[str, Any]) -> dict[
return {"기준": None, "줄": [], "재료": [], "까닭": f"수식 문서 없음 「{code}」"}
apart = dc.apart_of(one.get("자재표시"), [{"차례": n} for n, _, _ in _mat_lines(base)])
doc = dc.line_doc(base, one.get("켜쌓기율"), one.get("고름"), apart)
given = dc.given_of(whole, code, one.get("입력값"))
given = dc.given_of(whole, code, one.get("입력값"), docs)
copy = {"부름": docs}
try:
ans = mt.calc(doc, mt.Trace(whole, docs), given, dc.cover_of(copy, doc))
@@ -450,5 +471,5 @@ def calc(
return {
**got,
"알약": saved if isinstance(saved, list) else labor_doc.pills(doc),
"빠진입력": missing_inputs(snapshot, labor, values or {}),
"빠진입력": missing_inputs(docs, labor, values or {}),
}