Spaces:
Sleeping
Sleeping
Quincy Hsieh commited on
Commit ·
d2c4c08
1
Parent(s): b44881a
Add PDF reader example
Browse files
app.py
CHANGED
|
@@ -29,6 +29,7 @@ from chromadb.config import Settings
|
|
| 29 |
from sentence_transformers import SentenceTransformer
|
| 30 |
from huggingface_hub import InferenceClient
|
| 31 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
|
|
| 32 |
|
| 33 |
logging.basicConfig(level=logging.INFO)
|
| 34 |
logger = logging.getLogger(__name__)
|
|
@@ -86,6 +87,27 @@ logger.info(f"LLM client initialized for model: {LLM_MODEL_NAME}")
|
|
| 86 |
# Helper Functions
|
| 87 |
# ---------------------------------------------------------------------------
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
def chunk_text(text: str, source: str = "unknown") -> list[dict]:
|
| 90 |
"""
|
| 91 |
Split a document into smaller chunks for embedding.
|
|
@@ -278,12 +300,23 @@ def ingest_sample_documents():
|
|
| 278 |
logger.warning("No sample_documents directory found.")
|
| 279 |
return
|
| 280 |
|
|
|
|
| 281 |
for file_path in SAMPLE_DOCS_DIR.glob("*.txt"):
|
| 282 |
-
logger.info(f"Ingesting: {file_path.name}")
|
| 283 |
text = file_path.read_text(encoding="utf-8")
|
| 284 |
chunks = chunk_text(text, source=file_path.name)
|
| 285 |
add_documents_to_vectorstore(chunks)
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
logger.info(f"Sample document ingestion complete. Total chunks: {collection.count()}")
|
| 288 |
|
| 289 |
|
|
|
|
| 29 |
from sentence_transformers import SentenceTransformer
|
| 30 |
from huggingface_hub import InferenceClient
|
| 31 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 32 |
+
from pypdf import PdfReader
|
| 33 |
|
| 34 |
logging.basicConfig(level=logging.INFO)
|
| 35 |
logger = logging.getLogger(__name__)
|
|
|
|
| 87 |
# Helper Functions
|
| 88 |
# ---------------------------------------------------------------------------
|
| 89 |
|
| 90 |
+
def extract_text_from_pdf(pdf_path: Path) -> str:
|
| 91 |
+
"""
|
| 92 |
+
Extract text content from a PDF file using pypdf.
|
| 93 |
+
|
| 94 |
+
This demonstrates how to convert PDF documents into plain text
|
| 95 |
+
for downstream embedding. Each page is extracted sequentially
|
| 96 |
+
and concatenated with page separators for traceability.
|
| 97 |
+
"""
|
| 98 |
+
reader = PdfReader(str(pdf_path))
|
| 99 |
+
pages_text = []
|
| 100 |
+
|
| 101 |
+
for page_num, page in enumerate(reader.pages, start=1):
|
| 102 |
+
text = page.extract_text()
|
| 103 |
+
if text and text.strip():
|
| 104 |
+
pages_text.append(f"[Page {page_num}]\n{text.strip()}")
|
| 105 |
+
|
| 106 |
+
full_text = "\n\n".join(pages_text)
|
| 107 |
+
logger.info(f"Extracted {len(reader.pages)} pages from PDF: {pdf_path.name} ({len(full_text)} chars)")
|
| 108 |
+
return full_text
|
| 109 |
+
|
| 110 |
+
|
| 111 |
def chunk_text(text: str, source: str = "unknown") -> list[dict]:
|
| 112 |
"""
|
| 113 |
Split a document into smaller chunks for embedding.
|
|
|
|
| 300 |
logger.warning("No sample_documents directory found.")
|
| 301 |
return
|
| 302 |
|
| 303 |
+
# Ingest plain text files
|
| 304 |
for file_path in SAMPLE_DOCS_DIR.glob("*.txt"):
|
| 305 |
+
logger.info(f"Ingesting text file: {file_path.name}")
|
| 306 |
text = file_path.read_text(encoding="utf-8")
|
| 307 |
chunks = chunk_text(text, source=file_path.name)
|
| 308 |
add_documents_to_vectorstore(chunks)
|
| 309 |
|
| 310 |
+
# Ingest PDF files (e.g., ebook-a-compact-guide-to-pretraining-custom-llms.pdf)
|
| 311 |
+
for file_path in SAMPLE_DOCS_DIR.glob("*.pdf"):
|
| 312 |
+
logger.info(f"Ingesting PDF file: {file_path.name}")
|
| 313 |
+
text = extract_text_from_pdf(file_path)
|
| 314 |
+
if text.strip():
|
| 315 |
+
chunks = chunk_text(text, source=file_path.name)
|
| 316 |
+
add_documents_to_vectorstore(chunks)
|
| 317 |
+
else:
|
| 318 |
+
logger.warning(f"No extractable text found in: {file_path.name}")
|
| 319 |
+
|
| 320 |
logger.info(f"Sample document ingestion complete. Total chunks: {collection.count()}")
|
| 321 |
|
| 322 |
|