From 6a8bee0b4a16503cd928ad7f9c5eec482a2175b7 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 5 Sep 2024 21:15:49 +0200 Subject: [PATCH] With threads, some prettying up to do --- Cargo.toml | 1 + src/main.rs | 51 ++++++++++++++++++++++++++++++++++++--------------- 2 files changed, 37 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 931f842..b846f52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" [dependencies] clap = { version = "4.5.16", features = ["derive"] } +console = "0.15.8" image = "0.25.2" indicatif = { version = "0.17.8", features = ["rayon"] } kmeans_colors = "0.6.0" diff --git a/src/main.rs b/src/main.rs index fd4f274..4778bc9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,6 +1,8 @@ use clap::{Parser, ValueEnum}; +use console::style; use image::{GenericImageView, Pixel}; -use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle}; +use indicatif::{HumanDuration, MultiProgress, ProgressBar, ProgressStyle}; +// use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; // use image::ImageEncoder; use kmeans_colors::{get_kmeans_hamerly, Kmeans, Sort}; @@ -17,6 +19,8 @@ use std::path::PathBuf; use std::collections::HashSet; use std::path::Path; +use std::thread; +use std::time::{Duration, Instant}; /// CLI for extracting a color palette from an image and exporting it. #[derive(Parser, Debug)] @@ -79,11 +83,17 @@ impl RichColor { } fn main() { + let started = Instant::now(); + let spinner_style = ProgressStyle::with_template("{prefix:.bold.dim} {spinner} {wide_msg}") + .unwrap() + .tick_chars("⠁⠂⠄⡀⢀⠠⠐⠈ "); + let cli = Cli::parse(); let export_path = match cli.export { Some(e) => e, None => cli.image[0] .parent() + // Check output here, not later .expect("Couldn't find a place to save the output") .to_path_buf(), }; @@ -102,17 +112,31 @@ fn main() { ExtractMode::Cluster => extract_kcluster, }; - let style = ProgressStyle::default_bar(); - let colorblobs = cli + let m = MultiProgress::new(); + // let style = ProgressStyle::default_bar(); + let handles: Vec<_> = cli .image .par_iter() - .progress_with_style(style) - .map(|image| function(image, cli.nb_colors)) - .collect::>(); - export_html(export_path, colorblobs); + .map(|image| { + let pb = m.add(ProgressBar::new(8)); // TODO: Not use 8 for passes and have it as parameter + // pb.set_style(spinner_style.clone()); + pb.set_prefix(format!("[{:?}]", image)); // Make shorter by def + let image = image.clone(); + thread::spawn(move || function(&image, cli.nb_colors, &pb)) + }) + .collect(); + // .collect::>(); + for h in handles { + let _ = h.join(); + } + m.clear().unwrap(); + + // export(export_path, colorblobs); + + println!("Done in {}", HumanDuration(started.elapsed())); } -fn extract_kcluster(image: &PathBuf, nb_colors: Option) -> ColorIndex { +fn extract_kcluster(image: &PathBuf, nb_colors: Option, pb: &ProgressBar) -> ColorIndex { let name = image .file_name() .unwrap() @@ -146,11 +170,9 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option) -> ColorIndex { .filter(|x| x.alpha == 255) .map(|x| Srgb::::from_color(x.into_format::<_, f32>())), ); - println!("Started"); // Iterate over amount of runs keeping best results let mut result = Kmeans::new(); for i in 0..runs { - println!("{}", runs); let run_result = get_kmeans_hamerly( nb_colors, max_iter, @@ -162,8 +184,8 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option) -> ColorIndex { if run_result.score < result.score { result = run_result; } + pb.inc(1); } - println!("Done"); // Print and/or sort results, output to palette let mut res: Vec> = Srgb::sort_indexed_colors(&result.centroids, &result.indices); @@ -188,7 +210,7 @@ fn extract_kcluster(image: &PathBuf, nb_colors: Option) -> ColorIndex { ColorIndex::new(name, colors) } -fn extract_colors(image_path: &PathBuf, nb_colors: Option) -> ColorIndex { +fn extract_colors(image_path: &PathBuf, nb_colors: Option, pb: &ProgressBar) -> ColorIndex { let _ = nb_colors; let name = image_path .file_name() @@ -238,6 +260,7 @@ fn extract_colors(image_path: &PathBuf, nb_colors: Option) -> ColorIndex } vec.sort_by_key(|&(k, _, _)| k); + pb.inc(8); // TODO: Have a real pb println!("[{}] Found {} unique colors", name, colors.len()); ColorIndex::new( name, @@ -246,9 +269,7 @@ fn extract_colors(image_path: &PathBuf, nb_colors: Option) -> ColorIndex .collect(), ) } - -/// Export the colors a a html file -fn export_html(export_path: PathBuf, color_vec: Vec) { +fn export(export_path: PathBuf, color_vec: Vec) { // 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"));