# -*- 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