JSFiddle - React, Tailwind, and code Playground

by morphcast

HTML

<script src="https://ai-sdk.morphcast.com/v1.8.4/ai-sdk.js"></script>
<body><p>MorphCast SDK - v1.8.4</p>
<p>
In this example, after waiting few partial results, camera stops and the final dominant emotion is printed to the screen.
</p></body>

JavaScript

var startMorphcast = null;
var stopMorphcast = null;

function initMorphcast() {
	const config = {smoothness: 0.94};
  return CY.loader()
    .addModule(CY.modules().FACE_EMOTION.name, config)
    .load()
    .then(({ start, stop }) => {
    startMorphcast = start;
    stopMorphcast = stop;
  });
}

initMorphcast().then(()=>startMorphcast());

const MIN_EMOTION_RESULTS = 40;
var emotion_results = 0;
var last_dominant_emotion;
var done = false;

function check_results() {
	if (!done && emotion_results >= MIN_EMOTION_RESULTS) {
  	done = true;
    stopMorphcast();
    window.alert('Dominant emotion: ' + last_dominant_emotion);
  }
}

function getArgMaxKey(dict) {
	return Object.keys(dict).reduce((a, b) => dict[a] > dict[b] ? a : b)
} 

window.addEventListener(CY.modules().FACE_EMOTION.eventName, (evt) => {
  last_dominant_emotion = evt.detail.output.dominantEmotion;
  if (last_dominant_emotion) {
    emotion_results++;
    check_results();
  }
});