Spaces:
Sleeping
Sleeping
Download rag.py from FunWith/irish-maths-ai: direct link, hf CLI and curl.
- Browser
- Download file 7.44 kB
-
https://huggingface.co/spaces/FunWith/irish-maths-ai/resolve/main/rag.py
- Command line
-
hf download hf://spaces/FunWith/irish-maths-ai/rag.py
-
curl -L -o rag.py https://huggingface.co/spaces/FunWith/irish-maths-ai/resolve/main/rag.py
7.44 kB
| """ | |
| 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() | |