Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK: User input one pdf or folder (list of pdf files) or .txt file or folder (list of .txt files) may be any combination
processing the document and creating vector base very fast like with less than second , using multiprocessing use all cpu cores , make very very fast
chucking should be best possible techniques, very properly do mainly unnecessary space , voids space or (make sure zero data loss)
relevant content , most and best and accuracy correlation with user query
below code only reference you come best and (completely novel code ) (symlink each chuck of it should in the browse when click link)
import json
import logging
import shutil
import yaml
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import cpu_count
from pathlib import Path
from typing import Dict, List, Optional
import docx
import fitz # PyMuPDF for PDF processing
import nltk
import pandas as pd
import pptx
from datasets import Dataset
from langchain.docstore.document import Document as LangchainDocument
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_huggingface import HuggingFaceEmbeddings
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from tqdm import tqdm
from transformers import AutoTokenizer
EMBEDDING_MODEL_NAME = "thenlper/gte-large" # Replace with your preferred model
CHUNK_SIZE = 2048 # Adjust based on your needs
CHUNK_OVERLAP = 100 # Overlap between chunks for context
def extract_text_from_pdf(file_path: Path) -> str:
"""Extract text from a PDF file."""
try:
with fitz.open(file_path) as doc:
text = ""
for page in doc:
text += page.get_text()
return text
except Exception as e:
logger.error(f"Error reading PDF file {file_path}: {e}")
return ""
def extract_text_from_docx(file_path: Path) -> str:
"""Extract text from a Word document."""
try:
doc = docx.Document(file_path)
text = "\n".join([para.text for para in doc.paragraphs])
return text
except Exception as e:
logger.error(f"Error reading DOCX file {file_path}: {e}")
return ""
def extract_text_from_pptx(file_path: Path) -> str:
"""Extract text from a PowerPoint presentation."""
try:
prs = pptx.Presentation(file_path)
text = ""
for slide in prs.slides:
for shape in slide.shapes:
if hasattr(shape, "text"):
text += shape.text + "\n"
return text
except Exception as e:
logger.error(f"Error reading PPTX file {file_path}: {e}")
return ""
def extract_text_from_json(file_path: Path) -> str:
"""Extract text from a JSON file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
return json.dumps(data)
except Exception as e:
logger.error(f"Error reading JSON file {file_path}: {e}")
return ""
def extract_text_from_yaml(file_path: Path) -> str:
"""Extract text from a YAML file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = yaml.safe_load(f)
return yaml.dump(data)
except Exception as e:
logger.error(f"Error reading YAML file {file_path}: {e}")
return ""
def extract_text_from_csv(file_path: Path) -> str:
"""Extract text from a CSV file."""
try:
df = pd.read_csv(file_path)
return df.to_csv(index=False)
except Exception as e:
logger.error(f"Error reading CSV file {file_path}: {e}")
return ""
def extract_text(file_path: Path) -> str:
"""Extract text from a file based on its extension."""
ext = file_path.suffix.lower()
if ext == '.pdf':
return extract_text_from_pdf(file_path)
elif ext == '.docx':
return extract_text_from_docx(file_path)
elif ext == '.pptx':
return extract_text_from_pptx(file_path)
elif ext == '.json':
return extract_text_from_json(file_path)
elif ext in ['.yml', '.yaml']:
return extract_text_from_yaml(file_path)
elif ext == '.csv':
return extract_text_from_csv(file_path)
elif ext == '.txt':
try:
with open(file_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
logger.error(f"Error reading TXT file {file_path}: {e}")
return ""
else:
logger.warning(f"Unsupported file type: {file_path}")
return ""
def process_file(args: Dict) -> None:
"""Process a single file and save extracted text."""
file_path = args['file_path']
input_dir = args['input_dir']
output_dir = args['output_dir']
text = extract_text(file_path)
if text:
relative_path = file_path.relative_to(input_dir)
output_file = output_dir.joinpath(relative_path).with_suffix('.txt')
output_file.parent.mkdir(parents=True, exist_ok=True)
try:
with open(output_file, 'w', encoding='utf-8') as f:
f.write(text)
logger.info(f"Processed and saved text from {file_path} to {output_file}")
except Exception as e:
logger.error(f"Error writing to file {output_file}: {e}")
def process_files(input_dir: Path, output_dir: Path) -> None:
"""Recursively process files in input_dir and save text files to output_dir."""
if not output_dir.exists():
output_dir.mkdir(parents=True)
code
files = [p for p in input_dir.rglob('') if p.is_file()]
args_list = [{'file_path': file_path, 'input_dir': input_dir, 'output_dir': output_dir} for file_path in files]
with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
list(tqdm(executor.map(process_file, args_list), total=len(args_list), desc="Processing files"))
def load_documents(txt_folder: Path) -> List[LangchainDocument]:
"""Load text files and return as LangchainDocument objects."""
documents = []
files = list(txt_folder.rglob('*.txt')) # Corrected pattern here
# files = list(txt_folder.rglob('.txt'))
for file_path in tqdm(files, desc="Loading documents"):
try:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
metadata = {
'source': str(file_path),
'file_name': file_path.name,
'file_path': str(file_path)
}
document = LangchainDocument(page_content=text, metadata=metadata)
documents.append(document)
except Exception as e:
logger.error(f"Error loading document {file_path}: {e}")
return documents
def split_document(doc: LangchainDocument) -> List[LangchainDocument]:
"""Split a single document into smaller chunks."""
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=CHUNK_SIZE,
chunk_overlap=CHUNK_OVERLAP,
separators=["\n\n", "\n", " ", ""]
)
splits = text_splitter.split_text(doc.page_content)
split_docs = []
for i, content in enumerate(splits):
metadata = doc.metadata.copy()
metadata['chunk'] = i
split_docs.append(LangchainDocument(page_content=content, metadata=metadata))
return split_docs
def split_documents(documents: List[LangchainDocument]) -> List[LangchainDocument]:
"""Split documents into smaller chunks using multiprocessing."""
split_docs = []
with ProcessPoolExecutor(max_workers=cpu_count()) as executor:
results = list(tqdm(executor.map(split_document, documents), total=len(documents), desc="Splitting documents"))
for docs in results:
split_docs.extend(docs)
return split_docs
def create_embeddings(documents: List[LangchainDocument]) -> FAISS:
"""Create embeddings and build FAISS index."""
embeddings = HuggingFaceEmbeddings(
model_name=EMBEDDING_MODEL_NAME,
model_kwargs={'device': 'cpu'} # Change to 'cuda' if using GPU
)
vector_store = FAISS.from_documents(
documents,
embedding=embeddings,
distance_strategy=DistanceStrategy.EUCLIDEAN_DISTANCE
)
return vector_store
def save_vector_store(vector_store: FAISS, index_path: Path, metadata_path: Path) -> None:
"""Save the FAISS index and metadata."""
vector_store.save_local(str(index_path), str(metadata_path))
logger.info(f"Vector store saved to {index_path} and {metadata_path}")
def load_vector_store(index_path: Path, metadata_path: Path) -> FAISS:
"""Load the FAISS index and metadata."""
embeddings = HuggingFaceEmbeddings(
model_name=EMBEDDING_MODEL_NAME,
model_kwargs={'device': 'cpu'} # Change to 'cuda' if using GPU
)
vector_store = FAISS.load_local(
str(index_path),
embeddings,
str(metadata_path),
allow_dangerous_serialization=True # Acknowledge the risk if you trust the source
)
logger.info(f"Vector store loaded from {index_path} and {metadata_path}")
return vector_store
def query_vector_store(vector_store: FAISS, query: str, k: int = 5) -> List[Dict]:
"""Query the vector store and get top k documents."""
docs = vector_store.similarity_search(query, k=k)
results = []
for doc in docs:
result = {
'content': doc.page_content,
'metadata': doc.metadata
}
results.append(result)
return results
python
import os
import sys
import logging
import argparse
import shutil
import multiprocessing
from multiprocessing import Pool
from pathlib import Path
from typing import List, Tuple, Optional
import fitz # PyMuPDF for PDF processing
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModel
import torch
import faiss
import numpy as np
# Set up logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# Constants
EMBEDDING_MODEL_NAME = 'sentence-transformers/all-MiniLM-L6-v2' # Fast and lightweight model
CHUNK_SIZE = 512 # Adjust based on your needs
CPU_COUNT = multiprocessing.cpu_count()
def extract_text_from_pdf(pdf_path: Path) -> str:
"""
Extract text from a PDF file using PyMuPDF.
"""
try:
with fitz.open(pdf_path) as doc:
text = ""
for page in doc:
text += page.get_text()
return text
except Exception as e:
logger.error(f"Error reading PDF file {pdf_path}: {e}")
return ""
def extract_text_from_txt(txt_path: Path) -> str:
"""
Extract text from a txt file.
"""
try:
with open(txt_path, 'r', encoding='utf-8') as f:
return f.read()
except Exception as e:
logger.error(f"Error reading TXT file {txt_path}: {e}")
return ""
def process_file(file_path: Path) -> Tuple[str, str]:
"""
Reads a file and returns its text content along with the file name.
"""
ext = file_path.suffix.lower()
if ext == '.pdf':
text = extract_text_from_pdf(file_path)
elif ext == '.txt':
text = extract_text_from_txt(file_path)
else:
logger.warning(f"Unsupported file type: {file_path}")
return "", ""
return text, str(file_path)
def chunk_text(text: str, chunk_size: int) -> List[str]:
"""
Splits the text into chunks of specified size.
"""
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL_NAME)
tokens = tokenizer.tokenize(text)
chunks = []
for i in range(0, len(tokens), chunk_size):
chunk_tokens = tokens[i:i + chunk_size]
chunk_text = tokenizer.convert_tokens_to_string(chunk_tokens)
chunks.append(chunk_text)
return chunks
def embed_texts(texts: List[str], model_name: str) -> np.ndarray:
"""
Generates embeddings for a list of texts using a specified model.
"""
device = 'cuda' if torch.cuda.is_available() else 'cpu'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name).to(device)
embeddings = []
with torch.no_grad():
for text in texts:
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True).to(device)
outputs = model(**inputs)
# Mean pooling
embedding = outputs.last_hidden_state.mean(dim=1).cpu().numpy()
embeddings.append(embedding)
embeddings = np.vstack(embeddings)
return embeddings
def create_symlink(target: Path, link_name: Path) -> None:
"""
Creates a symlink pointing to target named link_name.
"""
try:
link_name.parent.mkdir(parents=True, exist_ok=True)
if link_name.exists() or link_name.is_symlink():
link_name.unlink()
os.symlink(target, link_name)
except OSError as e:
logger.error(f"Failed to create symlink {link_name} -> {target}: {e}")
def process_and_chunk_file(args: Tuple[Path, int]) -> List[Tuple[str, np.ndarray, str]]:
"""
Processes a single file: extracts text, chunks it, and generates embeddings.
Returns a list of tuples with (chunk_text, embedding, source_info).
"""
file_path, chunk_size = args
text, source = process_file(file_path)
if not text:
return []
chunks = chunk_text(text, chunk_size)
if not chunks:
return []
embeddings = embed_texts(chunks, EMBEDDING_MODEL_NAME)
results = []
for chunk_text, embedding in zip(chunks, embeddings):
results.append((chunk_text, embedding, source))
return results
def build_vector_database(data: List[Tuple[str, np.ndarray, str]]) -> faiss.IndexFlatL2:
"""
Builds a FAISS vector database from the embeddings.
Returns the FAISS index.
"""
if not data:
logger.error("No data provided to build vector database.")
raise ValueError("Data list is empty.")
embeddings = np.vstack([item[1] for item in data])
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(embeddings)
return index
def save_vector_database(index: faiss.IndexFlatL2, path: Path) -> None:
"""
Saves the FAISS index to the specified path.
"""
try:
faiss.write_index(index, str(path))
logger.info(f"Vector database saved to {path}")
except Exception as e:
logger.error(f"Failed to save vector database: {e}")
def main(input_paths: List[Path], output_dir: Path) -> None:
"""
Main processing function.
"""
try:
pool = Pool(processes=CPU_COUNT)
args = [(path, CHUNK_SIZE) for path in input_paths]
results = []
logger.info("Starting file processing and embedding generation...")
for res in tqdm(pool.imap_unordered(process_and_chunk_file, args), total=len(args), desc="Processing files"):
if res:
results.extend(res)
pool.close()
pool.join()
if not results:
logger.error("No results to process.")
return
# Build vector database
logger.info("Building vector database...")
index = build_vector_database(results)
# Save vector database
vector_db_path = output_dir / 'vector_database.index'
vector_db_path.parent.mkdir(parents=True, exist_ok=True)
save_vector_database(index, vector_db_path)
# Save metadata and create symlinks
logger.info("Saving metadata and creating symlinks...")
metadata_path = output_dir / 'metadata.txt'
symlink_dir = output_dir / 'symlinks'
symlink_dir.mkdir(parents=True, exist_ok=True)
with open(metadata_path, 'w', encoding='utf-8') as f:
for i, (chunk_text, _, source) in enumerate(results):
f.write(f"{i}\t{source}\n")
# Save chunk text to file
chunk_file = output_dir / f"chunk_{i}.txt"
with open(chunk_file, 'w', encoding='utf-8') as cf:
cf.write(chunk_text)
# Create symlink in symlink directory
symlink_path = symlink_dir / f"chunk_{i}.txt"
create_symlink(chunk_file, symlink_path)
logger.info(f"Processing completed successfully. Outputs are saved in {output_dir}")
except Exception as e:
logger.error(f"An error occurred during processing: {e}")
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Process documents and create a vector database.")
parser.add_argument('inputs', nargs='+', help="Input file(s) or directory(ies). Accepts PDFs and txt files.")
parser.add_argument('--output', required=True, help="Output directory to save vector database and metadata.")
args = parser.parse_args()
input_paths = []
for input_path in args.inputs:
path = Path(input_path)
if path.is_file() and path.suffix.lower() in {'.pdf', '.txt'}:
input_paths.append(path)
elif path.is_dir():
for ext in ('**/*.pdf', '**/*.txt'):
input_paths.extend(path.glob(ext))
else:
logger.warning(f"Input path {input_path} is not a valid file or directory.")
if not input_paths:
logger.error("No valid input files found.")
sys.exit(1)
output_dir = Path(args.output)
main(input_paths, output_dir)
This Python script efficiently processes PDF and text files to create a vector database using multiprocessing and advanced chunking techniques. It adheres to PEP-8 standards, includes comprehensive error handling, and utilizes type hints for clarity.
Key Features:
Multiprocessing: Uses all CPU cores to process files in parallel, significantly reducing processing time.
Efficient Chunking: Splits documents into chunks based on token counts to ensure zero data loss and optimal text segmentation.
Embedding Generation: Utilizes a lightweight and fast pre-trained transformer model (sentence-transformers/all-MiniLM-L6-v2) for generating embeddings.
Vector Database Creation: Builds a FAISS index for efficient similarity search and saves it for future queries.
Symlink Creation: Creates symlinks for each text chunk, allowing easy access and inspection through the file system or a browser.
Comprehensive Error Handling: Gracefully handles exceptions and provides meaningful error messages to aid in debugging and robustness.
Type Hints: Uses Python's typing module to add type hints throughout the code, improving readability and maintainability.
FAISS (pip install faiss-cpu or pip install faiss-gpu)
Notes:
The script checks for CUDA availability and utilizes the GPU if available, significantly speeding up embedding generation.
Ensure that the input files are accessible and that you have the necessary permissions to read them.
The output directory will contain the vector database (vector_database.index), metadata file (metadata.txt), chunk files, and symlinks.
Error Handling:
If an unsupported file type is encountered, a warning is logged, and the file is skipped.
If there's an error reading a file or during processing, it's logged with an error message, and the script continues with other files.
Performance Optimization:
The use of multiprocessing and efficient data structures ensures that the script can handle large datasets quickly.
The embedding model chosen balances performance and speed, making the script suitable for real-time or large-scale applications.
Conclusion:
This script provides a robust, efficient, and scalable solution for processing documents and creating a vector database. By following best practices and focusing on performance, it ensures that even large datasets are handled seamlessly.
Let me know if you have any questions or need further assistance!