Files
C.E.L_Slide_test2/tests/matching/phase9.py
T

157 lines
5.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Phase 9 — 제목 포함 + 가중치 3배 적용 후 8개 핵심 방법 재돌림
변경사항 (vs Phase 1~8):
1. MDX 유닛: 중목차 제목을 본문 맨 앞에 3번 반복 (TF-IDF/BM25에서 자동 가중)
2. Figma texts.md: 메타 헤더(Frame ID, 구조 라벨) 제거 + 타이틀 3번 반복
8개 방법:
1. TF-IDF
2. Char 3-gram
3. Kiwi+BM25
4. Distinctive-Kiwi (공통어 제거)
5. 청킹+SBERT
6. 청킹+E5
7. Cross (ko-reranker)
8. BM25 → Cross rerank (Phase 7 winner)
"""
import sys
import json
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
from common import load_figma_texts
from extract_units import extract_units
from methods import (
method_tfidf, method_char_ngram, method_kiwi_bm25,
method_distinctive_kiwi,
method_sbert_chunk, method_e5_chunk, method_cross_encoder,
method_hybrid_bm25_cross,
)
ROOT = Path(r"d:\ad-hoc\kei\design_agent")
PREVIEW_DIR = ROOT / "data" / "figma_previews"
TARGET_UNITS = [
("MDX01-2-details", "1. (MDX 1) 팝업 — DX와 BIM의 구분", "18"),
("MDX02-2.2-table", "2. (MDX 2) 2.2 DX 시행 주체별 기대효과", "14"),
("MDX03-1", "3. (MDX 03) 1. DX 시행을 위한 필수요건", "13"),
("MDX03-2", "4. (MDX 03) 2. Process 혁신과 Product 변화", "29"),
]
def short_id(fid, frame_to_short):
return frame_to_short.get(str(fid), "?")
def main():
units = extract_units() # 제목 포함 버전
figma = load_figma_texts() # 메타 제거 + 타이틀 가중 버전
with open(PREVIEW_DIR / "index.json", encoding="utf-8") as f:
idx_data = json.load(f)
frame_to_short = {info["frame_id"]: sid for sid, info in idx_data.items()}
methods = [
("TF-IDF", method_tfidf),
("Char 3-gram", method_char_ngram),
("Kiwi+BM25", method_kiwi_bm25),
("Distinctive-Kiwi", method_distinctive_kiwi),
("청킹+SBERT", method_sbert_chunk),
("청킹+E5", method_e5_chunk),
("Cross", method_cross_encoder),
("BM25 → Cross rerank", lambda m, f: method_hybrid_bm25_cross(m, f, top_k=5)),
]
print("[Phase 9] 제목 포함 + 가중치 3배 적용")
print()
print("MDX03-1 텍스트 앞부분:")
print(units["MDX03-1"][:120])
print()
print("=" * 70)
print("8개 방법 × 4개 유닛 — 1순위 정답률")
print("=" * 70)
strategy_results = {}
for sname, fn in methods:
top3_by = {}
results = []
for uid, _, correct_id in TARGET_UNITS:
text = units[uid]
try:
ranked = fn(text, figma)
top3 = [short_id(fid, frame_to_short) for fid, _ in ranked[:3]]
except Exception as e:
top3 = ["ERR", "-", "-"]
print(f"ERR {sname} {uid}: {e}")
top3_by[uid] = top3
results.append(top3[0] == correct_id)
strategy_results[sname] = (results, top3_by)
marks = ["✓" if r else "✗" for r in results]
score = sum(results)
print(f" {sname:28s} {' '.join(marks)} = {score}/4")
# MD 리포트
png_rel = "../../data/figma_previews/"
lines = []
lines.append("# Phase 9 — 제목 포함 + 가중치 3배 후 8개 방법 재평가")
lines.append("")
lines.append("**수정사항:**")
lines.append("- MDX 유닛: 중목차 제목을 본문 앞에 3번 반복 (TF-IDF/BM25 자동 가중)")
lines.append("- Figma texts.md: 메타 헤더/구조 라벨 제거 + 타이틀 3번 반복")
lines.append("")
lines.append("**예시 — MDX03-1 텍스트 앞부분:**")
lines.append("```")
lines.append(units["MDX03-1"][:150])
lines.append("```")
lines.append("")
lines.append("### 8개 방법 × 4개 유닛 — 1순위 정답률")
lines.append("")
lines.append("| 방법 | MDX1 팝업(18) | MDX2 2.2(14) | MDX03-1(13) | MDX03-2(29) | 합계 |")
lines.append("|------|---------------|--------------|-------------|-------------|------|")
for sname, _ in methods:
results, top3_by = strategy_results[sname]
marks = []
for idx, (uid, _, correct_id) in enumerate(TARGET_UNITS):
t3 = top3_by[uid]
mark = "✓" if results[idx] else f"✗({t3[0]})"
marks.append(mark)
score = sum(results)
lines.append(f"| {sname} | {marks[0]} | {marks[1]} | {marks[2]} | {marks[3]} | **{score}/4** |")
lines.append("")
# 유닛별 Top-3 상세
lines.append("---")
lines.append("")
lines.append("## 유닛별 전략 Top-3 상세")
lines.append("")
for uid, display, correct_id in TARGET_UNITS:
lines.append(f"### {display} — 정답 Frame **{correct_id}**")
lines.append("")
lines.append("| 방법 | 1순위 | 2순위 | 3순위 |")
lines.append("|------|-------|-------|-------|")
for sname, _ in methods:
_, top3_by = strategy_results[sname]
t3 = top3_by[uid]
row = [sname]
for sid in t3:
info = idx_data.get(sid, {})
png = info.get("png", "")
title = info.get("title_text", "").strip().replace("\n", " ") or ""
if len(title) > 15:
title = title[:15] + "…"
mark = "⭐ " if sid == correct_id else ""
cell = f"{mark}![{sid}]({png_rel}{png})<br>**{sid}**<br>{title}"
row.append(cell)
lines.append("| " + " | ".join(row) + " |")
lines.append("")
out_path = Path(__file__).parent / "MATRIX_PHASE9.md"
out_path.write_text("\n".join(lines), encoding="utf-8")
print(f"\n완료: {out_path}")
if __name__ == "__main__":
main()