Spaces:
Sleeping
Sleeping
Download ingest.py from Pavankumardns/chatdocs: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/spaces/Pavankumardns/chatdocs/resolve/main/ingest.py
- Command line
-
hf download hf://spaces/Pavankumardns/chatdocs/ingest.py
-
curl -L -o ingest.py https://huggingface.co/spaces/Pavankumardns/chatdocs/resolve/main/ingest.py
2.49 kB
| import os | |
| from dotenv import load_dotenv | |
| from pinecone import Pinecone, ServerlessSpec | |
| from sentence_transformers import SentenceTransformer | |
| import PyPDF2 | |
| load_dotenv() | |
| # Initialize Pinecone | |
| pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY")) | |
| index_name = "pdf-rag" | |
| # Create index if it doesn't exist | |
| if index_name not in pc.list_indexes().names(): | |
| pc.create_index( | |
| name=index_name, | |
| dimension=384, # all-MiniLM-L6-v2 embedding size | |
| metric="cosine", | |
| spec=ServerlessSpec(cloud="aws", region="us-east-1") | |
| ) | |
| index = pc.Index(index_name) | |
| # Initialize embedding model | |
| model = SentenceTransformer('all-MiniLM-L6-v2') | |
| def extract_text_from_pdf(pdf_path): | |
| """Extract text from PDF file.""" | |
| with open(pdf_path, 'rb') as file: | |
| reader = PyPDF2.PdfReader(file) | |
| text = "" | |
| for page in reader.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| def chunk_text(text, chunk_size=500, overlap=50): | |
| """Split text into overlapping chunks.""" | |
| words = text.split() | |
| chunks = [] | |
| for i in range(0, len(words), chunk_size - overlap): | |
| chunk = " ".join(words[i:i + chunk_size]) | |
| chunks.append(chunk) | |
| return chunks | |
| def ingest_pdf(pdf_path): | |
| """Ingest a PDF document into Pinecone.""" | |
| print(f"Processing {pdf_path}...") | |
| # Extract text | |
| text = extract_text_from_pdf(pdf_path) | |
| # Chunk text | |
| chunks = chunk_text(text) | |
| print(f"Created {len(chunks)} chunks") | |
| # Create embeddings and upsert to Pinecone | |
| vectors = [] | |
| for i, chunk in enumerate(chunks): | |
| embedding = model.encode(chunk).tolist() | |
| vectors.append({ | |
| "id": f"{os.path.basename(pdf_path)}_chunk_{i}", | |
| "values": embedding, | |
| "metadata": { | |
| "text": chunk, | |
| "source": os.path.basename(pdf_path), | |
| "chunk_id": i | |
| } | |
| }) | |
| # Upsert in batches | |
| batch_size = 100 | |
| for i in range(0, len(vectors), batch_size): | |
| batch = vectors[i:i + batch_size] | |
| index.upsert(vectors=batch) | |
| print(f"Successfully ingested {pdf_path}") | |
| if __name__ == "__main__": | |
| import sys | |
| if len(sys.argv) < 2: | |
| print("Usage: python ingest.py <pdf_file_path>") | |
| sys.exit(1) | |
| pdf_path = sys.argv[1] | |
| if not os.path.exists(pdf_path): | |
| print(f"Error: File {pdf_path} not found") | |
| sys.exit(1) | |
| ingest_pdf(pdf_path) | |