import { getModelOption, normalizeOptions, TRANSFORMERS_VERSION } from './models.js'; let libraryPromise; // Keep every captioner loaded so the side-by-side view can rerun one column // without re-initializing a model. Stopping the worker releases them all. const captioners = new Map(); 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 (captioners.has(option.key)) return captioners.get(option.key); 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 }), }; let engine; if (option.key === 'vit') { const pipeline = await lib.pipeline('image-to-text', option.modelId, settings); engine = { 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); engine = { key: option.key, processor, model, lib }; } captioners.set(option.key, engine); return engine; } 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, }; }