File size: 2,476 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
export const TRANSFORMERS_VERSION = '4.2.0';
export const MODEL_OPTIONS = Object.freeze([
  {
    key: 'vit', label: 'ViT-GPT2',
    modelId: 'Xenova/vit-gpt2-image-captioning',
    revision: '215b4edcb7ec1fad5905a18a03f7b2007f6fabd0',
    note: 'Start here: a visual encoder and a language decoder generate a short caption.',
    detailNote: 'This model generates a short caption. Use Florence-2 or SmolVLM to change the description style.',
  },
  {
    key: 'florence', label: 'Florence-2 Base',
    modelId: 'onnx-community/Florence-2-base-ft',
    revision: 'e88a44eaf3791a35eae0c5a47b3dbcd36e67eb6f',
    note: 'A vision-language model with task prompts for short and detailed descriptions.',
    detailNote: 'Short and detailed styles use the model’s corresponding captioning task prompts.',
  },
  {
    key: 'smol', label: 'SmolVLM 256M',
    modelId: 'HuggingFaceTB/SmolVLM-256M-Instruct',
    revision: '7e3e67edbbed1bf9888184d9df282b700a323964',
    note: 'A compact instruction-following model. Explore how the wording of your request changes the description.',
    detailNote: 'Choose a style to fill in an instruction, or write your own request below.',
  },
]);

export function getModelOption(key) {
  const model = MODEL_OPTIONS.find(item => item.key === key);
  if (!model) throw new Error('Unknown captioning model.');
  return model;
}

export function defaultInstruction(style) {
  return style === 'detailed'
    ? 'Describe the visible objects, actions, and relationships in this image in a few sentences.'
    : 'Describe this image in one short sentence.';
}

export function normalizeOptions(options) {
  const model = getModelOption(options.modelKey);
  const maxTokens = Number(options.maxTokens);
  if (!Number.isInteger(maxTokens) || maxTokens < 32 || maxTokens > 128) throw new Error('Choose an output limit from 32 to 128 tokens.');
  if (!['short', 'detailed'].includes(options.style)) throw new Error('Choose a valid description style.');
  const style = model.key === 'vit' ? 'short' : options.style;
  const instruction = String(options.instruction ?? '').trim();
  if (model.key === 'smol' && (!instruction || instruction.length > 400)) throw new Error('Enter an instruction between 1 and 400 characters.');
  return {
    modelKey: model.key, maxTokens, style,
    instruction: model.key === 'smol' ? instruction : null,
    task: model.key === 'florence' ? (style === 'short' ? '<CAPTION>' : '<MORE_DETAILED_CAPTION>') : null,
  };
}