From 51007f5b8ff6d5960ac034854ceae1ab15237b6a Mon Sep 17 00:00:00 2001 From: Lia Lenckowski Date: Wed, 6 Sep 2023 14:33:33 +0200 Subject: cache by hash instead of path --- src/embedders.rs | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) (limited to 'src/embedders.rs') diff --git a/src/embedders.rs b/src/embedders.rs index 0693b5e..8911e95 100644 --- a/src/embedders.rs +++ b/src/embedders.rs @@ -1,5 +1,6 @@ +use anyhow::{bail, Result}; use rayon::prelude::*; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; pub trait MetricElem: Send + Sync + 'static + Serialize + for<'a> Deserialize<'a> { @@ -16,21 +17,21 @@ pub trait EmbedderT: Send + Sync { type Embedding: MetricElem; const NAME: &'static str; - fn embed(&self, _: &PathBuf) -> Result; + fn embed(&self, _: &Path) -> Result; } pub trait BatchEmbedder: Send + Sync { type Embedding: MetricElem; const NAME: &'static str; - fn embeds(&mut self, _: &[PathBuf]) -> Result, String>; + fn embeds(&mut self, _: &[PathBuf]) -> Result>; } impl BatchEmbedder for T { type Embedding = T::Embedding; const NAME: &'static str = T::NAME; - fn embeds(&mut self, paths: &[PathBuf]) -> Result, String> { + fn embeds(&mut self, paths: &[PathBuf]) -> Result> { paths.par_iter() .map(|p| self.embed(p)) .collect::>() @@ -44,12 +45,12 @@ impl EmbedderT for BrightnessEmbedder { type Embedding = f64; const NAME: &'static str = "Brightness"; - fn embed(&self, path: &PathBuf) -> Result { - let im = image::open(path).map_err(|e| e.to_string())?; + fn embed(&self, path: &Path) -> Result { + let im = image::open(path)?; let num_bytes = 3 * (im.height() * im.width()); if num_bytes == 0 { - return Err("Encountered NaN brightness, due to an empty image".to_string()); + bail!("Encountered NaN brightness, due to an empty image"); } Ok(im.to_rgb8() @@ -74,8 +75,8 @@ impl EmbedderT for HueEmbedder { type Embedding = Hue; const NAME: &'static str = "Hue"; - fn embed(&self, path: &PathBuf) -> Result { - let im = image::open(path).map_err(|e| e.to_string())?; + fn embed(&self, path: &Path) -> Result { + let im = image::open(path)?; let num_pixels = im.height() * im.width(); let [sr, sg, sb] = im .to_rgb8() @@ -98,7 +99,7 @@ impl EmbedderT for HueEmbedder { }; if hue.is_nan() { - return Err("Encountered NaN hue, possibly because of a colorless or empty image".to_string()); + bail!("Encountered NaN hue, possibly because of a colorless or empty image"); } Ok(Hue(hue)) @@ -118,8 +119,8 @@ impl EmbedderT for ColorEmbedder { type Embedding = (f64, f64, f64); const NAME: &'static str = "Color"; - fn embed(&self, path: &PathBuf) -> Result<(f64, f64, f64), String> { - let im = image::open(path).map_err(|e| e.to_string())?; + fn embed(&self, path: &Path) -> Result<(f64, f64, f64)> { + let im = image::open(path)?; let num_pixels = im.height() * im.width(); let [sr, sg, sb] = im .to_rgb8() -- cgit v1.2.3-70-g09d2