File size: 4,248 Bytes
011f1af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { getModelOption, normalizeOptions, TRANSFORMERS_VERSION } from './models.js';

let libraryPromise;
let active = null;

async function getLibrary() {
  // Lazy loading keeps the page usable even when the model CDN cannot be reached.
  libraryPromise ??= import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.2.0')
    .catch(error => { libraryPromise = null; throw error; });
  const library = await libraryPromise;
  library.env.allowLocalModels = false;
  library.env.useBrowserCache = true;
  library.env.backends.onnx.wasm.numThreads = 1;
  return library;
}

async function loadCaptioner(option, report) {
  if (active?.key === option.key) return active;
  if (active) {
    await (active.pipeline ?? active.model).dispose();
    active = null;
  }
  report({ phase: 'library' });
  const lib = await getLibrary();
  const settings = {
    revision: option.revision, dtype: 'q8', device: 'wasm',
    // The old ViT-GPT2 quantized decoder hits an ORT 1.26 QDQ optimizer error.
    // Keep its original graph; other models use the default optimizer.
    ...(option.key === 'vit' ? { session_options: { graphOptimizationLevel: 'disabled' } } : {}),
    progress_callback: progress => report({ phase: 'download', ...progress }),
  };
  if (option.key === 'vit') {
    const pipeline = await lib.pipeline('image-to-text', option.modelId, settings);
    active = { key: option.key, pipeline, lib };
  } else {
    // Load sequentially so a processor failure does not leave a large model allocated.
    const processor = await lib.AutoProcessor.from_pretrained(option.modelId, { revision: option.revision });
    const Model = option.key === 'florence' ? lib.Florence2ForConditionalGeneration : lib.AutoModelForImageTextToText;
    const model = await Model.from_pretrained(option.modelId, settings);
    active = { key: option.key, processor, model, lib };
  }
  return active;
}

export async function captionImage(imageUrl, options, report = () => {}) {
  const config = normalizeOptions(options);
  const option = getModelOption(config.modelKey);
  const began = performance.now();
  const engine = await loadCaptioner(option, report);
  const loaded = performance.now();
  report({ phase: 'generate' });
  const generation = { max_new_tokens: config.maxTokens, do_sample: false, num_beams: 1 };
  let text;
  if (option.key === 'vit') {
    const output = await engine.pipeline(imageUrl, generation);
    text = output[0]?.generated_text;
  } else {
    const image = await engine.lib.RawImage.read(imageUrl);
    if (option.key === 'florence') {
      const prompts = engine.processor.construct_prompts(config.task);
      const inputs = await engine.processor(image, prompts);
      const ids = await engine.model.generate({ ...inputs, ...generation });
      const raw = engine.processor.batch_decode(ids, { skip_special_tokens: false })[0];
      const parsed = engine.processor.post_process_generation(raw, config.task, image.size);
      text = parsed[config.task];
    } else {
      const messages = [{ role: 'user', content: [{ type: 'image' }, { type: 'text', text: config.instruction }] }];
      const prompt = engine.processor.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
      const inputs = await engine.processor(prompt, image);
      const ids = await engine.model.generate({ ...inputs, ...generation });
      // Decoder-only output contains the input prompt; export only newly generated tokens.
      const generated = ids.tolist()[0].slice(inputs.input_ids.dims[1]);
      text = engine.processor.batch_decode([generated], { skip_special_tokens: true })[0];
    }
  }
  if (typeof text !== 'string' || !text.trim()) throw new Error('The model returned an empty caption. Try another image or a higher token limit.');
  const ended = performance.now();
  return {
    caption: text.trim(), model: option.label, modelId: option.modelId, revision: option.revision,
    library: `Transformers.js ${TRANSFORMERS_VERSION}`, device: 'wasm', dtype: 'q8',
    graphOptimization: option.key === 'vit' ? 'disabled' : 'default',
    config, generation, loadSeconds: (loaded - began) / 1000,
    generationSeconds: (ended - loaded) / 1000, totalSeconds: (ended - began) / 1000,
  };
}