refactor(857-3b): 소요량 · 계수 값 역색인 = M01 수식 문서 — 옛 로직 줄 · 옛 식 파서 안 읽음
- San_Basis_Index.load 로직 = 수식문서 폴더(master_doc_link.load_all) · scan = 문서 변수 연결(표 찾기 · 단가산출 부름 · 기계 요소 칸) · 식 줄 · 덧줄 식 · 금액 줄 수량 수(문서 파서) · 이름 인자 = 입력 이름(기호 → 열쇠) · 지문에 수식 문서 파일 - master_auto(ma._texts) · mf.parse · mf._OPS 안 씀 · trade 는 그대로(이미 Hopyo_ReadEst.trade 한 줄 감쌈 = 가벼운 자리 Hopyo_Shares 와 같은 것) - 대조: 옛 역색인 대 새 역색인 — 3,241 블록 소요량 자리 10,671 후보 전부 같음(속 표 uses · inline 은 문서가 × 1 · ÷ 100 군더더기를 걷어 갈래 몇이 다름 · 후보에는 안 닿음) - 세기: 불러오기 길(짓기 · 검산 · 열기 두 판 · 이음 고침 · 소요량 보기 · 단가기준) 옛 변환기 · 색인 .logic · 옛 식 파서 부름 0(전 = 역색인 짓기 mf.parse 14,102) - 지킴: test_797_2 · 802_4b1 · 857 골든 전수 · 관련 시험 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,7 +12,8 @@ N6 표 기준 · N7 식 속 수 · N8 단위 성격(N9 · N10 옛 근거 제안
|
||||
쓰는 곳 = 소요량 · 계수 이음 `M02_Sangeun_QtyLinks`).
|
||||
우연 보정(`q_of` · `pb_sig`) = 보정 자료(실무 여덟 파일 상수 · `M02_San_Basis_corpus.json`) 몫 ·
|
||||
포아송 이항 꼬리 −log10.
|
||||
짓기 = M01 폴더 지문(`stamp`)마다 한 번(`get` · 프로세스 안 캐시 · 지문 바뀌면 다시).
|
||||
짓기 = M01 폴더 지문(`stamp`)마다 한 번(`get` · 프로세스 안 캐시 · 지문 바뀌면 다시) ·
|
||||
로직 = M01 수식 문서(857-3b · 옛 로직 줄 · 옛 식 파서 안 읽음 · 문서 파서).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,8 +35,12 @@ from common_util import common_util_derived_store as derived
|
||||
from M01_MasterData import M01_MasterData_Store as m01
|
||||
from M02_MasterTemplete import M02_Hopyo_ReadEst as est
|
||||
|
||||
mf = m01.cm.mf
|
||||
import master_auto as ma # noqa: E402 — mf 를 불러 scripts 경로가 깔린 뒤
|
||||
m01.cm.mf # noqa: B018 — scripts 경로를 깖(M01 저장 모듈이 부름)
|
||||
import master_doc as md # noqa: E402
|
||||
import master_doc_link as ml # noqa: E402
|
||||
|
||||
DOCS = "수식문서" # M01 폴더 아래 수식 문서 폴더(`master_doc_link.FOLDER`)
|
||||
CMP = ("<=", ">=", "==", "!=", "<", ">") # 비교 글자
|
||||
|
||||
CORPUS = Path(__file__).with_name("M02_San_Basis_corpus.json")
|
||||
INLINE_MAX = 20 # 식 속 수가 이보다 많은 로직(표를 식으로 펼친 것)은 식 속 수 맞음을 안 셈
|
||||
@@ -149,6 +154,8 @@ def stamp() -> str:
|
||||
}
|
||||
if m01.cm.mmf.here(folder()): # 기계 = 폴더(826-2)
|
||||
files[m01.cm.mmf.NAME] = m01.version_of(m01.cm.mmf.raw(folder(), m01.cm.mmf.NAME))
|
||||
for p in sorted((folder() / DOCS).glob("수식_*.json")): # 857-3b 로직 = 수식 문서
|
||||
files[f"{DOCS}/{p.name}"] = derived.file_digest(p)
|
||||
return derived.derived_key("san-basis-index", files, derived.file_digest(CORPUS))
|
||||
|
||||
|
||||
@@ -157,9 +164,8 @@ def load(root: Path) -> tuple[dict, dict, dict, dict]:
|
||||
for f in glob.glob(str(root / "소요량_*.json")) + glob.glob(str(root / "계수_*.json")):
|
||||
for t in json.loads(Path(f).read_text(encoding="utf-8")).get("표", []):
|
||||
tables[t["키"]] = t
|
||||
for f in glob.glob(str(root / "로직_*.json")):
|
||||
for it in json.loads(Path(f).read_text(encoding="utf-8"))["줄"]:
|
||||
logic[it["키"]] = it
|
||||
if (root / DOCS).is_dir(): # 857-3b 로직 = 수식 문서(옛 로직 줄 안 읽음)
|
||||
logic = ml.load_all(root / DOCS)
|
||||
for r in m01.cm.mmf.table(root)[0]["줄"]: # 기계 = 폴더(826-2)
|
||||
eq[r["키"]] = r
|
||||
by_no: dict = {}
|
||||
@@ -178,63 +184,82 @@ def _resolve(ref: str, tables: dict, by_no: dict) -> str | None:
|
||||
return hit[0] if len(hit) == 1 else None
|
||||
|
||||
|
||||
def scan(item: dict, tables: dict, by_no: dict) -> tuple:
|
||||
"""로직 하나 → (찾기 부름, 식 속 수, 하위 로직 부름, 기계 부름, 호표 수량 속 수)."""
|
||||
names = {s["이름"] for s in item.get("입력", [])}
|
||||
def inputs_of(doc: dict) -> dict[str, str]:
|
||||
"""문서 입력 · 선택 변수 {기호: 열쇠(입력 이름)}."""
|
||||
return {
|
||||
md.var_id(v): str(v.get("열쇠"))
|
||||
for v in doc.get("변수") or []
|
||||
if (v.get("연결") or {}).get("갈래") in ("입력", "선택")
|
||||
}
|
||||
|
||||
|
||||
def scan(doc: dict, tables: dict, by_no: dict) -> tuple:
|
||||
"""수식 문서 하나 → (찾기 부름, 식 속 수, 하위 로직 부름, 기계 부름, 호표 수량 속 수) — 857-3b ·
|
||||
옛 로직 줄 훑기와 같은 꼴(이름 = 입력 이름 · 표 · 하위 로직 · 기계 = 변수 연결)."""
|
||||
names = inputs_of(doc)
|
||||
finds, nums, calls, eqs = [], [], [], []
|
||||
|
||||
def arg_of(node):
|
||||
def parse(text: Any) -> Any:
|
||||
try:
|
||||
return md.parse(text)
|
||||
except md.DocError:
|
||||
return None
|
||||
|
||||
def arg_of(text: Any) -> tuple:
|
||||
node = parse(text)
|
||||
if node is None:
|
||||
return ("expr", str(text)[:80])
|
||||
if node[0] == "str":
|
||||
return ("lit", node[1])
|
||||
if node[0] == "num":
|
||||
return ("lit", float(node[1]))
|
||||
if node[0] == "name":
|
||||
return ("name", node[1]) if node[1] in names else ("expr", node[1])
|
||||
if node[0] == "var":
|
||||
return ("name", names[node[1]]) if node[1] in names else ("expr", node[1])
|
||||
visit(node)
|
||||
return ("expr", str(node)[:80])
|
||||
|
||||
def visit(node, field=None):
|
||||
def visit(node: Any) -> None:
|
||||
kind = node[0]
|
||||
if kind == "field":
|
||||
visit(node[1], node[2])
|
||||
elif kind in ("find", "logic"):
|
||||
if kind == "find" and (ref := _resolve(node[1], tables, by_no)):
|
||||
finds.append((ref, field, {c: arg_of(a) for c, a in node[2]}))
|
||||
if kind == "logic" and isinstance(node[1], str) and "{" not in node[1]:
|
||||
calls.append((node[1], {c: arg_of(a) for c, a in node[2]}))
|
||||
for _, a in node[2]:
|
||||
if a[0] not in ("str", "num", "name"):
|
||||
visit(a)
|
||||
elif kind == "ref":
|
||||
if node[1].startswith("EQ") and field:
|
||||
eqs.append((node[1], field))
|
||||
elif kind == "num":
|
||||
if kind == "num":
|
||||
nums.append(float(node[1]))
|
||||
elif kind == "bin":
|
||||
for side in (node[2], node[3]): # 비교 글자(「SCH == 20」)는 셈 수가 아님
|
||||
if node[1] in mf._OPS and side[0] == "num":
|
||||
if node[1] in CMP and side[0] == "num":
|
||||
continue
|
||||
visit(side)
|
||||
elif kind == "neg":
|
||||
elif kind in ("neg", "pct", "field"):
|
||||
visit(node[1])
|
||||
elif kind == "call":
|
||||
for a in node[2]:
|
||||
visit(a)
|
||||
|
||||
for text in ma._texts(item):
|
||||
if any(text is h["수량"] for h in item.get("호표", [])):
|
||||
continue
|
||||
try:
|
||||
visit(mf.parse(text))
|
||||
except mf.FormulaError:
|
||||
pass
|
||||
def hole(key: str) -> str:
|
||||
"""`EQ:{기호}` → `EQ:{입력 이름}`(옛 로직 줄 꼴)."""
|
||||
return re.sub(r"\{([^{}]+)\}", lambda m: "{" + names.get(m.group(1), m.group(1)) + "}", key)
|
||||
|
||||
for var in doc.get("변수") or []:
|
||||
link = var.get("연결") or {}
|
||||
kind, key = link.get("갈래"), str(link.get("키") or link.get("표") or "")
|
||||
if kind == "표" and (ref := _resolve(key, tables, by_no)):
|
||||
args = {c: arg_of(a) for c, a in (link.get("조건") or {}).items()}
|
||||
finds.append((ref, link.get("칸"), args))
|
||||
elif kind == "단가산출" and key and "{" not in key and not key.startswith("SK-"):
|
||||
calls.append((key, {c: arg_of(a) for c, a in (link.get("입력") or {}).items()}))
|
||||
elif kind == "요소" and key.startswith("EQ") and link.get("칸"):
|
||||
eqs.append((hole(key), link["칸"]))
|
||||
texts = [x.get("식") for x in doc.get("식") or []]
|
||||
texts += [x.get("단가") for x in doc.get("금액") or [] if "수량" not in x] # 덧줄 식
|
||||
for text in texts:
|
||||
if (node := parse(text)) is not None:
|
||||
visit(node)
|
||||
trade_nums = [] # (호표 이름, 수량 식 속 수)
|
||||
for h in item.get("호표", []):
|
||||
before = len(nums)
|
||||
try:
|
||||
visit(mf.parse(h["수량"]))
|
||||
except mf.FormulaError:
|
||||
for line in doc.get("금액") or []:
|
||||
if "수량" not in line or (node := parse(line["수량"])) is None:
|
||||
continue
|
||||
trade_nums += [(h.get("이름") or "", x) for x in nums[before:]]
|
||||
before = len(nums)
|
||||
visit(node)
|
||||
trade_nums += [(line.get("이름") or "", x) for x in nums[before:]]
|
||||
|
||||
return finds, nums, calls, eqs, trade_nums
|
||||
|
||||
|
||||
@@ -371,7 +396,7 @@ class Index:
|
||||
m = re.match(r"EQ:\{(\w+)\}", ref)
|
||||
if m:
|
||||
arg = m.group(1)
|
||||
inputs = {sp["이름"] for sp in self.logic[key].get("입력", [])}
|
||||
inputs = set(inputs_of(self.logic[key]).values())
|
||||
if depth == 0 and arg in inputs:
|
||||
use = ("입력", arg)
|
||||
elif depth > 0 and arg in rename:
|
||||
|
||||
Reference in New Issue
Block a user