feat: add summary (No.7) consensus and grounded generation trials

요약 성능지표(No.7, ROUGE 65점) 실험 일습을 커밋한다.

- app/engine/summary_consensus.py: 후보 5개 생성 후 합의 선택(select_consensus).
  문자/어절 2-gram 가중 합의로 고르며, 유효 후보가 없으면 valid=False 를 낸다.
- app/engine/summary_grounded.py: 근거 추출 후 압축하는 2단계 생성.
- summarizer.py: 추출 전략 3종(textrank/coverage/lead). coverage 는 MMR 로
  중복 문장을 눌러 문서 전체를 넓게 담는다. 기본값은 textrank 로 유지한다.

스크립트는 생성·평가·검증을 분리했다. verify_* 는 API 호출 없이 저장된 산출물만
재계산하는 독립 검증기라 지표를 공용 함수로 합치지 않는다. 합치면 검증이 성립하지
않는다. tune_summarizer 는 사람 검수 참조(build_summary_annotation_packet ->
export_summary_annotations)를 입력으로 받아 선택과 최종 보고를 분리한다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5 committed 2026-09-28 10:02:04 +09:00
1 parent d980f34388
commit 8ae52b0a82
18 files changed
+1281 -3

No files matched your search

+65 -2
View File
@@ -31,6 +31,7 @@ from app.engine.structural import extract_lemmas
logger = logging.getLogger(__name__)
DETAIL_RATIOS = {"brief": 0.2, "standard": 0.3, "detailed": 0.45}
EXTRACTIVE_STRATEGIES = {"textrank", "coverage", "lead"}
# 문장 분할 — 종결부호 기준 (한국어 '다./요./까?/!' + 줄바꿈)
_SENT_SPLIT = re.compile(r"(?<=[.!?。…])\s+|\n+")
@@ -86,6 +87,59 @@ def _textrank_scores(vectors: list[Counter], damping: float = 0.85, iters: int =
return scores
def _normalize(scores: list[float]) -> list[float]:
"""0~1 정규화. 모든 값이 같으면 동률로 취급한다."""
if not scores:
return []
low, high = min(scores), max(scores)
if high - low < 1e-12:
return [1.0] * len(scores)
return [(score - low) / (high - low) for score in scores]
def _coverage_scores(sentences: list[str], vectors: list[Counter]) -> list[float]:
"""문서의 고유 내용어를 넓게 담는 문장을 우선하는 점수.
TextRank만 쓰면 같은 사건을 반복하는 문장이 상위를 독점할 수 있다. 이 점수는
문서 전체에서 드문 내용어(인물·사건·시간 등)가 든 문장을 높게 평가하고, 선택
단계에서 이미 선택한 문장과의 중복을 감점한다. 외부 모델이나 정답셋을 보지 않는
순수 추출 방식이다.
"""
document_frequency: Counter = Counter()
for vector in vectors:
document_frequency.update(vector.keys())
n = max(1, len(sentences))
lexical = [
sum(count * math.log((n + 1) / (document_frequency[token] + 0.5))
for token, count in vector.items()) / max(1, sum(vector.values()))
for vector in vectors
]
# 회고록·에피소드 형식에서는 첫 문장이 사건의 맥락을 잡는 경우가 많다. 단,
# 위치만으로 결정되지 않게 작은 사전 등록 가중치만 둔다.
position = [1.0 - (index / max(1, n - 1)) * 0.35 for index in range(n)]
centrality = _normalize(_textrank_scores(vectors))
lexical = _normalize(lexical)
return [0.50 * c + 0.38 * l + 0.12 * p
for c, l, p in zip(centrality, lexical, position)]
def _coverage_select(vectors: list[Counter], base_scores: list[float], k: int) -> list[int]:
"""MMR 방식으로 중요하면서 서로 다른 정보를 담는 문장 k개를 고른다."""
chosen: list[int] = []
remaining = set(range(len(vectors)))
while remaining and len(chosen) < k:
def candidate_score(index: int) -> tuple[float, float, int]:
redundancy = max((_cosine(vectors[index], vectors[other]) for other in chosen), default=0.0)
# 중복 문장은 낮추되, 낮은 중요도의 문장이 끼어들 정도로 과도하게 벌주진 않는다.
value = base_scores[index] - 0.22 * redundancy
return (value, base_scores[index], -index)
best = max(remaining, key=candidate_score)
chosen.append(best)
remaining.remove(best)
return chosen
@dataclass
class SummaryResult:
extractive: str # 추출적 요약 (선택된 원문 문장)
@@ -105,6 +159,7 @@ def extractive_summary(
max_sentences: int | None = None,
emphasis: list[str] | None = None,
detail: str = "standard",
strategy: str = "textrank",
) -> SummaryResult:
"""비지도 추출적 요약 — 정답셋/LLM/외부호출 불필요."""
sentences = split_sentences(text)
@@ -123,8 +178,13 @@ def extractive_summary(
if max_sentences is not None:
k = min(k, max_sentences)
if strategy not in EXTRACTIVE_STRATEGIES:
raise ValueError("strategy must be one of %s" % sorted(EXTRACTIVE_STRATEGIES))
vectors = [_lemma_vector(s) for s in sentences]
scores = _textrank_scores(vectors)
scores = _textrank_scores(vectors) if strategy == "textrank" else _coverage_scores(sentences, vectors)
if strategy == "lead":
scores = [float(n - index) for index in range(n)]
# 사용자가 지정한 주제를 포함한 문장에 명시적 가중치를 준다.
# TextRank 중심성은 유지하되 강조 요청이 상위 선택에 반영되도록 한다.
@@ -135,7 +195,8 @@ def extractive_summary(
scores[i] += 2.0 * matched / len(lowered_terms)
# 상위 k개 문장 선택 → 원문 등장 순서로 재정렬 (가독성)
top = sorted(range(n), key=lambda i: scores[i], reverse=True)[:k]
top = (_coverage_select(vectors, scores, k) if strategy == "coverage"
else sorted(range(n), key=lambda i: scores[i], reverse=True)[:k])
top_sorted = sorted(top)
summary = " ".join(sentences[i] for i in top_sorted)
return SummaryResult(
@@ -177,6 +238,7 @@ class Summarizer:
use_abstractive: bool = True,
detail: str = "standard",
emphasis: list[str] | None = None,
strategy: str = "textrank",
) -> SummaryResult:
effective_ratio = ratio if ratio is not None else DETAIL_RATIOS.get(detail, 0.3)
base = extractive_summary(
@@ -185,6 +247,7 @@ class Summarizer:
max_sentences=max_sentences,
emphasis=emphasis,
detail=detail,
strategy=strategy,
)
if not base.extractive:
return base