Files
Aislo/resources/knowledge/original/_pipeline/fix_spacing.py
T
eomsangdonandClaude Fable 5 81cd7e23c3 feat(knowledge): 도메인 지식저장소 메인 통합 + resources 그룹 체계 재편
knowledge (구 Aislo-law 독립 저장소 → resources/knowledge 이관, 저장소 폐지):
- 법령·행정규칙·표준시방서·교본 원문 + 기술문서 55건 + 실무 분석·종합비교
- 루트 지침 체계: README(지도)·00_운영지침·01_수집지침·02_분석지침·
  03_미결_및_확인사항(교본 충돌 리스트 포함)·04_참조_법령기준_목록
- 기술문서 55건 원문 전수 검증 완료 (사방 설계홍수량 법정 기준 등 반영)
- 정리: CAD·오피스 잔재 142건, 중복 zip 7건(413MB), 빈 폴더 30개 제거

resources 그룹 재편 (이름순 그룹핑):
- app_branding(구 prog_icon.jpg)·app_policies(구 legal)·
  data_global_contours(구 grobal_contours)·data_rainfall_idf_cache(구 wamis_contours)·
  template_2dDrawing(구 dwg_analysis/templete — 오타 교정, 상수·경로 동기화)
- dwg_analysis(분석 완료 1.8GB)·templates(빈 폴더)·templete_calc_cost.xlsx 삭제
- 참조 코드 5파일 경로 수정 + 프론트 재빌드 (구 경로 잔존 0)
- .gitignore: resources 추적 전환, national_contours.gpkg(22GB) 영구 제외
- .env: knowledge 수집용 API 정보 주석 통합 (KCSC·법령센터·조달청 제비율)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 19:14:32 +09:00

142 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