test(857-0): 불러오기 지문 — 블록 두 판 · 검산 · 이음 · 엑셀 올림 호표 목록 · 칠 · 고정 줄 · 재료 이음 표

- 새 test_857_import_golden + helper_857_import + golden_857_import.json(블록 3,241 · 올림 47 · 재료표 11 파일)
- 블록 = 원파일 EST · STC · 실무 엑셀 블록마다 엑셀 판 · 우리 판 문서 셈(노 · 재 · 경 · 계) · 검산 판정 · 줄 이음 판정
- 올림 = 실무 엑셀 11 을 임시 개인 층에 올림 → 거절 글 | 호표 목록 · 칠 · 고정 줄 · 재료 이음 표(호표 길 키 대 단가산출 길 키)
- 기본 = 빠른 표본(블록 60 · 엑셀 3 · 약 30 초) · 전수 = S857_ALL=1 · 견본 없는 PC = 그 갈래 건너뜀(수를 경고로)
- 걸음 4(857) 동안 「다름 0」 자 · 다시 뜨기 = S857_ALL=1 … test_857_import_golden.py --write

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-17 18:35:35 +09:00
co-authored by Claude Opus 5.5
parent 2040bc0c9f
commit 0123e700ea
3 changed files with 3709 additions and 0 deletions
File diff suppressed because it is too large Load Diff
+301
View File
@@ -0,0 +1,301 @@
"""857-0 지킴 도우미 — 불러오기 지문(블록 × 두 판 · 검산 · 이음 / 엑셀 올림 · 호표 목록 · 칠 ·
고정 줄 / 재료 이음 표).
- 블록 = 견본(원파일 EST · STC · 실무 엑셀)마다 `Doc_FromNative.emit` → 가져온 식 SK(저장 없음) →
엑셀 판 · 우리 판 문서 셈(`Doc_Import.derive` + `run`) 노 · 재 · 경 · 계 +
검산(`Sangeun_Imported.check` 같음 · 줄 같음 수) + 줄마다 이음(종류 · 이음 · 기계 찾기 ·
재료 찾기 판정 · 키).
- 올림 = 엑셀을 임시 개인 층에 올림(`Hopyo_Router._upload`) → 거절 글 | 목록(`Hopyo_View.listing`) ·
칠(`Hopyo_Marks.blocks`) · 고정 줄(`Hopyo_Fixed.line_of` 이름 · 규격 · 단위 · 단가 · 이음 · 비율).
- 재료 이음 표 = 일위대가 호표 자재 · 별도계상 줄 — 호표 길 키(`line_of`) ·
단가산출 길 키(`San_Link.m01`).
- 지문 = 갈래 열쇠(「블록 EST:거창#3」 등)마다 sha256 앞 16 자 · 견본 내용은 안 남김.
- M01 한 벌 쥠(셈 동안 M01 파일이 안 바뀜 — 빠르게만 · 답 같음).
"""
from __future__ import annotations
import contextlib
import hashlib
import json
import sys
import tempfile
import warnings
from pathlib import Path
from typing import Any
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[1]
for p in (str(ROOT), str(HERE)):
if p not in sys.path:
sys.path.insert(0, p)
warnings.filterwarnings("ignore", category=UserWarning, module="openpyxl")
KEYS = ("노무비", "재료비", "경비", "계")
#: 기본(빠른) 표본 — 견본마다 블록 몇 개 · 올림 파일 몇 개(전수 = `S857_ALL=1`)
QUICK_BLOCKS = {
"EST:거창": 8,
"STC:봉화": 8,
"엑셀:북부청임도": 8,
"엑셀:봉화": 8,
"엑셀:2026수목": 8,
}
QUICK_UPLOAD = ("북부청임도", "봉화", "2026수목")
def sources() -> dict[str, Path]:
"""「갈래:이름」 → 견본 경로(없는 PC = 경로가 없음)."""
import test_797_1a_import_flags as practice
from test_810_1_estx import FILES as EST
from test_810_1_stc import FILES as STC
out = {f"EST:{k}": v for k, v in EST.items()}
out |= {f"STC:{k}": v for k, v in STC.items()}
return out | {f"엑셀:{k}": v for k, v in practice.FILES.items()}
def digest(value: Any) -> str:
raw = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16]
@contextlib.contextmanager
def hold_m01():
"""M01 한 벌을 셈 동안 쥠(줄마다 파일 날짜 다시 재기 뺌)."""
from M01_MasterData import M01_MasterData_Store as m01
real, memo = m01.loaded, []
def once():
if not memo:
memo.append(real())
return memo[0]
m01.loaded = once
try:
yield
finally:
m01.loaded = real
@contextlib.contextmanager
def personal():
"""임시 storage 개인 층(원본 storage · 마스터 안 씀)."""
from config import config_system
old = config_system.STORAGE_BASE_DIR
tmp = Path(tempfile.mkdtemp(prefix="t857_"))
config_system.STORAGE_BASE_DIR = str(tmp / "storage")
(tmp / "storage").mkdir()
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_Template_Layers as layers
folder = layers.personal_dir(7, 42)
folder.mkdir(parents=True, exist_ok=True)
try:
with store.at(folder):
yield folder
finally:
config_system.STORAGE_BASE_DIR = old
# ── 블록 ──────────────────────────────────────────────────────────────
def saved_of(tag: str, path: Path) -> dict:
from M02_MasterTemplete import M02_Doc_FromNative as fn
from M02_MasterTemplete import M02_San_Xlsx as sx
raw = path.read_bytes()
if tag.startswith("엑셀:"):
return fn.pack(sx.read(path.name, raw), path.name)
return fn.read(path.name, raw)
def _money(got: dict) -> Any:
return {k: str(got.get(k)) for k in KEYS} if got.get("셈됨") else "못 셈"
def _links(row: dict) -> list:
out = []
for it in row.get("호표") or []:
res = it.get("자원") or {}
find, mat = res.get("찾기") or {}, res.get("재료찾기") or {}
out.append(
[
it.get("종류"),
it.get("이음"),
find.get("판정"),
find.get("키"),
mat.get("판정"),
mat.get("키"),
]
)
return out
def block(saved: dict, no: int) -> dict:
"""블록 하나 → 지문 몸 {엑셀, 우리, 검산, 이음}."""
from M02_MasterTemplete import M02_Doc_FromNative as fn
from M02_MasterTemplete import M02_Doc_Import as dim
from M02_MasterTemplete import M02_Sangeun_Doc as sd
from M02_MasterTemplete import M02_Sangeun_Imported as imp
whole = imp._whole()
out = fn.emit(saved, no)
row = out["로직"]
sk = {
"키": "SK-999999",
"이름": row["이름"],
"단위": str(row.get("결과단위", "/")).split("/", 1)[-1],
}
sk |= {"바탕": None, "입력값": {}, "덮개": {}, "뺀줄": [], "더한줄": []}
sk[imp.KEY] = {"로직": row, "원본": out["원본"], "단가기준": "엑셀"}
sk = sd.clean(sk, None, whole)
got: dict[str, Any] = {"이음": _links(row)}
for basis in ("엑셀", "우리"):
one = {**sk, imp.KEY: {**sk[imp.KEY], "단가기준": basis}}
try:
got[basis] = _money(dim.run(dim.derive(one, None, whole), one, whole))
except Exception as e: # noqa: BLE001 — 예외도 지문
got[basis] = f"예외 {type(e).__name__}"
try:
c = imp.check(sk, whole)
got["검산"] = [c["같음"], sum(1 for x in c["줄"] if x.get("같음")), len(c["줄"])]
except Exception as e: # noqa: BLE001
got["검산"] = f"예외 {type(e).__name__}"
return got
def blocks(full: bool) -> tuple[dict[str, str], int]:
"""{「블록 갈래:이름#번」: 지문} · 건너뛴 견본 수."""
from M02_MasterTemplete import M02_Doc_FromNative as fn
out, skipped = {}, 0
with hold_m01(), personal():
for tag, path in sources().items():
if not full and tag not in QUICK_BLOCKS:
continue
if not path or not path.exists():
skipped += 1
continue
saved = saved_of(tag, path)
nos = sorted(fn.numbers(saved))
if not full:
step = max(1, len(nos) // QUICK_BLOCKS[tag])
nos = nos[::step][: QUICK_BLOCKS[tag]]
for no in nos:
out[f"블록 {tag}#{no}"] = digest(block(saved, no))
return out, skipped
# ── 엑셀 올림 · 호표 쪽 ─────────────────────────────────────────────────
def _fixed(book: dict) -> list:
from M02_MasterTemplete import M02_Hopyo_Fixed as hf
linker, out = hf.Linker(True), []
for h in book.get("호표") or []:
for ln in h.get("줄") or []:
fx = hf.line_of(ln, h["줄"], {}, set(), linker)["고정"]
out.append(
[
h["번"],
ln.get("차례"),
{k: fx.get(k) for k in ("이름", "규격", "단위", "단가", "이음", "비율")},
]
)
return out
def mats(book: dict, clues: list) -> list:
"""재료 이음 표 [호표, 차례, 갈래, 호표 길 키, 단가산출 길 키, 산근 판정 · 방법]."""
from M02_MasterTemplete import M02_Hopyo_Fixed as hf
from M02_MasterTemplete import M02_Hopyo_Match as hm
from M02_MasterTemplete import M02_San_Link as sl
from M02_MasterTemplete import M02_San_MatFind as smf
linker, out = hf.Linker(True), []
for h in book.get("호표") or []:
for ln in h.get("줄") or []:
if hf.kind_of(ln) not in hm.MATERIAL_KINDS:
continue
a = (hf.line_of(ln, h["줄"], {}, set(), linker)["고정"]["이음"] or {}).get("자재")
src = {k: ln.get(k) or "" for k in ("이름", "규격", "단위")}
src |= {"종류": "자재", "코드": ln.get("코드") or ""}
with smf.clues_on(clues):
b, _ = sl.m01("재료", src, "")
found = src.get("재료찾기") or {}
out.append(
[
h["번"],
ln.get("차례"),
ln.get("갈래"),
a,
b,
found.get("판정"),
found.get("방법"),
]
)
return out
def upload(tag: str, path: Path) -> dict[str, Any]:
"""엑셀 하나 올림(임시 층) → {올림, 목록, 칠, 고정, 재료} 지문 몸."""
from M02_MasterTemplete import M02_Doc_FromNative as fn
from M02_MasterTemplete import M02_Hopyo_Marks as marks
from M02_MasterTemplete import M02_Hopyo_Router as router
from M02_MasterTemplete import M02_Hopyo_Store as hstore
from M02_MasterTemplete import M02_Hopyo_View as view
from M02_MasterTemplete import M02_MasterTemplete_Store as store
from M02_MasterTemplete import M02_San_Book as sb
from M02_MasterTemplete import M02_San_Xlsx as sx
data = path.read_bytes()
try:
row = router._upload(path.name, data, {"id": 42, "이름": "시험"})
except store.StoreError as e:
return {"올림": f"거절 {e.status} {e}"}
folder, key = store.root(), row["키"]
book = hstore.read(folder, key)
listing = view.listing(folder, key, folder)
sheets = sb.sheets(path.name, data)
clues = (fn.pack(sx.read_sheets(sheets), path.name) if sb.kind_of(sheets) else {}).get("단서")
return {
"올림": {k: row.get(k) for k in ("시트", "호표수", "읽기불가")},
"목록": {k: listing.get(k) for k in ("호표", "단산", "검산")},
"칠": marks.blocks(folder, key),
"고정": _fixed(book),
"재료": mats(book, clues or []),
}
def uploads(full: bool) -> tuple[dict[str, str], dict[str, list], int]:
"""({「올림 이름 갈래」: 지문}, {이름: 재료 이음 표}, 건너뛴 수)."""
out, table, skipped = {}, {}, 0
with hold_m01(), personal():
for tag, path in sources().items():
name = tag.split(":", 1)[1]
if not tag.startswith("엑셀:") or (not full and name not in QUICK_UPLOAD):
continue
if not path or not path.exists():
skipped += 1
continue
got = upload(tag, path)
for part, body in got.items():
out[f"올림 {name} {part}"] = digest(body)
table[name] = got.get("재료") or []
return out, table, skipped
def mat_counts(table: dict[str, list]) -> dict[str, dict[str, int]]:
"""재료 이음 전후 표(`m857_mat` 꼴) — 같음(이음) · 같음(못 이음) · 생김 · 풂 · 다른 품목."""
out = {}
for name, rows in table.items():
c: dict[str, int] = {}
for r in rows:
a, b = r[3], r[4]
if a == b:
k = "같음(이음)" if a else "같음(못 이음)"
else:
k = "풀림" if a and not b else "생김" if b and not a else "다른 품목"
c[k] = c.get(k, 0) + 1
out[name] = c
return out
@@ -0,0 +1,70 @@
"""857-0 지킴 — 불러오기 지문(걸음 4 동안 「다름 0」 자 · 도우미 `helper_857_import`).
- 블록 = 원파일 EST · STC · 실무 엑셀 블록마다 엑셀 판 · 우리 판 문서 셈(노 · 재 · 경 · 계) ·
검산 판정 · 줄 이음 판정.
- 올림 = 실무 엑셀을 임시 개인 층에 올림 → 거절 | 호표 목록 · 칠 · 고정 줄 · 재료 이음 표.
- 재료 이음 전후 표 = 호표 길 키 대 단가산출 길 키 갈래 수(857-4 의 기준).
- 기본 = 빠른 표본(`QUICK_*`) · 전수 = 환경 `S857_ALL=1` · 견본 없는 PC = 그 갈래 건너뜀(수를 글로).
- 다르면 실패 + 갈래 이름 — 뜻대로 바꾼 걸음만 다시 뜸(바뀐 갈래를 커밋 글에):
`S857_ALL=1 ./venv/Scripts/python.exe resources/tester/test_857_import_golden.py --write`
"""
from __future__ import annotations
import json
import os
import sys
import warnings
from pathlib import Path
import pytest
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import helper_857_import as h # noqa: E402
FILE = HERE / "golden_857_import.json"
REDO = "S857_ALL=1 ./venv/Scripts/python.exe resources/tester/test_857_import_golden.py --write"
ALL = os.environ.get("S857_ALL") == "1"
def _want() -> dict:
return json.loads(FILE.read_text("utf-8"))
def _compare(got: dict[str, str], want: dict[str, str], skipped: int) -> None:
if not got:
pytest.skip(f"견본 없음 — 건너뜀 {skipped}")
missing = sorted(k for k in got if k not in want)
changed = sorted(k for k in got if k in want and want[k] != got[k])
gone = sorted(k for k in want if k not in got) if ALL and not skipped else []
assert not (missing or changed or gone), (
f"지문 다름 — 바뀜 {len(changed)} {changed[:15]} · 새 {missing[:10]} · 빠짐 {gone[:10]}"
f" · 건너뜀 {skipped}\n뜻대로 바꾼 걸음이면 다시 뜸: {REDO}"
)
if skipped:
warnings.warn(f"견본 없어 건너뜀 {skipped}", stacklevel=2)
def test_블록_두_판_검산_이음_지문_같음():
got, skipped = h.blocks(ALL)
_compare(got, _want()["블록"], skipped)
def test_엑셀_올림_호표_목록_칠_고정_재료_지문_같음():
got, table, skipped = h.uploads(ALL)
_compare(got, _want()["올림"], skipped)
want = _want()["재료표"]
assert {k: v for k, v in h.mat_counts(table).items()} == {k: want[k] for k in table}
if __name__ == "__main__":
if "--write" not in sys.argv or not ALL:
sys.exit(f"다시 뜨기 = {REDO}")
blocks, skip_b = h.blocks(True)
ups, table, skip_u = h.uploads(True)
body = {"판": 1, "블록": blocks, "올림": ups, "재료표": h.mat_counts(table)}
FILE.write_text(
json.dumps(body, ensure_ascii=False, indent=1, sort_keys=True) + "\n", "utf-8", newline="\n"
)
print(f"블록 {len(blocks)} · 올림 {len(ups)} · 건너뜀 {skip_b + skip_u} → {FILE.name}")