mold-ai 0.5.3

Local AI image generation CLI — FLUX, SDXL, SD3.5, Z-Image diffusion models on your GPU
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
use std::collections::HashSet;
use std::path::Path;

use anyhow::Result;
use colored::Colorize;
use mold_core::manifest::known_manifests;
use mold_core::Config;
use serde_json::json;

use crate::theme;
use crate::ui::format_bytes;

/// Count files and total bytes in a directory (recursive, no symlink following).
fn dir_stats(path: &Path) -> (u64, u64) {
    let mut files = 0u64;
    let mut bytes = 0u64;
    for entry in walkdir::WalkDir::new(path)
        .follow_links(false)
        .into_iter()
        .flatten()
    {
        if entry.file_type().is_file() {
            files += 1;
            bytes += entry.metadata().map(|m| m.len()).unwrap_or(0);
        }
    }
    (files, bytes)
}

/// Count only image files in a directory (recursive).
fn count_images(path: &Path) -> u64 {
    let mut count = 0u64;
    for entry in walkdir::WalkDir::new(path)
        .follow_links(false)
        .into_iter()
        .flatten()
    {
        if entry.file_type().is_file() {
            if let Some(ext) = entry.path().extension().and_then(|e| e.to_str()) {
                if matches!(ext.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg") {
                    count += 1;
                }
            }
        }
    }
    count
}

struct ModelStats {
    name: String,
    bytes: u64,
}

/// Collect per-model disk usage, deduplicating shared files.
fn collect_model_stats(config: &Config) -> (Vec<ModelStats>, u64) {
    let mut models: Vec<ModelStats> = Vec::new();
    let mut seen_names: HashSet<String> = HashSet::new();
    let mut shared_bytes = 0u64;
    let mut shared_paths: HashSet<String> = HashSet::new();

    // Collect all installed model names (config + manifest-discovered)
    let mut model_names: Vec<String> = config.models.keys().cloned().collect();
    for manifest in known_manifests() {
        if !seen_names.contains(&manifest.name)
            && !config.models.contains_key(&manifest.name)
            && config.manifest_model_is_downloaded(&manifest.name)
        {
            model_names.push(manifest.name.clone());
        }
    }

    let models_dir = config.resolved_models_dir();

    for name in &model_names {
        if !seen_names.insert(name.clone()) {
            continue;
        }

        let mc = config.model_config(name);
        let paths = mc.all_file_paths();
        let mut model_bytes = 0u64;

        for path in &paths {
            let size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
            if size == 0 {
                continue;
            }

            let is_shared = Path::new(path)
                .strip_prefix(&models_dir)
                .ok()
                .and_then(|rel| rel.components().next())
                .map(|c| c.as_os_str() == "shared")
                .unwrap_or(false);

            if is_shared {
                if shared_paths.insert(path.clone()) {
                    shared_bytes += size;
                }
            } else {
                model_bytes += size;
            }
        }

        models.push(ModelStats {
            name: name.clone(),
            bytes: model_bytes,
        });
    }

    // Sort by size descending
    models.sort_by(|a, b| b.bytes.cmp(&a.bytes));

    (models, shared_bytes)
}

/// Build a human-readable label for shared component types.
fn shared_components_label(config: &Config) -> String {
    let models_dir = config.resolved_models_dir();
    let shared_dir = models_dir.join("shared");
    if !shared_dir.is_dir() {
        return String::new();
    }

    let mut labels: Vec<&str> = Vec::new();

    // Check for component types by scanning shared directory filenames
    let mut has_t5 = false;
    let mut has_clip = false;
    let mut has_vae = false;
    let mut has_tokenizer = false;

    for entry in walkdir::WalkDir::new(&shared_dir)
        .follow_links(false)
        .into_iter()
        .flatten()
    {
        if !entry.file_type().is_file() {
            continue;
        }
        let name = entry
            .file_name()
            .to_str()
            .unwrap_or_default()
            .to_lowercase();
        if name.contains("t5") && !name.contains("tokenizer") {
            has_t5 = true;
        }
        if name.contains("clip") && !name.contains("tokenizer") {
            has_clip = true;
        }
        if name.contains("ae.") || name.contains("vae") || name.contains("decoder") {
            has_vae = true;
        }
        if name.contains("tokenizer") {
            has_tokenizer = true;
        }
    }

    if has_t5 {
        labels.push("T5 encoder");
    }
    if has_clip {
        labels.push("CLIP encoder");
    }
    if has_vae {
        labels.push("VAE");
    }
    if has_tokenizer {
        labels.push("tokenizers");
    }

    labels.join(", ")
}

pub fn run(json: bool) -> Result<()> {
    let config = Config::load_or_default();

    let models_dir = config.resolved_models_dir();
    let output_dir = config.effective_output_dir();
    let log_dir = config.resolved_log_dir();
    let hf_cache_dir = models_dir.join(".hf-cache");

    // Gather directory stats
    let (_models_dir_files, models_dir_bytes) = if models_dir.is_dir() {
        dir_stats(&models_dir)
    } else {
        (0, 0)
    };

    let (_output_files, output_bytes) = if output_dir.is_dir() {
        dir_stats(&output_dir)
    } else {
        (0, 0)
    };
    let output_images = if output_dir.is_dir() {
        count_images(&output_dir)
    } else {
        0
    };

    let (_log_files, log_bytes) = if log_dir.is_dir() {
        dir_stats(&log_dir)
    } else {
        (0, 0)
    };

    let (_hf_files, hf_bytes) = if hf_cache_dir.is_dir() {
        dir_stats(&hf_cache_dir)
    } else {
        (0, 0)
    };

    let (model_stats, shared_bytes) = collect_model_stats(&config);
    let shared_label = shared_components_label(&config);

    if json {
        print_json(&JsonData {
            config: &config,
            model_stats: &model_stats,
            models_dir_bytes,
            output_bytes,
            output_images,
            log_bytes,
            hf_cache_bytes: hf_bytes,
            shared_bytes,
        });
        return Ok(());
    }

    // Directory overview
    println!(
        "Models directory: {} ({})",
        tilde(&models_dir.to_string_lossy()),
        format_bytes(models_dir_bytes)
    );

    if output_dir.is_dir() {
        println!(
            "Output directory: {} ({}, {} images)",
            tilde(&output_dir.to_string_lossy()),
            format_bytes(output_bytes),
            output_images,
        );
    } else {
        println!(
            "Output directory: {} {}",
            tilde(&output_dir.to_string_lossy()),
            "(not created)".dimmed(),
        );
    }

    if log_dir.is_dir() && log_bytes > 0 {
        println!(
            "Logs directory:   {} ({})",
            tilde(&log_dir.to_string_lossy()),
            format_bytes(log_bytes),
        );
    } else {
        println!(
            "Logs directory:   {} {}",
            tilde(&log_dir.to_string_lossy()),
            if log_dir.is_dir() {
                "(empty)".dimmed()
            } else {
                "(not created)".dimmed()
            },
        );
    }

    println!(
        "Cache/temp:       {} ({})",
        tilde(&hf_cache_dir.to_string_lossy()),
        format_bytes(hf_bytes),
    );

    // Per-model breakdown
    if !model_stats.is_empty() {
        println!();
        println!("{}:", "Models".bold());

        for m in &model_stats {
            println!("  {:<24} {}", m.name, format_bytes(m.bytes));
        }

        let total_model_bytes: u64 = model_stats.iter().map(|m| m.bytes).sum();
        println!("  {}", "".repeat(40).dimmed());
        println!(
            "  {:<24} {} ({} models)",
            "Total:".bold(),
            format_bytes(total_model_bytes),
            model_stats.len(),
        );
    } else {
        println!();
        println!(
            "{} No models installed. Run {} to download one.",
            theme::icon_neutral(),
            "mold pull <model>".bold()
        );
    }

    // Shared components
    if shared_bytes > 0 {
        println!();
        if shared_label.is_empty() {
            println!("Shared components: {}", format_bytes(shared_bytes));
        } else {
            println!(
                "Shared components: {} ({})",
                format_bytes(shared_bytes),
                shared_label,
            );
        }
    }

    let total = models_dir_bytes + output_bytes + log_bytes;
    println!();
    println!("Total disk usage: {}", format_bytes(total).bold());

    Ok(())
}

struct JsonData<'a> {
    config: &'a Config,
    model_stats: &'a [ModelStats],
    models_dir_bytes: u64,
    output_bytes: u64,
    output_images: u64,
    log_bytes: u64,
    hf_cache_bytes: u64,
    shared_bytes: u64,
}

fn print_json(data: &JsonData) {
    let models_dir = data.config.resolved_models_dir();
    let output_dir = data.config.effective_output_dir();
    let log_dir = data.config.resolved_log_dir();

    let models: Vec<serde_json::Value> = data
        .model_stats
        .iter()
        .map(|m| json!({ "name": m.name, "bytes": m.bytes }))
        .collect();

    let output = json!({
        "models_dir": models_dir.to_string_lossy(),
        "models_dir_bytes": data.models_dir_bytes,
        "output_dir": output_dir.to_string_lossy(),
        "output_bytes": data.output_bytes,
        "output_images": data.output_images,
        "log_dir": log_dir.to_string_lossy(),
        "log_bytes": data.log_bytes,
        "hf_cache_bytes": data.hf_cache_bytes,
        "shared_bytes": data.shared_bytes,
        "models": models,
    });

    println!("{}", serde_json::to_string_pretty(&output).unwrap());
}

/// Replace home directory prefix with `~` for display.
fn tilde(path: &str) -> String {
    if let Some(home) = dirs::home_dir() {
        let home_str = home.to_string_lossy();
        if let Some(rest) = path.strip_prefix(home_str.as_ref()) {
            return format!("~{rest}");
        }
    }
    path.to_string()
}

#[cfg(test)]
mod tests {
    #![allow(clippy::field_reassign_with_default)]

    use super::*;

    #[test]
    fn tilde_replaces_home() {
        if let Some(home) = dirs::home_dir() {
            let path = format!("{}/foo/bar", home.display());
            assert_eq!(tilde(&path), "~/foo/bar");
        }
    }

    #[test]
    fn tilde_no_home_prefix_unchanged() {
        assert_eq!(tilde("/usr/local/bin"), "/usr/local/bin");
    }

    #[test]
    fn shared_components_label_empty_when_no_shared_dir() {
        let tmp = std::env::temp_dir().join(format!(
            "mold-stats-shared-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let mut config = Config::default();
        config.models_dir = tmp.to_string_lossy().to_string();
        let label = shared_components_label(&config);
        assert!(label.is_empty(), "expected empty label, got: {label}");
    }

    #[test]
    fn shared_components_label_detects_t5_and_vae() {
        let tmp = std::env::temp_dir().join(format!(
            "mold-stats-label-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        let shared = tmp.join("shared").join("flux");
        std::fs::create_dir_all(&shared).unwrap();
        std::fs::write(shared.join("t5xxl_fp16.safetensors"), b"x").unwrap();
        std::fs::write(shared.join("ae.safetensors"), b"x").unwrap();
        let mut config = Config::default();
        config.models_dir = tmp.to_string_lossy().to_string();
        let label = shared_components_label(&config);
        assert!(label.contains("T5 encoder"), "expected T5, got: {label}");
        assert!(label.contains("VAE"), "expected VAE, got: {label}");
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn collect_model_stats_empty_models_dir() {
        let tmp = std::env::temp_dir().join(format!(
            "mold-stats-empty-{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&tmp).unwrap();
        let mut config = Config::default();
        config.models_dir = tmp.to_string_lossy().to_string();
        let (models, shared) = collect_model_stats(&config);
        assert!(
            models.is_empty(),
            "expected no models, got {}",
            models.len()
        );
        assert_eq!(shared, 0);
        let _ = std::fs::remove_dir_all(&tmp);
    }
}