File size: 4,183 Bytes
7af9206
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""
ingest.py
---------
Step 2: Embed Q&A pairs with sentence-transformers β†’ store in ChromaDB.
Output: chroma_db/  (vector index - commit this folder to GitHub!)

Run once locally after preprocess.py:
    python ingest.py
"""

import pandas as pd
import chromadb
from chromadb.config import Settings
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
import os
import sys

PARQUET_PATH = "data/clean_qa.parquet"
CHROMA_PATH  = "chroma_db"
COLLECTION   = "python_qa"
BATCH_SIZE   = 128
MODEL_NAME   = "all-MiniLM-L6-v2"   # ~90MB, downloads once, very fast at inference

# ─── Guard: skip if already ingested ─────────────────────────────────────────
if os.path.exists(CHROMA_PATH) and os.listdir(CHROMA_PATH):
    print(f"βœ… ChromaDB already exists at '{CHROMA_PATH}'. Skipping ingestion.")
    print("   Delete the folder and re-run to re-index.")
    sys.exit(0)

# ─── Load data ────────────────────────────────────────────────────────────────
if not os.path.exists(PARQUET_PATH):
    print("❌ data/clean_qa.parquet not found. Run preprocess.py first.")
    sys.exit(1)

print(f"πŸ“‚ Loading {PARQUET_PATH}...")
df = pd.read_parquet(PARQUET_PATH)
print(f"   βœ… {len(df):,} Q&A pairs loaded")

# ─── Build the document string that will be embedded ─────────────────────────
# Format: "Q: <title>\n<question_body>\nA: <answer_body>"
# We cap lengths so single docs don't blow up memory
df["document"] = df.apply(
    lambda r: (
        f"Q: {r['title']}\n"
        f"{str(r['question_body'])[:600]}\n\n"
        f"A: {str(r['answer_body'])[:900]}"
    ),
    axis=1,
)

# ─── Load embedding model ─────────────────────────────────────────────────────
print(f"\nπŸ€– Loading embedding model '{MODEL_NAME}'...")
print("   (Downloads ~90MB on first run, cached afterwards)")
model = SentenceTransformer(MODEL_NAME)
print("   βœ… Model ready")

# ─── Setup ChromaDB ───────────────────────────────────────────────────────────
print(f"\n Setting up ChromaDB at '{CHROMA_PATH}'...")
client = chromadb.PersistentClient(
    path=CHROMA_PATH,
    settings=Settings(anonymized_telemetry=False)
)

# Fresh collection
try:
    client.delete_collection(COLLECTION)
except Exception:
    pass

collection = client.create_collection(
    name=COLLECTION,
    metadata={"hnsw:space": "cosine"},   # cosine similarity for semantic search
)

# ─── Embed & Index in batches ─────────────────────────────────────────────────
print(f"\nβš™οΈ  Embedding and indexing {len(df):,} documents (batch={BATCH_SIZE})...")
print("   This takes ~5-15 minutes on CPU. Grab a coffee β˜•")

total_indexed = 0
for i in tqdm(range(0, len(df), BATCH_SIZE), desc="Indexing"):
    batch = df.iloc[i : i + BATCH_SIZE]

    docs   = batch["document"].tolist()
    ids    = [str(qid) for qid in batch["question_id"].tolist()]
    metas  = [
        {
            "title":          str(row["title"])[:200],
            "question_score": int(row["question_score"]),
            "answer_score":   int(row["answer_score"]),
        }
        for _, row in batch.iterrows()
    ]

    embeddings = model.encode(docs, show_progress_bar=False).tolist()

    collection.add(
        documents=docs,
        embeddings=embeddings,
        ids=ids,
        metadatas=metas,
    )
    total_indexed += len(batch)

print(f"\nβœ… Done! Indexed {collection.count():,} documents into ChromaDB")
print(f"   Folder: {os.path.abspath(CHROMA_PATH)}")
print("\nπŸ“Œ Next step: commit the 'chroma_db/' folder to your GitHub repo")
print("   Then deploy to Render β€” no re-indexing needed!")