File size: 6,678 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 |
from sentence_transformers import SentenceTransformer
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_core.documents import Document
from typing import List, Tuple
import numpy as np
import pickle
import os
from tqdm import tqdm
import time
class VehicleManualEmbeddings:
def __init__(self, model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"):
print(f" ์๋ฒ ๋ฉ ๋ชจ๋ธ ๋ก๋ฉ ์ค: {model_name}")
print(" (์ฒซ ์คํ์ ๋ชจ๋ธ ๋ค์ด๋ก๋๋ก ์๊ฐ์ด ๊ฑธ๋ฆด ์ ์์ต๋๋ค)")
# HuggingFaceEmbeddings๋ LangChain๊ณผ ํตํฉ์ด ์ฌ์
self.embeddings = HuggingFaceEmbeddings(
model_name=model_name,
model_kwargs={'device': 'cpu'}, # GPU ์์ด๋ OK
encode_kwargs={'normalize_embeddings': True} # ์ฝ์ฌ์ธ ์ ์ฌ๋ ๊ณ์ฐ ์ต์ ํ
)
self.vector_store = None
self.index_path = "data/faiss_index" # ์ธ๋ฑ์ค ์ ์ฅ ๊ฒฝ๋ก
print("์๋ฒ ๋ฉ ๋ชจ๋ธ ๋ก๋ ์๋ฃ")
def create_vector_store(self, chunks: List[Document], save: bool = True) -> FAISS:
print(f" {len(chunks)}๊ฐ ์ฒญํฌ๋ฅผ ๋ฒกํฐ๋ก ๋ณํ ์ค...")
print(" (6000๊ฐ ๊ธฐ์ค ์ฝ 2-5๋ถ ์์)")
start_time = time.time()
# ๋ฐฐ์น ์ฒ๋ฆฌ๋ก ์๋ ํฅ์
batch_size = 100
all_texts = [chunk.page_content for chunk in chunks]
all_metadatas = [chunk.metadata for chunk in chunks]
self.vector_store = FAISS.from_documents(
documents=chunks[:batch_size], # ์ฒซ ๋ฐฐ์น๋ก ์ด๊ธฐํ
embedding=self.embeddings
)
# ๋๋จธ์ง ๋ฐฐ์น ์ถ๊ฐ
for i in tqdm(range(batch_size, len(chunks), batch_size), desc="๋ฒกํฐํ ์งํ"):
batch_chunks = chunks[i:i + batch_size]
if batch_chunks: # ๋น ๋ฐฐ์น๊ฐ ์๋ ๊ฒฝ์ฐ๋ง
self.vector_store.add_documents(batch_chunks)
elapsed_time = time.time() - start_time
print(f"๋ฒกํฐํ ์๋ฃ! (์์์๊ฐ: {elapsed_time:.1f}์ด)")
# ์ธ๋ฑ์ค ์ ์ฅ
if save:
self.save_index()
# ํต๊ณ ์ถ๋ ฅ
self._print_statistics()
return self.vector_store
def save_index(self):
if not self.vector_store:
raise ValueError("๋จผ์ create_vector_store()๋ฅผ ์คํํ์ธ์")
print(f"์ธ๋ฑ์ค ์ ์ฅ ์ค: {self.index_path}")
# ๋๋ ํ ๋ฆฌ ์์ฑ
os.makedirs(os.path.dirname(self.index_path), exist_ok=True)
# FAISS ์ธ๋ฑ์ค ์ ์ฅ
self.vector_store.save_local(self.index_path)
print("์ธ๋ฑ์ค ์ ์ฅ ์๋ฃ")
def load_index(self) -> FAISS:
if not os.path.exists(self.index_path):
raise FileNotFoundError(f"์ธ๋ฑ์ค ํ์ผ์ด ์์ต๋๋ค: {self.index_path}")
print(f"์ธ๋ฑ์ค ๋ก๋ฉ ์ค: {self.index_path}")
self.vector_store = FAISS.load_local(
self.index_path,
self.embeddings,
allow_dangerous_deserialization=True # ๋ก์ปฌ ํ์ผ์ด๋ฏ๋ก ์์
)
print("์ธ๋ฑ์ค ๋ก๋ ์๋ฃ")
return self.vector_store
def similarity_search(self, query: str, k: int = 3) -> List[Document]:
if not self.vector_store:
raise ValueError("๋จผ์ create_vector_store() ๋๋ load_index()๋ฅผ ์คํํ์ธ์")
# ๋ฒกํฐ ๊ฒ์ ์ํ
results = self.vector_store.similarity_search(query, k=k)
return results
def similarity_search_with_score(self, query: str, k: int = 3) -> List[Tuple[Document, float]]:
if not self.vector_store:
raise ValueError("๋จผ์ create_vector_store() ๋๋ load_index()๋ฅผ ์คํํ์ธ์")
results = self.vector_store.similarity_search_with_score(query, k=k)
return results
def _print_statistics(self):
if not self.vector_store:
return
# FAISS ์ธ๋ฑ์ค ์ ๋ณด
print("\n ๋ฒกํฐ ์ ์ฅ์ ํต๊ณ:")
print(f" - ์ ์ฅ๋ ๋ฒกํฐ ์: {self.vector_store.index.ntotal:,}๊ฐ")
print(f" - ๋ฒกํฐ ์ฐจ์: {self.vector_store.index.d}์ฐจ์")
print(f" - ์ธ๋ฑ์ค ํ์
: {type(self.vector_store.index).__name__}")
# ํ
์คํธ ์ฝ๋
if __name__ == "__main__":
from document_loader import VehicleManualLoader
from text_splitter import VehicleManualTextSplitter
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")
index_path = os.path.join(project_root, "data", "faiss_index")
print("=" * 60)
print("์ฐจ๋ ๋งค๋ด์ผ ์๋ฒ ๋ฉ ๋ฐ ๋ฒกํฐ ๊ฒ์ ํ
์คํธ")
print("=" * 60)
# ์๋ฒ ๋ฉ ์์คํ
์ด๊ธฐํ
embedder = VehicleManualEmbeddings()
# ๊ธฐ์กด ์ธ๋ฑ์ค๊ฐ ์์ผ๋ฉด ๋ก๋, ์์ผ๋ฉด ์๋ก ์์ฑ
if os.path.exists(index_path):
print("\n๊ธฐ์กด ์ธ๋ฑ์ค ๋ฐ๊ฒฌ! ๋ก๋ํฉ๋๋ค...")
vector_store = embedder.load_index()
else:
print("\n์๋ก์ด ์ธ๋ฑ์ค๋ฅผ ์์ฑํฉ๋๋ค...")
# 1. PDF ๋ก๋
print("\n1. PDF ๋ก๋ฉ...")
loader = VehicleManualLoader(pdf_path)
documents = loader.load_pdf()
# 2. ํ
์คํธ ๋ถํ
print("\n2๏ธ. ํ
์คํธ ๋ถํ ...")
splitter = VehicleManualTextSplitter(chunk_size=500, chunk_overlap=100)
chunks = splitter.split_documents(documents)
# 3. ๋ฒกํฐํ ๋ฐ ์ธ๋ฑ์ค ์์ฑ
print("\n3๏ธ. ๋ฒกํฐํ ์์...")
vector_store = embedder.create_vector_store(chunks, save=True)
# 4. ๊ฒ์ ํ
์คํธ
print("\n4๏ธ. ๊ฒ์ ํ
์คํธ")
print("-" * 50)
test_queries = [
"์์ง ์ค์ผ ๊ต์ฒด ์ฃผ๊ธฐ๋?",
"ํ์ด์ด ๊ณต๊ธฐ์์ ์ผ๋ง๊ฐ ์ ์ ํ๊ฐ์?",
"์์ดํผ ๊ต์ฒด ๋ฐฉ๋ฒ",
"๊ฒฝ๊ณ ๋ฑ์ด ์ผ์ก์ ๋ ๋์ฒ๋ฒ",
"๋ธ๋ ์ดํฌ ํจ๋ ์ ๊ฒ"
]
for query in test_queries[:3]: # ์ฒ์ 3๊ฐ๋ง ํ
์คํธ
print(f"\n ์ง๋ฌธ: {query}")
# ์ ์ฌ๋ ์ ์์ ํจ๊ป ๊ฒ์
results = embedder.similarity_search_with_score(query, k=2)
for i, (doc, score) in enumerate(results):
print(f"\n [{i + 1}] ์ ์ฌ๋: {score:.3f}")
print(f" ํ์ด์ง: {doc.metadata.get('page', 'N/A')}")
print(f" ์น์
: {doc.metadata.get('section', 'N/A')}")
print(f" ๋ด์ฉ: {doc.page_content[:150]}...")
print("\n" + "=" * 60)
print("๋ชจ๋ ํ
์คํธ ์๋ฃ!")
print("=" * 60) |