3.5만 에피소드 기반 표절·AI·판례 분석 파이프라인 구현
This commit is contained in:
1 parent
4f6898d0b2
commit
ce50e89089
32 files changed
+4505
-69
No files matched your search
File diff suppressed because it is too large.
Load diff
+242
-31
@@ -25,6 +25,7 @@ from app.api.schemas import (
|
||||
DocumentMetadata,
|
||||
InfringementTag,
|
||||
InfringementType,
|
||||
LegalRiskSignal,
|
||||
MatchResult,
|
||||
PartialPlagiarismSignal,
|
||||
ReviewSummary,
|
||||
@@ -32,10 +33,15 @@ from app.api.schemas import (
|
||||
)
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.engine.autobiography_filter import preprocess_for_autobiography
|
||||
from app.engine.ai_detector import get_ai_detector
|
||||
from app.engine.clustering import ClusterIndex
|
||||
from app.engine.corpus import load_corpus
|
||||
from app.engine.extractor import Extractor, get_extractor
|
||||
from app.engine.lsh_filter import LshIndex
|
||||
from app.engine.legal_risk import LegalRiskEngine, load_precedents
|
||||
from app.engine.persistent_index import PersistentCorpusIndex, PersistentHit
|
||||
from app.engine.provenance import DocumentRecord, SegmentRecord, stable_id
|
||||
from app.engine.source_extraction import chunk_with_offsets
|
||||
from app.engine.similarity import (
|
||||
DualSimilarityIndex,
|
||||
SimilarityHit,
|
||||
@@ -52,6 +58,34 @@ class PlagiarismDetector:
|
||||
self.settings = settings or get_settings()
|
||||
self._extractor: Extractor = extractor or get_extractor(self.settings)
|
||||
self.taxonomy: Taxonomy | None = load_taxonomy(self.settings.taxonomy_path)
|
||||
self._legal_engine = LegalRiskEngine(load_precedents(self.settings.precedent_path))
|
||||
self._ai_detector = get_ai_detector(
|
||||
self.settings.ai_detector_model_path,
|
||||
allow_heuristic=self.settings.ai_detector_allow_heuristic,
|
||||
use_pos=self.settings.ai_detector_use_pos,
|
||||
)
|
||||
self._persistent: PersistentCorpusIndex | None = None
|
||||
|
||||
if self.settings.use_persistent_index:
|
||||
candidate = PersistentCorpusIndex(
|
||||
self.settings.corpus_db, self.settings.persistent_index_path,
|
||||
)
|
||||
if candidate.ready:
|
||||
self._persistent = candidate.load()
|
||||
self._corpus = []
|
||||
self._corpus_preprocessed_texts = []
|
||||
self._corpus_elements = []
|
||||
self._corpus_lemmas = []
|
||||
self._index = None
|
||||
self._lsh = None
|
||||
self._cluster = None
|
||||
self._docs_by_id = {}
|
||||
logger.info("Loaded persistent index: %d segments", self._persistent.size)
|
||||
return
|
||||
logger.warning(
|
||||
"USE_PERSISTENT_INDEX=true but index is absent; falling back to text corpus: %s",
|
||||
self.settings.persistent_index_path,
|
||||
)
|
||||
|
||||
self._corpus = load_corpus(self.settings.corpus_path)
|
||||
|
||||
@@ -106,17 +140,47 @@ class PlagiarismDetector:
|
||||
|
||||
@property
|
||||
def corpus_size(self) -> int:
|
||||
return self._persistent.size if self._persistent else len(self._corpus)
|
||||
|
||||
@property
|
||||
def corpus_document_count(self) -> int:
|
||||
if self._persistent:
|
||||
return self._persistent.document_count
|
||||
return len(self._corpus)
|
||||
|
||||
@property
|
||||
def index_backend(self) -> str:
|
||||
return "persistent-hashing-char-3-4" if self._persistent else "legacy-in-memory"
|
||||
|
||||
@property
|
||||
def precedent_count(self) -> int:
|
||||
return len(self._legal_engine.precedents)
|
||||
|
||||
@property
|
||||
def ai_model_ready(self) -> bool:
|
||||
return self._ai_detector.mode == "trained"
|
||||
|
||||
@property
|
||||
def uses_persistent_index(self) -> bool:
|
||||
return self._persistent is not None
|
||||
|
||||
def list_persistent_documents(self) -> list[dict]:
|
||||
return self._persistent.store.list_documents() if self._persistent else []
|
||||
|
||||
def detect(
|
||||
self,
|
||||
doc_id: str,
|
||||
text: str,
|
||||
metadata: DocumentMetadata | None = None,
|
||||
options: DetectOptions | None = None,
|
||||
include_ai_segments: bool = True,
|
||||
) -> DetectResponse:
|
||||
opts = options or DetectOptions()
|
||||
threshold = opts.threshold if opts.threshold is not None else self.settings.similarity_threshold
|
||||
default_threshold = (
|
||||
self.settings.persistent_similarity_threshold
|
||||
if self._persistent else self.settings.similarity_threshold
|
||||
)
|
||||
threshold = opts.threshold if opts.threshold is not None else default_threshold
|
||||
|
||||
# 요청 단위 자서전 모드 override
|
||||
autobio_mode = (
|
||||
@@ -136,37 +200,101 @@ class PlagiarismDetector:
|
||||
# 요소 추출 (원본 텍스트 기준 — 사용자 검토용)
|
||||
elements = self._extractor.extract(text)
|
||||
|
||||
# 1차 LSH 필터 (옵션)
|
||||
# 영속 CPU 인덱스: 전량 행렬곱으로 후보를 구하고 상위 후보만 증거 비교한다.
|
||||
persistent_hits: list[PersistentHit] = []
|
||||
if self._persistent:
|
||||
persistent_query_lemmas = extract_lemmas(text)
|
||||
persistent_hits = self._persistent.query(
|
||||
text,
|
||||
top_k=max(opts.top_k, self.settings.persistent_rerank_top_k),
|
||||
)
|
||||
hits = [
|
||||
self._persistent_to_similarity_hit(h, persistent_query_lemmas, elements)
|
||||
for h in persistent_hits
|
||||
]
|
||||
hits.sort(key=lambda h: h.score, reverse=True)
|
||||
candidates_count = len(hits)
|
||||
lsh_jaccards: dict[str, float] = {}
|
||||
else:
|
||||
hits = []
|
||||
candidates_count = None
|
||||
lsh_jaccards = {}
|
||||
|
||||
# 1차 LSH 필터 (레거시 옵션)
|
||||
candidate_ids: set[str] | None = None
|
||||
candidates_count: int | None = None
|
||||
lsh_jaccards: dict[str, float] = {}
|
||||
if self._lsh:
|
||||
if not self._persistent and self._lsh:
|
||||
cands = self._lsh.query(query_text, top_k=self.settings.lsh_top_k)
|
||||
candidate_ids = {c.doc_id for c in cands}
|
||||
candidates_count = len(cands)
|
||||
lsh_jaccards = {c.doc_id: c.jaccard for c in cands}
|
||||
|
||||
# 정밀 비교 (LSH 후보가 있으면 그것만, 없으면 풀스캔)
|
||||
hits = self._index.query(query_text, elements, top_k=opts.top_k)
|
||||
if candidate_ids is not None:
|
||||
hits = [h for h in hits if h.doc_id in candidate_ids]
|
||||
if not self._persistent:
|
||||
hits = self._index.query(query_text, elements, top_k=opts.top_k)
|
||||
if candidate_ids is not None:
|
||||
hits = [h for h in hits if h.doc_id in candidate_ids]
|
||||
|
||||
# 군집화 부분 표절 신호용 query lemma (전처리 텍스트 기준)
|
||||
query_lemmas = extract_lemmas(query_text) if self._cluster else None
|
||||
|
||||
matches = [
|
||||
self._to_match(
|
||||
persistent_by_id = {h.segment_id: h for h in persistent_hits}
|
||||
matches = []
|
||||
for h in hits:
|
||||
provenance_hit = persistent_by_id.get(h.doc_id)
|
||||
exact_partial_match = bool(
|
||||
provenance_hit and (
|
||||
provenance_hit.longest_span >= self.settings.persistent_min_exact_span
|
||||
or provenance_hit.coverage >= self.settings.persistent_min_coverage
|
||||
)
|
||||
)
|
||||
if (h.score < threshold and not exact_partial_match) or len(matches) >= opts.top_k:
|
||||
continue
|
||||
match = self._to_match(
|
||||
h, opts.return_evidence, lsh_jaccards.get(h.doc_id),
|
||||
self._partial_signal(h.doc_id, elements, query_lemmas),
|
||||
)
|
||||
for h in hits if h.score >= threshold
|
||||
]
|
||||
if provenance_hit:
|
||||
match = self._add_provenance(match, provenance_hit)
|
||||
matches.append(match)
|
||||
confidence = matches[0].similarity if matches else (hits[0].score if hits else 0.0)
|
||||
is_infringement = bool(matches)
|
||||
is_infringement = bool(matches) # 후방호환 필드. 법적 확정이 아니라 임계 초과 매칭.
|
||||
ccl_basis = self._build_ccl_basis(matches) if is_infringement else None
|
||||
|
||||
# 저작권 탭 UI 매핑 (나누구 앱). 독창성=100-유사도, AI 의심도는 현재 스텁.
|
||||
ai_signal = _dummy_ai_generation_signal(text)
|
||||
top_coverage = max((m.matched_coverage for m in matches), default=0.0)
|
||||
top_longest = max((m.longest_span for m in matches), default=0)
|
||||
legal_tags = [t.tag for m in matches for t in m.tags]
|
||||
legal = self._legal_engine.assess(
|
||||
max_similarity=matches[0].similarity if matches else 0.0,
|
||||
coverage=top_coverage,
|
||||
longest_span=top_longest,
|
||||
legal_tags=legal_tags,
|
||||
work_type="literary",
|
||||
)
|
||||
|
||||
# AI 탐지는 전처리 전 raw text에서만 실행한다.
|
||||
ai_result = self._ai_detector.detect(text, with_segments=include_ai_segments)
|
||||
ai_signal = AiGenerationSignal(
|
||||
suspicion_level=ai_result.suspicion_level or "unknown",
|
||||
score=ai_result.score,
|
||||
available=ai_result.available,
|
||||
provenance=ai_result.provenance,
|
||||
is_stub=ai_result.is_stub,
|
||||
model_version=ai_result.model_version,
|
||||
feature_set_version=ai_result.feature_set_version,
|
||||
pos_available=ai_result.pos_available,
|
||||
warnings=ai_result.warnings,
|
||||
segments=[{
|
||||
"index": s.index, "start": s.start, "end": s.end,
|
||||
"char_count": s.char_count, "score": s.score,
|
||||
"suspicion_level": s.suspicion_level, "scored": s.scored,
|
||||
"note": s.note,
|
||||
} for s in ai_result.segments],
|
||||
top_contributions=[
|
||||
{"feature": name, "contribution": round(value, 4)}
|
||||
for name, value in ai_result.top_contributions
|
||||
],
|
||||
note=ai_result.note,
|
||||
)
|
||||
sim_pct = _calibrate_similarity(confidence, threshold)
|
||||
review = ReviewSummary(
|
||||
originality_percent=100 - sim_pct,
|
||||
@@ -186,6 +314,21 @@ class PlagiarismDetector:
|
||||
ccl_basis=ccl_basis,
|
||||
review_summary=review,
|
||||
ai_generation=ai_signal,
|
||||
has_similarity_match=bool(matches),
|
||||
corpus_scope_note=(
|
||||
f"현재 등록된 {self.corpus_document_count}개 원천 문서의 "
|
||||
f"{self.corpus_size}개 검색 세그먼트만 대조했습니다. 미매칭은 비침해 확정이 아닙니다."
|
||||
),
|
||||
legal_risk=LegalRiskSignal(
|
||||
status=legal.status,
|
||||
risk_level=legal.risk_level,
|
||||
similarity_evidence=legal.similarity_evidence,
|
||||
protected_expression=legal.protected_expression,
|
||||
access_evidence=legal.access_evidence,
|
||||
missing_factors=list(legal.missing_factors),
|
||||
precedent_ids=list(legal.precedent_ids),
|
||||
disclaimer=legal.disclaimer,
|
||||
),
|
||||
autobiography_mode=autobio_mode,
|
||||
candidates_before_filter=candidates_count,
|
||||
engine_version=self.settings.engine_version,
|
||||
@@ -195,6 +338,87 @@ class PlagiarismDetector:
|
||||
def detect_request(self, req: DetectRequest) -> DetectResponse:
|
||||
return self.detect(req.doc_id, req.text, req.metadata, req.options)
|
||||
|
||||
def _persistent_to_similarity_hit(
|
||||
self, hit: PersistentHit, query_lemmas: list[str], query_elements,
|
||||
) -> SimilarityHit:
|
||||
from app.api.schemas import EvidenceSpan
|
||||
from app.engine.similarity import _element_similarities
|
||||
from app.engine.structural import lemma_overlap_ratio
|
||||
|
||||
reference_elements = self._extractor.extract(hit.reference_text)
|
||||
element_sim = _element_similarities(query_elements, reference_elements)
|
||||
lemma_sim = lemma_overlap_ratio(query_lemmas, extract_lemmas(hit.reference_text))
|
||||
s = self.settings
|
||||
combined = (
|
||||
s.weight_text_sim * hit.score
|
||||
+ s.weight_lemma_sim * lemma_sim
|
||||
+ s.weight_char_sim * element_sim["characters"]
|
||||
+ s.weight_motif_sim * element_sim["motifs"]
|
||||
)
|
||||
|
||||
return SimilarityHit(
|
||||
doc_id=hit.segment_id,
|
||||
title=hit.title,
|
||||
score=combined,
|
||||
text_sim=hit.score,
|
||||
lemma_sim=lemma_sim,
|
||||
element_sim=element_sim,
|
||||
evidence=[EvidenceSpan(**span) for span in hit.evidence],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _add_provenance(match: MatchResult, hit: PersistentHit) -> MatchResult:
|
||||
return match.model_copy(update={
|
||||
"source_document_id": hit.document_id,
|
||||
"source_segment_id": hit.segment_id,
|
||||
"source_locator": hit.source_locator,
|
||||
"coordinate_scope": hit.coordinate_scope,
|
||||
"page_number": hit.page_number,
|
||||
"paragraph_number": hit.paragraph_number,
|
||||
"source_char_start": hit.source_char_start,
|
||||
"source_char_end": hit.source_char_end,
|
||||
"matched_coverage": round(hit.coverage, 4),
|
||||
"longest_span": hit.longest_span,
|
||||
})
|
||||
|
||||
def add_persistent_document(self, doc_id: str | None, title: str, text: str) -> str:
|
||||
if not self._persistent:
|
||||
raise RuntimeError("persistent index is not enabled")
|
||||
document_id = (doc_id or stable_id("doc", title)).strip()
|
||||
self._persistent.store.upsert_document(DocumentRecord(document_id=document_id, title=title))
|
||||
clean_text = text.strip()
|
||||
segments = [SegmentRecord(
|
||||
segment_id=stable_id("seg", document_id, str(start), chunk),
|
||||
document_id=document_id, text=chunk, ordinal=str(i),
|
||||
coordinate_scope="document", char_start=start, char_end=end,
|
||||
source_locator=f"api://corpus/{document_id}#chars={start}-{end}",
|
||||
metadata={"provenance_quality": "api_document"},
|
||||
) for i, (start, end, chunk) in enumerate(
|
||||
chunk_with_offsets(clean_text, size=1000, stride=500), 1
|
||||
)]
|
||||
inserted, duplicates = self._persistent.store.add_segments(segments)
|
||||
if duplicates and not inserted:
|
||||
raise FileExistsError(f"doc_id '{document_id}' 또는 동일 본문이 이미 존재합니다")
|
||||
self._replace_persistent_index()
|
||||
return document_id
|
||||
|
||||
def delete_persistent_document(self, doc_id: str) -> bool:
|
||||
if not self._persistent:
|
||||
raise RuntimeError("persistent index is not enabled")
|
||||
deleted = self._persistent.store.delete_document(doc_id)
|
||||
if deleted:
|
||||
self._replace_persistent_index()
|
||||
return deleted
|
||||
|
||||
def _replace_persistent_index(self) -> None:
|
||||
"""새 객체를 완성한 뒤 포인터를 한 번에 교체해 동시 질의 정합성을 보장."""
|
||||
replacement = PersistentCorpusIndex(
|
||||
self.settings.corpus_db, self.settings.persistent_index_path,
|
||||
)
|
||||
replacement.sync()
|
||||
replacement.load()
|
||||
self._persistent = replacement
|
||||
|
||||
def _partial_signal(self, doc_id, query_elements, query_lemmas) -> PartialPlagiarismSignal | None:
|
||||
"""군집화 기반 요소별 부분 표절 분해 (옵션)."""
|
||||
if not self._cluster:
|
||||
@@ -308,8 +532,9 @@ class PlagiarismDetector:
|
||||
tag_summary = ", ".join(primary_labels) if primary_labels else "확인 필요"
|
||||
case_part = f" 추정 케이스 {top.case_id} ({top.case_title})." if top.case_id else ""
|
||||
return (
|
||||
f"'{top.source_title}'와 결합 유사도 {top.similarity:.2%}로 매칭. "
|
||||
f"주 침해 태그: {tag_summary}.{case_part}{breakdown}"
|
||||
f"'{top.source_title}'와 검색 유사도 {top.similarity:.2%}로 후보 매칭. "
|
||||
f"검토 가설 태그: {tag_summary}.{case_part}{breakdown} "
|
||||
"법적 침해 여부는 보호되는 표현·의거관계·권리관계를 별도 검토해야 합니다."
|
||||
)
|
||||
|
||||
|
||||
@@ -330,20 +555,6 @@ def _calibrate_similarity(raw: float, threshold: float) -> int:
|
||||
return max(0, min(100, round(disp)))
|
||||
|
||||
|
||||
def _dummy_ai_generation_signal(text: str) -> AiGenerationSignal:
|
||||
"""AI 생성 의심도 스텁 — 실제 판별이 아니라 텍스트 기반 결정적 더미 값.
|
||||
|
||||
바이칼 UI(낮음/중간/높음 배지) 연동용 계약 확정 목적. 정식 구현(워터마킹+
|
||||
언어특징 분류) 전까지 is_stub=True 로 반환한다.
|
||||
"""
|
||||
h = sum(ord(c) for c in text[:300]) % 100
|
||||
if h < 70:
|
||||
return AiGenerationSignal(suspicion_level="low", score=round(0.05 + h / 500, 3))
|
||||
if h < 90:
|
||||
return AiGenerationSignal(suspicion_level="medium", score=round(0.45 + (h - 70) / 200, 3))
|
||||
return AiGenerationSignal(suspicion_level="high", score=round(0.72 + (h - 90) / 200, 3))
|
||||
|
||||
|
||||
def _classify_legacy(hit: SimilarityHit) -> InfringementType:
|
||||
"""후방 호환 - 단일 enum 분류 (UI/기존 통합 코드용)."""
|
||||
elem = hit.element_sim
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""등록된 판례만 인용하는 저작권 위험도 보조 엔진.
|
||||
|
||||
유사도 점수를 법적 결론으로 바꾸지 않는다. 보호되는 표현, 의거관계, 권리 귀속
|
||||
등 입력되지 않은 사실을 ``missing_factors`` 로 남기고 사람 검토를 요구한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Iterable
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Precedent:
|
||||
case_id: str
|
||||
title: str
|
||||
source_url: str
|
||||
work_types: tuple[str, ...]
|
||||
legal_tags: tuple[str, ...]
|
||||
criteria: tuple[str, ...]
|
||||
holding_summary: str
|
||||
outcome: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LegalRiskAssessment:
|
||||
status: str
|
||||
risk_level: str | None
|
||||
similarity_evidence: str
|
||||
protected_expression: str
|
||||
access_evidence: str
|
||||
missing_factors: tuple[str, ...]
|
||||
precedent_ids: tuple[str, ...] = field(default_factory=tuple)
|
||||
disclaimer: str = (
|
||||
"이 결과는 등록 코퍼스와 판례에 기반한 검토 우선순위이며 법률상 침해 확정이 아닙니다."
|
||||
)
|
||||
|
||||
|
||||
def load_precedents(path: str | Path) -> list[Precedent]:
|
||||
file = Path(path)
|
||||
if not file.exists():
|
||||
return []
|
||||
rows: list[Precedent] = []
|
||||
seen: set[str] = set()
|
||||
for lineno, line in enumerate(file.read_text(encoding="utf-8").splitlines(), 1):
|
||||
if not line.strip():
|
||||
continue
|
||||
raw = json.loads(line)
|
||||
required = ("case_id", "title", "source_url", "holding_summary")
|
||||
missing = [key for key in required if not str(raw.get(key, "")).strip()]
|
||||
if missing:
|
||||
raise ValueError(f"{file}:{lineno} 필수 필드 없음: {missing}")
|
||||
case_id = str(raw["case_id"])
|
||||
if case_id in seen:
|
||||
raise ValueError(f"중복 사건번호: {case_id}")
|
||||
if not str(raw["source_url"]).startswith("https://"):
|
||||
raise ValueError(f"검증 가능한 HTTPS 출처가 필요합니다: {case_id}")
|
||||
seen.add(case_id)
|
||||
rows.append(Precedent(
|
||||
case_id=case_id,
|
||||
title=str(raw["title"]),
|
||||
source_url=str(raw["source_url"]),
|
||||
work_types=tuple(raw.get("work_types", [])),
|
||||
legal_tags=tuple(raw.get("legal_tags", [])),
|
||||
criteria=tuple(raw.get("criteria", [])),
|
||||
holding_summary=str(raw["holding_summary"]),
|
||||
outcome=raw.get("outcome"),
|
||||
))
|
||||
return rows
|
||||
|
||||
|
||||
class LegalRiskEngine:
|
||||
def __init__(self, precedents: Iterable[Precedent]):
|
||||
self.precedents = list(precedents)
|
||||
|
||||
def assess(
|
||||
self,
|
||||
*,
|
||||
max_similarity: float,
|
||||
coverage: float,
|
||||
longest_span: int,
|
||||
legal_tags: Iterable[str],
|
||||
work_type: str = "literary",
|
||||
access_evidence: bool | None = None,
|
||||
protected_expression_reviewed: bool = False,
|
||||
rights_verified: bool = False,
|
||||
) -> LegalRiskAssessment:
|
||||
tags = set(legal_tags)
|
||||
related = sorted([
|
||||
p for p in self.precedents
|
||||
if (not p.work_types or work_type in p.work_types)
|
||||
and (not p.legal_tags or tags.intersection(p.legal_tags))
|
||||
], key=lambda p: (
|
||||
-len(tags.intersection(p.legal_tags)),
|
||||
0 if work_type in p.work_types else 1,
|
||||
p.case_id,
|
||||
))[:5]
|
||||
missing: list[str] = []
|
||||
if not protected_expression_reviewed:
|
||||
missing.append("보호되는 창작적 표현인지에 대한 사람 검토")
|
||||
if access_evidence is None:
|
||||
missing.append("원저작물 접근·의거 가능성")
|
||||
if not rights_verified:
|
||||
missing.append("저작권 귀속·이용허락·인용 요건")
|
||||
|
||||
if not self.precedents:
|
||||
status, level = "insufficient_precedent_data", None
|
||||
elif max_similarity <= 0 and coverage <= 0:
|
||||
status, level = "no_registered_corpus_match", "low"
|
||||
else:
|
||||
status = "review_required"
|
||||
strong_copy = coverage >= 0.30 or longest_span >= 100
|
||||
level = "high" if strong_copy and max_similarity >= 0.75 else "medium"
|
||||
if not strong_copy and max_similarity < 0.60:
|
||||
level = "low"
|
||||
|
||||
return LegalRiskAssessment(
|
||||
status=status,
|
||||
risk_level=level,
|
||||
similarity_evidence=(
|
||||
f"검색 유사도 {max_similarity:.3f}, 질의 커버리지 {coverage:.3f}, "
|
||||
f"최장 연속 일치 {longest_span}자"
|
||||
),
|
||||
protected_expression=("reviewed" if protected_expression_reviewed else "not_reviewed"),
|
||||
access_evidence=(
|
||||
"provided" if access_evidence is True else
|
||||
"not_found" if access_evidence is False else "not_provided"
|
||||
),
|
||||
missing_factors=tuple(missing),
|
||||
precedent_ids=tuple(p.case_id for p in related),
|
||||
)
|
||||
@@ -0,0 +1,267 @@
|
||||
"""CPU 친화적인 영속 후보 검색 인덱스.
|
||||
|
||||
HashingVectorizer를 사용해 학습 vocabulary를 메모리에 들고 있지 않으며, sparse
|
||||
행렬을 디스크에 저장한다. 기존 ID가 모두 유지된 경우 새 세그먼트만 transform하여
|
||||
append하므로 문서 한 건 추가 시 전체 임베딩/인덱스를 재계산하지 않는다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from difflib import SequenceMatcher
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
from app.engine.provenance import CorpusStore, SegmentRecord
|
||||
|
||||
|
||||
INDEX_VERSION = 1
|
||||
VECTORIZER_CONFIG = {
|
||||
"analyzer": "char_wb",
|
||||
"ngram_range": [3, 4],
|
||||
"alternate_sign": False,
|
||||
"lowercase": False,
|
||||
"norm": "l2",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PersistentHit:
|
||||
segment_id: str
|
||||
document_id: str
|
||||
title: str
|
||||
score: float
|
||||
evidence: list[dict]
|
||||
coverage: float
|
||||
longest_span: int
|
||||
source_locator: str | None
|
||||
coordinate_scope: str
|
||||
page_number: int | None
|
||||
paragraph_number: int | None
|
||||
source_char_start: int | None
|
||||
source_char_end: int | None
|
||||
reference_text: str
|
||||
|
||||
|
||||
def _vectorizer(n_features: int, config: dict | None = None):
|
||||
from sklearn.feature_extraction.text import HashingVectorizer
|
||||
|
||||
cfg = config or VECTORIZER_CONFIG
|
||||
return HashingVectorizer(
|
||||
analyzer=cfg["analyzer"],
|
||||
ngram_range=tuple(cfg["ngram_range"]),
|
||||
n_features=n_features,
|
||||
alternate_sign=cfg["alternate_sign"],
|
||||
lowercase=cfg["lowercase"],
|
||||
norm=cfg["norm"],
|
||||
dtype=np.float32,
|
||||
)
|
||||
|
||||
|
||||
def _evidence_spans(query: str, reference: str, min_match: int = 12, limit: int = 10) -> tuple[list[dict], float, int]:
|
||||
"""원문 query 좌표의 공통 연속 구간과 coverage를 반환."""
|
||||
if not query or not reference:
|
||||
return [], 0.0, 0
|
||||
blocks = SequenceMatcher(None, query, reference, autojunk=False).get_matching_blocks()
|
||||
useful = [b for b in blocks if b.size >= min_match]
|
||||
useful.sort(key=lambda b: (-b.size, b.a))
|
||||
selected = sorted(useful[:limit], key=lambda b: b.a)
|
||||
spans = [
|
||||
{
|
||||
"start": b.a,
|
||||
"end": b.a + b.size,
|
||||
"source_start": b.b,
|
||||
"source_end": b.b + b.size,
|
||||
"matched": query[b.a : b.a + b.size],
|
||||
}
|
||||
for b in selected
|
||||
]
|
||||
covered: set[int] = set()
|
||||
for b in useful:
|
||||
covered.update(range(b.a, b.a + b.size))
|
||||
return spans, len(covered) / max(1, len(query)), max((b.size for b in useful), default=0)
|
||||
|
||||
|
||||
class PersistentCorpusIndex:
|
||||
MATRIX_FILE = "lexical.npz"
|
||||
META_FILE = "index.json"
|
||||
|
||||
def __init__(self, store_path: str | Path, index_dir: str | Path):
|
||||
self.store = CorpusStore(store_path)
|
||||
self.index_dir = Path(index_dir)
|
||||
self._matrix = None
|
||||
self._meta: dict = {}
|
||||
|
||||
@property
|
||||
def ready(self) -> bool:
|
||||
meta_path = self.index_dir / self.META_FILE
|
||||
if not meta_path.exists():
|
||||
return False
|
||||
try:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
return self._matrix_path(meta).exists()
|
||||
except (OSError, ValueError, json.JSONDecodeError):
|
||||
return False
|
||||
|
||||
@property
|
||||
def size(self) -> int:
|
||||
return len(self._meta.get("segment_ids", []))
|
||||
|
||||
@property
|
||||
def document_count(self) -> int:
|
||||
if "document_count" in self._meta:
|
||||
return int(self._meta["document_count"])
|
||||
return self.store.document_count()
|
||||
|
||||
def load(self) -> "PersistentCorpusIndex":
|
||||
if not self.ready:
|
||||
raise FileNotFoundError(f"영속 인덱스가 없습니다: {self.index_dir}")
|
||||
from scipy.sparse import load_npz
|
||||
|
||||
self._meta = json.loads((self.index_dir / self.META_FILE).read_text(encoding="utf-8"))
|
||||
if self._meta.get("version") != INDEX_VERSION:
|
||||
raise ValueError("지원하지 않는 영속 인덱스 버전")
|
||||
if self._meta.get("vectorizer_config") != VECTORIZER_CONFIG:
|
||||
raise ValueError("인덱스 vectorizer 설정이 현재 코드와 달라 재빌드가 필요합니다")
|
||||
self._matrix = load_npz(self._matrix_path(self._meta)).tocsr()
|
||||
if self._matrix.shape[0] != len(self._meta["segment_ids"]):
|
||||
raise ValueError("인덱스 행과 segment_ids 개수가 다릅니다")
|
||||
return self
|
||||
|
||||
def _matrix_path(self, meta: dict) -> Path:
|
||||
return self.index_dir / str(meta.get("matrix_file") or self.MATRIX_FILE)
|
||||
|
||||
def sync(self, n_features: int = 2**20) -> dict:
|
||||
"""DB와 동기화. 추가만 있으면 append, 삭제/변경이면 안전하게 rebuild."""
|
||||
from scipy.sparse import load_npz, save_npz, vstack
|
||||
|
||||
self.index_dir.mkdir(parents=True, exist_ok=True)
|
||||
segments = list(self.store.iter_segments())
|
||||
current = {s.segment_id: s.text_sha256 for s in segments}
|
||||
mode = "rebuild"
|
||||
existing_ids: list[str] = []
|
||||
matrix = None
|
||||
if self.ready:
|
||||
old = json.loads((self.index_dir / self.META_FILE).read_text(encoding="utf-8"))
|
||||
old_ids = old.get("segment_ids", [])
|
||||
old_hashes = old.get("text_hashes", {})
|
||||
if (
|
||||
old.get("vectorizer_config") == VECTORIZER_CONFIG
|
||||
and int(old.get("n_features", 0)) == n_features
|
||||
and all(i in current and current[i] == old_hashes.get(i) for i in old_ids)
|
||||
):
|
||||
existing_ids = old_ids
|
||||
matrix = load_npz(self._matrix_path(old)).tocsr()
|
||||
mode = "append"
|
||||
|
||||
by_id = {s.segment_id: s for s in segments}
|
||||
existing_set = set(existing_ids)
|
||||
new_ids = [s.segment_id for s in segments if s.segment_id not in existing_set]
|
||||
vectorizer = _vectorizer(n_features)
|
||||
if matrix is None:
|
||||
existing_ids = []
|
||||
new_ids = [s.segment_id for s in segments]
|
||||
matrix = vectorizer.transform([by_id[i].text for i in new_ids]).tocsr()
|
||||
elif new_ids:
|
||||
delta = vectorizer.transform([by_id[i].text for i in new_ids]).tocsr()
|
||||
matrix = vstack([matrix, delta], format="csr")
|
||||
ids = existing_ids + new_ids
|
||||
generation_payload = json.dumps(
|
||||
{"ids": ids, "hashes": {i: current[i] for i in ids},
|
||||
"config": VECTORIZER_CONFIG, "features": n_features},
|
||||
sort_keys=True,
|
||||
).encode("utf-8")
|
||||
generation = hashlib.sha256(generation_payload).hexdigest()[:16]
|
||||
matrix_file = f"lexical-{generation}.npz"
|
||||
meta = {
|
||||
"version": INDEX_VERSION,
|
||||
"backend": "hashing-char-3-4",
|
||||
"n_features": n_features,
|
||||
"vectorizer_config": VECTORIZER_CONFIG,
|
||||
"segment_ids": ids,
|
||||
"text_hashes": {i: current[i] for i in ids},
|
||||
"document_count": self.store.document_count(),
|
||||
"matrix_file": matrix_file,
|
||||
}
|
||||
matrix_tmp = self.index_dir / f"{matrix_file}.tmp.npz"
|
||||
save_npz(matrix_tmp, matrix, compressed=False)
|
||||
matrix_tmp.replace(self.index_dir / matrix_file)
|
||||
tmp = self.index_dir / f"{self.META_FILE}.tmp"
|
||||
tmp.write_text(json.dumps(meta, ensure_ascii=False), encoding="utf-8")
|
||||
tmp.replace(self.index_dir / self.META_FILE)
|
||||
self._matrix, self._meta = matrix, meta
|
||||
return {"mode": mode, "total": len(ids), "added": len(new_ids)}
|
||||
|
||||
def query(self, text: str, top_k: int = 50, min_score: float = 0.0) -> list[PersistentHit]:
|
||||
if self._matrix is None:
|
||||
self.load()
|
||||
if not text.strip() or self._matrix is None or self._matrix.shape[0] == 0:
|
||||
return []
|
||||
vectorizer = _vectorizer(
|
||||
int(self._meta["n_features"]), self._meta["vectorizer_config"]
|
||||
)
|
||||
# 긴 원고 앞부분만 보거나 전체 벡터에 부분 복사가 희석되지 않도록 query도
|
||||
# 1,200자/600 stride로 나누고 각 원문 세그먼트의 최대 점수를 사용한다.
|
||||
query_chunks: list[tuple[int, str]] = []
|
||||
for start in range(0, len(text), 600):
|
||||
chunk = text[start : start + 1200]
|
||||
if chunk.strip():
|
||||
query_chunks.append((start, chunk))
|
||||
if start + 1200 >= len(text):
|
||||
break
|
||||
scores = np.zeros(self._matrix.shape[0], dtype=np.float32)
|
||||
best_chunk = np.zeros(self._matrix.shape[0], dtype=np.int32)
|
||||
for batch_start in range(0, len(query_chunks), 32):
|
||||
batch = query_chunks[batch_start : batch_start + 32]
|
||||
queries = vectorizer.transform([chunk for _, chunk in batch])
|
||||
block = (self._matrix @ queries.T).toarray()
|
||||
local_argmax = block.argmax(axis=1)
|
||||
local_scores = block[np.arange(block.shape[0]), local_argmax]
|
||||
improved = local_scores > scores
|
||||
scores[improved] = local_scores[improved]
|
||||
best_chunk[improved] = batch_start + local_argmax[improved]
|
||||
k = min(max(1, top_k), len(scores))
|
||||
indexes = np.argpartition(scores, -k)[-k:]
|
||||
indexes = indexes[np.argsort(scores[indexes])[::-1]]
|
||||
ids = [self._meta["segment_ids"][int(i)] for i in indexes if scores[int(i)] >= min_score]
|
||||
records = self.store.get_segments(ids)
|
||||
hits: list[PersistentHit] = []
|
||||
for i in indexes:
|
||||
score = float(scores[int(i)])
|
||||
if score < min_score:
|
||||
continue
|
||||
segment_id = self._meta["segment_ids"][int(i)]
|
||||
record = records.get(segment_id)
|
||||
if not record:
|
||||
continue
|
||||
chunk_start, chunk_text = query_chunks[int(best_chunk[int(i)])]
|
||||
evidence, _, longest = _evidence_spans(chunk_text, record.text)
|
||||
for span in evidence:
|
||||
span["start"] += chunk_start
|
||||
span["end"] += chunk_start
|
||||
covered = sum(span["end"] - span["start"] for span in evidence)
|
||||
coverage = min(1.0, covered / max(1, len(text)))
|
||||
hits.append(self._to_hit(record, score, evidence, coverage, longest))
|
||||
return hits
|
||||
|
||||
@staticmethod
|
||||
def _to_hit(record: SegmentRecord, score: float, evidence: list[dict], coverage: float, longest: int) -> PersistentHit:
|
||||
return PersistentHit(
|
||||
segment_id=record.segment_id,
|
||||
document_id=record.document_id,
|
||||
title=str(record.metadata.get("document_title") or record.document_id),
|
||||
score=max(0.0, min(1.0, score)),
|
||||
evidence=evidence,
|
||||
coverage=coverage,
|
||||
longest_span=longest,
|
||||
source_locator=record.source_locator,
|
||||
coordinate_scope=record.coordinate_scope,
|
||||
page_number=record.page_number,
|
||||
paragraph_number=record.paragraph_number,
|
||||
source_char_start=record.char_start,
|
||||
source_char_end=record.char_end,
|
||||
reference_text=record.text,
|
||||
)
|
||||
@@ -0,0 +1,268 @@
|
||||
"""원문 위치를 보존하는 SQLite 코퍼스 저장소.
|
||||
|
||||
검색용 전처리 텍스트와 증거 표시용 원문을 분리한다. 현재 수령한 XLSX처럼
|
||||
페이지 정보가 없는 데이터도 ``coordinate_scope=episode`` 로 정직하게 기록하며,
|
||||
향후 PDF/DOCX 재추출 시 동일 스키마에 page/paragraph/char offset을 채울 수 있다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import sqlite3
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Iterable, Iterator
|
||||
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
|
||||
|
||||
def text_sha256(text: str) -> str:
|
||||
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def stable_id(prefix: str, *parts: str) -> str:
|
||||
payload = "\x1f".join(parts).encode("utf-8")
|
||||
return f"{prefix}-{hashlib.sha256(payload).hexdigest()[:20]}"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DocumentRecord:
|
||||
document_id: str
|
||||
title: str
|
||||
source_path: str | None = None
|
||||
source_sha256: str | None = None
|
||||
metadata: dict = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SegmentRecord:
|
||||
segment_id: str
|
||||
document_id: str
|
||||
text: str
|
||||
ordinal: str
|
||||
coordinate_scope: str = "episode"
|
||||
page_number: int | None = None
|
||||
paragraph_number: int | None = None
|
||||
char_start: int | None = None
|
||||
char_end: int | None = None
|
||||
source_locator: str | None = None
|
||||
metadata: dict = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def text_sha256(self) -> str:
|
||||
return text_sha256(self.text)
|
||||
|
||||
|
||||
class CorpusStore:
|
||||
"""SQLite 기반 원문/세그먼트 저장소.
|
||||
|
||||
연결은 호출 단위로 열어 멀티프로세스 API에서도 안전하게 사용한다. WAL은
|
||||
읽기 중 증분 적재를 허용한다.
|
||||
"""
|
||||
|
||||
def __init__(self, path: str | Path):
|
||||
self.path = Path(path)
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
con = sqlite3.connect(self.path)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA journal_mode=WAL")
|
||||
con.execute("PRAGMA foreign_keys=ON")
|
||||
return con
|
||||
|
||||
def initialize(self) -> None:
|
||||
with self._connect() as con:
|
||||
con.executescript(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS corpus_meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS documents (
|
||||
document_id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
source_path TEXT,
|
||||
source_sha256 TEXT,
|
||||
metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS segments (
|
||||
segment_id TEXT PRIMARY KEY,
|
||||
document_id TEXT NOT NULL REFERENCES documents(document_id) ON DELETE CASCADE,
|
||||
ordinal TEXT NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
text_sha256 TEXT NOT NULL,
|
||||
coordinate_scope TEXT NOT NULL,
|
||||
page_number INTEGER,
|
||||
paragraph_number INTEGER,
|
||||
char_start INTEGER,
|
||||
char_end INTEGER,
|
||||
source_locator TEXT,
|
||||
metadata_json TEXT NOT NULL DEFAULT '{}',
|
||||
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(document_id, text_sha256)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_segments_document ON segments(document_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_segments_hash ON segments(text_sha256);
|
||||
"""
|
||||
)
|
||||
con.execute(
|
||||
"INSERT OR REPLACE INTO corpus_meta(key, value) VALUES('schema_version', ?)",
|
||||
(str(SCHEMA_VERSION),),
|
||||
)
|
||||
|
||||
def upsert_document(self, record: DocumentRecord) -> None:
|
||||
self.upsert_documents([record])
|
||||
|
||||
def upsert_documents(self, records: Iterable[DocumentRecord]) -> None:
|
||||
self.initialize()
|
||||
with self._connect() as con:
|
||||
con.executemany(
|
||||
"""
|
||||
INSERT INTO documents(document_id,title,source_path,source_sha256,metadata_json)
|
||||
VALUES(?,?,?,?,?)
|
||||
ON CONFLICT(document_id) DO UPDATE SET
|
||||
title=excluded.title,
|
||||
source_path=COALESCE(excluded.source_path, documents.source_path),
|
||||
source_sha256=COALESCE(excluded.source_sha256, documents.source_sha256),
|
||||
metadata_json=excluded.metadata_json,
|
||||
updated_at=CURRENT_TIMESTAMP
|
||||
""",
|
||||
[(
|
||||
record.document_id, record.title, record.source_path,
|
||||
record.source_sha256,
|
||||
json.dumps(record.metadata, ensure_ascii=False, sort_keys=True),
|
||||
) for record in records],
|
||||
)
|
||||
|
||||
def add_segments(self, records: Iterable[SegmentRecord]) -> tuple[int, int]:
|
||||
"""세그먼트를 추가하고 (inserted, duplicates) 반환."""
|
||||
self.initialize()
|
||||
inserted = duplicates = 0
|
||||
with self._connect() as con:
|
||||
for r in records:
|
||||
before = con.total_changes
|
||||
con.execute(
|
||||
"""
|
||||
INSERT OR IGNORE INTO segments(
|
||||
segment_id,document_id,ordinal,text,text_sha256,coordinate_scope,
|
||||
page_number,paragraph_number,char_start,char_end,source_locator,metadata_json
|
||||
) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
|
||||
""",
|
||||
(
|
||||
r.segment_id,
|
||||
r.document_id,
|
||||
r.ordinal,
|
||||
r.text,
|
||||
r.text_sha256,
|
||||
r.coordinate_scope,
|
||||
r.page_number,
|
||||
r.paragraph_number,
|
||||
r.char_start,
|
||||
r.char_end,
|
||||
r.source_locator,
|
||||
json.dumps(r.metadata, ensure_ascii=False, sort_keys=True),
|
||||
),
|
||||
)
|
||||
if con.total_changes > before:
|
||||
inserted += 1
|
||||
else:
|
||||
duplicates += 1
|
||||
return inserted, duplicates
|
||||
|
||||
def iter_segments(self) -> Iterator[SegmentRecord]:
|
||||
if not self.path.exists():
|
||||
return
|
||||
with self._connect() as con:
|
||||
rows = con.execute(
|
||||
"""
|
||||
SELECT s.*, d.title
|
||||
FROM segments s JOIN documents d USING(document_id)
|
||||
ORDER BY s.document_id, s.ordinal, s.segment_id
|
||||
"""
|
||||
)
|
||||
for row in rows:
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
metadata.setdefault("document_title", row["title"])
|
||||
yield SegmentRecord(
|
||||
segment_id=row["segment_id"],
|
||||
document_id=row["document_id"],
|
||||
text=row["text"],
|
||||
ordinal=row["ordinal"],
|
||||
coordinate_scope=row["coordinate_scope"],
|
||||
page_number=row["page_number"],
|
||||
paragraph_number=row["paragraph_number"],
|
||||
char_start=row["char_start"],
|
||||
char_end=row["char_end"],
|
||||
source_locator=row["source_locator"],
|
||||
metadata=metadata,
|
||||
)
|
||||
|
||||
def get_segments(self, segment_ids: Iterable[str]) -> dict[str, SegmentRecord]:
|
||||
ids = list(dict.fromkeys(segment_ids))
|
||||
if not ids or not self.path.exists():
|
||||
return {}
|
||||
result: dict[str, SegmentRecord] = {}
|
||||
with self._connect() as con:
|
||||
for start in range(0, len(ids), 500):
|
||||
batch = ids[start : start + 500]
|
||||
marks = ",".join("?" for _ in batch)
|
||||
rows = con.execute(
|
||||
f"""SELECT s.*, d.title FROM segments s
|
||||
JOIN documents d USING(document_id)
|
||||
WHERE segment_id IN ({marks})""",
|
||||
batch,
|
||||
)
|
||||
for row in rows:
|
||||
metadata = json.loads(row["metadata_json"] or "{}")
|
||||
metadata.setdefault("document_title", row["title"])
|
||||
result[row["segment_id"]] = SegmentRecord(
|
||||
segment_id=row["segment_id"], document_id=row["document_id"],
|
||||
text=row["text"], ordinal=row["ordinal"],
|
||||
coordinate_scope=row["coordinate_scope"],
|
||||
page_number=row["page_number"], paragraph_number=row["paragraph_number"],
|
||||
char_start=row["char_start"], char_end=row["char_end"],
|
||||
source_locator=row["source_locator"], metadata=metadata,
|
||||
)
|
||||
return result
|
||||
|
||||
def stats(self) -> dict[str, int]:
|
||||
if not self.path.exists():
|
||||
return {"documents": 0, "segments": 0, "characters": 0}
|
||||
with self._connect() as con:
|
||||
documents = con.execute("SELECT COUNT(*) FROM documents").fetchone()[0]
|
||||
segments, characters = con.execute(
|
||||
"SELECT COUNT(*), COALESCE(SUM(LENGTH(text)),0) FROM segments"
|
||||
).fetchone()
|
||||
return {"documents": documents, "segments": segments, "characters": characters}
|
||||
|
||||
def document_count(self) -> int:
|
||||
if not self.path.exists():
|
||||
return 0
|
||||
with self._connect() as con:
|
||||
return int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
||||
|
||||
def list_documents(self) -> list[dict]:
|
||||
if not self.path.exists():
|
||||
return []
|
||||
with self._connect() as con:
|
||||
rows = con.execute(
|
||||
"""SELECT d.document_id, d.title, d.source_path,
|
||||
COUNT(s.segment_id) AS segment_count,
|
||||
COALESCE(SUM(LENGTH(s.text)),0) AS characters
|
||||
FROM documents d LEFT JOIN segments s USING(document_id)
|
||||
GROUP BY d.document_id ORDER BY d.title"""
|
||||
).fetchall()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def delete_document(self, document_id: str) -> bool:
|
||||
if not self.path.exists():
|
||||
return False
|
||||
with self._connect() as con:
|
||||
before = con.total_changes
|
||||
con.execute("DELETE FROM documents WHERE document_id=?", (document_id,))
|
||||
return con.total_changes > before
|
||||
@@ -0,0 +1,106 @@
|
||||
"""PDF/DOCX 원문을 위치 좌표가 보존된 세그먼트로 변환한다."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Iterator
|
||||
|
||||
from app.engine.provenance import DocumentRecord, SegmentRecord, stable_id
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionResult:
|
||||
document: DocumentRecord
|
||||
segments: tuple[SegmentRecord, ...]
|
||||
warnings: tuple[str, ...] = ()
|
||||
|
||||
|
||||
def file_sha256(path: Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with path.open("rb") as stream:
|
||||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||||
digest.update(block)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def chunk_with_offsets(text: str, size: int = 1000, stride: int = 500) -> Iterator[tuple[int, int, str]]:
|
||||
if size < 1 or stride < 1:
|
||||
raise ValueError("size and stride must be positive")
|
||||
text = text or ""
|
||||
for start in range(0, len(text), stride):
|
||||
end = min(len(text), start + size)
|
||||
chunk = text[start:end]
|
||||
if chunk.strip():
|
||||
yield start, end, chunk
|
||||
if end >= len(text):
|
||||
break
|
||||
|
||||
|
||||
def extract_pdf(path: Path, size: int = 1000, stride: int = 500) -> ExtractionResult:
|
||||
try:
|
||||
from pypdf import PdfReader
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("PDF 추출에는 pypdf가 필요합니다") from exc
|
||||
sha = file_sha256(path)
|
||||
document_id = stable_id("doc", sha)
|
||||
document = DocumentRecord(
|
||||
document_id=document_id, title=path.stem, source_path=str(path), source_sha256=sha,
|
||||
metadata={"format": "pdf", "coordinate_scope": "page"},
|
||||
)
|
||||
segments: list[SegmentRecord] = []
|
||||
warnings: list[str] = []
|
||||
reader = PdfReader(str(path))
|
||||
for page_number, page in enumerate(reader.pages, 1):
|
||||
text = page.extract_text() or ""
|
||||
if not text.strip():
|
||||
warnings.append(f"page {page_number}: text 없음(OCR 필요 가능)")
|
||||
continue
|
||||
for local_index, (start, end, chunk) in enumerate(chunk_with_offsets(text, size, stride), 1):
|
||||
segments.append(SegmentRecord(
|
||||
segment_id=stable_id("seg", document_id, str(page_number), str(start), chunk),
|
||||
document_id=document_id, text=chunk,
|
||||
ordinal=f"p{page_number:05d}-{local_index:04d}", coordinate_scope="page",
|
||||
page_number=page_number, char_start=start, char_end=end,
|
||||
source_locator=f"{path.name}#page={page_number}&chars={start}-{end}",
|
||||
metadata={"extractor": "pypdf", "page_text_coordinates": True},
|
||||
))
|
||||
return ExtractionResult(document, tuple(segments), tuple(warnings))
|
||||
|
||||
|
||||
def extract_docx(path: Path, size: int = 1000, stride: int = 500) -> ExtractionResult:
|
||||
try:
|
||||
from docx import Document
|
||||
except ImportError as exc:
|
||||
raise RuntimeError("DOCX 추출에는 python-docx가 필요합니다") from exc
|
||||
sha = file_sha256(path)
|
||||
document_id = stable_id("doc", sha)
|
||||
document = DocumentRecord(
|
||||
document_id=document_id, title=path.stem, source_path=str(path), source_sha256=sha,
|
||||
metadata={"format": "docx", "coordinate_scope": "paragraph"},
|
||||
)
|
||||
segments: list[SegmentRecord] = []
|
||||
source = Document(str(path))
|
||||
for paragraph_number, paragraph in enumerate(source.paragraphs, 1):
|
||||
text = paragraph.text or ""
|
||||
for local_index, (start, end, chunk) in enumerate(chunk_with_offsets(text, size, stride), 1):
|
||||
segments.append(SegmentRecord(
|
||||
segment_id=stable_id("seg", document_id, str(paragraph_number), str(start), chunk),
|
||||
document_id=document_id, text=chunk,
|
||||
ordinal=f"para{paragraph_number:06d}-{local_index:04d}",
|
||||
coordinate_scope="paragraph", paragraph_number=paragraph_number,
|
||||
char_start=start, char_end=end,
|
||||
source_locator=f"{path.name}#paragraph={paragraph_number}&chars={start}-{end}",
|
||||
metadata={"extractor": "python-docx", "paragraph_text_coordinates": True},
|
||||
))
|
||||
return ExtractionResult(document, tuple(segments))
|
||||
|
||||
|
||||
def extract_source(path: Path, size: int = 1000, stride: int = 500) -> ExtractionResult:
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".pdf":
|
||||
return extract_pdf(path, size, stride)
|
||||
if suffix == ".docx":
|
||||
return extract_docx(path, size, stride)
|
||||
raise ValueError(f"지원하지 않는 원본 형식: {path.suffix}")
|
||||
Reference in new issue
Block a user