Compare commits

..

19 Commits

Author SHA1 Message Date
Subhodip Ghosh 5e741897c5 Update src/routes/api/takeSnap.js 2025-03-17 05:45:27 +00:00
Subhodip Ghosh 37316ff794 Update src/routes/api/takeSnap.js 2025-03-17 04:55:42 +00:00
Subhodip Ghosh f6835d9417 Update src/routes/api/takeSnap.js 2025-03-15 13:59:36 +00:00
Subhodip Ghosh 3cba906217 Update src/routes/api/takeSnap.js 2025-03-15 13:42:54 +00:00
Subhodip Ghosh 9f3f904a3a Update src/routes/api/takeSnap.js 2025-03-15 13:28:11 +00:00
Subhodip Ghosh 0038ee1b25 Update src/routes/api/takeSnap.js 2025-03-15 13:12:17 +00:00
Subhodip Ghosh b9d2e682c5 Update src/routes/api/takeSnap.js 2025-03-15 13:05:36 +00:00
Subhodip Ghosh ec27c1b366 Update src/routes/api/takeSnap.js 2025-03-15 12:48:13 +00:00
Subhodip Ghosh d3212fadbc Update src/routes/api/takeSnap.js 2025-03-15 12:12:15 +00:00
Subhodip Ghosh 9b9f841b12 Update src/routes/api/takeSnap.js 2025-03-15 11:16:30 +00:00
Suvodip e12308e8bb game screenshot 2025-03-15 16:26:42 +05:30
Suvodip cdee582951 s1 2025-03-11 18:37:19 +05:30
Suvodip dc6194f7e7 s1 2025-03-11 18:06:25 +05:30
Suvodip 6d380c6cbb s11 2025-03-11 18:02:28 +05:30
Suvodip 8e0cce2465 s11 2025-03-11 17:56:51 +05:30
Suvodip 0735a91450 s1 2025-03-11 17:45:38 +05:30
Suvodip 1576fa92c1 s1 2025-03-11 17:39:47 +05:30
Suvodip 319bc33d4a s1 2025-03-11 17:02:44 +05:30
Suvodip b7da294a17 s1 2025-03-11 16:52:39 +05:30
6 changed files with 745 additions and 172 deletions

612
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -48,18 +48,19 @@
],
"dependencies": {
"aws-sdk": "^2.1669.0",
"axios": "^1.7.7",
"axios": "^1.8.2",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"compression": "^1.7.4",
"cors": "^2.8.5",
"cross-env": "^7.0.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express": "^4.21.2",
"express-mongo-sanitize": "^2.0.0",
"express-rate-limit": "^5.0.0",
"form-data": "^4.0.1",
"form-data": "^4.0.2",
"formdata-node": "^6.0.3",
"fs": "^0.0.1-security",
"helmet": "^4.1.0",
"http-status": "^1.4.0",
"install": "^0.13.0",
@ -75,7 +76,9 @@
"npm": "^11.0.0",
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"path": "^0.12.7",
"pm2": "^5.1.0",
"puppeteer": "^24.4.0",
"swagger-jsdoc": "^6.0.8",
"swagger-ui-express": "^4.1.6",
"validator": "^13.0.0",

View File

@ -1,29 +1,4 @@
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');
@ -31,16 +6,16 @@ const aiFollowupQuestion = async (req, res) => {
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({
@ -53,71 +28,70 @@ const aiFollowupQuestion = async (req, res) => {
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({
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: 'Invalid session ID.',
error: 'MongoDB is not connected yet. Please try again later.',
});
}
conversation.conversationHistory.push({ role: 'user', content: prompt });
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({
success: false,
error: 'Something went wrong. Please try again later.',
});
}
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

@ -3,15 +3,6 @@ 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,
@ -20,12 +11,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;
@ -50,9 +41,7 @@ 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}`;
}
@ -70,18 +59,23 @@ 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

@ -0,0 +1,99 @@
const { execSync } = require("child_process");
const fs = require("fs");
const path = require("path");
const axios = require("axios");
const gameIds = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'11', '12', '13', '14', '15', '16', '17', '18', '19', '20',
'21', '22', '23', '24', '25', '26', '27', '28', '29', '30',
'31', '32', '33', '34', '35', '36', '37', '38', '39', '40',
'41', '42', '43', '44', '45', '46', '47', '48', '49', '50',
'51', '52', '53', '54', '55', '56', '57', '58', '59', '60',
'61', '62', '63', '64', '65', '66', '67', '68', '69', '70',
'71', '72', '73', '74', '75', '76', '77', '78', '79', '80',
'81', '82', '83', '84', '85', '86', '87', '88', '89', '90',
'91', '92', '93', '94', '95', '96', '97', '98', '99', '100',
'101', '102', '103', '104', '105', '114'
];
const SCREENSHOT_FOLDER = path.join(__dirname, "game-screen/drawing");
if (!fs.existsSync(SCREENSHOT_FOLDER)) {
fs.mkdirSync(SCREENSHOT_FOLDER, { recursive: true });
}
const DIRECTUS_API_URL = "https://game-du.teachertrainingkolkata.in/files";
async function takeSnap(req, res) {
for (const id of gameIds) {
try {
const url = `https://interaktogames.beanstalkedu.com/tick/v1?id=${id}`;
console.log(`📸 Taking screenshot for Game ID: ${id}`);
const command = `url2jpg ${url}`;
execSync(command, { stdio: "inherit", shell: true });
const files = fs.readdirSync(process.cwd()).filter(f => f.endsWith(".jpg"));
if (files.length === 0) throw new Error("No screenshot found!");
const latestFile = files.reduce((a, b) =>
fs.statSync(b).mtimeMs > fs.statSync(a).mtimeMs ? b : a
);
const newPath = path.join(SCREENSHOT_FOLDER, `${id}.jpg`);
fs.renameSync(latestFile, newPath);
console.log(`✅ Screenshot saved: ${newPath}`);
const fileId = await uploadToDirectus(newPath);
if (fileId) {
console.log(`📤 Uploaded to Directus. File ID: ${fileId}`);
await updateThumbnail(id, fileId);
}
} catch (error) {
console.error(`❌ Error processing Game ID ${id}:`, error.message);
}
}
res.json({ message: "All screenshots processed successfully!" });
}
async function uploadToDirectus(filePath) {
try {
const fileData = fs.createReadStream(filePath);
const response = await axios.post(
DIRECTUS_API_URL,
{ file: fileData },
{
headers: { "Content-Type": "multipart/form-data" },
}
);
return response.data.data.id;
} catch (error) {
console.error("❌ Failed to upload screenshot to Directus:", error.message);
return null;
}
}
async function updateThumbnail(gameId, fileId) {
const UPDATE_THUMBNAIL_URL = "https://game-du.teachertrainingkolkata.in/items/game_tick_variant1/";
try {
const response = await axios.patch(
`${UPDATE_THUMBNAIL_URL}${gameId}`,
{ thumbnail: fileId }, // ✅ No need for "data" wrapper in REST API
{ headers: { "Content-Type": "application/json" } }
);
console.log(`✅ Thumbnail updated for Game ID ${gameId}:`, response.data);
} catch (error) {
console.error(`❌ Failed to update thumbnail for Game ID ${gameId}`);
if (error.response) {
console.error("Response Data:", error.response.data);
console.error("Status Code:", error.response.status);
} else {
console.error("Error Message:", error.message);
}
}
}
module.exports = takeSnap;

View File

@ -35,6 +35,7 @@ const getGameInfo = require("../api/getGameInfo");
const saveGalleryImage = require("../api/saveGalleryImage");
const getGalleryImage = require("../api/getGalleryImage");
const getGameData = require("../api/getGameData");
const takeSnap = require("../api/takeSnap");
// const aiTest = require("../api/aiTest");
@ -214,6 +215,10 @@ router.get("/ping", (req, res) => {
getGameData(req, res);
});
router.get("/takeSnap", (req, res) => {
takeSnap(req, res);
});
// Get Drawing Game Gallery Image
// router.post("/aiTest", (req, res) => {
// aiTest(req, res);