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:
1 parent
d980f34388
commit
8ae52b0a82
18 files changed
+1281
-3
No files matched your search
@@ -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
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Source-only short-summary consensus; never accepts reference summaries."""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections import Counter
|
||||
|
||||
SHORT_SUMMARY_PROMPT = (
|
||||
"다음 전기 문단의 중심 사건 또는 주제를 한국어 한 문장, 50자 이내로 요약하세요. "
|
||||
"핵심 인물과 행동 또는 원인·결과를 보존하고 원문의 표현을 가능한 한 유지하세요. "
|
||||
"배경 설명과 수식은 줄이고 원문에 없는 사실은 쓰지 마세요. 제목·목록 없이 요약만 출력하세요."
|
||||
)
|
||||
|
||||
|
||||
def character_f1(a: str, b: str) -> float:
|
||||
def grams(text):
|
||||
text = re.sub(r"\s+", "", text)
|
||||
return Counter(text[i:i + 2] for i in range(len(text) - 1))
|
||||
x, y = grams(a), grams(b)
|
||||
total = sum(x.values()) + sum(y.values())
|
||||
return 2 * sum((x & y).values()) / total if total else 0.0
|
||||
|
||||
|
||||
def word_f1(a: str, b: str) -> float:
|
||||
def grams(text):
|
||||
words = text.split()
|
||||
return Counter(zip(words, words[1:]))
|
||||
x, y = grams(a), grams(b)
|
||||
total = sum(x.values()) + sum(y.values())
|
||||
return 2 * sum((x & y).values()) / total if total else 0.0
|
||||
|
||||
|
||||
def select_consensus(summaries: list[str], word_weight: float = 0.0) -> int:
|
||||
"""Select a medoid among independently generated candidates, under 50 chars.
|
||||
|
||||
Consensus measures stability, not truth: systematic model errors can survive.
|
||||
Return -1 if all candidates are empty/overlength instead of silently truncating.
|
||||
"""
|
||||
if not 0 <= word_weight <= 1:
|
||||
raise ValueError("word_weight must be between 0 and 1")
|
||||
eligible = [i for i, s in enumerate(summaries) if s.strip() and len(s.strip()) <= 50]
|
||||
if not eligible:
|
||||
return -1
|
||||
return max(eligible, key=lambda i: (
|
||||
sum((1 - word_weight) * character_f1(summaries[i], summaries[j])
|
||||
+ word_weight * word_f1(summaries[i], summaries[j])
|
||||
for j in eligible if j != i), -i))
|
||||
|
||||
|
||||
def generate_candidates(client, text: str, count: int = 5) -> list[dict]:
|
||||
if not text.strip():
|
||||
raise ValueError("Source text must not be empty")
|
||||
if not 1 <= count <= 5:
|
||||
raise ValueError("Candidate count must be between 1 and 5")
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o", temperature=0.3, max_tokens=100, n=count,
|
||||
messages=[{"role": "system", "content": "당신은 텍스트 요약 전문가입니다."},
|
||||
{"role": "user", "content": SHORT_SUMMARY_PROMPT + "\n\n" + text}],
|
||||
)
|
||||
return [{"summary": (c.message.content or "").strip() if c.finish_reason == "stop" else "",
|
||||
"finish_reason": c.finish_reason, "model": response.model,
|
||||
"response_id": response.id} for c in response.choices]
|
||||
|
||||
|
||||
def summarize_short(client, text: str, word_weight: float = 0.0) -> dict:
|
||||
"""Opt-in 50-character summary; five completions incur additional API cost.
|
||||
|
||||
Return an explicit invalid result if no complete length-compliant summary exists.
|
||||
Callers should inspect valid, not silently present an empty result as success.
|
||||
"""
|
||||
candidates = generate_candidates(client, text)
|
||||
chosen = select_consensus([c["summary"] for c in candidates], word_weight=word_weight)
|
||||
return {"summary": candidates[chosen]["summary"] if chosen >= 0 else "",
|
||||
"valid": chosen >= 0, "selected_index": chosen,
|
||||
"strategy": "source_only_consensus5", "word_weight": word_weight,
|
||||
"candidates": candidates}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Experimental evidence extraction followed by short-summary compression."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from app.engine.summary_consensus import SHORT_SUMMARY_PROMPT, select_consensus
|
||||
|
||||
EVIDENCE_PROMPT = (
|
||||
"전기 문단 전체를 읽고 중심 인물·핵심 행동·결과를 가장 잘 드러내는 원문 구절을 고르세요. "
|
||||
"주변 묘사보다 문단의 중심 사건이나 논지를 우선하세요. 표현을 고쳐 쓰지 말고 "
|
||||
"원문에 연속해서 실제 존재하는 구절만 최대 3개, 각 120자 이내로 복사하세요. "
|
||||
'JSON 객체 {"evidence": ["구절1", "구절2"]}만 출력하세요.'
|
||||
)
|
||||
COMPRESSION_INSTRUCTION = (
|
||||
"아래 핵심 구절은 원문에서 검증한 보조 단서입니다. 반드시 원문 전체와 대조하세요. "
|
||||
"핵심 구절에 등장하는 인물명·명사·동사를 임의의 동의어로 치환하지 마세요. "
|
||||
"단서를 기계적으로 나열하지 말고 중심 사건과 결과를 자연스럽게 연결하세요."
|
||||
)
|
||||
|
||||
|
||||
def validated_evidence(text: str, payload: dict) -> list[str]:
|
||||
raw = payload.get("evidence", [])
|
||||
if not isinstance(raw, list):
|
||||
return []
|
||||
return list(dict.fromkeys(s.strip() for s in raw if isinstance(s, str)
|
||||
and 1 <= len(s.strip()) <= 120 and s.strip() in text))[:3]
|
||||
|
||||
|
||||
def generate_grounded(client, text: str, count: int = 5) -> dict:
|
||||
if not text.strip():
|
||||
raise ValueError("Source text must not be empty")
|
||||
if not 1 <= count <= 5:
|
||||
raise ValueError("Candidate count must be between 1 and 5")
|
||||
extraction = client.chat.completions.create(
|
||||
model="gpt-4o", temperature=0, max_tokens=400,
|
||||
response_format={"type": "json_object"},
|
||||
messages=[{"role": "system", "content": "원문에서 근거 구절을 정확히 추출하세요."},
|
||||
{"role": "user", "content": EVIDENCE_PROMPT + "\n\n" + text}],
|
||||
)
|
||||
evidence = []
|
||||
choice = extraction.choices[0]
|
||||
if choice.finish_reason == "stop":
|
||||
try:
|
||||
payload = json.loads(choice.message.content or "{}")
|
||||
evidence = validated_evidence(text, payload) if isinstance(payload, dict) else []
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
# Invalid extraction falls back to the full source; never invent evidence.
|
||||
prompt = SHORT_SUMMARY_PROMPT + "\n\n[원문]\n" + text
|
||||
if evidence:
|
||||
prompt += "\n\n" + COMPRESSION_INSTRUCTION + "\n[핵심 구절]\n" + "\n".join(evidence)
|
||||
response = client.chat.completions.create(
|
||||
model="gpt-4o", temperature=0.3, max_tokens=100, n=count,
|
||||
messages=[{"role": "system", "content": "당신은 텍스트 요약 전문가입니다."},
|
||||
{"role": "user", "content": prompt}],
|
||||
)
|
||||
candidates = [{"summary": (c.message.content or "").strip() if c.finish_reason == "stop" else "",
|
||||
"finish_reason": c.finish_reason, "model": response.model,
|
||||
"response_id": response.id} for c in response.choices]
|
||||
return {"evidence": evidence, "evidence_response_id": extraction.id,
|
||||
"evidence_model": extraction.model, "evidence_finish_reason": choice.finish_reason,
|
||||
"evidence_fallback": not bool(evidence), "candidates": candidates}
|
||||
|
||||
|
||||
def summarize_grounded(client, text: str) -> dict:
|
||||
generated = generate_grounded(client, text)
|
||||
index = select_consensus([c["summary"] for c in generated["candidates"]], word_weight=0.5)
|
||||
return {**generated, "selected_index": index, "valid": index >= 0,
|
||||
"summary": generated["candidates"][index]["summary"] if index >= 0 else ""}
|
||||
Reference in new issue
Block a user