Views
No views yet
[!IMPORTANT] NOTE: Florence-2 support is experimental and requires you to install Transformers.js v3 from source.
npm install xenova/transformers.js#v3onnx-community/Florence-2-large.1import {
2 Florence2ForConditionalGeneration,
3 AutoProcessor,
4 AutoTokenizer,
5 RawImage,
6} from '@xenova/transformers';
7
8// Load model, processor, and tokenizer
9const model_id = 'onnx-community/Florence-2-large';
10const model = await Florence2ForConditionalGeneration.from_pretrained(model_id, {
11 dtype: {
12 embed_tokens: 'fp16', // or 'fp32'
13 vision_encoder: 'fp16', // or 'fp32'
14 encoder_model: 'q4',
15 decoder_model_merged: 'q4',
16 },
17});
18const processor = await AutoProcessor.from_pretrained(model_id);
19const tokenizer = await AutoTokenizer.from_pretrained(model_id);
20
21// Load image and prepare vision inputs
22const url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/car.jpg';
23const image = await RawImage.fromURL(url);
24const vision_inputs = await processor(image);
25
26// Specify task and prepare text inputs
27const task = '<MORE_DETAILED_CAPTION>';
28const prompts = processor.construct_prompts(task);
29const text_inputs = tokenizer(prompts);
30
31// Generate text
32const generated_ids = await model.generate({
33 ...text_inputs,
34 ...vision_inputs,
35 max_new_tokens: 256,
36});
37
38// Decode generated text
39const generated_text = tokenizer.batch_decode(generated_ids, { skip_special_tokens: false })[0];
40
41// Post-process the generated text
42const result = processor.post_process_generation(generated_text, task, image.size);
43console.log(result);
44// { '<MORE_DETAILED_CAPTION>': 'The image shows a vintage Volkswagen Beetle car parked on a cobblestone street in front of a yellow building with two wooden doors. The car is a bright turquoise color and has a classic design with a round body and a sloping roofline. It has two doors on either side of the car, one on the left side and one in the center, with a brown door on the right side. The doors are made of wood and have a rustic, weathered look. The building behind the car is painted in a light yellow color and appears to be old and dilapidated. The sky is blue and there are trees in the background. The image is taken from a low angle, looking up at the car and the building.' }onnx).