Files
Aislo/B09_Estimation/B09_Estimation_Sangeun_Text.py
T
eomsangdonandClaude Opus 5.5 efc881ad12 refactor(855-F B9-4): B09 산출근거 글이 옛 엔진 · master_text 대신 풀이 블록 + 문서 셈 답으로
- Sangeun_Text 새 render · foot — 풀이 블록 줄 값(B09 수량 · 단가 · 금액) + 문서 셈 답(입력 · 공식 · 표 값 · 단위) · 수 꼴 · 단위 · 금액 줄 꼴 = master_doc_text(화면 줄 쌓기 산출근거 규칙)
- Sangeun _env · _captured · _Prices · price_of 지움 · Solver._text = render 한 번(못 지으면 빈 글 · 값 그대로)
- Sangeun_Sum 옛 shown · _cut · places · sums · scope · extra · totals 지움(doc_* 만)
- helper_855_engine 옛 대조 기준 _old_env · _old_captured(test_855_trace)
- test_155_5 · test_157_1 · test_155_b09_sources — 엑셀 꼴 글자 대신 새 규칙 결과(글 금액 = 블록 · 계 · Q 공식 줄 · 값 넣은 수량 식 · ÷ 배 · 원)
- 골든 855_b09 글 5 갈래 다시 뜸(전 → 후 견본 tmp 표) · 값 10 갈래 같음 · 옛 글이 블록 값과 어긋나던 자리(옛 키 단가 0) 바로잡힘
- B09 옛 엔진 부름 37 → 0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 02:53:03 +09:00

293 lines
13 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.
"""B09 산근 한 블록 → 산출근거 글 줄들(PLAN 155-5 · 855-F B9-4) — 서버 단독(③ · 순수 함수 · 셈 안 함).
재료 = 산근 풀이 블록 줄(`B09_Estimation_Sangeun.Solver` · B09 수량 · 단가 · 금액) + 그 로직 문서 셈 답
(`B09_Estimation_Doc_Run.Answer` · 입력 · 중간 값 · 단위) — 옛 엔진 · `master_text` 안 부름.
수 꼴 · 단위 · 금액 줄 꼴 = 화면 줄 쌓기 산출근거 규칙(`master_doc_text` · 짝 `A00_Common/line_stack_out.ts`):
머리 = 「이름 / 단위」 · 「출처 적용」 · 입력 「이름 : 설명 = 값 단위」(기계 · 직종 번호 = 「이름 규격」 157-3) ·
공식 줄 「이름 = 이름식 = 값식 = 값 단위」(식 변수 · 같은 꼴은 한 번) · 표 · 하위 결과 값 「이름 = 값 단위」
줄 = 「이름 : 단가 원/단위 × 수량 단위[ ÷ 배][ × 율 %] = 금액 원」(B09 단가 · 1 단위 수량 = 문서 수량 ÷ 배 × 율) ·
중기 = 노무비 · 재료비 · 경비 세 줄 · 하위 산근 = 「산근 n호표 단가 × 수량」 ·
% 덧줄 = 「이름 (노무비의 %) : 밑수 × n % = 금액 원」 · 못 셈 = 「이름 : — 까닭」
끝 = 「계 : 노무비 + 재료비 + 경비 = 합」(블록 합 · B09 끝수).
화면만인 것(옮기지 않음) = 식 조판 · 표 조건 글 · 만약 갈래 글 · 하위 결과 펼침 · 쌓기 묶음.
"""
from __future__ import annotations
import importlib
from decimal import Decimal
from typing import Any
from M02_MasterTemplete import M02_Labor_Inputs as labor_inputs
md = importlib.import_module("master_doc")
mdt = importlib.import_module("master_doc_text")
ml = importlib.import_module("master_doc_link")
PART_NAME = {"labor": "노무비", "material": "재료비", "expense": "경비"}
PARTS = tuple(PART_NAME)
NO_PRICE = "단가 없음"
GAP = "—"
INPUTS = ("입력", "선택")
VALUES = ("표", "단가산출", "숫자") # 값만 줄(표 찾기 · 하위 결과 · 손 수)
PACK = 4 # 값만 줄 = 넷까지 한 줄(화면 공식 묶음)
def _dec(v: Any) -> Decimal | None:
return mdt._dec(v)
def _won(v: Any) -> str:
return GAP if v is None else f"{v:,.0f}"
def _word(whole: Any, name: str, value: Any) -> str:
"""값 글 — 수 = 화면 수 꼴 · 기계 · 직종 원문번호 = 「이름 규격」(157-3 · 85-1 도우미)."""
if isinstance(value, str):
return labor_inputs._labels(whole, {"이름": name, "고르기": [value]}).get(value, value)
return mdt.eq_text(value) if _dec(value) is not None else str(value)
# ── 머리(입력 · 공식) ────────────────────────────────────────────────
def _bare(node: tuple) -> tuple:
"""표시 자리 감싸개(`반올림(식, n)` · B09 작업량 Q) — 식 글은 속 식으로."""
if node and node[0] == "call" and node[1] in ("반올림", "올림", "버림") and len(node[2]) == 2:
return node[2][0]
return node
def _swap(node: Any, put) -> Any:
"""식 나무의 기호 바꿈 — `put(이름)` 이 None 이면 그대로."""
if not isinstance(node, tuple):
return node
if node[0] == "var":
got = put(node[1])
return node if got is None else got
if node[0] == "call":
return ("call", node[1], [_swap(x, put) for x in node[2]])
return tuple(_swap(x, put) for x in node)
def _label(i: str, var: dict) -> str:
"""기호 화면 이름 — 원래 이름(열쇠) · 지은 기호(열쇠 = 기호 · 표 칸)면 변수 이름(「표 이름.칸」)."""
key = str(var.get("열쇠") or "")
return key if key and key != i else str(var.get("이름") or i)
class _Head:
def __init__(self, whole: Any, answer: Any) -> None:
self.whole, self.answer = whole, answer
self.doc, self.values = answer.doc, answer.ans.get("값") or {}
self.vars = {md.var_id(v): v for v in self.doc.get("변수") or []}
self.names = {i: _label(i, v) for i, v in self.vars.items()}
def unit(self, i: str) -> str:
return mdt.unit_text((self.vars.get(i) or {}).get("단위"))
def value(self, i: str) -> str:
v = self.values.get(i)
if v is None:
return "값 없음"
if isinstance(v, dict):
return " · ".join(f"{c} {mdt.eq_text(v.get(c))}" for c in mdt.COSTS)
return " ".join(x for x in (_word(self.whole, self.names.get(i, i), v), self.unit(i)) if x)
def formula(self, i: str, text: str) -> str:
"""「이름 = 이름식 = 값식 = 값 단위」 — 같은 글이 이어지면 한 번만."""
node = _decide(mdt.node_of(text), self.answer) # 만약 = 걸린 갈래
parts = [self.names.get(i, i)]
if node is not None:
node = _bare(node)
named = md.text_of(
_swap(node, lambda n: ("var", self.names[n]) if n in self.names else None)
)
valued = md.text_of(_swap(node, self._num))
parts += [named, valued]
v = self.values.get(i)
bare = mdt.eq_text(v) if _dec(v) is not None else f"'{v}'" if isinstance(v, str) else None
out = [parts[0]]
for p in parts[1:]: # 같은 글 · 값 그대로인 식 = 한 번만(화면 공식 줄)
if p and p != out[-1] and p != bare:
out.append(p)
out.append(self.value(i))
return " = ".join(out)
def _num(self, name: str):
v = self.values.get(name)
d = _dec(v)
return ("var", mdt.eq_text(d)) if d is not None else None
def lines(self, times: Decimal) -> list[str]:
doc = self.doc
out = [f"{doc.get('이름') or doc.get('키')} / {mdt.unit_text(_per_unit(doc, times))}"]
if doc.get("출처"):
out.append(f"{doc['출처']} 적용")
steps = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []}
pack: list[str] = []
def flush() -> None:
if pack:
out.append(" · ".join(pack))
pack.clear()
for i, v in self.vars.items():
kind = (v.get("연결") or {}).get("갈래")
if kind in INPUTS and self.values.get(i) is not None:
about = f"{v['설명']} = " if v.get("설명") else ""
flush()
out.append(f"{v.get('열쇠') or self.names[i]} : {about}{self.value(i)}")
elif kind == "식" and i in steps:
flush()
out.append(self.formula(i, steps[i]))
elif kind in VALUES and _dec(self.values.get(i)) is not None:
pack.append(f"{self.names[i]} = {self.value(i)}")
if len(pack) >= PACK:
flush()
flush()
return out
def _per_unit(doc: dict, times: Decimal) -> str:
"""결과단위 1 단위 이름(「원/10㎡」 = ㎡ · 배 1 = 그대로 「원/1기」 = 1기)."""
unit = str(doc.get("결과단위") or "").removeprefix("원/")
return unit.removeprefix(mdt.eq_text(times)) if times != 1 else unit
# ── 금액 줄 ───────────────────────────────────────────────────────────
class _Docs:
"""`master_doc_text.money_units` 의 하위 문서 읽기 — 사본 문서 묶음에서."""
def __init__(self, docs: dict) -> None:
self.docs = docs
def doc(self, key: str) -> dict | None:
return self.docs.get(key)
def _units(answer: Any, n: int) -> dict:
doc = answer.doc
line = (doc.get("금액") or [])[n]
sym = mdt.price_sym(line)
var = answer.vars.get(sym) if sym else None
link = (var or {}).get("연결") or {}
sub = (answer.docs or {}).get(str(link.get("키"))) if link.get("갈래") == "단가산출" else None
qty = mdt.node_of(line.get("수량"))
return mdt.money_units(line, mdt.node_of(line.get("단가")), qty, var, sub)
def _qty(answer: Any, n: int, units: dict, times: Decimal, rate: Decimal | None) -> str:
"""수량 글 — 값 넣은 수량 식(화면 금액 줄 「× (수량 식) 단위」 · 식이면 괄호) 단위[ ÷ 배][ × 율 %]."""
raw = (answer.ans.get("줄") or [{}] * (n + 1))[n].get("수량")
node = _decide(mdt.node_of(((answer.doc.get("금액") or [])[n]).get("수량")), answer)
values = answer.ans.get("값") or {}
shown = mdt.eq_text(raw)
if node is not None and not mdt.is_atom(node):
put = lambda s: ("var", mdt.eq_text(values[s])) if _dec(values.get(s)) is not None else None # noqa: E731
shown = f"({md.text_of(_swap(_bare(node), put))})"
text = mdt._u(shown, units["qty"])
if times != 1:
text += f" ÷ {mdt.eq_text(times)}"
if rate is not None:
text += f" × {mdt.eq_text(rate * 100)} %"
return text
def _decide(node: Any, answer: Any) -> Any:
"""만약 = 걸린 갈래만(화면 `decide` · 조건 = 셈 답 값 · `master_doc_text._Look`)."""
if node is None:
return None
look = getattr(answer, "_look", None)
if look is None:
look = answer._look = mdt._Look(answer.doc, answer.ans, ml.Links(answer.whole, answer.docs))
def walk(n: Any) -> Any:
if not isinstance(n, tuple):
return n
if (pick := look.taken(n)) and n[0] == "call":
return walk(n[2][pick])
if n[0] == "call":
return ("call", n[1], [walk(x) for x in n[2]])
return tuple(walk(x) for x in n)
return walk(node)
def _price(v: Any, unit: str) -> str:
return NO_PRICE if v is None else mdt._u(mdt.eq_text(v), unit)
def _amount(v: Any) -> str:
return GAP if v is None else f"{mdt.one(v)} {mdt.AMOUNT_UNIT}"
def _line_texts(
ln: dict, answer: Any, n: int, times: Decimal, rate: Decimal | None, no_of
) -> list[str]:
name, kind = ln.get("name") or "", ln.get("kind")
if kind == "blank":
return [f"{name} : {GAP} {ln.get('why') or '못 셈'}"]
units = _units(answer, n)
qty = _qty(answer, n, units, times, rate)
price = ln.get("price") or {}
if kind == "machine" and ln.get("why"): # 기계 시간당 없음 = 한 줄(풀이 줄 글 수와 같게)
return [f"{name} : {NO_PRICE} × {qty} = {GAP}"]
if kind == "machine":
return [
f"{name} {PART_NAME[p]} : {_price(price.get(p), units['price'])} × {qty} = "
f"{_amount(ln.get(p))}"
for p in PARTS
]
if kind == "sangeun":
no = no_of((ln.get("ref") or {}).get("key"))
unit = None if any(price.get(p) is None for p in PARTS) else sum(price[p] for p in PARTS)
money = None if unit is None else sum(ln.get(p) or 0 for p in PARTS)
head = f"산근 {no}호표 " if no else ""
return [f"{name} : {head}{_price(unit, units['price'])} × {qty} = {_amount(money)}"]
part = next(iter(price), None) or next((p for p in PARTS if ln.get(p)), "material")
shown = ln.get(part)
label = f"{name}({ln['spec']})" if kind == "material" and ln.get("spec") else name
return [f"{label} : {_price(price.get(part), units['price'])} × {qty} = {_amount(shown)}"]
def _extra_text(ln: dict) -> str:
"""% 덧줄 · 고정 덧줄 — 밑수 × 율 % · 값 하나."""
spec = f" ({ln.get('spec')})" if ln.get("unit") == "%" and ln.get("spec") else ""
head = f"{ln['name']}{spec} : "
part = next(iter(ln.get("price") or {}), None)
if part is None or ln.get(part) is None:
return f"{head}{GAP} {ln.get('why') or '밑수 빈칸'}"
value, money = ln["price"][part], ln[part]
if ln.get("unit") == "%" and ln.get("qty"):
base = Decimal(str(value)) * 100 / Decimal(str(ln["qty"]))
return f"{head}{mdt.eq_text(base)} × {mdt.eq_text(ln['qty'])} % = {_amount(money)}"
return f"{head}{mdt.eq_text(value)} = {_amount(money)}"
def render(
whole: Any,
answer: Any,
lines: list[dict],
*,
times: Any = 1,
rate: Any = None,
no_of=lambda _key: None,
) -> tuple[list[str], list[list[str]]]:
"""산근 한 블록 → (머리 줄들, 블록 줄마다 글 줄들 · 중기 = 셋) — `answer` = 그 로직 문서 셈 답
(켜쌓기율 없이 · 결과단위 몫) · `lines` = 풀이 블록 줄(관급 0 원 앞) · times = 결과단위 배 ·
rate = 켜쌓기율 % · `no_of(산근 키)` = 하위 산근 호표 번호."""
times = Decimal(str(times or 1))
scale = Decimal(str(rate)) / 100 if rate not in (None, 100) else None
head = _Head(whole, answer).lines(times)
heads = len([x for x in lines if x.get("kind") != "extra"])
texts = [
_line_texts(ln, answer, n, times, scale, no_of) if n < heads else [_extra_text(ln)]
for n, ln in enumerate(lines)
]
return head, texts
def foot(sums: dict) -> str:
"""계 줄 — 블록 비목 합(B09 끝수 · 관급 0 원 뒤)."""
parts = " + ".join(f"{PART_NAME[p]} {_won(sums.get(p))}" for p in PARTS)
return f"계 : {parts} = {_won(sums.get('sum'))}"