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 id="chart">

  </div>
  <div id="emo_over">
    <span>CLICK TO START</span>
  </div>
</div>

CSS

#emotion{
  position:relative;
}
#emo_over{
  position:absolute;
  background-color:rgba(0,0,0,0.4);
  top:0;left:0;right:0;bottom:0;
  z-index:1000;
  cursor:pointer;
}

#emo_over span{
  position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
    display: block;
    height: 20px;
    margin: auto;
    text-align: center;
}

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;
  }
}

let emoStarted = false;

CY.loader()
  .addModule(CY.modules().FACE_DETECTOR.name)
  .addModule(CY.modules().FACE_ATTENTION.name, {})
  .addModule(CY.modules().FACE_EMOTION.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("#chart"), options);
chart.render();
  
const AGE = document.querySelector("#age");
const GEN = document.querySelector("#gender");
const EmoAvg = new EmotionAvg();
const EMO_START = document.querySelector("#emo_over");
EMO_START.onclick = function() {
  emoStarted = true;
  EMO_START.style.display = "none";
  setTimeout(() => {
      emoStarted = false;
      alert("Tracking Emozioni terminato");
    },5000);
}

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) => {
  if(!emoStarted) return;
	EmoAvg.add(evt.detail.output.emotion);
  const emos = EmoAvg.get();
 	const labels = [];
  const data = [];
  Object.keys(emos).forEach(k => {
  	labels.push(k);
   ...