Feat: Implement AI DPP CBT conversion and frontend sync

This commit is contained in:
2026-07-07 16:12:56 +05:30
parent b6ebb9d9c3
commit 988923ef4b
11 changed files with 168 additions and 18 deletions

View File

@@ -76,10 +76,15 @@ def verify_otp(phone_or_email: str, code: str, session: Session = Depends(get_se
# --- CBT TEST ENVIRONMENT CONTENT DELIVERY ENDPOINTS ---
@app.get("/api/tests", response_model=List[models.Test], tags=["CBT Engine"])
def list_active_tests(exam_pattern: Optional[str] = None, session: Session = Depends(get_session)):
def list_active_tests(exam_pattern: Optional[str] = None, type: Optional[str] = None, session: Session = Depends(get_session)):
query = select(models.Test).where(models.Test.is_active == True)
if exam_pattern:
query = query.where(models.Test.exam_pattern == exam_pattern)
if type:
query = query.where(models.Test.type == type)
else:
# If type isn't specified, don't return DPS in regular tests query
query = query.where(models.Test.type != "DPS")
return session.exec(query).all()

112
backend/seed_dpps.py Normal file
View File

@@ -0,0 +1,112 @@
import asyncio
import os
import uuid
from sqlmodel import Session, select
from datetime import datetime
from database import engine, init_db
import models
import storage
from pdf_parser import parse_pdf_to_questions
async def seed_pdfs():
# Admin ID fallback
admin_id_str = "b0e17378-864d-439e-8806-708dc48a891b" # Or fetch first user
with Session(engine) as session:
admin = session.exec(select(models.User).limit(1)).first()
if admin:
admin_id = admin.id
else:
admin_id = uuid.UUID(admin_id_str)
# Paths to the 4 PDFs
base_dir = r"/app/pdfs"
pdf_files = [
"media_e3dd3511-9fc4-402b-8054-6a56f7ed8202_1782971559253.pdf",
"media_e3dd3511-9fc4-402b-8054-6a56f7ed8202_1782979477911.pdf",
"media_e3dd3511-9fc4-402b-8054-6a56f7ed8202_1783273583537.pdf",
"media_e3dd3511-9fc4-402b-8054-6a56f7ed8202_1783410386530.pdf"
]
subjects = ["Physics", "Chemistry", "Biology", "Mathematics"]
topics = ["Rotational Dynamics", "Chemical Kinetics", "Genetics", "Calculus"]
for idx, filename in enumerate(pdf_files):
file_path = os.path.join(base_dir, filename)
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
continue
print(f"Processing {filename}...")
with open(file_path, "rb") as f:
pdf_bytes = f.read()
# 1. Upload to Minio
object_name = f"dpps/{uuid.uuid4()}_{filename}"
storage.upload_file(pdf_bytes, object_name, content_type="application/pdf")
# 2. Extract
questions_data = await parse_pdf_to_questions(pdf_bytes, "JEE_Main")
if not questions_data:
print(f"Warning: No questions extracted for {filename}. Using mock data fallback.")
questions_data = [
{
"subject": subjects[idx],
"topic": topics[idx],
"subtopic": "General",
"difficulty": "Hard",
"type": "MCQ_Single",
"question_text": f"What is the most fundamental principle of {topics[idx]}?",
"options": {"A": "Conservation of Energy", "B": "Newton's Second Law", "C": "Kinetic Theory", "D": "Thermodynamics"},
"correct_answer": {"value": "A"},
"solution_text": "By fundamental principles."
}
]
question_ids = []
for q_data in questions_data:
new_q = models.Question(
subject=q_data.get("subject", subjects[idx]),
topic=q_data.get("topic", topics[idx]),
subtopic=q_data.get("subtopic", "General"),
difficulty=q_data.get("difficulty", "Medium"),
type=models.QuestionTypeEnum.MCQ_SINGLE,
question_text=q_data.get("question_text", ""),
options=q_data.get("options", {}),
correct_answer=q_data.get("correct_answer", {}),
solution_text=q_data.get("solution_text", ""),
language=models.MediumEnum.ENGLISH,
exam=models.ExamEnum.JEE_MAIN,
created_by=admin_id
)
session.add(new_q)
session.flush()
question_ids.append(str(new_q.id))
# Create Test record
test_obj = models.Test(
title=f"AI DPP: {topics[idx]}",
type="DPS",
exam_pattern=models.ExamEnum.JEE_MAIN,
sections={
"Section 1": {
"questions": question_ids,
"time_limit": 60
}
},
total_time=60,
difficulty="Hard" if idx % 2 == 0 else "Medium",
scheduled_date=datetime.utcnow(),
is_active=True,
created_by=admin_id
)
session.add(test_obj)
session.commit()
print(f"Successfully created DPS Test: {test_obj.title} with {len(question_ids)} questions.")
if __name__ == "__main__":
asyncio.run(seed_pdfs())

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -2,13 +2,29 @@ import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { BrainCircuit, Play, CheckCircle2, Download, Filter, Lock } from "lucide-react"
import { useEffect, useState } from "react"
import Link from "next/link"
export default function DPPPage() {
const dpps = [
{ title: "Top Overturning", subject: "Physics", topic: "Rotational Dynamics", difficulty: "Hard", count: 15, status: "Pending", priority: "High" },
{ title: "First Order Reactions", subject: "Chemistry", topic: "Chemical Kinetics", difficulty: "Medium", count: 20, status: "Pending", priority: "Medium" },
{ title: "Mendelian Inheritance", subject: "Biology", topic: "Genetics", difficulty: "Easy", count: 25, status: "Completed", score: "23/25" },
{ title: "Definite Integration", subject: "Mathematics", topic: "Calculus", difficulty: "Mixed", count: 15, status: "Completed", score: "14/15" },
]
const [dpps, setDpps] = useState<any[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
async function fetchDpps() {
try {
const res = await fetch("http://localhost:8000/api/tests?type=DPS")
if (res.ok) {
const data = await res.json()
setDpps(data)
}
} catch (err) {
console.error("Failed to fetch DPPs", err)
} finally {
setLoading(false)
}
}
fetchDpps()
}, [])
const getDifficultyColor = (diff: string) => {
switch(diff) {
@@ -51,18 +67,31 @@ export default function DPPPage() {
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{dpps.map((dpp, i) => (
<Card key={i} className={`group cursor-pointer transition-all hover:shadow-md ${dpp.status === 'Completed' ? 'opacity-70 hover:opacity-100 bg-secondary/10' : 'hover:border-[#00F0FF]/50 bg-background'}`}>
{loading ? (
<div className="col-span-2 text-center py-12 text-muted-foreground">Loading AI-generated DPPs...</div>
) : dpps.length === 0 ? (
<div className="col-span-2 text-center py-12 text-muted-foreground border border-dashed rounded-xl">No DPPs available yet. Upload some PDFs in the Admin Panel!</div>
) : dpps.map((dpp, i) => {
// Calculate total questions dynamically from sections
let count = 0;
if (dpp.sections) {
Object.values(dpp.sections).forEach((s: any) => { count += (s.questions?.length || 0) });
}
// Temporary mock for status
const status = "Pending"
return (
<Card key={dpp.id} className={`group cursor-pointer transition-all hover:shadow-md ${status === 'Completed' ? 'opacity-70 hover:opacity-100 bg-secondary/10' : 'hover:border-[#00F0FF]/50 bg-background'}`}>
<CardContent className="p-6 flex items-center justify-between">
<div className="flex gap-4">
<div className={`mt-1 flex-shrink-0 ${dpp.status === 'Completed' ? 'text-green-500' : 'text-foreground'}`}>
{dpp.status === 'Completed' ? <CheckCircle2 size={24} /> : <div className="size-6 rounded-full border-2 border-muted-foreground group-hover:border-[#00F0FF] transition-colors flex items-center justify-center"></div>}
<div className={`mt-1 flex-shrink-0 ${status === 'Completed' ? 'text-green-500' : 'text-foreground'}`}>
{status === 'Completed' ? <CheckCircle2 size={24} /> : <div className="size-6 rounded-full border-2 border-muted-foreground group-hover:border-[#00F0FF] transition-colors flex items-center justify-center"></div>}
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-bold uppercase tracking-wider text-[#00F0FF]">{dpp.subject}</span>
<span className="text-xs font-bold uppercase tracking-wider text-[#00F0FF]">{dpp.exam_pattern?.replace("_", " ") || "JEE/NEET"}</span>
<span className="text-muted-foreground text-xs font-bold">•</span>
<span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">{dpp.topic}</span>
<span className="text-xs font-bold uppercase tracking-wider text-muted-foreground">{dpp.difficulty} Level</span>
</div>
<h3 className="font-bold text-lg leading-tight group-hover:text-[#00F0FF] transition-colors flex items-center gap-2">
{dpp.title}
@@ -71,20 +100,24 @@ export default function DPPPage() {
</span>
</h3>
<div className="text-sm text-muted-foreground mt-2 font-medium">
{dpp.count} Questions • {dpp.status === 'Completed' ? `Score: ${dpp.score}` : `${dpp.priority} Priority`}
{count} Questions • {dpp.total_time} mins
</div>
</div>
</div>
<div className="text-muted-foreground group-hover:text-foreground transition-colors pl-4 shrink-0">
{dpp.status === 'Completed' ? (
<Button variant="ghost" size="sm" className="font-bold">Review</Button>
{status === 'Completed' ? (
<Link href={`/dashboard/cbt/history/${dpp.id}`}>
<Button variant="ghost" size="sm" className="font-bold">Review</Button>
</Link>
) : (
<Button variant="secondary" size="icon" className="rounded-full group-hover:bg-[#00F0FF] group-hover:text-background transition-colors"><Play size={16} className="ml-1" /></Button>
<Link href={`/cbt/${dpp.id}`}>
<Button variant="secondary" size="icon" className="rounded-full group-hover:bg-[#00F0FF] group-hover:text-background transition-colors"><Play size={16} className="ml-1" /></Button>
</Link>
)}
</div>
</CardContent>
</Card>
))}
)})}
</div>
</div>
)