Back

Step by Step Guide to Building a Teachable API Integration in JS

Aug 11, 20245 minute read

Introduction

Hey there, fellow code enthusiasts! Ready to dive into the world of machine learning without breaking a sweat? Let's talk about Teachable Machine and its nifty API. We're going to use the @sashido/teachablemachine-node package to make magic happen in JavaScript. Buckle up!

Prerequisites

Before we jump in, make sure you've got:

  • A Node.js environment up and running
  • Some JavaScript chops (especially with async/await)

Don't sweat it if you're not an expert – we'll walk through this together!

Installation

First things first, let's get our hands on that sweet @sashido/teachablemachine-node package:

npm install @sashido/teachablemachine-node

Easy peasy, right?

Setting up the project

Time to get our project off the ground:

  1. Initialize a new Node.js project:

    npm init -y
  2. Create your main JavaScript file (let's call it index.js):

    touch index.js

Importing and configuring the package

Open up index.js and let's start cooking:

const { TeachableMachine } = require('@sashido/teachablemachine-node'); const model = new TeachableMachine({ modelUrl: 'YOUR_MODEL_URL_HERE' });

Replace YOUR_MODEL_URL_HERE with the URL of your trained model. You got this!

Loading the model

Let's create an async function to load our model:

async function loadModel() { try { await model.load(); console.log('Model loaded successfully!'); } catch (error) { console.error('Error loading model:', error); } }

Making predictions

Now for the fun part – let's classify some images:

async function classifyImage(imageUrl) { try { const predictions = await model.classify({ imageUrl: imageUrl }); console.log('Predictions:', predictions); return predictions; } catch (error) { console.error('Error classifying image:', error); } }

Error handling and best practices

Notice how we're using try-catch blocks? Always handle your errors gracefully – your future self will thank you!

Example use cases

Let's put our code to work:

async function main() { await loadModel(); await classifyImage('https://example.com/image.jpg'); } main();

Want to level up? Try continuous prediction on video frames!

Performance optimization

Pro tip: Cache your model results and consider batch processing for a speed boost. Your users will love the snappy responses!

Conclusion

And there you have it, folks! You've just built a Teachable API integration in JS. Pretty cool, huh? Remember, this is just the beginning – there's a whole world of machine learning out there waiting for you to explore.

Resources

Want to dive deeper? Check out:

Got questions? The community's got your back. Don't be shy – reach out and keep learning!

Now go forth and build something awesome. You've got this! 🚀