Spaces:
Sleeping
Sleeping
File size: 7,438 Bytes
4e3ac7f | 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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | """
RAG pipeline — lightweight in-memory TF-IDF search over curriculum chunks.
No heavy dependencies (works on Python 3.14+).
"""
import json
import math
import os
import re
from collections import Counter
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
_index = None # lazy singleton
class CurriculumIndex:
"""Simple TF-IDF based search over curriculum chunks."""
def __init__(self):
self.chunks = [] # list of {id, text, metadata}
self.idf = {} # word -> idf score
self.tfidf_vecs = [] # list of {word: tfidf_score} dicts
def _tokenize(self, text):
return re.findall(r"[a-z0-9]+", text.lower())
def add_chunks(self, chunks):
self.chunks = chunks
doc_count = len(chunks)
# Build document frequency
df = Counter()
tokenized = []
for c in chunks:
tokens = self._tokenize(c["text"])
unique = set(tokens)
for w in unique:
df[w] += 1
tokenized.append(tokens)
# IDF
self.idf = {}
for w, count in df.items():
self.idf[w] = math.log((doc_count + 1) / (count + 1)) + 1
# TF-IDF vectors per chunk
self.tfidf_vecs = []
for tokens in tokenized:
tf = Counter(tokens)
total = len(tokens) if tokens else 1
vec = {}
for w, count in tf.items():
vec[w] = (count / total) * self.idf.get(w, 1.0)
self.tfidf_vecs.append(vec)
def search(self, query, level="", n_results=4):
query_tokens = self._tokenize(query)
if not query_tokens:
return []
# Query TF-IDF
qtf = Counter(query_tokens)
qtotal = len(query_tokens)
qvec = {}
for w, count in qtf.items():
qvec[w] = (count / qtotal) * self.idf.get(w, 1.0)
# Cosine similarity
scores = []
for i, dvec in enumerate(self.tfidf_vecs):
# Optional level filter
if level and self.chunks[i]["metadata"].get("level") != level:
continue
dot = sum(qvec.get(w, 0) * dvec.get(w, 0) for w in qvec)
mag_q = math.sqrt(sum(v ** 2 for v in qvec.values()))
mag_d = math.sqrt(sum(v ** 2 for v in dvec.values()))
if mag_q == 0 or mag_d == 0:
sim = 0
else:
sim = dot / (mag_q * mag_d)
scores.append((sim, i))
scores.sort(reverse=True)
results = []
for sim, idx in scores[:n_results]:
if sim > 0:
c = self.chunks[idx]
results.append({
"text": c["text"],
"metadata": c["metadata"],
"score": round(sim, 4),
})
return results
def _flatten_curriculum(data):
"""Walk curriculum JSON and produce flat list of searchable chunks."""
chunks = []
for level_key, level_data in data.items():
level_label = level_data.get("label", level_key)
strands = level_data.get("strands", {})
for strand_key, strand_data in strands.items():
strand_label = strand_data.get("label", strand_key)
topics = strand_data.get("topics", {})
for topic_key, topic_data in topics.items():
topic_label = topic_data.get("label", topic_key)
# Primary: outcomes_by_stage
outcomes_by_stage = topic_data.get("outcomes_by_stage", {})
for stage, outcomes in outcomes_by_stage.items():
stage_info = data[level_key].get("stages", {}).get(stage, {})
stage_label = stage_info.get("label", stage)
classes = ", ".join(stage_info.get("classes", []))
text = (
f"Level: {level_label}\n"
f"Stage: {stage_label} ({classes})\n"
f"Strand: {strand_label}\n"
f"Topic: {topic_label}\n"
f"Learning Outcomes:\n"
)
for o in outcomes:
text += f" - {o}\n"
chunks.append({
"id": f"{level_key}_{strand_key}_{topic_key}_{stage}",
"text": text,
"metadata": {
"level": level_key,
"level_label": level_label,
"strand": strand_key,
"strand_label": strand_label,
"topic": topic_key,
"topic_label": topic_label,
"stage": stage,
"stage_label": stage_label,
"classes": classes,
},
})
# Secondary: flat outcomes
outcomes = topic_data.get("outcomes", [])
if outcomes:
levels_list = data[level_key].get("levels", [])
text = (
f"Level: {level_label}\n"
f"Available at: {', '.join(levels_list)}\n"
f"Strand: {strand_label}\n"
f"Topic: {topic_label}\n"
f"Learning Outcomes:\n"
)
for o in outcomes:
text += f" - {o}\n"
chunks.append({
"id": f"{level_key}_{strand_key}_{topic_key}",
"text": text,
"metadata": {
"level": level_key,
"level_label": level_label,
"strand": strand_key,
"strand_label": strand_label,
"topic": topic_key,
"topic_label": topic_label,
"stage": "",
"stage_label": "",
"classes": ", ".join(levels_list),
},
})
return chunks
def build_index():
"""Load curriculum.json and build the search index."""
global _index
curriculum_path = os.path.join(DATA_DIR, "curriculum.json")
with open(curriculum_path, "r", encoding="utf-8") as f:
data = json.load(f)
chunks = _flatten_curriculum(data)
_index = CurriculumIndex()
_index.add_chunks(chunks)
return len(chunks)
def search_curriculum(query, level="", n_results=4):
"""Search the curriculum index."""
global _index
if _index is None:
build_index()
return _index.search(query, level=level, n_results=n_results)
if __name__ == "__main__":
n = build_index()
print(f"Indexed {n} curriculum chunks")
print()
results = search_curriculum("fractions for 4th class")
for r in results:
m = r["metadata"]
print(f"[{r['score']}] {m['topic_label']} -- {m['stage_label'] or m['level_label']}")
print(r["text"][:150])
print()
|