npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

teachable-machine.js

v2.0.2

Published

A robust and optimized JavaScript library for integrating Google's Teachable Machine models, supporting various image sources and providing efficient classification capabilities.

Maintainers

nixautservicesnixautservices

Keywords

teachable machinetensorflow.jsmachine learningimage classificationaijavascriptnodejsbunjsdeep learningmodel inferencecomputer visionneural networksweb developmentbackendfrontenddata scienceartificial intelligencemodel deploymentimage processingsharpgotfs/promisesbase64httplocal filespredictionclassificationoptimizedefficientscalablerobustapisdkutilitylibraryopen sourceapache-2.0nixautmlopsmodel servinginference enginejavascript libraryteachablemachineimage recognitionpattern recognitiondata processingreal-time inferenceserver-side javascriptedge computingmodel optimizationperformanceaccuracydeveloper toolscode exampletutorialgetting startedquick startmodel loadingimage decodingtensor operationsdispose modelmemory managementerror handlingasync awaites modulesmodern javascriptbest practicesproduction readycross-platformcloud deploymentlocal executionmodel trainingcustom modelspre-trained modelstransfer learningcomputer vision tasksimage analysisobject detectionimage understandingmachine intelligenceintelligent applicationssmart systemsautomationdata analysispredictive analyticsmodel managementresource managementjavascript ecosystemnpm packagebun packagemoduletypescript compatibletype definitionsdeclarationsdocumentationexamplesuse casessolutionframework agnosticflexibleextensiblehigh performancelow latencyresource efficientproduction gradeenterprise readycommunity drivenactive developmentstable releaseversion controlgitgithubci/cdtestingunit testsintegration testse2e testscode qualitylintingformattingprettiereslintwebpackrollupparcelbundlertranspilerbabeltypescriptflowstatic analysiscode reviewcontributionscontributing guideissue trackerbug reportsfeature requestsroadmapchangelogrelease notessecurity auditvulnerability managementcompliancelicensinglegalterms of useprivacy policycode of conductcommunity guidelinessupportfaqtroubleshootingdebuggingperformance tuningoptimization techniquesmemory optimizationcpu optimizationgpu accelerationwebglwebgpuwasmwebassemblybrowser compatibilityserver compatibilityenvironment setupinstallation guideusage guideapi referenceclass documentationmethod documentationparameter descriptionsreturn valuesexceptionserror codesbest practices guidedesign patternsarchitectural patternssoftware engineeringdevelopment workflowproject structurefile organizationmodule systemimport exportcommonjsesmpackage managernpmyarnbundependency managementlock filessemantic versioningrelease processcontinuous integrationcontinuous deliveryautomated testingtest driven developmentbehavior driven developmentrefactoringcode maintenancetechnical debtcode review processpull requestsmerge requestsversion control systemgit commandsbranching strategyrelease strategyhotfixespatchesmajor releasesminor releasespatch releasesdeprecation policybackward compatibilityforward compatibilitymigration guideupgrade guidedowngrade guidebreaking changesnon-breaking changesnew featuresbug fixesimprovementsrefactoringsdocumentation updatesexample updatestest updatesbuild systemtask runnerscriptingautomation scriptsdeployment scriptsconfiguration filesenvironment variablessecrets managementcredential managementsecurity best practicesvulnerability scanningpenetration testingsecurity patchescompliance standardsdata privacygdprccpahipaaiso 27001soc 2nistowaspthreat modelingrisk assessmentincident responsedisaster recoverybusiness continuitybackup strategyrecovery strategymonitoringloggingalertingobservabilitytelemetrymetricstracingprofilingperformance monitoringerror trackinguptime monitoringhealth checksload balancingauto-scalingcontainerizationdockerkubernetesserverlessaws lambdaazure functionsgoogle cloud functionscloud computingdevopssite reliability engineeringsreplatform engineeringinfrastructure as codeterraformansiblepuppetchefsaltstackconfiguration managementorchestrationprovisioningdeployment automationrelease automationpipeline automationci/cd pipelinesjenkinsgitlab cigithub actionsazure devopstravis cicirclecibitbucket pipelinescloud buildcodefreshspinnakerargo cdflux cdgitopsobservability stackprometheusgrafanaelk stacksplunkdatadognew relicappdynamicsdynatracesumologiclogz.iovictoropspagerdutyopsgeniealertmanagerthanoscortexmimirlokitempografana cloudaws cloudwatchazure monitorgoogle cloud monitoringopen telemetryjaegerzipkindistributed tracingservice meshistiolinkerdenvoyapi gatewaynginxhaproxytraefikkongtykapigeeaws api gatewayazure api managementgoogle cloud api gatewaymessage queuerabbitmqkafkaactivemqzeromqredismemcacheddatabasepostgresqlmysqlmongodbcassandracouchbasedynamodbcosmosdbbigtablespannercockroachdbyugabytedbtimescaledbinfluxdbelasticsearchsolropensearchvector databasepineconeweaviateqdrantmilvusfaisschromalangchainllama indexgenerative ailarge language modelsllmstransformershugging faceopenaigoogle aianthropiccoherereplicaterunpodvast.aigpu cloudai infrastructureml infrastructuredata infrastructuredata pipelineetleltdata warehousingdata lakedata lakehousedata meshdata fabricdata governancedata qualitydata securitydata privacydata catalogmetadata managementdata lineagedata observabilitydata reliabilitydata validationdata transformationdata loadingdata ingestionstreaming databatch datareal-time dataevent driven architecturemicroservicesserverless architecturemonolithic architecturedistributed systemsfault toleranceresiliencescalability patternsdesign patternsarchitectural patternssoftware architecturesystem designsolution architectureenterprise architecturetechnical leadershipteam managementproject managementagilescrumkanbanleandevops culturesre cultureplatform cultureengineering excellenceinnovationresearch and developmentproof of conceptprototypeminimum viable productmvpproduct developmentsoftware development life cyclesdlcrequirements gatheringdesign phaseimplementation phasetesting phasedeployment phasemaintenance phaseretirement phasepost-mortem analysisroot cause analysisproblem solvingdecision makingcritical thinkinganalytical skillscommunication skillsteamworkcollaborationmentoringcoachingleadershipstrategic planningtactical executionoperational excellenceprocess improvementautomationefficiencyproductivitycost optimizationresource allocationbudget managementvendor managementstakeholder managementrisk managementcompliance managementsecurity managementquality assurancetesting strategiestest automationtest frameworksjestmochachaicypressplaywrightseleniumpuppeteerweb scrapingdata extractionweb crawlingapi integrationthird party servicesexternal apissdk developmentlibrary developmentframework developmenttoolingdeveloper experiencedxcli toolside extensionspluginsintegrationsecosystemcommunityopen source contributioncontributor guidelinescode of conductgovernanceroadmapfuture plansvisionmissionvaluescultureteam buildingrecruitmentonboardingtrainingskill developmentcareer growthperformance reviewsfeedbackrecognitionrewardscompensationbenefitswork-life balanceremote workhybrid workoffice culturediversityequityinclusionbelongingpsychological safetytrusttransparencyaccountabilityownershipautonomymasterypurposemotivationengagementsatisfactionhappinesswell-beingmental healthphysical healthstress managementburnout preventionresilience buildingpersonal developmentprofessional developmentlearninggrowth mindsetcontinuous learninglifelong learningknowledge sharingmentorshipcoachingpeer learningcommunity of practiceguildschaptersforumsmeetupsconferencesworkshopsbootcampsonline coursescertificationsdegreeshigher educationresearchpublicationspatentsintellectual propertyinnovation managementproduct innovationprocess innovationbusiness model innovationdisruptive innovationsustaining innovationincremental innovationradical innovationopen innovationco-creationcrowdsourcingdesign thinkinguser experience designuxuser interface designuiinteraction designinformation architectureusability testingaccessibility testingperformance testingsecurity testingload testingstress testingchaos engineeringsite reliabilitysystem reliabilityapplication reliabilityservice reliabilitydata reliabilitynetwork reliabilityinfrastructure reliabilitycloud reliabilityon-premise reliabilityhybrid cloud reliabilitymulti-cloud reliabilityedge reliabilityiot reliabilitymobile reliabilityweb reliabilitydesktop reliabilityembedded reliabilityfirmware reliabilityhardware reliabilitysoftware reliabilitysystem resilienceapplication resilienceservice resiliencedata resiliencenetwork resilienceinfrastructure resiliencecloud resilienceon-premise resiliencehybrid cloud resiliencemulti-cloud resilienceedge resilienceiot resiliencemobile resilienceweb resiliencedesktop resilienceembedded resiliencefirmware resiliencehardware resiliencesoftware resiliencedisaster recovery planningbusiness continuity planningincident managementproblem managementchange managementrelease managementconfiguration managementasset managementservice level agreementsslasservice level objectivesslosservice level indicatorssliserror budgetpost-incident reviewblameless post-mortemslearning from incidentsknowledge baserunbooksplaybooksautomation scriptsself-healing systemsself-optimizing systemsself-configuring systemsself-managing systemsautonomous systemsintelligent automationai opsml opsdevsecopsfinopsgreen itsustainable softwareethical airesponsible aiai governanceai ethicsai safetyai fairnessai transparencyai accountabilityai explainabilityxaiinterpretable aitrustworthy aihuman-centered aiai for goodai for social impactai for sustainabilityai for healthcareai for financeai for retailai for manufacturingai for automotiveai for educationai for entertainmentai for gamingai for artai for musicai for writingai for codingai for designai for marketingai for salesai for customer serviceai for hrai for legalai for researchai for scienceai for engineeringai for operationsai for supply chainai for logisticsai for agricultureai for energyai for environmentai for smart citiesai for smart homesai for roboticsai for dronesai for autonomous vehiclesai for space explorationai for cybersecurityai for fraud detectionai for risk managementai for complianceai for governanceai for auditai for forensicsai for investigationsai for intelligenceai for defenseai for national securityai for public safetyai for emergency servicesai for disaster managementai for humanitarian aidai for social goodai for economic developmentai for poverty reductionai for education accessai for healthcare accessai for financial inclusionai for digital literacyai for digital transformationai for business transformationai for organizational transformationai for societal transformationai for global challengesai for sustainable development goalsai for un goalsai for climate actionai for biodiversityai for clean energyai for clean waterai for sanitationai for zero hungerai for good health and well-beingai for quality educationai for gender equalityai for clean water and sanitationai for affordable and clean energyai for decent work and economic growthai for industry, innovation and infrastructureai for reduced inequalitiesai for sustainable cities and communitiesai for responsible consumption and productionai for climate actionai for life below waterai for life on landai for peace, justice and strong institutionsai for partnerships for the goals

Readme

teachable-machine.js

Ultra‑fast, production‑ready Teachable Machine inference for Node.js with smart RAM/Disk I/O, unified Image & Video classification, and optional native backend acceleration.

Repo: https://github.com/nixaut-codelabs/teachable-machine.js • NPM: teachable-machine.js

Highlights

  • Ultra fast classification — batched inference, turbo mode, and optional native backend (@tensorflow/tfjs-node).
  • Smart resource management — in‑memory (RAM) pipeline by default, automatic disk fallback, strict cleanup guarantees.
  • Video classification (FFmpeg) — sample frames evenly via FFmpeg; supports MP4, GIF, and more.
  • Backend control — choose between pure tfjs and tfjs-node (native TensorFlow) for best performance.
  • Detailed parameters & outputs — timings, backend, I/O mode (RAM/Disk), size limits, fallback, and cleanup status.
  • Unified API — classify images and videos through a single, ergonomic interface.
  • Flexible inputs — URLs, local paths, Buffers/Uint8Arrays, data URIs, and base64 strings.

Author: Nixaut • License: Apache‑2.0


Installation

Install from NPM:

npm i teachable-machine.js
# or
bun add teachable-machine.js

This library relies on:

  • @tensorflow/tfjs (installed transitively)
  • sharp for image decoding/resizing
  • ffmpeg-static for bundled FFmpeg (or use system FFmpeg via PATH)

Optional (highly recommended for speed):

npm i @tensorflow/tfjs-node
# or
bun add @tensorflow/tfjs-node

Note: When you pass backend: 'tfjs-node' the library will try to use the native backend (tensorflow) for a large CPU speedup.


Quick Start

import TeachableMachine from 'teachable-machine.js';

const tm = await TeachableMachine.create({
  modelUrl: 'https://teachablemachine.withgoogle.com/models/your-model-id/',
  saveToDir: 'model',      // optional: cache locally
  loadFrom: 'auto',        // 'auto'|'dir'
  warmup: true,            // run one warmup forward pass
  ioMode: 'ram',           // 'ram' (default) | 'disk'
  backend: 'tfjs-node',    // 'tfjs' (default) | 'tfjs-node'
  preprocessUseWorkers: true // offload sharp preprocess to Worker Threads
});

// Single image
const img = await tm.classify({ input: 'local_or_url_or_buffer.jpg', mediaType: 'image' });
console.log(img.predictions);

// Batch images
const imgs = await tm.classifyImages({ images: ['1.jpg', '2.jpg'], batchSize: 2 });
console.log(imgs.results[0].predictions);

// Single video (mp4/gif)
const vid = await tm.classify({ input: 'video.mp4', mediaType: 'video', frames: 8, turboMode: true });
console.log(vid.aggregate.predictions);

// Batch videos
const vids = await tm.classifyVideos({ videos: ['a.mp4', 'b.gif'], frames: 8 });
console.log(vids[0].aggregate.predictions);

// Mixed: images + videos together
const mixed = await tm.classify({
  input: { images: ['1.jpg', '2.jpg'], videos: ['a.mp4', 'b.gif'] },
  frames: 8,
  turboMode: true
});
console.log(mixed.images?.results?.length, mixed.videos?.length);

tm.dispose();

CLI (tmjs)

After installation, you can quickly try it from the terminal:

# Single image
tmjs --model https://teachablemachine.withgoogle.com/models/XXX/ image.jpg

# Video + GIF with turbo and frame count
tmjs --model ./model --media video --frames 8 --turbo video.mp4 gif.gif

Arguments:

  • --model <url|dir>: Model source (URL or local directory)
  • --backend tfjs|tfjs-node: Backend selection
  • --io ram|disk: I/O mode
  • --media image|video|auto: Input type routing
  • --frames N, --topK K, --maxBytes BYTES, --turbo

Output is printed as JSON to stdout; suitable for CI and automation.


Why this library?

  • Ultra fast classification
    • Image turbo batching and video turbo mode (preprocess tensors + single batched forward).
    • Optional @tensorflow/tfjs-node backend for native CPU acceleration.
  • Smart resource management
    • Default in‑RAM pipeline avoids disk I/O.
    • Automatic fallback to disk when RAM extractor yields no frames.
    • Guaranteed temp cleanup on success and failure.
    • Optional Worker Threads (preprocessUseWorkers: true) separate preprocessing from the main thread.
  • Video classification (FFmpeg)
    • Frame sampling via FFmpeg with robust single‑pass PNG pipeline.
    • GIFs supported the same way.
  • Backend control
    • backend: 'tfjs' | 'tfjs-node' on model creation.
  • Detailed diagnostics
    • Outputs include backend, timings for each stage, I/O mode, fallback flag, sizeBytes/maxBytes.

API

TeachableMachine.create(options)Promise<TeachableMachine>

Options:

  • modelUrl?: string — Teachable Machine base URL (ends with /).
  • modelDir?: string — directory containing a cached model.
  • loadFrom?: 'auto'|'dir' — auto prefer local dir when available.
  • saveToDir?: string — if provided, downloads and caches the model locally.
  • warmup?: boolean — run one forward pass on zeros (default true).
  • ioMode?: 'ram'|'disk' — RAM mode uses in‑memory pipeline; disk uses temp files.
  • backend?: 'tfjs'|'tfjs-node' — select JS vs native backend at init.
  • preprocessUseWorkers?: boolean — run sharp-based preprocessing in Worker Threads (keeps CPU-heavy work off the main thread).

Returns an instance with methods below.

Image classification

  • classifyImages({ images, topK?, centerCrop=true, resizeOnCPU=true, batchSize? })
    • images: single input or array (string | Buffer | Uint8Array | data URI | base64).
    • Returns either a single detailed result or a batch summary { count, timings, results }.

Video classification

  • classifyVideos({ videos, frames=10, topK?, centerCrop=true, resizeOnCPU=true, turboMode=false, extractionConcurrency?, preprocessConcurrency?, maxConcurrent=2, maxBytes=10*MB })
    • videos: single input or array.
    • Returns per‑video detailed outputs with frame predictions and aggregate.predictions.

Unified classification

  • classify({ input, mediaType='auto', frames=10, topK?, centerCrop=true, resizeOnCPU=true, turboMode=false, extractionConcurrency?, preprocessConcurrency?, maxConcurrent=2, maxBytes=10*MB, batchSize? })
    • If input is an array or scalar, the route is chosen by mediaType and frames.
    • If input is { images, videos }, both branches run and return { images, videos }.

Compatibility helper

  • classifyBatch({ imageUrls, ... }) — original batch images API.
  • batchImageClassify(opts) — alias to classifyBatch().

Lifecycle

  • dispose() — free model resources.

TypeScript

The package ships with a .d.ts type file. Key types:

  • CreateOptions
  • ImageResult, BatchImageResult
  • VideoResult, FramePrediction

Example:

import TeachableMachine, { CreateOptions, VideoResult } from 'teachable-machine.js';

const opts: CreateOptions = { backend: 'tfjs-node', preprocessUseWorkers: true };
const tm = await TeachableMachine.create(opts);

I/O Modes, Size Limits, and Cleanup

  • ioMode: 'ram' | 'disk' on .create()
    • RAM: No temp files; streams media into memory buffers.
    • Disk: Uses temp files; always cleaned up in finally.
  • Size limits
    • maxBytes on video classification to prevent oversized inputs.
  • Output io object
    • { mode, fallbackToDisk, tempCleaned, sizeBytes, maxBytes } for audits & debugging.

Performance tips

  • Use backend: 'tfjs-node' for large CPU speedups (server/desktop).
  • Enable turboMode for videos to preprocess frames and run a single batched forward pass.
  • Use batchSize on images for better throughput.
  • Tune extractionConcurrency and preprocessConcurrency to match CPU cores.

FFmpeg requirements

Video/GIF classification requires FFmpeg.

  • Bundled: ffmpeg-static is used if present.
  • System: Otherwise a system ffmpeg binary on PATH is used.

We include a small diagnostic helper internally that prefers ffmpeg-static and falls back to system PATH.


Examples

See advanced-example.js for a comprehensive demo with environment toggles:

  • BACKEND=tfjs-node or tfjs
  • IO_MODE=ram or disk
  • FRAMES=8, TURBO=true, MAX_BYTES=10485760

Run with Bun:

bun run advanced-example.js

Contributing

PRs are welcome! Please open an issue to discuss substantial changes first.


License

This project is licensed under the Apache-2.0 License. See the LICENSE file for details.