Spaces:
Sleeping
Sleeping
Add: enhance embedding process with document cleaning and batch validation
Browse files- src/embedding.py +59 -10
src/embedding.py
CHANGED
|
@@ -2,7 +2,7 @@ from typing import List, Any, Optional
|
|
| 2 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 3 |
from sentence_transformers import SentenceTransformer
|
| 4 |
import numpy as np
|
| 5 |
-
from src.
|
| 6 |
|
| 7 |
class EmbeddingPipeline:
|
| 8 |
def __init__(self, model_name: str = 'all-MiniLM-L6-v2', chunk_size: int = 1000, chunk_overlap: int = 200):
|
|
@@ -10,26 +10,75 @@ class EmbeddingPipeline:
|
|
| 10 |
self.chunk_size = chunk_size
|
| 11 |
self.chunk_overlap = chunk_overlap
|
| 12 |
self.model = SentenceTransformer(model_name)
|
|
|
|
| 13 |
print(f"[INFO] Loaded embedding model: {model_name}")
|
| 14 |
|
| 15 |
def chunk_documents(self, documents: List[Any]) -> List[Any]:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
splitter = RecursiveCharacterTextSplitter(
|
| 17 |
chunk_size=self.chunk_size,
|
| 18 |
chunk_overlap=self.chunk_overlap,
|
| 19 |
length_function=len,
|
| 20 |
-
separators=["\n\n", "\n", " "
|
| 21 |
)
|
| 22 |
|
| 23 |
-
chunks = splitter.split_documents(
|
| 24 |
-
print(f"[INFO] Split {len(
|
| 25 |
return chunks
|
| 26 |
|
| 27 |
-
def embed_chunks(self, chunks: List[Any]) -> np.ndarray:
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
if __name__ == "__main__":
|
| 35 |
docs = load_all_documents('Research/data/pdf')
|
|
|
|
| 2 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 3 |
from sentence_transformers import SentenceTransformer
|
| 4 |
import numpy as np
|
| 5 |
+
from src.cleaner import get_default_cleaner
|
| 6 |
|
| 7 |
class EmbeddingPipeline:
|
| 8 |
def __init__(self, model_name: str = 'all-MiniLM-L6-v2', chunk_size: int = 1000, chunk_overlap: int = 200):
|
|
|
|
| 10 |
self.chunk_size = chunk_size
|
| 11 |
self.chunk_overlap = chunk_overlap
|
| 12 |
self.model = SentenceTransformer(model_name)
|
| 13 |
+
self.cleaner = get_default_cleaner()
|
| 14 |
print(f"[INFO] Loaded embedding model: {model_name}")
|
| 15 |
|
| 16 |
def chunk_documents(self, documents: List[Any]) -> List[Any]:
|
| 17 |
+
# 1. Clean documents first
|
| 18 |
+
cleaned_docs = self.cleaner.clean_documents(documents)
|
| 19 |
+
|
| 20 |
+
# 2. Split into chunks
|
| 21 |
splitter = RecursiveCharacterTextSplitter(
|
| 22 |
chunk_size=self.chunk_size,
|
| 23 |
chunk_overlap=self.chunk_overlap,
|
| 24 |
length_function=len,
|
| 25 |
+
separators=["\n\n", "\n", " "]
|
| 26 |
)
|
| 27 |
|
| 28 |
+
chunks = splitter.split_documents(cleaned_docs)
|
| 29 |
+
print(f"[INFO] Split {len(cleaned_docs)} documents into {len(chunks)} chunks.")
|
| 30 |
return chunks
|
| 31 |
|
| 32 |
+
def embed_chunks(self, chunks: List[Any], batch_size: int = 500) -> tuple[np.ndarray, List[Any]]:
|
| 33 |
+
"""
|
| 34 |
+
Embeds chunks in batches for stability and better error reporting.
|
| 35 |
+
Returns a tuple of (embeddings_array, valid_chunks_list).
|
| 36 |
+
"""
|
| 37 |
+
valid_chunks = []
|
| 38 |
+
all_embeddings = []
|
| 39 |
+
|
| 40 |
+
print(f"[INFO] Generating embeddings for {len(chunks)} chunks in batches of {batch_size}...")
|
| 41 |
+
|
| 42 |
+
for i in range(0, len(chunks), batch_size):
|
| 43 |
+
batch = chunks[i:i+batch_size]
|
| 44 |
+
batch_texts = []
|
| 45 |
+
current_batch_chunks = []
|
| 46 |
+
|
| 47 |
+
# Additional validation per chunk
|
| 48 |
+
for chunk in batch:
|
| 49 |
+
content = getattr(chunk, 'page_content', None)
|
| 50 |
+
if content is not None and isinstance(content, str) and content.strip():
|
| 51 |
+
batch_texts.append(content)
|
| 52 |
+
current_batch_chunks.append(chunk)
|
| 53 |
+
|
| 54 |
+
if not batch_texts:
|
| 55 |
+
continue
|
| 56 |
+
|
| 57 |
+
try:
|
| 58 |
+
batch_embeddings = self.model.encode(batch_texts, show_progress_bar=False)
|
| 59 |
+
all_embeddings.append(batch_embeddings)
|
| 60 |
+
valid_chunks.extend(current_batch_chunks)
|
| 61 |
+
except Exception as e:
|
| 62 |
+
print(f"[ERROR] Failed to embed batch starting at index {i}. Error: {e}")
|
| 63 |
+
print("[INFO] Attempting to identify problematic chunk in batch...")
|
| 64 |
+
for j, text in enumerate(batch_texts):
|
| 65 |
+
try:
|
| 66 |
+
self.model.encode([text], show_progress_bar=False)
|
| 67 |
+
except Exception as ex:
|
| 68 |
+
print(f"[ERROR] Problematic chunk found at original index {i+j}!")
|
| 69 |
+
# Safely encode for windows terminal printing to avoid crashes
|
| 70 |
+
safe_text = text[:100].encode('ascii', 'replace').decode('ascii')
|
| 71 |
+
print(f"[DEBUG] Content snippet: {safe_text}...")
|
| 72 |
+
# We skip this specific chunk and continue
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
if not all_embeddings:
|
| 76 |
+
print("[WARNING] No embeddings were generated.")
|
| 77 |
+
return np.array([]), []
|
| 78 |
+
|
| 79 |
+
final_embeddings = np.vstack(all_embeddings)
|
| 80 |
+
print(f"[INFO] Total valid embeddings: {final_embeddings.shape[0]} / {len(chunks)}")
|
| 81 |
+
return final_embeddings, valid_chunks
|
| 82 |
|
| 83 |
if __name__ == "__main__":
|
| 84 |
docs = load_all_documents('Research/data/pdf')
|