feat: 수령 자서전 데이터 파이프라인과 맞춤 요약 추가
This commit is contained in:
1 parent
5386222f1b
commit
946e9e9474
17 files changed
+437
-48
No files matched your search
@@ -12,7 +12,8 @@
|
||||
자체 sLLM(고려대 2차저작 생성지원 모델) 으로 교체할 자리.
|
||||
③ 통합 요약 (hybrid) — ①의 핵심 문장을 ②의 입력으로 (계획서 통합 요약 시스템).
|
||||
|
||||
사용자 맞춤형 옵션(요약 길이/비율)은 계획서 2단계 '사용자 맞춤형 요약' 반영.
|
||||
사용자 맞춤형 옵션(요약 상세도/강조 주제)은 계획서 2단계
|
||||
'사용자 맞춤형 요약' 반영.
|
||||
|
||||
평가지표 No.7(N-gram ROUGE)는 scripts/eval_rouge.py 로 측정한다 (정답셋 들어오면).
|
||||
"""
|
||||
@@ -29,6 +30,8 @@ from app.engine.structural import extract_lemmas
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
DETAIL_RATIOS = {"brief": 0.2, "standard": 0.3, "detailed": 0.45}
|
||||
|
||||
# 문장 분할 — 종결부호 기준 (한국어 '다./요./까?/!' + 줄바꿈)
|
||||
_SENT_SPLIT = re.compile(r"(?<=[.!?。…])\s+|\n+")
|
||||
|
||||
@@ -92,17 +95,29 @@ class SummaryResult:
|
||||
mode: str # "extractive" | "hybrid"
|
||||
num_sentences_in: int
|
||||
num_sentences_out: int
|
||||
detail: str = "standard"
|
||||
emphasis: list[str] | None = None
|
||||
|
||||
|
||||
def extractive_summary(text: str, ratio: float = 0.3, max_sentences: int | None = None) -> SummaryResult:
|
||||
def extractive_summary(
|
||||
text: str,
|
||||
ratio: float = 0.3,
|
||||
max_sentences: int | None = None,
|
||||
emphasis: list[str] | None = None,
|
||||
detail: str = "standard",
|
||||
) -> SummaryResult:
|
||||
"""비지도 추출적 요약 — 정답셋/LLM/외부호출 불필요."""
|
||||
sentences = split_sentences(text)
|
||||
n = len(sentences)
|
||||
clean_emphasis = [term.strip() for term in (emphasis or []) if term.strip()]
|
||||
if n == 0:
|
||||
return SummaryResult("", None, "", [], "extractive", 0, 0)
|
||||
return SummaryResult("", None, "", [], "extractive", 0, 0, detail, clean_emphasis)
|
||||
if n <= 2:
|
||||
joined = " ".join(sentences)
|
||||
return SummaryResult(joined, None, joined, list(range(n)), "extractive", n, n)
|
||||
return SummaryResult(
|
||||
joined, None, joined, list(range(n)), "extractive", n, n,
|
||||
detail, clean_emphasis,
|
||||
)
|
||||
|
||||
k = max(1, math.ceil(n * ratio))
|
||||
if max_sentences is not None:
|
||||
@@ -111,6 +126,14 @@ def extractive_summary(text: str, ratio: float = 0.3, max_sentences: int | None
|
||||
vectors = [_lemma_vector(s) for s in sentences]
|
||||
scores = _textrank_scores(vectors)
|
||||
|
||||
# 사용자가 지정한 주제를 포함한 문장에 명시적 가중치를 준다.
|
||||
# TextRank 중심성은 유지하되 강조 요청이 상위 선택에 반영되도록 한다.
|
||||
if clean_emphasis:
|
||||
lowered_terms = [term.casefold() for term in clean_emphasis]
|
||||
for i, sentence in enumerate(sentences):
|
||||
matched = sum(term in sentence.casefold() for term in lowered_terms)
|
||||
scores[i] += 2.0 * matched / len(lowered_terms)
|
||||
|
||||
# 상위 k개 문장 선택 → 원문 등장 순서로 재정렬 (가독성)
|
||||
top = sorted(range(n), key=lambda i: scores[i], reverse=True)[:k]
|
||||
top_sorted = sorted(top)
|
||||
@@ -123,6 +146,8 @@ def extractive_summary(text: str, ratio: float = 0.3, max_sentences: int | None
|
||||
mode="extractive",
|
||||
num_sentences_in=n,
|
||||
num_sentences_out=len(top_sorted),
|
||||
detail=detail,
|
||||
emphasis=clean_emphasis,
|
||||
)
|
||||
|
||||
|
||||
@@ -147,16 +172,25 @@ class Summarizer:
|
||||
def summarize(
|
||||
self,
|
||||
text: str,
|
||||
ratio: float = 0.3,
|
||||
ratio: float | None = None,
|
||||
max_sentences: int | None = None,
|
||||
use_abstractive: bool = True,
|
||||
detail: str = "standard",
|
||||
emphasis: list[str] | None = None,
|
||||
) -> SummaryResult:
|
||||
base = extractive_summary(text, ratio=ratio, max_sentences=max_sentences)
|
||||
effective_ratio = ratio if ratio is not None else DETAIL_RATIOS.get(detail, 0.3)
|
||||
base = extractive_summary(
|
||||
text,
|
||||
ratio=effective_ratio,
|
||||
max_sentences=max_sentences,
|
||||
emphasis=emphasis,
|
||||
detail=detail,
|
||||
)
|
||||
if not base.extractive:
|
||||
return base
|
||||
|
||||
if use_abstractive and self.settings.use_llm_extractor and self.settings.has_openai:
|
||||
abstractive = self._abstractive(base.extractive)
|
||||
abstractive = self._abstractive(base.extractive, detail, emphasis or [])
|
||||
if abstractive:
|
||||
return SummaryResult(
|
||||
extractive=base.extractive,
|
||||
@@ -166,10 +200,14 @@ class Summarizer:
|
||||
mode="hybrid",
|
||||
num_sentences_in=base.num_sentences_in,
|
||||
num_sentences_out=base.num_sentences_out,
|
||||
detail=detail,
|
||||
emphasis=base.emphasis,
|
||||
)
|
||||
return base
|
||||
|
||||
def _abstractive(self, extractive_text: str) -> str | None:
|
||||
def _abstractive(
|
||||
self, extractive_text: str, detail: str, emphasis: list[str]
|
||||
) -> str | None:
|
||||
try:
|
||||
from openai import OpenAI
|
||||
client = OpenAI(api_key=self.settings.openai_api_key)
|
||||
@@ -178,7 +216,15 @@ class Summarizer:
|
||||
temperature=0.2,
|
||||
messages=[
|
||||
{"role": "system", "content": "You are a concise Korean summarizer. Never hallucinate."},
|
||||
{"role": "user", "content": _ABSTRACTIVE_PROMPT + extractive_text},
|
||||
{
|
||||
"role": "user",
|
||||
"content": (
|
||||
_ABSTRACTIVE_PROMPT
|
||||
+ extractive_text
|
||||
+ f"\n\n[\uC0C1세도] {detail}"
|
||||
+ (f"\n[\uAC15조 주제] {', '.join(emphasis)}" if emphasis else "")
|
||||
),
|
||||
},
|
||||
],
|
||||
)
|
||||
return (resp.choices[0].message.content or "").strip() or None
|
||||
|
||||
Reference in new issue
Block a user