Exam Analyzer Pro - AI-Powered Question Paper Analysis
// server.js - Node.js Backend for Exam Analyzer
// This server handles OCR processing and AI-powered question analysis
const express = require('express');
const multer = require('multer');
const Anthropic = require('@anthropic-ai/sdk');
const Tesseract = require('tesseract.js');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3001;
// Configure multer for file uploads
const storage = multer.diskStorage({
destination: async (req, file, cb) => {
const uploadDir = './uploads';
try {
await fs.mkdir(uploadDir, { recursive: true });
cb(null, uploadDir);
} catch (err) {
cb(err);
}
},
filename: (req, file, cb) => {
const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1E9)}${path.extname(file.originalname)}`;
cb(null, uniqueName);
}
});
const upload = multer({
storage: storage,
limits: {
fileSize: 10 * 1024 * 1024 // 10MB limit
},
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png', 'image/jpg', 'application/pdf'];
if (allowedTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type. Only JPG, PNG, and PDF are allowed.'));
}
}
});
// Middleware
app.use(cors({
origin: process.env.FRONTEND_URL || '*',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type']
}));
app.use(express.json());
// Initialize Anthropic client
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY
});
// Auto-delete files after processing
const cleanupFile = async (filePath) => {
try {
// Delete after 5 minutes
setTimeout(async () => {
try {
await fs.unlink(filePath);
console.log(`Cleaned up file: ${filePath}`);
} catch (err) {
console.error(`Error cleaning up file: ${err.message}`);
}
}, 5 * 60 * 1000);
} catch (err) {
console.error(`Cleanup error: ${err.message}`);
}
};
// Health check endpoint
app.get('/api/health', (req, res) => {
res.json({
status: 'OK',
message: 'Exam Analyzer API is running',
timestamp: new Date().toISOString()
});
});
// OCR Endpoint - Extract text from image/PDF
app.post('/api/ocr', upload.single('file'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({
error: 'No file uploaded',
success: false
});
}
console.log(`Processing file: ${req.file.originalname}`);
// Perform OCR using Tesseract.js
const { data: { text } } = await Tesseract.recognize(
req.file.path,
'eng',
{
logger: (m) => {
if (m.status === 'recognizing text') {
console.log(`OCR Progress: ${Math.round(m.progress * 100)}%`);
}
}
}
);
// Clean extracted text
const cleanedText = text
.replace(/\r\n/g, '\n')
.replace(/\n{3,}/g, '\n\n')
.trim();
// Schedule file cleanup
cleanupFile(req.file.path);
res.json({
text: cleanedText,
filename: req.file.originalname,
success: true
});
} catch (error) {
console.error('OCR Error:', error);
// Clean up file on error
if (req.file) {
cleanupFile(req.file.path);
}
res.status(500).json({
error: 'Error processing image. Please try again with a clearer image.',
details: error.message,
success: false
});
}
});
// AI Analysis Endpoint - Analyze questions and generate solutions
app.post('/api/analyze', async (req, res) => {
try {
const { questions } = req.body;
if (!questions || !Array.isArray(questions) || questions.length === 0) {
return res.status(400).json({
error: 'Invalid questions data',
success: false
});
}
console.log(`Analyzing ${questions.length} questions...`);
// Process questions in parallel with rate limiting
const batchSize = 5;
const solutions = [];
for (let i = 0; i < questions.length; i += batchSize) {
const batch = questions.slice(i, i + batchSize);
const batchSolutions = await Promise.all(
batch.map(async (question) => {
try {
const prompt = createAnalysisPrompt(question);
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1500,
messages: [{
role: 'user',
content: prompt
}]
});
const aiResponse = message.content[0].text;
const parsedSolution = parseAIResponse(aiResponse, question);
return {
...question,
solution: parsedSolution,
aiAnalyzed: true
};
} catch (error) {
console.error(`Error analyzing question ${question.id}:`, error.message);
return {
...question,
solution: {
answer: 'Analysis pending',
explanation: 'Unable to analyze this question. Please try again.',
difficulty: 'Moderate',
subject: question.subject || 'General',
estimatedTime: 2
},
aiAnalyzed: false
};
}
})
);
solutions.push(...batchSolutions);
// Small delay between batches to respect rate limits
if (i + batchSize < questions.length) {
await new Promise(resolve => setTimeout(resolve, 500));
}
}
res.json({
solutions,
totalAnalyzed: solutions.filter(s => s.aiAnalyzed).length,
success: true
});
} catch (error) {
console.error('Analysis Error:', error);
res.status(500).json({
error: 'Error analyzing questions. Please try again.',
details: error.message,
success: false
});
}
});
// Generate similar practice questions
app.post('/api/generate-similar', async (req, res) => {
try {
const { question, count = 5 } = req.body;
if (!question) {
return res.status(400).json({
error: 'Question is required',
success: false
});
}
const prompt = `Generate ${count} similar practice questions based on this original question.
Maintain the same difficulty level, topic, and format, but vary the specific details and numbers.
Original Question: ${question.text}
${question.options ? `Options:\n${question.options.join('\n')}` : ''}
For each question, provide:
1. The question text
2. Options (if MCQ)
3. Correct answer
4. Brief explanation
Format each question clearly and number them 1-${count}.`;
const message = await anthropic.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 2000,
messages: [{
role: 'user',
content: prompt
}]
});
res.json({
similarQuestions: message.content[0].text,
count: count,
success: true
});
} catch (error) {
console.error('Generate Similar Error:', error);
res.status(500).json({
error: 'Error generating similar questions',
details: error.message,
success: false
});
}
});
// Helper function to create analysis prompt
function createAnalysisPrompt(question) {
return `You are an expert exam analyzer. Analyze this question and provide a structured response.
Question ${question.id}: ${question.text}
${question.options && question.options.length > 0 ? `\nOptions:\n${question.options.join('\n')}` : ''}
Provide your analysis in the following format:
ANSWER: [The correct answer - for MCQ provide the letter, for numerical provide the value, for descriptive provide a concise answer]
EXPLANATION: [Detailed step-by-step explanation showing how to arrive at the answer]
SUBJECT: [Subject category - choose from: Mathematics, Science, English, Geography, History, Civics, General Knowledge, Computer Science, Economics, or other appropriate subject]
DIFFICULTY: [Easy, Moderate, or Hard]
TYPE: [MCQ, Numerical, Assertion-Reason, Descriptive, or True/False]
TIME: [Estimated time to solve in minutes - just the number]
Be thorough in your explanation and ensure the answer is correct.`;
}
// Helper function to parse AI response
function parseAIResponse(aiResponse, question) {
try {
const lines = aiResponse.split('\n').filter(line => line.trim());
let answer = '';
let explanation = '';
let subject = question.subject || 'General';
let difficulty = 'Moderate';
let type = question.type || 'MCQ';
let estimatedTime = 2;
let currentSection = '';
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('ANSWER:')) {
currentSection = 'answer';
answer = trimmedLine.replace('ANSWER:', '').trim();
} else if (trimmedLine.startsWith('EXPLANATION:')) {
currentSection = 'explanation';
explanation = trimmedLine.replace('EXPLANATION:', '').trim();
} else if (trimmedLine.startsWith('SUBJECT:')) {
subject = trimmedLine.replace('SUBJECT:', '').trim();
} else if (trimmedLine.startsWith('DIFFICULTY:')) {
difficulty = trimmedLine.replace('DIFFICULTY:', '').trim();
} else if (trimmedLine.startsWith('TYPE:')) {
type = trimmedLine.replace('TYPE:', '').trim();
} else if (trimmedLine.startsWith('TIME:')) {
const timeMatch = trimmedLine.match(/\d+/);
if (timeMatch) {
estimatedTime = parseInt(timeMatch[0]);
}
} else if (currentSection === 'explanation' && trimmedLine) {
explanation += '\n' + trimmedLine;
}
}
// Extract correct option letter for MCQ
let correct = null;
if (type === 'MCQ' && answer) {
const optionMatch = answer.match(/^([A-D])/i);
if (optionMatch) {
correct = optionMatch[1].toUpperCase();
}
}
return {
answer: answer || 'Answer pending',
explanation: explanation || 'Explanation pending',
subject: subject,
difficulty: difficulty,
type: type,
correct: correct,
estimatedTime: estimatedTime
};
} catch (error) {
console.error('Error parsing AI response:', error);
return {
answer: 'Parsing error',
explanation: 'Unable to parse AI response. Please try again.',
subject: question.subject || 'General',
difficulty: 'Moderate',
type: question.type || 'MCQ',
estimatedTime: 2
};
}
}
// Error handling middleware
app.use((error, req, res, next) => {
console.error('Server Error:', error);
res.status(500).json({
error: 'Internal server error',
message: error.message,
success: false
});
});
// Start server
app.listen(PORT, () => {
console.log(`
╔═══════════════════════════════════════════════════════╗
║ ║
║ 📚 Exam Analyzer API Server Running 🚀 ║
║ ║
║ Port: ${PORT} ║
║ Environment: ${process.env.NODE_ENV || 'development'} ║
║ API Key: ${process.env.ANTHROPIC_API_KEY ? '✓ Configured' : '✗ Missing'} ║
║ ║
║ Endpoints: ║
║ • GET /api/health ║
║ • POST /api/ocr ║
║ • POST /api/analyze ║
║ • POST /api/generate-similar ║
║ ║
╚═══════════════════════════════════════════════════════╝
`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing HTTP server');
server.close(() => {
console.log('HTTP server closed');
});
});
module.exports = app;
import React, { useState, useRef, useEffect } from 'react';
import { Upload, FileText, Brain, BarChart3, Download, Zap, CheckCircle, AlertCircle, BookOpen, Target, TrendingUp, Clock, Sparkles, ChevronRight, X, Eye, EyeOff } from 'lucide-react';
// Main App Component
export default function ExamAnalyzer() {
const [currentTab, setCurrentTab] = useState('upload');
const [uploadedFile, setUploadedFile] = useState(null);
const [filePreview, setFilePreview] = useState(null);
const [isProcessing, setIsProcessing] = useState(false);
const [processingStage, setProcessingStage] = useState('');
const [extractedText, setExtractedText] = useState('');
const [questions, setQuestions] = useState([]);
const [analytics, setAnalytics] = useState(null);
const [showAnswers, setShowAnswers] = useState({});
const fileInputRef = useRef(null);
const [dragActive, setDragActive] = useState(false);
// Handle file upload
const handleFileUpload = (file) => {
if (!file) return;
const validTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
if (!validTypes.includes(file.type)) {
alert('Please upload a PDF or image file (JPG, PNG)');
return;
}
setUploadedFile(file);
// Create preview
const reader = new FileReader();
reader.onload = (e) => {
setFilePreview(e.target.result);
};
reader.readAsDataURL(file);
};
// Drag and drop handlers
const handleDrag = (e) => {
e.preventDefault();
e.stopPropagation();
if (e.type === "dragenter" || e.type === "dragover") {
setDragActive(true);
} else if (e.type === "dragleave") {
setDragActive(false);
}
};
const handleDrop = (e) => {
e.preventDefault();
e.stopPropagation();
setDragActive(false);
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
handleFileUpload(e.dataTransfer.files[0]);
}
};
// Process the uploaded file
const processFile = async () => {
if (!uploadedFile) return;
setIsProcessing(true);
setProcessingStage('Extracting text from image...');
setCurrentTab('processing');
try {
// Simulate OCR processing (in production, use Tesseract.js or Google Vision API)
await new Promise(resolve => setTimeout(resolve, 2000));
// Mock extracted text (in production, this would be from OCR)
const mockText = `
1. What is the capital of France?
A) London
B) Paris
C) Berlin
D) Madrid
2. Solve: 2x + 5 = 15. Find x.
3. The process by which plants make food is called:
A) Respiration
B) Photosynthesis
C) Transpiration
D) Digestion
4. Assertion (A): Water boils at 100°C at sea level.
Reason (R): The boiling point of water decreases with altitude.
A) Both A and R are true and R is the correct explanation of A
B) Both A and R are true but R is not the correct explanation of A
C) A is true but R is false
D) A is false but R is true
5. In a sentence, "She sings beautifully," what part of speech is "beautifully"?
A) Noun
B) Verb
C) Adjective
D) Adverb
6. Calculate the area of a circle with radius 7 cm. (Use π = 22/7)
7. Who wrote "Romeo and Juliet"?
A) Charles Dickens
B) William Shakespeare
C) Jane Austen
D) Mark Twain
8. If a train travels 120 km in 2 hours, what is its average speed?
9. The largest planet in our solar system is:
A) Earth
B) Mars
C) Jupiter
D) Saturn
10. Assertion (A): Democracy is the best form of government.
Reason (R): It gives power to the people.
A) Both A and R are true and R is the correct explanation of A
B) Both A and R are true but R is not the correct explanation of A
C) A is true but R is false
D) A is false but R is true
`;
setExtractedText(mockText);
setProcessingStage('Analyzing questions...');
await new Promise(resolve => setTimeout(resolve, 1500));
// Parse questions
setProcessingStage('Classifying question types...');
const parsedQuestions = parseQuestions(mockText);
setProcessingStage('Generating AI solutions...');
await new Promise(resolve => setTimeout(resolve, 2000));
// Generate solutions using AI
const questionsWithSolutions = await generateSolutions(parsedQuestions);
setQuestions(questionsWithSolutions);
setProcessingStage('Creating analytics...');
await new Promise(resolve => setTimeout(resolve, 1000));
// Generate analytics
const analyticsData = generateAnalytics(questionsWithSolutions);
setAnalytics(analyticsData);
setIsProcessing(false);
setCurrentTab('questions');
} catch (error) {
console.error('Processing error:', error);
setIsProcessing(false);
alert('Error processing file. Please try again.');
}
};
// Parse questions from text
const parseQuestions = (text) => {
const lines = text.trim().split('\n').filter(line => line.trim());
const questions = [];
let currentQuestion = null;
lines.forEach(line => {
const questionMatch = line.match(/^(\d+)\.\s*(.+)/);
if (questionMatch) {
if (currentQuestion) {
questions.push(currentQuestion);
}
const questionText = questionMatch[2];
const type = detectQuestionType(questionText);
const subject = detectSubject(questionText);
currentQuestion = {
id: questionMatch[1],
text: questionText,
type: type,
subject: subject,
options: [],
difficulty: 'Moderate'
};
} else if (currentQuestion && line.match(/^\s*[A-D]\)/)) {
currentQuestion.options.push(line.trim());
}
});
if (currentQuestion) {
questions.push(currentQuestion);
}
return questions;
};
// Detect question type
const detectQuestionType = (text) => {
if (text.toLowerCase().includes('assertion') || text.toLowerCase().includes('reason')) {
return 'Assertion-Reason';
}
if (text.includes('?') && !text.toLowerCase().includes('calculate') && !text.toLowerCase().includes('solve')) {
return 'MCQ';
}
if (text.toLowerCase().includes('calculate') || text.toLowerCase().includes('solve') || text.toLowerCase().includes('find')) {
return 'Numerical';
}
if (text.toLowerCase().includes('explain') || text.toLowerCase().includes('describe')) {
return 'Descriptive';
}
return 'MCQ';
};
// Detect subject
const detectSubject = (text) => {
const lowerText = text.toLowerCase();
if (lowerText.includes('capital') || lowerText.includes('country') || lowerText.includes('geography')) {
return 'Geography';
}
if (lowerText.includes('x') && (lowerText.includes('=') || lowerText.includes('solve')) || lowerText.includes('calculate')) {
return 'Mathematics';
}
if (lowerText.includes('plant') || lowerText.includes('photosynthesis') || lowerText.includes('boil') || lowerText.includes('planet')) {
return 'Science';
}
if (lowerText.includes('wrote') || lowerText.includes('speech') || lowerText.includes('sentence')) {
return 'English';
}
if (lowerText.includes('democracy') || lowerText.includes('government')) {
return 'Civics';
}
return 'General Knowledge';
};
// Generate AI solutions
const generateSolutions = async (questions) => {
// In production, this would call the Anthropic API
// For demo purposes, we'll use mock solutions
const solutions = {
'1': { answer: 'B) Paris', explanation: 'Paris is the capital and largest city of France, located in the north-central part of the country.', correct: 'B', estimatedTime: 1 },
'2': { answer: 'x = 5', explanation: 'Step 1: 2x + 5 = 15\nStep 2: 2x = 15 - 5\nStep 3: 2x = 10\nStep 4: x = 10/2\nStep 5: x = 5', correct: null, estimatedTime: 2 },
'3': { answer: 'B) Photosynthesis', explanation: 'Photosynthesis is the process by which green plants use sunlight, water, and carbon dioxide to create glucose and oxygen.', correct: 'B', estimatedTime: 1 },
'4': { answer: 'B', explanation: 'Both statements are true. Water does boil at 100°C at sea level, and the boiling point does decrease with altitude. However, R does not explain A - they are separate facts about water\'s boiling behavior.', correct: 'B', estimatedTime: 2 },
'5': { answer: 'D) Adverb', explanation: '"Beautifully" modifies the verb "sings" and describes how she sings, making it an adverb.', correct: 'D', estimatedTime: 1 },
'6': { answer: '154 cm²', explanation: 'Area = πr²\nArea = (22/7) × 7 × 7\nArea = (22/7) × 49\nArea = 22 × 7\nArea = 154 cm²', correct: null, estimatedTime: 3 },
'7': { answer: 'B) William Shakespeare', explanation: 'William Shakespeare wrote the tragedy "Romeo and Juliet" around 1594-1596. It is one of his most famous plays.', correct: 'B', estimatedTime: 1 },
'8': { answer: '60 km/h', explanation: 'Average Speed = Distance / Time\nAverage Speed = 120 km / 2 hours\nAverage Speed = 60 km/h', correct: null, estimatedTime: 2 },
'9': { answer: 'C) Jupiter', explanation: 'Jupiter is the largest planet in our solar system with a diameter of about 142,984 km, more than 11 times the diameter of Earth.', correct: 'C', estimatedTime: 1 },
'10': { answer: 'A', explanation: 'Both statements can be considered true from a normative perspective, and the reason (giving power to people) is indeed the primary explanation for why democracy is often considered the best form of government.', correct: 'A', estimatedTime: 2 }
};
return questions.map(q => ({
...q,
solution: solutions[q.id] || { answer: 'Solution pending', explanation: 'AI analysis in progress...', estimatedTime: 1 }
}));
};
// Generate analytics
const generateAnalytics = (questions) => {
const subjectCount = {};
const typeCount = {};
const difficultyCount = { Easy: 0, Moderate: 0, Hard: 0 };
let totalTime = 0;
questions.forEach(q => {
subjectCount[q.subject] = (subjectCount[q.subject] || 0) + 1;
typeCount[q.type] = (typeCount[q.type] || 0) + 1;
difficultyCount[q.difficulty] = (difficultyCount[q.difficulty] || 0) + 1;
totalTime += q.solution?.estimatedTime || 1;
});
// Assign difficulty levels
questions.forEach((q, idx) => {
if (idx % 3 === 0) q.difficulty = 'Easy';
else if (idx % 3 === 1) q.difficulty = 'Moderate';
else q.difficulty = 'Hard';
difficultyCount[q.difficulty]++;
});
return {
totalQuestions: questions.length,
subjectBreakdown: subjectCount,
typeBreakdown: typeCount,
difficultyBreakdown: difficultyCount,
estimatedTime: totalTime,
topics: Object.keys(subjectCount)
};
};
// Export functions
const exportAnswerKey = () => {
const content = questions.map(q =>
`Q${q.id}. ${q.solution?.answer || 'N/A'}`
).join('\n');
downloadTextFile('answer-key.txt', `ANSWER KEY\n\n${content}`);
};
const exportSolutions = () => {
const content = questions.map(q =>
`Question ${q.id}: ${q.text}\n\nAnswer: ${q.solution?.answer}\n\nExplanation:\n${q.solution?.explanation}\n\n${'='.repeat(60)}\n`
).join('\n');
downloadTextFile('detailed-solutions.txt', `DETAILED SOLUTIONS\n\n${content}`);
};
const exportPracticeSheet = () => {
const content = questions.map(q =>
`${q.id}. ${q.text}\n${q.options.join('\n')}\n`
).join('\n');
downloadTextFile('practice-worksheet.txt', `PRACTICE WORKSHEET\n\n${content}\n\nAnswer Key: (Fill in after attempting)`);
};
const downloadTextFile = (filename, content) => {
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
};
const toggleAnswer = (id) => {
setShowAnswers(prev => ({ ...prev, [id]: !prev[id] }));
};
return (
{/* Header */}
Exam Analyzer Pro
AI-Powered Question Paper Analysis & Auto-Solver
Powered by Claude AI
{/* Navigation Tabs */}
{[
{ id: 'upload', icon: Upload, label: 'Upload' },
{ id: 'questions', icon: FileText, label: 'Questions', disabled: !questions.length },
{ id: 'solutions', icon: Brain, label: 'Solutions', disabled: !questions.length },
{ id: 'analytics', icon: BarChart3, label: 'Analytics', disabled: !analytics },
{ id: 'export', icon: Download, label: 'Export', disabled: !questions.length }
].map(tab => (
!tab.disabled && setCurrentTab(tab.id)}
disabled={tab.disabled}
className={`flex items-center gap-2 px-6 py-3 rounded-xl font-semibold transition-all ${
currentTab === tab.id ? 'tab-active' : 'tab-inactive'
} ${tab.disabled ? 'opacity-50 cursor-not-allowed' : 'hover:shadow-lg'}`}
>
{tab.label}
))}
{/* Main Content */}
{/* Upload Tab */}
{currentTab === 'upload' && (
Upload Question Paper
Upload a scanned exam paper (PDF, JPG, or PNG) to get started
fileInputRef.current?.click()}
>
handleFileUpload(e.target.files[0])}
className="hidden"
/>
{uploadedFile ? uploadedFile.name : 'Drop your file here or click to browse'}
Supports PDF, JPG, PNG (Max 10MB)
{!uploadedFile && (
Select File
)}
{filePreview && (
Preview:
{uploadedFile?.type === 'application/pdf' ? (
{uploadedFile.name}
) : (
)}
)}
{uploadedFile && (
Start AI Analysis
)}
{/* Features Preview */}
{[
{ icon: Brain, title: 'AI-Powered', desc: 'Advanced question analysis & solving', color: 'from-purple-500 to-pink-500' },
{ icon: Target, title: 'Smart Classification', desc: 'Auto-detect question types & subjects', color: 'from-blue-500 to-cyan-500' },
{ icon: BarChart3, title: 'Deep Analytics', desc: 'Performance insights & difficulty analysis', color: 'from-green-500 to-emerald-500' }
].map((feature, idx) => (
{feature.title}
{feature.desc}
))}
)}
{/* Processing Tab */}
{currentTab === 'processing' && isProcessing && (
Processing Your Paper...
{processingStage}
{['OCR', 'Parse', 'AI Solve', 'Analytics'].map((step, idx) => (
))}
)}
{/* Questions Tab */}
{currentTab === 'questions' && questions.length > 0 && (
Extracted Questions
{questions.length} questions identified and classified
setShowAnswers({})}
className="px-4 py-2 bg-white rounded-lg border border-slate-200 text-sm font-semibold text-slate-700 hover:bg-slate-50"
>
Hide All
{
const all = {};
questions.forEach(q => all[q.id] = true);
setShowAnswers(all);
}}
className="px-4 py-2 bg-white rounded-lg border border-slate-200 text-sm font-semibold text-slate-700 hover:bg-slate-50"
>
Show All
{questions.map((question) => (
Q{question.id}
{question.difficulty}
{question.type}
{question.subject}
{question.text}
{question.options.length > 0 && (
{question.options.map((option, idx) => {
const isCorrect = option.startsWith(question.solution?.correct);
return (
{option}
{showAnswers[question.id] && isCorrect && (
)}
);
})}
)}
toggleAnswer(question.id)}
className="ml-4 px-4 py-2 bg-indigo-100 text-indigo-700 rounded-lg font-semibold hover:bg-indigo-200 transition-colors"
>
{showAnswers[question.id] ? : }
{showAnswers[question.id] && question.solution && (
Solution
Answer: {question.solution.answer}
{question.solution.explanation}
Estimated time: {question.solution.estimatedTime} min
)}
))}
)}
{/* Solutions Tab */}
{currentTab === 'solutions' && questions.length > 0 && (
Complete Solutions Guide
{questions.map((question) => (
Question {question.id}
{question.text}
{question.options.length > 0 && (
{question.options.map((opt, idx) => (
{opt}
))}
)}
AI-Generated Solution
✓ {question.solution?.answer}
Explanation:
{question.solution?.explanation}
{question.difficulty}
{question.solution?.estimatedTime || 1} min
))}
)}
{/* Analytics Tab */}
{currentTab === 'analytics' && analytics && (
Paper Analysis & Insights
{/* Summary Stats */}
{analytics.totalQuestions}
Total Questions
{analytics.topics.length}
Subjects Covered
{analytics.estimatedTime}
Minutes (Est.)
{Math.round((analytics.difficultyBreakdown.Hard / analytics.totalQuestions) * 100)}%
Difficulty (Hard)
{/* Subject Breakdown */}
Subject-wise Distribution
{Object.entries(analytics.subjectBreakdown).map(([subject, count]) => {
const percentage = ((count / analytics.totalQuestions) * 100).toFixed(0);
return (
{subject}
{count} questions ({percentage}%)
);
})}
{/* Question Type Breakdown */}
Question Type Analysis
{Object.entries(analytics.typeBreakdown).map(([type, count]) => (
))}
{/* Difficulty Breakdown */}
Difficulty Level Distribution
{Object.entries(analytics.difficultyBreakdown).map(([level, count]) => (
))}
)}
{/* Export Tab */}
{currentTab === 'export' && questions.length > 0 && (
Export Options
Download your analyzed paper in various formats
Answer Key
Quick reference with correct answers only
Download Answer Key
Detailed Solutions
Complete explanations for every question
Download Solutions
Practice Worksheet
Print-friendly version without answers
Download Worksheet
Coming Soon: Advanced Features
Generate 5 similar practice questions for each original question
Create interactive revision flashcards
Build custom mock tests from your papers
WhatsApp-shareable answer summaries
)}
{/* Footer */}
© 2026 Exam Analyzer Pro • Powered by AI
Privacy Policy
•
Terms of Service
•
Support
);
}
Comments
Post a Comment