Merge remote-tracking branch 'origin/dev' into sub_laptop_3

This commit is contained in:
2026-11-17 18:01:35 +09:00
79 changed files with 4981 additions and 748 deletions
@@ -5,6 +5,7 @@
- 셈 = `scripts/master_doc_calc.py` ↔ `common_util/common_util_formula_doc_calc.ts`(짝)
- 풀이 · 글 · 검사 = `scripts/master_doc.py` ↔ `common_util/common_util_formula_doc.ts`(짝)
- 표 찾기 · M01 연결 풀이 = `scripts/master_doc_link.py` ↔ `common_util/common_util_formula_doc_table.ts`(표 찾기 짝)
- 셈 기록(줄마다 부른 자원 · 하위 문서 · 고른 품목 · 서버 단독) = `scripts/master_doc_trace.py`(B08 · B09 가 답을 갈라 합산)
- 옛 로직 변환 = `scripts/master_doc_convert.py` · 빌더 `scripts/build_수식문서_802_2.py`(`--check`)
- 거울 · 꼴 시험 = `resources/tester/test_802_1_formula_doc.py` · 변환 대조 = `test_802_2_convert.py`
@@ -81,6 +81,23 @@ def new_answer(links, doc: dict, given: dict | None = None):
return {"결과": got["결과"]} if doc.get("결과") else {k: got.get(k) for k in KEYS}
def cases_of(whole, row: dict) -> list[tuple]:
"""(옵션 글, 옛 엔진 입력, 새 문서에 넘길 바뀐 입력) — 기본 + 고르기 입력의 다른 갈래 하나씩."""
base = meq.given_of(whole, row)
cases = [("", base, None)]
for spec in row.get("입력") or []:
for opt in spec.get("고르기") or []:
if str(opt) != str(base.get(spec["이름"])):
one = {spec["이름"]: opt}
cases.append((f"{spec['이름']}={opt}", {**base, **one}, one))
return cases
def agree(old, new) -> bool:
"""대조 같음 — 같은 값 · 둘 다 못 셈."""
return old == new or (isinstance(old, str) and isinstance(new, str))
def _text(v) -> str:
if isinstance(v, str):
return v
@@ -137,17 +154,11 @@ def build(log=print) -> dict:
links = ml.Links(whole, docs)
runs, both_out = [], 0
for _, row in items:
key, base = str(row["키"]), meq.given_of(whole, row)
cases = [("", base, None)] # (옵션 글, 옛 엔진 입력, 새 문서에 넘길 바뀐 입력)
for spec in row.get("입력") or []:
for opt in spec.get("고르기") or []:
if str(opt) != str(base.get(spec["이름"])):
one = {spec["이름"]: opt}
cases.append((f"{spec['이름']}={opt}", {**base, **one}, one))
for label, given, changed in cases:
key = str(row["키"])
for label, given, changed in cases_of(whole, row):
old = old_answer(whole, row, given)
new = new_answer(links, docs[key], changed)
same = old == new or (isinstance(old, str) and isinstance(new, str))
same = agree(old, new)
both_out += isinstance(old, str) and isinstance(new, str)
runs.append(
{
@@ -275,6 +275,8 @@ class _Run:
for k in ("칸", "단위"):
if link.get(k):
payload[k] = link[k]
if hasattr(self.links, "at"): # 855-F 셈 기록(`master_doc_trace`) — 기록 안 켬 = 안 탐
self.links.at(self.stack, name, kind, payload)
try:
if kind == "요소":
return number(self.links.element(payload))
@@ -407,6 +409,8 @@ def _money(run: _Run, doc: dict, rules: dict):
for i, line in enumerate(lines):
scope = _scope(doc, outs, dict(running), cover, syms)
where = str(line.get("이름") or f"금액 {i + 1}")
if hasattr(run.links, "at"): # 855-F 셈 기록 — 이 줄 읽음(시간당 작업량)
run.links.at(run.stack, i, "금액", {})
swapped, more, work = mw.line_work(run, line, scope) # 846-1 시간당 작업량
text = line.get("수량") if swapped is None else swapped
qty = (
@@ -14,6 +14,7 @@
from __future__ import annotations
import json
import os
from decimal import Decimal
from pathlib import Path
@@ -24,7 +25,9 @@ import master_machine_crew as mcrew
import master_material as mm
import master_pick as mp
FOLDER = Path(__file__).resolve().parents[1] / "수식문서"
# 화면 저장 시험 사본(`AISLO_MASTER_DIR` — `M01_MasterData_Store.FOLDER` 와 같이) · 없으면 정본
_HOME = os.environ.get("AISLO_MASTER_DIR") or Path(__file__).resolve().parents[1]
FOLDER = Path(_HOME).resolve() / "수식문서"
_ARITH_OK = ("num", "bin", "neg")
@@ -0,0 +1,327 @@
# -*- coding: utf-8 -*-
"""단가산출 수식 문서 셈 답 → 산출근거 글(PLAN 855-C 2-C4 · 서버 풀이 글) — 셈 안 함(답만 읽음).
쓰는 곳 = M02 기준 목록 계산서(`M02_Logic_Standard.sheet`) · (뒤에) B09 산출근거(855 보충 B9-4).
⚠ 짝(글 규칙) — 한쪽을 고치면 다른 쪽도 · 거울 시험 `resources/tester/test_855_c4_doc_text.py`:
`A00_Common/line_stack_out.ts`(금액 줄 · 계 줄 꼴 · 수 꼴 `one` · `won` · 비목 이름) ·
`ui_template/ui_template_equation.ts`(`eqText`) ·
`common_util/common_util_line_stack_unit.ts`(`unitText` · `isAtom` · `moneyUnits`) ·
`common_util/common_util_formula_doc_view.ts`(`offLine` — 선택으로 꺼진 줄).
금액 줄 = 「이름 : 단가 원/단위 × 수량 단위 = 금액 원」 · 묶음 줄 = 비목마다 「노무비 : …」 ·
계 = 「노무비 : 줄 + 줄 = 금액 원」 · 「합계 : 금액 원」.
수 꼴 = 화면과 같음 — 단가 · 수량 = `eqText`(소수 여섯 자리까지 · 셈 값 그대로) ·
줄 금액 = 소수 한 자리 · 비목 · 합계 = 원(셈 답의 끝수 그대로 · 여기서 자르지 않음).
옮기지 않은 것(화면만) — 식 조판(KaTeX · 수량 식은 값 하나로) · 공식 줄 · 펼침 ·
작업량 줄(846-2) · 굳은 기계 이름(847-1) · 비목곱 인수 글(848-7 · 금액은 답 그대로) ·
계 덧셈 항 = 줄 금액(화면은 묶음 줄 있는 항목 · 항이 넷 넘으면 항목 소계 — 여기는 금액만).
"""
from __future__ import annotations
import re
from decimal import ROUND_FLOOR, ROUND_HALF_UP, Decimal, InvalidOperation
import master_doc as md
import master_doc_calc as mc
COSTS = md.COSTS # 노무비 · 재료비 · 경비
COST_SHOW = {"노무비": "노무비", "재료비": "재료비", "경비": "경 비"}
AMOUNT_UNIT = "원"
LONG_SUM = 4
_HIDE = ("반올림", "올림", "버림")
_SAME = (("일", "인"), ("㎏", "kg"), ("ℓ", "L"))
# ── 수 꼴 ─────────────────────────────────────────────────────────────
def _dec(v) -> Decimal | None:
if isinstance(v, bool) or v is None:
return None
try:
d = Decimal(str(v)) if not isinstance(v, Decimal) else v
except InvalidOperation:
return None
return d if d.is_finite() else None
def _group(d: Decimal, places: int, keep: bool) -> str:
q = d.quantize(Decimal(1).scaleb(-places), ROUND_HALF_UP)
sign = "-" if q.is_signed() else "" # Intl 과 같음 — 0 으로 반올림된 음수 = 「-0」
whole, _, frac = f"{abs(q):f}".partition(".")
frac = frac if keep else frac.rstrip("0")
head = f"{int(whole):,}"
return f"{sign}{head}.{frac}" if frac else f"{sign}{head}"
def eq_text(v) -> str:
"""`eqText` — 수 = 천 단위 쉼표 · 소수 여섯 자리까지(반올림 · 끝 0 뗌) · 그 밖 = 글 그대로."""
if v is None or v == "":
return ""
if isinstance(v, bool):
return "true" if v else "false"
d = _dec(v)
if d is None or (isinstance(v, str) and not v.strip()):
return str(v)
return _group(d, 6, False)
def one(v) -> str:
"""줄 금액 — 소수 한 자리 꼭(「26,890.8」 · 「0.0」)."""
return _group(_dec(v) or Decimal(0), 1, True)
def won(v) -> str:
"""비목 · 합계 — 원(JS `Math.round` = 0.5 올림)."""
d = _dec(v) or Decimal(0)
r = (d + Decimal("0.5")).to_integral_value(ROUND_FLOOR)
return eq_text(Decimal("-0") if r == 0 and d.is_signed() else r) # JS Math.round(-0.4) = -0
# ── 단위 ─────────────────────────────────────────────────────────────
def unit_text(u) -> str:
"""자료 단위 글 → 화면 단위(메타 단위 = 빈 글)."""
s = str(u if u is not None else "").strip()
if not s or re.search(r"따름|원문 단위 없음", s) or re.match(r"^수(\(| 또는|$)", s):
return ""
s = re.sub(r"^%\(.*\)$", "%", s)
return s.replace("10^-7", "10⁻⁷").replace("kWh", "㎾h")
def _same(a: str, b: str) -> bool:
return a == b or any((a == x and b == y) or (a == y and b == x) for x, y in _SAME)
def is_atom(n) -> bool:
"""한 덩이(기호 · 수 · 칸 · 글 — 반올림 · 올림 · 버림 감싸개 안 한 덩이 포함)."""
if not n:
return False
if n[0] == "call" and n[1] in _HIDE and 1 <= len(n[2]) <= 2:
return is_atom(n[2][0])
return n[0] in ("var", "num", "field", "str")
def node_of(text):
if text is None or str(text).strip() == "":
return None
try:
return md.parse(text)
except md.DocError:
return None
def money_units(
line: dict, price, qty, price_var: dict | None = None, sub: dict | None = None
) -> dict:
"""금액 줄 단위 자리 `{price, qty, wrap}` — 수량이 식이면 괄호 ·
단가 분모가 수량 단위와 같은 뜻이면 수량 단위 글."""
has = line.get("수량") not in (None, "")
q = unit_text(line.get("단위")) if has else ""
wrap = bool(q) and bool(qty) and not is_atom(qty)
own = next(
(
u
for u in (
unit_text((sub or {}).get("결과단위")),
unit_text((price_var or {}).get("단위")),
)
if u.startswith("원")
), # fmt: skip
None,
)
mine = f"{AMOUNT_UNIT}/{q}" if own and q and _same(own[2:], q) else own
fallback = f"{AMOUNT_UNIT}/{q}" if q else ""
price_unit = (mine if mine is not None else fallback) if has and is_atom(price) else ""
return {"price": price_unit, "qty": q, "wrap": wrap}
def price_sym(line: dict) -> str | None:
n = node_of(line.get("단가"))
if not n:
return None
if n[0] == "var":
return n[1]
if n[0] == "field" and n[1][0] == "var":
return n[1][1]
return None
def line_name(line: dict) -> str:
"""이름에 규격이 들면 한 번만(814-1)."""
name, spec = str(line.get("이름") or ""), line.get("규격")
return f"{name} {spec}".strip() if spec and spec not in name else name
# ── 선택으로 꺼진 줄(`offLine`) ───────────────────────────────────────
class _Look:
"""셈 답 값으로 조건만 읽음 — 계산기 한 벌(`master_doc_calc._Run.ev`) · 값은 답에서 채움."""
def __init__(self, doc: dict, answer: dict, links):
self.run = mc._Run(doc, links, None, (), {})
got = answer.get("값") or {}
names = {md.var_id(v) for v in doc.get("변수") or []}
names |= {str(x.get("기호") or "") for x in doc.get("식") or []}
for name in names: # 답에 없는 값 = 모름(다시 셈하지 않음 · 화면 `evalNode` 와 같음)
have = got.get(name)
self.run.values[name] = mc.Blank("모름") if have is None else have
self.lines = {str(x.get("기호") or ""): x.get("식") for x in doc.get("식") or []}
def value(self, n):
try:
v = self.run.ev(n, None, "")
except Exception: # noqa: BLE001 — 그림용 값 · 모르면 없음
return None
return None if isinstance(v, (mc.Blank, mc.Stop)) else v
def taken(self, n) -> int:
if not (n and n[0] == "call" and n[1] == "만약" and len(n[2]) == 3):
return 0
t = self.value(n[2][0])
return 0 if t is None else (1 if t else 2)
def off_zero(self, n, path: frozenset = frozenset()) -> bool:
if not n:
return False
at, hop = n, 0
while pick := self.taken(at):
at, hop = at[2][pick], hop + 1
if hop and at[0] == "num":
return at[1] == 0
kind = at[0]
if kind == "var":
name = at[1]
if name not in self.lines or name in path:
return False
return self.off_zero(node_of(self.lines[name]), path | {name})
if kind in ("neg", "pct"):
return self.off_zero(at[1], path)
if kind == "bin":
if at[1] == "*":
return self.off_zero(at[2], path) or self.off_zero(at[3], path)
if at[1] == "/":
return self.off_zero(at[2], path)
if at[1] in ("+", "-"):
return self.off_zero(at[2], path) and self.off_zero(at[3], path)
return False
def off_line(self, line: dict) -> bool:
return any(self.off_zero(node_of(line.get(k))) for k in ("수량", "단가"))
# ── 줄 글 ────────────────────────────────────────────────────────────
def _num(v) -> Decimal | None:
return _dec(v)
def _u(text: str, unit: str) -> str:
return f"{text} {unit}" if unit else text
def money_lines(doc: dict, answer: dict, links) -> list[dict]:
"""금액 줄마다 산출근거 조각 `{i, 이름, 비목, 단가, 수량, 금액, 단위, 글, 꺼짐, 합밖, 까닭?}` ·
묶음 줄 = 비목마다 한 조각(`비목` = 노무비 · 재료비 · 경비 · `묶음줄` 참)."""
look = _Look(doc, answer, links)
vars_ = {md.var_id(v): v for v in doc.get("변수") or []}
rows = answer.get("줄") or []
out: list[dict] = []
for i, line in enumerate(doc.get("금액") or []):
got = rows[i] if i < len(rows) else {}
name = line_name(line)
ps = price_sym(line)
pv = vars_.get(ps) if ps else None
link = (pv or {}).get("연결") or {}
sub = None
if link.get("갈래") == "단가산출" and link.get("키") and "{" not in str(link["키"]):
try:
sub = links.doc(str(link["키"]))
except Exception: # noqa: BLE001 — 못 읽는 부름 = 단위 없이
sub = None
mu = money_units(line, node_of(line.get("단가")), node_of(line.get("수량")), pv, sub)
qty = got.get("수량")
base = {
"i": i,
"이름": name,
"수량": _num(qty),
"단위": mu,
"꺼짐": look.off_line(line),
"합밖": bool(got.get("합밖")),
"묶음": line.get("묶음") or "",
}
tail = "" if qty is None else " × " + _u(eq_text(qty), mu["qty"])
if got.get("까닭") and got.get("금액") is None:
why = got["까닭"]
out.append({**base, "비목": line.get("비목"), "단가": None, "금액": None, "까닭": why,
"글": f"{name} : — {why}"}) # fmt: skip
continue
if line.get("비목") == "묶음":
bundle = got.get("단가") if isinstance(got.get("단가"), dict) else {}
for c in COSTS:
part = (got.get("비목") or {}).get(c)
if _dec(part) is None or (not part and not bundle.get(c)):
continue
price = _u(eq_text(bundle.get(c)), mu["price"])
text = f"{COST_SHOW[c]} : {price}{tail} = {one(part)} {AMOUNT_UNIT}"
out.append({**base, "비목": c, "묶음줄": True, "단가": _num(bundle.get(c)),
"금액": _num(part), "글": text}) # fmt: skip
continue
amt, price = got.get("금액"), got.get("단가")
text = f"{name} : {_u(eq_text(price), mu['price'])}{tail} = {one(amt or 0)} {AMOUNT_UNIT}"
out.append({**base, "비목": line.get("비목"), "단가": _num(price), "금액": _num(amt),
"글": text}) # fmt: skip
return out
def total_lines(answer: dict, lines: list[dict]) -> list[str]:
"""계 줄 — 비목마다 「노무비 : 줄 + 줄 = 금액 원」(항이 넷 넘으면 금액만) ·
「합계 : 금액 원」."""
out = []
for c in COSTS:
terms = [
x["금액"]
for x in lines
if x.get("비목") == c and not x["합밖"] and not x["꺼짐"] and x.get("금액")
]
v = answer.get(c)
if _dec(v) is None:
body = "—"
elif 1 < len(terms) <= LONG_SUM:
body = f"{' + '.join(one(t) for t in terms)} = {won(v)}"
else:
body = won(v) if terms or v else ""
unit = f" {AMOUNT_UNIT}" if _dec(v) is not None and body else ""
out.append(f"{COST_SHOW[c]} : {body}{unit}")
total = answer.get("계")
out.append(f"합계 : {_u(won(total), AMOUNT_UNIT) if _dec(total) is not None else '—'}")
return out
def sheet_groups(doc: dict, answer: dict, links) -> list[dict]:
"""공용 계산서(`A00_Common/calc_sheet.ts`) 묶음 — 비목마다 줄
`{이름, 글 「단가 * 수량 = 금액」, 금액, 묶음, 장비, 옵션꺼짐}` ·
소계 = 셈 답 비목 값(끝수 뒤) ·
합 밖 줄 · 비목 없는 줄 = 뺌."""
groups: dict[str, list] = {c: [] for c in COSTS}
for x in money_lines(doc, answer, links):
c = x.get("비목")
if c not in groups or x["합밖"]:
continue
mu = x["단위"]
if x.get("까닭"):
text = f"— {x['까닭']}"
else:
price = "—" if x["단가"] is None else _u(eq_text(x["단가"]), mu["price"])
qty = "" if x["수량"] is None else " * " + _u(eq_text(x["수량"]), mu["qty"])
text = f"{price}{qty} = {one(x['금액'] or 0)}"
groups[c].append(
{
"이름": x["이름"],
"글": text,
"금액": x["금액"],
"묶음": x["묶음"] or None,
"장비": bool(x.get("묶음줄")) or None,
"옵션꺼짐": x["꺼짐"] or None,
}
)
return [
{"비목": c, "소계": _num(answer.get(c)), "끝수": "", "줄": groups[c]}
for c in COSTS
if groups[c] or _dec(answer.get(c))
]
@@ -0,0 +1,175 @@
# -*- coding: utf-8 -*-
"""수식 문서 셈 기록 — 줄마다 부른 것(PLAN 855-F B9-1 · 설계 855 보충 1-3).
서버 단독(TS 짝 없음) — B08 · B09 가 문서 셈 답을 갈라 합산할 때 「이 줄이 어느 노임 · 자재 ·
기계 · 표 · 하위 단가산출을 불렀나」 를 읽음. 셈은 그대로: `Trace` = `master_doc_link.Links` +
기록 · `master_doc_calc` 의 훅(`links.at`)이 연결마다 알림 — `Links` 에는 `at` 이 없어 기록을 안
켜면 지금 길 그대로.
`calc(doc, Trace(master, docs), given)` → 셈 답 +
- `부름` = 연결 부른 차례 [{문서, 깊이, 이름, 갈래(요소 · 표 · 단가산출), 부름(넘긴 꼴 — 키 · 표 ·
조건 · 입력 · 재료 …), 자원[{키, 갈래(인력 · 재료 · 기계 · 표)}], 품목?(고른 재료 키) ·
기계?(기계경비 부름 = 결과단위 원/시간 돈 문서의 기계 키)}] —
하위 문서 안 부름도 깊이를 달고 같이(같은 하위 · 같은 입력 두 번째는 셈 답을 다시 씀 = 안 적음)
- `줄[i].부름` = 그 금액 줄 식(수량 · 단가 · 비목곱)이 닿는 이름의 맨 위 부름 차례 번호 + 그 줄
셈 중 읽음(갈래 「금액」 · 이름 = 줄 차례 · 시간당 작업량 기계 칸)
- `자원` = 문서 전체(하위 포함) 자원 키 차례 · 겹침 없음(표 빼고 · 단가 책 수요)
"""
from __future__ import annotations
import inspect
import re
import types
from itertools import takewhile
import master_doc as md
import master_doc_calc as mc
import master_doc_link as ml
CAT = {"LB": "인력", "MT": "재료", "MO": "재료", "EQ": "기계"} # `master_equation_view.CAT` 같은 말
_SLOTS = ("키", "표", "칸", "단위", "재료", "조건", "입력", "지역", "계약종별")
class _Seen:
"""마스터 감쌈 — `get` 이 돌려준 줄을 알림 ·
마스터 메서드도 이 감쌈에 묶어 안쪽 `self.get` 까지 잡음."""
def __init__(self, master, note):
self._m, self._note = master, note
def get(self, ref):
row = self._m.get(ref)
self._note(row)
return row
def __setattr__(self, name, value): # 마스터 칸(찾기 색인 `_found` 등)은 마스터에
if name in ("_m", "_note"):
object.__setattr__(self, name, value)
else:
setattr(self._m, name, value)
def __getattr__(self, name):
raw = inspect.getattr_static(self._m, name)
if isinstance(raw, types.FunctionType):
return raw.__get__(self)
return getattr(self._m, name)
class Trace(ml.Links):
"""기록 켠 연결 — `calls` 에 부른 차례대로 쌓임(여러 문서 셈에 다시 써도 됨)."""
def __init__(self, master, docs: dict[str, dict] | None = None):
super().__init__(_Seen(master, self._note), docs)
self.calls: list[dict] = []
self._now: dict | None = None
self._last: str | None = None
def at(
self, stack: tuple, name, kind: str, payload: dict
) -> None: # 셈 훅(이름 | 금액 줄 차례)
self._now = {
"문서": stack[-1] if stack else "",
"깊이": len(stack),
"이름": name,
"갈래": kind,
"부름": {k: payload[k] for k in _SLOTS if k in payload},
"자원": [],
}
self.calls.append(self._now)
def _note(self, row: dict) -> None:
key = self._last = str(row.get("키") or "")
kind = CAT.get(key[:2]) or ("표" if "줄" in row and "조건" in row else None)
if not kind:
return
if self._now is None: # 연결 밖 부름(이름 없는 기계 줄 읽기) — 이름 빈 기록
self.at((), "", "", {})
got = self._now["자원"]
if not any(x["키"] == key for x in got):
got.append({"키": key, "갈래": kind})
def element(self, p: dict):
if p.get("재료") is None or self._now is None:
return super().element(p)
got, before, self._last = self._now["자원"], len(self._now["자원"]), None
try:
return super().element(p)
finally: # 재료 찾기 = 고른 품목 하나 — 찾을 때 훑은 후보 · 색인 짓기 읽음은 뺌
del got[before:]
if self._last and CAT.get(self._last[:2]) == "재료": # 마지막 읽음 = 고른 품목
self._now["품목"] = self._last # (`mp.priced` 출처 · 값 없음 = 그 이름 글 읽음)
if not any(x["키"] == self._last for x in got):
got.append({"키": self._last, "갈래": "재료"})
def _names(text) -> list[str]:
if text in (None, ""):
return []
try:
return md.names(md.parse(str(text)))
except md.DocError:
return []
def reach(doc: dict, texts: list) -> set[str]:
"""식 글들이 닿는 이름 전부 — 식 줄 · 연결 구멍(`{이름}`) · 조건 · 입력 식 · 지역 칸을
따라감."""
vars_ = {md.var_id(v): v for v in doc.get("변수") or []}
lines = {str(x.get("기호") or ""): x for x in doc.get("식") or []}
todo = [n for t in texts for n in _names(t)]
seen: set[str] = set()
while todo:
name = todo.pop()
if name in seen:
continue
seen.add(name)
if name in lines:
todo += _names(lines[name].get("식"))
link = (vars_.get(name) or {}).get("연결") or {}
for k in ("키", "표"):
todo += md.HOLE.findall(str(link.get(k) or ""))
for v in (link.get("재료") or {}).values() if isinstance(link.get("재료"), dict) else ():
todo += md.HOLE.findall(str(v))
for k in ("조건", "입력"):
for v in (link.get(k) or {}).values() if isinstance(link.get(k), dict) else ():
todo += _names(v)
todo += [str(link[k]) for k in ("지역", "계약종별") if link.get(k)]
return seen
def _machines(trace: Trace, calls: list[dict]) -> None:
"""기계경비 부름(결과단위 원/시간 돈 문서 · `master_bundle.is_machine` 같은 판별)에 「기계」 =
그 부름 안에서 처음 읽은 기계 키(옛 `B09 call_of` 의 machine) · 같은 부름 두 번째 = 앞 답."""
seen: dict[str, str | None] = {}
for i, c in enumerate(calls):
doc = trace.doc(str(c["부름"].get("키"))) if c["갈래"] == "단가산출" else None
unit = re.sub(r"\s", "", str((doc or {}).get("결과단위") or ""))
if not doc or doc.get("결과") or unit != "원/시간":
continue
tag = repr((c["부름"].get("키"), sorted((c["부름"].get("입력") or {}).items())))
inner = [c, *takewhile(lambda x: x["깊이"] > c["깊이"], calls[i + 1 :])]
got = [x["키"] for one in inner for x in one["자원"] if x["갈래"] == "기계"]
c["기계"] = seen[tag] = got[0] if got else seen.get(tag)
def calc(doc: dict, trace: Trace, given: dict | None = None, cover: dict | None = None) -> dict:
"""문서 셈(`master_doc_calc.calc` 그대로) + 기록 — 모듈 머리 꼴."""
start = len(trace.calls)
trace._now = None
got = mc.calc(doc, trace, given, cover=cover)
calls = [c for c in trace.calls[start:] if c["갈래"] != "금액" or c["자원"]] # 빈 줄 읽음 뺌
top = 1 if doc.get("키") else 0
for i, (line, out) in enumerate(zip(doc.get("금액") or [], got.get("줄") or [])):
texts = [line.get("수량"), line.get("단가"), *(line.get(mc.TIMES) or {}).values()]
names = reach(doc, texts) | {i} # 이 줄 읽음(갈래 「금액」 · 이름 = 줄 차례)
out["부름"] = [
j
for j, c in enumerate(calls)
if c["깊이"] == top and c["이름"] in names and (c["갈래"] == "금액") == (c["이름"] == i)
]
_machines(trace, calls)
keys: list[str] = []
for c in calls:
keys += [x["키"] for x in c["자원"] if x["갈래"] != "표" and x["키"] not in keys]
return {**got, "부름": calls, "자원": keys}
+4 -1
View File
@@ -7,6 +7,7 @@
from __future__ import annotations
import json
import os
import re
from decimal import Decimal
from pathlib import Path
@@ -77,7 +78,9 @@ def save_book(book: dict, path: Path = BOOK) -> None:
comma = "," if i < len(items) - 1 else ""
lines.append(f" {json.dumps(key)}: {json.dumps(v, ensure_ascii=False)}{comma}")
lines += [" }", "}"]
path.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
tmp = path.with_name(f".{path.name}.tmp") # 임시 파일 → 교체(원자적 · 끊겨도 반쪽 대장 없음)
tmp.write_text("\n".join(lines) + "\n", encoding="utf-8", newline="\n")
os.replace(tmp, path)
def lookup(book: dict) -> dict: