diff --git a/ai-service/adaptive_ai.py b/ai-service/adaptive_ai.py new file mode 100644 index 0000000..31602a0 --- /dev/null +++ b/ai-service/adaptive_ai.py @@ -0,0 +1,191 @@ +""" +Adaptive AI & ML helpers: +1. Subtopic Auto-Tagging (AI_SUGGESTED) +2. Transcript-Grounded Misconception Explanations (RAG) +3. Weak-Subtopic Practice Question Generation +4. Tag Co-occurrence / PMI Calculation (Phase 4 graph prior) +""" + +import json +import math +import re +from collections import Counter +from typing import List, Dict, Optional + +from gemini_rotator import GeminiKeyRotator +from transcript_loader import fetch_youtube_transcript, group_transcript_chunks +from embeddings_rag import semantic_search_chunks + + +def _extract_json_block(text: str): + cleaned = re.sub(r"^```(?:json)?\s*|\s*```$", "", (text or "").strip(), flags=re.MULTILINE) + return json.loads(cleaned) + + +def auto_tag_question( + question_text: str, + available_subtopics: List[str], + rotator: Optional[GeminiKeyRotator] = None, +) -> List[Dict]: + if not question_text or not available_subtopics: + return [] + + active_rotator = rotator or GeminiKeyRotator() + if active_rotator.is_configured(): + prompt = f"""Assign 1 to 3 relevant subtopics with weights (0.1 to 1.0) for this quiz question. +Return ONLY a valid JSON array like: [{{"name": "", "weight": 0.70, "source": "AI_SUGGESTED"}}] + +Available Subtopics: {json.dumps(available_subtopics)} +Question: "{question_text}" +""" + try: + raw = active_rotator.generate_content(prompt) + parsed = _extract_json_block(raw) + if isinstance(parsed, list) and parsed: + return [ + { + "name": str(item.get("name", available_subtopics[0])), + "weight": min(1.0, max(0.05, float(item.get("weight", 0.5)))), + "source": "AI_SUGGESTED", + } + for item in parsed[:3] + ] + except Exception: + pass + + # Deterministic fallback: keyword overlap scoring + q_words = set(re.findall(r"[a-z0-9]+", question_text.lower())) + matches = [] + for sub in available_subtopics: + s_words = set(re.findall(r"[a-z0-9]+", sub.lower())) + score = len(q_words.intersection(s_words)) + if score > 0: + matches.append((score, sub)) + matches.sort(reverse=True) + if not matches: + return [{"name": available_subtopics[0], "weight": 1.0, "source": "AI_SUGGESTED"}] + + total = sum(m[0] for m in matches[:3]) + return [ + {"name": sub, "weight": round(score / total, 3), "source": "AI_SUGGESTED"} + for score, sub in matches[:3] + ] + + +def explain_adaptive_mistake( + question_text: str, + submitted_answer: str, + correct_answer: str, + video_id: Optional[str] = None, + lecture_title: str = "Course Lecture", + transcript_text: Optional[str] = None, + rotator: Optional[GeminiKeyRotator] = None, +) -> Dict: + chunks = [] + if video_id: + lines = fetch_youtube_transcript(video_id, lecture_title) + chunks = group_transcript_chunks(lines, window_size=8) + elif transcript_text: + chunks = [{"lecture_title": lecture_title, "timestamp": "00:00", "start_seconds": 0, "text": transcript_text}] + + matched = semantic_search_chunks(f"{question_text} {correct_answer}", chunks, top_k=3) if chunks else [] + citations = [ + {"lectureTitle": c.get("lecture_title", lecture_title), "timestamp": c.get("timestamp", "00:00"), "excerpt": c.get("text", "")[:180]} + for c in matched + ] + context_str = "\n".join(f"[{c.get('lecture_title')} @ {c.get('timestamp')}]: {c.get('text')}" for c in matched) + + active_rotator = rotator or GeminiKeyRotator() + if active_rotator.is_configured(): + prompt = f"""Explain concisely why the student's answer is wrong and what misconception likely caused it. +Ground your explanation in the lecture transcript context if provided and cite timestamps [mm:ss]. + +Question: {question_text} +Student Submitted: {submitted_answer} +Correct Answer: {correct_answer} +Lecture Context: +{context_str or "No transcript provided."} +""" + try: + explanation = active_rotator.generate_content(prompt) + return {"explanation": explanation, "citations": citations, "mode": "GEMINI_RAG"} + except Exception: + pass + + ts = citations[0]["timestamp"] if citations else "00:00" + return { + "explanation": ( + f"Your answer '{submitted_answer}' does not satisfy the concept tested here. " + f"The expected answer is '{correct_answer}'. Review {lecture_title} @ [{ts}] to clarify this concept." + ), + "citations": citations, + "mode": "DETERMINISTIC_FALLBACK", + } + + +def generate_adaptive_question( + target_subtopics: List[str], + course_title: str = "Course", + difficulty: str = "MEDIUM", + rotator: Optional[GeminiKeyRotator] = None, +) -> Dict: + topics = target_subtopics or ["Core Fundamentals"] + active_rotator = rotator or GeminiKeyRotator() + if active_rotator.is_configured(): + prompt = f"""Generate 1 {difficulty} difficulty multiple-choice practice question for "{course_title}" covering {json.dumps(topics)}. +Return ONLY valid JSON: +{{"questionText": "...", "options": ["A", "B", "C", "D"], "correctAnswer": "A", "explanation": "...", "difficulty": "{difficulty}", "subtopics": {json.dumps(topics)}, "origin": "AI_GENERATED"}} +""" + try: + raw = active_rotator.generate_content(prompt) + parsed = _extract_json_block(raw) + if isinstance(parsed, dict) and parsed.get("questionText"): + parsed["origin"] = "AI_GENERATED" + return parsed + except Exception: + pass + + topic_label = ", ".join(topics) + return { + "questionText": f"[{difficulty}] Which statement best describes the key principle of {topic_label} in {course_title}?", + "options": [ + f"Applies core invariant of {topic_label}", + "Ignores boundary constraints completely", + "Assumes unbounded memory allocation", + "Skips validation checks", + ], + "correctAnswer": f"Applies core invariant of {topic_label}", + "explanation": f"Correct understanding of {topic_label} requires enforcing core invariants and boundary conditions.", + "difficulty": difficulty, + "subtopics": topics, + "origin": "AI_GENERATED", + } + + +def compute_tag_cooccurrence(tag_sets: List[List[int]]) -> List[Dict]: + """Computes normalized PMI co-occurrence scores for subtopic pairs (subtopic_a_id < subtopic_b_id).""" + total_docs = len(tag_sets) + if total_docs == 0: + return [] + + single_counts = Counter() + pair_counts = Counter() + for tags in tag_sets: + unique_tags = sorted(set(tags)) + for t in unique_tags: + single_counts[t] += 1 + for i in range(len(unique_tags)): + for j in range(i + 1, len(unique_tags)): + pair_counts[(unique_tags[i], unique_tags[j])] += 1 + + results = [] + for (a, b), joint in pair_counts.items(): + p_ab = joint / total_docs + p_a = single_counts[a] / total_docs + p_b = single_counts[b] / total_docs + pmi = math.log(p_ab / (p_a * p_b)) if (p_ab > 0 and p_a > 0 and p_b > 0) else 0.0 + npmi = pmi / (-math.log(p_ab)) if p_ab < 1.0 else 1.0 + results.append({"subtopic_a_id": a, "subtopic_b_id": b, "score": round(max(0.0, min(1.0, npmi)), 4)}) + + results.sort(key=lambda r: r["score"], reverse=True) + return results \ No newline at end of file diff --git a/ai-service/app.py b/ai-service/app.py index 7e31f15..1719030 100644 --- a/ai-service/app.py +++ b/ai-service/app.py @@ -11,6 +11,14 @@ from context_pyramid import ContextPyramid from synthesizer import LectureSynthesizer from rag_service import extract_text_from_pdf, answer_with_rag +from embeddings_rag import semantic_search_chunks +from transcript_loader import fetch_youtube_transcript, group_transcript_chunks +from adaptive_ai import ( + auto_tag_question, + explain_adaptive_mistake, + generate_adaptive_question, + compute_tag_cooccurrence, +) app = Flask(__name__) synthesizer = LectureSynthesizer() @@ -89,6 +97,70 @@ def ask_with_pdf(): ) return jsonify(result), 200 + +@app.route("/search/semantic", methods=["POST"]) +def semantic_lecture_search(): + data = request.get_json(force=True, silent=True) or {} + query = (data.get("query") or "").strip() + if not query: + return jsonify({"error": "Missing required field: query"}), 400 + + chunks = data.get("chunks") or [] + video_id = data.get("videoId") + lecture_title = data.get("lectureTitle") or "Course Lecture" + if not chunks and video_id: + chunks = group_transcript_chunks(fetch_youtube_transcript(video_id, lecture_title), window_size=8) + + top_k = int(data.get("topK") or 5) + results = semantic_search_chunks(query, chunks, top_k=top_k) + return jsonify({"query": query, "results": results}), 200 + + +@app.route("/adaptive/auto-tag", methods=["POST"]) +def adaptive_auto_tag(): + data = request.get_json(force=True, silent=True) or {} + question_text = (data.get("questionText") or "").strip() + available = data.get("availableSubtopics") or [] + if not question_text: + return jsonify({"error": "Missing required field: questionText"}), 400 + suggestions = auto_tag_question(question_text, available) + return jsonify({"suggestions": suggestions}), 200 + + +@app.route("/adaptive/explain-mistake", methods=["POST"]) +def adaptive_explain_mistake(): + data = request.get_json(force=True, silent=True) or {} + question_text = (data.get("questionText") or "").strip() + if not question_text: + return jsonify({"error": "Missing required field: questionText"}), 400 + res = explain_adaptive_mistake( + question_text=question_text, + submitted_answer=data.get("submittedAnswer") or "", + correct_answer=data.get("correctAnswer") or "", + video_id=data.get("videoId"), + lecture_title=data.get("lectureTitle") or "Course Lecture", + transcript_text=data.get("transcriptText"), + ) + return jsonify(res), 200 + + +@app.route("/adaptive/generate-question", methods=["POST"]) +def adaptive_generate_question(): + data = request.get_json(force=True, silent=True) or {} + target_subtopics = data.get("targetSubtopics") or [] + course_title = data.get("courseTitle") or "Course" + difficulty = data.get("difficulty") or "MEDIUM" + generated = generate_adaptive_question(target_subtopics, course_title, difficulty) + return jsonify(generated), 200 + + +@app.route("/adaptive/cooccurrence", methods=["POST"]) +def adaptive_cooccurrence(): + data = request.get_json(force=True, silent=True) or {} + tag_sets = data.get("tagSets") or [] + pairs = compute_tag_cooccurrence(tag_sets) + return jsonify({"pairs": pairs}), 200 + if __name__ == "__main__": port = int(os.environ.get("PORT", 8000)) app.run(host="0.0.0.0", port=port) diff --git a/ai-service/embeddings_rag.py b/ai-service/embeddings_rag.py new file mode 100644 index 0000000..ee32495 --- /dev/null +++ b/ai-service/embeddings_rag.py @@ -0,0 +1,85 @@ +""" +Vector Embeddings & Cosine Similarity retrieval using Gemini embedding models +(gemini-embedding-2 / gemini-embedding-001) with automatic multi-key rotation. +""" + +import math +import re +from typing import List, Dict, Optional +from google import genai + +from gemini_rotator import GeminiKeyRotator + + +EMBEDDING_MODELS = ["gemini-embedding-2", "gemini-embedding-001"] + + +def cosine_similarity(vec_a: List[float], vec_b: List[float]) -> float: + if not vec_a or not vec_b or len(vec_a) != len(vec_b): + return 0.0 + dot = sum(a * b for a, b in zip(vec_a, vec_b)) + norm_a = math.sqrt(sum(a * a for a in vec_a)) + norm_b = math.sqrt(sum(b * b for b in vec_b)) + if norm_a == 0.0 or norm_b == 0.0: + return 0.0 + return dot / (norm_a * norm_b) + + +def _keyword_score(query: str, text: str) -> float: + q_tokens = set(re.findall(r"[a-z0-9]+", (query or "").lower())) + t_tokens = set(re.findall(r"[a-z0-9]+", (text or "").lower())) + if not q_tokens or not t_tokens: + return 0.0 + return len(q_tokens.intersection(t_tokens)) / math.sqrt(len(q_tokens) * len(t_tokens)) + + +def embed_texts(texts: List[str], rotator: Optional[GeminiKeyRotator] = None) -> Optional[List[List[float]]]: + active_rotator = rotator or GeminiKeyRotator() + if not active_rotator.is_configured() or not texts: + return None + + for model_name in EMBEDDING_MODELS: + for _ in range(len(active_rotator.api_keys)): + key = next(active_rotator.key_cycle) + try: + client = genai.Client(api_key=key, http_options=active_rotator.http_options) + result = client.models.embed_content(model=model_name, contents=texts) + if result and getattr(result, "embeddings", None): + return [list(e.values) for e in result.embeddings] + except Exception: + continue + return None + + +def semantic_search_chunks( + query: str, + chunks: List[Dict], + top_k: int = 5, + rotator: Optional[GeminiKeyRotator] = None, +) -> List[Dict]: + """Ranks transcript chunks by Gemini embedding cosine similarity, falling back to TF keyword overlap.""" + if not chunks: + return [] + + texts = [c.get("text", "") for c in chunks] + vectors = embed_texts([query] + texts, rotator=rotator) + + scored = [] + if vectors and len(vectors) == len(texts) + 1: + query_vec = vectors[0] + for idx, (chunk, doc_vec) in enumerate(zip(chunks, vectors[1:])): + sim = cosine_similarity(query_vec, doc_vec) + enriched = dict(chunk) + enriched["similarity_score"] = round(sim, 4) + enriched["retrieval_mode"] = "VECTOR_EMBEDDING" + scored.append((sim, -idx, enriched)) + else: + for idx, chunk in enumerate(chunks): + sim = _keyword_score(query, chunk.get("text", "")) + enriched = dict(chunk) + enriched["similarity_score"] = round(sim, 4) + enriched["retrieval_mode"] = "KEYWORD_FALLBACK" + scored.append((sim, -idx, enriched)) + + scored.sort(reverse=True) + return [item[2] for item in scored[:top_k]] \ No newline at end of file diff --git a/ai-service/rag_service.py b/ai-service/rag_service.py index bdc91da..e055418 100644 --- a/ai-service/rag_service.py +++ b/ai-service/rag_service.py @@ -5,6 +5,7 @@ import io import re +from embeddings_rag import semantic_search_chunks from typing import List, Dict, Optional from pypdf import PdfReader @@ -34,18 +35,10 @@ def _tokenize(text: str) -> set: def search_relevant_chunks(question: str, pdf_text: str, chunks: List[Dict], top_k: int = 5) -> List[Dict]: if not chunks: return [] - query_tokens = _tokenize(question) | _tokenize(pdf_text[:1000]) - if not query_tokens: + combined_query = f"{question} {pdf_text[:800]}".strip() + if not combined_query: return chunks[:top_k] - - scored = [] - for idx, chunk in enumerate(chunks): - chunk_tokens = _tokenize(chunk.get("text", "")) - overlap = len(query_tokens.intersection(chunk_tokens)) - scored.append((overlap, -idx, chunk)) - - scored.sort(reverse=True) - return [item[2] for item in scored[:top_k]] + return semantic_search_chunks(combined_query, chunks, top_k=top_k) def parse_raw_transcript_lines(raw_text: str, lecture_title: str = "Course Lecture") -> List[Dict]: diff --git a/ai-service/test_adaptive_ai.py b/ai-service/test_adaptive_ai.py new file mode 100644 index 0000000..2d8a85e --- /dev/null +++ b/ai-service/test_adaptive_ai.py @@ -0,0 +1,66 @@ +import unittest +from unittest.mock import patch + +from app import app +from embeddings_rag import cosine_similarity, semantic_search_chunks +from adaptive_ai import compute_tag_cooccurrence + + +class TestAdaptiveAiAndEmbeddings(unittest.TestCase): + + def setUp(self): + self.client = app.test_client() + + def test_cosine_similarity(self): + self.assertAlmostEqual(cosine_similarity([1.0, 0.0], [1.0, 0.0]), 1.0) + self.assertAlmostEqual(cosine_similarity([1.0, 0.0], [0.0, 1.0]), 0.0) + + def test_semantic_search_fallback_orders_relevant_chunk_first(self): + chunks = [ + {"lecture_title": "L1", "timestamp": "01:00", "text": "HTML tables and semantic markup."}, + {"lecture_title": "L2", "timestamp": "03:45", "text": "Dynamic memory allocation with malloc returns NULL on failure."}, + ] + with patch.dict("os.environ", {"AI_MOCK_ONLY": "1"}): + results = semantic_search_chunks("malloc returns NULL memory", chunks, top_k=1) + self.assertEqual(len(results), 1) + self.assertEqual(results[0]["timestamp"], "03:45") + self.assertEqual(results[0]["retrieval_mode"], "KEYWORD_FALLBACK") + + def test_compute_tag_cooccurrence_orders_ids_and_scores(self): + tag_sets = [[1, 2], [1, 2, 3], [2, 3], [4]] + pairs = compute_tag_cooccurrence(tag_sets) + self.assertTrue(len(pairs) >= 2) + for p in pairs: + self.assertLess(p["subtopic_a_id"], p["subtopic_b_id"]) + self.assertGreaterEqual(p["score"], 0.0) + + def test_adaptive_endpoints(self): + with patch.dict("os.environ", {"AI_MOCK_ONLY": "1"}): + res_tag = self.client.post("/adaptive/auto-tag", json={ + "questionText": "Write a recursive tree traversal.", + "availableSubtopics": ["Recursion", "Tree Traversal", "Sorting"], + }) + self.assertEqual(res_tag.status_code, 200) + self.assertEqual(res_tag.get_json()["suggestions"][0]["source"], "AI_SUGGESTED") + + res_exp = self.client.post("/adaptive/explain-mistake", json={ + "questionText": "What does malloc return on failure?", + "submittedAnswer": "0", + "correctAnswer": "NULL", + "transcriptText": "malloc returns NULL when memory fails.", + "lectureTitle": "Pointers", + }) + self.assertEqual(res_exp.status_code, 200) + self.assertIn("NULL", res_exp.get_json()["explanation"]) + + res_gen = self.client.post("/adaptive/generate-question", json={ + "targetSubtopics": ["Recursion"], + "courseTitle": "Algorithms", + "difficulty": "HARD", + }) + self.assertEqual(res_gen.status_code, 200) + self.assertEqual(res_gen.get_json()["origin"], "AI_GENERATED") + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file