feat: expand infringement case matching to v1.3 precedent mapping

태그 동점 시 첫 케이스만 반환해 나머지를 버리던 문제를 고친다.
A1·A2·A3·A4·A5·A6·A15 는 주/보조 태그가 동일하고 실제 구별자는 원본의
종류라 태그로 좁혀지지 않는다. find_case -> find_cases 로 바꿔 동점군을
전부 내보내고, 확정은 사람이 원본 종류로 한다.

- cases_v1.3.json 신설(v1.2 삭제): 39건 전부에 대표판례·처리구분(●/○) 적재.
  판례 미지정 10건은 사유를 값으로 남긴다.
- detectable_internal 10 -> 19건 (v1.3 IX장 총괄표 ● 기준으로 정정)
- _assign_tags 주 태그 조합 3 -> 5종. 유사도로 판단 가능한 쟁점만 주 태그로
  낸다. 도달 케이스 3 -> 16건(● 19건 중).
- B3·C1·D1 은 게재 사실·편집 개입·성명표시가 필요해 텍스트로 알 수 없다.
  추측하지 않고 LegalContext 대기로 두며 경계를 테스트로 고정한다.
- 케이스 수 검증을 38~39 범위에서 39 로 고정. v1.3 본문 통계 줄(●16/○22=38)이
  같은 문서의 표(●19/○20=39)와 어긋난 것이 38/39 혼재의 원인이었다.
- docs/PRECEDENT_SOURCE_GAP.md: 대표판례이나 적재본에 없어 출처를 제시할 수
  없는 14건. 응답에서도 precedents_without_source 로 구분한다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5 committed 2026-09-18 15:42:34 +09:00
1 parent aaabbdd8c6
commit 52a0fdcdf0
10 files changed
+1120 -133

No files matched your search

+47 -7
View File
@@ -17,6 +17,7 @@ import logging
from datetime import datetime, timezone
from app.api.schemas import (
CaseCandidate,
TAG_LABEL_KO,
AiGenerationSignal,
DetectOptions,
@@ -604,15 +605,30 @@ class PlagiarismDetector:
) -> MatchResult:
legacy_type = _classify_legacy(hit)
tags = self._assign_tags(hit, legacy_type)
case = self.taxonomy.find_case([t.tag for t in tags if t.role == "primary"]) if self.taxonomy else None
cases = (self.taxonomy.find_cases([t.tag for t in tags if t.role == "primary"])
if self.taxonomy else ())
candidates = [
CaseCandidate(
case_id=c.case_id,
title=c.title,
handling=c.handling,
representative_precedents=[p.case_id for p in c.representative_precedents],
precedents_without_source=[
p.case_id for p in c.representative_precedents if not p.in_runtime_corpus
],
precedent_note=c.representative_precedent_note,
)
for c in cases
]
return MatchResult(
source_doc=hit.doc_id,
source_title=hit.title,
similarity=round(hit.score, 4),
tags=tags,
case_id=case.case_id if case else None,
case_title=case.title if case else None,
case_id=cases[0].case_id if cases else None,
case_title=cases[0].title if cases else None,
case_candidates=candidates,
infringement_type=legacy_type,
evidence_spans=hit.evidence if return_evidence else [],
score_breakdown=ScoreBreakdown(
@@ -633,6 +649,12 @@ class PlagiarismDetector:
- lemma만 매우 높음 → 인용 표시 누락(주 보조)
- 인물 일치도 매우 높음(서사·구조 차용) → 2차적저작물작성권(주) + 자기창작인양표시(보조)
- 구조 미달 가공 신호 (text 낮음 + lemma 중간) → 2차적저작물 미달 가공
주 태그는 케이스 후보를 좁히는 유일한 입력이므로, 유사도 분포로 판단할 수
있는 쟁점은 보조가 아니라 주 태그로 낸다. 반대로 게재 사실·편집 개입·성명
표시처럼 텍스트에서 알 수 없는 사실은 태그로 만들지 않는다. 그래서 B3·C1·
D1 은 이 함수만으로 후보에 오르지 않으며, LegalContext 로 사람이 확인한
사실이 들어와야 한다.
"""
text_sim = hit.text_sim
lemma_sim = hit.lemma_sim
@@ -649,14 +671,25 @@ class PlagiarismDetector:
# 표절 실무 - 인용 누락
primary.append("citation_missing")
# 표면 복제 + 구조 차용 동시 성립 (재수록·편집 수록형) → A10
elif lemma_sim >= 0.50 and char_sim >= 0.40:
primary.append("reproduction")
primary.append("derivative_work")
secondary.append("publication")
secondary.append("attribution")
# 2차적저작물작성권: 구조·서사 차용 (인물/모티프 일치 + 표면은 낮음)
elif (char_sim >= 0.40 or motif_sim >= 0.50) and text_sim < 0.40:
primary.append("derivative_work")
secondary.append("attribution")
secondary.append("citation_missing")
# 미달 가공 가능성
# 구조를 차용하고 출처 표시가 없으면 인용 누락이 주 쟁점이다 → A16
if lemma_sim >= 0.40:
primary.append("citation_missing")
else:
secondary.append("citation_missing")
# 미달 가공: 원문 표현을 거의 남기지 않은 구조 차용 → A7/B2
if text_sim < 0.30 and lemma_sim < 0.50:
secondary.append("substandard_derivative")
primary.append("substandard_derivative")
# 부분 변형 (text 중간 + 인물 일치)
elif text_sim >= 0.40 and char_sim >= 0.30:
@@ -690,7 +723,14 @@ class PlagiarismDetector:
)
primary_labels = [t.label_ko for t in top.tags if t.role == "primary"]
tag_summary = ", ".join(primary_labels) if primary_labels else "확인 필요"
case_part = f" 추정 케이스 {top.case_id} ({top.case_title})." if top.case_id else ""
if len(top.case_candidates) > 1:
ids = ", ".join(c.case_id for c in top.case_candidates)
case_part = (f" 추정 케이스 후보 {ids} — 태그만으로는 구별되지 않으므로 "
f"베껴온 원본의 종류를 확인해 확정해야 합니다.")
elif top.case_id:
case_part = f" 추정 케이스 {top.case_id} ({top.case_title})."
else:
case_part = ""
return (
f"'{top.source_title}'와 검색 유사도 {top.similarity:.2%}로 후보 매칭. "
f"검토 가설 태그: {tag_summary}.{case_part}{breakdown} "
+45 -17
View File
@@ -1,6 +1,10 @@
"""10종 메타 태그 분류체계 + 38개 케이스 로더.
"""10종 메타 태그 분류체계 + 39개 침해 케이스 로더.
PDF IV/IX장 그대로 JSON으로 보관 (data/taxonomy/). 부팅 시 1회 로드.
IV장(메타태그)과 IX장 「침해 케이스 ↔ 메타태그 매핑 총괄표」를 그대로 JSON으로
보관 (data/taxonomy/). 부팅 시 1회 로드.
케이스 데이터는 실무방안 v1.3 기준이며, 케이스별 **대표판례**와 처리 구분
(● 기술검출 근거 / ○ 약관·신고)을 함께 담는다.
"""
from __future__ import annotations
@@ -26,6 +30,12 @@ class MetaTagDef:
description: str
@dataclass(frozen=True)
class RepresentativePrecedent:
case_id: str # 법원 사건번호 (케이스 ID 아님)
in_runtime_corpus: bool # precedents.jsonl 적재 여부. False 면 인용 시 출처 미확보.
@dataclass(frozen=True)
class CaseDef:
case_id: str # A1, A7, B1, ...
@@ -38,6 +48,11 @@ class CaseDef:
detectable_internal: bool = False
high_risk: bool = False
note: str | None = None
#: v1.3 총괄표의 처리 구분. technical_detection(●) / terms_or_report(○)
handling: str = "terms_or_report"
representative_precedents: tuple[RepresentativePrecedent, ...] = field(default_factory=tuple)
#: 대표판례가 지정되지 않은 이유("확립 판례 없음" 등). 빈 목록과 구분한다.
representative_precedent_note: str | None = None
@dataclass(frozen=True)
@@ -53,35 +68,42 @@ class Taxonomy:
return t.label_ko
return tag_id
def find_case(self, primary_tags: Iterable[str]) -> CaseDef | None:
"""주 태그 조합이 가장 잘 매칭되는 케이스 추정.
def find_cases(self, primary_tags: Iterable[str]) -> tuple[CaseDef, ...]:
"""주 태그 조합에 가장 잘 맞는 케이스 **전부**를 반환한다.
완벽 일치 우선, 없으면 부분 일치 (jaccard).
내부 검출 가능 케이스(A1~A5, A24, A25, B1, B2, D1)에 가중치.
태그만으로는 케이스가 1:1로 좁혀지지 않는다. A1·A2·A3·A4·A5·A6·A15 는
주/보조 태그가 완전히 같고, 실제 구별자는 베껴온 **원본의 종류**(가사·기사·
위키·교재·타인 자서전)다. 원본 종류 라벨은 코퍼스에 아직 없으므로, 동점
케이스 중 하나를 임의로 고르는 대신 동점군을 그대로 돌려준다. 호출자는
이를 "이 중 하나"로 제시하고 사람이 원본 종류로 확정한다.
# ponytail: 원본 종류 라벨이 코퍼스에 들어오면 이 함수에 source_type 인자를
# 추가해 동점군을 좁힌다. 라벨 없는 상태에서 미리 배선하면 항상 None 이다.
"""
target = set(primary_tags)
if not target:
return None
best: CaseDef | None = None
best_score = -1.0
return ()
scored: list[tuple[float, CaseDef]] = []
for c in self.cases:
primary = set(c.primary_tags)
if not primary:
continue
inter = len(target & primary)
union = len(target | primary)
score = inter / max(1, union)
score = len(target & primary) / len(target | primary)
# v1.3 에서 기술검출 근거(●)로 확인된 케이스에 작은 가중치.
if c.detectable_internal:
score += 0.1
if score > best_score:
best_score = score
best = c
return best if best_score > 0.3 else None
scored.append((score, c))
if not scored:
return ()
best = max(score for score, _ in scored)
if best <= 0.3:
return ()
return tuple(c for score, c in scored if abs(score - best) < 1e-9)
def load_taxonomy(taxonomy_dir: Path) -> Taxonomy | None:
mt_path = taxonomy_dir / "meta_tags_v1.0.json"
cs_path = taxonomy_dir / "cases_v1.2.json"
cs_path = taxonomy_dir / "cases_v1.3.json"
if not mt_path.exists() or not cs_path.exists():
logger.warning("Taxonomy files not found in %s", taxonomy_dir)
return None
@@ -108,6 +130,12 @@ def load_taxonomy(taxonomy_dir: Path) -> Taxonomy | None:
detectable_internal=c.get("detectable_internal", False),
high_risk=c.get("high_risk", False),
note=c.get("note"),
handling=c.get("handling", "terms_or_report"),
representative_precedents=tuple(
RepresentativePrecedent(case_id=p["case_id"], in_runtime_corpus=p["in_runtime_corpus"])
for p in c.get("representative_precedents", [])
),
representative_precedent_note=c.get("representative_precedent_note"),
)
for c in cs_data["cases"]
)