3.5만 에피소드 기반 표절·AI·판례 분석 파이프라인 구현
This commit is contained in:
1 parent
4f6898d0b2
commit
ce50e89089
32 files changed
+4505
-69
No files matched your search
+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
|
||||
|
||||
Reference in new issue
Block a user