Spaces:
Sleeping
Sleeping
Download src/parser.py from veltrixcode/businesslawrag: direct link, hf CLI and curl.
- Browser
- Download file 1.2 kB
-
https://huggingface.co/spaces/veltrixcode/businesslawrag/resolve/main/src/parser.py
- Command line
-
hf download hf://spaces/veltrixcode/businesslawrag/src/parser.py
-
curl -L -o parser.py https://huggingface.co/spaces/veltrixcode/businesslawrag/resolve/main/src/parser.py
1.2 kB
| import os | |
| import re | |
| from typing import List, Dict, Any | |
| from pypdf import PdfReader | |
| def extract_pdf_pages(pdf_path: str, metadata: Dict[str, Any] = None) -> List[Dict[str, Any]]: | |
| """ | |
| Extracts text from each page of a PDF file, tracking page numbers, | |
| book title, chapter name, and clean text. | |
| """ | |
| if metadata is None: | |
| metadata = {} | |
| pages_data = [] | |
| reader = PdfReader(pdf_path) | |
| total_pages = len(reader.pages) | |
| for idx, page in enumerate(reader.pages): | |
| raw_text = page.extract_text() or "" | |
| # Clean redundant linebreaks / extra whitespace while keeping paragraph structure | |
| clean_text = re.sub(r'[ \t]+', ' ', raw_text) | |
| clean_text = re.sub(r'\n\s*\n+', '\n\n', clean_text).strip() | |
| if not clean_text: | |
| continue | |
| pages_data.append({ | |
| "pdf_filename": os.path.basename(pdf_path), | |
| "title": metadata.get("title", os.path.basename(pdf_path)), | |
| "chapter": metadata.get("chapter", "General"), | |
| "page_number": idx + 1, | |
| "total_pages": total_pages, | |
| "text": clean_text | |
| }) | |
| return pages_data | |