"""로직 복사 설계용 — 호표·중간·덧줄 식 속 찾기()·로직() 전수 세기 (읽기 전용 · 아무것도 안 씀). resources/master_data/ref/_설계_식_복사.md 의 ② 수치 근거. 사용: ./venv/Scripts/python.exe resources/master_data/scripts/analyze_식_복사.py """ from __future__ import annotations import json import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] NAME_OF = re.compile(r"(찾기|로직)\(\s*([A-Za-z0-9]+)") def find_calls(text: str) -> list[tuple[str, str, str]]: """text 안 찾기(...)·로직(...) 전부 — (종류, 키, 괄호 안 전체 글) 목록. 중첩 괄호는 짝을 맞춰 끊음.""" out = [] for m in NAME_OF.finditer(text): kind, key = m.group(1), m.group(2) start = m.start() + len(kind) # '(' 위치 — 찾기·로직 바로 뒤 depth = 0 i = start while i < len(text): if text[i] == "(": depth += 1 elif text[i] == ")": depth -= 1 if depth == 0: break i += 1 args = text[start + 1 : i] out.append((kind, key, args.strip())) return out def row_lines(row: dict) -> list[tuple[str, str]]: """(자리표, 식 글) 목록 — 호표 수량 · 호표 요소(문자열일 때) · 중간 식 · 덧줄 식.""" out = [] for i, h in enumerate(row.get("호표") or []): if isinstance(h.get("수량"), str): out.append((f"호표[{i}].수량", h["수량"])) if isinstance(h.get("요소"), str): out.append((f"호표[{i}].요소", h["요소"])) for i, m in enumerate(row.get("중간") or []): if isinstance(m.get("식"), str): out.append((f"중간[{i}].식", m["식"])) for i, m in enumerate(row.get("덧줄") or []): if isinstance(m.get("식"), str): out.append((f"덧줄[{i}].식", m["식"])) return out def load_table_names() -> dict[str, str]: """표 키 → 표 이름 (소요량_*.json · 계수_*.json).""" names = {} for path in list(ROOT.glob("소요량_*.json")) + list(ROOT.glob("계수_*.json")): data = json.loads(path.read_text(encoding="utf-8")) for t in data.get("표", []): names[t["키"]] = t.get("이름", "") return names def load_logic_names() -> dict[str, str]: names = {} for path in ROOT.glob("로직_*.json"): data = json.loads(path.read_text(encoding="utf-8")) for row in data.get("줄", []): names[row["키"]] = row.get("이름", "") return names def main() -> None: sys.stdout.reconfigure(encoding="utf-8") table_names = load_table_names() logic_names = load_logic_names() total_rows = 0 total_찾기 = 0 total_로직 = 0 rows_with_call = 0 multi_call_lines = 0 # 한 줄(자리표 하나)에 찾기·로직 합쳐 2번 이상 rows_with_dup_call = 0 # 같은 행 안에서 (종류,키,인자) 짝이 완전히 같은 호출이 2번 이상 dup_call_examples = [] name_collisions = {} # 표이름 -> {키, 키, ...} (다른 키가 같은 이름을 씀 — 별칭 지을 때 번호 필요) rows_with_collision = 0 for path in sorted(ROOT.glob("로직_*.json")): data = json.loads(path.read_text(encoding="utf-8")) for row in data.get("줄", []): total_rows += 1 row_calls = [] has_call = False for place, text in row_lines(row): calls = find_calls(text) if not calls: continue has_call = True if len(calls) >= 2: multi_call_lines += 1 for kind, key, args in calls: if kind == "찾기": total_찾기 += 1 else: total_로직 += 1 row_calls.append((kind, key, args, place)) if has_call: rows_with_call += 1 sig_count = {} for kind, key, args, place in row_calls: sig = (kind, key, args) sig_count[sig] = sig_count.get(sig, 0) + 1 dups = [s for s, c in sig_count.items() if c >= 2] if dups: rows_with_dup_call += 1 if len(dup_call_examples) < 8: dup_call_examples.append((row["키"], dups[0][0], dups[0][1], sig_count[dups[0]])) keys_in_row = {key for kind, key, args, place in row_calls if kind == "찾기"} names_seen = {} collided = False for key in keys_in_row: nm = table_names.get(key, key) names_seen.setdefault(nm, set()).add(key) for nm, keys in names_seen.items(): if len(keys) >= 2: collided = True name_collisions.setdefault(nm, set()).update(keys) if collided: rows_with_collision += 1 print(f"로직 전체 줄 수: {total_rows}") print(f"찾기() 호출 수: {total_찾기}") print(f"로직() 호출 수: {total_로직}") print(f"찾기·로직 호출이 1개 이상 있는 줄: {rows_with_call}") print(f"한 자리(호표 수량 1칸·중간 식 1줄 등)에 호출이 2번 이상 겹친 자리 수: {multi_call_lines}") print(f"같은 행 안에서 (표·인자)가 완전히 같은 호출이 2번 이상 반복되는 행 수: {rows_with_dup_call}") print(" 보기:") for key, kind_str, args, count in dup_call_examples: print(f" {key} — {kind_str}({args[:40]}...) 를 {count}번") print( f"표 이름이 겹쳐(다른 키가 같은 표이름) 별칭에 번호가 필요한 행 수: {rows_with_collision}" ) print(" 겹치는 표이름 보기:") for nm, keys in list(name_collisions.items())[:10]: print(f" '{nm}' <- {sorted(keys)}") if __name__ == "__main__": main()