vision-squeezer 0.1.9

LLM-native image optimization middleware & MCP server. Reduces vision model token consumption by snapping to tile boundaries.
Documentation
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
use std::fs;
use std::path::PathBuf;

use vision_squeezer::{
    OutputFormat, ProcessConfig, ProcessMode, VisionModel, encode_to_bytes, process,
    token_savings_table,
};

fn print_usage() {
    eprintln!("Usage: vision-squeezer <image> [options]");
    eprintln!("       vision-squeezer stats          (show cumulative savings)");
    eprintln!("       vision-squeezer /vision-stats  (alias for stats)");
    eprintln!("       vision-squeezer setup-hook    (print shell integration script)");
    eprintln!("\nOptions:");
    eprintln!("  --mode ocr|standard|auto  (default: auto)");
    eprintln!("  --format jpeg|webp         (default: jpeg)");
    eprintln!("  --quality 1-100            (default: 75)");
    eprintln!("  --tile-size N              (default: 512)");
    eprintln!("  --no-crop");
    eprintln!("  --bg-tolerance N           (default: 15)");
    eprintln!("  --model claude|gpt4o|gpt5|gemini  model-aware resizing");
    eprintln!("  --max-tiles N              (limit maximum token tiles)");
    eprintln!("  --output, -o <path>        (custom output path)");
    eprintln!("  --ops 'JSON'               (Think in Code: list of atomic operations)");
    eprintln!(
        "                             ex: --ops '[{{\"op\":\"crop\",\"x\":0,\"y\":0,\"width\":100,\"height\":100}},{{\"op\":\"grayscale\"}}]'"
    );
}

fn main() {
    let args: Vec<String> = std::env::args().collect();

    // Initialize DB
    let _ = vision_squeezer::Persistence::init_db();

    if matches!(
        args.get(1).map(|s| s.as_str()),
        Some("--version") | Some("-V") | Some("version")
    ) {
        println!("vision-squeezer {}", env!("CARGO_PKG_VERSION"));
        return;
    }

    if matches!(
        args.get(1).map(|s| s.as_str()),
        Some("stats") | Some("/vision-stats")
    ) {
        print_stats();
        return;
    }

    if args.get(1).map(|s| s.as_str()) == Some("setup-hook") {
        print_hook_script();
        return;
    }

    if args.len() < 2 {
        print_usage();
        return;
    }

    let path = PathBuf::from(&args[1]);
    let input_bytes = fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
    let img = image::open(&path).expect("failed to open image");
    let (orig_w, orig_h) = (img.width(), img.height());

    // Parse flags
    let mut cfg = ProcessConfig::builder();
    let mut mode = ProcessMode::Auto;
    let mut fmt = OutputFormat::Jpeg;
    let mut custom_output: Option<PathBuf> = None;
    let mut ops: Vec<vision_squeezer::ImageOp> = Vec::new();
    let mut i = 2usize;
    while i < args.len() {
        match args[i].as_str() {
            "--output" | "-o" => {
                i += 1;
                if let Some(p) = args.get(i) {
                    custom_output = Some(PathBuf::from(p));
                }
            }
            "--mode" => {
                i += 1;
                match args.get(i).map(|s| s.as_str()) {
                    Some("ocr") => mode = ProcessMode::Ocr,
                    Some("standard") => mode = ProcessMode::Standard,
                    _ => mode = ProcessMode::Auto,
                }
            }
            "--format" => {
                i += 1;
                if args.get(i).map(|s| s.as_str()) == Some("webp") {
                    fmt = OutputFormat::WebP;
                }
            }
            "--quality" => {
                i += 1;
                if let Some(q) = args.get(i).and_then(|s| s.parse().ok()) {
                    cfg = cfg.quality(q);
                }
            }
            "--tile-size" => {
                i += 1;
                if let Some(t) = args.get(i).and_then(|s| s.parse().ok()) {
                    cfg = cfg.tile_size(t);
                }
            }
            "--max-tiles" => {
                i += 1;
                if let Some(m) = args.get(i).and_then(|s| s.parse().ok()) {
                    cfg = cfg.max_tiles(m);
                }
            }
            "--no-crop" => {
                cfg = cfg.crop(false);
            }
            "--bg-tolerance" => {
                i += 1;
                if let Some(t) = args.get(i).and_then(|s| s.parse().ok()) {
                    cfg = cfg.bg_tolerance(t);
                }
            }
            "--model" => {
                i += 1;
                let m = match args.get(i).map(|s| s.as_str()) {
                    Some("gpt4o") | Some("gpt-4o") => Some(VisionModel::Gpt4o),
                    Some("gpt5") | Some("gpt-5") | Some("gpt5.5") => Some(VisionModel::Gpt5),
                    Some("gemini") => Some(VisionModel::Gemini15),
                    _ => Some(VisionModel::Claude),
                };
                if let Some(model) = m {
                    cfg = cfg.target_model(model);
                }
            }
            "--ops" => {
                i += 1;
                if let Some(s) = args.get(i) {
                    let parsed: Vec<vision_squeezer::ImageOp> =
                        serde_json::from_str(s).expect("failed to parse --ops JSON");
                    ops.extend(parsed);
                }
            }
            _ => {}
        }
        i += 1;
    }
    let cfg = cfg.output_format(fmt).build();

    println!(
        "Input:  {}×{}  ({:.1} MB)",
        orig_w,
        orig_h,
        input_bytes as f64 / 1_048_576.0
    );

    let img = if !ops.is_empty() {
        println!("Sandbox: Applying {} operations...", ops.len());
        vision_squeezer::process_with_operations(img, ops)
    } else {
        img
    };

    let mut result = process(img, mode, input_bytes, &cfg);

    // Encode
    let ext = match cfg.output_format {
        OutputFormat::WebP => "webp",
        OutputFormat::Jpeg => "jpg",
    };
    let out_path = custom_output.unwrap_or_else(|| path.with_extension(format!("optimized.{ext}")));
    let bytes = encode_to_bytes(&result.image, &cfg).expect("encode failed");
    let output_bytes = bytes.len() as u64;
    fs::write(&out_path, &bytes).expect("write failed");
    result.report.bytes_after = Some(output_bytes);

    println!(
        "Output: {}×{}  ({:.1} MB, {} q{})",
        result.width,
        result.height,
        output_bytes as f64 / 1_048_576.0,
        ext.to_uppercase(),
        cfg.quality,
    );

    if let Some(pct) = result.report.size_reduction_pct() {
        println!("File:   {:.1}% smaller", pct);
    }

    println!();
    println!("── Token Estimates ─────────────────────────────────────────");
    let table = token_savings_table(orig_w, orig_h, result.width, result.height);
    table.print();
    println!("────────────────────────────────────────────────────────────");
    println!("{}", out_path.display());

    // Log to DB for Analytics
    let target_model_name = match cfg.target_model {
        Some(VisionModel::Claude) => "Claude",
        Some(VisionModel::Gpt4o) => "GPT-4o",
        Some(VisionModel::Gpt5) => "GPT-5",
        Some(VisionModel::Gemini15) => "Gemini",
        None => "Agnostic",
    };

    let m = cfg.target_model.unwrap_or(VisionModel::Claude);
    let orig_tokens = vision_squeezer::estimate_tokens(orig_w, orig_h, m).tokens;
    let opt_tokens = vision_squeezer::estimate_tokens(result.width, result.height, m).tokens;

    let _ = vision_squeezer::Persistence::log_optimization(
        target_model_name,
        orig_tokens,
        opt_tokens,
        input_bytes,
        output_bytes,
        &format!("{:?}", mode),
    );
}

fn print_hook_script() {
    println!(
        r#"
# VisionSqueezer Shell Hook
# Add this to your .zshrc or .bashrc:
#   eval "$(vision-squeezer setup-hook)"

# The 'squeeze' command: optimizes an image and returns the new path
squeeze() {{
    if [ -z "$1" ]; then
        echo "Usage: squeeze <file> [options]"
        return 1
    fi
    local input="$1"
    local output="${{input%.*}}.squeezed.${{input##*.}}"
    vision-squeezer "$input" --output "$output" "${{@:2}}" > /dev/null
    if [ -f "$output" ]; then
        echo "$output"
    else
        echo "Error: Optimization failed"
        return 1
    fi
}}

# Aliases for quick analytics
alias vision-stats='vision-squeezer stats'
alias /vision-stats='vision-squeezer stats'

# Install /vision-stats Claude Code skill (zero-overhead stats — no MCP round-trip)
_vs_install_skill() {{
    local skill_dir="$HOME/.claude/skills/vision-stats"
    local skill_file="$skill_dir/SKILL.md"
    local bin
    bin="$(command -v vision-squeezer 2>/dev/null || echo 'vision-squeezer')"
    if [ ! -f "$skill_file" ]; then
        mkdir -p "$skill_dir"
        cat > "$skill_file" << 'SKILL_EOF'
---
name: vision-stats
description: >
  Show VisionSqueezer cumulative token & byte savings analytics. Zero MCP
  overhead — reads directly from local stats.db via CLI binary. Use when user
  says "vision-stats", "squeeze stats", "token savings", "how much saved",
  "vision-squeezer stats", "optimization history", or "/vision-stats".
allowed-tools: Bash
---

# vision-stats — VisionSqueezer Analytics Skill

Zero-overhead stats. Calls `vision-squeezer stats` directly — no MCP round-trip.

## Trigger

`/vision-stats` or any of: "vision stats", "squeeze stats", "show savings", "how much have I saved", "optimization stats"

## Action

Run this binary resolution chain, stop at first success:

```bash
vision-squeezer stats 2>/dev/null \
  || ~/.cargo/bin/vision-squeezer stats 2>/dev/null \
  || "$(dirname "$(command -v vision-squeezer-mcp 2>/dev/null)")/vision-squeezer" stats 2>/dev/null \
  || find "$HOME/.cargo/bin" "$HOME/Desktop" "$HOME/Projects" -maxdepth 6 -name "vision-squeezer" -not -path "*/deps/*" -not -path "*/debug/*" 2>/dev/null | head -1 | xargs -I{{}} {{}} stats 2>/dev/null \
  || echo "vision-squeezer not found. Install: cargo install --git https://github.com/eralpozcan/vision-squeezer"
```

Print output verbatim. No wrapping, no commentary, no interpretation.

## Error handling

Binary not found → tell user to run `cargo install --path .` from project root or `eval "$(vision-squeezer setup-hook)"` after install.

## Notes

- Stats persist in local stats.db on the user's machine
- MCP tool `get_savings_stats` does the same but costs ~150 tokens overhead — use this skill instead
SKILL_EOF
        echo "[vision-squeezer] /vision-stats skill installed → $skill_file"
    fi
}}
_vs_install_skill
unset -f _vs_install_skill

# Install /vision-doctor Claude Code skill (version check + update guidance)
_vs_install_doctor_skill() {{
    local skill_dir="$HOME/.claude/skills/vision-doctor"
    local skill_file="$skill_dir/SKILL.md"
    if [ ! -f "$skill_file" ]; then
        mkdir -p "$skill_dir"
        cat > "$skill_file" << 'SKILL_EOF'
---
name: vision-doctor
description: >
  Check VisionSqueezer installation health and version status. Detects installed
  version, compares against latest npm release, and shows update command if outdated.
  Use when user says "vision-doctor", "check vision-squeezer version", "update vision-squeezer",
  "is vision-squeezer up to date", "upgrade vision-squeezer", or "/vision-doctor".
allowed-tools: Bash
---

# vision-doctor — VisionSqueezer Health Check Skill

Checks binary installation, current version, and latest available version.

## Trigger

`/vision-doctor` or any of: "vision doctor", "check vision-squeezer", "update vision-squeezer",
"is vision-squeezer up to date", "upgrade vision-squeezer", "vision-squeezer version"

## Action

Run the following shell script:

```bash
BIN=$(command -v vision-squeezer 2>/dev/null)
if [ -z "$BIN" ] && [ -x "$HOME/.cargo/bin/vision-squeezer" ]; then
  BIN="$HOME/.cargo/bin/vision-squeezer"
fi
if [ -n "$BIN" ] && [ -x "$BIN" ]; then
  INSTALLED=$("$BIN" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
else
  INSTALLED=""
  BIN=""
fi
LATEST=$(npm view vision-squeezer version 2>/dev/null)
MCP_CMD=$(claude mcp list 2>/dev/null | grep vision-squeezer | head -1 || echo "")
echo "BIN=$BIN"
echo "INSTALLED=$INSTALLED"
echo "LATEST=$LATEST"
echo "MCP=$MCP_CMD"
```

## Output format

Display as a markdown checklist:

```
## VisionSqueezer Doctor

- [x/ ] Binary found: <path or "not found (using npx)">
- [x/ ] Installed version: <version or "n/a — npx always pulls latest">
- [x/ ] Latest version (npm): <version>
- [x/ ] MCP registered: <yes/no>
- [x/ ] Status: <see below>
```

### Status logic

| Condition | Status |
|-----------|--------|
| `INSTALLED` == `LATEST` | ✅ Up to date |
| `INSTALLED` != `LATEST`, both non-empty | ⚠️ Update available — run `/vision-upgrade` |
| `BIN` empty, `MCP` contains "npx" | ✅ Using npx — always latest, no action needed |
| `BIN` empty, no MCP | ❌ Not installed |

### If update available:

```
Update available: v<INSTALLED> → v<LATEST>
Run /vision-upgrade to update.
```

### If not installed:

```
## VisionSqueezer not found

Install via Claude Code (one-liner):
  claude mcp add vision-squeezer -- npx -y vision-squeezer
```

## Notes

- `npx -y vision-squeezer` users are always on latest — show this as ✅, not an error
- cargo install users must run `/vision-upgrade` or `cargo install vision-squeezer` to upgrade
SKILL_EOF
        echo "[vision-squeezer] /vision-doctor skill installed → $skill_file"
    fi
}}
_vs_install_doctor_skill
unset -f _vs_install_doctor_skill

# Install /vision-upgrade Claude Code skill (upgrade to latest)
_vs_install_upgrade_skill() {{
    local skill_dir="$HOME/.claude/skills/vision-upgrade"
    local skill_file="$skill_dir/SKILL.md"
    if [ ! -f "$skill_file" ]; then
        mkdir -p "$skill_dir"
        cat > "$skill_file" << 'SKILL_EOF'
---
name: vision-upgrade
description: >
  Upgrade VisionSqueezer to the latest version. Detects install method (cargo, npm global, npx)
  and runs the correct update command. Use when user says "vision-upgrade", "upgrade vision-squeezer",
  "update vision-squeezer", or "/vision-upgrade".
allowed-tools: Bash
---

# vision-upgrade — VisionSqueezer Upgrade Skill

Detects install method and upgrades to latest.

## Trigger

`/vision-upgrade` or any of: "vision upgrade", "upgrade vision-squeezer", "update vision-squeezer", "install latest vision-squeezer"

## Action

Run the following detection script first:

```bash
BIN=$(command -v vision-squeezer 2>/dev/null)
[ -z "$BIN" ] && [ -x "$HOME/.cargo/bin/vision-squeezer" ] && BIN="$HOME/.cargo/bin/vision-squeezer"
INSTALLED=""
[ -n "$BIN" ] && [ -x "$BIN" ] && INSTALLED=$("$BIN" --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
LATEST=$(npm view vision-squeezer version 2>/dev/null)
NPM_GLOBAL=$(npm list -g vision-squeezer --depth=0 2>/dev/null | grep vision-squeezer | head -1)
echo "BIN=$BIN"
echo "INSTALLED=$INSTALLED"
echo "LATEST=$LATEST"
echo "NPM_GLOBAL=$NPM_GLOBAL"
```

### Then run the appropriate upgrade command:

**If `NPM_GLOBAL` non-empty** (npm global install):
```bash
npm install -g vision-squeezer
```

**If `BIN` contains `.cargo`** (cargo install):
```bash
cargo install vision-squeezer
```

**If `BIN` empty** (npx user):
No action needed — npx always pulls latest. Confirm to user.

### After upgrade, verify:
```bash
vision-squeezer --version 2>/dev/null || ~/.cargo/bin/vision-squeezer --version 2>/dev/null
```

## Output format

```
## VisionSqueezer Upgrade

- [ ] Detected install method: <cargo / npm global / npx>
- [ ] Version before: v<INSTALLED or "n/a">
- [ ] Running upgrade...
- [ ] Version after: v<NEW_VERSION>
- [ ] Status: ✅ Updated to v<LATEST> / ✅ Already on latest (npx)
```

## Notes

- npx users: always on latest, no upgrade needed — tell them explicitly
- If cargo install fails (no Rust): suggest switching to npx with `claude mcp add vision-squeezer -- npx -y vision-squeezer`
SKILL_EOF
        echo "[vision-squeezer] /vision-upgrade skill installed → $skill_file"
    fi
}}
_vs_install_upgrade_skill
unset -f _vs_install_upgrade_skill
"#
    );
}

fn print_stats() {
    match vision_squeezer::Persistence::get_stats() {
        Ok(stats) => {
            println!("\x1b[1m── VisionSqueezer Analytics ────────────────────────────────\x1b[0m");
            println!("Total Optimizations: {}", stats.total_optimizations);
            println!(
                "Total Tokens Saved:  \x1b[32m{}\x1b[0m",
                stats.total_token_savings()
            );
            println!(
                "Total Bytes Saved:   \x1b[32m{:.2} MB\x1b[0m",
                stats.total_byte_savings() as f64 / 1_048_576.0
            );
            println!(
                "Estimated USD Saved: \x1b[35m${:.2}\x1b[0m",
                stats.estimated_usd_saved()
            );
            println!("────────────────────────────────────────────────────────────");
            if !stats.history.is_empty() {
                println!("\x1b[2mLast 5 operations:\x1b[0m");
                for (i, op) in stats.history.iter().take(5).enumerate() {
                    let date = op.timestamp.split('T').next().unwrap_or("");
                    println!(
                        "{}. {} | {:8} | {}{} tokens",
                        i + 1,
                        date,
                        op.model,
                        op.original_tokens,
                        op.optimized_tokens
                    );
                }
            }
        }
        Err(e) => eprintln!("Error retrieving stats: {}", e),
    }
}