Spaces:
Runtime error
Runtime error
Download utils/pdf_processor.py from Pridhvi2297/AI: direct link, hf CLI and curl.
- Browser
- Download file 1.08 kB
-
https://huggingface.co/spaces/Pridhvi2297/AI/resolve/main/utils/pdf_processor.py
- Command line
-
hf download hf://spaces/Pridhvi2297/AI/utils/pdf_processor.py
-
curl -L -o pdf_processor.py https://huggingface.co/spaces/Pridhvi2297/AI/resolve/main/utils/pdf_processor.py
1.08 kB
| import os | |
| from PyPDF2 import PdfReader | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| def extract_text_from_pdf(pdf_path): | |
| """Extract text from PDF with page numbers.""" | |
| reader = PdfReader(pdf_path) | |
| text_with_pages = [] | |
| for page_num, page in enumerate(reader.pages, start=1): | |
| text = page.extract_text() | |
| text_with_pages.append({ | |
| "page": page_num, | |
| "content": text | |
| }) | |
| return text_with_pages | |
| def chunk_documents(text_with_pages, chunk_size=1000, chunk_overlap=200): | |
| """Split text into chunks while preserving page numbers.""" | |
| text_splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=chunk_size, | |
| chunk_overlap=chunk_overlap, | |
| length_function=len | |
| ) | |
| chunks = [] | |
| for page_data in text_with_pages: | |
| page_chunks = text_splitter.split_text(page_data["content"]) | |
| for chunk in page_chunks: | |
| chunks.append({ | |
| "content": chunk, | |
| "page": page_data["page"] | |
| }) | |
| return chunks | |