Adds better error handling
This commit is contained in:
parent
8847935f28
commit
85200d74a4
|
|
@ -12,6 +12,7 @@ indicatif = { version = "0.17.8", features = ["rayon"] }
|
|||
kmeans_colors = "0.6.0"
|
||||
palette = "0.7.6"
|
||||
rayon = "1.10.0"
|
||||
thiserror = "1.0.63"
|
||||
|
||||
[profile.dev]
|
||||
debug = 0
|
||||
|
|
|
|||
|
|
@ -32,4 +32,60 @@
|
|||
#71808E
|
||||
</div> <div class='color' style='background:#A2A09F; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#A2A09F
|
||||
</div></div><h1>Bender</h1><div class='custom-div'> <div class='color' style='background:#49291A; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#49291A
|
||||
</div> <div class='color' style='background:#9C9997; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#9C9997
|
||||
</div> <div class='color' style='background:#7F6563; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#7F6563
|
||||
</div> <div class='color' style='background:#81818D; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#81818D
|
||||
</div> <div class='color' style='background:#9FA3A7; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#9FA3A7
|
||||
</div> <div class='color' style='background:#95959B; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#95959B
|
||||
</div></div><h1>Great Green</h1><div class='custom-div'> <div class='color' style='background:#5E5546; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#5E5546
|
||||
</div> <div class='color' style='background:#29281E; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#29281E
|
||||
</div> <div class='color' style='background:#51574B; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#51574B
|
||||
</div> <div class='color' style='background:#4D493A; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#4D493A
|
||||
</div> <div class='color' style='background:#3A3D33; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#3A3D33
|
||||
</div> <div class='color' style='background:#575042; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#575042
|
||||
</div> <div class='color' style='background:#5E4F40; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#5E4F40
|
||||
</div> <div class='color' style='background:#453D2C; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#453D2C
|
||||
</div></div><h1>Lochre</h1><div class='custom-div'> <div class='color' style='background:#B36C36; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#B36C36
|
||||
</div> <div class='color' style='background:#853B22; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#853B22
|
||||
</div> <div class='color' style='background:#9E5A2B; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#9E5A2B
|
||||
</div> <div class='color' style='background:#CB7A38; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#CB7A38
|
||||
</div> <div class='color' style='background:#F7B285; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#F7B285
|
||||
</div> <div class='color' style='background:#7D5E58; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#7D5E58
|
||||
</div> <div class='color' style='background:#C69583; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#C69583
|
||||
</div> <div class='color' style='background:#4C1E0C; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#4C1E0C
|
||||
</div></div><h1>Red Haze</h1><div class='custom-div'> <div class='color' style='background:#6D4033; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#6D4033
|
||||
</div> <div class='color' style='background:#B7A4A5; color: #000000; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#B7A4A5
|
||||
</div> <div class='color' style='background:#93756D; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#93756D
|
||||
</div> <div class='color' style='background:#431B10; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#431B10
|
||||
</div> <div class='color' style='background:#6B4746; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#6B4746
|
||||
</div> <div class='color' style='background:#8E7C7C; color: #FFFFFF; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'>
|
||||
#8E7C7C
|
||||
</div></div></body></html>
|
||||
|
|
@ -10,13 +10,17 @@ use std::{
|
|||
};
|
||||
|
||||
use crate::{
|
||||
structs::{ColorIndex, RichColor},
|
||||
structs::{ColorIndex, PaletteError, RichColor},
|
||||
utilities::extract_name,
|
||||
Cli,
|
||||
};
|
||||
|
||||
/// Extract a subset of most representative colors
|
||||
pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex {
|
||||
pub(crate) fn extract_kcluster(
|
||||
image: &PathBuf,
|
||||
cli: &Cli,
|
||||
pb: &ProgressBar,
|
||||
) -> Result<ColorIndex, PaletteError> {
|
||||
let name = extract_name(image);
|
||||
let runs = cli.runs.unwrap_or(8);
|
||||
let nb_colors = cli.nb_colors.unwrap_or(8);
|
||||
|
|
@ -29,7 +33,7 @@ pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) ->
|
|||
let mut rgb_pixels: Vec<Srgb<f32>> = Vec::new();
|
||||
// Open the image
|
||||
let img = image::open(image_path)
|
||||
.expect("Couldn't open image")
|
||||
.map_err(|e| PaletteError::ImageLoad(image.to_path_buf(), e))?
|
||||
.into_rgba8();
|
||||
let img_vec: &[Srgba<u8>] = img.as_raw().components_as();
|
||||
|
||||
|
|
@ -77,14 +81,19 @@ pub(crate) fn extract_kcluster(image: &PathBuf, cli: &Cli, pb: &ProgressBar) ->
|
|||
})
|
||||
.collect::<Vec<RichColor>>();
|
||||
|
||||
ColorIndex::new(name, colors)
|
||||
Ok(ColorIndex::new(name, colors))
|
||||
}
|
||||
|
||||
/// Extract the first nb unique colors
|
||||
pub(crate) fn extract_colors(image_path: &PathBuf, cli: &Cli, pb: &ProgressBar) -> ColorIndex {
|
||||
pub(crate) fn extract_colors(
|
||||
image_path: &PathBuf,
|
||||
cli: &Cli,
|
||||
pb: &ProgressBar,
|
||||
) -> Result<ColorIndex, PaletteError> {
|
||||
let _ = cli;
|
||||
let name = extract_name(image_path);
|
||||
let img = image::open(Path::new(&image_path)).expect("Failed to open image");
|
||||
let img = image::open(Path::new(&image_path))
|
||||
.map_err(|e| PaletteError::ImageLoad(image_path.to_path_buf(), e))?;
|
||||
|
||||
// Create a HashSet to store unique colors
|
||||
let mut colors = HashSet::new();
|
||||
|
|
@ -129,10 +138,10 @@ pub(crate) fn extract_colors(image_path: &PathBuf, cli: &Cli, pb: &ProgressBar)
|
|||
// if cli.verbosity{
|
||||
// println!("[{}] Found {} unique colors", name, colors.len());
|
||||
// }
|
||||
ColorIndex::new(
|
||||
Ok(ColorIndex::new(
|
||||
name,
|
||||
vec.iter()
|
||||
.map(|(hue, rgb, luma)| RichColor::new(*hue, *luma, rgb.to_owned()))
|
||||
.collect(),
|
||||
)
|
||||
))
|
||||
}
|
||||
|
|
|
|||
31
src/main.rs
31
src/main.rs
|
|
@ -10,7 +10,7 @@ use std::{
|
|||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use structs::{ColorIndex, ExtractMode};
|
||||
use structs::{ColorIndex, ExtractMode, PaletteError};
|
||||
use utilities::{export_html, small_name};
|
||||
|
||||
/// CLI for extracting a color palette from an image and exporting it.
|
||||
|
|
@ -46,20 +46,18 @@ struct Cli {
|
|||
threads: Option<usize>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
fn main() -> Result<(), PaletteError> {
|
||||
let started = Instant::now();
|
||||
let spinner_style = ProgressStyle::with_template(
|
||||
"[{elapsed_precise}] {spinner} {bar:40.cyan/blue} {pos}/{len} [{prefix:.bold.dim}]",
|
||||
)
|
||||
.unwrap()
|
||||
)?
|
||||
.tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ ");
|
||||
|
||||
let cli = Cli::parse();
|
||||
if let Some(t) = cli.threads {
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(t)
|
||||
.build_global()
|
||||
.unwrap();
|
||||
.build_global()?;
|
||||
}
|
||||
let export_path = match cli.export.clone() {
|
||||
Some(e) => e,
|
||||
|
|
@ -100,11 +98,30 @@ fn main() {
|
|||
pb_general.inc(1);
|
||||
r
|
||||
})
|
||||
.filter_map(|x| match x {
|
||||
Ok(c) => Some(c),
|
||||
Err(e) => {
|
||||
// match e {
|
||||
// PaletteError::ImageLoad(e) => {
|
||||
|
||||
// },
|
||||
// _ => (),
|
||||
// }
|
||||
pb_general.println(format!("[ERR] {}", e));
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<ColorIndex>>();
|
||||
|
||||
pb_general.finish_and_clear();
|
||||
if cli.verbosity {
|
||||
println!("[INFO] Done in {}", HumanDuration(started.elapsed()));
|
||||
}
|
||||
export_html(export_path, colorblobs);
|
||||
// let r = export_html(export_path, colorblobs);
|
||||
// match r {
|
||||
// Ok(_) => (),
|
||||
// Err(ref e) => println!("[Error] {}", e),
|
||||
// }
|
||||
// r
|
||||
export_html(export_path, colorblobs)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,10 @@
|
|||
use std::path::PathBuf;
|
||||
|
||||
use clap::ValueEnum;
|
||||
use image::ImageError;
|
||||
use indicatif::style::TemplateError;
|
||||
use rayon::ThreadPoolBuildError;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Supported export formats for the color palette
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
|
||||
|
|
@ -38,3 +44,18 @@ impl RichColor {
|
|||
Self { hue, luma, rgb }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum PaletteError {
|
||||
#[error("image {:#?} couldn't be loaded ({:?})", .0, .1)]
|
||||
ImageLoad(PathBuf, ImageError),
|
||||
|
||||
#[error("an error occured when creating the progressbar")]
|
||||
ProgressBar(#[from] TemplateError),
|
||||
|
||||
#[error("an error occured when building the ThreadPool")]
|
||||
ThreadPool(#[from] ThreadPoolBuildError),
|
||||
|
||||
#[error("the data couldn't be written to file {:?}",.0)]
|
||||
HTMLExport(#[from] std::io::Error),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ use std::{
|
|||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use crate::structs::ColorIndex;
|
||||
use crate::structs::{ColorIndex, PaletteError};
|
||||
|
||||
/// Make a smaller name
|
||||
pub(crate) fn small_name(name: &Path) -> String {
|
||||
|
|
@ -14,14 +14,14 @@ pub(crate) fn small_name(name: &Path) -> String {
|
|||
let (beg, end, file_name) = if l > 2 {
|
||||
(
|
||||
ancs[l - 2].to_string_lossy(),
|
||||
ancs[1].file_name().unwrap().to_string_lossy(),
|
||||
ancs[0].file_name().unwrap().to_string_lossy(),
|
||||
extract_full_name(ancs[1]),
|
||||
extract_full_name(ancs[0]),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
Cow::Borrowed(""),
|
||||
Cow::Borrowed(""),
|
||||
ancs[0].file_name().unwrap().to_string_lossy(),
|
||||
extract_full_name(ancs[0]),
|
||||
)
|
||||
};
|
||||
|
||||
|
|
@ -34,40 +34,35 @@ pub(crate) fn small_name(name: &Path) -> String {
|
|||
}
|
||||
}
|
||||
|
||||
/// Extract the full name of the last element, as string
|
||||
fn extract_full_name(ancs: &Path) -> Cow<'_, str> {
|
||||
ancs.file_name().unwrap_or_default().to_string_lossy()
|
||||
}
|
||||
|
||||
/// Extract the image name
|
||||
pub(crate) fn extract_name(image: &Path) -> String {
|
||||
image
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.split(".")
|
||||
.next()
|
||||
.unwrap()
|
||||
.unwrap_or("")
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// Export the file as html
|
||||
pub(crate) fn export_html(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
|
||||
// let mut out = File::create(&export_path).expect("Can't open output file");
|
||||
let mut out = BufWriter::new(File::create(&export_path).expect("Can't open output file"));
|
||||
pub(crate) fn export_html(
|
||||
export_path: PathBuf,
|
||||
color_vec: Vec<ColorIndex>,
|
||||
) -> Result<(), PaletteError> {
|
||||
let mut out = BufWriter::new(File::create(&export_path)?);
|
||||
|
||||
write!(
|
||||
out,
|
||||
r#"<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>"#
|
||||
).unwrap();
|
||||
write!(
|
||||
out,
|
||||
"Palette: {}",
|
||||
&export_path
|
||||
.file_name()
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.split(".")
|
||||
.next()
|
||||
.unwrap()
|
||||
)
|
||||
.unwrap();
|
||||
)?;
|
||||
write!(out, "Palette: {}", &extract_name(&export_path))?;
|
||||
write!(
|
||||
out,
|
||||
r#"</title> <style> body{{background-color: #332f35;
|
||||
|
|
@ -93,22 +88,18 @@ pub(crate) fn export_html(export_path: PathBuf, color_vec: Vec<ColorIndex>) {
|
|||
}}
|
||||
</style></head><body>
|
||||
"#
|
||||
)
|
||||
.unwrap();
|
||||
)?;
|
||||
for blob in color_vec {
|
||||
write!(out, "<h1>{}</h1>", blob.name).unwrap();
|
||||
write!(out, "<div class='custom-div'>").unwrap();
|
||||
write!(out, "<h1>{}</h1>", blob.name)?;
|
||||
write!(out, "<div class='custom-div'>")?;
|
||||
for v in blob.colors {
|
||||
let c = if v.luma < 60 { "FFFFFF" } else { "000000" };
|
||||
write!(out," <div class='color' style='background:{}; color: #{}; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'> \n {} \n</div>",v.rgb_string(),c,v.rgb_string()).expect("Can't write color in the output");
|
||||
write!(out," <div class='color' style='background:{}; color: #{}; min-width: 25%; height: 75px; line-height: 75px; font-size: 14px'> \n {} \n</div>",v.rgb_string(),c,v.rgb_string())?;
|
||||
}
|
||||
write!(out, "</div>").unwrap();
|
||||
write!(out, "</div>")?;
|
||||
}
|
||||
write!(out, "</body></html>").unwrap();
|
||||
println!(
|
||||
"[INFO] Exported pallete to file: {}",
|
||||
export_path.to_string_lossy()
|
||||
);
|
||||
write!(out, "</body></html>")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Save the kcluster picture
|
||||
|
|
|
|||
Reference in New Issue