feat: 수령 자서전 데이터 파이프라인과 맞춤 요약 추가

This commit is contained in:
HyeongBaeYang committed 2026-08-20 16:59:17 +09:00
1 parent 5386222f1b
commit 946e9e9474
17 files changed
+437 -48

No files matched your search

+57 -7
View File
@@ -39,6 +39,7 @@ import csv
import hashlib
import json
import logging
import os
import re
import sys
import unicodedata
@@ -49,6 +50,8 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from app.engine.training_data import pseudonymous_id, redact_direct_identifiers # noqa: E402
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
logger = logging.getLogger("build-ai-dataset")
@@ -57,7 +60,7 @@ LABEL_AI = 1
#: 헤더 자동탐지 힌트 (부분일치, 소문자 비교). 실제 파일을 못 본 상태라
#: 오탐 가능성이 있으니 --inspect 로 먼저 확인하고 --text-column 으로 고정할 것.
TEXT_HINTS = ("에피소드", "본문", "내용", "원고", "텍스트", "story", "text", "body", "content")
TEXT_HINTS = ("본문", "에피소드", "내용", "원고", "텍스트", "story", "text", "body", "content")
BOOK_HINTS = ("도서", "책", "서명", "제목", "book", "title", "작품")
ID_HINTS = ("id", "번호", "no", "식별")
AUTHOR_HINTS = ("저자", "작가", "author", "writer")
@@ -178,6 +181,9 @@ def load_human_from_xlsx(
id_column: str | None,
sheet: str | None,
min_chars: int,
group_column: str | None = None,
anonymization_salt: str | None = None,
provenance: str = "unknown",
) -> list[Record]:
wb = _load_workbook(path)
sheets = [sheet] if sheet else wb.sheetnames
@@ -202,11 +208,13 @@ def load_human_from_xlsx(
bcol = book_column or _match_column(header, BOOK_HINTS)
icol = id_column or _match_column(header, ID_HINTS)
acol = _match_column(header, AUTHOR_HINTS)
gcol = group_column or acol or icol or bcol
ti = header.index(tcol)
bi = header.index(bcol) if bcol in header else None
ii = header.index(icol) if icol in header else None
ai = header.index(acol) if acol in header else None
gi = header.index(gcol) if gcol in header else None
logger.info(
"[%s] text=%r book=%r id=%r author=%r", name, tcol, bcol, icol, acol
@@ -216,22 +224,48 @@ def load_human_from_xlsx(
if ti >= len(row):
continue
text = normalize(row[ti] if row[ti] is not None else "")
if anonymization_salt:
text = redact_direct_identifiers(text)
if len(text) < min_chars:
continue
book = ""
if bi is not None and bi < len(row) and row[bi] is not None:
book = str(row[bi]).strip()
# 책 정보가 없으면 시트명으로라도 묶는다. group 없는 분할은 금지.
group = f"book:{book}" if book else f"sheet:{name}"
meta = {"sheet": name, "row": rownum, "source_file": path.name}
raw_group = ""
if gi is not None and gi < len(row) and row[gi] is not None:
raw_group = str(row[gi]).strip()
if anonymization_salt and raw_group:
group = pseudonymous_id(raw_group, anonymization_salt)
elif raw_group:
group = f"source:{raw_group}"
else:
group = f"sheet:{name}"
meta = {
"sheet": name,
"row": rownum,
"source_file": path.name,
"provenance": provenance,
"human_verified": True,
"ai_assistance": False,
}
if ii is not None and ii < len(row) and row[ii] is not None:
meta["row_id"] = str(row[ii]).strip()
raw_id = str(row[ii]).strip()
if anonymization_salt:
meta["row_id_hash"] = pseudonymous_id(raw_id, anonymization_salt)
else:
meta["row_id"] = raw_id
if ai is not None and ai < len(row) and row[ai] is not None:
meta["author"] = str(row[ai]).strip()
raw_author = str(row[ai]).strip()
if anonymization_salt:
meta["author_hash"] = pseudonymous_id(raw_author, anonymization_salt)
else:
meta["author"] = raw_author
records.append(
Record(
text=text, label=LABEL_HUMAN, origin="human",
source_group=group, book=book, meta=meta,
source_group=group,
book="" if anonymization_salt else book,
meta=meta,
)
)
wb.close()
@@ -410,6 +444,12 @@ def main() -> int:
ap.add_argument("--text-column", default=None, help="본문 컬럼명 (미지정 시 자동탐지)")
ap.add_argument("--book-column", default=None, help="도서 컬럼명 (분할 그룹 기준)")
ap.add_argument("--id-column", default=None, help="행 식별자 컬럼명")
ap.add_argument("--group-column", default=None,
help="분할 그룹 컬럼. 자서전.net은 id를 지정해 작성자 누출 방지")
ap.add_argument("--anonymize", action="store_true",
help="그룹/행 ID를 HMAC 가명화하고 본문의 직접 식별자를 제거")
ap.add_argument("--anonymization-salt-env", default="DATA_ANONYMIZATION_SALT")
ap.add_argument("--human-provenance", default="combooks_confirmed_human")
ap.add_argument("--ai-jsonl", type=Path, action="append", default=[], help="AI 샘플 JSONL (반복 가능)")
ap.add_argument("--ai-csv", type=Path, action="append", default=[], help="AI 샘플 CSV (반복 가능)")
ap.add_argument("--ai-text-field", default="text", help="AI 파일의 본문 필드명")
@@ -430,6 +470,15 @@ def main() -> int:
return 0
records: list[Record] = []
anonymization_salt = None
if args.anonymize:
anonymization_salt = os.environ.get(args.anonymization_salt_env, "")
if not anonymization_salt:
logger.error(
"--anonymize 사용 시 %s 환경변수가 필요합니다.",
args.anonymization_salt_env,
)
return 2
if args.xlsx:
if not args.xlsx.exists():
logger.error("xlsx 없음: %s", args.xlsx)
@@ -437,6 +486,7 @@ def main() -> int:
records += load_human_from_xlsx(
args.xlsx, args.text_column, args.book_column,
args.id_column, args.sheet, args.min_chars,
args.group_column, anonymization_salt, args.human_provenance,
)
jsonl = [p for p in args.ai_jsonl if p.exists()]
+1 -1
View File
@@ -81,7 +81,7 @@ def main() -> int:
print()
print("=" * 60)
print(f"전체 정밀도 (precision): {precision:.4f} (목표 0.95)")
print(f"전체 정밀도 (precision): {precision:.4f} (계획서 목표 0.97)")
print(f"재현율 (recall): {recall:.4f}")
print(f"F1: {f1:.4f}")
print(f"TP={tp} FP={fp} TN={tn} FN={fn}")
+45 -6
View File
@@ -61,6 +61,7 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(mes
logger = logging.getLogger("gen-ai-samples")
from app.engine.ocr_normalize import normalize_ocr # noqa: E402
from app.engine.training_data import pseudonymous_id, sanitize_prompt_metadata # noqa: E402
#: 프롬프트에 쓸 수 있는 컬럼. 본문 컬럼은 의도적으로 목록에 없다.
META_COLUMNS = (
@@ -70,7 +71,8 @@ META_COLUMNS = (
"gpt_character_keyword",
"생애사건_category",
)
TEXT_COLUMN_BLOCKLIST = ("에피소드", "본문", "내용", "원고", "text", "content")
TEXT_COLUMN_BLOCKLIST = ("본문", "내용", "원고", "text", "content", "body")
TEXT_COLUMN_EXACT_BLOCKLIST = ("에피소드", "story")
SYSTEM_PROMPT = (
"당신은 한국어 자서전 원고를 쓰는 작가다. 주어진 소재로 자서전의 한 "
@@ -99,8 +101,11 @@ def assert_no_body_columns(columns: list[str]) -> list[str]:
주석만으로는 다음 사람이 META_COLUMNS 에 본문 컬럼을 한 줄 추가하는 것을
못 막는다. 그 한 줄이 원고를 외부 API 로 내보내는 경로가 된다.
"""
leaked = [c for c in columns
if any(bad in c.lower() for bad in TEXT_COLUMN_BLOCKLIST)]
leaked = [
c for c in columns
if c.strip().lower() in TEXT_COLUMN_EXACT_BLOCKLIST
or any(bad in c.lower() for bad in TEXT_COLUMN_BLOCKLIST)
]
if leaked:
raise SystemExit(
f"본문으로 보이는 컬럼이 프롬프트 소재에 있습니다: {leaked}. "
@@ -158,6 +163,15 @@ def main() -> int:
ap.add_argument("--xlsx", type=Path, required=True, help="소재를 뽑을 에피소드 xlsx")
ap.add_argument("--text-column", default="에피소드",
help="길이 분포 계산에만 쓴다. 본문은 API 로 보내지 않는다.")
ap.add_argument(
"--meta-column", action="append", default=[],
help="프롬프트 소재 컬럼(반복 지정). 제목·키워드만 허용하며 본문은 차단",
)
ap.add_argument(
"--group-column", default=None,
help="human과 같은 작성자 그룹으로 묶을 컬럼(원본값은 저장·전송하지 않음)",
)
ap.add_argument("--group-salt-env", default="DATA_ANONYMIZATION_SALT")
ap.add_argument("--model", action="append", default=[],
help="생성 모델 (반복 지정 = 혼합). 최소 2개 권장")
ap.add_argument("--base-url", default=None,
@@ -179,13 +193,26 @@ def main() -> int:
lengths[len(lengths) // 2], low_chars, high_chars, len(lengths),
)
usable_meta = assert_no_body_columns([c for c in META_COLUMNS if c in frame.columns])
requested_meta = args.meta_column or [c for c in META_COLUMNS if c in frame.columns]
missing_meta = [c for c in requested_meta if c not in frame.columns]
if missing_meta:
raise SystemExit(f"프롬프트 소재 컬럼이 없습니다: {missing_meta}")
usable_meta = assert_no_body_columns(requested_meta)
if not usable_meta:
raise SystemExit(
f"소재로 쓸 컬럼이 없습니다. 기대: {META_COLUMNS} / 실제: {list(frame.columns)}"
)
logger.info("프롬프트 소재 컬럼: %s", usable_meta)
group_salt = os.environ.get(args.group_salt_env, "")
if args.group_column:
if args.group_column not in frame.columns:
raise SystemExit(f"그룹 컬럼이 없습니다: {args.group_column}")
if not group_salt:
raise SystemExit(
f"--group-column 사용 시 {args.group_salt_env} 환경변수가 필요합니다."
)
models = args.model or ["gpt-4o-mini"]
if len(models) == 1 and not args.dry_run:
logger.warning(
@@ -229,11 +256,20 @@ def main() -> int:
if prompt_id in done:
continue
meta = {c: str(frame[c].iloc[idx]) for c in usable_meta
if isinstance(frame[c].iloc[idx], str) and frame[c].iloc[idx].strip()}
meta = {
c: sanitize_prompt_metadata(str(frame[c].iloc[idx]))
for c in usable_meta
if isinstance(frame[c].iloc[idx], str) and frame[c].iloc[idx].strip()
}
if not meta:
continue
source_group = f"ai-topic:{prompt_id}"
if args.group_column:
raw_group = str(frame[args.group_column].iloc[idx] or "").strip()
if raw_group and raw_group.lower() != "nan":
source_group = pseudonymous_id(raw_group, group_salt)
target = rng.choice(lengths)
style = STYLE_VARIANTS[_stable_int(prompt_id) % len(STYLE_VARIANTS)]
model = models[attempted % len(models)]
@@ -276,6 +312,9 @@ def main() -> int:
"target_chars": target,
"char_count": len(text),
"style": style,
"source_group": source_group,
"generation_type": "pure_ai",
"provenance": "ai_generated_controlled",
"meta": meta,
}, ensure_ascii=False) + "\n")
sink.flush() # 중간에 죽어도 여기까지는 남는다
+1 -1
View File
@@ -12,7 +12,7 @@
"is_plagiarism": true, "original_excerpt": "...", "derived_text": "..."}
자체 평가 데이터셋(계획서 성능지표 #4) 용도. 운영 모델 학습 시
이 데이터와 컴북스 보유 30,000 건 원천 자료를 결합하여 정밀도 95% 달성.
이 데이터와 컴북스 보유 원천 자료를 결합하여 계획서 목표 정밀도 97% 달성.
사용:
export OPENAI_API_KEY=sk-...
+59 -8
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import argparse
import json
import os
import sys
from collections import Counter
from pathlib import Path
@@ -13,6 +14,11 @@ if __package__ in (None, ""):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.engine.provenance import CorpusStore, DocumentRecord, SegmentRecord, stable_id
from app.engine.training_data import (
pseudonymous_id,
redact_direct_identifiers,
sanitize_prompt_metadata,
)
def parse_args() -> argparse.Namespace:
@@ -23,7 +29,14 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--book-column", default="book_name")
p.add_argument("--text-column", default="에피소드")
p.add_argument("--index-column", default="episode_index")
p.add_argument("--author-column", default=None,
help="작성자 그룹 컬럼. 지정하면 같은 작성자의 여러 자서전을 함께 묶는다")
p.add_argument("--episode-title-column", default=None)
p.add_argument("--path-column", default="json_path")
p.add_argument("--anonymize", action="store_true",
help="작성자·책 제목을 가명화하고 본문의 직접 식별자를 제거")
p.add_argument("--anonymization-salt-env", default="DATA_ANONYMIZATION_SALT")
p.add_argument("--provenance", default="combooks_confirmed_human")
return p.parse_args()
@@ -43,7 +56,9 @@ def main() -> int:
rows = ws.iter_rows(values_only=True)
headers = [str(v).strip() if v is not None else "" for v in next(rows)]
positions = {name: i for i, name in enumerate(headers)}
required = [args.book_column, args.text_column, args.index_column]
required = [args.book_column, args.text_column]
if args.author_column:
required.append(args.author_column)
missing = [name for name in required if name not in positions]
if missing:
print(f"필수 열 없음: {missing}; 실제 열={headers}", file=sys.stderr)
@@ -55,24 +70,54 @@ def main() -> int:
book_counts: Counter[str] = Counter()
documents: dict[str, DocumentRecord] = {}
segments: list[SegmentRecord] = []
salt = os.environ.get(args.anonymization_salt_env, "")
if args.anonymize and not salt:
print(
f"--anonymize 사용 시 {args.anonymization_salt_env} 환경변수가 필요합니다.",
file=sys.stderr,
)
return 2
for row in rows:
for rownum, row in enumerate(rows, start=2):
book = str(row[positions[args.book_column]] or "").strip()
text = str(row[positions[args.text_column]] or "").strip()
ordinal = str(row[positions[args.index_column]] or "").strip()
ordinal = str(row[positions[args.index_column]] or "").strip() \
if args.index_column in positions else str(rownum - 1)
if not book or not text:
skipped += 1
continue
author = ""
if args.author_column:
author = str(row[positions[args.author_column]] or "").strip()
raw_group = f"{author}\x1f{book}" if author else book
author_group = pseudonymous_id(author, salt) if args.anonymize and author else None
document_id = (
pseudonymous_id(raw_group, salt, prefix="doc")
if args.anonymize else stable_id("doc", raw_group)
)
display_title = f"익명 자서전 {document_id.split(':')[-1][:8]}" if args.anonymize else book
if args.anonymize:
text = redact_direct_identifiers(text)
source_path = None
if args.path_column in positions:
if args.path_column in positions and not args.anonymize:
source_path = str(row[positions[args.path_column]] or "").strip() or None
document_id = stable_id("doc", book)
documents[document_id] = DocumentRecord(
document_id=document_id,
title=book,
title=display_title,
source_path=source_path,
metadata={"import_source": args.xlsx.name},
metadata={
"import_source": args.xlsx.name,
"provenance": args.provenance,
"human_verified": True,
"ai_assistance": False,
**({"author_group": author_group} if author_group else {}),
},
)
episode_title = None
if args.episode_title_column in positions:
episode_title = str(row[positions[args.episode_title_column]] or "").strip() or None
if episode_title and args.anonymize:
episode_title = sanitize_prompt_metadata(episode_title)
segments.append(SegmentRecord(
segment_id=stable_id("seg", document_id, text),
document_id=document_id,
@@ -85,9 +130,13 @@ def main() -> int:
metadata={
"provenance_quality": "episode_only",
"page_offset_available": False,
"provenance": args.provenance,
"human_verified": True,
"ai_assistance": False,
**({"episode_title": episode_title} if episode_title else {}),
},
))
book_counts[book] += 1
book_counts[document_id] += 1
store.upsert_documents(documents.values())
inserted, duplicates = store.add_segments(segments)
@@ -99,6 +148,8 @@ def main() -> int:
"duplicate_segments": duplicates,
"skipped_rows": skipped,
"source_books": len(book_counts),
"anonymized": args.anonymize,
"provenance": args.provenance,
"store": store.stats(),
"location_warning": (
"수령 XLSX에는 원본 페이지/문단 offset이 없어 episode 좌표만 저장했습니다. "