### Clone Repository and Install Dependencies Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/frontend/README.md Follow these steps to clone the project repository, navigate into the directory, install necessary dependencies, and start the development server. ```sh git clone cd npm i npm run dev ``` -------------------------------- ### Backend Setup: Install Dependencies Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/README.md Installs all required Python packages listed in the requirements.txt file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Frontend Setup: Start Development Server Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/README.md Launches the Vite development server for the React frontend. ```bash npm run dev ``` -------------------------------- ### Frontend Setup: Install Dependencies Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/README.md Installs Node.js dependencies for the frontend application. ```bash npm install ``` -------------------------------- ### Backend Setup: Run Development Server Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/README.md Starts the FastAPI development server with hot-reloading enabled. ```bash uvicorn app.main:app --reload ``` -------------------------------- ### Backend Setup: Create Virtual Environment Source: https://github.com/thamizh0206/edugen-ai-learning-engine/blob/main/README.md Creates a Python virtual environment for managing project dependencies. Activate it before installing packages. ```bash python -m venv .venv source .venv/bin/activate # On Windows: .venv\Scripts\activate ``` -------------------------------- ### Login User and Get JWT (Bash) Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Authenticate a user with email and password. Returns a JWT access token and user ID upon successful login. ```bash curl -X POST http://localhost:8000/auth/login \ -H "Content-Type: application/json" \ -d '{"email": "student@example.com", "password": "securePass123"}' # Success: # { # "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", # "user_id": 42 # } # Bad credentials: # HTTP 400 # { "detail": "Invalid credentials" } ``` -------------------------------- ### Retrieve All User Topic Mastery Scores using API Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Call the GET /progress endpoint with a user_id to get a dictionary of topics and their mastery percentages. Mastery is calculated as correct_attempts / total_attempts * 100. ```bash curl "http://localhost:8000/progress?user_id=42" ``` ```json # { # "Newton's Laws": 75.0, # "Thermodynamics": 40.0, # "Electromagnetism": 100.0 # } ``` -------------------------------- ### GET /progress Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Retrieves mastery scores for all topics a user has attempted. The score for each topic is calculated as the percentage of correct attempts out of total attempts. ```APIDOC ## GET /progress ### Description Retrieve mastery scores for all user topics. Returns a dictionary mapping each topic the user has attempted to their mastery percentage (0–100), calculated as `correct_attempts / total_attempts * 100`. ### Method GET ### Endpoint /progress ### Parameters #### Query Parameters - **user_id** (integer) - Required - The ID of the user whose progress to retrieve. ### Request Example ```bash curl "http://localhost:8000/progress?user_id=42" ``` ### Response #### Success Response (200) - A dictionary where keys are topic names (string) and values are mastery percentages (float from 0.0 to 100.0). #### Response Example ```json { "Newton's Laws": 75.0, "Thermodynamics": 40.0, "Electromagnetism": 100.0 } ``` ``` -------------------------------- ### Document Cache Helpers Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Provides a lightweight SQLite cache keyed on the SHA-256 hash of document text, preventing redundant LLM calls for duplicate uploads. Check cache before starting expensive pipeline. ```python from app.database.db import get_doc_hash, get_cached_response, save_cache text = open("notes.txt").read() doc_hash = get_doc_hash(text) # deterministic SHA-256 hex string # Check cache before starting expensive pipeline cached = get_cached_response(doc_hash) if cached: print("Cache hit — returning stored result") print(cached["summary"]) else: # ... run pipeline ... result = {"summary": "...", "questions": [...]} save_cache(doc_hash, result) # persist for future uploads print("Saved to cache:", doc_hash) ``` -------------------------------- ### Generate Focused Retest for a Topic using API Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Use the GET /retest/{topic_name} endpoint to generate 5 MCQs for a specific weak topic. Requires the topic name to be URL-encoded. Returns a 404 if the topic is not found in the database. ```bash curl "http://localhost:8000/retest/Newton%27s%20Laws" ``` ```json # { # "topic": "Newton's Laws", # "questions": [ # { # "question": "A 10 kg object accelerates at 2 m/s². What is the net force?", # "options": ["A) 5 N", "B) 20 N", "C) 12 N", "D) 8 N"], # "answer": "B", # "explanation": "F = ma = 10 × 2 = 20 N (Newton's Second Law)" # } # // ... 4 more questions # ] # } # # # Topic not in DB: # # HTTP 404 # # { "detail": "Topic not found. Please upload a document first." } ``` -------------------------------- ### GET /retest/{topic_name} Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Generates a focused retest for a specified weak topic. It looks up the topic, retrieves its document, runs RAG to select relevant chunks, and creates 5 new multiple-choice questions targeting that topic. ```APIDOC ## GET /retest/{topic_name} ### Description Looks up the topic in the database, retrieves the associated document, runs RAG to select the most relevant chunks, and generates 5 fresh MCQs specifically targeting that topic. ### Method GET ### Endpoint /retest/{topic_name} ### Parameters #### Path Parameters - **topic_name** (string) - Required - The name of the topic to generate a retest for. ### Request Example ```bash curl "http://localhost:8000/retest/Newton%27s%20Laws" ``` ### Response #### Success Response (200) - **topic** (string) - The name of the topic. - **questions** (array) - An array of question objects. - **question** (string) - The text of the question. - **options** (array) - An array of possible answer options. - **answer** (string) - The correct answer. - **explanation** (string) - An explanation for the correct answer. #### Response Example ```json { "topic": "Newton's Laws", "questions": [ { "question": "A 10 kg object accelerates at 2 m/s². What is the net force?", "options": ["A) 5 N", "B) 20 N", "C) 12 N", "D) 8 N"], "answer": "B", "explanation": "F = ma = 10 × 2 = 20 N (Newton's Second Law)" } // ... 4 more questions ] } ``` #### Error Response (404) - **detail** (string) - Error message indicating the topic was not found. #### Error Response Example ```json { "detail": "Topic not found. Please upload a document first." } ``` ``` -------------------------------- ### POST /submit-answer — Submit a quiz answer and get feedback Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Evaluates the user's answer against the correct answer, persists the attempt, and generates a follow-up question on incorrect answers. ```APIDOC ## POST /submit-answer — Submit a quiz answer and get feedback ### Description Evaluates the user's answer against the correct answer (case-insensitive exact match), persists the attempt to the database, and — on an incorrect answer — uses the LLM to generate a follow-up question on the same concept. ### Method POST ### Endpoint `/submit-answer` ### Parameters #### Request Body - **user_id** (integer) - Required - The ID of the user. - **topic** (string) - Required - The topic of the question. - **question** (string) - Required - The quiz question text. - **correct_answer** (string) - Required - The correct answer to the question. - **user_answer** (string) - Required - The user's submitted answer. - **context** (string) - Required - The context provided for the question. ### Request Example ```bash curl -X POST http://localhost:8000/submit-answer \ -H "Content-Type: application/json" \ -d '{ "user_id": 42, "topic": "Newton\'s Laws", "question": "What does Newton\'s First Law state?", "correct_answer": "B", "user_answer": "A", "context": "Newton\'s First Law states that an object at rest stays at rest..." }' ``` ### Response #### Success Response (200) - **result** (string) - Indicates if the answer was 'correct' or 'wrong'. - **followup** (object) - Contains a follow-up question if the user's answer was wrong. - **question** (string) - The follow-up question. #### Response Example (Correct Answer) ```json { "result": "correct" } ``` #### Response Example (Wrong Answer) ```json { "result": "wrong", "followup": { "question": "Which law describes inertia?" } } ``` ``` -------------------------------- ### GET /status/{doc_hash} — Poll processing status Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Poll for the result of an async upload using the doc_hash token received from /upload. Returns 'processing' while the background task is running, or 'ready' with the full data once complete. ```APIDOC ## GET /status/{doc_hash} — Poll processing status ### Description Poll for the result of an async upload using the `doc_hash` token received from `/upload`. Returns `"processing"` while the background task is running, or `"ready"` with the full data once complete. ### Method GET ### Endpoint `/status/{doc_hash}` ### Parameters #### Path Parameters - **doc_hash** (string) - Required - The document hash token obtained from the `/upload` endpoint. ### Request Example ```bash DOC_HASH="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" curl http://localhost:8000/status/$DOC_HASH ``` ### Response #### Success Response (200) - **status** (string) - The current processing status ('processing', 'ready', or 'error'). - **data** (object) - Contains the processed document data (summary, questions, topics) if status is 'ready'. - **error** (string) - An error message if the status is 'error'. #### Response Example (Processing) ```json { "status": "processing" } ``` #### Response Example (Completed) ```json { "status": "ready", "data": { "summary": "...", "questions": [...], "extracted_topics": ["Topic A", "Topic B"] } } ``` #### Response Example (Error) ```json { "status": "error", "error": "Task failed or disappeared." } ``` ``` -------------------------------- ### Register New User (Bash) Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Register a new user account with email and password. Returns an error if the email is already in use. ```bash curl -X POST http://localhost:8000/auth/register \ -H "Content-Type: application/json" \ -d '{"email": "student@example.com", "password": "securePass123"}' # Success: # { "message": "User created" } # Duplicate email: # HTTP 400 # { "detail": "Email already registered" } ``` -------------------------------- ### POST /auth/register — Register a new user account Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Creates a new user with a bcrypt-hashed password. Returns an error if the email is already taken. ```APIDOC ## POST /auth/register — Register a new user account ### Description Creates a new user with a bcrypt-hashed password. Returns an error if the email is already taken. ### Method POST ### Endpoint `/auth/register` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```bash curl -X POST http://localhost:8000/auth/register \ -H "Content-Type: application/json" \ -d '{"email": "student@example.com", "password": "securePass123"}' ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful user creation. #### Error Response (400) - **detail** (string) - Error message indicating that the email is already registered. #### Response Example (Success) ```json { "message": "User created" } ``` #### Response Example (Duplicate Email) ```json { "detail": "Email already registered" } ``` ``` -------------------------------- ### Upload Study Document (Bash) Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Use this endpoint to upload PDF or text files for processing. It returns a doc_hash for polling status. If the document is cached, it returns ready data immediately. ```bash # Upload a PDF file curl -X POST http://localhost:8000/upload \ -F "file=@lecture_notes.pdf" \ -F "user_id=42" # Expected response when document is new (background processing started) # { # "status": "processing", # "doc_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" # } # Expected response when document was already processed (cache hit) # { # "status": "ready", # "data": { # "summary": "This chapter covers Newton's three laws of motion...", # "questions": [ # { # "question": "What does Newton's First Law state?", # "options": ["A) F=ma", "B) An object at rest stays at rest...", "C) ...", "D) ..."], # "answer": "B", # "explanation": "Newton's First Law is the law of inertia..." # } # ], # "extracted_topics": ["Newton's Laws", "Force", "Momentum"] # } # } ``` -------------------------------- ### Extract Topics from Text using LLM Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Sends the first 4000 characters of a document to the LLM and returns a list of 5–10 key topic strings. These are stored as `Topic` records and used to seed the mastery lookup during adaptive difficulty selection. ```python from app.services.topic_service import extract_topics text = open("biology_chapter3.txt").read() topics = extract_topics(text) print(topics) # ["Cell Division", "Mitosis", "Meiosis", "Chromosomes", "DNA Replication", # "Cytokinesis", "Spindle Fibers"] ``` -------------------------------- ### POST /upload — Upload a study document for async processing Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Accepts a .pdf or .txt file (max 5 MB) and an optional user_id form field. Returns a doc_hash for polling if the document is new, or cached results if already processed. ```APIDOC ## POST /upload — Upload a study document for async processing ### Description Accepts a `.pdf` or `.txt` file (max 5 MB) and an optional `user_id` form field. If the document has been processed before (identified by SHA-256 hash), the cached result is returned immediately; otherwise, processing begins in the background and a `doc_hash` polling token is returned. ### Method POST ### Endpoint `/upload` ### Parameters #### Form Data - **file** (file) - Required - The study document (PDF or TXT). - **user_id** (string) - Optional - The ID of the user. ### Request Example ```bash curl -X POST http://localhost:8000/upload \ -F "file=@lecture_notes.pdf" \ -F "user_id=42" ``` ### Response #### Success Response (200) - **status** (string) - Indicates processing status ('processing' or 'ready'). - **doc_hash** (string) - A token for polling status (returned when processing starts). - **data** (object) - Contains summary, questions, and extracted_topics (returned on cache hit). #### Response Example (Processing) ```json { "status": "processing", "doc_hash": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" } ``` #### Response Example (Cache Hit) ```json { "status": "ready", "data": { "summary": "This chapter covers Newton's three laws of motion...", "questions": [ { "question": "What does Newton's First Law state?", "options": ["A) F=ma", "B) An object at rest stays at rest...", "C) ...", "D) ..."], "answer": "B", "explanation": "Newton's First Law is the law of inertia..." } ], "extracted_topics": ["Newton's Laws", "Force", "Momentum"] } } ``` ``` -------------------------------- ### VectorStore for FAISS-backed Semantic Indexing Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt The `VectorStore` class utilizes FAISS for in-memory L2-distance nearest-neighbor search. It supports adding embeddings and performing both semantic and index-based searches for retrieval. ```python from app.services.vector_store import VectorStore from app.services.embedding_service import generate_embeddings, embed_query from app.services.chunk_service import chunk_text chunks = chunk_text(open("notes.txt").read()) embeddings = generate_embeddings(chunks) # shape (N, 384) store = VectorStore(dimension=embeddings.shape[1]) store.add(embeddings, chunks) # Semantic search — returns text chunks query_emb = embed_query("laws of thermodynamics") top_chunks = store.search(query_emb, top_k=3) print(top_chunks[0][:120]) # most relevant chunk # Index search — returns integer positions for hybrid retrieval indices = store.search_indices(query_emb, top_k=5) # e.g. [2, 7, 0, 4, 1] ``` -------------------------------- ### Generate Topic-Focused Quiz using Python Service Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Employ `generate_topic_focused_quiz` for targeted RAG searches to create MCQs on specific weak topics. It generates up to 5 questions based on the provided document text. ```python from app.services.summary_service import generate_topic_focused_quiz doc_text = open("thermodynamics_notes.txt").read() result = generate_topic_focused_quiz("Entropy", doc_text) print(result["topic"]) # "Entropy" for q in result["questions"]: # always ≤ 5 items print(f"Q: {q['question']}") print(f"Options: {q['options']}") print(f"Answer: {q['answer']} — {q['explanation']} ") ``` -------------------------------- ### Generate RAG Summary and Quiz using Python Service Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Use the `generate_rag_summary_and_quiz` function to process text content and generate a summary along with MCQs. The `mastery` parameter controls quiz difficulty (0 for easy, 85 for hard). ```python from app.services.summary_service import generate_rag_summary_and_quiz text = open("lecture_notes.txt").read() # mastery=0 → Easy difficulty; mastery=60 → Medium; mastery=85 → Hard result = generate_rag_summary_and_quiz(text, mastery=65.0) print(result["summary"]) # "This lecture covers the three fundamental laws of thermodynamics..." for q in result["questions"]: print(q["question"]) print(q["options"]) print("Answer:", q["answer"]) print("Why:", q["explanation"]) print() # result["extracted_topics"] is populated in process_document(), not here directly # { "summary": "...", "questions": [{...}, ...] } ``` -------------------------------- ### Calculate User Mastery Score using Python Service Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt The `calculate_mastery` function queries the database for `QuizAttempt` records to compute a user's mastery percentage for a given topic. This score informs adaptive difficulty. ```python from app.services.mastery_service import calculate_mastery from app.database.session import SessionLocal db = SessionLocal() score = calculate_mastery(db, user_id=42, topic="Entropy") db.close() print(score) # e.g. 66.67 (8 correct out of 12 attempts) # Difficulty mapping: ``` -------------------------------- ### POST /auth/login — Authenticate and receive a JWT token Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Validates credentials and returns a signed HS256 JWT (1-hour expiry) together with the numeric user_id needed by other endpoints. ```APIDOC ## POST /auth/login — Authenticate and receive a JWT token ### Description Validates credentials and returns a signed HS256 JWT (1-hour expiry) together with the numeric `user_id` needed by other endpoints. ### Method POST ### Endpoint `/auth/login` ### Parameters #### Request Body - **email** (string) - Required - The user's email address. - **password** (string) - Required - The user's password. ### Request Example ```bash curl -X POST http://localhost:8000/auth/login \ -H "Content-Type: application/json" \ -d '{"email": "student@example.com", "password": "securePass123"}' ``` ### Response #### Success Response (200) - **access_token** (string) - The JWT access token. - **user_id** (integer) - The unique identifier for the user. #### Error Response (400) - **detail** (string) - Error message indicating invalid credentials. #### Response Example (Success) ```json { "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...", "user_id": 42 } ``` #### Response Example (Bad Credentials) ```json { "detail": "Invalid credentials" } ``` ``` -------------------------------- ### generate_topic_focused_quiz Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Generates a targeted retest by running a topic-scoped RAG search over a document to create 5 MCQs for a specific weak area. ```python from app.services.summary_service import generate_topic_focused_quiz doc_text = open("thermodynamics_notes.txt").read() result = generate_topic_focused_quiz("Entropy", doc_text) print(result["topic"]) for q in result["questions"]: # always ≤ 5 items print(f"Q: {q['question']}") print(f"Options: {q['options']}") print(f"Answer: {q['answer']} — {q['explanation']}\n") ``` -------------------------------- ### Generate Follow-up Question with LLM Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Generates a new multiple-choice question (MCQ) testing the same concept when a user answers incorrectly. Uses json_repair for robust JSON extraction from LLM output. ```python from app.services.evaluation_service import generate_followup_question context = "Newton's Second Law states F = ma, where F is force in Newtons..." original_q = "Which formula represents Newton's Second Law?" followup = generate_followup_question(context, original_q) print(followup["question"]) # "If a 5 kg object has acceleration 3 m/s², what is the net force?" print(followup["options"]) # ["A) 8 N", "B) 15 N", "C) 2 N", "D) 1.67 N"] print(followup["answer"]) # "B" print(followup["explanation"]) # "F = ma = 5 × 3 = 15 N" ``` -------------------------------- ### Submit Quiz Answer (Bash) Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Submit a user's answer to a quiz question. Evaluates the answer, persists the attempt, and generates a follow-up question if the answer is incorrect. ```bash curl -X POST http://localhost:8000/submit-answer \ -H "Content-Type: application/json" \ -d '{ "user_id": 42, "topic": "Newton's Laws", "question": "What does Newton's First Law state?", "correct_answer": "B", "user_answer": "A", "context": "Newton's First Law states that an object at rest stays at rest..." }' # Correct answer: # { "result": "correct" } # Wrong answer — follow-up question generated: # { # "result": "wrong", # "followup": { # "question": "Which law describes inertia?", ``` -------------------------------- ### Chunk Text using Sliding-Window Chunker Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt The `chunk_text` function splits large documents into 800-character segments with a 100-character overlap. This is the initial step before text embedding. ```python from app.services.chunk_service import chunk_text text = "Newton's First Law of Motion states that..." * 50 # long document chunks = chunk_text(text) print(f"Total chunks: {len(chunks)}") # e.g. 12 print(f"Chunk size: {len(chunks[0])}") # ~800 chars print(f"Overlap: chunk[0][-100:] == chunk[1][:100] → {chunks[0][-100:] == chunks[1][:100]}") # True — 100-char overlap preserved ``` -------------------------------- ### Poll Document Processing Status (Bash) Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Poll for the status of an asynchronous document upload using the doc_hash. Returns 'processing' or 'ready' with data upon completion. ```bash DOC_HASH="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" curl http://localhost:8000/status/$DOC_HASH # Still processing: # { "status": "processing" } # Completed: # { # "status": "ready", # "data": { # "summary": "...", # "questions": [...], # "extracted_topics": ["Topic A", "Topic B"] # } # } # Failed / disappeared: # { "status": "error", "error": "Task failed or disappeared." } ``` -------------------------------- ### Evaluate Answer for Exact Match Source: https://context7.com/thamizh0206/edugen-ai-learning-engine/llms.txt Performs a case-insensitive, whitespace-trimmed exact match for answer evaluation. Returns a boolean indicating if the user's answer matches the correct answer. ```python from app.services.evaluation_service import evaluate_answer print(evaluate_answer("What is F=ma?", "B", "b")) # True (case-insensitive) print(evaluate_answer("What is F=ma?", "B", "A")) # False print(evaluate_answer("What is F=ma?", "B", " B ")) # True (whitespace trimmed) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.