Skip to content

Instantly share code, notes, and snippets.

@louis030195
Created September 2, 2023 23:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louis030195/cc31a886b178c39afe367085f8ac07f1 to your computer and use it in GitHub Desktop.
Save louis030195/cc31a886b178c39afe367085f8ac07f1 to your computer and use it in GitHub Desktop.
const createJob = async (image) => {
const url = 'https://api.hume.ai/v0/batch/jobs';
const formData = new FormData();
formData.append('file', image);
const response = await fetch(url, {
method: 'POST',
headers: {
'X-Hume-Api-Key': process.env.HUME_API_KEY,
'Accept': 'application/json',
},
body: formData
});
if (!response.ok) {
const errorResponse = await response.text();
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
const getJob = async (jobId) => {
const url = `https://api.hume.ai/v0/batch/jobs/${jobId}/predictions`;
const response = await fetch(url, {
method: 'GET',
headers: {
'X-Hume-Api-Key': process.env.HUME_API_KEY,
'accept': 'application/json; charset=utf-8',
},
});
if (!response.ok) {
const errorResponse = await response.text();
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
const pollJob = async (jobId) => {
return new Promise((resolve, reject) => {
const interval = setInterval(async () => {
const jobResult = await getJob(jobId).catch((e) => ({ status: 400 }));
if (jobResult.status === 400) {
console.log('Job is still queued. Keep polling...');
} else if (jobResult?.[0]?.results?.predictions?.[0]?.models?.language?.grouped_predictions) {
clearInterval(interval);
resolve(jobResult);
}
}, 1000);
});
}
const processJob = async (image) => {
try {
const job = await createJob(image);
const result = await pollJob(job.job_id);
const topEmotions = result[0].results.predictions[0].models.language.grouped_predictions[0].predictions[0].emotions.sort((a, b) => b.score - a.score).slice(0, 3);
console.log(topEmotions);
} catch (error) {
console.error(error);
}
}
processJob('louis.jpg');
processJob('louis2.jpg');
processJob('louis3.png');
processJob('louis4.jpg');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment