Spaces:
Sleeping
Sleeping
Quincy Hsieh commited on
Commit ·
d2c4c08
1
Parent(s): b44881a
Add PDF reader example
Browse files28 unmodified lines29303132333451 unmodified lines868788899091186 unmodified lines27827928028128228328428528628728828928 unmodified linesfrom sentence_transformers import SentenceTransformerfrom huggingface_hub import InferenceClientfrom langchain_text_splitters import RecursiveCharacterTextSplitterlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)51 unmodified lines# Helper Functions# ---------------------------------------------------------------------------def chunk_text(text: str, source: str = "unknown") -> list[dict]:"""Split a document into smaller chunks for embedding.186 unmodified lineslogger.warning("No sample_documents directory found.")returnfor file_path in SAMPLE_DOCS_DIR.glob("*.txt"):logger.info(f"Ingesting: {file_path.name}")text = file_path.read_text(encoding="utf-8")chunks = chunk_text(text, source=file_path.name)add_documents_to_vectorstore(chunks)logger.info(f"Sample document ingestion complete. Total chunks: {collection.count()}")28 unmodified lines2930313233343551 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113186 unmodified lines30030130230330430530630730830931031131231331431531631731831932032132228 unmodified linesfrom sentence_transformers import SentenceTransformerfrom huggingface_hub import InferenceClientfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom pypdf import PdfReaderlogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)51 unmodified lines# Helper Functions# ---------------------------------------------------------------------------def extract_text_from_pdf(pdf_path: Path) -> str:"""Extract text content from a PDF file using pypdf.This demonstrates how to convert PDF documents into plain textfor downstream embedding. Each page is extracted sequentiallyand concatenated with page separators for traceability."""reader = PdfReader(str(pdf_path))pages_text = []for page_num, page in enumerate(reader.pages, start=1):text = page.extract_text()if text and text.strip():pages_text.append(f"[Page {page_num}]\n{text.strip()}")full_text = "\n\n".join(pages_text)logger.info(f"Extracted {len(reader.pages)} pages from PDF: {pdf_path.name} ({len(full_text)} chars)")return full_textdef chunk_text(text: str, source: str = "unknown") -> list[dict]:"""Split a document into smaller chunks for embedding.186 unmodified lineslogger.warning("No sample_documents directory found.")return# Ingest plain text filesfor file_path in SAMPLE_DOCS_DIR.glob("*.txt"):logger.info(f"Ingesting text file: {file_path.name}")text = file_path.read_text(encoding="utf-8")chunks = chunk_text(text, source=file_path.name)add_documents_to_vectorstore(chunks)# Ingest PDF files (e.g., ebook-a-compact-guide-to-pretraining-custom-llms.pdf)for file_path in SAMPLE_DOCS_DIR.glob("*.pdf"):logger.info(f"Ingesting PDF file: {file_path.name}")text = extract_text_from_pdf(file_path)if text.strip():chunks = chunk_text(text, source=file_path.name)add_documents_to_vectorstore(chunks)else:logger.warning(f"No extractable text found in: {file_path.name}")logger.info(f"Sample document ingestion complete. Total chunks: {collection.count()}")
app.py+34-1