95 lines
2.7 KiB
JavaScript
95 lines
2.7 KiB
JavaScript
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;
|