fastembed 7.8.0

Library for generating vector embeddings, reranking locally.
Documentation
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use crate::common::{Error, Result};
use image::{imageops::FilterType, DynamicImage, GenericImageView};
use ndarray::{Array, Array3};
use std::ops::{Div, Sub};
#[cfg(feature = "hf-hub")]
use std::{fs::read_to_string, path::Path};

pub enum TransformData {
    Image(DynamicImage),
    NdArray(Array3<f32>),
}

impl TransformData {
    pub fn image(self) -> Result<DynamicImage> {
        match self {
            TransformData::Image(img) => Ok(img),
            _ => Err(Error::ImageTransform("TransformData convert error".into())),
        }
    }

    pub fn array(self) -> Result<Array3<f32>> {
        match self {
            TransformData::NdArray(array) => Ok(array),
            _ => Err(Error::ImageTransform("TransformData convert error".into())),
        }
    }
}

pub(crate) type ResizeFn =
    dyn Fn(DynamicImage, u32, u32, FilterType) -> Result<DynamicImage> + Send + Sync;

/// The `image` decoders allow 512 MiB for one decoded image, and each buffer of a resize keeps
/// that limit. An image that is a few pixels wide and thousands of pixels tall resizes to
/// gigabytes.
const MAX_RESIZE_BUFFER_BYTES: u64 = 512 * 1024 * 1024;

fn default_resize(
    image: DynamicImage,
    width: u32,
    height: u32,
    filter: FilterType,
) -> Result<DynamicImage> {
    // `resize_exact` allocates an RGBA f32 image of the source width and the new height, and
    // then the result.
    let bytes = |width: u32, height: u32, per_pixel: u64| {
        u64::from(width)
            .saturating_mul(u64::from(height))
            .saturating_mul(per_pixel)
    };
    let buffers = [
        bytes(image.width(), height, 16),
        bytes(width, height, u64::from(image.color().bytes_per_pixel())),
    ];
    if buffers.iter().any(|&size| size > MAX_RESIZE_BUFFER_BYTES) {
        return Err(Error::ImageTransform(format!(
            "The resize of a {}x{} image to {width}x{height} needs a buffer above 512 MiB",
            image.width(),
            image.height()
        )));
    }
    Ok(image.resize_exact(width, height, filter))
}

pub trait Transform: Send + Sync {
    fn transform(&self, data: TransformData) -> Result<TransformData> {
        self.transform_with_resize(data, &default_resize)
    }

    fn transform_with_resize(
        &self,
        data: TransformData,
        resize: &ResizeFn,
    ) -> Result<TransformData>;
}

struct ConvertToRGB;

impl Transform for ConvertToRGB {
    fn transform_with_resize(&self, data: TransformData, _: &ResizeFn) -> Result<TransformData> {
        let image = data.image()?;
        let image = image.into_rgb8().into();
        Ok(TransformData::Image(image))
    }
}

/// The `size` entry of a `preprocessor_config.json`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResizeSize {
    ShortestEdge(u32),
    Exact { width: u32, height: u32 },
}

pub struct Resize {
    pub size: ResizeSize,
    pub resample: FilterType,
}

impl Resize {
    fn target_dimensions(&self, width: u32, height: u32) -> (u32, u32) {
        match self.size {
            ResizeSize::Exact { width, height } => (width, height),
            ResizeSize::ShortestEdge(edge) => {
                let (short, long) = if width <= height {
                    (width, height)
                } else {
                    (height, width)
                };
                if short == edge {
                    return (width, height);
                }
                let scaled_long = ((edge as f64 * long as f64) / short as f64) as u32;
                if width <= height {
                    (edge, scaled_long.max(1))
                } else {
                    (scaled_long.max(1), edge)
                }
            }
        }
    }
}

impl Transform for Resize {
    fn transform_with_resize(
        &self,
        data: TransformData,
        resize: &ResizeFn,
    ) -> Result<TransformData> {
        let image = data.image()?;
        let (width, height) = image.dimensions();
        let (new_width, new_height) = self.target_dimensions(width, height);
        if (new_width, new_height) == (width, height) {
            return Ok(TransformData::Image(image));
        }
        let image = resize(image, new_width, new_height, self.resample)?;
        Ok(TransformData::Image(image))
    }
}

pub struct CenterCrop {
    pub size: (u32, u32),
}

impl Transform for CenterCrop {
    fn transform_with_resize(&self, data: TransformData, _: &ResizeFn) -> Result<TransformData> {
        let mut image = data.image()?;
        let (mut origin_width, mut origin_height) = image.dimensions();
        let (crop_width, crop_height) = self.size;
        if origin_width >= crop_width && origin_height >= crop_height {
            // cropped area is within image boundaries
            let x = (origin_width - crop_width) / 2;
            let y = (origin_height - crop_height) / 2;
            let image = image.crop_imm(x, y, crop_width, crop_height);
            Ok(TransformData::Image(image))
        } else {
            if origin_width > crop_width || origin_height > crop_height {
                let (new_width, new_height) =
                    (origin_width.min(crop_width), origin_height.min(crop_height));
                let (x, y) = if origin_width > crop_width {
                    ((origin_width - crop_width) / 2, 0)
                } else {
                    (0, (origin_height - crop_height) / 2)
                };
                image = image.crop_imm(x, y, new_width, new_height);
                (origin_width, origin_height) = image.dimensions();
            }
            let mut pixels_array =
                Array3::zeros((3usize, crop_height as usize, crop_width as usize));
            // transformers puts `ceil(padding / 2)` before the image.
            let offset_x = (crop_width - origin_width).div_ceil(2);
            let offset_y = (crop_height - origin_height).div_ceil(2);
            // HWC -> CHW
            for (x, y, pixel) in image.to_rgb8().enumerate_pixels() {
                pixels_array[[0, (y + offset_y) as usize, (x + offset_x) as usize]] =
                    pixel[0] as f32;
                pixels_array[[1, (y + offset_y) as usize, (x + offset_x) as usize]] =
                    pixel[1] as f32;
                pixels_array[[2, (y + offset_y) as usize, (x + offset_x) as usize]] =
                    pixel[2] as f32;
            }
            Ok(TransformData::NdArray(pixels_array))
        }
    }
}

struct PILToNDarray;

impl Transform for PILToNDarray {
    fn transform_with_resize(&self, data: TransformData, _: &ResizeFn) -> Result<TransformData> {
        match data {
            TransformData::Image(image) => {
                let image = image.to_rgb8();
                let (width, height) = image.dimensions();
                // HWC -> CHW
                let mut pixels_array = Array3::zeros((3usize, height as usize, width as usize));
                for (x, y, pixel) in image.enumerate_pixels() {
                    pixels_array[[0, y as usize, x as usize]] = pixel[0] as f32;
                    pixels_array[[1, y as usize, x as usize]] = pixel[1] as f32;
                    pixels_array[[2, y as usize, x as usize]] = pixel[2] as f32;
                }
                Ok(TransformData::NdArray(pixels_array))
            }
            ndarray => Ok(ndarray),
        }
    }
}

pub struct Rescale {
    pub scale: f32,
}

impl Transform for Rescale {
    fn transform_with_resize(&self, data: TransformData, _: &ResizeFn) -> Result<TransformData> {
        let array = data.array()?;
        let array = array * self.scale;
        Ok(TransformData::NdArray(array))
    }
}

pub struct Normalize {
    pub mean: Vec<f32>,
    pub std: Vec<f32>,
}

impl Transform for Normalize {
    fn transform_with_resize(&self, data: TransformData, _: &ResizeFn) -> Result<TransformData> {
        let array = data.array()?;
        let mean = Array::from_vec(self.mean.clone())
            .into_shape_with_order((3, 1, 1))
            .map_err(|e| Error::InvalidShape(format!("Failed to reshape mean array: {e}")))?;
        let std = Array::from_vec(self.std.clone())
            .into_shape_with_order((3, 1, 1))
            .map_err(|e| Error::InvalidShape(format!("Failed to reshape std array: {e}")))?;

        let shape = array.shape().to_vec();
        match shape.as_slice() {
            [c, h, w] => {
                let mean_broadcast = mean.broadcast((*c, *h, *w)).ok_or_else(|| {
                    Error::InvalidShape(format!(
                        "Failed to broadcast mean array to shape {:?}",
                        (*c, *h, *w)
                    ))
                })?;
                let std_broadcast = std.broadcast((*c, *h, *w)).ok_or_else(|| {
                    Error::InvalidShape(format!(
                        "Failed to broadcast std array to shape {:?}",
                        (*c, *h, *w)
                    ))
                })?;
                let array_normalized = array.sub(mean_broadcast).div(std_broadcast);
                Ok(TransformData::NdArray(array_normalized))
            }
            _ => Err(Error::ImageTransform(
                "Transformer convert error. Normalize operator got error shape.".into(),
            )),
        }
    }
}

pub struct Compose {
    transforms: Vec<Box<dyn Transform>>,
}

impl Compose {
    fn new(transforms: Vec<Box<dyn Transform>>) -> Self {
        Self { transforms }
    }

    #[cfg(feature = "hf-hub")]
    pub fn from_file<P: AsRef<Path>>(file: P) -> Result<Self> {
        let content = read_to_string(file)?;
        let config = serde_json::from_str(&content)
            .map_err(|e| Error::PreprocessorConfig(format!("Invalid preprocessor JSON: {e}")))?;
        load_preprocessor(config)
    }

    pub fn from_bytes<P: AsRef<[u8]>>(bytes: P) -> Result<Compose> {
        let config = serde_json::from_slice(bytes.as_ref())
            .map_err(|e| Error::PreprocessorConfig(format!("Invalid preprocessor JSON: {e}")))?;
        load_preprocessor(config)
    }

    pub(crate) fn preprocess_image(&self, image: DynamicImage) -> Result<Array3<f32>> {
        self.transform(TransformData::Image(image))?.array()
    }

    pub(crate) fn preprocess_image_with_resize(
        &self,
        image: DynamicImage,
        resize: &ResizeFn,
    ) -> Result<Array3<f32>> {
        self.transform_with_resize(TransformData::Image(image), resize)?
            .array()
    }
}

impl Transform for Compose {
    fn transform_with_resize(
        &self,
        mut image: TransformData,
        resize: &ResizeFn,
    ) -> Result<TransformData> {
        for transform in &self.transforms {
            image = transform.transform_with_resize(image, resize)?;
        }
        Ok(image)
    }
}

fn load_preprocessor(config: serde_json::Value) -> Result<Compose> {
    let mut transformers: Vec<Box<dyn Transform>> = vec![];
    transformers.push(Box::new(ConvertToRGB));

    let mode = config["image_processor_type"]
        .as_str()
        .unwrap_or("CLIPImageProcessor");
    match mode {
        "CLIPImageProcessor" | "CLIPFeatureExtractor" | "BitImageProcessor" => {
            if config["do_resize"].as_bool().unwrap_or(false) {
                transformers.push(Box::new(Resize {
                    size: parse_resize_size(&config["size"])?,
                    resample: parse_resample(&config["resample"]),
                }));
            }

            if config["do_center_crop"].as_bool().unwrap_or(false) {
                transformers.push(Box::new(CenterCrop {
                    size: parse_crop_size(&config["crop_size"])?,
                }));
            }
        }
        "ConvNextImageProcessor" | "ConvNextFeatureExtractor" => {
            let shortest_edge = config["size"]["shortest_edge"].as_u64().ok_or_else(|| {
                Error::PreprocessorConfig(
                    "Size dictionary must contain 'shortest_edge' key.".into(),
                )
            })? as u32;
            let crop_pct = config["crop_pct"].as_f64().unwrap_or(0.875);
            if shortest_edge < 384 {
                let resize_shortest_edge = shortest_edge as f64 / crop_pct;
                transformers.push(Box::new(Resize {
                    size: ResizeSize::ShortestEdge(resize_shortest_edge as u32),
                    resample: parse_resample(&config["resample"]),
                }));
                transformers.push(Box::new(CenterCrop {
                    size: (shortest_edge, shortest_edge),
                }))
            } else {
                transformers.push(Box::new(Resize {
                    size: ResizeSize::Exact {
                        width: shortest_edge,
                        height: shortest_edge,
                    },
                    resample: parse_resample(&config["resample"]),
                }));
            }
        }
        mode => {
            return Err(Error::PreprocessorConfig(format!(
                "Preprocessor {mode} is not supported"
            )));
        }
    }

    transformers.push(Box::new(PILToNDarray));

    if config["do_rescale"].as_bool().unwrap_or(true) {
        let rescale_factor = config["rescale_factor"].as_f64().unwrap_or(1.0f64 / 255.0);
        transformers.push(Box::new(Rescale {
            scale: rescale_factor as f32,
        }));
    }

    if config["do_normalize"].as_bool().unwrap_or(false) {
        let mean = config["image_mean"]
            .as_array()
            .ok_or_else(|| Error::PreprocessorConfig("image_mean must be contained".into()))?
            .iter()
            .map(|value| {
                value
                    .as_f64()
                    .map(|num| num as f32)
                    .ok_or_else(|| Error::PreprocessorConfig("image_mean must be float".into()))
            })
            .collect::<Result<Vec<f32>>>()?;
        let std = config["image_std"]
            .as_array()
            .ok_or_else(|| Error::PreprocessorConfig("image_std must be contained".into()))?
            .iter()
            .map(|value| {
                value
                    .as_f64()
                    .map(|num| num as f32)
                    .ok_or_else(|| Error::PreprocessorConfig("image_std must be float".into()))
            })
            .collect::<Result<Vec<f32>>>()?;
        transformers.push(Box::new(Normalize { mean, std }));
    }

    Ok(Compose::new(transformers))
}

/// The filter that `resample` names by its number in PIL. Bicubic stands in for an absent
/// number, and for a PIL filter that the image crate does not have.
fn parse_resample(resample: &serde_json::Value) -> FilterType {
    match resample.as_u64() {
        Some(0) => FilterType::Nearest,
        Some(1) => FilterType::Lanczos3,
        Some(2) => FilterType::Triangle,
        _ => FilterType::CatmullRom,
    }
}

fn parse_resize_size(size: &serde_json::Value) -> Result<ResizeSize> {
    if let Some(shortest_edge) = size["shortest_edge"].as_u64() {
        return Ok(ResizeSize::ShortestEdge(shortest_edge as u32));
    }
    match (size["width"].as_u64(), size["height"].as_u64()) {
        (Some(width), Some(height)) => Ok(ResizeSize::Exact {
            width: width as u32,
            height: height as u32,
        }),
        _ => Err(Error::PreprocessorConfig(
            "Size must contain either 'shortest_edge' or 'height' and 'width'.".into(),
        )),
    }
}

/// `crop_size` as `(width, height)`.
fn parse_crop_size(crop_size: &serde_json::Value) -> Result<(u32, u32)> {
    if let Some(size) = crop_size.as_u64() {
        return Ok((size as u32, size as u32));
    }
    if crop_size.is_object() {
        let height = crop_size["height"].as_u64().ok_or_else(|| {
            Error::PreprocessorConfig("crop_size height must be contained".into())
        })?;
        let width = crop_size["width"]
            .as_u64()
            .ok_or_else(|| Error::PreprocessorConfig("crop_size width must be contained".into()))?;
        return Ok((width as u32, height as u32));
    }
    Err(Error::PreprocessorConfig(format!(
        "Invalid crop size: {crop_size:?}"
    )))
}

#[cfg(test)]
mod tests {
    use super::*;
    use image::RgbImage;

    fn image(width: u32, height: u32) -> TransformData {
        TransformData::Image(DynamicImage::ImageRgb8(RgbImage::from_pixel(
            width,
            height,
            image::Rgb([255, 0, 0]),
        )))
    }

    #[test]
    fn shortest_edge_resize_preserves_aspect_ratio() {
        let resize = Resize {
            size: ResizeSize::ShortestEdge(224),
            resample: FilterType::Nearest,
        };
        let out = resize.transform(image(400, 200)).unwrap().image().unwrap();
        assert_eq!(out.dimensions(), (448, 224));
        let out = resize.transform(image(200, 400)).unwrap().image().unwrap();
        assert_eq!(out.dimensions(), (224, 448));
    }

    #[test]
    fn exact_resize_keeps_width_and_height_apart() {
        let resize = Resize {
            size: ResizeSize::Exact {
                width: 320,
                height: 240,
            },
            resample: FilterType::Nearest,
        };
        let out = resize.transform(image(100, 100)).unwrap().image().unwrap();
        assert_eq!(out.dimensions(), (320, 240));
    }

    #[test]
    fn center_crop_pads_smaller_non_square_images_as_chw() {
        let crop = CenterCrop { size: (224, 100) };
        let out = crop.transform(image(50, 40)).unwrap().array().unwrap();
        assert_eq!(out.dim(), (3, 100, 224));
        assert_eq!(out[[0, 50, 112]], 255.0);
        assert_eq!(out[[0, 0, 0]], 0.0);
    }

    #[test]
    fn center_crop_puts_the_odd_pixel_of_padding_before_the_image() {
        let crop = CenterCrop { size: (224, 100) };
        let out = crop.transform(image(51, 41)).unwrap().array().unwrap();
        // 173 columns and 59 rows of padding: 87 and 30 before the image, 86 and 29 after.
        assert_eq!(out[[0, 30, 87]], 255.0);
        assert_eq!(out[[0, 70, 137]], 255.0);
        assert_eq!(out[[0, 29, 87]], 0.0);
        assert_eq!(out[[0, 30, 86]], 0.0);
        assert_eq!(out[[0, 71, 137]], 0.0);
        assert_eq!(out[[0, 70, 138]], 0.0);
    }

    #[test]
    fn a_resize_with_a_buffer_above_the_limit_is_an_error() {
        let above_the_limit = |resize: Resize, image: TransformData| {
            let err = resize.transform(image).err().unwrap().to_string();
            assert!(err.contains("above 512 MiB"), "error was: {err}");
        };
        let shortest_edge = || Resize {
            size: ResizeSize::ShortestEdge(224),
            resample: FilterType::Nearest,
        };
        // The result has 224 x 22,400,000 pixels of three bytes.
        above_the_limit(shortest_edge(), image(1, 100_000));
        // The first pass keeps the source width: 40,000 x 1,000 pixels of 16 bytes.
        let exact = |width: u32, height: u32| Resize {
            size: ResizeSize::Exact { width, height },
            resample: FilterType::Nearest,
        };
        above_the_limit(exact(1, 1000), image(40_000, 1));
        above_the_limit(exact(u32::MAX, u32::MAX), image(1, 1));

        let out = shortest_edge()
            .transform(image(1, 30))
            .unwrap()
            .image()
            .unwrap();
        assert_eq!(out.dimensions(), (224, 6720));
    }

    #[test]
    fn deprecated_and_current_processor_names_build_the_same_pipeline() {
        let output = |processor: &str, extra: serde_json::Value| {
            let mut config = serde_json::json!({
                "image_processor_type": processor,
                "do_resize": true,
                "size": {"shortest_edge": 224},
                "do_rescale": false
            });
            config
                .as_object_mut()
                .unwrap()
                .extend(extra.as_object().unwrap().clone());
            let compose = load_preprocessor(config).unwrap();
            compose.transform(image(640, 480)).unwrap().array().unwrap()
        };

        let crop = serde_json::json!({"do_center_crop": true, "crop_size": 224});
        assert_eq!(
            output("CLIPFeatureExtractor", crop.clone()),
            output("CLIPImageProcessor", crop)
        );
        let none = serde_json::json!({});
        assert_eq!(
            output("ConvNextImageProcessor", none.clone()),
            output("ConvNextFeatureExtractor", none)
        );
    }

    #[test]
    fn clip_config_builds_shortest_edge_pipeline() {
        let config = serde_json::json!({
            "image_processor_type": "CLIPImageProcessor",
            "do_resize": true,
            "size": {"shortest_edge": 224},
            "do_center_crop": true,
            "crop_size": 224,
            "do_rescale": true,
            "do_normalize": true,
            "image_mean": [0.5, 0.5, 0.5],
            "image_std": [0.5, 0.5, 0.5]
        });
        let compose = load_preprocessor(config).unwrap();
        let out = compose.transform(image(640, 480)).unwrap().array().unwrap();
        assert_eq!(out.dim(), (3, 224, 224));
        assert!((out[[0, 100, 100]] - 1.0).abs() < 1e-6);
        assert!((out[[1, 100, 100]] + 1.0).abs() < 1e-6);
    }
}