#![deny(clippy::all)]
#![deny(clippy::pedantic)]
#![forbid(unsafe_code)]
use std::fs::File;
use std::io::Write;
use std::num::NonZero;
use std::path::PathBuf;
use std::process::ExitCode;
use anyhow::{Result, bail, ensure};
use clap::{Command, CommandFactory, Parser, Subcommand, ValueHint};
use clap_complete::{Shell, generate};
use malware_modeler::crossval::{CrossValidation, CrossValidationReport, SelectionMetric};
use walkdir::WalkDir;
#[derive(Parser)]
#[command(author, about, version = malware_modeler::VERSION)]
pub struct Args {
#[clap(subcommand)]
cmd: Actions,
#[clap(long, default_value_t = threads())]
threads: usize,
}
#[inline]
fn threads() -> usize {
std::thread::available_parallelism()
.unwrap_or(NonZero::<usize>::MIN)
.get()
}
#[derive(Subcommand)]
enum Actions {
Ngram(Ngram),
Dataset(Dataset),
DatasetConvert(DatasetConvert),
DatasetInfo(DatasetInfo),
DatasetSplit(DatasetSplit),
Train(Train),
Evaluate(Evaluate),
Model(ModelInfo),
Types(Types),
Similarity(Similarity),
SelectiveUnzip(SelectiveUnzip),
Split(Split),
ZipSummary(ZipSummary),
Generate(Generator),
}
#[derive(Parser)]
struct Ngram {
#[arg(short, long, value_hint = ValueHint::DirPath)]
path: PathBuf,
#[arg(short = 't', long = "type", ignore_case = true)]
ftype: Option<malware_modeler::ftype::FileType>,
#[arg(short, default_value_t = 6)]
n: u16,
#[arg(short, default_value_t = 10000)]
k: usize,
#[arg(short, long, default_value_t = 1)]
stride: u16,
#[arg(short, long, value_hint = ValueHint::FilePath, default_value = "ngrams.txt")]
output: PathBuf,
#[clap(short, long, short, action)]
counts: bool,
#[clap(long, default_value = "false", action)]
verbose: bool,
#[clap(long, default_value = "false", action)]
skip_unknowns: bool,
}
impl Ngram {
fn execute(&self) -> Result<ExitCode> {
ensure!(
!self.output.exists(),
"Refusing to overwrite existing n-grams file {}",
self.output.display()
);
if self.k < 10 {
eprintln!("N-Gram count must be at least 10, should be ~100k");
return Ok(ExitCode::FAILURE);
}
if self.n < 2 {
eprintln!("N-Gram size must be at least 2, should be >4");
return Ok(ExitCode::FAILURE);
}
if self.stride == 0 {
eprintln!("N-Gram stride must be greater than 0");
return Ok(ExitCode::FAILURE);
}
let (mut ngrammer, skipped) = malware_modeler::ngram::Ngrammer::new(
self.ftype,
&self.path,
self.n,
self.k,
self.stride,
self.verbose,
self.skip_unknowns,
)?;
ngrammer.find();
println!(
"{}-gramming skipped {skipped} files which weren't {} files.",
self.n,
ngrammer.ftype()
);
if ngrammer.ngrams().len() < self.k {
println!(
"Found {} n-grams, fewer than the {} requested.",
ngrammer.ngrams().len(),
self.k
);
}
ngrammer.save(&self.output, self.counts)?;
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct Dataset {
#[arg(short, long, value_hint = ValueHint::DirPath)]
pub malicious: PathBuf,
#[arg(short, long, value_hint = ValueHint::DirPath)]
pub benign: PathBuf,
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub ngrams: PathBuf,
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub output: PathBuf,
#[arg(short, long, default_value_t = false)]
pub verbose: bool,
}
impl Dataset {
fn execute(&self) -> Result<ExitCode> {
ensure!(
!self.output.exists(),
"Refusing to overwrite existing dataset file {}",
self.output.display()
);
malware_modeler::dataset::Dataset::create_save_from_benign_malicious_files_and_ngrams(
&self.malicious,
&self.benign,
&self.ngrams,
&self.output,
self.verbose,
)?;
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct DatasetConvert {
#[arg(short, long = "in", value_hint = ValueHint::FilePath)]
pub input: PathBuf,
#[arg(short, long = "out", value_hint = ValueHint::FilePath)]
pub output: PathBuf,
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub model: Option<PathBuf>,
}
impl DatasetConvert {
fn execute(&self) -> Result<ExitCode> {
if self.input.extension() == self.output.extension() && self.model.is_none() {
eprintln!("Refusing to attempt 'conversion' between files with the same extension.");
return Ok(ExitCode::FAILURE);
}
ensure!(
!self.output.exists(),
"Refusing to overwrite existing dataset file {}",
self.output.display()
);
let mut dataset = malware_modeler::dataset::Dataset::load(&self.input)?;
if let Some(model) = &self.model {
let original = dataset.data.row_len();
let model_contents = std::fs::read_to_string(model)?;
let model: malware_modeler::model::LogisticRegression =
serde_json::from_str(model_contents.as_str())?;
let removed = dataset.reduce(&model)?.len();
println!("Removed {removed} features from the original {original}");
}
dataset.save(&self.output)?;
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct DatasetInfo {
#[arg(value_hint = ValueHint::FilePath)]
pub dataset: PathBuf,
}
impl DatasetInfo {
fn execute(&self) -> Result<ExitCode> {
let probe = malware_modeler::dataset::Dataset::probe(&self.dataset)?;
println!("{probe}");
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct DatasetSplit {
#[arg(short, long = "in", value_hint = ValueHint::FilePath)]
pub input: PathBuf,
#[arg(short, long = "train", value_hint = ValueHint::FilePath)]
pub training: PathBuf,
#[arg(short = 'e', long = "test", value_hint = ValueHint::FilePath)]
pub testing: PathBuf,
#[arg(short, long, default_value_t = 0.8)]
pub ratio: f32,
}
impl DatasetSplit {
fn execute(&self) -> Result<ExitCode> {
ensure!(
!self.training.exists(),
"Refusing to overwrite existing dataset file {}",
self.training.display()
);
ensure!(
!self.testing.exists(),
"Refusing to overwrite existing dataset file {}",
self.testing.display()
);
let mut original = malware_modeler::dataset::Dataset::load(&self.input)?;
let testing = original.split(self.ratio);
original.save(&self.training)?;
testing.save(&self.testing)?;
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct Train {
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub dataset: PathBuf,
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub test: Option<PathBuf>,
#[arg(short, long, value_hint = ValueHint::FilePath)]
pub model: PathBuf,
#[arg(short, long, default_value_t = 100)]
pub epochs: u32,
#[arg(short = 'r', long = "lr", default_value_t = 0.001)]
pub learning_rate: f32,
#[arg(short = '1', long = "l1", default_value_t = 0.1)]
pub l1_penalty: f32,
#[arg(short = '2', long = "l2", default_value_t = 0.1)]
pub l2_penalty: f32,
#[arg(long, default_value_t = false)]
pub dry_run: bool,
#[arg(short = 'k', long, value_parser = clap::value_parser!(u16).range(2..))]
pub folds: Option<u16>,
#[arg(long, default_value_t = SelectionMetric::Auc, requires = "folds")]
pub select_by: SelectionMetric,
}
impl Train {
fn execute(&self) -> Result<ExitCode> {
match malware_modeler::dataset::Dataset::probe(&self.dataset) {
Ok(probe) => println!("{probe}\n"),
Err(e) => eprintln!("Could not probe {}: {e}", self.dataset.display()),
}
if self.dry_run {
return Ok(ExitCode::SUCCESS);
}
ensure!(
!self.model.exists(),
"Refusing to overwrite existing model file {}",
self.model.display()
);
if let Some(test_dataset) = &self.test
&& let Ok(probe) = malware_modeler::dataset::Dataset::probe(test_dataset)
{
println!("Test dataset:\n{probe}\n");
}
let mut dataset = malware_modeler::dataset::Dataset::load(&self.dataset)?;
let test_dataset = if let Some(test_dataset) = &self.test {
let test = malware_modeler::dataset::Dataset::load(test_dataset)?;
ensure!(
dataset.same_ngrams_ftype(&test),
"Train and test datasets have different features or file type"
);
Some(test)
} else {
None
};
if let Some(folds) = self.folds {
return self.cross_validate(&dataset, test_dataset.as_ref(), folds.into());
}
let mut model = malware_modeler::model::LogisticRegression::new(
dataset.data.row_len(),
self.learning_rate,
self.l1_penalty,
self.l2_penalty,
);
let run = match model.fit(self.epochs, &mut dataset, test_dataset.as_ref()) {
Ok(run) => run,
Err(error) => {
eprintln!("Training failed: {error}");
return Ok(ExitCode::FAILURE);
}
};
println!("Training complete, final error {}", run.loss);
print_feature_reduction(&model, run.features_removed);
println!("\nPerformance on the training dataset:");
print_performance_stats(&model.train_performance);
if let Some(test) = &model.test_performance {
println!("\nPerformance on the test dataset:");
print_performance_stats(test);
}
model.save(&self.model)?;
Ok(ExitCode::SUCCESS)
}
fn cross_validate(
&self,
dataset: &malware_modeler::dataset::Dataset,
test: Option<&malware_modeler::dataset::Dataset>,
folds: usize,
) -> Result<ExitCode> {
let cv = CrossValidation::new(dataset, folds)?;
let mut results = Vec::with_capacity(folds);
for index in 0..folds {
println!("Fold {}/{folds}", index + 1);
let result = match cv.run_fold(
index,
self.epochs,
self.learning_rate,
self.l1_penalty,
self.l2_penalty,
) {
Ok(result) => result,
Err(error) => {
eprintln!("Training fold {} failed: {error}", index + 1);
return Ok(ExitCode::FAILURE);
}
};
println!(
"Trained on {} rows, tested on {}, final error {}",
result.train_rows, result.test_rows, result.loss
);
print_feature_reduction(&result.model, result.features_removed);
print_performance_stats(&result.test_performance);
println!();
results.push(result);
}
let report = CrossValidationReport::new(results, self.select_by)?;
println!("{report}");
let mut model = report.into_best();
if let Some(test) = test {
println!("\nBest model's performance on the test dataset:");
let result = model.evaluate_dataset(test)?;
print_confusion_matrix(&result);
model.test_performance = Some(result.into());
}
model.save(&self.model)?;
Ok(ExitCode::SUCCESS)
}
}
fn print_feature_reduction(model: &malware_modeler::model::LogisticRegression, removed: usize) {
let reduced = model.weights.len();
let original = reduced + removed;
println!("Features reduced by {removed}: {original} - {reduced}");
}
fn print_confusion_matrix(result: &malware_modeler::model::ConfusionMatrix) {
println!("{result}");
println!("Accuracy: {:.2}", result.accuracy());
println!("Precision: {:.2}", result.precision());
println!("Recall: {:.2}", result.recall());
println!("F1: {:.2}", result.f1());
println!("Auc: {:.2}", result.auc());
}
fn print_performance_stats(result: &malware_modeler::model::PerformanceStats) {
println!("{result}");
println!("Accuracy: {:.2}", result.accuracy());
println!("Precision: {:.2}", result.precision());
println!("Recall: {:.2}", result.recall());
println!("F1: {:.2}", result.f1());
println!("Auc: {:.2}", result.auc);
}
#[derive(Parser)]
struct Evaluate {
#[arg(short, long, value_hint = ValueHint::FilePath)]
dataset: PathBuf,
#[arg(short, long, value_hint = ValueHint::FilePath)]
model: PathBuf,
#[arg(long, default_value_t = false)]
update_model: bool,
}
impl Evaluate {
fn execute(&self) -> Result<ExitCode> {
let dataset = malware_modeler::dataset::Dataset::load(&self.dataset)?;
let mut model = malware_modeler::model::LogisticRegression::load(&self.model)?;
let result = model.evaluate_dataset(&dataset)?;
print_confusion_matrix(&result);
if self.update_model {
model.test_performance = Some(result.into());
model.save(&self.model)?;
}
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct ModelInfo {
#[arg(short, long, value_hint = ValueHint::FilePath)]
model: PathBuf,
#[arg(short = 'n', long, value_hint = ValueHint::FilePath)]
extract_ngrams: Option<PathBuf>,
#[arg(short, long, value_hint = ValueHint::AnyPath)]
eval: Option<PathBuf>,
#[arg(short = 'o', long, value_hint = ValueHint::FilePath)]
output: Option<PathBuf>,
}
impl ModelInfo {
fn execute(&self) -> Result<ExitCode> {
let model = malware_modeler::model::LogisticRegression::load(&self.model)?;
println!(
"This model is for {} files and has {} {}-grams",
model.file_type,
model.weights.len(),
model.n
);
println!("Original number of features: {}", model.original_ngrams);
println!("Stride used for n-gram discovery: {}", model.s);
println!("Learning rate: {}", model.learning_rate);
println!("L1: {}", model.l1);
println!("L2: {}", model.l2);
println!("Trained on: {}", model.created);
println!("\nTraining performance:");
print_performance_stats(&model.train_performance);
if let Some(eval_performance) = &model.test_performance {
println!("\nEvaluation performance:");
print_performance_stats(eval_performance);
}
if let Some(extract_ngrams) = &self.extract_ngrams {
let features = model
.features
.keys()
.map(hex::encode)
.collect::<Vec<String>>()
.join("\n");
let mut file = File::create(extract_ngrams)?;
file.write_all(features.as_bytes())?;
file.write_all(b"\n")?;
file.sync_all()?;
}
if let Some(eval) = &self.eval {
if eval.is_file() {
let (label, prediction, features) = model.evaluate_file(eval)?;
println!(
"{} is predicted to be {label} (raw: {prediction}) and had {features} of {} features",
eval.display(),
model.features.len()
);
} else if eval.is_dir() {
println!("Path, PredictionLabel, PredictionRaw, FoundFeatures/AvailableFeatures");
for entry in WalkDir::new(eval)
.max_depth(malware_modeler::MAX_RECURSION_DEPTH)
.follow_links(true)
.into_iter()
.flatten()
{
if entry.file_type().is_file() {
let (label, prediction, features) = model.evaluate_file(entry.path())?;
println!(
"{}, {label}, {prediction}, {features}/{}",
entry.path().display(),
model.features.len()
);
}
}
} else {
eprintln!("{} is not a file or directory", eval.display());
}
}
if let Some(output) = &self.output {
ensure!(
!output.exists(),
"Refusing to overwrite existing model file {}",
output.display()
);
let Some(new_ext) = output.extension().and_then(|ext| ext.to_str()) else {
bail!("Output file {} has no extension", output.display());
};
let old_ext = self
.model
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("");
if new_ext == old_ext {
println!(
"Output file {} has the same extension as the loaded file, nothing to do",
output.display()
);
} else {
model.save(output)?;
}
}
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser)]
struct Types {
#[arg(value_hint = ValueHint::AnyPath)]
path: PathBuf,
#[arg(value_hint = ValueHint::DirPath)]
destination: Option<PathBuf>,
#[arg(long, default_value_t = 3)]
depth: u8,
}
impl Types {
pub fn execute(&self) -> Result<ExitCode> {
if self.path.is_file() {
let contents = std::fs::read(&self.path)?;
let ftype = malware_modeler::sorting::FileTypeUnion::from_bytes(&contents);
println!("{ftype}");
} else if self.path.is_dir() && self.destination.is_none() {
for entry in WalkDir::new(&self.path)
.max_depth(malware_modeler::MAX_RECURSION_DEPTH)
.follow_links(true)
.into_iter()
.flatten()
{
if entry.file_type().is_file() {
let contents = std::fs::read(entry.path())?;
let ftype = malware_modeler::sorting::FileTypeUnion::from_bytes(&contents);
println!("{}: {ftype}", entry.path().display());
}
}
} else if self.path.is_dir()
&& let Some(dest) = &self.destination
{
let destination = dest.to_owned();
if destination.is_file() {
eprintln!("Destination must be a directory, not a file");
return Ok(ExitCode::FAILURE);
}
let result =
malware_modeler::sorting::file_sorting(&self.path, &destination, self.depth)?;
println!(
"Countered {} files, {} of which were duplicates.",
result.total_files, result.files_removed
);
if result.errors > 0 {
eprintln!("Encountered {} errors while sorting files.", result.errors);
}
}
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser, Debug, Clone, PartialEq)]
struct Similarity {
one: PathBuf,
two: Option<PathBuf>,
#[arg(long, default_value_t = 0.8)]
threshold: f32,
#[arg(long, default_value_t = false)]
delete_file_if_too_similar_yes_i_really_mean_it: bool,
}
impl Similarity {
pub fn execute(&self) -> Result<ExitCode> {
if self.one.is_file() {
if let Some(two) = &self.two {
if two.is_file() {
let sim = malware_modeler::similarity::lzjd_compare_paths(&self.one, two)?;
println!("{sim:.4}");
}
} else {
let lzjd = malware_modeler::similarity::lzjd_from_path(&self.one)?;
println!("{lzjd}");
}
} else {
if self.two.is_some() {
bail!("Similarity does not a directory argument with another path");
}
let similarity_check = malware_modeler::similarity::Similarity {
path: &self.one,
threshold: self.threshold,
};
let similar_count = similarity_check.find(|a, b, sim| {
eprintln!("{} & {} too similar: {sim}", a.display(), b.display());
if self.delete_file_if_too_similar_yes_i_really_mean_it
&& std::fs::exists(a).unwrap_or_default()
&& let Err(e) = std::fs::remove_file(a)
{
eprintln!("Failed to remove {}: {e}", a.display());
}
})?;
println!("Total similar file pairs: {similar_count}");
}
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser, Debug, Clone, PartialEq)]
struct SelectiveUnzip {
#[arg(value_hint = ValueHint::FilePath)]
source: PathBuf,
#[arg(value_hint = ValueHint::DirPath)]
destination: PathBuf,
#[arg(short, long)]
password: Option<String>,
#[arg(long, default_value_t = 3)]
depth: u8,
#[arg(short = 't', long = "type", value_parser = malware_modeler::sorting::parse_file_type_union)]
file_type: Option<malware_modeler::sorting::FileTypeUnion>,
#[cfg(feature = "libmagic")]
#[arg(short = 'm', long = "magic")]
magic: Option<String>,
#[arg(long, default_value_t = false)]
keep_unknowns: bool,
}
impl SelectiveUnzip {
pub fn execute(self) -> Result<ExitCode> {
let extracted_count = malware_modeler::unzip::unzip_files_by_type(
self.source,
self.destination,
self.password.as_ref(),
self.depth,
self.file_type,
#[cfg(feature = "libmagic")]
self.magic.as_deref(),
self.keep_unknowns,
)?;
println!("Extracted {extracted_count} files");
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser, Debug, Clone, PartialEq)]
struct Split {
#[arg(long, value_hint = ValueHint::DirPath)]
malware: PathBuf,
#[arg(long, value_hint = ValueHint::DirPath)]
goodware: PathBuf,
#[arg(long, value_hint = ValueHint::DirPath)]
training_malware: PathBuf,
#[arg(long, value_hint = ValueHint::DirPath)]
testing_malware: PathBuf,
#[arg(long, value_hint = ValueHint::DirPath)]
training_goodware: PathBuf,
#[arg(long, value_hint = ValueHint::DirPath)]
testing_goodware: PathBuf,
#[arg(long, default_value_t = 0.8)]
training_ratio: f32,
#[arg(long, value_hint = ValueHint::DirPath)]
validation_malware: Option<PathBuf>,
#[arg(long, value_hint = ValueHint::DirPath)]
validation_goodware: Option<PathBuf>,
#[arg(long)]
validation_ratio: Option<f32>,
}
impl Split {
pub fn execute(self) -> Result<ExitCode> {
ensure!(
self.training_ratio > 0.0,
"Train/test split ratio cannot be negative"
);
if self.validation_malware.is_some() != self.validation_goodware.is_some()
|| self.validation_ratio.is_some() != self.validation_malware.is_some()
{
bail!("All validation parameters must be provided or none are provided");
}
let validation = if let Some(benign) = self.validation_goodware
&& let Some(malicious) = self.validation_malware
&& let Some(split) = self.validation_ratio
{
ensure!(split > 0.0, "Validation ratio cannot be negative");
ensure!(
split + self.training_ratio < 0.0,
"Training and split ratios must have a sum less than 1"
);
Some(malware_modeler::split::ValidationDirectoriesConfig {
benign,
malicious,
split,
})
} else {
None
};
let split_summary = malware_modeler::split::split(
self.goodware,
self.malware,
self.training_goodware,
self.training_malware,
self.testing_goodware,
self.testing_malware,
self.training_ratio,
validation.as_ref(),
)?;
println!("{split_summary}");
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser, Debug, Clone, PartialEq)]
struct ZipSummary {
#[arg(value_hint = ValueHint::FilePath)]
source: PathBuf,
#[arg(short, long)]
password: Option<String>,
#[arg(short, long, default_value_t = 0)]
unknown_magic: usize,
#[arg(long, default_value_t = 2)]
unknown_minimum: usize,
}
impl ZipSummary {
pub fn execute(self) -> Result<ExitCode> {
const WIDTH: usize = 14;
let zip_summary = malware_modeler::unzip::zip_file_type_counts(
self.source,
self.password.as_ref(),
self.unknown_magic,
)?;
println!("{0:<WIDTH$} {1:<WIDTH$}", "Type", "Count");
let mut ordered_summary: Vec<_> = zip_summary.file_type_counts.into_iter().collect();
ordered_summary.sort_by_key(|b| std::cmp::Reverse(b.1));
for (ftype, count) in ordered_summary {
println!("{:<WIDTH$} {count:<WIDTH$}", format!("{ftype}"));
}
println!("{:^WIDTH$} {:<WIDTH$}", "Total", zip_summary.total_files);
if !zip_summary.unknown_magic_counts.is_empty() {
#[cfg(feature = "libmagic")]
println!("\n{0:<WIDTH$} {1:<WIDTH$} Magic", "Unknown Header", "Count");
#[cfg(not(feature = "libmagic"))]
println!("\n{0:<WIDTH$} {1:<WIDTH$}", "Unknown Header", "Count");
let mut ordered_summary: Vec<_> =
zip_summary.unknown_magic_counts.into_iter().collect();
#[allow(clippy::unnecessary_sort_by)]
ordered_summary.sort_by(|a, b| b.1.cmp(&a.1));
#[cfg(feature = "libmagic")]
for (unknown_bytes, (count, magic)) in ordered_summary {
if count >= self.unknown_minimum {
println!(
"{:<WIDTH$} {count:<WIDTH$} {magic}",
hex::encode(unknown_bytes)
);
}
}
#[cfg(not(feature = "libmagic"))]
for (unknown_bytes, count) in ordered_summary {
if count >= self.unknown_minimum {
println!("{:<WIDTH$} {count:<WIDTH$}", hex::encode(unknown_bytes));
}
}
}
Ok(ExitCode::SUCCESS)
}
}
#[derive(Parser, Debug, Clone, PartialEq)]
pub struct Generator {
#[arg(value_enum)]
shell: Shell,
}
impl Generator {
#[must_use]
pub fn execute(&self) -> ExitCode {
let mut cmd = Args::command();
self.print_completions(&mut cmd);
ExitCode::SUCCESS
}
fn print_completions(&self, cmd: &mut Command) {
generate(
self.shell,
cmd,
cmd.get_name().to_string(),
&mut std::io::stdout(),
);
}
}
fn main() -> Result<ExitCode> {
let args = Args::parse();
rayon::ThreadPoolBuilder::new()
.num_threads(args.threads)
.build_global()?;
let ret = match args.cmd {
Actions::Ngram(ngram) => ngram.execute(),
Actions::Dataset(dataset) => dataset.execute(),
Actions::DatasetConvert(dataset) => dataset.execute(),
Actions::DatasetInfo(dataset) => dataset.execute(),
Actions::DatasetSplit(split) => split.execute(),
Actions::Train(training) => training.execute(),
Actions::Evaluate(evaluate) => evaluate.execute(),
Actions::Model(model) => model.execute(),
Actions::Types(types) => types.execute(),
Actions::Similarity(sim) => sim.execute(),
Actions::SelectiveUnzip(unzip) => unzip.execute(),
Actions::Split(split) => split.execute(),
Actions::ZipSummary(summary) => summary.execute(),
Actions::Generate(generator) => Ok(generator.execute()),
};
if let Some(mem) = app_memory_usage_fetcher::get_memory_usage_string() {
println!("Memory used: {mem}");
}
ret
}
#[test]
fn verify_cli() {
use clap::CommandFactory;
Args::command().debug_assert();
}