JSFiddle - React, Tailwind, and code Playground
by morphcast
HTML
<script src="https://ai-sdk.morphcast.com/v1.8/ai-sdk.js"></script>
<body><p>MorphCast SDK - v1.8</p>
<p>
In this example, after waiting few partial results, camera stops and the final emotion distribution and dominant emotion are printed to the screen.
</p></body>
JavaScript
const STOP_AFTER_N_RESULTS = 30;
var startMorphcast = null;
var stopMorphcast = null;
function initMorphcast() {
return CY.loader()
.addModule(CY.modules().FACE_EMOTION.name, {})
.load()
.then(({ start, stop }) => {
startMorphcast = start;
stopMorphcast = stop;
});
}
initMorphcast().then(()=>startMorphcast());
var CMA = ()=>{
var avg_dict = null;
var n = 0;
return {
get avg_dict() {
return avg_dict;
},
get length() {
return n;
},
push: function (next_dict) {
n += 1;
if (avg_dict) {
Object.keys(avg_dict).forEach(function (key) {
avg_dict[key] = avg_dict[key] + (next_dict[key] - avg_dict[key]) / n
})
} else {
avg_dict = Object.assign({}, next_dict);
}
}
}
};
var avg_emotions = CMA();
var done = false;
function check_results() {
if (!done && avg_emotions.length >= STOP_AFTER_N_RESULTS) {
done = true;
stopMorphcast();
const avg_dict_string = JSON.stringify(avg_emotions.avg_dict,
function(key, val) {
return val.toFixed ? Number(val.toFixed(2)) : val;
})
window.alert('Average distribution of emotions: ' + avg_dict_string + '\n'
+ ' - Average dominant emotion: ' + getArgMaxKey(avg_emotions.avg_dict));
}
}
function getArgMaxKey(dict) {
return Object.keys(dict).reduce((a, b) => dict[a] > dict[b] ? a : b)
}
window.addEventListener(CY.modules().FACE_EMOTION.eventName, (evt) => {
let result = evt.detail.output.rawEmotion;
if (result) {
avg_emotions.push(result);
console.log(result);
check_results();
}
});