Spaces:
Sleeping
Sleeping
Download src/chunking.py from kaustuvkunal/pdf-rag: direct link, hf CLI and curl.
- Browser
- Download file 2.06 kB
-
https://huggingface.co/spaces/kaustuvkunal/pdf-rag/resolve/main/src/chunking.py
- Command line
-
hf download hf://spaces/kaustuvkunal/pdf-rag/src/chunking.py
-
curl -L -o chunking.py https://huggingface.co/spaces/kaustuvkunal/pdf-rag/resolve/main/src/chunking.py
2.06 kB
| from __future__ import annotations | |
| from langchain_text_splitters import ( | |
| RecursiveCharacterTextSplitter, | |
| CharacterTextSplitter, | |
| TokenTextSplitter, | |
| MarkdownHeaderTextSplitter, | |
| ) | |
| from src.logger import logger | |
| from src.config import settings | |
| def get_chunker(config=settings, strategy: str | None = None): | |
| strategy = (strategy or config.chunk_strategy).lower() | |
| size = config.chunk_size | |
| overlap = config.chunk_overlap | |
| logger.info( | |
| "Initializing chunker", | |
| context={"strategy": strategy, "size": size, "overlap": overlap}, | |
| ) | |
| if strategy == "recursive": | |
| return RecursiveCharacterTextSplitter( | |
| chunk_size=size, | |
| chunk_overlap=overlap, | |
| separators=["\n\n", "\n", " ", ""], | |
| ) | |
| if strategy == "character": | |
| return CharacterTextSplitter( | |
| chunk_size=size, | |
| chunk_overlap=overlap, | |
| separator="\n", | |
| ) | |
| if strategy == "token": | |
| return TokenTextSplitter( | |
| chunk_size=size, | |
| chunk_overlap=overlap, | |
| ) | |
| if strategy == "markdown": | |
| headers_to_split_on = [ | |
| ("#", "Header 1"), | |
| ("##", "Header 2"), | |
| ("###", "Header 3"), | |
| ] | |
| return MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on) | |
| if strategy == "code": | |
| return RecursiveCharacterTextSplitter.from_language( | |
| language="python", | |
| chunk_size=size, | |
| chunk_overlap=overlap, | |
| ) | |
| if strategy == "semantic": | |
| try: | |
| from langchain_experimental.text_splitter import SemanticChunker | |
| from src.embedding_model import get_embeddings | |
| return SemanticChunker(get_embeddings()) | |
| except ImportError as e: | |
| raise ValueError( | |
| "Semantic chunking requires langchain-experimental. " | |
| "Install with: pip install langchain-experimental" | |
| ) from e | |
| raise ValueError(f"Unsupported chunk strategy: {strategy}") |