File size: 2,076 Bytes
7bf5f68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.2.0';

export const MODEL_OPTIONS = [
  {
    key: 'resnet18',
    label: 'ResNet-18',
    modelId: 'Xenova/resnet-18',
    task: 'image-classification',
    note: 'Recommended classroom default: a compact CNN with 1,000 ImageNet labels.',
    dtype: 'q8',
  },
  {
    key: 'vit',
    label: 'ViT-B/16',
    modelId: 'Xenova/vit-base-patch16-224',
    task: 'image-classification',
    note: 'A Vision Transformer that compares patterns across image patches.',
    dtype: 'q8',
  },
  {
    key: 'clip',
    label: 'CLIP ViT-B/32',
    modelId: 'Xenova/clip-vit-base-patch32',
    task: 'zero-shot-image-classification',
    note: 'A vision-language model that ranks your own candidate descriptions.',
    dtype: 'q8',
  },
];

const classifierCache = new Map();

export function getModelOption(key) {
  return MODEL_OPTIONS.find((model) => model.key === key) || MODEL_OPTIONS[0];
}

export async function loadClassifier(modelKey, progressCallback) {
  const option = getModelOption(modelKey);
  if (classifierCache.has(option.key)) return classifierCache.get(option.key);

  const classifier = await pipeline(option.task, option.modelId, {
    dtype: option.dtype,
    progress_callback: progressCallback,
  });

  classifierCache.set(option.key, classifier);
  return classifier;
}

export async function classifyImage(imageDataUrl, options = {}) {
  const modelKey = options.modelKey || MODEL_OPTIONS[0].key;
  const topK = Number.isFinite(options.topK) ? options.topK : 5;
  const option = getModelOption(modelKey);
  const classifier = await loadClassifier(modelKey, options.progressCallback);

  let predictions;
  if (option.task === 'zero-shot-image-classification') {
    predictions = await classifier(imageDataUrl, options.candidateLabels, {
      hypothesis_template: 'a photo of {}',
    });
  } else {
    predictions = await classifier(imageDataUrl, { top_k: topK });
  }

  return [...predictions]
    .sort((a, b) => Number(b.score) - Number(a.score))
    .slice(0, topK);
}