JSFiddle - React, Tailwind, and code Playground
by morphcast
HTML
<script src="https://ai-sdk.morphcast.com/v1.8/ai-sdk.js"></script>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<div id="age"> - </div>
<div id="gender"> - </div>
<div id="emotion">
</div>
JavaScript
class EmotionAvg{
constructor() {
this.emos = {};
this.n = 0;
}
add(emo) {
Object.keys(emo).forEach(k => {
this.emos[k] = this.emos[k] || 0;
this.emos[k] = (this.emos[k] * this.n + emo[k]) / (this.n + 1);
});
this.n++;
}
get(){
return this.emos;
}
}
CY.loader()
.addModule(CY.modules().FACE_DETECTOR.name)
.addModule(CY.modules().FACE_ATTENTION.name, {})
.addModule(CY.modules().FACE_EMOTION.name, {})
.addModule(CY.modules().FACE_AGE.name, {})
.addModule(CY.modules().FACE_GENDER.name, {})
.load()
.then(({start, stop}) => start());
var options = {
chart: {
height: 350,
type: 'radar',
},
yaxis: {
min:0,
max:50
},
series:[],
title: {
text: 'Emotions'
},
labels:[]
};
const chart = new ApexCharts(document.querySelector("#emotion"), options);
chart.render();
const AGE = document.querySelector("#age");
const GEN = document.querySelector("#gender");
const EmoAvg = new EmotionAvg();
window.addEventListener(CY.modules().FACE_AGE.eventName, (evt) => {
AGE.innerHTML = evt.detail.output.numericAge;
});
window.addEventListener(CY.modules().FACE_GENDER.eventName, (evt) => {
const M = evt.detail.output.rawGender.Male;
const F = evt.detail.output.rawGender.Female;
if( Math.max(M,F) > 0.65 ){
GEN.innerHTML = M > F ? "Male" : "Female";
} else {
GEN.innerHTML = "Unknown";
}
});
window.addEventListener(CY.modules().FACE_EMOTION.eventName, (evt) => {
EmoAvg.add(evt.detail.output.emotion);
const emos = EmoAvg.get();
const labels = [];
const data = [];
Object.keys(emos).forEach(k => {
labels.push(k);
data.push((emos[k] * 100));
});
chart.updateOptions({
labels: labels,
series:[{
name: 'Emotions',
data:data
}]
});
});