Deign86 commited on
Commit
79993bc
·
verified ·
1 Parent(s): da42f1c

Upload backend/rag/curriculum_rag.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/rag/curriculum_rag.py +318 -0
backend/rag/curriculum_rag.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Updated curriculum RAG with exact match retrieval and 7-section notebook output.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from typing import Dict, List, Optional, Tuple
8
+
9
+
10
+ def _to_where(
11
+ subject: Optional[str] = None,
12
+ quarter: Optional[int] = None,
13
+ content_domain: Optional[str] = None,
14
+ chunk_type: Optional[str] = None,
15
+ module_id: Optional[str] = None,
16
+ lesson_id: Optional[str] = None,
17
+ competency_code: Optional[str] = None,
18
+ storage_path: Optional[str] = None,
19
+ ) -> Optional[Dict[str, object]]:
20
+ clauses = []
21
+ if subject:
22
+ clauses.append({"subject": {"$eq": subject}})
23
+ if quarter is not None:
24
+ clauses.append({"quarter": {"$eq": int(quarter)}})
25
+ if content_domain:
26
+ clauses.append({"content_domain": {"$eq": content_domain}})
27
+ if chunk_type:
28
+ clauses.append({"chunk_type": {"$eq": chunk_type}})
29
+ if module_id:
30
+ clauses.append({"module_id": {"$eq": module_id}})
31
+ if lesson_id:
32
+ clauses.append({"lesson_id": {"$eq": lesson_id}})
33
+ if competency_code:
34
+ clauses.append({"competency_code": {"$eq": competency_code}})
35
+ if storage_path:
36
+ clauses.append({"storage_path": {"$eq": storage_path}})
37
+ if not clauses:
38
+ return None
39
+ if len(clauses) == 1:
40
+ return clauses[0]
41
+ return {"$and": clauses}
42
+
43
+
44
+ def _distance_to_score(distance: float) -> float:
45
+ return round(1.0 / (1.0 + max(distance, 0.0)), 4)
46
+
47
+
48
+ def retrieve_curriculum_context(
49
+ query: str,
50
+ subject: str | None = None,
51
+ quarter: int | None = None,
52
+ content_domain: str | None = None,
53
+ chunk_type: str | None = None,
54
+ module_id: str | None = None,
55
+ lesson_id: str | None = None,
56
+ competency_code: str | None = None,
57
+ storage_path: str | None = None,
58
+ top_k: int = 8,
59
+ ) -> list[dict]:
60
+ from rag.vectorstore_loader import get_vectorstore_components
61
+
62
+ _, collection, embedder = get_vectorstore_components()
63
+ where = _to_where(subject, quarter, content_domain, chunk_type, module_id, lesson_id, competency_code, storage_path)
64
+
65
+ prefixed_query = f"Represent this sentence for searching relevant passages: {query}"
66
+ query_embedding = embedder.encode(
67
+ prefixed_query,
68
+ normalize_embeddings=True,
69
+ ).tolist()
70
+
71
+ result = collection.query(
72
+ query_embeddings=[query_embedding],
73
+ n_results=max(1, top_k),
74
+ where=where,
75
+ include=["documents", "metadatas", "distances"],
76
+ )
77
+
78
+ documents = (result.get("documents") or [[]])[0]
79
+ metadatas = (result.get("metadatas") or [[]])[0]
80
+ distances = (result.get("distances") or [[]])[0]
81
+
82
+ rows: List[dict] = []
83
+ for idx, content in enumerate(documents):
84
+ md = metadatas[idx] if idx < len(metadatas) and isinstance(metadatas[idx], dict) else {}
85
+ distance = float(distances[idx]) if idx < len(distances) else 1.0
86
+ rows.append({
87
+ "content": str(content or ""),
88
+ "subject": str(md.get("subject") or "unknown"),
89
+ "quarter": int(md.get("quarter") or 0),
90
+ "content_domain": str(md.get("content_domain") or "general"),
91
+ "chunk_type": str(md.get("chunk_type") or "concept"),
92
+ "source_file": str(md.get("source_file") or ""),
93
+ "storage_path": str(md.get("storage_path") or ""),
94
+ "module_id": str(md.get("module_id") or ""),
95
+ "lesson_id": str(md.get("lesson_id") or ""),
96
+ "competency_code": str(md.get("competency_code") or ""),
97
+ "page": int(md.get("page") or 0),
98
+ "score": _distance_to_score(distance),
99
+ })
100
+ return rows
101
+
102
+
103
+ def build_exact_lesson_query(
104
+ topic: str,
105
+ subject: str,
106
+ quarter: int,
107
+ lesson_title: str | None = None,
108
+ competency: str | None = None,
109
+ module_unit: str | None = None,
110
+ learner_level: str | None = None,
111
+ competency_code: str | None = None,
112
+ ) -> str:
113
+ parts = [topic, subject, f"Quarter {quarter}"]
114
+ for value in (lesson_title, competency, module_unit, learner_level, competency_code):
115
+ clean = str(value or "").strip()
116
+ if clean:
117
+ parts.append(clean)
118
+ return " | ".join(parts)
119
+
120
+
121
+ def build_lesson_query(
122
+ topic: str,
123
+ subject: str,
124
+ quarter: int,
125
+ *,
126
+ lesson_title: Optional[str] = None,
127
+ competency: Optional[str] = None,
128
+ module_unit: Optional[str] = None,
129
+ learner_level: Optional[str] = None,
130
+ ) -> str:
131
+ parts = [topic, subject, f"Quarter {quarter}"]
132
+ for value in (lesson_title, competency, module_unit, learner_level):
133
+ clean_value = str(value or "").strip()
134
+ if clean_value:
135
+ parts.append(clean_value)
136
+ return " | ".join(parts)
137
+
138
+
139
+ def retrieve_lesson_pdf_context(
140
+ topic: str,
141
+ subject: str,
142
+ quarter: int,
143
+ lesson_title: str | None = None,
144
+ competency: str | None = None,
145
+ module_id: str | None = None,
146
+ lesson_id: str | None = None,
147
+ competency_code: str | None = None,
148
+ storage_path: str | None = None,
149
+ top_k: int = 8,
150
+ ) -> Tuple[list[dict], str]:
151
+ """Retrieve chunks by storage_path exact match + semantic ranking; fallback to general query."""
152
+ if storage_path:
153
+ exact_chunks = retrieve_curriculum_context(
154
+ query=topic,
155
+ subject=subject,
156
+ quarter=quarter,
157
+ storage_path=storage_path,
158
+ top_k=top_k,
159
+ )
160
+ if exact_chunks and any(c["score"] >= 0.65 for c in exact_chunks):
161
+ return exact_chunks, "exact"
162
+
163
+ general_chunks = retrieve_curriculum_context(
164
+ query=topic,
165
+ subject=subject,
166
+ quarter=quarter,
167
+ top_k=top_k,
168
+ )
169
+
170
+ if storage_path and exact_chunks:
171
+ all_chunks = exact_chunks + general_chunks
172
+ seen = set()
173
+ deduped = []
174
+ for c in all_chunks:
175
+ key = f"{c.get('source_file')}:{c.get('page')}:{c.get('content', '')[:60]}"
176
+ if key not in seen:
177
+ seen.add(key)
178
+ deduped.append(c)
179
+ deduped.sort(key=lambda x: x.get("score", 0), reverse=True)
180
+ return deduped[:top_k], "hybrid"
181
+
182
+ return general_chunks, "general"
183
+
184
+
185
+ def format_retrieved_chunks(curriculum_chunks: list[dict]) -> str:
186
+ refs = []
187
+ for i, chunk in enumerate(curriculum_chunks, start=1):
188
+ refs.append(
189
+ f"{i}. [{chunk.get('source_file')} p.{chunk.get('page')}] "
190
+ f"({chunk.get('content_domain')}/{chunk.get('chunk_type')}) score={chunk.get('score')}\n"
191
+ f" Excerpt: {chunk.get('content', '')}"
192
+ )
193
+ return "\n".join(refs) if refs else "No curriculum context retrieved."
194
+
195
+
196
+ def summarize_retrieval_confidence(curriculum_chunks: list[dict]) -> Dict[str, any]:
197
+ if not curriculum_chunks:
198
+ return {"confidence": 0.0, "band": "low"}
199
+
200
+ top_scores = [float(c.get("score") or 0.0) for c in curriculum_chunks[:5]]
201
+ score = sum(top_scores) / max(1, len(top_scores))
202
+ band = "high" if score >= 0.72 else "medium" if score >= 0.5 else "low"
203
+ return {"confidence": round(score, 3), "band": band}
204
+
205
+
206
+ def organize_chunks_by_section(chunks: list[dict]) -> Dict[str, List[dict]]:
207
+ """Organize retrieved chunks into lesson section categories."""
208
+ sections: Dict[str, List[dict]] = {
209
+ "introduction": [],
210
+ "key_concepts": [],
211
+ "worked_examples": [],
212
+ "important_notes": [],
213
+ "practice": [],
214
+ "summary": [],
215
+ "assessment": [],
216
+ "general": [],
217
+ }
218
+ domain_priority = {
219
+ "introduction": 1, "key_concepts": 2, "worked_examples": 3,
220
+ "important_notes": 4, "practice": 5, "summary": 6,
221
+ "assessment": 7, "general": 8,
222
+ }
223
+ for chunk in chunks:
224
+ domain = chunk.get("content_domain", "general")
225
+ if domain in sections:
226
+ sections[domain].append(chunk)
227
+ else:
228
+ sections["general"].append(chunk)
229
+ return sections
230
+
231
+
232
+ def build_lesson_prompt(
233
+ *,
234
+ lesson_title: str,
235
+ competency: str,
236
+ grade_level: str,
237
+ subject: str,
238
+ quarter: int,
239
+ learner_level: Optional[str],
240
+ module_unit: Optional[str],
241
+ curriculum_chunks: list[dict],
242
+ competency_code: Optional[str] = None,
243
+ ) -> str:
244
+ refs_text = format_retrieved_chunks(curriculum_chunks)
245
+ organized = organize_chunks_by_section(curriculum_chunks)
246
+
247
+ return (
248
+ "You are a DepEd-aligned Grade 11-12 mathematics instructional designer.\n"
249
+ "Generate a lesson in JSON format. Use ONLY the retrieved curriculum evidence below.\n"
250
+ "Do NOT invent content. Do NOT add generic motivational text. All content must be grounded in the retrieved excerpts.\n\n"
251
+ f"Lesson title: {lesson_title}\n"
252
+ f"Competency code: {competency_code or 'n/a'}\n"
253
+ f"Curriculum competency: {competency}\n"
254
+ f"Grade level: {grade_level}\n"
255
+ f"Subject: {subject}\n"
256
+ f"Quarter: Q{quarter}\n"
257
+ f"Learner level: {learner_level or 'Grade 11-12'}\n"
258
+ f"Module/unit: {module_unit or 'n/a'}\n\n"
259
+ "[CURRICULUM CONTEXT]\n"
260
+ f"{refs_text}\n\n"
261
+ "Return ONLY valid JSON with this exact structure. All 7 sections are required:\n"
262
+ "{\n"
263
+ ' "sections": [\n'
264
+ ' {"type": "introduction", "title": "Introduction", "content": "..."},\n'
265
+ ' {"type": "key_concepts", "title": "Key Concepts", "content": "...", "callouts": [{"type":"important|ti..."}]\n},'
266
+ ' {"type": "video", "title": "Video Lesson", "content": "...", "videoId": "", "videoTitle": "", "videoChannel": "", "embedUrl": "", "thumbnailUrl": ""},\n'
267
+ ' {"type": "worked_examples", "title": "Worked Examples", "examples": [{"problem":"...","steps":["Step 1: ...","Step 2: ..."],"answer":"..."}]},\n'
268
+ ' {"type": "important_notes", "title": "Important Notes", "bulletPoints": ["...","..."]},\n'
269
+ ' {"type": "try_it_yourself", "title": "Try It Yourself", "practiceProblems": [{"question":"...","solution":"..."}]},\n'
270
+ ' {"type": "summary", "title": "Summary", "content": "..."}\n'
271
+ " ],\n"
272
+ ' "needsReview": false\n'
273
+ "}\n\n"
274
+ "Rules:\n"
275
+ "- content in introduction, key_concepts, important_notes, summary: use paragraph/bullet text grounded in retrieved chunks\n"
276
+ "- examples must reflect actual content from the retrieved curriculum (real formulas, real contexts)\n"
277
+ "- practiceProblems should be derivable from worked examples\n"
278
+ "- callouts: type is 'important', 'tip', or 'warning'\n"
279
+ "- video section: content is a brief sentence, leave videoId empty (will be filled by backend)\n"
280
+ "- Do not use placeholder text like 'placeholder' or 'example text'\n"
281
+ "- Do not fabricate worked examples - use actual curriculum content\n"
282
+ )
283
+
284
+
285
+ def build_problem_generation_prompt(topic: str, difficulty: str, curriculum_chunks: list[dict]) -> str:
286
+ refs = []
287
+ for i, chunk in enumerate(curriculum_chunks, start=1):
288
+ refs.append(
289
+ f"{i}. [{chunk.get('source_file')} p.{chunk.get('page')}] "
290
+ f"({chunk.get('content_domain')}/{chunk.get('chunk_type')}) {chunk.get('content', '')}"
291
+ )
292
+ refs_text = "\n".join(refs) if refs else "No curriculum context retrieved."
293
+
294
+ return (
295
+ "Generate one practice problem strictly aligned to the retrieved DepEd competency scope.\n"
296
+ "Do not include topics outside the competency context.\n\n"
297
+ f"Topic: {topic}\n"
298
+ f"Difficulty: {difficulty}\n\n"
299
+ "[CURRICULUM CONTEXT]\n"
300
+ f"{refs_text}\n\n"
301
+ "Return JSON with keys: problem, solution, competencyReference"
302
+ )
303
+
304
+
305
+ def build_analysis_curriculum_context(weak_topics: list[str], subject: str) -> list[dict]:
306
+ dedup: Dict[str, dict] = {}
307
+ for weak_topic in weak_topics:
308
+ rows = retrieve_curriculum_context(
309
+ query=f"DepEd learning competency for {weak_topic}",
310
+ subject=subject,
311
+ chunk_type="learning_competency",
312
+ top_k=2,
313
+ )
314
+ for row in rows:
315
+ key = f"{row.get('source_file')}::{row.get('page')}::{row.get('content', '')[:80]}"
316
+ if key not in dedup:
317
+ dedup[key] = row
318
+ return list(dedup.values())