2단계 고도화 선행 작업: 군집화·요약·평가환경·데이터 스펙 (데이터 수령 전)
컴북스 데이터 수령 전 가능한 작업을 선행 구현. 데이터 도착 즉시 학습·검증에 착수할 수 있도록 알고리즘·평가 하니스·문서를 준비. 알고리즘/파이프라인: - engine/clustering.py: 군집화 기반 부분 표절(요소 교체) 판별, detect 응답에 partial_signal 필드 노출 (계획서 2단계 표절검출 고도화) - engine/summarizer.py + POST /v1/summary: TextRank 추출적 요약 + 통합(LLM) 골격 (과제2 ② 스토리 요약/분석) - engine/preference.py + scripts/build_preference_dataset.py: Human Feedback 선호학습(DPO) 데이터 파이프라인 골격 평가 하니스 (정답셋 도착 즉시 측정): - engine/rouge.py + scripts/eval_rouge.py: 요약 ROUGE (지표 No.7) - engine/metadata_eval.py + scripts/eval_metadata_f1.py: 메타 추출 F1 (지표 No.3, KLUE NER 호환) - engine/case_coverage.py + scripts/analyze_case_coverage.py: 39 케이스 갭 분석 → 컴북스 데이터 요청 목록 (정밀도 97% 근거) 문서: - docs/DATA_REQUEST_SPEC.md: 요청 데이터 스펙 + 요약 정답셋/HF 라벨 가이드 - docs/INTEGRATION_INTERFACE.md: 2단계 통합 인터페이스 - docs/SW_COPYRIGHT_REGISTRATION.md: SW 저작권 등록 준비 - docs/PHASE2_PROGRESS.md, docs/CASE_COVERAGE.md 테스트 31 → 67건 전부 통과. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
cfa3d1b7cf
commit
0472ae1f8a
25 files changed
+2053
-2
No files matched your search
@@ -0,0 +1,43 @@
|
||||
"""39 케이스 커버리지 갭 분석 단위테스트."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from app.engine.case_coverage import analyze_coverage
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Case:
|
||||
case_id: str
|
||||
subgroup: str
|
||||
actor: str
|
||||
detectable_internal: bool
|
||||
|
||||
|
||||
_CASES = [
|
||||
_Case("A1", "A-1", "저자(가해)", True),
|
||||
_Case("A2", "A-1", "저자(가해)", True),
|
||||
_Case("C1", "C", "플랫폼", False), # 탐지 범위 밖
|
||||
]
|
||||
|
||||
|
||||
def test_no_data_all_detectable_need_data():
|
||||
rep = analyze_coverage(_CASES, None)
|
||||
assert rep["detectable_cases"] == 2
|
||||
assert rep["need_data_cases"] == 2
|
||||
assert rep["covered_cases"] == 0
|
||||
assert rep["coverage_ratio"] == 0.0
|
||||
|
||||
|
||||
def test_with_samples_marks_covered():
|
||||
rep = analyze_coverage(_CASES, {"A1": 10})
|
||||
assert rep["covered_cases"] == 1
|
||||
assert rep["need_data_cases"] == 1
|
||||
assert rep["coverage_ratio"] == 0.5
|
||||
|
||||
|
||||
def test_out_of_scope_excluded_from_request():
|
||||
rep = analyze_coverage(_CASES, {"A1": 5, "A2": 5})
|
||||
ids = {x["case_id"] for x in rep["data_request_list"]}
|
||||
assert "C1" not in ids
|
||||
assert rep["need_data_cases"] == 0
|
||||
@@ -0,0 +1,109 @@
|
||||
"""군집화 기반 표절 판별 단위테스트 (계획서 2단계 고도화).
|
||||
|
||||
핵심 시나리오: "본문(lemma)·키워드는 그대로 두고 인물만 바꾼 표절" 을
|
||||
element_swap_plagiarism 으로 분해해서 잡는다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.api.schemas import ExtractedElements
|
||||
from app.engine.clustering import (
|
||||
ClusterIndex,
|
||||
signature_similarity,
|
||||
_element_signature,
|
||||
)
|
||||
|
||||
|
||||
def _elem(characters=None, motifs=None, keywords=None, genre=None) -> ExtractedElements:
|
||||
return ExtractedElements(
|
||||
characters=characters or [],
|
||||
motifs=motifs or [],
|
||||
keywords=keywords or [],
|
||||
genre=genre,
|
||||
)
|
||||
|
||||
|
||||
def test_signature_similarity_identical():
|
||||
a = _element_signature(_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리"], genre="역사"))
|
||||
assert signature_similarity(a, a) == 1.0
|
||||
|
||||
|
||||
def test_clusters_group_similar_docs():
|
||||
# 두 홍길동 변형은 한 군집, 어린왕자는 별도 군집
|
||||
ids = ["hong-a", "hong-b", "prince"]
|
||||
elems = [
|
||||
_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리", "재물"], genre="역사"),
|
||||
_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리", "재물"], genre="역사"),
|
||||
_elem(characters=["어린왕자", "여우"], keywords=["사막", "장미", "별"], genre="동화"),
|
||||
]
|
||||
idx = ClusterIndex(ids, elems, link_threshold=0.35)
|
||||
assert idx.cluster_of("hong-a") == idx.cluster_of("hong-b")
|
||||
assert idx.cluster_of("prince") != idx.cluster_of("hong-a")
|
||||
|
||||
|
||||
def test_route_to_nearest_cluster():
|
||||
ids = ["hong", "prince"]
|
||||
elems = [
|
||||
_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리", "재물"], genre="역사"),
|
||||
_elem(characters=["어린왕자"], keywords=["사막", "장미", "별"], genre="동화"),
|
||||
]
|
||||
idx = ClusterIndex(ids, elems, link_threshold=0.9) # 분리 유지
|
||||
q = _elem(characters=["홍길동"], keywords=["활빈당", "재물"], genre="역사")
|
||||
routed = idx.route(q)
|
||||
assert routed is not None
|
||||
assert "hong" in routed.members
|
||||
|
||||
|
||||
def test_element_swap_plagiarism_detected():
|
||||
"""본문 lemma·키워드 유지 + 인물만 교체 → element_swap_plagiarism."""
|
||||
ids = ["original"]
|
||||
elems = [_elem(characters=["홍길동"], motifs=["복수"], keywords=["활빈당", "탐관오리", "재물", "의적"])]
|
||||
lemmas = [["만들다", "빼앗다", "재물", "탐관오리", "활빈당", "나누다"]]
|
||||
idx = ClusterIndex(ids, elems, doc_lemmas=lemmas, link_threshold=0.35)
|
||||
|
||||
# 인물(홍길동→김민수)·모티프만 바꾸고 본문 lemma/키워드는 그대로
|
||||
q_elem = _elem(characters=["김민수"], motifs=["정의"], keywords=["활빈당", "탐관오리", "재물", "의적"])
|
||||
q_lemmas = ["만들다", "빼앗다", "재물", "탐관오리", "활빈당", "나누다"]
|
||||
|
||||
sig = idx.partial_signal("original", q_elem, q_lemmas)
|
||||
assert sig is not None
|
||||
assert sig.verdict == "element_swap_plagiarism", sig.per_element
|
||||
assert "characters" in sig.changed_elements
|
||||
assert "lemmas" in sig.retained_elements
|
||||
|
||||
|
||||
def test_near_duplicate_verdict():
|
||||
ids = ["original"]
|
||||
elems = [_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리", "재물"])]
|
||||
lemmas = [["만들다", "빼앗다", "재물"]]
|
||||
idx = ClusterIndex(ids, elems, doc_lemmas=lemmas)
|
||||
|
||||
sig = idx.partial_signal(
|
||||
"original",
|
||||
_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리", "재물"]),
|
||||
["만들다", "빼앗다", "재물"],
|
||||
)
|
||||
assert sig is not None
|
||||
assert sig.verdict == "near_duplicate"
|
||||
|
||||
|
||||
def test_unrelated_gets_none_or_weak():
|
||||
ids = ["original"]
|
||||
elems = [_elem(characters=["홍길동"], keywords=["활빈당", "탐관오리"])]
|
||||
lemmas = [["만들다", "빼앗다"]]
|
||||
idx = ClusterIndex(ids, elems, doc_lemmas=lemmas)
|
||||
|
||||
sig = idx.partial_signal(
|
||||
"original",
|
||||
_elem(characters=["우주비행사"], keywords=["로켓", "행성"]),
|
||||
["날다", "탐사하다"],
|
||||
)
|
||||
assert sig is not None
|
||||
assert sig.verdict in ("none", "weak")
|
||||
assert sig.verdict != "element_swap_plagiarism"
|
||||
|
||||
|
||||
def test_empty_index():
|
||||
idx = ClusterIndex([], [])
|
||||
assert idx.num_clusters == 0
|
||||
assert idx.route(_elem(characters=["x"])) is None
|
||||
assert idx.candidate_ids(_elem(characters=["x"])) == set()
|
||||
@@ -0,0 +1,42 @@
|
||||
"""메타데이터 추출 F1 평가 단위테스트 (성능지표 No.3)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.engine.metadata_eval import set_prf, evaluate_extraction
|
||||
|
||||
|
||||
def test_set_prf_perfect():
|
||||
r = set_prf(["홍길동", "활빈당"], ["홍길동", "활빈당"])
|
||||
assert r.f1 == 1.0 and r.fp == 0 and r.fn == 0
|
||||
|
||||
|
||||
def test_set_prf_partial():
|
||||
r = set_prf(["홍길동", "임꺽정"], ["홍길동", "활빈당"])
|
||||
assert r.tp == 1 and r.fp == 1 and r.fn == 1
|
||||
assert 0.0 < r.f1 < 1.0
|
||||
|
||||
|
||||
def test_set_prf_case_insensitive():
|
||||
r = set_prf(["Hong"], ["hong"])
|
||||
assert r.f1 == 1.0
|
||||
|
||||
|
||||
def test_evaluate_extraction_micro():
|
||||
preds = [{"characters": ["홍길동"], "motifs": ["복수"], "keywords": ["활빈당"], "genre": "역사"}]
|
||||
golds = [{"characters": ["홍길동"], "motifs": ["복수"], "keywords": ["활빈당"], "genre": "역사"}]
|
||||
out = evaluate_extraction(preds, golds)
|
||||
assert out["micro_avg"]["f1"] == 1.0
|
||||
assert out["genre_accuracy"]["accuracy"] == 1.0
|
||||
|
||||
|
||||
def test_evaluate_extraction_genre_mismatch():
|
||||
preds = [{"characters": [], "motifs": [], "keywords": [], "genre": "SF"}]
|
||||
golds = [{"characters": [], "motifs": [], "keywords": [], "genre": "역사"}]
|
||||
out = evaluate_extraction(preds, golds)
|
||||
assert out["genre_accuracy"]["accuracy"] == 0.0
|
||||
|
||||
|
||||
def test_length_mismatch_raises():
|
||||
with pytest.raises(ValueError):
|
||||
evaluate_extraction([{}], [{}, {}])
|
||||
@@ -0,0 +1,59 @@
|
||||
"""HF 선호학습 데이터 파이프라인 단위테스트 (계획서 2단계 고도화)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.engine.preference import (
|
||||
PreferenceCandidate,
|
||||
build_candidate,
|
||||
to_dpo_record,
|
||||
to_dpo_dataset,
|
||||
validate_labeled,
|
||||
dataset_stats,
|
||||
)
|
||||
|
||||
|
||||
def test_build_candidate_is_pending():
|
||||
c = build_candidate("p1", "원문", "글A", "글B", suggested_rejected="b")
|
||||
assert c.label_status == "pending"
|
||||
assert "원문" in c.prompt
|
||||
assert to_dpo_record(c) is None # 미라벨은 학습 레코드 없음
|
||||
|
||||
|
||||
def test_labeled_becomes_dpo_record():
|
||||
c = build_candidate("p1", "원문", "정상글", "표절글", suggested_rejected="b")
|
||||
c.label_status = "labeled"
|
||||
c.chosen = "정상글"
|
||||
c.rejected = "표절글"
|
||||
rec = to_dpo_record(c)
|
||||
assert rec is not None
|
||||
assert rec["chosen"] == "정상글" and rec["rejected"] == "표절글"
|
||||
|
||||
|
||||
def test_validate_catches_same_chosen_rejected():
|
||||
c = PreferenceCandidate("p1", "p", "a", "b", label_status="labeled", chosen="x", rejected="x")
|
||||
errors = validate_labeled(c)
|
||||
assert any("chosen == rejected" in e for e in errors)
|
||||
|
||||
|
||||
def test_validate_catches_missing():
|
||||
c = PreferenceCandidate("p1", "p", "a", "b", label_status="labeled", chosen="x", rejected=None)
|
||||
assert any("rejected 누락" in e for e in validate_labeled(c))
|
||||
|
||||
|
||||
def test_dataset_stats():
|
||||
pending = build_candidate("p1", "o", "a", "b")
|
||||
labeled = build_candidate("p2", "o", "a", "b")
|
||||
labeled.label_status = "labeled"
|
||||
labeled.chosen, labeled.rejected = "a", "b"
|
||||
stats = dataset_stats([pending, labeled])
|
||||
assert stats["total"] == 2
|
||||
assert stats["labeled"] == 1
|
||||
assert stats["pending"] == 1
|
||||
assert stats["trainable"] == 1
|
||||
assert stats["errors"] == []
|
||||
|
||||
|
||||
def test_to_dpo_dataset_filters_pending():
|
||||
cs = [build_candidate(f"p{i}", "o", "a", "b") for i in range(3)]
|
||||
cs[0].label_status = "labeled"
|
||||
cs[0].chosen, cs[0].rejected = "a", "b"
|
||||
assert len(to_dpo_dataset(cs)) == 1
|
||||
@@ -0,0 +1,50 @@
|
||||
"""ROUGE 평가 모듈 단위테스트 (성능지표 No.7)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.engine.rouge import rouge_n, rouge_l, evaluate_pairs, tokenize
|
||||
|
||||
|
||||
def test_identical_is_perfect():
|
||||
s = rouge_n("홍길동은 활빈당을 만들었다", "홍길동은 활빈당을 만들었다", n=1)
|
||||
assert s.f1 == 1.0
|
||||
assert s.recall == 1.0
|
||||
|
||||
|
||||
def test_no_overlap_is_zero():
|
||||
s = rouge_n("우주선이 행성을 탐사한다", "사랑은 아름다운 감정이다", n=1, mode="char")
|
||||
assert s.f1 == 0.0
|
||||
|
||||
|
||||
def test_partial_overlap_between_zero_and_one():
|
||||
s = rouge_n("홍길동은 활빈당을 만들어 재물을 빼앗았다",
|
||||
"홍길동은 활빈당을 조직했다", n=1)
|
||||
assert 0.0 < s.f1 < 1.0
|
||||
|
||||
|
||||
def test_rouge2_stricter_than_rouge1():
|
||||
sys = "홍길동은 활빈당을 만들어 재물을 빼앗았다"
|
||||
ref = "홍길동은 재물을 활빈당으로 만들어 빼앗았다" # 단어 순서 섞임
|
||||
r1 = rouge_n(sys, ref, n=1).f1
|
||||
r2 = rouge_n(sys, ref, n=2).f1
|
||||
assert r2 <= r1 # bigram 은 순서에 민감 → 더 낮거나 같음
|
||||
|
||||
|
||||
def test_rouge_l_rewards_sequence():
|
||||
s = rouge_l("홍길동은 활빈당을 만들어 재물을 빼앗았다",
|
||||
"홍길동은 활빈당을 만들어 재물을 빼앗았다")
|
||||
assert s.f1 == 1.0
|
||||
|
||||
|
||||
def test_evaluate_pairs_aggregates():
|
||||
pairs = [
|
||||
("홍길동은 활빈당을 만들었다", "홍길동은 활빈당을 만들었다"),
|
||||
("어린왕자가 여우를 만났다", "어린왕자가 여우를 만났다"),
|
||||
]
|
||||
out = evaluate_pairs(pairs)
|
||||
assert set(out) == {"rouge1", "rouge2", "rougeL"}
|
||||
assert out["rouge1"]["f1"] == 1.0
|
||||
|
||||
|
||||
def test_tokenize_char_fallback():
|
||||
toks = tokenize("Hello 월드 123", mode="char")
|
||||
assert "hello" in toks and "월드" in toks and "123" in toks
|
||||
@@ -0,0 +1,67 @@
|
||||
"""스토리 요약 모듈 단위테스트 (계획서 과제2 ②).
|
||||
|
||||
추출적 요약은 외부 의존(LLM/정답셋) 없이 동작해야 한다.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.config import Settings
|
||||
from app.engine.summarizer import (
|
||||
Summarizer,
|
||||
extractive_summary,
|
||||
split_sentences,
|
||||
)
|
||||
|
||||
_DOC = (
|
||||
"홍길동은 조선시대 의적이었다. 그는 활빈당을 만들어 탐관오리의 재물을 빼앗았다. "
|
||||
"빼앗은 재물은 가난한 백성들에게 나누어 주었다. 홍길동은 둔갑술과 도술에 능했다. "
|
||||
"조정에서는 그를 잡으려 했으나 번번이 실패했다. 결국 홍길동은 율도국으로 떠나 새 나라를 세웠다. "
|
||||
"오늘 날씨는 맑고 화창하다. 점심으로 김밥을 먹었다."
|
||||
)
|
||||
|
||||
|
||||
def test_split_sentences():
|
||||
sents = split_sentences("첫 문장이다. 둘째 문장이다! 셋째 문장인가?")
|
||||
assert len(sents) == 3
|
||||
|
||||
|
||||
def test_extractive_summary_shortens():
|
||||
result = extractive_summary(_DOC, ratio=0.4)
|
||||
assert result.num_sentences_in == 8
|
||||
assert 0 < result.num_sentences_out < result.num_sentences_in
|
||||
assert result.mode == "extractive"
|
||||
assert result.final == result.extractive
|
||||
|
||||
|
||||
def test_extractive_preserves_source_order():
|
||||
result = extractive_summary(_DOC, ratio=0.5)
|
||||
# 선택된 인덱스는 원문 등장 순서여야 함 (가독성)
|
||||
assert result.selected_indices == sorted(result.selected_indices)
|
||||
|
||||
|
||||
def test_extractive_picks_central_over_offtopic():
|
||||
"""본문 핵심(홍길동 서사)이 무관한 문장(날씨/점심)보다 우선 선택."""
|
||||
result = extractive_summary(_DOC, ratio=0.4)
|
||||
text = result.extractive
|
||||
assert "홍길동" in text
|
||||
# 마지막 두 무관 문장은 덜 선택되어야 함
|
||||
assert not ("김밥" in text and "날씨" in text)
|
||||
|
||||
|
||||
def test_max_sentences_cap():
|
||||
result = extractive_summary(_DOC, ratio=1.0, max_sentences=2)
|
||||
assert result.num_sentences_out <= 2
|
||||
|
||||
|
||||
def test_empty_and_short():
|
||||
assert extractive_summary("").final == ""
|
||||
one = extractive_summary("한 문장만 있다.")
|
||||
assert one.final == "한 문장만 있다."
|
||||
|
||||
|
||||
def test_summarizer_without_llm_is_extractive():
|
||||
"""LLM 비활성 시 통합 요청도 추출적 결과를 반환 (외부 의존 0 폴백)."""
|
||||
settings = Settings(use_llm_extractor=False, openai_api_key="", use_kosimcse=False)
|
||||
result = Summarizer(settings).summarize(_DOC, ratio=0.4, use_abstractive=True)
|
||||
assert result.mode == "extractive"
|
||||
assert result.abstractive is None
|
||||
assert result.final
|
||||
Reference in new issue
Block a user