52 Commits

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
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
91b73215be node v 2025-02-14 01:37:23 +05:30
40eda82022 node v 2025-02-14 01:33:59 +05:30
2150d52b9d node v 2025-02-14 01:27:56 +05:30
fb21f179e6 node v 2025-02-14 01:26:43 +05:30
5777ee5131 node v 2025-02-14 01:23:16 +05:30
f96a50b7f4 node v 2025-02-14 01:05:49 +05:30
3f944eb49e nodeVersion 2025-02-14 00:51:44 +05:30
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
73b3d67508 Update src/routes/v1/api.route.js 2025-02-11 11:21:01 +00:00
1706a910fd clean 2025-02-06 17:46:06 +05:30
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
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
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
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
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
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
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
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
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
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
7db4089223 working1 2025-01-29 22:27:10 +05:30
e589d66e36 list-models 2025-01-29 21:03:30 +05:30
cfa16dbdc7 list-models 2025-01-29 21:01:05 +05:30
fe72636dd7 node 2025-01-29 19:16:10 +05:30
f5d6c3cedc aiTest 2025-01-29 19:13:55 +05:30
136286599f multi ai provider added 2025-01-29 18:48:49 +05:30
40c650f7d4 log 2025-01-29 18:26:26 +05:30
b44c72e690 3 to 10 2025-01-26 08:49:17 +00:00
4acaac5b84 Merge pull request 's4' (#8) from tmp2 into master
Reviewed-on: #8
2025-01-23 14:45:24 +00:00
22c2affa00 Merge pull request 's3' (#7) from tmp2 into master
Reviewed-on: #7
2025-01-23 14:14:22 +00:00
Suvodip
7dda27e86e s2 2025-01-23 19:38:46 +05:30
Suvodip
5152ca2e23 gallery 2 api 2024-12-23 19:17:45 +05:30
23 changed files with 3133 additions and 252 deletions

View File

@@ -1,21 +1,26 @@
ARG NODE_VERSION=18
# Use an official Node.js runtime as a parent image
FROM node:20-alpine
FROM node:${NODE_VERSION}-alpine
# Set the working directory inside the container
WORKDIR /app
ENV NODE_ENV production
# Copy package files and set ownership
COPY --chown=node:node package*.json ./
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 ./
USER node
RUN yarn install --pure-lockfile
# Install dependencies
RUN npm install --omit=dev
# Copy the rest of the app's source code with correct ownership
COPY --chown=node:node . .
EXPOSE 5174
# Use a non-root user for better security
USER node
CMD yarn start
# Expose the application port
EXPOSE 3000
# Set environment variables (optional)
ENV NODE_ENV=production
# Start the application
CMD ["npm", "run", "start"]

BIN
output.png Normal file

Binary file not shown.

2570
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -22,8 +22,7 @@
"prettier:fix": "prettier --write **/*.js",
"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:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up",
"prepare": "husky install"
"docker:test": "docker-compose -f docker-compose.yml -f docker-compose.test.yml up"
},
"keywords": [
"node",
@@ -60,8 +59,10 @@
"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",
"mariadb": "^3.4.0",
@@ -69,7 +70,9 @@
"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",
@@ -89,7 +92,6 @@
"eslint-plugin-prettier": "^3.1.1",
"eslint-plugin-security": "^1.4.0",
"faker": "^5.1.0",
"husky": "7.0.4",
"jest": "^26.0.1",
"lint-staged": "^11.0.0",
"node-mocks-http": "^1.8.0",

View File

@@ -2,12 +2,11 @@ const mongoose = require("mongoose");
const gameSchema = new mongoose.Schema({
gameName: { type: String, required: true },
userId: { type: String, required: true },
childId: { type: String, required: true },
gameID: { type: String, required: true },
gameTime: { type: String, required: false },
score: { type: String},
gameStar: { type: Number},
screenshotUrl: { type: String }, // Store the S3 URL of the screenshot
});
gameStar: { type: Number },
screenshotUrl: { type: String },
}, { collection: "gameData" });
module.exports = mongoose.model("Game", gameSchema);

View File

@@ -2,7 +2,7 @@ const mongoose = require('mongoose');
// Define the GalleryImage schema
const galleryImageSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true }, // Assuming you have a User model
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 },

View File

@@ -2,7 +2,7 @@ const mongoose = require("mongoose");
const galleryImageScema = new mongoose.Schema({
gameName: { type: String, required: true },
userId: { type: String, required: true },
childId: { type: String, required: true },
gameID: { type: String, required: true },
screenshotUrl: { type: String },
});

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

@@ -1,30 +1,27 @@
const AWS = require('aws-sdk');
const axios = require('axios');
const FormData = require('form-data');
const mongoose = require('mongoose');
const FormData = require('form-data');
const Game = require('../../models/gameModel');
const aiEvaluateImageToStar = async (req, res) => {
try {
const { userId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
const { childId, gameName, gameID, gameTime, gameStar, screenShot } = req.body;
if (!screenShot) {
return res.status(400).json({ error: 'Screenshot is required' });
}
const formData = new FormData();
formData.append('image', screenShot);
const screenshotUrl = await axios.post('https://teachertrainingchennai.in/api/uploadBase64/', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
// .then(response => {
// console.log('Response:', response.data);
// })
// .catch(error => {
// console.error('Error:', error);
// });
console.log(screenshotUrl.data.filePath)
// 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: [
@@ -33,12 +30,12 @@ const aiEvaluateImageToStar = async (req, res) => {
content: [
{
type: 'text',
text: 'The coloring was done by a 5-year-old kid. Give a score between 3 to 5 in JSON format.',
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.data.filePath,
url: screenshotUrl,
},
},
],
@@ -47,7 +44,6 @@ const aiEvaluateImageToStar = async (req, res) => {
max_tokens: 300,
};
// console.log('AAAAAA')
const openAiResponse = await axios.post(
'https://api.openai.com/v1/chat/completions',
openAiPayload,
@@ -58,18 +54,29 @@ const aiEvaluateImageToStar = async (req, res) => {
},
}
);
const rResp=openAiResponse.data.choices[0].message;
const cleanContent = rResp.content.replace(/```json|```/g, '').trim();
const parsedScore = JSON.parse(cleanContent);
// console.log(parsedScore); // { score: 8 }
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,
userId,
childId,
gameID,
gameTime,
score: parsedScore.score || 'N/A',
gameStar,
screenshotUrl:screenshotUrl.data.filePath,
gameStar: parsedScore.score || 'N/A',
screenshotUrl,
});
await gameData.save();
@@ -80,7 +87,7 @@ const parsedScore = JSON.parse(cleanContent);
});
} catch (error) {
console.error('Error:', error.message);
return res.status(500).json({ error: 'Something went wrong' });
return res.status(500).json({ error: error.message || 'Something went wrong' });
}
};

View File

@@ -1,5 +1,5 @@
const aiFeedbackOnReport = async (req, res) => {
const fetch = require('node-fetch');
// const fetch = require('node-fetch');
const url = process.env.AI_API_ENDOINT;
const api_key = process.env.AI_API_KEY;
const payload = {

View File

@@ -1,5 +1,5 @@
const aiFeedbackOnReport = async (req, res) => {
const fetch = require('node-fetch');
// const fetch = require('node-fetch');
const url = process.env.AI_API_ENDOINT;
const api_key = process.env.OPENAI_KEY;
const payload = {

View File

@@ -1,7 +1,7 @@
const aiFollowupQuestion = async (req, res) => {
const { MongoClient } = require('mongodb');
const fetch = require('node-fetch');
// const fetch = require('node-fetch');
const { v4: uuidv4 } = require('uuid');
const url = process.env.MONGODB_URL;
const dbName = process.env.MONGO_DB_NAME;

View File

@@ -1,21 +1,46 @@
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 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) {
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}`,
Authorization: `Bearer ${process.env.OPENAI_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
@@ -28,70 +53,71 @@ const aiFollowupQuestion = async (req, res) => {
max_tokens: max_tokens,
}),
});
const data = await response.json();
console.log(process.env.OPENAI_KEY)
console.log(data)
// 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: 'answer within 10 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({
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: 'Something went wrong. Please try again later.',
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;
};
module.exports = aiFollowupQuestion;

View File

@@ -2,7 +2,7 @@ const aiMarkDrawing = async (req, res) => {
const express = require('express');
const fetch = require('node-fetch'); // For making HTTP requests
// const fetch = require('node-fetch'); // For making HTTP requests
const path = require('path');
const fs = require('fs');

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

@@ -3,6 +3,15 @@ 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,
@@ -11,12 +20,12 @@ const aiTextToSpeech = async (req, res) => {
const polly = new AWS.Polly();
const voiceIdMap = {
"Ava": "Ivy",
"Monstero": "Justin",
"Dax": "Kevin",
"Kai": "Danielle",
"Arlo": "Ruth",
"Yara": "Salli"
Ava: 'Ivy',
Monstero: 'Justin',
Dax: 'Kevin',
Kai: 'Danielle',
Arlo: 'Ruth',
Yara: 'Salli',
};
const { text, voiceId: frontendVoiceId } = req.body;
@@ -41,7 +50,9 @@ const aiTextToSpeech = async (req, res) => {
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');
const randomDigits = Math.floor(Math.random() * 10000)
.toString()
.padStart(4, '0');
return `${formattedDate}_${randomDigits}`;
}
@@ -59,23 +70,18 @@ const aiTextToSpeech = async (req, res) => {
// 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
}
}
);
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
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' });

View File

@@ -3,7 +3,7 @@ const GalleryImage = require('../../models/getGalleyImage');
const getGalleryImage = async (req, res) => {
try {
// Extract query parameters for filtering (if provided)
const { gameName, userId, gameID} = req.query;
const { gameName, childId, gameID} = req.query;
// Build a filter object based on the query parameters
const filter = {};
@@ -12,15 +12,15 @@ const getGalleryImage = async (req, res) => {
filter.gameName = gameName;
}
if (userId) {
filter.userId = userId;
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 userId gameID screenshotUrl'); // Select only these 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' });

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

@@ -15,15 +15,19 @@ async function main() {
const collection = database.collection('gameData'); // Replace with your collection name
// Find a single document
// const user = await collection.findOne({ userId: 'dsfdfgffgfgeg' });
// const user = await collection.findOne({ childId: 'dsfdfgffgfgeg' });
const { userId, gameName, gameID } = req.body;
const gameData = await collection.findOne({
userId: userId,
gameName: gameName,
gameID: gameID
});
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 {

View File

@@ -4,7 +4,7 @@ const FormData = require('form-data'); // Import form-data for Node.js
const saveGalleryImage = async (req, res) => {
try {
const { userId, gameName, gameID, screenShot } = req.body;
const { childId, gameName, gameID, screenShot } = req.body;
// Validate base64 format
const isValidBase64 = validateBase64(screenShot);
@@ -41,12 +41,13 @@ const saveGalleryImage = async (req, res) => {
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({
userId,
childId,
gameName,
gameID,
screenshotUrl,

View File

@@ -1,69 +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,gameStar, screenShot } = req.body;
const data = {
userId: userId,
gameName: gameName,
gameID: gameID,
gameTime: gameTime,
score: score,
gameStar:gameStar
};
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

@@ -1,4 +1,5 @@
const AWS = require("aws-sdk");
const mongoose = require("mongoose");
const Game = require("../../models/gameModel");
const s3 = new AWS.S3({
@@ -7,35 +8,55 @@ const s3 = new AWS.S3({
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 { userId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
const { childId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;
try {
if (!gameName || !userId || !gameID) {
if (!gameName || !childId || !gameID) {
return res.status(400).json({ error: "Missing required fields" });
}
const newGame = new Game({
gameName,
userId,
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 buffer = Buffer.from(screenShot, "base64");
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,

View File

@@ -22,7 +22,7 @@ const saveQuizResponse = require("../api/saveQuizResponse");
const getGameScore = require("../api/getGameScore");
const resultAfterQuizSubmit = require("../api/resultAfterQuizSubmit");
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");
@@ -34,6 +34,8 @@ 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();
@@ -149,9 +151,9 @@ router.get("/ping", (req, res) => {
});
// For Quiz Result After Submit Quiz
router.post("/saveGameScore", (req, res) => {
saveGameScore(req, res);
});
// router.post("/saveGameScore", (req, res) => {
// saveGameScore(req, res);
// });
// For Quiz Result After Submit Quiz
router.post("/saveGameScore2", (req, res) => {
@@ -207,6 +209,15 @@ router.get("/ping", (req, res) => {
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;