File size: 3,809 Bytes
7bf5f68
 
 
 
 
 
 
 
c8b18eb
7bf5f68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8b18eb
7bf5f68
 
ce7ca2d
 
 
 
 
c8b18eb
ce7ca2d
 
7bf5f68
 
 
 
 
 
 
 
3d40d64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf5f68
 
3d40d64
7bf5f68
 
 
c8b18eb
7bf5f68
 
 
 
 
 
 
 
 
 
 
3d40d64
 
 
 
7bf5f68
 
 
 
3d40d64
7bf5f68
 
ce7ca2d
3d40d64
ce7ca2d
 
 
7bf5f68
3d40d64
7bf5f68
 
 
 
 
3d40d64
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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: '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 candidate descriptions.',
    dtype: 'q8',
  },
  {
    key: 'rtdetr-r18',
    label: 'RT-DETR R18',
    modelId: 'onnx-community/rtdetr_r18vd',
    task: 'object-detection',
    note: 'A browser-compatible object detector packaged for Transformers.js.',
    dtype: 'q8',
  },
];

const classifierCache = new Map();

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

function getSelectedBlurPixels() {
  const slider = document.getElementById('blur-range');
  if (!slider) return 0;
  const value = Number(slider.value);
  return Number.isFinite(value) ? Math.min(50, Math.max(0, value)) : 0;
}

async function applyBlurToImageDataUrl(imageDataUrl, blurPixels) {
  if (blurPixels <= 0) return imageDataUrl;

  const image = new Image();
  image.decoding = 'async';
  image.src = imageDataUrl;
  await image.decode();

  const canvas = document.createElement('canvas');
  canvas.width = image.naturalWidth || image.width;
  canvas.height = image.naturalHeight || image.height;

  const context = canvas.getContext('2d');
  if (!context) throw new Error('Canvas is unavailable for blur preprocessing.');

  // Expand the draw area so the blur does not create transparent edge pixels.
  const padding = Math.ceil(blurPixels * 2);
  context.filter = `blur(${blurPixels}px)`;
  context.drawImage(
    image,
    -padding,
    -padding,
    canvas.width + padding * 2,
    canvas.height + padding * 2,
  );

  return canvas.toDataURL('image/jpeg', 0.92);
}

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,
    device: 'wasm',
    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 blurPixels = Number.isFinite(options.blurPixels)
    ? Math.min(50, Math.max(0, options.blurPixels))
    : getSelectedBlurPixels();
  const processedImageDataUrl = await applyBlurToImageDataUrl(imageDataUrl, blurPixels);
  const classifier = await loadClassifier(modelKey, options.progressCallback);

  let predictions;
  if (option.task === 'zero-shot-image-classification') {
    predictions = await classifier(processedImageDataUrl, options.candidateLabels, {
      hypothesis_template: 'a photo of {}',
    });
  } else if (option.task === 'object-detection') {
    predictions = await classifier(processedImageDataUrl, {
      threshold: options.threshold ?? 0.25,
      percentage: false,
    });
  } else {
    predictions = await classifier(processedImageDataUrl, { top_k: topK });
  }

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