-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
179 lines (127 loc) · 5.37 KB
/
server.js
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
168
169
170
171
172
173
174
175
176
177
178
179
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
const fs = require('fs');
const path = require('path');
const csv = require('csv-parser');
const { log } = require('console');
require('dotenv').config();
// import { GoogleGenerativeAI } from "@google/generative-ai";
const { GoogleGenerativeAI } = require('@google/generative-ai');
const apiKey = process.env.Gemini_API_KEY;
// Middleware to parse JSON bodies
app.use(express.json());
// Middleware to enable CORS
app.use(cors());
// Read the CSV file
const readCSV = () => {
return new Promise((resolve, reject) => {
const filePath = path.join(__dirname, 'geography_questions.csv');
const results = [];
fs.createReadStream(filePath)
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => resolve(results))
.on('error', (error) => reject(error));
});
}
(async () => {
try{
const csvData = await readCSV();
let questionIndex = 0;
let score = 0;
let lives = 3;
let hints = 3;
// toDo: remove this
console.log("questionIndex is: ", questionIndex, " and csvData.length is: ", csvData.length);
// routes
app.get('/test', (req, res) => {
res.send('Hello, World!');
});
app.get('/api/start', (req, res) => {
res.json({ score: score, lives: lives, hints: hints, isGameOver: false });
});
app.get('/api/question', (req, res) => {
if (questionIndex < csvData.length) {
const question = csvData[questionIndex];
res.json({question: question.Question})
} else if (questionIndex === csvData.length) {
res.json({question: "completed"})
} else {
res.status(404).send('No more questions');
}
});
const getHint = async (question) => {
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = `
You are a geography expert. You are given a question and need to provide a hint that is related to the question. The hint should not be the answer to the question or contain any key words from the question. The question is: ${question}. Provide hint that is less than 20 words.
`
const result = await model.generateContent(prompt);
console.log(result.response.text());
return result.response.text();
}
// get hint from gemini
app.get('/api/hint', async (req, res) => {
if (hints > 0) {
const question = csvData[questionIndex];
const questionHint = await getHint(question.Question);
console.log("questionHint is: ", questionHint);
res.json({ questionHint: questionHint, hintsRemaining: hints });
hints--;
} else {
res.json({ questionHint: "No hints left", hintsRemaining: hints });
}
});
app.get('/api/stats', (req, res) => {
const accuracy = ((score / (questionIndex)) * 100).toFixed(2);
res.json({ score: score, lives: lives, hints: hints, accuracy: accuracy });
});
app.post('/api/response', (req, res) => {
const response = req.body;
const userAnswer = response.answer;
const correctAnswer = csvData[questionIndex].Answer;
console.log("userAnswer is: ", userAnswer.toLowerCase().trim(), " and correctAnswer is: ", correctAnswer.toLowerCase().trim());
if (userAnswer.toLowerCase().trim() === correctAnswer.toLowerCase().trim()) {
score++;
if (score % 3 === 0){
lives++;
}
res.json({ answer: correctAnswer, message: 'Correct', score: score, lives: lives, hints: hints, isGameOver: false });
} else {
lives--;
if (lives <= 0) {
res.json({ answer: correctAnswer, message: 'Incorrect', score: score, lives: lives, hints: hints, isGameOver: true });
} else {
res.json({ answer: correctAnswer, message: 'Incorrect', score: score, lives: lives, hints: hints, isGameOver: false });
}
}
console.log({
questionIndex: questionIndex,
score: score,
lives: lives,
hints: hints,
isGameOver: false
});
questionIndex++;
});
app.get('/api/reset', (req, res) => {
console.log("resetting game");
questionIndex = 0;
score = 0;
lives = 3;
hints = 3;
res.json({ message: 'Question index reset to 0' });
});
// Start the server
app.listen(PORT, '0.0.0.0', () => {
// app.listen(PORT, () => {
console.log(`Server is running on http://0.0.0.0:${PORT}`);
// console.log(`Server is running on http://localhost:${PORT}`);
});
}
catch (error){
console.log("An error occurred:", error);
}
})();