Spaces:
Sleeping

File size: 2,613 Bytes
1a2633a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""
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)