Spaces:
Sleeping
Sleeping
Download ingest.py from Fsubhan786/AIEngineer: direct link, hf CLI and curl.
- Browser
- Download file 2.61 kB
-
https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/ingest.py
- Command line
-
hf download hf://spaces/Fsubhan786/AIEngineer/ingest.py
-
curl -L -o ingest.py https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/ingest.py
2.61 kB
| """ | |
| ingest.py — Phase 2 RAG indexing pipeline. | |
| Loads documents → chunks them → embeds with a free local model → stores in Chroma. | |
| Free tools only: pypdf, sentence-transformers, chromadb. | |
| Usage: python ingest.py ./docs | |
| """ | |
| import os | |
| import sys | |
| import glob | |
| import chromadb | |
| from chromadb.utils import embedding_functions | |
| from pypdf import PdfReader | |
| STORE_PATH = "./store" | |
| COLLECTION = "knowledge_base" | |
| EMBED_MODEL = "all-MiniLM-L6-v2" # free, runs locally | |
| CHUNK_SIZE = 700 # ~tokens; tune per corpus | |
| CHUNK_OVERLAP = 100 # ~15% overlap preserves boundary context | |
| def read_text(path): | |
| """Extract text from a .pdf, .md, or .txt file.""" | |
| if path.lower().endswith(".pdf"): | |
| reader = PdfReader(path) | |
| return "\n".join((page.extract_text() or "") for page in reader.pages) | |
| with open(path, encoding="utf-8", errors="ignore") as f: | |
| return f.read() | |
| def chunk(text, size=CHUNK_SIZE, overlap=CHUNK_OVERLAP): | |
| """Split text into overlapping word-based chunks, respecting rough size.""" | |
| words = text.split() | |
| chunks, start = [], 0 | |
| while start < len(words): | |
| end = start + size | |
| piece = " ".join(words[start:end]).strip() | |
| if piece: | |
| chunks.append(piece) | |
| start += size - overlap # step forward, leaving overlap | |
| return chunks | |
| def build_index(docs_dir): | |
| client = chromadb.PersistentClient(path=STORE_PATH) | |
| ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=EMBED_MODEL) | |
| # Reset for a clean rebuild | |
| try: | |
| client.delete_collection(COLLECTION) | |
| except Exception: | |
| pass | |
| col = client.create_collection(COLLECTION, embedding_function=ef) | |
| documents, metadatas, ids = [], [], [] | |
| paths = [] | |
| for ext in ("*.pdf", "*.md", "*.txt"): | |
| paths.extend(glob.glob(os.path.join(docs_dir, "**", ext), recursive=True)) | |
| if not paths: | |
| print(f"No documents found in {docs_dir}. Add .pdf/.md/.txt files and retry.") | |
| return | |
| for path in paths: | |
| source = os.path.basename(path) | |
| for i, piece in enumerate(chunk(read_text(path))): | |
| documents.append(piece) | |
| metadatas.append({"source": source, "chunk": i}) | |
| ids.append(f"{source}-{i}") | |
| # Chroma embeds and stores in batches under the hood. | |
| col.add(documents=documents, metadatas=metadatas, ids=ids) | |
| print(f"Indexed {len(documents)} chunks from {len(paths)} files into '{COLLECTION}'.") | |
| if __name__ == "__main__": | |
| docs_dir = sys.argv[1] if len(sys.argv) > 1 else "./docs" | |
| build_index(docs_dir) | |