chore: add value-facts plans, roadmap and law.go.kr download notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,93 @@
|
||||
---
|
||||
name: open-law-kr-download
|
||||
description: >-
|
||||
국가법령정보센터(open.law.go.kr / www.law.go.kr/DRF)에서 현행 법령(법률·대통령령·총리령·부령·대법원규칙),
|
||||
특정 조문·범위 조문(가지조문 자동 포함), 행정규칙(고시·예규·훈령), 대법원·하급심 판례·결정례, 별표·서식을
|
||||
공식 JSON 형식으로 검색·다운로드·검증하는 전용 스킬. 사용자가 법령·규칙·고시·예규·판례 원문을 JSON으로
|
||||
다운로드하거나 대조하라고 요청할 때 사용한다.
|
||||
---
|
||||
|
||||
# 국가법령정보센터 (open.law.go.kr) 원문 JSON 다운로드 스킬
|
||||
|
||||
## Overview
|
||||
|
||||
국가법령정보센터(`https://www.law.go.kr/DRF/lawSearch.do`, `lawService.do`) Open API를 통해 대한민국 현행 법령·시행령·시행규칙·대법원규칙(`target=law`), 행정규칙·고시·예규(`target=admrul`), 판례·결정례(`target=prec`), 별표·서식(`target=licbyl`) 원문을 공식 JSON 스키마 그대로 다운로드하고 무결성을 검증한다.
|
||||
|
||||
- **기본 API 인증키(`OC`)**: `jhogyu` (`OPEN_LAW_OC` 환경변수 또는 `--oc` 인자로 재정의 가능; 공용 `OC=test`는 차단됨)
|
||||
- **핵심 자동화 기능**:
|
||||
1. 법령명/행정규칙명 정확 일치(공백·괄호 부연 설명 정규화) 및 현행(`현행연혁구분 == "현행"`·최신 `시행일자`) 기준 최신 일련번호(`MST` / `ID`) 자동 조회
|
||||
2. 단일 조문(`§186`, `§388 2호`, `§13①2나·3호`), 가지조문(`§109의2`, `§2의4`), 복수 조문(`§356·§357·§358·§360`), 범위 조문(`§333~§341`, `§100~§103`, `§60~§66`) 표기 자동 파싱
|
||||
3. 범위 조문(`A~B`) 조회 시 해당 법령의 전체 조문 목차를 먼저 스캔하여 범위 내 유효한 **가지조문(`제N조의M`, 삭제 조문 제외)**을 누락 없이 자동 포함
|
||||
4. 복수 조문 조회 시 개별 `JO=NNNNMM`(6자리: 조번호 4자리 + 가지번호 2자리) 호출 결과를 `open.law.go.kr` 표준 스키마(`{"법령": {"법령키": ..., "기본정보": ..., "조문": {"조문단위": [...]}}}`)로 병합 및 `조문단위` 존재 여부 검증
|
||||
|
||||
## Dependencies
|
||||
|
||||
- Python 3 표준 라이브러리(`urllib`, `json`, `argparse`, `fcntl`, `re`, `pathlib`)만 사용하므로 외부 패키지 설치가 필요 없다.
|
||||
|
||||
## Quick Start
|
||||
|
||||
스크립트는 본 `SKILL.md`와 동일한 스킬 폴더 하위의 `./scripts/open_law_cli.py`에 위치한다(전역 설치 경로: `~/.codex/skills/open-law-kr-download/scripts/open_law_cli.py` 또는 워크스페이스 `.agents/skills/open-law-kr-download/scripts/open_law_cli.py`).
|
||||
|
||||
### 1. 단일 법령 조문·범위 또는 전문 다운로드 (`fetch`)
|
||||
|
||||
```bash
|
||||
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
|
||||
|
||||
# 특정 조문 또는 복수·범위 조문 다운로드 (가지조문 자동 포함)
|
||||
python3 "$SCRIPT_PATH" fetch \
|
||||
--target law \
|
||||
--name "민사소송법" \
|
||||
--articles "§333~§341" \
|
||||
--output "/path/to/민사소송법_제333조_제341조.json"
|
||||
|
||||
# 법령 현행 전문 다운로드 (--articles 생략 또는 "전문")
|
||||
python3 "$SCRIPT_PATH" fetch \
|
||||
--target law \
|
||||
--name "부동산등기법" \
|
||||
--output "/path/to/부동산등기법_현행.json"
|
||||
|
||||
# 행정규칙(고시·예규·훈령) 전문 다운로드 (target=admrul)
|
||||
python3 "$SCRIPT_PATH" fetch \
|
||||
--target admrul \
|
||||
--name "감정평가 실무기준" \
|
||||
--output "/path/to/감정평가_실무기준_전문.json"
|
||||
```
|
||||
|
||||
### 2. 리스트 일괄 다운로드 (`batch`)
|
||||
|
||||
사용자가 제시한 마크다운 불릿 리스트(`- 법령명 §조문` 형식)나 JSON 매니페스트 파일을 입력받아 지정 폴더에 일괄 저장한다.
|
||||
|
||||
```bash
|
||||
SCRIPT_PATH="${SKILL_DIR:-$HOME/.codex/skills/open-law-kr-download}/scripts/open_law_cli.py"
|
||||
|
||||
cat << 'EOF' > /tmp/law_list.txt
|
||||
- 지방세기본법 §2
|
||||
- 지방세법시행령 §109의2
|
||||
- 상속세 및 증여세법 §60~§66
|
||||
- `감정평가 실무기준(국토교통부 고시)` 전문
|
||||
EOF
|
||||
|
||||
python3 "$SCRIPT_PATH" batch \
|
||||
--input /tmp/law_list.txt \
|
||||
--out-dir "/path/to/output_dir"
|
||||
```
|
||||
|
||||
## Utility Scripts
|
||||
|
||||
스크립트 위치: [open_law_cli.py](./scripts/open_law_cli.py)
|
||||
|
||||
| 서브커맨드 | 주요 인자 | 설명 |
|
||||
|---|---|---|
|
||||
| `search` | `--target {law,admrul,prec,licbyl}` `--query <검색어>` `--limit <N>` `--output <파일>` | 검색 결과를 JSON 파일로 저장 |
|
||||
| `fetch` | `--target {law,admrul,prec,licbyl}` `--name <법령/규칙명>` `[--id <MST/ID>]` `[--articles <조문표기>]` `--output <파일>` | 단건 법령(전문/조문/범위)·고시·판례·별표 원문 JSON 다운로드 및 검증 |
|
||||
| `batch` | `--input <리스트파일.txt\|.json>` `--out-dir <저장폴더>` `[--report <요약.json>]` | 항목 리스트를 파싱하여 항목별 표준 파일명으로 일괄 다운로드 |
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
- [open_law_cli.py](./scripts/open_law_cli.py) 내부에서 프로세스 간 파일 락(`/tmp/open_law_kr_rate_limit.lock`)과 `time.monotonic()`을 사용하여 요청 간 최소 `0.25초` 간격을 강제하며, 일시적 네트워크/5xx 오류 시 지수 백오프(최대 3회)로 자동 재시도한다.
|
||||
|
||||
## Common Mistakes
|
||||
|
||||
1. **`OC=test` 사용 금지**: 국가법령정보센터에서 공용 `OC=test`는 `"사용자 정보 검증에 실패하였습니다"` 오류로 거부된다. 반드시 기본 설정된 `OC=jhogyu`(또는 유효한 발급 키)를 사용한다.
|
||||
2. **법령(`target=law`)과 행정규칙(`target=admrul`) 혼동**: 법률·대통령령·부령·대법원규칙은 `target=law`(`MST` 사용)이고, 각 부처 고시(예: `감정평가 실무기준`)·대법원 재판예규(예: `재민 91-1`, `재일 87-4`)·훈령은 `target=admrul`(`ID` 사용)이다.
|
||||
3. **범위 조문(`§A~§B`)에서 가지조문 누락**: 예컨대 `민사소송법 §333~§341`에는 `제335조의2`, `제339조의2`, `제339조의3`이 포함되어 있다. 단순 정수 루프(`333..341`)로만 호출하면 가지조문이 누락되므로 반드시 본 스크립트의 범위 해석기(`resolve_jo_codes_for_law`)를 사용한다.
|
||||
@@ -0,0 +1,4 @@
|
||||
interface:
|
||||
display_name: "국가법령정보센터(open.law.go.kr) 원문 다운로드"
|
||||
short_description: "현행 법령·규칙·고시·예규·판례 원문을 공식 JSON으로 검색·다운로드·검증"
|
||||
default_prompt: "국가법령정보센터(open.law.go.kr) Open API(OC=jhogyu)를 사용하여 요청된 법령·규칙·고시·판례의 현행 원문(특정 조문·가지조문·범위 조문 또는 전문)을 공식 JSON 형식으로 다운로드하고 검증하라."
|
||||
+556
@@ -0,0 +1,556 @@
|
||||
#!/usr/bin/env python3
|
||||
"""National Law Information Center (open.law.go.kr) DRF JSON Downloader CLI.
|
||||
|
||||
Supports:
|
||||
- target=law : Statutes, Presidential Decrees, Ministerial Ordinances, Supreme Court Rules
|
||||
(full law or article/range selection with automatic branch-article discovery)
|
||||
- target=admrul : Administrative Rules (Notices/고시, Directives/훈령, Established Rules/예규)
|
||||
- target=prec : Supreme Court & Lower Court Precedents / Decisions (판례·결정례)
|
||||
- target=licbyl : Statute Attached Tables & Forms (별표·서식)
|
||||
|
||||
Default OC authentication key: "jhogyu" (override via --oc or OPEN_LAW_OC env var).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
DEFAULT_OC = os.environ.get("OPEN_LAW_OC", "jhogyu")
|
||||
BASE_SEARCH_URL = "https://www.law.go.kr/DRF/lawSearch.do"
|
||||
BASE_SERVICE_URL = "https://www.law.go.kr/DRF/lawService.do"
|
||||
RATE_LIMIT_LOCK = Path(tempfile.gettempdir()) / "open_law_kr_rate_limit.lock"
|
||||
MIN_INTERVAL_SEC = 0.25
|
||||
|
||||
|
||||
class OpenLawError(RuntimeError):
|
||||
"""Raised when open.law.go.kr returns an error or invalid payload."""
|
||||
|
||||
|
||||
def _rate_limited_get(url: str, timeout: int = 25, max_retries: int = 3) -> bytes:
|
||||
"""Perform a cross-process rate-limited HTTP GET with retry on transient errors."""
|
||||
RATE_LIMIT_LOCK.touch(exist_ok=True)
|
||||
with RATE_LIMIT_LOCK.open("r+", encoding="utf-8") as lock_file:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX)
|
||||
try:
|
||||
lock_file.seek(0)
|
||||
content = lock_file.read().strip()
|
||||
last_ts = float(content) if content else 0.0
|
||||
elapsed = time.monotonic() - last_ts
|
||||
if 0.0 <= elapsed < MIN_INTERVAL_SEC:
|
||||
time.sleep(MIN_INTERVAL_SEC - elapsed)
|
||||
now_ts = time.monotonic()
|
||||
lock_file.seek(0)
|
||||
lock_file.truncate()
|
||||
lock_file.write(f"{now_ts:.6f}")
|
||||
lock_file.flush()
|
||||
finally:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
last_err: Exception | None = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
headers={
|
||||
"User-Agent": "Mozilla/5.0 (compatible; OpenLawKrSkill/1.0)",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
},
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
text_preview = raw[:500].decode("utf-8", errors="ignore")
|
||||
if "사용자 정보 검증에 실패하였습니다" in text_preview:
|
||||
raise OpenLawError(
|
||||
f"API key (OC) authentication failed on open.law.go.kr for URL: {url}"
|
||||
)
|
||||
return raw
|
||||
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc:
|
||||
last_err = exc
|
||||
if isinstance(exc, urllib.error.HTTPError) and 400 <= exc.code < 500 and exc.code != 429:
|
||||
body = exc.read().decode("utf-8", errors="ignore")[:400]
|
||||
raise OpenLawError(f"HTTP {exc.code} for {url}: {body}") from exc
|
||||
wait_sec = 0.8 * (2 ** (attempt - 1))
|
||||
print(
|
||||
f"[retry {attempt}/{max_retries}] {exc} -> waiting {wait_sec:.1f}s ({url})",
|
||||
file=sys.stderr,
|
||||
)
|
||||
time.sleep(wait_sec)
|
||||
raise OpenLawError(f"Failed to fetch {url} after {max_retries} attempts: {last_err}")
|
||||
|
||||
|
||||
def fetch_json(url: str) -> dict[str, Any]:
|
||||
raw = _rate_limited_get(url)
|
||||
text = raw.decode("utf-8", errors="replace").strip()
|
||||
try:
|
||||
data = json.loads(text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise OpenLawError(
|
||||
f"Non-JSON response from {url} (first 300 chars): {text[:300]}"
|
||||
) from exc
|
||||
if not isinstance(data, dict):
|
||||
raise OpenLawError(f"Unexpected JSON root type {type(data).__name__} from {url}")
|
||||
return data
|
||||
|
||||
|
||||
def normalize_law_name(name: str) -> str:
|
||||
"""Strip spaces and parenthetical notes for resilient matching."""
|
||||
cleaned = re.sub(r"\([^)]*\)", "", name)
|
||||
return re.sub(r"\s+", "", cleaned).strip()
|
||||
|
||||
|
||||
def format_jo_code(main_no: int, sub_no: int = 0) -> str:
|
||||
"""Format article number + branch number into 6-digit JO code (NNNNMM)."""
|
||||
return f"{main_no:04d}{sub_no:02d}"
|
||||
|
||||
|
||||
def parse_article_token(token: str) -> tuple[int, int]:
|
||||
"""Parse a single article token like '§109의2', '제2조의4', '§263①', '§388 2호', '§13①2나' into (main, sub)."""
|
||||
m = re.search(r"(?:제\s*)?(\d+)\s*(?:조)?(?:\s*의\s*(\d+))?", token)
|
||||
if not m:
|
||||
raise ValueError(f"Cannot parse article number from token: {token!r}")
|
||||
main_no = int(m.group(1))
|
||||
sub_no = int(m.group(2)) if m.group(2) else 0
|
||||
return main_no, sub_no
|
||||
|
||||
|
||||
def parse_article_spec(spec: str) -> list[dict[str, Any]]:
|
||||
"""Parse an article specification string into single or range descriptors.
|
||||
|
||||
Examples:
|
||||
"§186" -> [{"type": "single", "main": 186, "sub": 0}]
|
||||
"§356·§357·§358·§360" -> 4 singles
|
||||
"§333~§341" -> [{"type": "range", "start": 333, "end": 341}]
|
||||
"§3·§10·§16~§18" -> 2 singles + 1 range
|
||||
"§13①2나·3호" -> [{"type": "single", "main": 13, "sub": 0}]
|
||||
"""
|
||||
spec = spec.strip()
|
||||
if not spec or spec in {"전문", "전체", "ALL", "all"}:
|
||||
return []
|
||||
|
||||
parts = [p.strip() for p in re.split(r"[·,]+", spec) if p.strip()]
|
||||
descriptors: list[dict[str, Any]] = []
|
||||
for part in parts:
|
||||
# Check if part is a mere sub-item continuation like "3호" or "2호" without §/제
|
||||
if re.fullmatch(r"\d+\s*(?:호|목|항)", part) and descriptors:
|
||||
continue
|
||||
# Check range pattern: e.g. §333~§341, 60~66, 제16조~제18조
|
||||
range_match = re.search(
|
||||
r"(?:§|제)?\s*(\d+)\s*(?:조)?\s*[~\-∼]\s*(?:§|제)?\s*(\d+)\s*(?:조)?",
|
||||
part,
|
||||
)
|
||||
if range_match:
|
||||
start_no = int(range_match.group(1))
|
||||
end_no = int(range_match.group(2))
|
||||
descriptors.append({"type": "range", "start": start_no, "end": end_no})
|
||||
else:
|
||||
main_no, sub_no = parse_article_token(part)
|
||||
descriptors.append({"type": "single", "main": main_no, "sub": sub_no})
|
||||
return descriptors
|
||||
|
||||
|
||||
def search_law(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
|
||||
"""Find the current law entry matching `name` via lawSearch.do?target=law."""
|
||||
# Strip parenthetical qualification like "(국토교통부령)" for query if needed
|
||||
base_query = re.sub(r"\([^)]*\)$", "", name).strip()
|
||||
q = urllib.parse.quote(base_query)
|
||||
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON& display=100&query={q}".replace(
|
||||
"& display=", "&display="
|
||||
)
|
||||
data = fetch_json(url)
|
||||
laws = data.get("LawSearch", {}).get("law", [])
|
||||
if isinstance(laws, dict):
|
||||
laws = [laws]
|
||||
if not laws:
|
||||
raise OpenLawError(f"No law found for query: {base_query!r}")
|
||||
|
||||
norm_target = normalize_law_name(base_query)
|
||||
exact = [
|
||||
x
|
||||
for x in laws
|
||||
if normalize_law_name(str(x.get("법령명한글", ""))) == norm_target
|
||||
]
|
||||
candidates = exact if exact else laws
|
||||
# Prefer 현행연혁구분 == "현행", then latest 시행일자
|
||||
candidates.sort(
|
||||
key=lambda x: (
|
||||
1 if x.get("현행연혁구분") == "현행" else 0,
|
||||
str(x.get("시행일자", "")),
|
||||
str(x.get("공포일자", "")),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def search_admrul(name: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
|
||||
"""Find the current administrative rule (고시·예규·훈령) matching `name`."""
|
||||
base_query = re.sub(r"\((?:국토교통부|법무부|국세청|행정안전부|기획재정부|금융위원회)?\s*(?:고시|예규|훈령|지침)\)$", "", name).strip()
|
||||
q = urllib.parse.quote(base_query)
|
||||
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&display=100&query={q}"
|
||||
data = fetch_json(url)
|
||||
items = data.get("AdmRulSearch", {}).get("admrul", [])
|
||||
if isinstance(items, dict):
|
||||
items = [items]
|
||||
if not items:
|
||||
raise OpenLawError(f"No administrative rule (admrul) found for query: {base_query!r}")
|
||||
|
||||
norm_target = normalize_law_name(base_query)
|
||||
exact = [
|
||||
x
|
||||
for x in items
|
||||
if normalize_law_name(str(x.get("행정규칙명", ""))) == norm_target
|
||||
]
|
||||
candidates = exact if exact else items
|
||||
candidates.sort(
|
||||
key=lambda x: (
|
||||
1 if x.get("현행연혁구분") == "현행" else 0,
|
||||
str(x.get("시행일자", "")),
|
||||
str(x.get("발령일자", "")),
|
||||
),
|
||||
reverse=True,
|
||||
)
|
||||
return candidates[0]
|
||||
|
||||
|
||||
def search_prec(query: str, oc: str = DEFAULT_OC) -> dict[str, Any]:
|
||||
"""Find a precedent/decision (판례·결정례) by case number or query."""
|
||||
q = urllib.parse.quote(query.strip())
|
||||
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&display=50&query={q}"
|
||||
data = fetch_json(url)
|
||||
items = data.get("PrecSearch", {}).get("prec", [])
|
||||
if isinstance(items, dict):
|
||||
items = [items]
|
||||
if not items:
|
||||
raise OpenLawError(f"No precedent (prec) found for query: {query!r}")
|
||||
for item in items:
|
||||
if str(item.get("사건번호", "")).strip() == query.strip():
|
||||
return item
|
||||
return items[0]
|
||||
|
||||
|
||||
def resolve_jo_codes_for_law(
|
||||
mst: str,
|
||||
descriptors: list[dict[str, Any]],
|
||||
oc: str = DEFAULT_OC,
|
||||
include_deleted: bool = False,
|
||||
) -> list[str]:
|
||||
"""Resolve descriptors (including ranges with branch articles) into 6-digit JO codes."""
|
||||
has_range = any(d["type"] == "range" for d in descriptors)
|
||||
full_units: list[dict[str, Any]] = []
|
||||
if has_range:
|
||||
full_url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
|
||||
full_data = fetch_json(full_url)
|
||||
raw_units = full_data.get("법령", {}).get("조문", {}).get("조문단위", [])
|
||||
if isinstance(raw_units, dict):
|
||||
raw_units = [raw_units]
|
||||
full_units = raw_units
|
||||
|
||||
jo_codes: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for desc in descriptors:
|
||||
if desc["type"] == "single":
|
||||
code = format_jo_code(desc["main"], desc["sub"])
|
||||
if code not in seen:
|
||||
seen.add(code)
|
||||
jo_codes.append(code)
|
||||
elif desc["type"] == "range":
|
||||
start_no, end_no = desc["start"], desc["end"]
|
||||
for u in full_units:
|
||||
if u.get("조문여부") != "조문":
|
||||
continue
|
||||
jnum = int(u.get("조문번호", "0"))
|
||||
if start_no <= jnum <= end_no:
|
||||
content_str = str(u.get("조문내용", "")).strip()
|
||||
if not include_deleted and u.get("조문제목") is None and "삭제" in content_str:
|
||||
continue
|
||||
sub_str = str(u.get("조문가지번호", "")).strip()
|
||||
sub_no = int(sub_str) if sub_str.isdigit() else 0
|
||||
code = format_jo_code(jnum, sub_no)
|
||||
if code not in seen:
|
||||
seen.add(code)
|
||||
jo_codes.append(code)
|
||||
return jo_codes
|
||||
|
||||
|
||||
def fetch_law_json(
|
||||
law_name_or_mst: str,
|
||||
articles_spec: str | None = None,
|
||||
oc: str = DEFAULT_OC,
|
||||
include_deleted: bool = False,
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""Fetch full law JSON or specific article(s) JSON from open.law.go.kr.
|
||||
|
||||
Returns (json_payload, meta_info).
|
||||
"""
|
||||
if law_name_or_mst.isdigit():
|
||||
mst = law_name_or_mst
|
||||
law_meta = {"법령일련번호": mst}
|
||||
else:
|
||||
law_meta = search_law(law_name_or_mst, oc=oc)
|
||||
mst = str(law_meta["법령일련번호"])
|
||||
|
||||
descriptors = parse_article_spec(articles_spec or "")
|
||||
if not descriptors:
|
||||
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=law&type=JSON&MST={urllib.parse.quote(mst)}"
|
||||
data = fetch_json(url)
|
||||
return data, {"mst": mst, "jo_codes": [], "law_meta": law_meta}
|
||||
|
||||
jo_codes = resolve_jo_codes_for_law(
|
||||
mst=mst,
|
||||
descriptors=descriptors,
|
||||
oc=oc,
|
||||
include_deleted=include_deleted,
|
||||
)
|
||||
if len(jo_codes) == 1:
|
||||
url = (
|
||||
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
|
||||
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo_codes[0]}"
|
||||
)
|
||||
data = fetch_json(url)
|
||||
if "조문" not in data.get("법령", {}) or "조문단위" not in data["법령"]["조문"]:
|
||||
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo_codes[0]}")
|
||||
return data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
|
||||
|
||||
combined_units: list[Any] = []
|
||||
base_data: dict[str, Any] | None = None
|
||||
for jo in jo_codes:
|
||||
url = (
|
||||
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}"
|
||||
f"&target=law&type=JSON&MST={urllib.parse.quote(mst)}&JO={jo}"
|
||||
)
|
||||
d = fetch_json(url)
|
||||
if "조문" not in d.get("법령", {}) or "조문단위" not in d["법령"]["조문"]:
|
||||
raise OpenLawError(f"Missing 조문단위 for MST={mst} JO={jo}")
|
||||
if base_data is None:
|
||||
base_data = d
|
||||
unit = d["법령"]["조문"]["조문단위"]
|
||||
if isinstance(unit, list):
|
||||
combined_units.extend(unit)
|
||||
else:
|
||||
combined_units.append(unit)
|
||||
|
||||
assert base_data is not None
|
||||
base_data["법령"]["조문"]["조문단위"] = combined_units
|
||||
return base_data, {"mst": mst, "jo_codes": jo_codes, "law_meta": law_meta}
|
||||
|
||||
|
||||
def fetch_admrul_json(name_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
if name_or_id.isdigit():
|
||||
adm_id = name_or_id
|
||||
meta = {"행정규칙일련번호": adm_id}
|
||||
else:
|
||||
meta = search_admrul(name_or_id, oc=oc)
|
||||
adm_id = str(meta["행정규칙일련번호"])
|
||||
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=admrul&type=JSON&ID={urllib.parse.quote(adm_id)}"
|
||||
data = fetch_json(url)
|
||||
return data, {"id": adm_id, "admrul_meta": meta}
|
||||
|
||||
|
||||
def fetch_prec_json(query_or_id: str, oc: str = DEFAULT_OC) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
if query_or_id.isdigit():
|
||||
prec_id = query_or_id
|
||||
meta = {"판례일련번호": prec_id}
|
||||
else:
|
||||
meta = search_prec(query_or_id, oc=oc)
|
||||
prec_id = str(meta["판례일련번호"])
|
||||
url = f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(oc)}&target=prec&type=JSON&ID={urllib.parse.quote(prec_id)}"
|
||||
data = fetch_json(url)
|
||||
return data, {"id": prec_id, "prec_meta": meta}
|
||||
|
||||
|
||||
def build_default_filename(law_name: str, articles_spec: str | None, target: str = "law") -> str:
|
||||
"""Build a clean, deterministic Korean JSON filename from law name and article spec."""
|
||||
clean_law = re.sub(r"\([^)]*\)$", "", law_name).strip()
|
||||
clean_law = re.sub(r"\s+", "_", clean_law)
|
||||
if target == "admrul" or not articles_spec or articles_spec.strip() in {"전문", "전체", "ALL", "all"}:
|
||||
suffix = "전문" if (articles_spec and "전문" in articles_spec) else "현행"
|
||||
return f"{clean_law}_{suffix}.json"
|
||||
|
||||
circle_map = {
|
||||
"①": "제1항", "②": "제2항", "③": "제3항", "④": "제4항", "⑤": "제5항",
|
||||
"⑥": "제6항", "⑦": "제7항", "⑧": "제8항", "⑨": "제9항", "⑩": "제10항",
|
||||
}
|
||||
s = articles_spec.strip()
|
||||
for c, rep in circle_map.items():
|
||||
s = s.replace(c, rep)
|
||||
|
||||
# Convert §N(의M)? to 제N조(의M)?
|
||||
s = re.sub(r"§\s*(\d+)(?:의(\d+))?", lambda m: f"제{m.group(1)}조" + (f"의{m.group(2)}" if m.group(2) else ""), s)
|
||||
s = re.sub(r"[·,~∼\s]+", "_", s).strip("_")
|
||||
return f"{clean_law}_{s}.json"
|
||||
|
||||
|
||||
def cmd_search(args: argparse.Namespace) -> None:
|
||||
q = urllib.parse.quote(args.query)
|
||||
url = f"{BASE_SEARCH_URL}?OC={urllib.parse.quote(args.oc)}&target={urllib.parse.quote(args.target)}&type=JSON&display={args.limit}&query={q}"
|
||||
data = fetch_json(url)
|
||||
out_path = Path(args.output)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Success! Search results written to: {out_path} ({out_path.stat().st_size} bytes)")
|
||||
|
||||
|
||||
def cmd_fetch(args: argparse.Namespace) -> None:
|
||||
if args.target == "law":
|
||||
data, meta = fetch_law_json(
|
||||
law_name_or_mst=args.name or args.id,
|
||||
articles_spec=args.articles,
|
||||
oc=args.oc,
|
||||
include_deleted=args.include_deleted,
|
||||
)
|
||||
elif args.target == "admrul":
|
||||
data, meta = fetch_admrul_json(args.name or args.id, oc=args.oc)
|
||||
elif args.target == "prec":
|
||||
data, meta = fetch_prec_json(args.name or args.id, oc=args.oc)
|
||||
else:
|
||||
url = (
|
||||
f"{BASE_SERVICE_URL}?OC={urllib.parse.quote(args.oc)}"
|
||||
f"&target={urllib.parse.quote(args.target)}&type=JSON&ID={urllib.parse.quote(args.id or args.name)}"
|
||||
)
|
||||
data = fetch_json(url)
|
||||
meta = {"id": args.id or args.name}
|
||||
|
||||
out_path = Path(args.output)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(
|
||||
f"Success! Saved {out_path} ({out_path.stat().st_size} bytes) | meta={json.dumps(meta, ensure_ascii=False)}"
|
||||
)
|
||||
|
||||
|
||||
def parse_batch_line(line: str) -> dict[str, Any] | None:
|
||||
"""Parse a bullet line such as '- `감정평가 및 감정평가사에 관한 법률` §3·§6' or '- 지방세법시행령 §109의2'."""
|
||||
s = line.strip()
|
||||
s = re.sub(r"^[-*•]\s*", "", s).strip()
|
||||
if not s:
|
||||
return None
|
||||
|
||||
# Check if backtick-quoted law name: `법령명` 스펙
|
||||
m_bt = re.match(r"^`([^`]+)`\s*(.*)$", s)
|
||||
if m_bt:
|
||||
raw_name, rest = m_bt.group(1).strip(), m_bt.group(2).strip()
|
||||
else:
|
||||
# Split before first § or '전문'
|
||||
m_split = re.match(r"^(.+?)\s+(§.+|전문|전체)$", s)
|
||||
if m_split:
|
||||
raw_name, rest = m_split.group(1).strip(), m_split.group(2).strip()
|
||||
else:
|
||||
raw_name, rest = s, ""
|
||||
|
||||
# Common spacing normalizations for decree names (e.g. 지방세법시행령 -> 지방세법 시행령)
|
||||
if raw_name.endswith("시행령") and not raw_name.endswith(" 시행령"):
|
||||
raw_name = raw_name[:-3] + " 시행령"
|
||||
if raw_name.endswith("시행규칙") and not raw_name.endswith(" 시행규칙"):
|
||||
raw_name = raw_name[:-4] + " 시행규칙"
|
||||
|
||||
is_admrul = bool(re.search(r"\((?:[^)]*고시|[^)]*예규|[^)]*훈령)\)", raw_name)) or "실무기준" in raw_name
|
||||
target = "admrul" if is_admrul else "law"
|
||||
filename = build_default_filename(raw_name, rest, target=target)
|
||||
return {
|
||||
"target": target,
|
||||
"name": raw_name,
|
||||
"articles": rest if target == "law" else None,
|
||||
"filename": filename,
|
||||
}
|
||||
|
||||
|
||||
def cmd_batch(args: argparse.Namespace) -> None:
|
||||
spec_path = Path(args.input)
|
||||
raw_text = spec_path.read_text(encoding="utf-8").strip()
|
||||
if raw_text.startswith("[") or raw_text.startswith("{"):
|
||||
parsed = json.loads(raw_text)
|
||||
items = parsed["items"] if isinstance(parsed, dict) and "items" in parsed else parsed
|
||||
else:
|
||||
items = [x for line in raw_text.splitlines() if (x := parse_batch_line(line)) is not None]
|
||||
|
||||
out_dir = Path(args.out_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
summary: list[dict[str, Any]] = []
|
||||
|
||||
for item in items:
|
||||
target = item.get("target", "law")
|
||||
name = item["name"]
|
||||
articles = item.get("articles")
|
||||
filename = item.get("filename") or build_default_filename(name, articles, target=target)
|
||||
if target == "law":
|
||||
data, meta = fetch_law_json(name, articles_spec=articles, oc=args.oc)
|
||||
elif target == "admrul":
|
||||
data, meta = fetch_admrul_json(name, oc=args.oc)
|
||||
elif target == "prec":
|
||||
data, meta = fetch_prec_json(name, oc=args.oc)
|
||||
else:
|
||||
raise OpenLawError(f"Unsupported batch target: {target}")
|
||||
|
||||
dest = out_dir / filename
|
||||
dest.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
entry = {
|
||||
"name": name,
|
||||
"articles": articles,
|
||||
"target": target,
|
||||
"filename": str(dest),
|
||||
"bytes": dest.stat().st_size,
|
||||
"meta": meta,
|
||||
}
|
||||
summary.append(entry)
|
||||
print(f"Saved: {filename} ({dest.stat().st_size} bytes)")
|
||||
|
||||
if args.report:
|
||||
report_path = Path(args.report)
|
||||
report_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
report_path.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Batch report written to: {report_path}")
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
p = argparse.ArgumentParser(description="open.law.go.kr DRF JSON Downloader CLI")
|
||||
p.add_argument("--oc", default=DEFAULT_OC, help="API key (OC), defaults to OPEN_LAW_OC or 'jhogyu'")
|
||||
sub = p.add_subparsers(dest="subcommand", required=True)
|
||||
|
||||
sp_search = sub.add_parser("search", help="Search law / admrul / prec / licbyl")
|
||||
sp_search.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
|
||||
sp_search.add_argument("--query", required=True, help="Search query")
|
||||
sp_search.add_argument("--limit", type=int, required=True, help="Max results to retrieve")
|
||||
sp_search.add_argument("--output", required=True, help="Output JSON file path")
|
||||
sp_search.set_defaults(func=cmd_search)
|
||||
|
||||
sp_fetch = sub.add_parser("fetch", help="Fetch a single law (full or articles), admrul, prec, or licbyl")
|
||||
sp_fetch.add_argument("--target", default="law", choices=["law", "admrul", "prec", "licbyl"])
|
||||
sp_fetch.add_argument("--name", help="Exact Korean name of law / admrul / case number")
|
||||
sp_fetch.add_argument("--id", help="Explicit MST or ID if known")
|
||||
sp_fetch.add_argument("--articles", help="Article spec for target=law (e.g. '§3·§10·§16~§18', '§109의2')")
|
||||
sp_fetch.add_argument("--include-deleted", action="store_true", help="Include deleted branch articles in ranges")
|
||||
sp_fetch.add_argument("--output", required=True, help="Output JSON file path")
|
||||
sp_fetch.set_defaults(func=cmd_fetch)
|
||||
|
||||
sp_batch = sub.add_parser("batch", help="Batch download a list of items (markdown bullet list or JSON)")
|
||||
sp_batch.add_argument("--input", required=True, help="Path to text/markdown list or JSON manifest")
|
||||
sp_batch.add_argument("--out-dir", required=True, help="Destination directory for JSON files")
|
||||
sp_batch.add_argument("--report", help="Optional path to write batch download summary JSON")
|
||||
sp_batch.set_defaults(func=cmd_batch)
|
||||
|
||||
return p
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = build_parser()
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
args.func(args)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user