fix(845-3): 단위 점검 마무리 — 채움 규칙이 안 닿던 길 · 표 줄 단위 · 나눔 역산(값 · 금액 불변)

- 자료 자리(sub3 차림 도구) 3,836 → 3,299 · 이름 맞춤 2,065 → 1,823(무차원 579 = 흠 아님 · 진짜 빈 자리 1,643 → 1,244)
- 「목록에 없음」 1,905 = 화면 이름 표기(위첨자 「표」 숨김 · 금액 줄 이름 별칭)로 같은 변수가 두 번 잡힌 것 — 자료 결손 0
- master_doc_unit.fill: 값칸 「수」 표는 줄 단위 칸 = 값 단위(한 가지 = 그 단위 · 여럿 = 줄 따름) · 고른 줄 단위 없음 + 계수 이름 = 빈 단위 · 덧글 괄호 뗌 · 나눔 역산 꼴 둘(V ÷ 시공량 → 줄 단위 · 계수 ÷ V → 결과 분모 ÷ 줄 단위) · 표 줄 단위가 금액 줄과 다르면 금액 줄 · 값칸 빈칸 표 줄 단위(무엇당)는 안 읽음
- 표 줄 단위 채움(원문이 또렷한 것만): ㎝(sec) · ㎝(초) · 적용원문 sec · 표 이름 0.7㎥ 의 q · 원문 22″ 를 「“」 로 옮긴 줄(소요량 · 계수 산림 표 6 파일)
- 수식 문서 저장본 = 빌더 다시 지음(변수 단위 칸만 351 칸 · 단위 밖 다름 0 · --check 1,520 같음 · 옵션 표본 18,873)
- 시험 test_845_3_doc_units 신설(저장본 단위 · 규칙 꼴 · 안 하는 꼴)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 01:04:59 +09:00
co-authored by Claude Opus 5.5
parent 77b63e02e1
commit b241702d23
21 changed files with 576 additions and 370 deletions
@@ -43,6 +43,10 @@ NOT_UNIT = (
"수 또는 글자",
"수 또는 글",
) # 단위 칸에 적힌 「수」 = 단위 아님 → 빈 단위
ROWS_ONE, ROWS_MANY = "고를 수 있는 행 단위 한 가지", "행마다 단위 다름"
ROWS_NONE = "고른 행에 단위 칸 없음(계수)"
ROWS_GAP = "고른 행에 단위 칸 없음"
ROWS_NUM = "값칸 「수」 · 고를 수 있는 행 단위 한 가지" # 845-3 새 길 — 금액 줄과 어긋나면 줄 단위(`_direct`)
ROW = "줄 따름" # 행마다 다른 단위 한 표기(화면이 안 그림 · `common_util_line_stack_pick`)
TEXT = ("글", "글자")
# 비교 · 셈 꼴 — 같은 단위의 다른 표기
@@ -313,6 +317,10 @@ def _one(units) -> str | None:
if len(got) != 1 or any(u in (None, "") for u in units):
return None
one = got.pop()
bare = re.sub(
r"\s*\([^()]*\)$", "", one
).strip() # 「시간(h)」 · 「m/분(2단)」 = 단위 + 덧글(845-3)
one = bare if bare and parse(bare) == parse(one) else one
return one if parse(one) is not None else None
@@ -345,6 +353,13 @@ def element_unit(master, link: dict, choices: dict | None = None) -> tuple[str |
return None, f"요소 「{tid}」"
COEF = re.compile(r"^[kKfEe](\(|$|\s)|계수|효율|율") # 단위 없는 계수 줄 이름
def _coef(row: dict) -> bool:
return any(COEF.search(str(row.get(k) or "")) for k in ("구분", "항목", "이름"))
def _row_unit(master, link: dict, choices: dict) -> tuple[str | None, str]:
"""표 칸 단위 — 값칸 단위 · 자리표시면 고를 수 있는 행이 모두 같은 `단위` 칸."""
rows = _rows_of(master, str(link.get("표") or ""))
@@ -357,7 +372,11 @@ def _row_unit(master, link: dict, choices: dict) -> tuple[str | None, str]:
if head in TEXT:
return "글", "값칸 = 글"
picked = table.get("줄") or []
if head not in ROW_UNIT and not (parse(head) is None and any("단위" in r for r in picked)):
rows = any(
"단위" in r for r in picked
) # 줄마다 `단위` 칸 = 값 칸의 참 단위(845-3 — 값칸 「수」 도)
# 값칸 빈칸 표의 줄 `단위` = 「무엇당」(케이싱 m 당 인) 일 수 있어 안 읽음
if head not in ROW_UNIT and not (rows and (parse(head) is None or head in PLAIN_NUMBER)):
return show(head), "값칸 단위"
for k, cond in (link.get("조건") or {}).items():
cond = str(cond).strip()
@@ -365,8 +384,12 @@ def _row_unit(master, link: dict, choices: dict) -> tuple[str | None, str]:
picked = [r for r in picked if str(r.get(k)) == cond[1:-1]]
elif cond in choices:
picked = [r for r in picked if str(r.get(k)) in choices[cond]]
if picked and all(r.get("단위") in (None, "") for r in picked): # 845-3
if all(_coef(r) for r in picked):
return "", ROWS_NONE # 고른 행에 단위 칸 없음 + 계수 이름(k · f · E · 소모율)
return None, ROWS_GAP # 표 자료 빈칸 — 금액 줄 역산에 맡김
got = _one([r.get("단위") for r in picked]) if picked else None
return got, ("고를 수 있는 행 단위 한 가지" if got else "행마다 단위 다름")
return got, ((ROWS_NUM if head in PLAIN_NUMBER else ROWS_ONE) if got else ROWS_MANY)
def dimensionless(var: dict) -> bool:
@@ -419,6 +442,19 @@ def decide(master, doc: dict, v: dict) -> tuple[str | None, str]:
src, why = source_unit(master, doc, v)
if src == "글":
return ("글", why) if not now else (None, why)
if kind == "표" and why == ROWS_NONE and now in (*ROW_UNIT, *NOT_UNIT):
return "", why
if (
kind == "표" and why == ROWS_GAP
): # 표 빈칸 — 옛 꼴 그대로(자리표시 한 표기 · 「수」 = 빈 단위)
if now in ROW_UNIT and now != ROW:
return ROW, "행마다 다른 단위 표기 하나로"
return ("", "단위 칸 「수」 = 단위 아님") if now in NOT_UNIT else (None, why)
if kind == "표" and (now in NOT_UNIT or not now) and why in (ROWS_ONE, ROWS_NUM, ROWS_MANY):
if src: # 값칸 「수」 · 빈칸이어도 줄 `단위` 칸이 있으면 그것(845-3)
return (src if src != now else None), why
if why == ROWS_MANY:
return ROW, "행마다 다른 단위 표기 하나로(줄 `단위` 칸)"
if kind == "표" and now in NOT_UNIT:
return "", "단위 칸 「수」 = 단위 아님"
if not now or (kind == "표" and (now in ROW_UNIT or parse(now) is None)):
@@ -436,6 +472,7 @@ def fill(doc: dict, master) -> list[tuple[str, str, str, str]]:
"""빈 단위(· 자리표시)를 원본 · 식 셈 · 금액 줄 역산으로 채움 — [(기호, 전, 후, 근거)]."""
changed, texts = [], set()
by_id = {md.var_id(v): v for v in doc.get("변수") or []}
rowed = set() # 이번에 표 줄 `단위` 칸으로 채운 변수(845-3) — 금액 줄과 어긋나면 줄 단위
for v in doc.get("변수") or []:
got, why = decide(master, doc, v)
if got == "글":
@@ -443,12 +480,21 @@ def fill(doc: dict, master) -> list[tuple[str, str, str, str]]:
elif got is not None:
changed.append((md.var_id(v), str(v.get("단위") or ""), got, why))
v["단위"] = got
if why == ROWS_NUM: # 값칸 「수」 길(845-3)만
rowed.add(md.var_id(v))
steps = {line["기호"]: line["식"] for line in doc.get("식") or []}
for vid, (unit, why) in _direct(doc, by_id, known(doc, texts), rowed).items():
changed.append((vid, str(by_id[vid].get("단위") or ""), unit, why))
by_id[vid]["단위"] = unit
_forward(doc, by_id, steps, texts, changed)
for vid, (unit, why) in _back(doc, by_id, steps, known(doc, texts)).items():
changed.append((vid, "", unit, why))
by_id[vid]["단위"] = unit
_forward(doc, by_id, steps, texts, changed)
for vid, (unit, why) in _solve(doc, by_id, known(doc, texts)).items():
changed.append((vid, "", unit, why))
by_id[vid]["단위"] = unit
_forward(doc, by_id, steps, texts, changed)
return changed
@@ -529,6 +575,91 @@ def _back(doc, by_id, steps, units) -> dict:
return out
def _direct(doc, by_id, units, rowed=()) -> dict:
"""금액 줄 수량 = 변수 하나(표) · 단가와 맞는 줄 — 이번에 표 줄 `단위` 칸으로 채운 변수가 줄 단위와 다르면
줄 단위(표 줄 단위 = 자료 흠 · 근거 글에 남김 · 845-3)."""
got: dict[str, set] = {}
for line in doc.get("금액") or []:
vid = str(line.get("수량") or "").strip()
v = by_id.get(vid)
if v is None or str(line.get("단위") or "") == "식" or not line_ok(line, units):
continue
if (v.get("연결") or {}).get("갈래") in ("표", "식"):
got.setdefault(vid, set()).add(show(line["단위"]))
out = {}
for vid, kinds in got.items():
have = str(by_id[vid].get("단위") or "")
if len(kinds) != 1 or have in ROW_UNIT:
continue
want = kinds.pop()
if vid in rowed and parse(have) is not None and not same(have, want):
out[vid] = (
want,
f"금액 줄 수량 그대로 — 줄 단위 {want}(표 줄 단위 「{have}」 와 다름)",
)
return out
_V = "□" # 풀 변수 자리(차원 이름)
def _solve(doc, by_id, units) -> dict:
"""금액 줄 나눔 역산(845-3) — 수량에 단위 모르는 표 · 식 변수가 하나 · 나머지 단위 앎 · 수가 단위를 안 품음:
수량 참 단위 = 줄 단위 ÷ 결과 분모(원/X — 품 값은 X 하나당)로 그 변수를 풂 · 꼴 둘만(지어내지 않음)
㉮ 「V ÷ 시공량[X]」(× 보정 계수) → V = 줄 단위(「Q_특별인부^표 ÷ Q_시공」 → 인)
㉯ 「계수 ÷ V」(r ÷ 100 · 2 배 안 수) → V = X / 줄 단위(「r_기계 ÷ 100 ÷ Q_작업」 → ㎥/시간).
한 변수에 두 단위가 나오면 안 채움."""
res = str(doc.get("결과단위") or "")
per = parse(res.split("/", 1)[1]) if res.startswith("원/") else None
if per is None or per[0] != 1 or not per[1]:
return {}
got: dict[str, set] = {}
for line in doc.get("금액") or []:
if not line.get("수량") or str(line.get("단위") or "") == "식" or not line_ok(line, units):
continue
try:
node = md.parse(line["수량"])
except md.DocError:
continue
loose = [
n
for n in md.names(node)
if n in by_id
and n not in units
and not by_id[n].get("단위")
and (by_id[n].get("연결") or {}).get("갈래") in ("표", "식")
]
if len(loose) != 1:
continue
try:
val = _val(node, {**units, loose[0]: (Fraction(1), {_V: 1})})
except (Unknown, ArithmeticError):
continue
if val in (_ZERO, _TEXTV) or not all(FACTOR[0] <= abs(1 / f) <= FACTOR[1] for f in val[0]):
continue
e, rest = val[1].get(_V), {k: n for k, n in val[1].items() if k != _V}
mine = parse(line.get("단위"))[1]
if e == 1 and rest == {k: -n for k, n in per[1].items()}:
dims = dict(mine) # ㉮
elif e == -1 and not rest:
dims = {**per[1]} # ㉯ X / 줄 단위
for k, n in mine.items():
dims[k] = dims.get(k, 0) - n
dims = {k: n for k, n in dims.items() if n}
else:
continue
if not dims or any(abs(n) > 1 for n in dims.values()):
continue
got.setdefault(loose[0], set()).add((text_of(dims), str(line.get("이름") or "")))
out = {}
for vid, hits in got.items():
kinds = {u for u, _ in hits}
if len(kinds) == 1:
names = " · ".join(sorted({n for _, n in hits})[:3])
out[vid] = (kinds.pop(), f"금액 줄 「{names}」 나눔 역산(줄 단위 ÷ 결과 단위 {res})")
return out
def _factor(node) -> bool:
"""변수 없는 수 · 만약(…, 수, 수) — 2 배 안 보정 계수."""
try: