-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
167 lines (145 loc) Β· 5.61 KB
/
Copy pathserver.js
File metadata and controls
167 lines (145 loc) Β· 5.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
require('dotenv').config();
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const fetch = require('node-fetch');
const pdfParse = require('pdf-parse');
const mammoth = require('mammoth');
const app = express();
const PORT = process.env.PORT || 3000;
const API_KEY = process.env.GEMINI_API_KEY;
const GEMINI_MODEL = 'gemini-2.5-flash';
if (!fs.existsSync(path.join(__dirname, 'uploads'))) {
fs.mkdirSync(path.join(__dirname, 'uploads'));
}
app.use(express.json());
app.use(express.static(path.join(__dirname, '.')));
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, path.join(__dirname, 'uploads')),
filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const upload = multer({
storage,
limits: { fileSize: 20 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowed = ['.pdf', '.doc', '.docx', '.txt', '.ppt', '.pptx'];
const ext = path.extname(file.originalname).toLowerCase();
if (allowed.includes(ext)) cb(null, true);
else cb(new Error('Unsupported file type: ' + ext));
}
});
async function extractText(filePath, originalName) {
const ext = path.extname(originalName).toLowerCase();
if (ext === '.txt') return fs.readFileSync(filePath, 'utf8');
if (ext === '.pdf') {
const buffer = fs.readFileSync(filePath);
const data = await pdfParse(buffer);
return data.text;
}
if (ext === '.docx' || ext === '.doc') {
const result = await mammoth.extractRawText({ path: filePath });
return result.value;
}
if (ext === '.pptx' || ext === '.ppt') {
try {
const buffer = fs.readFileSync(filePath);
const result = await mammoth.extractRawText({ buffer });
return result.value || 'Could not extract text from presentation.';
} catch (e) {
return 'Could not extract text from presentation file.';
}
}
throw new Error('Unsupported file type');
}
app.post('/api/generate', upload.single('file'), async (req, res) => {
const filePath = req.file?.path;
try {
if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
if (!API_KEY) return res.status(500).json({ error: 'GEMINI_API_KEY not set in .env' });
const count = parseInt(req.body.count) || 10;
const difficulty = req.body.difficulty || 'medium';
let textContent = '';
try {
textContent = await extractText(filePath, req.file.originalname);
} catch (e) {
return res.status(400).json({ error: 'Could not read file: ' + e.message });
}
if (!textContent || textContent.trim().length < 50) {
return res.status(400).json({ error: 'File content too short or empty. Please upload a proper document.' });
}
const content = textContent.slice(0, 20000);
const diffMap = {
easy: 'easy and basic, suitable for beginners',
medium: 'medium difficulty, suitable for exam practice',
hard: 'hard exam-level questions that test deep understanding'
};
const prompt = `You are an expert teacher. Create ${count} multiple choice questions from the content below.
Difficulty: ${diffMap[difficulty] || diffMap.medium}
Rules:
- Each question has exactly 4 options (A, B, C, D)
- Only ONE correct answer per question
- Wrong options must be plausible but clearly wrong
- Spread questions across different topics in the content
- Return ONLY valid JSON array, no markdown, no code blocks, no explanation
JSON format:
[
{
"q": "Question text?",
"options": ["Option A", "Option B", "Option C", "Option D"],
"correct": 0,
"explanation": "Why this answer is correct."
}
]
"correct" = 0-based index (0=A, 1=B, 2=C, 3=D)
Content:
${content}`;
const url = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent`;
const apiRes = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': API_KEY
},
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
temperature: 0.7,
maxOutputTokens: 8000,
responseMimeType: 'application/json'
}
})
});
const apiData = await apiRes.json();
if (apiData.error) {
return res.status(500).json({ error: 'Gemini API error: ' + apiData.error.message });
}
const raw = apiData.candidates?.[0]?.content?.parts?.[0]?.text || '';
if (!raw) return res.status(500).json({ error: 'Empty response from Gemini. Try again.' });
const clean = raw.replace(/```json\n?|```\n?/g, '').trim();
let questions;
try {
questions = JSON.parse(clean);
} catch (e) {
return res.status(500).json({ error: 'Could not parse questions. Try again.' });
}
if (!Array.isArray(questions) || !questions.length) {
return res.status(500).json({ error: 'No questions generated. Try again.' });
}
res.json({ questions, total: questions.length });
} catch (err) {
console.error('Error:', err);
res.status(500).json({ error: err.message || 'Server error' });
} finally {
if (filePath && fs.existsSync(filePath)) fs.unlinkSync(filePath);
}
});
app.get('/api/health', (req, res) => {
res.json({ status: 'ok', apiKey: API_KEY ? 'Set' : 'Missing', model: GEMINI_MODEL, port: PORT });
});
app.listen(PORT, () => {
console.log(`\nπ SmartQuiz Server running on http://localhost:${PORT}`);
console.log(`π€ AI Model: ${GEMINI_MODEL} (Google Gemini)`);
console.log(`π API Key: ${API_KEY ? 'β
Loaded' : 'β Missing β set GEMINI_API_KEY in .env'}`);
console.log(`π Uploads folder: ${path.join(__dirname, 'uploads')}\n`);
});