Spaces:
Sleeping
Sleeping
File size: 5,465 Bytes
a93a6b1 | 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 | import os
import json
import re
from pathlib import Path
import pdfplumber
from openai import OpenAI
import chromadb
from chromadb.utils import embedding_functions
from dotenv import load_dotenv
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
PDF_PATH = "sample-service-manual 1 (1).pdf"
CHUNKS_DIR = "chunks"
COLLECTION_NAME = "ford_f150_suspension"
client = OpenAI(api_key=OPENAI_API_KEY)
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
api_key=OPENAI_API_KEY,
model_name="text-embedding-3-large"
)
def clean_text(text):
"""
Clean extracted text
Args:
text: Raw text
Returns:
Cleaned text
"""
if not text:
return ""
text = re.sub(r'\(cid:122\)', '', text)
text = re.sub(r'\(cid:\d+\)', '', text)
text = re.sub(r'file:///.*', '', text, flags=re.IGNORECASE)
text = re.sub(r'\s+', ' ', text).strip()
return text
def table_to_markdown(table):
"""
Convert table to Markdown format
Args:
table: Table data
Returns:
Markdown formatted table
"""
if not table or len(table) < 2:
return ""
md = []
header = [str(col).strip() if col else "" for col in table[0]]
md.append("| " + " | ".join(header) + " |")
md.append("| " + "---|" * len(header))
for row in table[1:]:
cleaned_row = [str(cell).strip().replace("\n", " ") if cell else "" for cell in row]
md.append("| " + " | ".join(cleaned_row) + " |")
return "\n".join(md)
def extract_and_chunk_pdf():
"""
Extract and chunk PDF
Returns:
List of chunks
"""
chunks = []
output_path = Path(CHUNKS_DIR)
output_path.mkdir(exist_ok=True)
with pdfplumber.open(PDF_PATH) as pdf:
for page_num, page in enumerate(pdf.pages, 1):
print(f"Processing page {page_num}...")
full_text = page.extract_text() or ""
cleaned_full = clean_text(full_text)
tables = page.extract_tables()
for idx, table in enumerate(tables):
if table and len(table) > 1:
md_table = table_to_markdown(table)
chunk = {
"chunk_id": len(chunks) + 1,
"page": page_num,
"type": "table",
"parent_section": "Suspension System Manual",
"section": f"Table Page {page_num}",
"content": f"Table on Page {page_num}\n\n{md_table}",
"metadata": {"doc_type": "ford_f150_manual", "topic": "suspension", "has_table": True}
}
chunks.append(chunk)
if cleaned_full:
pattern = r'(?=(Inspection and Verification|Visual Inspection Chart|Symptom Chart|Pinpoint Test|Ball Joint Inspection|Camber and Caster|Ride Height Measurement))'
sections = re.split(pattern, full_text, flags=re.IGNORECASE)
current_parent = "Suspension System"
for section in sections:
cleaned = clean_text(section)
if len(cleaned) < 80:
continue
if re.search(pattern, section, re.IGNORECASE):
current_parent = clean_text(section.split('\n')[0])
chunk = {
"chunk_id": len(chunks) + 1,
"page": page_num,
"type": "text",
"parent_section": current_parent,
"section": current_parent,
"content": cleaned,
"metadata": {"doc_type": "ford_f150_manual", "topic": "suspension", "has_table": False}
}
chunks.append(chunk)
json_path = output_path / "suspension_chunks_final.json"
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(chunks, f, indent=2, ensure_ascii=False)
print(f"Chunking done! Total chunks: {len(chunks)}")
return chunks
def create_vector_db(chunks):
"""
Create vector database with embeddings
Args:
chunks: List of chunks
Returns:
ChromaDB collection
"""
print("Creating Chroma vector database with OpenAI embeddings...")
chroma_client = chromadb.PersistentClient(path="chroma_db")
collection = chroma_client.get_or_create_collection(
name=COLLECTION_NAME,
embedding_function=openai_ef,
metadata={"hnsw:space": "cosine"}
)
documents = []
metadatas = []
ids = []
for chunk in chunks:
embed_text = f"Section: {chunk['parent_section']}\n{chunk['content']}"
documents.append(embed_text)
metadatas.append({
"page": chunk["page"],
"type": chunk["type"],
"parent_section": chunk["parent_section"],
"has_table": chunk["metadata"].get("has_table", False)
})
ids.append(f"chunk_{chunk['chunk_id']}")
collection.add(
documents=documents,
metadatas=metadatas,
ids=ids
)
print(f"Vector DB created successfully!")
print(f"Collection '{COLLECTION_NAME}' contains {len(chunks)} documents")
return collection
if __name__ == "__main__":
chunks = extract_and_chunk_pdf()
collection = create_vector_db(chunks)
print("Pipeline Complete! Ready for RAG queries.")
|