File size: 6,973 Bytes
01661a1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.documents import Document
from typing import List
import re
class VehicleManualTextSplitter:
def __init__(self, chunk_size: int = 500, chunk_overlap: int = 100):
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.text_splitter = RecursiveCharacterTextSplitter(
chunk_size = chunk_size,
chunk_overlap = chunk_overlap,
length_function = len,
separators=["\n\n", "\n", ".", "ใ", "!", "?", ",", " ", ""],
is_separator_regex=False
)
self.chunks = []
def split_documents(self, documents: List[Document]) -> List[Document]:
print(f"{len(documents)}๊ฐ ํ์ด์ง๋ฅผ ์ฒญํฌ๋ก ๋ถํ ์ค...")
# ๋ถํ ์ ์ ์ฒ๋ฆฌ
processed_docs = self._preprocess_documents(documents)
# LangChain์ split_documents ๋ฉ์๋ ์ฌ์ฉ
self.chunks = self.text_splitter.split_documents(processed_docs)
# ์ฒญํฌ์ ์ถ๊ฐ ๋ฉํ๋ฐ์ดํฐ ๋ถ์ฌ
self._add_chunk_metadata()
print(f"์ด {len(self.chunks)}๊ฐ ์ฒญํฌ ์์ฑ ์๋ฃ")
print(f"ํ๊ท ์ฒญํฌ ํฌ๊ธฐ: {self._get_avg_chunk_size():.0f}์")
return self.chunks
def _preprocess_documents(self, documents: List[Document]) -> List[Document]:
processed = []
for doc in documents:
# ์ฐ์๋ ๊ณต๋ฐฑ์ ํ๋๋ก
content = re.sub(r'\s+', ' ', doc.page_content)
# ํ์ด์ง ๋ฒํธ ํจํด ์ ๊ฑฐ (์: "- 123 -", "Page 123")
content = re.sub(r'-\s*\d+\s*-', '', content)
content = re.sub(r'Page\s*\d+', '', content, flags=re.IGNORECASE)
# ๋๋ฌด ์งง์ ํ์ด์ง๋ ์คํต (๋ชฉ์ฐจ, ๋น ํ์ด์ง ๋ฑ)
if len(content.strip()) < 50:
continue
processed.append(Document(
page_content=content,
metadata=doc.metadata
))
return processed
def _add_chunk_metadata(self):
for i, chunk in enumerate(self.chunks):
chunk.metadata['chunk_id'] = f"chunk_{i:04d}"
chunk.metadata['chunk_index'] = i
# ์ฒญํฌ๊ฐ ์ด๋ค ์น์
์ ์ํ๋์ง ์ถ๋ก (์ ๋ชฉ ๊ธฐ๋ฐ)
section = self._infer_section(chunk.page_content)
if section:
chunk.metadata['section'] = section
def _infer_section(self, text: str) -> str:
text_lower = text.lower()
# ์ฃผ์ ์น์
ํค์๋ ๋งคํ
section_keywords = {
'์์ง': ['์์ง', '์๋', '์ถ๋ ฅ', '์ฐ๋ฃ'],
'๋ธ๋ ์ดํฌ': ['๋ธ๋ ์ดํฌ', '์ ๋', 'ํ๋ฌ'],
'ํ์ด์ด': ['ํ์ด์ด', 'ํ ', '๊ณต๊ธฐ์'],
'์ ๊ธฐ์ฅ์น': ['๋ฐฐํฐ๋ฆฌ', 'ํจ์ฆ', '๋จํ', '์กฐ๋ช
'],
'์์ ': ['์์ด๋ฐฑ', '์์ ๋ฒจํธ', '๊ฒฝ๊ณ ๋ฑ'],
'์ ๋น': ['์ ๊ฒ', '๊ต์ฒด', '์ ๋น', '์ค์ผ'],
'์ด์ ': ['์ฃผํ', '์ด์ ', '๊ธฐ์ด', '๋ณ์'],
'ADAS': ['ํฌ๋ฃจ์ฆ', '์ฐจ์ ', '์ถฉ๋', '์๋']
}
for section, keywords in section_keywords.items():
for keyword in keywords:
if keyword in text_lower:
return section
return '์ผ๋ฐ'
def _get_avg_chunk_size(self) -> float:
"""ํ๊ท ์ฒญํฌ ํฌ๊ธฐ ๊ณ์ฐ"""
if not self.chunks:
return 0
return sum(len(c.page_content) for c in self.chunks) / len(self.chunks)
def get_chunk_statistics(self) -> dict:
if not self.chunks:
return {}
lengths = [len(c.page_content) for c in self.chunks]
return {
'total_chunks': len(self.chunks),
'avg_size': sum(lengths) / len(lengths),
'min_size': min(lengths),
'max_size': max(lengths),
'total_chars': sum(lengths),
'sections': self._count_sections()
}
def _count_sections(self) -> dict:
sections = {}
for chunk in self.chunks:
section = chunk.metadata.get('section', '์ผ๋ฐ')
sections[section] = sections.get(section, 0) + 1
return sections
def search_chunks(self, keyword: str, limit: int = 5) -> List[Document]:
results = []
for chunk in self.chunks:
if keyword.lower() in chunk.page_content.lower():
results.append(chunk)
if len(results) >= limit:
break
return results
# ํ
์คํธ ์ฝ๋
if __name__ == "__main__":
from document_loader import VehicleManualLoader
import os
# ํ์ฌ ๋๋ ํ ๋ฆฌ ์ค์
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
pdf_path = os.path.join(project_root, "data", "LX3_2026_ko_KR.pdf")
print("=" * 60)
print("์ฐจ๋ ๋งค๋ด์ผ ํ
์คํธ ๋ถํ ํ
์คํธ")
print("=" * 60)
try:
# 1. PDF ๋ก๋
print("\n1. PDF ๋ก๋ฉ...")
loader = VehicleManualLoader(pdf_path)
documents = loader.load_pdf()
# 2. ํ
์คํธ ๋ถํ
print("\n2. ํ
์คํธ ๋ถํ ์ค...")
splitter = VehicleManualTextSplitter(
chunk_size=500, # ํ๊ตญ์ด ๊ธฐ์ค ์ฝ 2-3๋ฌธ๋จ
chunk_overlap=100 # ๋ฌธ๋งฅ ์ ์ง๋ฅผ ์ํ ์ค๋ณต
)
chunks = splitter.split_documents(documents)
# 3. ํต๊ณ ์ถ๋ ฅ
print("\n3. ์ฒญํฌ ํต๊ณ:")
stats = splitter.get_chunk_statistics()
print(f" - ์ด ์ฒญํฌ ์: {stats['total_chunks']:,}๊ฐ")
print(f" - ํ๊ท ํฌ๊ธฐ: {stats['avg_size']:.0f}์")
print(f" - ์ต์/์ต๋: {stats['min_size']}์ / {stats['max_size']}์")
print(f" - ์ด ๋ฌธ์ ์: {stats['total_chars']:,}์")
print("\n ์น์
๋ณ ๋ถํฌ:")
for section, count in stats['sections'].items():
print(f" - {section}: {count}๊ฐ")
# 4. ์ํ ์ฒญํฌ ํ์ธ
print("\n4๏ธ. ์ํ ์ฒญํฌ (์ฒ์ 3๊ฐ):")
print("-" * 50)
for i, chunk in enumerate(chunks[:3]):
print(f"\n[์ฒญํฌ {i + 1}]")
print(f"ID: {chunk.metadata.get('chunk_id')}")
print(f"์น์
: {chunk.metadata.get('section')}")
print(f"์๋ณธ ํ์ด์ง: {chunk.metadata.get('page', 'N/A')}")
print(f"๋ด์ฉ: {chunk.page_content[:150]}...")
print("-" * 50)
# 5. ํค์๋ ๊ฒ์ ํ
์คํธ
print("\n5๏ธ. '์์ง ์ค์ผ' ๊ฒ์ ํ
์คํธ:")
results = splitter.search_chunks("์์ง ์ค์ผ", limit=3)
print(f" ์ฐพ์ ์ฒญํฌ: {len(results)}๊ฐ")
for i, chunk in enumerate(results):
print(f" - ์ฒญํฌ {chunk.metadata['chunk_id']}: {chunk.page_content[:100]}...")
except Exception as e:
print(f" ์๋ฌ ๋ฐ์: {e}")
import traceback
traceback.print_exc() |