-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
77 lines (65 loc) · 2 KB
/
Copy pathserver.js
File metadata and controls
77 lines (65 loc) · 2 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
const express = require('express');
const multer = require('multer');
const pdf = require('pdf-parse');
const { OpenAI } = require('openai');
require('dotenv').config();
const path = require('path');
const session = require('express-session');
const app = express();
const upload = multer({ dest: 'uploads/' });
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});
app.use(express.json());
app.use(express.static(path.join(__dirname, '/')));
app.use(session({
secret: 'your-secret-key',
resave: false,
saveUninitialized: true
}));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Upload endpoint
app.post('/upload', upload.single('pdf'), async (req, res) => {
try {
const dataBuffer = fs.readFileSync(req.file.path);
const data = await pdf(dataBuffer);
// Store the PDF text in memory (or database for production)
req.session.pdfText = data.text;
res.json({ message: 'PDF uploaded and processed successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Question answering endpoint
app.post('/ask', async (req, res) => {
try {
const { question } = req.body;
const pdfText = req.session.pdfText;
if (!pdfText) {
return res.status(400).json({ error: 'Please upload a PDF first' });
}
const completion = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
role: "system",
content: "You are a helpful assistant that answers questions based on the provided PDF content."
},
{
role: "user",
content: `Context from PDF: ${pdfText}\n\nQuestion: ${question}`
}
],
max_tokens: 500
});
res.json({ answer: completion.choices[0].message.content });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});