Files
Aislo/resources/knowledge/original/_pipeline/fix_spacing.py
T
eomsangdonandClaude Opus 5 4cb9b15939 style: 저장소 전체 포맷터 일괄 적용 (prettier·biome·ruff)
파일마다 포맷 폭이 달라(≈80 대 100) 한 줄만 고쳐도 포맷터가 무관한 줄을 대량
재포맷했음. 사용자 지시로 전체를 한 번에 맞춤. 코드 동작 변경 없음 — 포맷만.

- 프론트엔드 `.ts/.css/.html` → 저장소 prettier (`.prettierrc`, printWidth 100)
- `B07_DesignDetail/openwebcad/**` → 자체 biome (tab 들여쓰기·single quote·lineWidth 100).
  `biome format` 만 사용 — `biome lint --write` 는 포맷 아닌 코드 수정까지 하므로 제외
- 파이썬 → `ruff format` (엔진 코드는 이미 정합, resources·scratch 스크립트 24개만 변경)

두 포맷터가 서로 되돌리지 않도록 `.prettierignore` 신규 — openwebcad 와 빌드·산출물
폴더를 prettier 대상에서 뺌. `.prettierrc` 에 `endOfLine: "auto"` 추가 — 기본값 `lf` 가
`core.autocrlf=true` 로 받은 CRLF 파일을 매번 전부 다시 써서 `--list-different` 가
실제 포맷 차이를 가리고 있었음.

검증: `tsc --noEmit` 통과(루트·openwebcad 둘 다), pytest 349 passed / 17 skipped /
0 failed, CAD vitest 87건 중 81 passed / 6 failed(laptop-sub 기준선과 동일, 회귀 없음).
포맷터 재실행 시 prettier·biome 모두 변경 0건.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-02 07:08:24 +09:00

153 lines
5.1 KiB
Python

# -*- coding: utf-8 -*-
"""공백 소실 별표·첨부 md의 띄어쓰기 복원.
PDF 표(정상)는 그대로 두고, 공백이 붙어버린 프로즈 줄만 HWP 원본의
띄어쓰기 버전으로 교체한다. 표 구조를 훼손하지 않는다.
- 별표: 같은 폴더 현행 XML의 별표서식파일링크(HWP)로 원본을 받아 hwp5 추출
- 첨부: 같은 폴더의 .hwp/.hwpx 원본을 사용
"""
import re, sys, time, urllib.request
import xml.etree.ElementTree as ET
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
import hwp5_text
BASEURL = "https://www.law.go.kr"
UA = {"User-Agent": "Mozilla/5.0"}
def nsp(s):
# 매칭 키: 공백·특수문자(사설글리프·불릿·문장부호) 제거 → 한글/영숫자만.
# HWP와 PDF 추출의 글자 차이(ㅇ·ㆍ·U+F09E 등)를 흡수한다.
return re.sub(r"[^가-힣0-9A-Za-z]", "", s)
def spaced_index(hwp_path):
"""HWP 전체를 하나의 띄어쓰기 문자열로 잇고, 무공백↔원문 위치 맵을 만든다.
반환: (spaced, pos) — spaced=공백 포함 전체, pos[i]=무공백 i번째 글자의 spaced 인덱스.
md 프로즈 줄이 HWP 문단을 병합/분할해도 무공백 시퀀스로 찾아 구간 복원 가능.
"""
try:
paras = hwp5_text.extract(str(hwp_path))
except Exception:
return "", []
chunks = [p.strip() for p in paras if p.strip()]
spaced = "\n".join(chunks)
pos = [i for i, ch in enumerate(spaced) if not ch.isspace()]
return spaced, pos
def respace(body, spaced, spaced_nsp, pos):
"""body(공백소실)의 무공백 시퀀스를 전역 인덱스에서 찾아 띄어쓰기째 반환."""
target = nsp(body)
if len(target) < 8:
return None
j = spaced_nsp.find(target)
if j < 0:
return None
s, e = pos[j], pos[j + len(target) - 1] + 1
seg = spaced[s:e]
# 원문 줄바꿈(문단경계)은 공백으로
return re.sub(r"\s+", " ", seg).strip()
def download(link, dest):
url = link if link.startswith("http") else BASEURL + link
for _ in range(3):
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=60) as r:
blob = r.read()
if blob and len(blob) > 500:
dest.write_bytes(blob)
return True
except Exception:
time.sleep(1.5)
return False
def byl_link_map(folder):
"""현행 XML → {별표 stem 접두: HWP링크}. md 파일명과 매칭용."""
xmls = sorted(folder.parent.glob("현행_*.xml"))
if not xmls:
xmls = sorted(folder.parent.glob("*.xml"))
if not xmls:
return {}
root = ET.parse(xmls[-1]).getroot()
byl = root.find("별표")
out = {}
if byl is None:
return out
for b in byl.findall("별표단위"):
num = (b.findtext("별표번호") or "0").lstrip("0") or "0"
g = (b.findtext("별표가지번호") or "").lstrip("0")
kind = (b.findtext("별표구분") or "별표").strip()
# 파일명 접두(별표/서식/별지)와 XML 구분을 맞춘다
pre = "별표" if kind == "별표" else ("별지" if kind == "별지" else "서식")
key = f"{pre}{num}{('의' + g) if g else ''}"
link = b.findtext("별표서식파일링크")
if link:
out[key] = link
return out
def restore_line(line, spaced, spaced_nsp, pos):
"""프로즈 줄이면 띄어쓰기 버전으로 교체. 표 행(|)은 건드리지 않는다."""
st = line.strip()
if (
not st
or st.startswith("|")
or st.startswith("#")
or st.startswith(">")
or st.startswith("![")
):
return line
m = re.match(r"^(\s*(?:[-*]\s+|[가-힣]\.\s*|\(\d+\)\s*|\d+\.\s*)?)(.*)$", line)
prefix, body = m.group(1), m.group(2)
if len(nsp(body)) < 8:
return line
if len(re.findall(r"[가-힣]{12,}", body)) == 0:
return line
sp = respace(body, spaced, spaced_nsp, pos)
if sp:
return prefix + sp
return line
def fix_file(md, hwp_dir_download=True):
text = md.read_text(encoding="utf-8")
folder = md.parent # .../별표 또는 .../첨부
stem = md.stem
# 소스 HWP 확보
hwp = None
local = list(folder.glob(stem + ".hwp")) + list(folder.glob(stem + ".hwpx"))
if local:
hwp = local[0]
elif folder.name == "별표":
key = stem.split("_")[0]
links = byl_link_map(folder)
link = links.get(key)
if link:
tmp = folder / (stem + ".hwp")
if tmp.exists() or download(link, tmp):
hwp = tmp
if not hwp:
return None
if hwp.suffix == ".hwpx":
return None # hwpx는 별도(hwpx_text)로 이미 처리
spaced, pos = spaced_index(hwp)
if not spaced:
return None
spaced_nsp = nsp(spaced)
lines = text.split("\n")
new = [restore_line(l, spaced, spaced_nsp, pos) for l in lines]
if new != lines:
md.write_text("\n".join(new), encoding="utf-8")
return sum(1 for a, b in zip(lines, new) if a != b)
return 0