JSFiddle - React, Tailwind, and code Playground
by morphcast
HTML
<script src="https://ai-sdk.morphcast.com/v1.16/ai-sdk.js"></script>
<body>
<div class="container-fluid">
<div class="row">
<canvas id="canvas" class="col-md-8"></canvas>
<div class="col-md-4">
<strong>MorphCast JS SDK - Engagement Index (v1.16 environment)</strong>
<div id="e_results" style="word-wrap:break-word;font-size:40px"></div>
</div>
</div>
<div>
<button id="start" onclick="onStart()" disabled>Start</button>
<button id="stop" onclick="onStop()">Stop</button>
<p>
<strong>Instructions</strong>
Press the start button to start the detector.
<br/> Press the stop button to end the detector.
</p>
<div>
<strong>LOG:</strong>
</div>
<div id="logs"></div>
</div>
</div>
</body>
JavaScript
function log(msg) {
var element = document.getElementById("logs");
element.innerHTML += "<span>" + msg + "</span><br />";
}
let timeout;
function print(node, msg) {
document.getElementById(node).innerHTML = msg;
}
//function executes when Start button is pushed.
function onStart() {
if (detector && !detector.isRunning) {
detector.isRunning = true;
detector.start();
}
log("Clicked the start button");
print("e_results", "Engagement Index: --");
}
//function executes when the Stop button is pushed.
function onStop() {
log("Clicked the stop button");
if (detector && detector.isRunning) {
detector.stop();
detector.isRunning = false;
}
}
window.addEventListener(CY.modules().FACE_EMOTION.eventName, (evt) => {
const emotion = evt.detail.output.emotion;
const weights = {
Happy: 0.6,
Surprise: 0.6,
Neutral: 0.9,
Angry: 0.25,
Fear: 0.3,
Sad: 0.3,
Disgust: 0 // Aggiungi il peso per Disgust se necessario
};
let engagementIndex = 0;
let engaged = false;
for (let emotionName in emotion) {
if (weights.hasOwnProperty(emotionName)) {
engagementIndex += emotion[emotionName] * weights[emotionName];
}
}
if (emotion.Neutral > 0.6 || emotion.Happy > 0.5 || emotion.Surprised > 0.6) {
engaged = true;
} else if (emotion.Angry > 0.2 || emotion.Fear > 0.3 || emotion.Sad > 0.3) {
engaged = false;
} else {
engaged = false;
engagementIndex = 0;
}
console.log('Engagement Index:', engagementIndex);
print("e_results", "Engagement Index: " + (engagementIndex * 100).toFixed(0) + "<br />ENGAGED: " + engaged);
});
const ctx = document.getElementById('canvas').getContext('2d');
let dimLogged = false;
window.addEventListener(CY.modules().CAMERA.eventName, (evt) => {
const imageData = evt.detail;
if (!dimLogged) {
log(`Camera dimensions: w: ${imageData.width}, h: ${imageData.height}`);
dimLogged = true;
}
ctx.canvas.width = imageData.width;
...