Compare commits
55 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d18f173ef6 | ||
|
|
10a797d450 | ||
|
|
3a64479fd4 | ||
|
|
d4d2a32a71 | ||
|
|
e8c29025aa | ||
|
|
b909a85225 | ||
|
|
b69bc6200f | ||
|
|
6d03408495 | ||
|
|
552cfbe574 | ||
|
|
ed657df69a | ||
|
|
3b75e915e3 | ||
|
|
02cc60f824 | ||
|
|
c2ee394195 | ||
|
|
7dda27e86e | ||
|
|
5152ca2e23 | ||
|
|
e520169fb9 | ||
| ddc864a25d | |||
| 9fa326666f | |||
| abcb44ace7 | |||
| 8ecbe43e6e | |||
| 583f85a7e8 | |||
| 2dec203ad0 | |||
| 9a64b60454 | |||
| 2593bfc7d9 | |||
| 3a73d0a9be | |||
| cad9154900 | |||
| c934f45726 | |||
| f1198c21de | |||
| 8eb4da619a | |||
| b5d40f21a6 | |||
| 411766987c | |||
| 51c520108b | |||
| 7fcc27ada1 | |||
| 02ec79b262 | |||
| 5e23f73645 | |||
| 2cbf1ebbaa | |||
| 5775c45d8c | |||
| 0a78f89fa9 | |||
| 101e1a2749 | |||
| 7252cfcce4 | |||
| 41c2ceb675 | |||
| da33f2ed43 | |||
| 060e6b0f1a | |||
| 58805dac6f | |||
| f490aac87e | |||
| 67bc3e9995 | |||
| a9a0cd5ca3 | |||
| 1244f5f06b | |||
| c74a6fd67d | |||
|
|
10b7fc5ee2 | ||
| 879a792907 | |||
| 554b4e8946 | |||
| 0381f74f06 | |||
| 8b420fb34f | |||
| f12e2d9e0a |
@@ -1,3 +1,6 @@
|
||||
node_modules
|
||||
.git
|
||||
.gitignore
|
||||
**/docker-compose*
|
||||
**/compose.y*ml
|
||||
**/Dockerfile*
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -3,7 +3,7 @@ node_modules
|
||||
|
||||
# yarn error logs
|
||||
yarn-error.log
|
||||
|
||||
yarn.lock
|
||||
# Environment varibales
|
||||
.env*
|
||||
!.env*.example
|
||||
|
||||
14
Dockerfile
14
Dockerfile
@@ -1,8 +1,12 @@
|
||||
FROM node:alpine
|
||||
ARG NODE_VERSION=18
|
||||
|
||||
RUN mkdir -p /usr/src/node-app && chown -R node:node /usr/src/node-app
|
||||
FROM node:${NODE_VERSION}-alpine
|
||||
|
||||
WORKDIR /usr/src/node-app
|
||||
ENV NODE_ENV production
|
||||
|
||||
RUN mkdir -p /usr/src/iimtt_api && chown -R node:node /usr/src/iimtt_api
|
||||
|
||||
WORKDIR /usr/src/iimtt_api
|
||||
|
||||
COPY package.json yarn.lock ./
|
||||
|
||||
@@ -12,4 +16,6 @@ RUN yarn install --pure-lockfile
|
||||
|
||||
COPY --chown=node:node . .
|
||||
|
||||
EXPOSE 3000
|
||||
EXPOSE 5174
|
||||
|
||||
CMD yarn start
|
||||
@@ -1,32 +1,31 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
node-app:
|
||||
iimtt_api:
|
||||
build: .
|
||||
image: node-app
|
||||
environment:
|
||||
- MONGODB_URL=mongodb://mongodb:27017/node-boilerplate
|
||||
image: iimtt_api
|
||||
# environment:
|
||||
# - MONGODB_URL=mongodb://mongodb:27017/node-boilerplate
|
||||
ports:
|
||||
- '3000:3000'
|
||||
depends_on:
|
||||
- mongodb
|
||||
- '5174:5174'
|
||||
# depends_on:
|
||||
# - mongodb
|
||||
volumes:
|
||||
- .:/usr/src/node-app
|
||||
networks:
|
||||
- node-network
|
||||
- .:/usr/src/iimtt_api
|
||||
# networks:
|
||||
# - host
|
||||
# - node-network
|
||||
|
||||
mongodb:
|
||||
image: mongo:4.2.1-bionic
|
||||
ports:
|
||||
- '27017:27017'
|
||||
volumes:
|
||||
- dbdata:/data/db
|
||||
networks:
|
||||
- node-network
|
||||
# mongodb:
|
||||
# image: mongo:4.2.1-bionic
|
||||
# ports:
|
||||
# - '27017:27017'
|
||||
# volumes:
|
||||
# - dbdata:/data/db
|
||||
# networks:
|
||||
# - node-network
|
||||
|
||||
volumes:
|
||||
dbdata:
|
||||
# volumes:
|
||||
# dbdata:
|
||||
|
||||
networks:
|
||||
node-network:
|
||||
driver: bridge
|
||||
# networks:
|
||||
# node-network:
|
||||
# driver: bridge
|
||||
|
||||
BIN
output.png
Normal file
BIN
output.png
Normal file
Binary file not shown.
16541
package-lock.json
generated
Normal file
16541
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
13
package.json
13
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "iimttapi",
|
||||
"version": "0.0.1",
|
||||
"version": "1.0.0",
|
||||
"description": "Create a Node.js app for building production-ready RESTful APIs using Express, by running one command",
|
||||
"bin": "bin/createNodejsApp.js",
|
||||
"main": "src/index.js",
|
||||
@@ -9,7 +9,8 @@
|
||||
"node": ">=12.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "pm2 start ecosystem.config.json --no-daemon",
|
||||
"start": "NODE_ENV=production node src/index.js",
|
||||
"start:pm2": "pm2 start ecosystem.config.json --no-daemon",
|
||||
"dev": "cross-env NODE_ENV=development nodemon src/index.js",
|
||||
"test": "jest -i --colors --verbose --detectOpenHandles",
|
||||
"test:watch": "jest -i --watchAll",
|
||||
@@ -48,6 +49,7 @@
|
||||
],
|
||||
"dependencies": {
|
||||
"aws-sdk": "^2.1669.0",
|
||||
"axios": "^1.7.7",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"body-parser": "^1.20.2",
|
||||
"compression": "^1.7.4",
|
||||
@@ -57,15 +59,20 @@
|
||||
"express": "^4.17.1",
|
||||
"express-mongo-sanitize": "^2.0.0",
|
||||
"express-rate-limit": "^5.0.0",
|
||||
"form-data": "^4.0.1",
|
||||
"formdata-node": "^6.0.3",
|
||||
"helmet": "^4.1.0",
|
||||
"http-status": "^1.4.0",
|
||||
"install": "^0.13.0",
|
||||
"joi": "^17.3.0",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"moment": "^2.24.0",
|
||||
"mongoose": "^5.7.7",
|
||||
"mongoose": "^8.7.1",
|
||||
"morgan": "^1.9.1",
|
||||
"mysql2": "^3.11.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"nodemailer": "^6.3.1",
|
||||
"npm": "^11.0.0",
|
||||
"passport": "^0.4.0",
|
||||
"passport-jwt": "^4.0.0",
|
||||
"pm2": "^5.1.0",
|
||||
|
||||
@@ -38,7 +38,7 @@ module.exports = {
|
||||
mongoose: {
|
||||
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
|
||||
options: {
|
||||
useCreateIndex: true,
|
||||
// useCreateIndex: true,
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
},
|
||||
|
||||
12
src/models/gameModel.js
Normal file
12
src/models/gameModel.js
Normal file
@@ -0,0 +1,12 @@
|
||||
const mongoose = require("mongoose");
|
||||
|
||||
const gameSchema = new mongoose.Schema({
|
||||
gameName: { type: String, required: true },
|
||||
childId: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
gameTime: { type: String, required: false },
|
||||
gameStar: { type: Number },
|
||||
screenshotUrl: { type: String },
|
||||
}, { collection: "gameData" });
|
||||
|
||||
module.exports = mongoose.model("Game", gameSchema);
|
||||
15
src/models/getGalleyImage.js
Normal file
15
src/models/getGalleyImage.js
Normal file
@@ -0,0 +1,15 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
// Define the GalleryImage schema
|
||||
const galleryImageSchema = new mongoose.Schema({
|
||||
childId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, // Assuming you have a User model
|
||||
gameName: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
screenshotUrl: { type: String, required: true },
|
||||
message: { type: String, default: 'Image received' },
|
||||
}, { timestamps: true });
|
||||
|
||||
// Check if the model already exists in mongoose.models
|
||||
const GalleryImage = mongoose.models.GalleryImage || mongoose.model('GalleryImage', galleryImageSchema);
|
||||
|
||||
module.exports = GalleryImage;
|
||||
10
src/models/imageGallery.js
Normal file
10
src/models/imageGallery.js
Normal file
@@ -0,0 +1,10 @@
|
||||
const mongoose = require("mongoose");
|
||||
|
||||
const galleryImageScema = new mongoose.Schema({
|
||||
gameName: { type: String, required: true },
|
||||
childId: { type: String, required: true },
|
||||
gameID: { type: String, required: true },
|
||||
screenshotUrl: { type: String },
|
||||
});
|
||||
|
||||
module.exports = mongoose.model("GalleryImage", galleryImageScema);
|
||||
21
src/module/base64ToImageFile.js
Normal file
21
src/module/base64ToImageFile.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
function base64ToImageFile(base64, fileName) {
|
||||
const matches = base64.match(/^data:(.+);base64,(.+)$/);
|
||||
if (!matches) {
|
||||
throw new Error("Invalid Base64 string");
|
||||
}
|
||||
|
||||
const mimeType = matches[1]; // e.g., image/png
|
||||
const base64Data = matches[2]; // Actual base64 string
|
||||
|
||||
const buffer = Buffer.from(base64Data, 'base64');
|
||||
const filePath = path.join(__dirname, fileName);
|
||||
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
|
||||
return filePath;
|
||||
}
|
||||
|
||||
module.exports = { base64ToImageFile };
|
||||
103
src/routes/api/aiEvaluateImageToScore.js
Normal file
103
src/routes/api/aiEvaluateImageToScore.js
Normal file
@@ -0,0 +1,103 @@
|
||||
const AWS = require('aws-sdk');
|
||||
const axios = require('axios');
|
||||
const mongoose = require('mongoose');
|
||||
const Game = require('../../models/gameModel'); // Ensure this path matches your project structure
|
||||
|
||||
const aiEvaluateImageToScore = async (req, res) => {
|
||||
try {
|
||||
// Destructure data from req.body
|
||||
const { userId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||
|
||||
if (!screenShot) {
|
||||
return res.status(400).json({ error: 'Screenshot is required' });
|
||||
}
|
||||
|
||||
// Decode the base64 image
|
||||
const buffer = Buffer.from(screenShot, 'base64');
|
||||
const fileName = `${Date.now()}-${gameID}.png`; // Unique filename
|
||||
const bucketName = process.env.S3_BUCKET_NAME;
|
||||
|
||||
// Initialize S3
|
||||
AWS.config.update({
|
||||
region: 'ap-south-1',
|
||||
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
});
|
||||
const s3 = new AWS.S3();
|
||||
|
||||
// Upload the image to S3
|
||||
const s3Params = {
|
||||
Bucket: bucketName,
|
||||
Key: `screenshots/${fileName}`,
|
||||
Body: buffer,
|
||||
ContentType: 'image/png',
|
||||
ACL: 'public-read', // Make the file publicly accessible
|
||||
};
|
||||
|
||||
const s3UploadResponse = await s3.upload(s3Params).promise();
|
||||
const screenshotUrl = s3UploadResponse.Location;
|
||||
|
||||
// Prepare the OpenAI API request
|
||||
const openAiPayload = {
|
||||
model: 'gpt-4o-mini',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'The coloring was done by a 5-year-old kid. Give a score between 1 to 10 in JSON format.',
|
||||
},
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: screenshotUrl,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
max_tokens: 300,
|
||||
};
|
||||
|
||||
// Call the OpenAI API
|
||||
const openAiResponse = await axios.post(
|
||||
'https://api.openai.com/v1/chat/completions',
|
||||
openAiPayload,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// Extract the score from OpenAI's response
|
||||
const scoreResponse = openAiResponse.data.choices[0].message.content;
|
||||
const parsedScore = JSON.parse(scoreResponse);
|
||||
|
||||
// Save to MongoDB
|
||||
const gameData = new Game({
|
||||
gameName,
|
||||
userId,
|
||||
gameID,
|
||||
gameTime,
|
||||
score: parsedScore.score || 'N/A', // Adjust key to match OpenAI response
|
||||
gameStar,
|
||||
screenshotUrl,
|
||||
});
|
||||
|
||||
await gameData.save();
|
||||
|
||||
// Respond with the saved data
|
||||
return res.status(201).json({
|
||||
message: 'Game data saved successfully',
|
||||
data: gameData,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
return res.status(500).json({ error: 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = aiEvaluateImageToScore;
|
||||
94
src/routes/api/aiEvaluateImageToStar.js
Normal file
94
src/routes/api/aiEvaluateImageToStar.js
Normal file
@@ -0,0 +1,94 @@
|
||||
const AWS = require('aws-sdk');
|
||||
const axios = require('axios');
|
||||
const mongoose = require('mongoose');
|
||||
const FormData = require('form-data');
|
||||
const Game = require('../../models/gameModel');
|
||||
const aiEvaluateImageToStar = async (req, res) => {
|
||||
try {
|
||||
const { childId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
|
||||
if (!screenShot) {
|
||||
return res.status(400).json({ error: 'Screenshot is required' });
|
||||
}
|
||||
|
||||
// Upload screenshot
|
||||
const formData = new FormData();
|
||||
formData.append('image', screenShot);
|
||||
|
||||
const screenshotUploadResponse = await axios.post('https://teachertrainingchennai.in/api/uploadBase64/', formData, {
|
||||
headers: {
|
||||
...formData.getHeaders(),
|
||||
},
|
||||
});
|
||||
|
||||
const screenshotUrl = screenshotUploadResponse.data.filePath;
|
||||
// The coloring was done by a 5-year-old kid. Give a score between 1 to 10 in JSON format.
|
||||
const openAiPayload = {
|
||||
model: 'gpt-4o-mini',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'The coloring was done by a 5-year-old kid. Give a score between 1 to 10 the Respond ONLY with a valid JSON object like {"score": 7}. No extra text, no formatting, just raw JSON.',
|
||||
},
|
||||
{
|
||||
type: 'image_url',
|
||||
image_url: {
|
||||
url: screenshotUrl,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
max_tokens: 300,
|
||||
};
|
||||
|
||||
const openAiResponse = await axios.post(
|
||||
'https://api.openai.com/v1/chat/completions',
|
||||
openAiPayload,
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
if (!openAiResponse.data.choices || openAiResponse.data.choices.length === 0) {
|
||||
throw new Error('Invalid OpenAI response format');
|
||||
}
|
||||
|
||||
let scoreResponse = openAiResponse.data.choices[0].message.content.trim();
|
||||
|
||||
if (scoreResponse.startsWith('```json')) {
|
||||
scoreResponse = scoreResponse.replace(/```json/, '').replace(/```/, '').trim();
|
||||
}
|
||||
|
||||
|
||||
const parsedScore = JSON.parse(scoreResponse);
|
||||
// console.log('Parsed Score:', parsedScore);
|
||||
|
||||
const gameData = new Game({
|
||||
gameName,
|
||||
childId,
|
||||
gameID,
|
||||
gameTime,
|
||||
gameStar: parsedScore.score || 'N/A',
|
||||
screenshotUrl,
|
||||
});
|
||||
|
||||
await gameData.save();
|
||||
|
||||
return res.status(200).json({
|
||||
message: 'Game data saved successfully',
|
||||
data: gameData,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
return res.status(500).json({ error: error.message || 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = aiEvaluateImageToStar;
|
||||
35
src/routes/api/aiFeedbackActionParent.js
Normal file
35
src/routes/api/aiFeedbackActionParent.js
Normal file
@@ -0,0 +1,35 @@
|
||||
const aiFeedbackOnReport = async (req, res) => {
|
||||
const fetch = require('node-fetch');
|
||||
const url = process.env.AI_API_ENDOINT;
|
||||
const api_key = process.env.AI_API_KEY;
|
||||
const payload = {
|
||||
"model": "gpt-3.5-turbo-16k",
|
||||
"messages": [{ "role": "user",
|
||||
"content": JSON.stringify(req.body.grades) + " - first dataset(grades) " + JSON.stringify(req.body.suggested) + " - second dataset(suggested actions) " + req.body.instruction }]
|
||||
}
|
||||
try {
|
||||
const apiResponse = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${api_key}`,
|
||||
// 'Authorization': api_key,
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
return res.status(apiResponse.status).send({ error: 'API response was not ok'+res });
|
||||
}
|
||||
|
||||
const data = await apiResponse.json();
|
||||
|
||||
res.send(data);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
res.status(500).send({ error: 'Something went wrong with the fetch operation' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = aiFeedbackOnReport;
|
||||
35
src/routes/api/aiFeedbackOnReport.js
Normal file
35
src/routes/api/aiFeedbackOnReport.js
Normal file
@@ -0,0 +1,35 @@
|
||||
const aiFeedbackOnReport = async (req, res) => {
|
||||
// const fetch = require('node-fetch');
|
||||
const url = process.env.AI_API_ENDOINT;
|
||||
const api_key = process.env.AI_API_KEY;
|
||||
const payload = {
|
||||
"model": "gpt-4o-mini",
|
||||
"messages": [{ "role": "user",
|
||||
"content": JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction }]
|
||||
}
|
||||
try {
|
||||
const apiResponse = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${api_key}`,
|
||||
// 'Authorization': api_key,
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
return res.status(apiResponse.status).send({ error: 'API response was not ok'+res });
|
||||
}
|
||||
|
||||
const data = await apiResponse.json();
|
||||
|
||||
res.send(data);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error fetching data:', error);
|
||||
res.status(500).send({ error: 'Something went wrong with the fetch operation' });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = aiFeedbackOnReport;
|
||||
95
src/routes/api/aiFeedbackOnReportWithFollowup.js
Normal file
95
src/routes/api/aiFeedbackOnReportWithFollowup.js
Normal file
@@ -0,0 +1,95 @@
|
||||
const aiFollowupQuestion = async (req, res) => {
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
const fetch = require('node-fetch');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url);
|
||||
|
||||
await client.connect();
|
||||
const database = client.db(dbName); // Replace with your database name
|
||||
const conversationsCollection = database.collection('conversations'); // Replace with your collection name
|
||||
|
||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 200) {
|
||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: model,
|
||||
messages: messages,
|
||||
max_tokens: max_tokens,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data.choices[0].message.content;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 200 } = req.body;
|
||||
if (!conversationsCollection) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'MongoDB is not connected yet. Please try again later.',
|
||||
});
|
||||
}
|
||||
let conversation;
|
||||
|
||||
if (!sessionId) {
|
||||
const newSessionId = uuidv4();
|
||||
|
||||
conversation = {
|
||||
sessionId: newSessionId,
|
||||
conversationHistory: [
|
||||
{ role: 'system', content: 'You are a helpful assistant.' },
|
||||
// { role: 'user', content: prompt },
|
||||
{ role: 'user', content: req.body.score + " - is the students report card. " + req.body.instruction },
|
||||
],
|
||||
};
|
||||
await conversationsCollection.insertOne(conversation);
|
||||
} else {
|
||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||
if (!conversation) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid session ID.',
|
||||
});
|
||||
}
|
||||
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
||||
}
|
||||
|
||||
// Call OpenAI API with the conversation history
|
||||
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
||||
|
||||
// Add the AI's response to the conversation history
|
||||
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse });
|
||||
|
||||
// Update the conversation in MongoDB
|
||||
await conversationsCollection.updateOne(
|
||||
{ sessionId: conversation.sessionId },
|
||||
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||
);
|
||||
|
||||
// Send the AI's response and session ID back to the frontend
|
||||
res.json({
|
||||
success: true,
|
||||
data: aiResponse,
|
||||
sessionId: conversation.sessionId, // Return the session ID for subsequent queries
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error generating response:', error.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Something went wrong. Please try again later.',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = aiFollowupQuestion;
|
||||
91
src/routes/api/aiFollowupQuestion.js
Normal file
91
src/routes/api/aiFollowupQuestion.js
Normal file
@@ -0,0 +1,91 @@
|
||||
const aiFollowupQuestion = async (req, res) => {
|
||||
|
||||
const { MongoClient } = require('mongodb');
|
||||
const fetch = require('node-fetch');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url);
|
||||
|
||||
await client.connect();
|
||||
const database = client.db(dbName);
|
||||
const conversationsCollection = database.collection('conversations');
|
||||
|
||||
async function fetchOpenAICompletion(prompt, messages, model = "gpt-3.5-turbo-16k", max_tokens = 200) {
|
||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${process.env.OPENAI_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: model,
|
||||
messages: messages,
|
||||
max_tokens: max_tokens,
|
||||
}),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
try {
|
||||
const { prompt, sessionId, model = "gpt-3.5-turbo-16k", max_tokens = 200 } = req.body;
|
||||
if (!conversationsCollection) {
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
error: 'MongoDB is not connected yet. Please try again later.',
|
||||
});
|
||||
}
|
||||
let conversation;
|
||||
|
||||
if (!sessionId) {
|
||||
const newSessionId = uuidv4();
|
||||
|
||||
conversation = {
|
||||
sessionId: newSessionId,
|
||||
conversationHistory: [
|
||||
{ role: 'system', content: 'answer within 50 words' },
|
||||
{ role: 'user', content: prompt },
|
||||
],
|
||||
};
|
||||
await conversationsCollection.insertOne(conversation);
|
||||
} else {
|
||||
conversation = await conversationsCollection.findOne({ sessionId: sessionId });
|
||||
if (!conversation) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid session ID.',
|
||||
});
|
||||
}
|
||||
conversation.conversationHistory.push({ role: 'user', content: prompt });
|
||||
}
|
||||
|
||||
const aiResponse = await fetchOpenAICompletion(prompt, conversation.conversationHistory, model, max_tokens);
|
||||
|
||||
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices[0].message.content });
|
||||
|
||||
await conversationsCollection.updateOne(
|
||||
{ sessionId: conversation.sessionId },
|
||||
{ $set: { conversationHistory: conversation.conversationHistory } }
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: aiResponse.choices[0].message.content,
|
||||
total_tokens: aiResponse.usage.total_tokens,
|
||||
sessionId: conversation.sessionId,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error generating response:', error.message);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Something went wrong. Please try again later.',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = aiFollowupQuestion;
|
||||
116
src/routes/api/aiMarkDrawing.js
Normal file
116
src/routes/api/aiMarkDrawing.js
Normal file
@@ -0,0 +1,116 @@
|
||||
const aiMarkDrawing = async (req, res) => {
|
||||
|
||||
|
||||
const express = require('express');
|
||||
const fetch = require('node-fetch'); // For making HTTP requests
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
// Create an Express app
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
// Middleware to handle JSON and URL-encoded form data
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
|
||||
// Replace with your OpenAI API key
|
||||
const OPENAI_API_KEY = 'your-openai-api-key';
|
||||
|
||||
// Route to handle image upload and forward it to OpenAI API
|
||||
app.post('/upload-image', async (req, res) => {
|
||||
try {
|
||||
// Check if the file is included in the request
|
||||
if (!req.headers['content-type']?.includes('multipart/form-data')) {
|
||||
return res.status(400).send({ message: 'No file uploaded' });
|
||||
}
|
||||
|
||||
// Extract the raw body data (binary) from the request
|
||||
let imageBuffer = Buffer.alloc(0);
|
||||
|
||||
// Collect the image data from the stream (raw body)
|
||||
req.on('data', chunk => {
|
||||
imageBuffer = Buffer.concat([imageBuffer, chunk]);
|
||||
});
|
||||
|
||||
req.on('end', async () => {
|
||||
// Forward the image to OpenAI's API for scoring
|
||||
const score = await sendImageToOpenAI(imageBuffer);
|
||||
|
||||
// Respond with the score
|
||||
res.json({ score: score });
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error processing the image:', error);
|
||||
res.status(500).send({ message: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Function to send image to OpenAI API and get the response
|
||||
async function sendImageToOpenAI(imageBuffer) {
|
||||
try {
|
||||
// Convert binary image data to base64 format
|
||||
const imageBase64 = imageBuffer.toString('base64');
|
||||
|
||||
// Make a request to the OpenAI API using fetch
|
||||
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${OPENAI_API_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "gpt-4-vision", // Use the appropriate model
|
||||
messages: [
|
||||
{ role: "system", content: "You are a grading assistant for 2nd grade students." },
|
||||
{ role: "user", content: "Evaluate this student's drawing or coloring." }
|
||||
],
|
||||
functions: {
|
||||
function_call: {
|
||||
name: "vision_function",
|
||||
args: {
|
||||
image: imageBase64 // Send the image in base64 format
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
// Parse the response
|
||||
const data = await response.json();
|
||||
|
||||
// Extract the score or other relevant information from the response
|
||||
const aiResponse = data.choices[0].message.content;
|
||||
|
||||
// You can parse this response and extract the score, for example:
|
||||
const score = extractScoreFromResponse(aiResponse);
|
||||
return score;
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error interacting with OpenAI API:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Example function to extract a score from OpenAI's response (you need to define this based on the actual response structure)
|
||||
function extractScoreFromResponse(responseText) {
|
||||
// You can use a regex or logic to extract the score from OpenAI's response
|
||||
const scoreMatch = responseText.match(/score:\s*(\d+)/i);
|
||||
if (scoreMatch) {
|
||||
return parseInt(scoreMatch[1], 10);
|
||||
} else {
|
||||
// If no score is found, return a default value
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Start the server
|
||||
app.listen(port, () => {
|
||||
console.log(`Server running at http://localhost:${port}`);
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
module.exports = aiMarkDrawing;
|
||||
85
src/routes/api/aiTextToSpeech.js
Normal file
85
src/routes/api/aiTextToSpeech.js
Normal file
@@ -0,0 +1,85 @@
|
||||
const axios = require('axios');
|
||||
const AWS = require('aws-sdk');
|
||||
const FormData = require('form-data');
|
||||
|
||||
const aiTextToSpeech = async (req, res) => {
|
||||
AWS.config.update({
|
||||
region: 'ap-south-1',
|
||||
accessKeyId: process.env.AWS_polly2_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.AWS_polly2_SECRET_ACCESS_KEY,
|
||||
});
|
||||
|
||||
const polly = new AWS.Polly();
|
||||
const voiceIdMap = {
|
||||
"Ava": "Ivy",
|
||||
"Monstero": "Justin",
|
||||
"Dax": "Kevin",
|
||||
"Kai": "Danielle",
|
||||
"Arlo": "Ruth",
|
||||
"Yara": "Salli"
|
||||
};
|
||||
|
||||
const { text, voiceId: frontendVoiceId } = req.body;
|
||||
|
||||
if (!text || !frontendVoiceId) {
|
||||
return res.status(400).json({ error: 'Text and voiceId are required' });
|
||||
}
|
||||
|
||||
const pollyVoiceId = voiceIdMap[frontendVoiceId];
|
||||
if (!pollyVoiceId) {
|
||||
return res.status(400).json({ error: 'Invalid voiceId provided' });
|
||||
}
|
||||
|
||||
const params = {
|
||||
Text: text,
|
||||
OutputFormat: 'mp3',
|
||||
Engine: 'neural',
|
||||
VoiceId: pollyVoiceId,
|
||||
};
|
||||
|
||||
try {
|
||||
function generateTimestampWithRandomDigits() {
|
||||
const now = new Date();
|
||||
const formattedDate = now.toISOString().replace('T', '_').replace(/\..+/, '').replace(/:/g, '-');
|
||||
const randomDigits = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
|
||||
return `${formattedDate}_${randomDigits}`;
|
||||
}
|
||||
|
||||
const folder = generateTimestampWithRandomDigits();
|
||||
const folderName = `audio_files/${folder}`;
|
||||
|
||||
const data = await polly.synthesizeSpeech(params).promise();
|
||||
const audioBuffer = data.AudioStream;
|
||||
|
||||
const textBuffer = Buffer.from(text, 'utf-8');
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file1', audioBuffer, 'speech.mp3');
|
||||
formData.append('file2', textBuffer, 'text.txt');
|
||||
// formData.append('folder', folderName); // Send folder name
|
||||
formData.append('bucket', 'polly-bs'); // Adjust bucket
|
||||
|
||||
const response = await axios.post(
|
||||
'https://preschool-curriculum.in/api/one/v1/file/upload',
|
||||
formData,
|
||||
{
|
||||
headers: {
|
||||
// 'Authorization': `Bearer ${process.env.BEARER_TOKEN}`,
|
||||
...formData.getHeaders() // Ensure FormData headers are included
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
res.json({
|
||||
message: 'Speech generated and saved successfully',
|
||||
fileUrls: response.data.urls,
|
||||
fileKeys: response.data.data
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error generating speech or uploading files:', error);
|
||||
res.status(500).json({ error: 'Error generating speech or uploading files' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = aiTextToSpeech;
|
||||
35
src/routes/api/generateQuestions copy.js
Normal file
35
src/routes/api/generateQuestions copy.js
Normal file
@@ -0,0 +1,35 @@
|
||||
const mysql = require("mysql2");
|
||||
|
||||
const generateQuestions = (req, res) => {
|
||||
const connection = mysql.createConnection({
|
||||
host: process.env.MARIA_HOST,
|
||||
user: process.env.MARIA_USER,
|
||||
password: process.env.MARIA_PASS,
|
||||
database: process.env.MARIA_DBNM
|
||||
});
|
||||
|
||||
connection.connect((err) => {
|
||||
if (err) {
|
||||
console.error('Error connecting to the database:', err);
|
||||
return;
|
||||
}
|
||||
console.log('Connected to the MariaDB database.');
|
||||
});
|
||||
|
||||
const { questions } = req.body;
|
||||
res.send( questions );
|
||||
questions.forEach(question => {
|
||||
const { questionText, options, correctAnswer } = question;
|
||||
const sql = 'INSERT INTO quiz_questions (questionText, option1, option2, option3, option4, correctAnswer) VALUES (?, ?, ?, ?, ?, ?)';
|
||||
db.query(sql, [questionText, options[0], options[1], options[2], options[3], correctAnswer], (err, result) => {
|
||||
if (err) {
|
||||
console.error('Error inserting question:', err);
|
||||
res.status(500).send('Error inserting question');
|
||||
return;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
res.status(200).send('Questions added successfully');
|
||||
}
|
||||
module.exports = generateQuestions;
|
||||
@@ -1,35 +1,48 @@
|
||||
const mysql = require("mysql2");
|
||||
var MongoClient = require('mongodb').MongoClient;
|
||||
// const AWS = require('aws-sdk');
|
||||
|
||||
const generateQuestions = (req, res) => {
|
||||
const connection = mysql.createConnection({
|
||||
host: process.env.MARIA_HOST,
|
||||
user: process.env.MARIA_USER,
|
||||
password: process.env.MARIA_PASS,
|
||||
database: process.env.MARIA_DBNM
|
||||
});
|
||||
const saveGameScore = (req, res) => {
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url, { useUnifiedTopology: true });
|
||||
client.connect((err) => {
|
||||
if (err) {
|
||||
console.error('Failed to connect to the server', err);
|
||||
return;
|
||||
}
|
||||
// console.log('Connected successfully to server');
|
||||
const db = client.db(dbName);
|
||||
const collection = db.collection('questions');
|
||||
// const data = req.body;
|
||||
const { question, option1, option2, option3, option4, correctAnswer, moduleId } = req.body;
|
||||
const data = {
|
||||
question: question,
|
||||
option1: option1,
|
||||
option2: option2,
|
||||
option3: option3,
|
||||
option4: option4,
|
||||
correctAnswer: correctAnswer,
|
||||
moduleId: moduleId
|
||||
};
|
||||
|
||||
connection.connect((err) => {
|
||||
if (err) {
|
||||
console.error('Error connecting to the database:', err);
|
||||
return;
|
||||
}
|
||||
console.log('Connected to the MariaDB database.');
|
||||
});
|
||||
|
||||
const { questions } = req.body;
|
||||
res.send( questions );
|
||||
questions.forEach(question => {
|
||||
const { questionText, options, correctAnswer } = question;
|
||||
const sql = 'INSERT INTO quiz_questions (questionText, option1, option2, option3, option4, correctAnswer) VALUES (?, ?, ?, ?, ?, ?)';
|
||||
db.query(sql, [questionText, options[0], options[1], options[2], options[3], correctAnswer], (err, result) => {
|
||||
collection.insertOne(data, (err, result) => {
|
||||
if (err) {
|
||||
console.error('Error inserting question:', err);
|
||||
res.status(500).send('Error inserting question');
|
||||
return;
|
||||
console.error('Failed to insert document', err);
|
||||
} else {
|
||||
// console.log('Document inserted with _id: ', result.insertedId);
|
||||
}
|
||||
client.close((err) => {
|
||||
if (err) {
|
||||
console.error('Failed to close connection', err);
|
||||
} else {
|
||||
console.log('Connection closed');
|
||||
|
||||
res.send(result.insertedId);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
res.status(200).send('Questions added successfully');
|
||||
}
|
||||
module.exports = generateQuestions;
|
||||
};
|
||||
|
||||
module.exports = saveGameScore;
|
||||
|
||||
36
src/routes/api/getGalleryImage.js
Normal file
36
src/routes/api/getGalleryImage.js
Normal file
@@ -0,0 +1,36 @@
|
||||
const GalleryImage = require('../../models/getGalleyImage');
|
||||
|
||||
const getGalleryImage = async (req, res) => {
|
||||
try {
|
||||
// Extract query parameters for filtering (if provided)
|
||||
const { gameName, childId, gameID} = req.query;
|
||||
|
||||
// Build a filter object based on the query parameters
|
||||
const filter = {};
|
||||
|
||||
if (gameName) {
|
||||
filter.gameName = gameName;
|
||||
}
|
||||
|
||||
if (childId) {
|
||||
filter.childId = childId;
|
||||
}
|
||||
if (gameID) {
|
||||
filter.gameID = gameID;
|
||||
}
|
||||
|
||||
// Fetch gallery images with filters and selected fields
|
||||
const galleryImages = await GalleryImage.find(filter).select('gameName childId gameID screenshotUrl'); // Select only these fields
|
||||
|
||||
if (!galleryImages.length) {
|
||||
return res.status(404).json({ message: 'No images found' });
|
||||
}
|
||||
|
||||
return res.status(200).json(galleryImages); // Return the filtered gallery images with selected fields
|
||||
} catch (error) {
|
||||
console.error('Error fetching images:', error.message);
|
||||
return res.status(500).json({ error: 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = getGalleryImage;
|
||||
@@ -1,32 +1,56 @@
|
||||
const mysql = require("mysql2");
|
||||
const getGameScore = (req, res) => {
|
||||
const pool = mysql.createPool({
|
||||
host: process.env.MARIA_HOST,
|
||||
user: process.env.MARIA_USER,
|
||||
password: process.env.MARIA_PASS,
|
||||
database: 'beanstalk_game',
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
queueLimit: 0
|
||||
});
|
||||
const promisePool = pool.promise();
|
||||
const { userId, gameName, gameID } = req.body;
|
||||
const { MongoClient } = require('mongodb');
|
||||
|
||||
const query = 'SELECT score, gameTime FROM gameData WHERE userId = ? AND gameName = ? AND gameID = ?';
|
||||
async function main() {
|
||||
const url = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
const client = new MongoClient(url, { useNewUrlParser: true, useUnifiedTopology: true });
|
||||
|
||||
pool.query(query, [userId, gameName, gameID], (error, results) => {
|
||||
if (error) {
|
||||
return res.status(500).json({ message: 'Database query failed', error });
|
||||
}
|
||||
try {
|
||||
// Connect to the MongoDB client
|
||||
await client.connect();
|
||||
|
||||
if (results.length > 0) {
|
||||
const game = results[0];
|
||||
res.json({ score: game.score, gameTime: game.gameTime });
|
||||
} else {
|
||||
res.status(404).json({ message: 'Game data not found' });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = getGameScore;
|
||||
// Select the database and collection
|
||||
const database = client.db(dbName); // Replace with your database name
|
||||
const collection = database.collection('gameData'); // Replace with your collection name
|
||||
|
||||
// Find a single document
|
||||
// const user = await collection.findOne({ childId: 'dsfdfgffgfgeg' });
|
||||
|
||||
const { childId, gameName, gameID } = req.body;
|
||||
const gameData = await collection.findOne(
|
||||
{
|
||||
childId: childId,
|
||||
gameName: gameName,
|
||||
gameID: gameID
|
||||
},{
|
||||
sort: {_id: -1}
|
||||
}
|
||||
);
|
||||
// console.log('gameData', gameData);
|
||||
if (gameData) {
|
||||
res.json({gameData});
|
||||
} else {
|
||||
res.status(404).json({ message: 'Game data not found' });
|
||||
}
|
||||
|
||||
// Output the result
|
||||
// if (user) {
|
||||
// console.log('User found:', user);
|
||||
// } else {
|
||||
// console.log('No user found with the username "john_doe"');
|
||||
// }
|
||||
} catch (error) {
|
||||
console.error('Error connecting to MongoDB or performing query:', error);
|
||||
} finally {
|
||||
// Close the connection
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
};
|
||||
|
||||
module.exports = getGameScore;
|
||||
|
||||
79
src/routes/api/saveGalleryImage.js
Normal file
79
src/routes/api/saveGalleryImage.js
Normal file
@@ -0,0 +1,79 @@
|
||||
const GalleryImage = require('../../models/imageGallery');
|
||||
const axios = require('axios');
|
||||
const FormData = require('form-data'); // Import form-data for Node.js
|
||||
|
||||
const saveGalleryImage = async (req, res) => {
|
||||
try {
|
||||
const { childId, gameName, gameID, screenShot } = req.body;
|
||||
|
||||
// Validate base64 format
|
||||
const isValidBase64 = validateBase64(screenShot);
|
||||
if (!isValidBase64) {
|
||||
return res.status(400).json({ error: 'Invalid base64 image data' });
|
||||
}
|
||||
|
||||
// Extract image details
|
||||
const imageData = extractImageDataFromBase64(screenShot);
|
||||
const contentType = imageData.contentType || 'image/jpeg'; // Default to JPEG
|
||||
|
||||
// Convert base64 to buffer
|
||||
const buffer = Buffer.from(screenShot.replace(/^data:image\/(png|jpg|jpeg);base64,/, ''), 'base64');
|
||||
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
formData.append('file1', buffer, { filename: 'screenshot.jpg', contentType });
|
||||
formData.append('folder', 'gameGallery');
|
||||
formData.append('bucket', 'polly-bs');
|
||||
|
||||
// Upload image to external API using axios
|
||||
const uploadResponse = await axios.post(
|
||||
'https://preschool-curriculum.in/api/one/v1/file/upload',
|
||||
formData,
|
||||
{
|
||||
headers: {
|
||||
...formData.getHeaders(), // Add form-data headers like Content-Type boundary
|
||||
// Add any necessary authentication headers if required
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (uploadResponse.status !== 200) {
|
||||
throw new Error('Image upload failed: ' + uploadResponse.statusText);
|
||||
}
|
||||
|
||||
|
||||
// Extract and store the uploaded image URL from the response
|
||||
const screenshotUrl = uploadResponse.data.urls[0];
|
||||
|
||||
// Create and save gallery image data
|
||||
const galleryImageData = new GalleryImage({
|
||||
childId,
|
||||
gameName,
|
||||
gameID,
|
||||
screenshotUrl,
|
||||
message: 'Image received',
|
||||
});
|
||||
await galleryImageData.save();
|
||||
|
||||
return res.status(200).json(galleryImageData);
|
||||
} catch (error) {
|
||||
console.error('Error:', error.message);
|
||||
return res.status(500).json({ error: 'Something went wrong' });
|
||||
}
|
||||
};
|
||||
|
||||
// Validate base64 image
|
||||
function validateBase64(base64String) {
|
||||
const regex = /^data:image\/(png|jpg|jpeg);base64,/;
|
||||
return regex.test(base64String);
|
||||
}
|
||||
|
||||
// Extract image data (like content type) from base64 string
|
||||
function extractImageDataFromBase64(base64String) {
|
||||
const matches = base64String.match(/^data:image\/(png|jpg|jpeg);base64,/);
|
||||
return {
|
||||
contentType: matches ? `image/${matches[1]}` : 'image/jpeg',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = saveGalleryImage;
|
||||
@@ -14,13 +14,14 @@ const saveGameScore = (req, res) => {
|
||||
const db = client.db(dbName);
|
||||
const collection = db.collection('gameData');
|
||||
// const data = req.body;
|
||||
const { userId, gameName, gameID, gameTime, score, screenShot } = req.body;
|
||||
const { userId, gameName, gameID, gameTime, score,gameStar, screenShot } = req.body;
|
||||
const data = {
|
||||
userId: userId,
|
||||
gameName: gameName,
|
||||
gameID: gameID,
|
||||
gameTime: gameTime,
|
||||
score: score
|
||||
score: score,
|
||||
gameStar:gameStar
|
||||
};
|
||||
|
||||
collection.insertOne(data, (err, result) => {
|
||||
|
||||
70
src/routes/api/saveGameScore2.js
Normal file
70
src/routes/api/saveGameScore2.js
Normal file
@@ -0,0 +1,70 @@
|
||||
const AWS = require("aws-sdk");
|
||||
const mongoose = require("mongoose");
|
||||
const Game = require("../../models/gameModel");
|
||||
|
||||
const s3 = new AWS.S3({
|
||||
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
||||
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
region: process.env.AWS_REGION,
|
||||
});
|
||||
|
||||
// MongoDB Connection
|
||||
const mongoURI = process.env.MONGODB_URL;
|
||||
const dbName = process.env.MONGO_DB_NAME;
|
||||
|
||||
mongoose.connect(mongoURI, {
|
||||
dbName: dbName,
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
})
|
||||
.then(() =>
|
||||
console.log("Connected to MongoDB"))
|
||||
.catch((err) => console.error("MongoDB connection error:", err));
|
||||
|
||||
const saveGameScore2 = async (req, res) => {
|
||||
const { childId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
|
||||
|
||||
try {
|
||||
if (!gameName || !childId || !gameID) {
|
||||
return res.status(400).json({ error: "Missing required fields" });
|
||||
}
|
||||
|
||||
const newGame = new Game({
|
||||
gameName,
|
||||
childId,
|
||||
gameID,
|
||||
gameTime,
|
||||
score,
|
||||
gameStar,
|
||||
});
|
||||
|
||||
// Save to MongoDB
|
||||
const result = await newGame.save();
|
||||
// Upload screenshot to S3 if provided
|
||||
if (screenShot) {
|
||||
let base64Image = screenShot.split(";base64,").pop();
|
||||
const buffer = Buffer.from(base64Image, "base64");
|
||||
|
||||
const uploadParams = {
|
||||
Bucket: process.env.S3_BUCKET_NAME,
|
||||
Key: `images/${result._id}.png`,
|
||||
Body: buffer,
|
||||
ContentType: "image/png",
|
||||
};
|
||||
|
||||
const s3Response = await s3.upload(uploadParams).promise();
|
||||
newGame.screenshotUrl = s3Response.Location;
|
||||
await newGame.save();
|
||||
}
|
||||
|
||||
res.status(200).json({
|
||||
message: "Game data saved successfully",
|
||||
data: newGame,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error:", error);
|
||||
res.status(500).json({ error: "Internal Server Error" });
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = saveGameScore2;
|
||||
@@ -23,6 +23,18 @@ const getGameScore = require("../api/getGameScore");
|
||||
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
|
||||
const generateQuestions = require("../api/generateQuestions");
|
||||
const saveGameScore = require("../api/saveGameScore");
|
||||
const saveGameScore2 = require("../api/saveGameScore2");
|
||||
const aiFeedbackOnReport = require("../api/aiFeedbackOnReport");
|
||||
const aiFeedbackActionParent = require("../api/aiFeedbackActionParent");
|
||||
const aiFollowupQuestion = require("../api/aiFollowupQuestion");
|
||||
const aiMarkDrawing = require("../api/aiMarkDrawing");
|
||||
const aiFeedbackOnReportWithFollowup = require("../api/aiFeedbackOnReportWithFollowup");
|
||||
const aiTextToSpeech = require("../api/aiTextToSpeech");
|
||||
const aiEvaluateImageToStar = require("../api/aiEvaluateImageToStar");
|
||||
// const getGameInfo = require("../api/getGameInfo");
|
||||
const saveGalleryImage = require("../api/saveGalleryImage");
|
||||
const getGalleryImage = require("../api/getGalleryImage");
|
||||
// const aiTest = require("../api/aiTest");
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
@@ -142,6 +154,66 @@ router.get("/ping", (req, res) => {
|
||||
saveGameScore(req, res);
|
||||
});
|
||||
|
||||
// For Quiz Result After Submit Quiz
|
||||
router.post("/saveGameScore2", (req, res) => {
|
||||
saveGameScore2(req, res);
|
||||
});
|
||||
|
||||
|
||||
// AI feedback for teacher on children's report card
|
||||
router.post("/aiFeedbackOnReport", (req, res) => {
|
||||
aiFeedbackOnReport(req, res);
|
||||
});
|
||||
// AI feedback for teacher on children's report card
|
||||
router.post("/aiFeedbackOnReportWithFollowup", (req, res) => {
|
||||
aiFeedbackOnReportWithFollowup(req, res);
|
||||
});
|
||||
|
||||
// AI top ten action items for a parent of this child.
|
||||
router.post("/aiFeedbackActionParent", (req, res) => {
|
||||
aiFeedbackActionParent(req, res);
|
||||
});
|
||||
|
||||
// AI to respond on initial and followup questions.
|
||||
router.post("/aiFollowupQuestion", (req, res) => {
|
||||
aiFollowupQuestion(req, res);
|
||||
});
|
||||
|
||||
// AI to provide star for drawing.
|
||||
router.post("/aiMarkDrawing", (req, res) => {
|
||||
aiMarkDrawing(req, res);
|
||||
});
|
||||
|
||||
// AI to provide star for drawing.
|
||||
router.post("/aiTextToSpeech", (req, res) => {
|
||||
aiTextToSpeech(req, res);
|
||||
});
|
||||
|
||||
// AI to provide star for drawing.
|
||||
router.post("/aiEvaluateImageToStar", (req, res) => {
|
||||
aiEvaluateImageToStar(req, res);
|
||||
});
|
||||
|
||||
// getGameInfo.
|
||||
// router.get("/getGameInfo", (req, res) => {
|
||||
// getGameInfo(req, res);
|
||||
// });
|
||||
|
||||
// Save Drawing Game Gallery Image
|
||||
router.post("/saveGalleryImage", (req, res) => {
|
||||
saveGalleryImage(req, res);
|
||||
});
|
||||
|
||||
// Get Drawing Game Gallery Image
|
||||
router.get("/getGalleryImage", (req, res) => {
|
||||
getGalleryImage(req, res);
|
||||
});
|
||||
|
||||
// Get Drawing Game Gallery Image
|
||||
// router.post("/aiTest", (req, res) => {
|
||||
// aiTest(req, res);
|
||||
// });
|
||||
|
||||
|
||||
module.exports = router;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user