documents.py

파일 다운로드

"""제목과 문단을 보존하는 문서 파이프라인."""
import json
from pathlib import Path
from document_schema import validate_document, is_effective


def load_documents(path):
    records = json.loads(Path(path).read_text(encoding="utf-8"))
    seen = set()
    for record in records:
        validate_document(record)
        if record["document_id"] in seen:
            raise ValueError("duplicate document_id")
        seen.add(record["document_id"])
    return records


def sections(body):
    heading, paragraphs, buffer = "본문", [], []
    for line in body.splitlines() + [""]:
        if line.startswith("## "):
            if buffer:
                paragraphs.append(" ".join(buffer)); buffer = []
            if paragraphs:
                yield heading, paragraphs
            heading, paragraphs = line[3:].strip(), []
        elif line.strip():
            buffer.append(line.strip())
        elif buffer:
            paragraphs.append(" ".join(buffer)); buffer = []
    if paragraphs:
        yield heading, paragraphs


def chunk_documents(documents, max_chars=360):
    if max_chars < 1:
        raise ValueError("max_chars must be positive")
    chunks = []
    for document in documents:
        number = 0
        for heading, paragraphs in sections(document["body"]):
            prefix = f"{document['title']}\n{heading}\n"
            groups, current = [], ""
            for paragraph in paragraphs:
                trial = current + ("\n\n" if current else "") + paragraph
                if current and len(prefix + trial) > max_chars:
                    groups.append(current); current = paragraph
                else:
                    current = trial
            if current:
                groups.append(current)
            for group in groups:
                number += 1
                chunk = {key: value for key, value in document.items() if key != "body"}
                chunk.update(chunk_id=f"{document['document_id']}__c{number:02d}",
                             heading=heading, text=prefix + group)
                chunks.append(chunk)
    return chunks


def write_jsonl(path, records):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text("".join(json.dumps(row, ensure_ascii=False) + "\n" for row in records), encoding="utf-8")