agent_evaluator 0.5.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. agent_evaluator/__init__.py +144 -0
  2. agent_evaluator/cli/__init__.py +1 -0
  3. agent_evaluator/cli/main.py +863 -0
  4. agent_evaluator/config.py +297 -0
  5. agent_evaluator/core/__init__.py +57 -0
  6. agent_evaluator/core/agent_evaluator.py +5409 -0
  7. agent_evaluator/core/hybrid_monitor.py +1006 -0
  8. agent_evaluator/core/monitor_context.py +141 -0
  9. agent_evaluator/datasets/__init__.py +11 -0
  10. agent_evaluator/datasets/korean_rag_dataset_generator.py +858 -0
  11. agent_evaluator/datasets/korean_rag_evaluator.py +787 -0
  12. agent_evaluator/examples/__init__.py +8 -0
  13. agent_evaluator/examples/example_runner.py +168 -0
  14. agent_evaluator/helpers/__init__.py +67 -0
  15. agent_evaluator/helpers/taskresult_helpers.py +978 -0
  16. agent_evaluator/integrations/__init__.py +102 -0
  17. agent_evaluator/integrations/autogen_integration.py +305 -0
  18. agent_evaluator/integrations/crewai_integration.py +669 -0
  19. agent_evaluator/integrations/framework_integrations.py +197 -0
  20. agent_evaluator/integrations/langchain_integration.py +443 -0
  21. agent_evaluator/integrations/langgraph_integration.py +298 -0
  22. agent_evaluator/integrations/llm_helpers.py +321 -0
  23. agent_evaluator/integrations/metric_adapters.py +754 -0
  24. agent_evaluator/py.typed +0 -0
  25. agent_evaluator/reporting/__init__.py +9 -0
  26. agent_evaluator/reporting/comprehensive_report.py +1588 -0
  27. agent_evaluator/serve/__init__.py +1 -0
  28. agent_evaluator/serve/loader.py +653 -0
  29. agent_evaluator/serve/routers/__init__.py +1 -0
  30. agent_evaluator/serve/routers/config.py +57 -0
  31. agent_evaluator/serve/routers/data.py +156 -0
  32. agent_evaluator/serve/routers/export.py +186 -0
  33. agent_evaluator/serve/routers/golden.py +168 -0
  34. agent_evaluator/serve/routers/stream.py +57 -0
  35. agent_evaluator/serve/routers/transparency.py +206 -0
  36. agent_evaluator/serve/routers/webhook.py +56 -0
  37. agent_evaluator/serve/server.py +185 -0
  38. agent_evaluator/serve/templates/dashboard.html.j2 +4341 -0
  39. agent_evaluator/serve/templates/sdk_docs.html.j2 +1022 -0
  40. agent_evaluator/serve/templates/slides.html.j2 +711 -0
  41. agent_evaluator/serve/watcher.py +85 -0
  42. agent_evaluator/utils/__init__.py +23 -0
  43. agent_evaluator/utils/dashboard_integration.py +227 -0
  44. agent_evaluator/utils/data_registry.py +441 -0
  45. agent_evaluator/utils/path_helpers.py +128 -0
  46. agent_evaluator/utils/test_transparency_manager.py +1542 -0
  47. agent_evaluator-0.5.3.dist-info/METADATA +716 -0
  48. agent_evaluator-0.5.3.dist-info/RECORD +51 -0
  49. agent_evaluator-0.5.3.dist-info/WHEEL +4 -0
  50. agent_evaluator-0.5.3.dist-info/entry_points.txt +2 -0
  51. agent_evaluator-0.5.3.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,858 @@
1
+ """
2
+ Korean RAG Dataset Generator
3
+ =============================
4
+ 한국어 PDF 문서에서 RAG 평가를 위한 Ground Truth (Golden Data) 생성
5
+
6
+ 주요 기능:
7
+ - PDF 파일에서 한국어 텍스트 추출
8
+ - AI를 활용한 QA 쌍 자동 생성
9
+ - Faithfulness, Context Recall, Context Precision, Answer Relevancy 평가를 위한 데이터셋 구축
10
+ - Golden data 저장/로드 (JSON, CSV)
11
+ """
12
+
13
+ import json
14
+ import csv
15
+ import os
16
+ import re
17
+ from typing import List, Dict, Any, Optional, Tuple
18
+ from dataclasses import dataclass, asdict
19
+ from datetime import datetime
20
+ from pathlib import Path
21
+ import hashlib
22
+
23
+ # PDF 처리
24
+ try:
25
+ import PyPDF2
26
+ PDF_LIBRARY = "PyPDF2"
27
+ except ImportError:
28
+ try:
29
+ import pdfplumber
30
+ PDF_LIBRARY = "pdfplumber"
31
+ except ImportError:
32
+ PDF_LIBRARY = None
33
+
34
+ # OpenAI
35
+ try:
36
+ from openai import OpenAI
37
+ OPENAI_AVAILABLE = True
38
+ except ImportError:
39
+ OPENAI_AVAILABLE = False
40
+
41
+ # 기타 의존성
42
+ import pandas as pd
43
+ from dotenv import load_dotenv
44
+
45
+ # 환경 변수 로드
46
+ load_dotenv()
47
+
48
+
49
+ # ============================================================================
50
+ # Data Classes
51
+ # ============================================================================
52
+
53
+ @dataclass
54
+ class DocumentChunk:
55
+ """문서 청크 정보"""
56
+ chunk_id: str
57
+ content: str
58
+ page_number: int
59
+ chunk_index: int
60
+ metadata: Dict[str, Any]
61
+
62
+
63
+ @dataclass
64
+ class QAPair:
65
+ """질문-답변 쌍"""
66
+ qa_id: str
67
+ question: str
68
+ answer: str
69
+ context: str
70
+ ground_truth: str # 기대되는 정답
71
+ metadata: Dict[str, Any]
72
+
73
+ # Layer 2: Agentic AI Metrics 필드 (Optional)
74
+ expected_tools: Optional[List[str]] = None # Tool Selection 평가용
75
+ expected_agents: Optional[List[str]] = None # Agent Coordination 평가용
76
+ expected_workflow_steps: Optional[List[str]] = None # Workflow Execution 평가용
77
+
78
+
79
+ @dataclass
80
+ class GoldenDataset:
81
+ """Golden Dataset - RAG 평가용"""
82
+ dataset_id: str
83
+ source_document: str
84
+ created_at: str
85
+ total_qa_pairs: int
86
+ qa_pairs: List[QAPair]
87
+ metadata: Dict[str, Any]
88
+
89
+
90
+ # ============================================================================
91
+ # PDF Text Extractor
92
+ # ============================================================================
93
+
94
+ class KoreanPDFExtractor:
95
+ """한국어 PDF 텍스트 추출기"""
96
+
97
+ def __init__(self):
98
+ if PDF_LIBRARY is None:
99
+ raise ImportError(
100
+ "PDF 처리 라이브러리가 필요합니다. 다음 중 하나를 설치하세요:\n"
101
+ "pip install PyPDF2 또는 pip install pdfplumber"
102
+ )
103
+ self.library = PDF_LIBRARY
104
+
105
+ def extract_text(self, pdf_path: str) -> List[Tuple[int, str]]:
106
+ """
107
+ PDF에서 텍스트 추출
108
+
109
+ Args:
110
+ pdf_path: PDF 파일 경로
111
+
112
+ Returns:
113
+ List of (page_number, text) tuples
114
+ """
115
+ if not os.path.exists(pdf_path):
116
+ raise FileNotFoundError(f"PDF 파일을 찾을 수 없습니다: {pdf_path}")
117
+
118
+ if self.library == "PyPDF2":
119
+ return self._extract_with_pypdf2(pdf_path)
120
+ elif self.library == "pdfplumber":
121
+ return self._extract_with_pdfplumber(pdf_path)
122
+
123
+ def _extract_with_pypdf2(self, pdf_path: str) -> List[Tuple[int, str]]:
124
+ """PyPDF2를 사용한 텍스트 추출"""
125
+ import warnings
126
+
127
+ pages_text = []
128
+
129
+ # PyPDF2 경고 억제 (FontBBox 등)
130
+ with warnings.catch_warnings():
131
+ warnings.filterwarnings('ignore', category=UserWarning)
132
+
133
+ with open(pdf_path, 'rb') as file:
134
+ pdf_reader = PyPDF2.PdfReader(file)
135
+
136
+ for page_num, page in enumerate(pdf_reader.pages, 1):
137
+ text = page.extract_text()
138
+ if text.strip():
139
+ pages_text.append((page_num, text))
140
+
141
+ return pages_text
142
+
143
+ def _extract_with_pdfplumber(self, pdf_path: str) -> List[Tuple[int, str]]:
144
+ """pdfplumber를 사용한 텍스트 추출 (더 정확함)"""
145
+ import pdfplumber
146
+ import logging
147
+ import warnings
148
+
149
+ # Suppress FontBBox warnings from pdfminer
150
+ logging.getLogger('pdfminer').setLevel(logging.ERROR)
151
+
152
+ # Suppress all warnings during PDF processing
153
+ with warnings.catch_warnings():
154
+ warnings.simplefilter("ignore")
155
+
156
+ pages_text = []
157
+
158
+ with pdfplumber.open(pdf_path) as pdf:
159
+ for page_num, page in enumerate(pdf.pages, 1):
160
+ text = page.extract_text()
161
+ if text and text.strip():
162
+ pages_text.append((page_num, text))
163
+
164
+ return pages_text
165
+
166
+ def clean_text(self, text: str) -> str:
167
+ """텍스트 정제"""
168
+ # 여러 개의 연속된 공백을 하나로
169
+ text = re.sub(r'\s+', ' ', text)
170
+
171
+ # 여러 개의 연속된 줄바꿈을 최대 2개로
172
+ text = re.sub(r'\n{3,}', '\n\n', text)
173
+
174
+ # 앞뒤 공백 제거
175
+ text = text.strip()
176
+
177
+ return text
178
+
179
+
180
+ # ============================================================================
181
+ # Text Chunker
182
+ # ============================================================================
183
+
184
+ class TextChunker:
185
+ """텍스트 청킹 - 의미 단위로 분할"""
186
+
187
+ def __init__(self, chunk_size: int = 1000, chunk_overlap: int = 200):
188
+ """
189
+ Args:
190
+ chunk_size: 청크 크기 (문자 수)
191
+ chunk_overlap: 청크 간 겹침 (문자 수)
192
+ """
193
+ self.chunk_size = chunk_size
194
+ self.chunk_overlap = chunk_overlap
195
+
196
+ def chunk_documents(self, pages_text: List[Tuple[int, str]]) -> List[DocumentChunk]:
197
+ """문서를 청크로 분할"""
198
+ chunks = []
199
+ chunk_index = 0
200
+
201
+ for page_num, text in pages_text:
202
+ page_chunks = self._chunk_text(text, page_num)
203
+
204
+ for chunk_text in page_chunks:
205
+ chunk_id = self._generate_chunk_id(page_num, chunk_index, chunk_text)
206
+
207
+ chunk = DocumentChunk(
208
+ chunk_id=chunk_id,
209
+ content=chunk_text,
210
+ page_number=page_num,
211
+ chunk_index=chunk_index,
212
+ metadata={
213
+ "char_count": len(chunk_text),
214
+ "word_count": len(chunk_text.split())
215
+ }
216
+ )
217
+
218
+ chunks.append(chunk)
219
+ chunk_index += 1
220
+
221
+ return chunks
222
+
223
+ def _chunk_text(self, text: str, page_num: int) -> List[str]:
224
+ """텍스트를 청크로 분할"""
225
+ chunks = []
226
+ start = 0
227
+ text_length = len(text)
228
+
229
+ while start < text_length:
230
+ end = start + self.chunk_size
231
+
232
+ # 청크 경계를 문장 끝으로 조정
233
+ if end < text_length:
234
+ # 마침표, 느낌표, 물음표 등을 찾아서 조정
235
+ for punct in ['. ', '.\n', '! ', '!\n', '? ', '?\n', '。', '!', '?']:
236
+ punct_pos = text.rfind(punct, start, end)
237
+ if punct_pos != -1:
238
+ end = punct_pos + len(punct)
239
+ break
240
+
241
+ chunk = text[start:end].strip()
242
+ if chunk:
243
+ chunks.append(chunk)
244
+
245
+ # 다음 청크 시작 위치 (오버랩 고려)
246
+ start = end - self.chunk_overlap
247
+
248
+ return chunks
249
+
250
+ def _generate_chunk_id(self, page_num: int, chunk_index: int, text: str) -> str:
251
+ """청크 ID 생성"""
252
+ text_hash = hashlib.md5(text.encode()).hexdigest()[:8]
253
+ return f"chunk_p{page_num}_i{chunk_index}_{text_hash}"
254
+
255
+
256
+ # ============================================================================
257
+ # QA Pair Generator
258
+ # ============================================================================
259
+
260
+ class KoreanQAGenerator:
261
+ """한국어 QA 쌍 생성기 (OpenAI GPT 사용)"""
262
+
263
+ def __init__(self, api_key: Optional[str] = None, model: str = "gpt-4o-mini"):
264
+ """
265
+ Args:
266
+ api_key: OpenAI API 키 (없으면 환경 변수에서 가져옴)
267
+ model: 사용할 모델 (gpt-4o-mini, gpt-4o, gpt-3.5-turbo 등)
268
+ """
269
+ if not OPENAI_AVAILABLE:
270
+ raise ImportError("OpenAI 라이브러리가 필요합니다: pip install openai")
271
+
272
+ self.api_key = api_key or os.getenv("OPENAI_API_KEY")
273
+ if not self.api_key:
274
+ raise ValueError("OPENAI_API_KEY가 설정되지 않았습니다")
275
+
276
+ self.client = OpenAI(api_key=self.api_key)
277
+ self.model = model
278
+
279
+ def generate_qa_pairs(
280
+ self,
281
+ chunk: DocumentChunk,
282
+ num_questions: int = 3,
283
+ question_types: Optional[List[str]] = None
284
+ ) -> List[QAPair]:
285
+ """
286
+ 청크에서 QA 쌍 생성
287
+
288
+ Args:
289
+ chunk: 문서 청크
290
+ num_questions: 생성할 질문 수
291
+ question_types: 질문 유형 (factual, reasoning, summary 등)
292
+
293
+ Returns:
294
+ 생성된 QA 쌍 리스트
295
+ """
296
+ if question_types is None:
297
+ question_types = ["factual", "reasoning", "summary"]
298
+
299
+ prompt = self._build_prompt(chunk.content, num_questions, question_types)
300
+
301
+ try:
302
+ response = self.client.chat.completions.create(
303
+ model=self.model,
304
+ messages=[
305
+ {"role": "system", "content": "당신은 한국어 교육 자료를 만드는 전문가입니다."},
306
+ {"role": "user", "content": prompt}
307
+ ],
308
+ temperature=0.7,
309
+ max_tokens=2000
310
+ )
311
+
312
+ qa_pairs_text = response.choices[0].message.content
313
+ qa_pairs = self._parse_qa_pairs(qa_pairs_text, chunk)
314
+
315
+ return qa_pairs
316
+
317
+ except Exception as e:
318
+ print(f"⚠️ QA 생성 실패 (chunk_id: {chunk.chunk_id}): {str(e)}")
319
+ return []
320
+
321
+ def _build_prompt(self, context: str, num_questions: int, question_types: List[str]) -> str:
322
+ """프롬프트 생성"""
323
+ types_desc = {
324
+ "factual": "사실 확인 질문 (문서에 명시된 정보)",
325
+ "reasoning": "추론 질문 (문서 내용을 바탕으로 한 논리적 추론)",
326
+ "summary": "요약 질문 (문서의 주요 내용 요약)"
327
+ }
328
+
329
+ types_str = "\n".join([f"- {types_desc.get(t, t)}" for t in question_types])
330
+
331
+ prompt = f"""
332
+ 다음 한국어 문서 내용을 읽고, RAG 시스템 평가를 위한 고품질 질문-답변 쌍을 {num_questions}개 생성해주세요.
333
+
334
+ [문서 내용]
335
+ {context}
336
+
337
+ [요구사항]
338
+ 1. 질문 유형:
339
+ {types_str}
340
+
341
+ 2. 각 QA 쌍은 다음 형식으로 작성:
342
+ ---
343
+ 질문: [명확하고 구체적인 질문]
344
+ 답변: [문서 내용을 바탕으로 한 완전한 답변 (2-3문장)]
345
+ ground_truth: [평가를 위한 핵심 정답 (1-2문장, 간결하게)]
346
+ ---
347
+
348
+ 3. 답변은 반드시 주어진 문서 내용만을 기반으로 작성하세요.
349
+
350
+ 4. 질문은 자연스럽고 실제 사용자가 물어볼 법한 형태로 작성하세요.
351
+
352
+ 5. Ground truth는 RAG 시스템 평가를 위한 기준 답변입니다.
353
+
354
+ 6. **중요: 다음과 같은 질문은 절대 생성하지 마세요:**
355
+ ❌ 메타 정보 질문: "몇 페이지인가요?", "문서의 구조는?", "총 섹션은 몇 개인가요?"
356
+ ❌ 문서 외부 질문: "다른 도구와 비교하면?", "앞으로 어떻게 발전할까요?"
357
+ ❌ 추상적 질문: "이 기술의 미래는?", "왜 중요한가요?" (문서에 답이 없는 경우)
358
+ ✅ 문서 내용 질문: 구체적인 기능, 사용법, 개념, 절차, 예시 등
359
+
360
+ 7. **좋은 질문 예시:**
361
+ - "CrewAI에서 에이전트를 생성하는 방법은 무엇인가요?"
362
+ - "Task의 필수 파라미터에는 어떤 것들이 있나요?"
363
+ - "Sequential Process와 Hierarchical Process의 차이점은 무엇인가요?"
364
+
365
+ 생성해주세요:
366
+ """
367
+ return prompt
368
+
369
+ def _parse_qa_pairs(self, response_text: str, chunk: DocumentChunk) -> List[QAPair]:
370
+ """AI 응답에서 QA 쌍 파싱"""
371
+ qa_pairs = []
372
+
373
+ # "---"로 구분된 블록들을 찾기
374
+ blocks = response_text.split("---")
375
+
376
+ for i, block in enumerate(blocks):
377
+ if not block.strip():
378
+ continue
379
+
380
+ # 질문, 답변, ground_truth 추출
381
+ question_match = re.search(r'질문:\s*(.+?)(?=\n|답변:|$)', block, re.DOTALL)
382
+ answer_match = re.search(r'답변:\s*(.+?)(?=\n|ground_truth:|$)', block, re.DOTALL)
383
+ gt_match = re.search(r'ground_truth:\s*(.+?)(?=\n|---|\Z)', block, re.DOTALL)
384
+
385
+ if question_match and answer_match and gt_match:
386
+ question = question_match.group(1).strip()
387
+ answer = answer_match.group(1).strip()
388
+ ground_truth = gt_match.group(1).strip()
389
+
390
+ qa_id = f"{chunk.chunk_id}_qa{i}"
391
+
392
+ qa_pair = QAPair(
393
+ qa_id=qa_id,
394
+ question=question,
395
+ answer=answer,
396
+ context=chunk.content,
397
+ ground_truth=ground_truth,
398
+ metadata={
399
+ "chunk_id": chunk.chunk_id,
400
+ "page_number": chunk.page_number,
401
+ "generated_at": datetime.now().isoformat()
402
+ }
403
+ )
404
+
405
+ qa_pairs.append(qa_pair)
406
+
407
+ return qa_pairs
408
+
409
+
410
+ # ============================================================================
411
+ # Golden Dataset Manager
412
+ # ============================================================================
413
+
414
+ class GoldenDatasetManager:
415
+ """Golden Dataset 관리자 - 저장/로드/검증"""
416
+
417
+ def __init__(self, output_dir: str = "results/golden_datasets"):
418
+ """
419
+ Args:
420
+ output_dir: 저장 디렉토리 (기본: results/golden_datasets)
421
+ """
422
+ self.output_dir = Path(output_dir)
423
+ self.output_dir.mkdir(parents=True, exist_ok=True)
424
+
425
+ def create_dataset(
426
+ self,
427
+ qa_pairs: List[QAPair],
428
+ source_document: str,
429
+ metadata: Optional[Dict[str, Any]] = None
430
+ ) -> GoldenDataset:
431
+ """Golden Dataset 생성"""
432
+ dataset_id = self._generate_dataset_id(source_document)
433
+
434
+ if metadata is None:
435
+ metadata = {}
436
+
437
+ dataset = GoldenDataset(
438
+ dataset_id=dataset_id,
439
+ source_document=source_document,
440
+ created_at=datetime.now().isoformat(),
441
+ total_qa_pairs=len(qa_pairs),
442
+ qa_pairs=qa_pairs,
443
+ metadata=metadata
444
+ )
445
+
446
+ return dataset
447
+
448
+ def save_dataset(
449
+ self,
450
+ dataset: GoldenDataset,
451
+ format: str = "json",
452
+ filename: Optional[str] = None
453
+ ) -> str:
454
+ """
455
+ Dataset 저장
456
+
457
+ Args:
458
+ dataset: Golden Dataset
459
+ format: 저장 형식 ("json" 또는 "csv")
460
+ filename: 파일명 (None이면 자동 생성)
461
+
462
+ Returns:
463
+ 저장된 파일 경로
464
+ """
465
+ if filename is None:
466
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
467
+ filename = f"golden_dataset_{dataset.dataset_id}_{timestamp}.{format}"
468
+
469
+ filepath = self.output_dir / filename
470
+
471
+ if format == "json":
472
+ self._save_as_json(dataset, filepath)
473
+ elif format == "csv":
474
+ self._save_as_csv(dataset, filepath)
475
+ else:
476
+ raise ValueError(f"지원하지 않는 형식: {format}")
477
+
478
+ return str(filepath)
479
+
480
+ def _save_as_json(self, dataset: GoldenDataset, filepath: Path):
481
+ """JSON 형식으로 저장"""
482
+ data = asdict(dataset)
483
+
484
+ with open(filepath, 'w', encoding='utf-8') as f:
485
+ json.dump(data, f, ensure_ascii=False, indent=2)
486
+
487
+ print(f"✅ JSON으로 저장됨: {filepath}")
488
+
489
+ def _save_as_csv(self, dataset: GoldenDataset, filepath: Path):
490
+ """CSV 형식으로 저장"""
491
+ rows = []
492
+
493
+ for qa in dataset.qa_pairs:
494
+ row = {
495
+ "qa_id": qa.qa_id,
496
+ "question": qa.question,
497
+ "answer": qa.answer,
498
+ "ground_truth": qa.ground_truth,
499
+ "context": qa.context,
500
+ "chunk_id": qa.metadata.get("chunk_id", ""),
501
+ "page_number": qa.metadata.get("page_number", ""),
502
+ "generated_at": qa.metadata.get("generated_at", "")
503
+ }
504
+ rows.append(row)
505
+
506
+ df = pd.DataFrame(rows)
507
+ df.to_csv(filepath, index=False, encoding='utf-8-sig') # utf-8-sig for Excel
508
+
509
+ print(f"✅ CSV로 저장됨: {filepath}")
510
+
511
+ def load_dataset(self, filepath: str) -> GoldenDataset:
512
+ """Dataset 로드"""
513
+ filepath = Path(filepath)
514
+
515
+ if not filepath.exists():
516
+ raise FileNotFoundError(f"파일을 찾을 수 없습니다: {filepath}")
517
+
518
+ if filepath.suffix == ".json":
519
+ return self._load_from_json(filepath)
520
+ elif filepath.suffix == ".csv":
521
+ return self._load_from_csv(filepath)
522
+ else:
523
+ raise ValueError(f"지원하지 않는 형식: {filepath.suffix}")
524
+
525
+ def _load_from_json(self, filepath: Path) -> GoldenDataset:
526
+ """JSON에서 로드"""
527
+ with open(filepath, 'r', encoding='utf-8') as f:
528
+ data = json.load(f)
529
+
530
+ # QAPair 객체로 변환
531
+ qa_pairs = [QAPair(**qa) for qa in data["qa_pairs"]]
532
+
533
+ dataset = GoldenDataset(
534
+ dataset_id=data["dataset_id"],
535
+ source_document=data["source_document"],
536
+ created_at=data["created_at"],
537
+ total_qa_pairs=data["total_qa_pairs"],
538
+ qa_pairs=qa_pairs,
539
+ metadata=data.get("metadata", {})
540
+ )
541
+
542
+ print(f"✅ JSON에서 로드됨: {filepath} ({len(qa_pairs)} QA pairs)")
543
+ return dataset
544
+
545
+ def _load_from_csv(self, filepath: Path) -> GoldenDataset:
546
+ """CSV에서 로드"""
547
+ df = pd.read_csv(filepath, encoding='utf-8-sig')
548
+
549
+ qa_pairs = []
550
+ for _, row in df.iterrows():
551
+ qa_pair = QAPair(
552
+ qa_id=row["qa_id"],
553
+ question=row["question"],
554
+ answer=row["answer"],
555
+ ground_truth=row["ground_truth"],
556
+ context=row["context"],
557
+ metadata={
558
+ "chunk_id": row.get("chunk_id", ""),
559
+ "page_number": row.get("page_number", ""),
560
+ "generated_at": row.get("generated_at", "")
561
+ }
562
+ )
563
+ qa_pairs.append(qa_pair)
564
+
565
+ # 메타데이터 추출 (첫 번째 행에서)
566
+ source_doc = filepath.stem
567
+ dataset_id = self._generate_dataset_id(source_doc)
568
+
569
+ dataset = GoldenDataset(
570
+ dataset_id=dataset_id,
571
+ source_document=source_doc,
572
+ created_at=datetime.now().isoformat(),
573
+ total_qa_pairs=len(qa_pairs),
574
+ qa_pairs=qa_pairs,
575
+ metadata={}
576
+ )
577
+
578
+ print(f"✅ CSV에서 로드됨: {filepath} ({len(qa_pairs)} QA pairs)")
579
+ return dataset
580
+
581
+ def validate_dataset(self, dataset: GoldenDataset) -> Dict[str, Any]:
582
+ """Dataset 검증"""
583
+ validation_results = {
584
+ "is_valid": True,
585
+ "total_qa_pairs": len(dataset.qa_pairs),
586
+ "issues": []
587
+ }
588
+
589
+ for qa in dataset.qa_pairs:
590
+ # 필수 필드 체크
591
+ if not qa.question or not qa.question.strip():
592
+ validation_results["issues"].append(f"{qa.qa_id}: 질문이 비어있음")
593
+ validation_results["is_valid"] = False
594
+
595
+ if not qa.answer or not qa.answer.strip():
596
+ validation_results["issues"].append(f"{qa.qa_id}: 답변이 비어있음")
597
+ validation_results["is_valid"] = False
598
+
599
+ if not qa.ground_truth or not qa.ground_truth.strip():
600
+ validation_results["issues"].append(f"{qa.qa_id}: Ground truth가 비어있음")
601
+ validation_results["is_valid"] = False
602
+
603
+ if not qa.context or not qa.context.strip():
604
+ validation_results["issues"].append(f"{qa.qa_id}: Context가 비어있음")
605
+ validation_results["is_valid"] = False
606
+
607
+ # 길이 체크
608
+ if len(qa.question) < 10:
609
+ validation_results["issues"].append(f"{qa.qa_id}: 질문이 너무 짧음")
610
+
611
+ if len(qa.answer) < 20:
612
+ validation_results["issues"].append(f"{qa.qa_id}: 답변이 너무 짧음")
613
+
614
+ return validation_results
615
+
616
+ def _generate_dataset_id(self, source_document: str) -> str:
617
+ """Dataset ID 생성"""
618
+ doc_hash = hashlib.md5(source_document.encode()).hexdigest()[:8]
619
+ return f"dataset_{doc_hash}"
620
+
621
+
622
+ # ============================================================================
623
+ # Main Pipeline
624
+ # ============================================================================
625
+
626
+ class KoreanRAGDatasetGenerator:
627
+ """한국어 RAG Dataset 생성 파이프라인"""
628
+
629
+ def __init__(
630
+ self,
631
+ api_key: Optional[str] = None,
632
+ model: str = "gpt-4o-mini",
633
+ chunk_size: int = 1000,
634
+ chunk_overlap: int = 200,
635
+ output_dir: str = "golden_datasets"
636
+ ):
637
+ """
638
+ Args:
639
+ api_key: OpenAI API 키
640
+ model: 사용할 모델
641
+ chunk_size: 청크 크기
642
+ chunk_overlap: 청크 겹침
643
+ output_dir: 출력 디렉토리
644
+ """
645
+ self.pdf_extractor = KoreanPDFExtractor()
646
+ self.text_chunker = TextChunker(chunk_size, chunk_overlap)
647
+ self.qa_generator = KoreanQAGenerator(api_key, model)
648
+ self.dataset_manager = GoldenDatasetManager(output_dir)
649
+
650
+ def generate_from_pdf(
651
+ self,
652
+ pdf_path: str,
653
+ num_questions_per_chunk: int = 3,
654
+ question_types: Optional[List[str]] = None,
655
+ save_format: str = "json",
656
+ max_chunks: Optional[int] = None
657
+ ) -> GoldenDataset:
658
+ """
659
+ PDF에서 Golden Dataset 생성 (전체 파이프라인)
660
+
661
+ Args:
662
+ pdf_path: PDF 파일 경로
663
+ num_questions_per_chunk: 청크당 질문 수
664
+ question_types: 질문 유형
665
+ save_format: 저장 형식 ("json" 또는 "csv")
666
+ max_chunks: 최대 청크 수 (테스트용, None이면 전체)
667
+
668
+ Returns:
669
+ 생성된 Golden Dataset
670
+ """
671
+ print(f"\n{'='*80}")
672
+ print(f"한국어 RAG Golden Dataset 생성 시작")
673
+ print(f"{'='*80}\n")
674
+
675
+ # 1. PDF 텍스트 추출
676
+ print(f"📄 PDF 파일 읽기: {pdf_path}")
677
+ pages_text = self.pdf_extractor.extract_text(pdf_path)
678
+ print(f" ✓ {len(pages_text)} 페이지 추출됨\n")
679
+
680
+ # 텍스트 정제
681
+ cleaned_pages = []
682
+ for page_num, text in pages_text:
683
+ cleaned_text = self.pdf_extractor.clean_text(text)
684
+ cleaned_pages.append((page_num, cleaned_text))
685
+
686
+ # 메모리 최적화: max_chunks 설정 시 페이지 수 제한
687
+ if max_chunks:
688
+ # 청크당 평균 1-2페이지로 가정, 여유있게 계산
689
+ estimated_pages_needed = max(3, max_chunks * 2)
690
+ if len(cleaned_pages) > estimated_pages_needed:
691
+ print(f"🛡️ 메모리 최적화: {len(cleaned_pages)} 페이지 중 앞 {estimated_pages_needed}페이지만 처리 (청크 {max_chunks}개 생성용)")
692
+ cleaned_pages = cleaned_pages[:estimated_pages_needed]
693
+
694
+ # 2. 텍스트 청킹
695
+ print(f"📦 텍스트 청킹 (chunk_size: {self.text_chunker.chunk_size}, overlap: {self.text_chunker.chunk_overlap})")
696
+ chunks = self.text_chunker.chunk_documents(cleaned_pages)
697
+
698
+ if max_chunks and len(chunks) > max_chunks:
699
+ chunks = chunks[:max_chunks]
700
+ print(f" ⚠️ 청크 제한 적용: {max_chunks}개 청크만 사용")
701
+
702
+ print(f" ✓ {len(chunks)} 청크 생성됨\n")
703
+
704
+ # 3. QA 쌍 생성
705
+ print(f"🤖 AI 기반 QA 쌍 생성 (청크당 {num_questions_per_chunk}개 질문)")
706
+ print(f" 모델: {self.qa_generator.model}")
707
+ print(f" 예상 생성 수: {len(chunks) * num_questions_per_chunk}개\n")
708
+
709
+ all_qa_pairs = []
710
+
711
+ for i, chunk in enumerate(chunks, 1):
712
+ print(f" [{i}/{len(chunks)}] 청크 처리 중 (Page {chunk.page_number})...", end=" ")
713
+
714
+ qa_pairs = self.qa_generator.generate_qa_pairs(
715
+ chunk,
716
+ num_questions=num_questions_per_chunk,
717
+ question_types=question_types
718
+ )
719
+
720
+ all_qa_pairs.extend(qa_pairs)
721
+ print(f"✓ {len(qa_pairs)}개 생성")
722
+
723
+ print(f"\n ✓ 총 {len(all_qa_pairs)}개 QA 쌍 생성됨\n")
724
+
725
+ # 4. Golden Dataset 생성
726
+ print("💾 Golden Dataset 생성 및 저장")
727
+ dataset = self.dataset_manager.create_dataset(
728
+ qa_pairs=all_qa_pairs,
729
+ source_document=pdf_path,
730
+ metadata={
731
+ "total_pages": len(pages_text),
732
+ "total_chunks": len(chunks),
733
+ "chunk_size": self.text_chunker.chunk_size,
734
+ "chunk_overlap": self.text_chunker.chunk_overlap,
735
+ "num_questions_per_chunk": num_questions_per_chunk,
736
+ "question_types": question_types,
737
+ "model": self.qa_generator.model
738
+ }
739
+ )
740
+
741
+ # 5. 검증
742
+ validation = self.dataset_manager.validate_dataset(dataset)
743
+ if validation["is_valid"]:
744
+ print(f" ✓ 데이터셋 검증 통과")
745
+ else:
746
+ print(f" ⚠️ 데이터셋 검증 실패:")
747
+ for issue in validation["issues"][:5]: # 처음 5개만 표시
748
+ print(f" - {issue}")
749
+
750
+ # 6. 저장
751
+ saved_path = self.dataset_manager.save_dataset(dataset, format=save_format)
752
+ print(f" ✓ 저장 완료: {saved_path}\n")
753
+
754
+ # 7. 요약 출력
755
+ self._print_summary(dataset)
756
+
757
+ return dataset
758
+
759
+ def _print_summary(self, dataset: GoldenDataset):
760
+ """생성 결과 요약 출력"""
761
+ print(f"{'='*80}")
762
+ print(f"📊 생성 결과 요약")
763
+ print(f"{'='*80}\n")
764
+
765
+ print(f"Dataset ID: {dataset.dataset_id}")
766
+ print(f"소스 문서: {dataset.source_document}")
767
+ print(f"생성 시간: {dataset.created_at}")
768
+ print(f"총 QA 쌍: {dataset.total_qa_pairs}개\n")
769
+
770
+ # 샘플 QA 쌍 출력
771
+ if dataset.qa_pairs:
772
+ print("📝 샘플 QA 쌍 (첫 번째):")
773
+ print("-" * 80)
774
+ sample = dataset.qa_pairs[0]
775
+ print(f"질문: {sample.question}")
776
+ print(f"답변: {sample.answer}")
777
+ print(f"Ground Truth: {sample.ground_truth}")
778
+ print(f"Context (처음 100자): {sample.context[:100]}...")
779
+ print("-" * 80 + "\n")
780
+
781
+ print(f"✅ Golden Dataset 생성 완료!\n")
782
+
783
+
784
+ # ============================================================================
785
+ # Example Usage
786
+ # ============================================================================
787
+
788
+ def example_generate_from_pdf():
789
+ """PDF에서 Golden Dataset 생성 예제"""
790
+
791
+ # 1. 생성기 초기화
792
+ generator = KoreanRAGDatasetGenerator(
793
+ model="gpt-4o-mini", # 또는 "gpt-4o" (더 비싸지만 품질 좋음)
794
+ chunk_size=800,
795
+ chunk_overlap=150,
796
+ output_dir="golden_datasets"
797
+ )
798
+
799
+ # 2. PDF에서 데이터셋 생성
800
+ dataset = generator.generate_from_pdf(
801
+ pdf_path="your_document.pdf", # 실제 PDF 경로로 변경
802
+ num_questions_per_chunk=3,
803
+ question_types=["factual", "reasoning", "summary"],
804
+ save_format="json", # "json" 또는 "csv"
805
+ max_chunks=5 # 테스트용, 실제 사용 시 None으로 설정
806
+ )
807
+
808
+ return dataset
809
+
810
+
811
+ def example_load_and_use():
812
+ """저장된 Golden Dataset 로드 및 사용 예제"""
813
+
814
+ manager = GoldenDatasetManager()
815
+
816
+ # 1. 로드
817
+ dataset = manager.load_dataset("golden_datasets/golden_dataset_xxx.json")
818
+
819
+ # 2. 검증
820
+ validation = manager.validate_dataset(dataset)
821
+ print(f"검증 결과: {'통과' if validation['is_valid'] else '실패'}")
822
+
823
+ # 3. RAG 평가에 사용
824
+ for qa in dataset.qa_pairs[:3]: # 처음 3개만
825
+ print(f"\nQuestion: {qa.question}")
826
+ print(f"Expected: {qa.ground_truth}")
827
+ print(f"Context: {qa.context[:100]}...")
828
+
829
+
830
+ if __name__ == "__main__":
831
+ print("""
832
+ Korean RAG Dataset Generator
833
+ =============================
834
+
835
+ 사용 방법:
836
+
837
+ 1. PDF에서 Golden Dataset 생성:
838
+ python korean_rag_dataset_generator.py
839
+
840
+ 2. 저장된 데이터셋 로드:
841
+ manager = GoldenDatasetManager()
842
+ dataset = manager.load_dataset("path/to/dataset.json")
843
+
844
+ 필수 환경 변수:
845
+ OPENAI_API_KEY=your-api-key
846
+
847
+ 필수 라이브러리:
848
+ pip install PyPDF2 openai pandas python-dotenv
849
+ # 또는
850
+ pip install pdfplumber openai pandas python-dotenv
851
+
852
+ 예제 실행:
853
+ - example_generate_from_pdf()
854
+ - example_load_and_use()
855
+ """)
856
+
857
+ # 예제 실행 (주석 해제하여 사용)
858
+ # example_generate_from_pdf()