Compare commits

...

107 Commits
b2 ... master

Author SHA1 Message Date
Kar 3421a198f3 curl sample 2025-08-14 22:09:10 +05:30
Kar 75656c8f17 Update src/routes/api/aiFollowupQuestion.js 2025-04-28 16:46:41 +00:00
Suvodip 0d4323df9e s11 2025-03-05 18:02:21 +05:30
Suvodip 5da7710af1 add get game thumbnail 2025-03-05 17:44:39 +05:30
Subhodip Ghosh 76e503c4a9 Merge pull request 'add system in aiTest' (#26) from branch2 into master
Reviewed-on: #26
2025-02-22 06:01:57 +00:00
Suvodip 59bcdcc3e8 add system in aiTest 2025-02-22 11:31:36 +05:30
Kar 91b73215be node v 2025-02-14 01:37:23 +05:30
Kar 40eda82022 node v 2025-02-14 01:33:59 +05:30
Kar 2150d52b9d node v 2025-02-14 01:27:56 +05:30
Kar fb21f179e6 node v 2025-02-14 01:26:43 +05:30
Kar 5777ee5131 node v 2025-02-14 01:23:16 +05:30
Kar f96a50b7f4 node v 2025-02-14 01:05:49 +05:30
Kar 3f944eb49e nodeVersion 2025-02-14 00:51:44 +05:30
Subhodip Ghosh ab74529965 Merge pull request 'Update src/routes/v1/api.route.js' (#25) from suvo-patch-1 into master
Reviewed-on: #25
2025-02-11 11:21:10 +00:00
Subhodip Ghosh 73b3d67508 Update src/routes/v1/api.route.js 2025-02-11 11:21:01 +00:00
Kar 1706a910fd clean 2025-02-06 17:46:06 +05:30
Subhodip Ghosh f922617e57 Merge pull request 'add last attempt function' (#24) from tmp into master
Reviewed-on: #24
2025-02-04 13:58:26 +00:00
Suvodip d18f173ef6 add last attempt function 2025-02-04 19:28:07 +05:30
Subhodip Ghosh b7bc87908e Merge pull request 's44' (#23) from tmp into master
Reviewed-on: #23
2025-02-04 13:42:25 +00:00
Suvodip 10a797d450 s44 2025-02-04 19:12:00 +05:30
Kar 23e5b2e329 Merge pull request 's33' (#22) from tmp into master
Reviewed-on: #22
2025-02-04 12:58:47 +00:00
Suvodip 3a64479fd4 s33 2025-02-04 18:25:20 +05:30
Subhodip Ghosh 571a079622 Merge pull request 'tmp' (#21) from tmp into master
Reviewed-on: #21
2025-02-04 11:17:58 +00:00
Suvodip d4d2a32a71 s33 2025-02-04 16:47:16 +05:30
Subhodip Ghosh 2d71ff105d Add src/routes/api/aiEvaluateImageToStar.js 2025-02-04 11:16:33 +00:00
Suvodip e8c29025aa s22 2025-02-04 16:41:40 +05:30
Subhodip Ghosh 6b1cad684d Delete src/routes/api/aiEvaluateImageToStar.js 2025-02-04 11:11:02 +00:00
Suvodip b909a85225 ai evaluate userid change to childid 2025-02-04 16:36:21 +05:30
Subhodip Ghosh d2db8ead08 Merge pull request 's2' (#16) from tmp into master
Reviewed-on: #16
2025-02-04 10:45:37 +00:00
Suvodip b69bc6200f s2 2025-02-04 16:14:54 +05:30
Subhodip Ghosh 1cf66178ae Merge pull request 'all userId replace to childId' (#15) from tmp into master
Reviewed-on: #15
2025-02-04 10:42:32 +00:00
Suvodip 6d03408495 all userId replace to childId 2025-02-04 16:11:06 +05:30
Subhodip Ghosh 34e71a7dcf Merge pull request 's3' (#13) from tmp into master
Reviewed-on: #13
2025-02-03 11:51:38 +00:00
Suvodip 552cfbe574 s3 2025-02-03 17:21:05 +05:30
Subhodip Ghosh abcfc2dbca Merge pull request 'replace userId to childId' (#12) from tmp into master
Reviewed-on: #12
2025-02-03 10:51:03 +00:00
Suvodip ed657df69a replace userId to childId 2025-02-03 16:20:05 +05:30
Subhodip Ghosh b77e3692d2 Merge pull request 'tmp' (#11) from tmp into master
Reviewed-on: #11
2025-01-31 07:51:51 +00:00
Suvodip 3b75e915e3 s4 2025-01-31 13:21:26 +05:30
Suvodip 02cc60f824 s3 2025-01-31 13:20:02 +05:30
Suvodip c2ee394195 s2 2025-01-31 13:16:19 +05:30
Kar 7db4089223 working1 2025-01-29 22:27:10 +05:30
Kar e589d66e36 list-models 2025-01-29 21:03:30 +05:30
Kar cfa16dbdc7 list-models 2025-01-29 21:01:05 +05:30
Kar fe72636dd7 node 2025-01-29 19:16:10 +05:30
Kar f5d6c3cedc aiTest 2025-01-29 19:13:55 +05:30
Kar 136286599f multi ai provider added 2025-01-29 18:48:49 +05:30
Kar 40c650f7d4 log 2025-01-29 18:26:26 +05:30
Kar b44c72e690 3 to 10 2025-01-26 08:49:17 +00:00
Subhodip Ghosh 4acaac5b84 Merge pull request 's4' (#8) from tmp2 into master
Reviewed-on: #8
2025-01-23 14:45:24 +00:00
Suvodip 8f2f36bce0 s4 2025-01-23 20:14:58 +05:30
Subhodip Ghosh 22c2affa00 Merge pull request 's3' (#7) from tmp2 into master
Reviewed-on: #7
2025-01-23 14:14:22 +00:00
Suvodip d38702698a s3 2025-01-23 19:43:45 +05:30
Suvodip 7dda27e86e s2 2025-01-23 19:38:46 +05:30
Kar 0296de1703 getGameInfo3 2025-01-19 15:17:11 +00:00
Kar 9384390811 getGameInfo2 2025-01-18 19:08:29 +00:00
Kar 92974caef1 table 2025-01-18 14:58:45 +00:00
Kar 956d0a72bd getGameInfoU 2025-01-17 23:45:05 +05:30
Kar c67378c3f4 getGameInfoU 2025-01-16 08:32:03 +00:00
Kar e34abbb017 getGameInfo 2025-01-16 08:09:57 +00:00
Kar a4e9e9cfb3 getGameInfo 2025-01-16 08:08:51 +00:00
Kar 4d9a785812 correction 2025-01-06 19:22:28 +05:30
Kar f68b1e78e0 limit resp 2025-01-06 17:29:45 +05:30
Kar 87afa13a42 reply cap 2025-01-01 21:25:10 +05:30
Suvodip 5152ca2e23 gallery 2 api 2024-12-23 19:17:45 +05:30
Kar at l5 4d251402af aiEvaluateImageToStar FormData 2024-12-21 16:43:51 +05:30
Kar at l5 d96461aedb aiEvaluateImageToStar 2024-12-21 15:55:53 +05:30
Kar at l5 b7b168b2d0 aiEvaluateImageToStar 2024-12-21 15:26:13 +05:30
Kar at l5 e520169fb9 aiEvaluateImageToStar 2024-12-19 13:55:01 +05:30
Kar ddc864a25d aiEvaluateImageToScore 2024-11-27 21:03:08 +05:30
Kar 9fa326666f aiEvaluateImageToScore 2024-11-27 21:02:50 +05:30
Kar abcb44ace7 saveGameScore2 2024-11-22 17:11:51 +05:30
Kar 8ecbe43e6e saveGameScore2 2024-11-22 16:57:21 +05:30
Kar 583f85a7e8 saveGameScore2 2024-11-22 16:49:27 +05:30
Kar 2dec203ad0 saveGameScore2 2024-11-22 16:49:03 +05:30
Kar 9a64b60454 aiTextToSpeech 2024-11-22 16:48:35 +05:30
Kar 2593bfc7d9 aiTextToSpeech 2024-11-22 14:10:16 +05:30
Kar 3a73d0a9be aiFeedbackOnReport 2024-11-21 21:06:34 +05:30
Kar cad9154900 gpt-4o-mini 2024-11-21 15:51:44 +05:30
Kar c934f45726 aiTextToSpeech working without folder and s3 bucket manipulation 2024-11-18 19:14:04 +05:30
Kar f1198c21de aiTextToSpeech- bucket and folder manipulation not working 2024-11-18 19:11:37 +05:30
Kar 8eb4da619a Authorization fileupload 2024-11-18 18:49:51 +05:30
Kar b5d40f21a6 aiTextToSpeech formData 2024-11-18 18:46:38 +05:30
Kar 411766987c aiTextToSpeech file upload 2024-11-18 18:42:46 +05:30
Kar 51c520108b Engine-neural 2024-11-18 16:35:11 +05:30
Kar 7fcc27ada1 gpt-3.5-turbo-16k 2024-11-15 12:02:00 +05:30
Kar 02ec79b262 only the two most recent messages for context 2024-11-11 12:27:23 +05:30
Kar 5e23f73645 s3-aiTextToSpeech 2024-11-11 12:23:07 +05:30
Kar 2cbf1ebbaa total_tokens 2024-11-08 19:14:25 +05:30
Kar 5775c45d8c Engine-neural 2024-11-06 18:39:02 +05:30
Kar 0a78f89fa9 aiTextToSpeech 2024-11-05 20:46:04 +05:30
Kar 101e1a2749 aiFeedbackOnReportWithFollowup 2024-10-29 15:53:13 +05:30
Kar 7252cfcce4 t 2024-10-28 22:09:46 +05:30
Kar 41c2ceb675 node-fetch 2024-10-14 10:17:11 +05:30
Kar da33f2ed43 aiFollowupQuestion 2024-10-14 09:52:32 +05:30
Kar 060e6b0f1a gameStar 2024-10-05 18:56:19 +05:30
Kar 58805dac6f aiFeedbackOnReport 2024-10-04 22:29:54 +05:30
Kar f490aac87e aiFeedbackOnReport 2024-09-20 15:28:37 +05:30
Kar 67bc3e9995 aiFeedbackOnReport working 2024-09-20 15:19:25 +05:30
Kar a9a0cd5ca3 aiFeedbackOnReport working 2024-09-20 14:59:58 +05:30
Kar 1244f5f06b gpt-4o-mini 2024-09-20 04:02:39 +05:30
Kar c74a6fd67d aiFeedbackOnReport 2024-09-20 03:51:26 +05:30
Suvodip 10b7fc5ee2 s1 2024-08-27 21:30:12 +05:30
dev2 siliconpin 879a792907 t 2024-08-13 11:56:40 +00:00
dev2 siliconpin 554b4e8946 s1 2024-08-13 11:45:49 +00:00
dev2 siliconpin 0381f74f06 t 2024-08-12 19:26:02 +00:00
dev2 siliconpin 8b420fb34f t 2024-08-12 19:24:20 +00:00
dev2 siliconpin f12e2d9e0a t 2024-08-12 18:08:43 +00:00
35 changed files with 18238 additions and 180 deletions

View File

@ -1,3 +1,6 @@
node_modules node_modules
.git .git
.gitignore .gitignore
**/docker-compose*
**/compose.y*ml
**/Dockerfile*

2
.gitignore vendored
View File

@ -3,7 +3,7 @@ node_modules
# yarn error logs # yarn error logs
yarn-error.log yarn-error.log
yarn.lock
# Environment varibales # Environment varibales
.env* .env*
!.env*.example !.env*.example

View File

@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn install

View File

@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
git status

View File

@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged

View File

@ -1,15 +1,26 @@
FROM node:alpine # Use an official Node.js runtime as a parent image
FROM node:20-alpine
RUN mkdir -p /usr/src/node-app && chown -R node:node /usr/src/node-app # Set the working directory inside the container
WORKDIR /app
WORKDIR /usr/src/node-app # Copy package files and set ownership
COPY --chown=node:node package*.json ./
COPY package.json yarn.lock ./ # Install dependencies
RUN npm install --omit=dev
USER node
RUN yarn install --pure-lockfile
# Copy the rest of the app's source code with correct ownership
COPY --chown=node:node . . COPY --chown=node:node . .
# Use a non-root user for better security
USER node
# Expose the application port
EXPOSE 3000 EXPOSE 3000
# Set environment variables (optional)
ENV NODE_ENV=production
# Start the application
CMD ["npm", "run", "start"]

View File

@ -1,32 +1,31 @@
version: '3'
services: services:
node-app: iimtt_api:
build: . build: .
image: node-app image: iimtt_api
environment: # environment:
- MONGODB_URL=mongodb://mongodb:27017/node-boilerplate # - MONGODB_URL=mongodb://mongodb:27017/node-boilerplate
ports: ports:
- '3000:3000' - '5174:5174'
depends_on: # depends_on:
- mongodb # - mongodb
volumes: volumes:
- .:/usr/src/node-app - .:/usr/src/iimtt_api
networks: # networks:
- node-network # - host
# - node-network
mongodb: # mongodb:
image: mongo:4.2.1-bionic # image: mongo:4.2.1-bionic
ports: # ports:
- '27017:27017' # - '27017:27017'
volumes: # volumes:
- dbdata:/data/db # - dbdata:/data/db
networks: # networks:
- node-network # - node-network
volumes: # volumes:
dbdata: # dbdata:
networks: # networks:
node-network: # node-network:
driver: bridge # driver: bridge

22
game_links.txt Normal file
View File

@ -0,0 +1,22 @@
/guided-tracing/A/
game_drawing /drawing/?id=
game_drawing_v2 /drawing/v2/?id=
game_drawing_v3 /drawing/v3/?id=
drawing_phonics /drawing/drawing_phonics/?id=
game_tick_variant1 /tick/v1/?id=
game_tick_variant2 /tick/v2/?id=
game_tick_varient3 /tick/v3/?id=
game_cross_varient1 /cross/v1/?id=
game_cross_varient2 /cross/v2/?id=
game_cross_varient3 /cross/v3/?id=
game_drag /drag/?id=
game_drag_v2 /drag/v2/?id=
game_drag_v3 /drag/v3/?id= // we do't use this version
game_drag_v4 /drag/v4/?id=
game_tick_v3_phonics /tick/tick_phonics_v1/?id=
tick_phonics_option_6 /tick/tick_phonics_v2/?id=
tick_phonics_option_9 /tick/tick_phonics_v3/?id=
drag_drop_phonics /drag/dragdrop_phonics/?id=
drag_phonics /drag/match_phonics/?id=
cross_phonics_option_9 /cross/cross_phonics_v2/?id=

BIN
output.png Normal file

Binary file not shown.

16563
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "iimttapi", "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", "description": "Create a Node.js app for building production-ready RESTful APIs using Express, by running one command",
"bin": "bin/createNodejsApp.js", "bin": "bin/createNodejsApp.js",
"main": "src/index.js", "main": "src/index.js",
@ -9,7 +9,8 @@
"node": ">=12.0.0" "node": ">=12.0.0"
}, },
"scripts": { "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", "dev": "cross-env NODE_ENV=development nodemon src/index.js",
"test": "jest -i --colors --verbose --detectOpenHandles", "test": "jest -i --colors --verbose --detectOpenHandles",
"test:watch": "jest -i --watchAll", "test:watch": "jest -i --watchAll",
@ -21,8 +22,7 @@
"prettier:fix": "prettier --write **/*.js", "prettier:fix": "prettier --write **/*.js",
"docker:prod": "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up", "docker:prod": "docker-compose -f docker-compose.yml -f docker-compose.prod.yml up",
"docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up", "docker:dev": "docker-compose -f docker-compose.yml -f docker-compose.dev.yml up",
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up", "docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up"
"prepare": "husky install"
}, },
"keywords": [ "keywords": [
"node", "node",
@ -48,6 +48,7 @@
], ],
"dependencies": { "dependencies": {
"aws-sdk": "^2.1669.0", "aws-sdk": "^2.1669.0",
"axios": "^1.7.7",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"compression": "^1.7.4", "compression": "^1.7.4",
@ -57,15 +58,21 @@
"express": "^4.17.1", "express": "^4.17.1",
"express-mongo-sanitize": "^2.0.0", "express-mongo-sanitize": "^2.0.0",
"express-rate-limit": "^5.0.0", "express-rate-limit": "^5.0.0",
"form-data": "^4.0.1",
"formdata-node": "^6.0.3",
"helmet": "^4.1.0", "helmet": "^4.1.0",
"http-status": "^1.4.0", "http-status": "^1.4.0",
"install": "^0.13.0",
"joi": "^17.3.0", "joi": "^17.3.0",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"mariadb": "^3.4.0",
"moment": "^2.24.0", "moment": "^2.24.0",
"mongoose": "^5.7.7", "mongoose": "^8.7.1",
"morgan": "^1.9.1", "morgan": "^1.9.1",
"mysql2": "^3.11.0", "mysql2": "^3.11.0",
"node-fetch": "^3.3.2",
"nodemailer": "^6.3.1", "nodemailer": "^6.3.1",
"npm": "^11.0.0",
"passport": "^0.4.0", "passport": "^0.4.0",
"passport-jwt": "^4.0.0", "passport-jwt": "^4.0.0",
"pm2": "^5.1.0", "pm2": "^5.1.0",
@ -85,7 +92,6 @@
"eslint-plugin-prettier": "^3.1.1", "eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-security": "^1.4.0", "eslint-plugin-security": "^1.4.0",
"faker": "^5.1.0", "faker": "^5.1.0",
"husky": "7.0.4",
"jest": "^26.0.1", "jest": "^26.0.1",
"lint-staged": "^11.0.0", "lint-staged": "^11.0.0",
"node-mocks-http": "^1.8.0", "node-mocks-http": "^1.8.0",

View File

@ -38,7 +38,7 @@ module.exports = {
mongoose: { mongoose: {
url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''), url: envVars.MONGODB_URL + (envVars.NODE_ENV === 'test' ? '-test' : ''),
options: { options: {
useCreateIndex: true, // useCreateIndex: true,
useNewUrlParser: true, useNewUrlParser: true,
useUnifiedTopology: true, useUnifiedTopology: true,
}, },

12
src/models/gameModel.js Normal file
View 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);

View 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;

View 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);

View 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 };

View 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;

View 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;

View 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;

View File

@ -0,0 +1,34 @@
const aiFeedbackOnReport = async (req, res) => {
// const fetch = require('node-fetch');
const url = process.env.AI_API_ENDOINT;
const api_key = process.env.OPENAI_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;

View File

@ -0,0 +1,97 @@
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 = 600) {
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;
// return data.choices[0].message.content;
}
try {
const { prompt, sessionId, model = "gpt-4o-mini", max_tokens = 600 } = 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: JSON.stringify(req.body.score) + " - is the students report card. " + req.body.instruction },
],
};
// console.log(req.body.score[0])
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;

View File

@ -0,0 +1,123 @@
const aiFollowupQuestion = async (req, res) => {
// curl -X POST http://localhost:3000/your-endpoint-path \
// -H "Content-Type: application/json" \
// -d '{
// "prompt": "Why is the sky blue?",
// "sessionId": "",
// "model": "gpt-3.5-turbo-16k",
// "max_tokens": 200
// }'
// curl -X POST http://localhost:5174/api/aiFollowupQuestion \
// -H "Content-Type: application/json" \
// -d '{
// "prompt": "Why is the sky blue?",
// "sessionId": "",
// "model": "gpt-3.5-turbo-16k",
// "sessionId" : "8c641aca-582d-4ea7-8e56-4f94318efe74",
// "max_tokens": 200
// }'
// {
// "success": true,
// "data": "The sky looks blue because of how sunlight scatters in the air. Great question! Ask me more!",
// "total_tokens": 45,
// "sessionId": "2a3b3cc4-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
// }
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,
// messages: [
// { role: "system", content: "reply must not exceed 20 words" },
// { role: "user", content: messages }
// ],
max_tokens: max_tokens,
}),
});
const data = await response.json();
// console.log(process.env.OPENAI_KEY)
// console.log(data)
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:
'Reply to the questions asked by a kindergarten child, Sound excited to answer and encourage the child to ask more questions in 30 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;

View 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;

166
src/routes/api/aiTest.js Normal file
View File

@ -0,0 +1,166 @@
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');
const MAX_TOKENS = 200;
const PROVIDER_KEYS = JSON.parse(process.env.PROVIDER_KEY || '[]');
const PROVIDER_MODELS = {
openai: [ "gpt-4o", "gpt-4o-mini", "o1", "o1-mini", "gpt-3.5-turbo", "gpt-3.5-turbo-mini", "gpt-3.5-mini", "gpt-3.5-turbo-2", "gpt-3.5-2", "gpt-3.5-turbo-2-mini", "gpt-3.5-2-mini" ],
deepseek: [ "deepseek-chat", "deepseek-reasoner", "deepseek-qa", "deepseek-qa-mini" ],
// Add more providers and models as needed
};
async function fetchOpenAICompletion(messages, model, max_tokens = MAX_TOKENS) {
// console.log(messages)
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,
}),
});
return response.json();
}
async function fetchDeepSeekCompletion(messages, model) {
const response = await fetch('https://api.deepseek.com/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: model,
messages: messages,
stream: false,
}),
});
return response.json();
}
// Similar function for Gemini can be added here...
try {
const { prompt, sessionId, provider, model = "gpt-4o-mini", key, system } = req.body;
if (!key || !PROVIDER_KEYS.includes(key)) {
return res.status(403).json({
success: false,
error: 'Unauthorized: Invalid or missing key.',
});
}
if (provider && req.body['list-models']) {
if (PROVIDER_MODELS[provider]) {
return res.json({
success: true,
models: PROVIDER_MODELS[provider],
});
} else {
return res.status(400).json({
success: false,
error: 'Invalid provider specified.',
});
}
}
// Check if the request is for listing AI providers
if (req.body['list-ais']) {
return res.json({
success: true,
providers: ['openai', 'deepseek', 'gemini', 'manual'],
});
}
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: system },
{ 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 });
}
let aiResponse;
if(prompt.length > 3) {
switch (provider) {
case 'openai':
aiResponse = await fetchOpenAICompletion([{ role: 'user', content: prompt }], model);
// console.log(aiResponse)
break;
case 'deepseek':
aiResponse = await fetchDeepSeekCompletion([{ role: 'user', content: prompt }], model);
break;
// case 'gemini':
// aiResponse = await fetchGeminiCompletion(conversation.conversationHistory, model);
// break;
// Add more cases for other providers as needed
default:
return res.status(400).json({
success: false,
error: 'Invalid provider specified.',
});
}
}
conversation.conversationHistory.push({ role: 'assistant', content: aiResponse.choices ? aiResponse.choices[0].message.content : aiResponse.response });
await conversationsCollection.updateOne(
{ sessionId: conversation.sessionId },
{ $set: { conversationHistory: conversation.conversationHistory } }
);
res.json({
success: true,
data: aiResponse.choices ? aiResponse.choices[0].message.content : aiResponse.response,
total_tokens: aiResponse.usage ? aiResponse.usage.total_tokens : undefined,
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;

View File

@ -0,0 +1,91 @@
const axios = require('axios');
const AWS = require('aws-sdk');
const FormData = require('form-data');
const aiTextToSpeech = async (req, res) => {
// curl -X POST http://localhost:5174/api/aiTextToSpeech \
// -H "Content-Type: application/json" \
// -d '{
// "text": "Hello, this is a sample speech.",
// "voiceId": "Ava"
// }'
// {"message":"Speech generated and saved successfully","fileUrls":["https://polly-bs.s3.ap-south-1.amazonaws.com/file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=12dd2feaf73564d6c843b0dc975fdedb35c430d316f4f09fcdf41e247d1ea63c&X-Amz-SignedHeaders=host","https://polly-bs.s3.ap-south-1.amazonaws.com/file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAQ35B6OYR6T5MGH7Q%2F20250814%2Fap-south-1%2Fs3%2Faws4_request&X-Amz-Date=20250814T163252Z&X-Amz-Expires=86400&X-Amz-Signature=d96eb4fe7cabfab93ce0ffe8fc74a8e722a2064d904652d47ad361f2f3667ec7&X-Amz-SignedHeaders=host"],"fileKeys":{"file1":"file_MpNpWluxR7R70BA-dzju_U3C94bPmC-n-speech.mp3","file2":"file_SXmwHWwlcSBlI9LNoZ1PcLEdMD7D1PWO-text.txt"}}
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;

View 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;

View File

@ -1,35 +1,48 @@
const mysql = require("mysql2"); var MongoClient = require('mongodb').MongoClient;
// const AWS = require('aws-sdk');
const generateQuestions = (req, res) => { const saveGameScore = (req, res) => {
const connection = mysql.createConnection({ const url = process.env.MONGODB_URL;
host: process.env.MARIA_HOST, const dbName = process.env.MONGO_DB_NAME;
user: process.env.MARIA_USER, const client = new MongoClient(url, { useUnifiedTopology: true });
password: process.env.MARIA_PASS, client.connect((err) => {
database: process.env.MARIA_DBNM 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) => { collection.insertOne(data, (err, result) => {
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) { if (err) {
console.error('Error inserting question:', err); console.error('Failed to insert document', err);
res.status(500).send('Error inserting question'); } else {
return; // 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 = saveGameScore;
module.exports = generateQuestions;

View 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;

View File

@ -0,0 +1,147 @@
require("dotenv").config();
const express = require("express");
const mariadb = require("mariadb");
const router = express.Router();
// Create MariaDB connection pool
const pool = mariadb.createPool({
host: process.env.MARIA_HOST,
user: process.env.MARIA_USER,
password: process.env.MARIA_PASS,
database: process.env.MARIA_DBNM,
connectionLimit: 5
});
const getGameData = async (req, res) => {
let conn;
let items = 'ws2gamelink';
try {
const { wsname } = req.query;
if (!items || !wsname) {
return res.status(400).json({ error: "Missing items or wsname parameter" });
}
console.log("Fetching game data from table:", items);
conn = await pool.getConnection();
// Fetching the first dataset
const ws2gamelinkQuery = `SELECT * FROM \`${items}\` WHERE wsname = ?`;
const rows = await conn.query(ws2gamelinkQuery, [wsname]);
if (!rows.length) {
return res.status(404).json({ error: "No data found" });
}
let gamelinkArray = rows[0].gamelink;
// Ensure gamelinkArray is an array
if (typeof gamelinkArray === "string") {
gamelinkArray = [gamelinkArray]; // Convert to array if it's a string
}
if (!Array.isArray(gamelinkArray)) {
return res.status(500).json({ error: "Invalid gamelink data format" });
}
const gameDataResults = [];
for (const link of gamelinkArray) {
const gameLinkParts = link.split('/');
let gameNameFromUrl = '';
let gameIdData = '';
let gameTableName = '';
let gameVersion = '';
if (gameLinkParts.length === 5) {
gameNameFromUrl = gameLinkParts[3];
gameIdData = gameLinkParts[4].split('=')[1]; // Extracting ID
} else if (gameLinkParts.length === 6) {
gameNameFromUrl = gameLinkParts[3];
gameVersion = gameLinkParts[4];
gameIdData = gameLinkParts[5].split('=')[1]; // Extracting ID
}
if (gameNameFromUrl === 'drawing' && gameVersion === 'v2') {
gameTableName = 'game_drawing_v2';
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'v3') {
gameTableName = 'game_drawing_v3';
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_writo') {
gameTableName = 'drawing_writo';
} else if (gameNameFromUrl === 'drawing' && gameVersion === 'drawing_phonics') {
gameTableName = 'drawing_phonics';
} else if (gameNameFromUrl === 'drawing') {
gameTableName = 'game_drawing'; // General case, only if no version is specified
} else if (gameNameFromUrl === 'drag' && gameVersion === 'v2') {
gameTableName = 'game_drag_v2';
} else if (gameNameFromUrl === 'drag' && gameVersion === 'v4') {
gameTableName = 'game_drag_v4';
} else if (gameNameFromUrl === 'drag' && gameVersion === 'dragdrop_phonics') {
gameTableName = 'drag_drop_phonics';
} else if (gameNameFromUrl === 'drag' && gameVersion === 'match_phonics') {
gameTableName = 'drag_phonics';
} else if (gameNameFromUrl === 'drag') {
gameTableName = 'game_drag'; // General case for "drag"
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v1') {
gameTableName = 'tick_phonics_option_6';
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v2') {
gameTableName = 'tick_phonics_option_9';
} else if (gameNameFromUrl === 'tick' && gameVersion === 'tick_phonics_v3') {
gameTableName = 'game_tick_v3_phonics';
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v1') {
gameTableName = 'game_tick_variant1';
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v2') {
gameTableName = 'game_tick_variant2';
} else if (gameNameFromUrl === 'tick' && gameVersion === 'v3') {
gameTableName = 'game_tick_varient3';
} else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v1') {
gameTableName = 'cross_phonics_option_6';
} else if (gameNameFromUrl === 'cross' && gameVersion === 'cross_phonics_v2') {
gameTableName = 'cross_phonics_option_9';
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v1') {
gameTableName = 'game_cross_varient1';
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
gameTableName = 'game_cross_varient2';
} else if (gameNameFromUrl === 'cross' && gameVersion === 'v3') {
gameTableName = 'game_cross_varient3';
}
// else if (gameNameFromUrl === 'cross' && gameVersion === 'v2') {
// gameTableName = 'game_cross_varient2';
// }
// console.log('Game Info:', { gameTableName, gameVersion, gameIdData });
if (gameTableName && gameIdData) {
let gameConn;
try {
gameConn = await pool.getConnection();
const gameDataQuery = `SELECT * FROM \`${gameTableName}\` WHERE id = ?`;
const gameDataRows = await gameConn.query(gameDataQuery, [gameIdData]);
gameDataResults.push({ link, data: gameDataRows });
} catch (gameError) {
console.error("Error fetching game data:", gameError);
} finally {
if (gameConn) gameConn.release();
}
}
}
res.json({ wsData: rows, gameData: gameDataResults });
} catch (err) {
console.error("Database error:", err);
res.status(500).json({ error: "Database error" });
} finally {
if (conn) conn.release();
}
};
module.exports = getGameData;

View File

@ -0,0 +1,136 @@
const mariadb = require('mariadb');
const gameInfo = async (req, res) => {
// Create a connection pool
const pool = mariadb.createPool({
host: process.env.MARIA_HOST,
user: process.env.MARIA_USER,
password: process.env.MARIA_PASS,
database: process.env.MARIA_DBNM,
connectionLimit: 5,
});
const { schoolId, teacherId } = req.query;
if (!schoolId && !teacherId) {
return res.status(400).send({ error: 'Either schoolId or teacherId is required in the query parameters.' });
}
let connection;
try {
// Establish a connection to the database
connection = await pool.getConnection();
let queryCondition;
let queryValue;
// Determine the query condition based on the parameters provided
if (schoolId) {
queryCondition = 'schoolId = ?';
queryValue = schoolId;
} else {
queryCondition = 'teacherId = ?';
queryValue = teacherId;
}
// Query both game1 and game2 tables
const query1 = `SELECT * FROM game_drawing WHERE ${queryCondition}`;
const query2 = `SELECT * FROM game_drawing_v2 WHERE ${queryCondition}`;
const query3 = `SELECT * FROM game_drawing_v3 WHERE ${queryCondition}`;
const query4 = `SELECT * FROM drawing_phonics WHERE ${queryCondition}`;
const query5 = `SELECT * FROM game_tick_variant1 WHERE ${queryCondition}`;
const query6 = `SELECT * FROM game_tick_variant2 WHERE ${queryCondition}`;
const query7 = `SELECT * FROM game_tick_varient3 WHERE ${queryCondition}`;
const query8 = `SELECT * FROM game_cross_varient1 WHERE ${queryCondition}`;
const query9 = `SELECT * FROM game_cross_varient2 WHERE ${queryCondition}`;
const query10 = `SELECT * FROM game_cross_varient3 WHERE ${queryCondition}`;
const query11 = `SELECT * FROM game_drag WHERE ${queryCondition}`;
const query12 = `SELECT * FROM game_drag_v2 WHERE ${queryCondition}`;
const query13 = `SELECT * FROM game_drag_v4 WHERE ${queryCondition}`;
const query14 = `SELECT * FROM game_tick_v3_phonics WHERE ${queryCondition}`;
const query15 = `SELECT * FROM tick_phonics_option_6 WHERE ${queryCondition}`;
const query16 = `SELECT * FROM tick_phonics_option_9 WHERE ${queryCondition}`;
const query17 = `SELECT * FROM drag_drop_phonics WHERE ${queryCondition}`;
const query18 = `SELECT * FROM drag_phonics WHERE ${queryCondition}`;
const query19 = `SELECT * FROM cross_phonics_option_9 WHERE ${queryCondition}`;
const [game_drawing, game_drawing_v2, game_drawing_v3, drawing_phonics, game_tick_variant1, game_tick_variant2, game_tick_varient3, game_cross_varient1, game_cross_varient2, game_cross_varient3, game_drag, game_drag_v2, game_drag_v4, game_tick_v3_phonics, tick_phonics_option_6, tick_phonics_option_9, drag_drop_phonics, drag_phonics, cross_phonics_option_9 ] = await Promise.all([
connection.query(query1, [queryValue]),
connection.query(query2, [queryValue]),
connection.query(query3, [queryValue]),
connection.query(query4, [queryValue]),
connection.query(query5, [queryValue]),
connection.query(query6, [queryValue]),
connection.query(query7, [queryValue]),
connection.query(query8, [queryValue]),
connection.query(query9, [queryValue]),
connection.query(query10, [queryValue]),
connection.query(query11, [queryValue]),
connection.query(query12, [queryValue]),
connection.query(query13, [queryValue]),
connection.query(query14, [queryValue]),
connection.query(query15, [queryValue]),
connection.query(query16, [queryValue]),
connection.query(query17, [queryValue]),
connection.query(query18, [queryValue]),
connection.query(query19, [queryValue])
]);
// const domain = 'https://domain.com/gamelink/?id=';
const domain = process.env.GAME_DOMAIN;
const formattedGame1 = game_drawing.map(game => ({ ...game, game_id: `game_drawing-${game.id}`, game_link: `${domain}/drawing/?id=${game.id}`, }));
const formattedGame2 = game_drawing_v2.map(({ status, ...game }) => ({ ...game, game_id: `game_drawing_v2-${game.id}`, game_link: `${domain}/drawing/v2/?id=${game.id}`, }));
const formattedGame3 = game_drawing_v3.map(({ status, ...game }) => ({ ...game, game_id: `game_drawing_v3-${game.id}`, game_link: `${domain}/drawing/v3/?id=${game.id}`, }));
const formattedGame4 = drawing_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drawing_phonics-${game.id}`, game_link: `${domain}/drawing/drawing_phonics/?id=${game.id}`, }));
const formattedGame5 = game_tick_variant1.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_variant1-${game.id}`, game_link: `${domain}/tick/v1/?id=${game.id}`, }));
const formattedGame6 = game_tick_variant2.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_variant2-${game.id}`, game_link: `${domain}/tick/v2/?id=${game.id}`, }));
const formattedGame7 = game_tick_varient3.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_varient3-${game.id}`, game_link: `${domain}/tick/v3/?id=${game.id}`, }));
const formattedGame8 = game_cross_varient1.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient1-${game.id}`, game_link: `${domain}/cross/v1/?id=${game.id}`, }));
const formattedGame9 = game_cross_varient2.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient2-${game.id}`, game_link: `${domain}/cross/v2/?id=${game.id}`, }));
const formattedGame10 = game_cross_varient3.map(({ status, ...game }) => ({ ...game, game_id: `game_cross_varient3-${game.id}`, game_link: `${domain}/cross/v3/?id=${game.id}`, }));
const formattedGame11 = game_drag.map(({ status, ...game }) => ({ ...game, game_id: `game_drag-${game.id}`, game_link: `${domain}/drag/?id=${game.id}`, }));
const formattedGame12 = game_drag_v2.map(({ status, ...game }) => ({ ...game, game_id: `game_drag_v2-${game.id}`, game_link: `${domain}/drag/v2/?id=${game.id}`, }));
const formattedGame13 = game_drag_v4.map(({ status, ...game }) => ({ ...game, game_id: `game_drag_v4-${game.id}`, game_link: `${domain}/drag/v4/?id=${game.id}`, }));
const formattedGame14 = game_tick_v3_phonics.map(({ status, ...game }) => ({ ...game, game_id: `game_tick_v3_phonics-${game.id}`, game_link: `${domain}/tick/tick_phonics_v1/?id=${game.id}`, }));
const formattedGame15 = tick_phonics_option_6.map(({ status, ...game }) => ({ ...game, game_id: `tick_phonics_option_6-${game.id}`, game_link: `${domain}/tick/tick_phonics_v2/?id=${game.id}`, }));
const formattedGame16 = tick_phonics_option_9.map(({ status, ...game }) => ({ ...game, game_id: `tick_phonics_option_9-${game.id}`, game_link: `${domain}/tick/tick_phonics_v3/?id=${game.id}`, }));
const formattedGame17 = drag_drop_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drag_drop_phonics-${game.id}`, game_link: `${domain}/drag/dragdrop_phonics/?id=${game.id}`, }));
const formattedGame18 = drag_phonics.map(({ status, ...game }) => ({ ...game, game_id: `drag_phonics-${game.id}`, game_link: `${domain}/drag/match_phonics/?id=${game.id}`, }));
const formattedGame19 = cross_phonics_option_9.map(({ status, ...game }) => ({ ...game, game_id: `cross_phonics_option_9-${game.id}`, game_link: `${domain}/cross/cross_phonics_v2/?id=${game.id}`, }));
const combinedResults = {
game_drawing: formattedGame1,
game_drawing_v2: formattedGame2,
game_drawing_v3: formattedGame3,
drawing_phonics: formattedGame4,
game_tick_variant1: formattedGame5,
game_tick_variant2: formattedGame6,
game_tick_varient3: formattedGame7,
game_cross_varient1: formattedGame8,
game_cross_varient2: formattedGame9,
game_cross_varient3: formattedGame10,
game_drag: formattedGame11,
game_drag_v2: formattedGame12,
game_drag_v4: formattedGame13,
game_tick_v3_phonics: formattedGame14,
tick_phonics_option_6: formattedGame15,
tick_phonics_option_9: formattedGame16,
drag_drop_phonics: formattedGame17,
drag_phonics: formattedGame18,
cross_phonics_option_9: formattedGame19
};
res.status(200).send(combinedResults);
} catch (error) {
console.error('Error querying game tables:', error);
res.status(500).send({ error: 'An error occurred while fetching game data.' });
} finally {
// Release the connection back to the pool
if (connection) connection.release();
}
};
module.exports = gameInfo;

View File

@ -1,32 +1,56 @@
const mysql = require("mysql2");
const getGameScore = (req, res) => { const getGameScore = (req, res) => {
const pool = mysql.createPool({ const { MongoClient } = require('mongodb');
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 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) => { try {
if (error) { // Connect to the MongoDB client
return res.status(500).json({ message: 'Database query failed', error }); await client.connect();
}
if (results.length > 0) { // Select the database and collection
const game = results[0]; const database = client.db(dbName); // Replace with your database name
res.json({ score: game.score, gameTime: game.gameTime }); const collection = database.collection('gameData'); // Replace with your collection name
} else {
res.status(404).json({ message: 'Game data not found' }); // Find a single document
} // const user = await collection.findOne({ childId: 'dsfdfgffgfgeg' });
});
}; const { childId, gameName, gameID } = req.body;
const gameData = await collection.findOne(
module.exports = getGameScore; {
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;

View 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;

View File

@ -1,68 +0,0 @@
var MongoClient = require('mongodb').MongoClient;
const AWS = require('aws-sdk');
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('gameData');
// const data = req.body;
const { userId, gameName, gameID, gameTime, score, screenShot } = req.body;
const data = {
userId: userId,
gameName: gameName,
gameID: gameID,
gameTime: gameTime,
score: score
};
collection.insertOne(data, (err, result) => {
if (err) {
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');
const s3 = new AWS.S3({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
});
if (screenShot != undefined) {
// Upload image to S3
let base64Image = screenShot.split(";base64,").pop();
const buffer = Buffer.from(base64Image, 'base64');
const s3Params = {
Bucket: process.env.S3_BUCKET_NAME,
Key: `images/${result.insertedId}.png`, // Change the file extension to .png
Body: buffer,
ContentEncoding: 'base64',
ContentType: 'image/jpeg' // Change the content type to image/png
};
try {
const data = s3.upload(s3Params).promise();
console.log(`File uploaded successfully at ${data.Location}`);
} catch (err) {
console.error(err);
}
};
res.send(result.insertedId);
}
});
});
});
};
module.exports = saveGameScore;

View 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;

View File

@ -22,7 +22,20 @@ const saveQuizResponse = require("../api/saveQuizResponse");
const getGameScore = require("../api/getGameScore"); const getGameScore = require("../api/getGameScore");
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit"); const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
const generateQuestions = require("../api/generateQuestions"); const generateQuestions = require("../api/generateQuestions");
const saveGameScore = require("../api/saveGameScore"); // 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 getGameData = require("../api/getGameData");
// const aiTest = require("../api/aiTest");
const router = express.Router(); const router = express.Router();
@ -138,10 +151,74 @@ router.get("/ping", (req, res) => {
}); });
// For Quiz Result After Submit Quiz // For Quiz Result After Submit Quiz
router.post("/saveGameScore", (req, res) => { // router.post("/saveGameScore", (req, res) => {
saveGameScore(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);
});
router.get("/getGameData", (req, res) => {
getGameData(req, res);
});
// Get Drawing Game Gallery Image
// router.post("/aiTest", (req, res) => {
// aiTest(req, res);
// });
module.exports = router; module.exports = router;