11import { pipeline } from "@huggingface/transformers" ;
2+ import handleArguments from "../utils/handleArguments" ;
23
4+ /**
5+ * @reference https://huggingface.co/docs/transformers.js/en/api/pipelines#module_pipelines.ImageClassificationPipeline
6+ */
37export class ImageClassifierTransformer {
48 constructor ( options , callback ) {
59 this . classifier = null ;
@@ -16,18 +20,30 @@ export class ImageClassifierTransformer {
1620 } ) ;
1721 }
1822
19- async classify ( input , callback ) {
20- if ( this . isClassifying ) return ;
21- if ( ! this . classifier ) return ;
23+ async classify ( inputNumOrCallback , numOrCallback , cb ) {
24+ if ( this . isClassifying || ! this . classifier ) return ;
2225 this . isClassifying = true ;
23- const results = await this . classifier ( input ) ;
24- callback ( results ) ;
26+ const { image, number, callback } = handleArguments (
27+ inputNumOrCallback ,
28+ numOrCallback ,
29+ cb
30+ ) . require (
31+ "image" ,
32+ "No input image provided. If you want to classify a video, use classifyStart."
33+ ) ;
34+ const options = number !== undefined ? { top_k : number } : { } ;
35+ const results = await this . classifier ( image , options ) ;
36+ const normalized = results . map ( ( result ) => ( {
37+ label : result . label ,
38+ confidence : result . score ,
39+ } ) ) ;
40+ callback ( normalized ) ;
2541 this . isClassifying = false ;
42+ return normalized ;
2643 }
2744
2845 async classifyStart ( input , callback ) {
29- if ( this . isClassifying ) return ;
30- if ( ! this . classifier ) return ;
46+ if ( this . isClassifying || ! this . classifier ) return ;
3147 this . needToStop = false ;
3248 const next = ( ...args ) => {
3349 if ( this . needToStop ) return ;
0 commit comments