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 estimated age and gender are printed to the screen.
</p></body>

JavaScript

var startMorphcast = null;
var stopMorphcast = null;

function initMorphcast() {

  return CY.loader()
    .addModule(CY.modules().FACE_AGE.name, {})
    .addModule(CY.modules().FACE_GENDER.name, {})
    .load()
    .then(({ start, stop }) => {
    startMorphcast = start;
    stopMorphcast = stop;
  });
}

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

const MIN_AGE_RESULTS = 1;
const MIN_GENDER_RESULTS = 1;
var age_results = 0;
var gender_results = 0;
var last_age, last_gender;
var done = false;

function check_results() {
	if (!done && age_results >= MIN_AGE_RESULTS && gender_results >= MIN_GENDER_RESULTS) {
  	done = true;
    stopMorphcast();
    window.alert('Age: ' + last_age + ' - Gender: ' + last_gender);
  }
}

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

window.addEventListener(CY.modules().FACE_AGE.eventName, (evt) => {
  //last_age = getArgMaxKey(evt.detail.output.age); 
  last_age = evt.detail.output.numericAge; //  for numeric age
  console.log('Age result', last_age);
  age_results++;
  check_results();
});

window.addEventListener(CY.modules().FACE_GENDER.eventName, (evt) => {
  last_gender = getArgMaxKey(evt.detail.output.gender);
  console.log('Gender result', last_gender);
  gender_results++;
  check_results();
});