with open("data/chunks.json", "w", encoding="utf-8") as f:
json.dump(chunks, f, indent=2, ensure_ascii=False)
improve and optimized chunking and give me updated code
import os
import pdfplumber
import json
import re
from typing import List, Dict, Any, Optional
# --- CONFIGURATION ---
# Use a dictionary for configuration to keep settings organized
CONFIG = {
"data_dir": "data",
"output_file": "data/chunks_improved.json",
"max_chars": 1500, # Increased for more context, balanced by semantic splitting
"overlap": 150, # Overlap is more effective with semantic chunking
}
def format_table_as_markdown(table: List[List[Optional[str]]]) -> str:
"""Converts a list-of-lists table into a Markdown string."""
markdown_rows = []
# Clean and prepare header
header = [str(cell).strip() if cell is not None else "" for cell in table[0]]
markdown_rows.append("| " + " | ".join(header) + " |")
# Prepare separator
separator = ["---" for _ in header]
markdown_rows.append("| " + " | ".join(separator) + " |")
# Prepare data rows
for row in table[1:]:
cleaned_row = [str(cell).strip().replace("\n", " ") if cell is not None else "" for cell in row]
markdown_rows.append("| " + " | ".join(cleaned_row) + " |")
return "\n".join(markdown_rows)
def split_text_semantically(text: str, max_chars: int, overlap: int) -> List[str]:
"""
Splits text into chunks, trying to preserve semantic boundaries (paragraphs, sentences).
"""
if not text:
return []
# 1. Split by paragraphs
paragraphs = text.split('\n\n')
chunks = []
current_chunk = ""
for para in paragraphs:
if not para.strip():
continue
# If a paragraph fits, or adding it to the current chunk still fits, combine them.
if len(current_chunk) + len(para) + 1 <= max_chars:
current_chunk += para + "\n\n"
else:
# If the current chunk is not empty, store it
if current_chunk:
chunks.append(current_chunk.strip())
# If the paragraph itself is too long, split it further
if len(para) > max_chars:
# Fallback to sentence splitting for very long paragraphs
sentences = re.split(r'(?<=[.!?])\s+', para)
sub_chunk = ""
for sentence in sentences:
if len(sub_chunk) + len(sentence) + 1 <= max_chars:
sub_chunk += sentence + " "
else:
if sub_chunk:
chunks.append(sub_chunk.strip())
sub_chunk = sentence + " "
if sub_chunk: # Add the last sub_chunk
chunks.append(sub_chunk.strip())
current_chunk = "" # Reset current chunk
else:
current_chunk = para + "\n\n"
# Add the last remaining chunk
if current_chunk:
chunks.append(current_chunk.strip())
# Note: A more complex overlap strategy could be implemented if needed,
# but semantic splitting often reduces the need for large overlaps.
# For simplicity, this implementation doesn't add explicit overlap between final chunks.
return chunks
def process_pdf(pdf_path: str, file_name: str, config: Dict[str, Any]) -> List[Dict[str, Any]]:
"""
Processes a single PDF file, extracting and chunking text and tables.
Returns a list of chunk dictionaries.
"""
chunks = []
try:
with pdfplumber.open(pdf_path) as pdf:
for i, page in enumerate(pdf.pages, start=1):
# Extract text with improved layout preservation
text = page.extract_text(x_tolerance=2, keep_blank_chars=True)
# Create text chunks using the semantic splitter
if text and text.strip():
text_chunks = split_text_semantically(text, config['max_chars'], config['overlap'])
for text_chunk in text_chunks:
chunks.append({
"type": "text",
"page_content": text_chunk,
"metadata": {"file": file_name, "page": i}
})
# Extract and process tables
tables = page.extract_tables()
for table in tables:
if table and any(any(cell and cell.strip() for cell in row) for row in table):
table_md = format_table_as_markdown(table)
chunks.append({
"type": "table",
"page_content": table_md,
"metadata": {"file": file_name, "page": i}
})
except Exception as e:
print(f"Error processing file {pdf_path}: {e}")
return chunks
def main():
"""Main function to run the PDF processing pipeline."""
data_dir = CONFIG["data_dir"]
# Ensure data directory exists
if not os.path.isdir(data_dir):
print(f"Error: Data directory '{data_dir}' not found.")
return
pdf_files = [f for f in os.listdir(data_dir) if f.lower().endswith(".pdf")]
if not pdf_files:
print(f"No PDF files found in '{data_dir}'.")
return
all_chunks = []
for pdf_file in pdf_files:
print(f"Processing {pdf_file}...")
pdf_path = os.path.join(data_dir, pdf_file)
file_chunks = process_pdf(pdf_path, pdf_file, CONFIG)
all_chunks.extend(file_chunks)
# Write the final chunks to a JSON file
output_path = CONFIG["output_file"]
with open(output_path, "w", encoding="utf-8") as f:
json.dump(all_chunks, f, indent=2, ensure_ascii=False)
print(f"\nProcessing complete. {len(all_chunks)} chunks saved to {output_path}")
if __name__ == "__main__":
main()