labelize 0.5.0

Fast Rust engine to parse ZPL & EPL label data and render to PNG/PDF. CLI, HTTP microservice, or library. Open-source Labelary alternative.
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
/// Analyzes which ZPL elements contribute most to the pixel diff.
use std::path::Path;

use image::RgbaImage;

use crate::elements::label_element::LabelElement;
use crate::elements::label_info::LabelInfo;

use super::error::AnalyzeError;
use super::models::{ElementBBox, ElementDiffContribution, ElementType};

/// Compute bounding box for a rendered element.
pub fn compute_element_bbox(element: &LabelElement, index: usize) -> Option<ElementBBox> {
    match element {
        LabelElement::Text(t) => {
            let font = &t.font;
            let h = font.height.max(10.0) as i32;
            let w = if let Some(ref block) = t.block {
                block.max_width.max(1)
            } else {
                // Estimate text width from font and data length
                let char_w = (font.width.max(1.0) * font.get_scale_x()) as i32;
                (char_w * t.text.len() as i32).max(1)
            };
            let block_h = if let Some(ref block) = t.block {
                let lines = block.max_lines.max(1);
                h * lines + block.line_spacing * (lines - 1)
            } else {
                h
            };
            Some(ElementBBox {
                x: t.position.x,
                y: t.position.y,
                width: w,
                height: block_h,
                element_index: index,
                element_type: ElementType::Text,
                zpl_command: "^A/^FD".to_string(),
            })
        }
        LabelElement::GraphicBox(g) => Some(ElementBBox {
            x: g.position.x,
            y: g.position.y,
            width: g.width.max(1),
            height: g.height.max(1),
            element_index: index,
            element_type: ElementType::GraphicBox,
            zpl_command: "^GB".to_string(),
        }),
        LabelElement::GraphicCircle(g) => Some(ElementBBox {
            x: g.position.x,
            y: g.position.y,
            width: g.circle_diameter.max(1),
            height: g.circle_diameter.max(1),
            element_index: index,
            element_type: ElementType::GraphicCircle,
            zpl_command: "^GC".to_string(),
        }),
        LabelElement::DiagonalLine(g) => Some(ElementBBox {
            x: g.position.x,
            y: g.position.y,
            width: g.width.max(1),
            height: g.height.max(1),
            element_index: index,
            element_type: ElementType::DiagonalLine,
            zpl_command: "^GD".to_string(),
        }),
        LabelElement::GraphicField(g) => {
            let rows = if g.row_bytes > 0 {
                g.total_bytes / g.row_bytes
            } else {
                1
            };
            Some(ElementBBox {
                x: g.position.x,
                y: g.position.y,
                width: (g.row_bytes * 8 * g.magnification_x).max(1),
                height: (rows * g.magnification_y).max(1),
                element_index: index,
                element_type: ElementType::GraphicField,
                zpl_command: "^GF".to_string(),
            })
        }
        LabelElement::Barcode128(b) => {
            // Width is pre-calculated by the parser
            let w = (b.width * 11 + 35).max(1); // rough estimate: 11 modules per char + start/stop
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: w,
                height: b.barcode.height.max(1),
                element_index: index,
                element_type: ElementType::Barcode128,
                zpl_command: "^BC".to_string(),
            })
        }
        LabelElement::BarcodeEan13(b) => {
            // EAN-13 is always 95 modules wide
            let w = 95 * b.width.max(1);
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: w,
                height: b.barcode.height.max(1),
                element_index: index,
                element_type: ElementType::BarcodeEan13,
                zpl_command: "^BE".to_string(),
            })
        }
        LabelElement::Barcode2of5(b) => {
            let data_len = b.data.len() as i32;
            let w = ((data_len * 2 + 3) * b.width.max(1) * 3).max(1);
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: w,
                height: b.barcode.height.max(1),
                element_index: index,
                element_type: ElementType::Barcode2of5,
                zpl_command: "^B2".to_string(),
            })
        }
        LabelElement::Barcode39(b) => {
            let data_len = b.data.len() as i32;
            let w = ((data_len + 2) * 13 * b.width.max(1)).max(1);
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: w,
                height: b.barcode.height.max(1),
                element_index: index,
                element_type: ElementType::Barcode39,
                zpl_command: "^B3".to_string(),
            })
        }
        LabelElement::BarcodePdf417(b) => {
            let cols = b.barcode.columns.max(1);
            let rows = b.barcode.rows.max(3);
            let mw = b.barcode.module_width.max(1);
            let w = (cols * 17 + 69) * mw;
            let h = rows * b.barcode.row_height.max(1);
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: w.max(1),
                height: h.max(1),
                element_index: index,
                element_type: ElementType::BarcodePdf417,
                zpl_command: "^B7".to_string(),
            })
        }
        LabelElement::BarcodeAztec(b) => {
            let mag = b.barcode.magnification.max(1);
            // Aztec default size depends on data; estimate conservatively
            let size = if b.barcode.size > 0 {
                b.barcode.size * mag
            } else {
                // Default: roughly 50 modules
                50 * mag
            };
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: size.max(1),
                height: size.max(1),
                element_index: index,
                element_type: ElementType::BarcodeAztec,
                zpl_command: "^BO".to_string(),
            })
        }
        LabelElement::BarcodeDatamatrix(b) => {
            let h = b.barcode.height.max(1);
            // DataMatrix is roughly square; height parameter controls module size
            let size = h * 10; // rough estimate
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: size.max(1),
                height: size.max(1),
                element_index: index,
                element_type: ElementType::BarcodeDatamatrix,
                zpl_command: "^BX".to_string(),
            })
        }
        LabelElement::BarcodeQr(b) => {
            let mag = b.barcode.magnification.max(1);
            // QR size depends on data; estimate
            let size = (21 + 4) * mag; // Version 1 + quiet zone
            Some(ElementBBox {
                x: b.position.x,
                y: b.position.y,
                width: size.max(1) * b.height.max(1),
                height: size.max(1) * b.height.max(1),
                element_index: index,
                element_type: ElementType::BarcodeQr,
                zpl_command: "^BQ".to_string(),
            })
        }
        LabelElement::Maxicode(m) => {
            // MaxiCode is always 1 inch square at any DPI
            // At 8 dpmm ≈ 200 DPI: ~200 pixels
            Some(ElementBBox {
                x: m.position.x,
                y: m.position.y,
                width: 200,
                height: 200,
                element_index: index,
                element_type: ElementType::Maxicode,
                zpl_command: "^BD".to_string(),
            })
        }
        // Config and template elements are not drawn
        _ => None,
    }
}

/// Count red diff pixels (R>200, G<50, B<50, A>200) in the entire image.
pub fn count_red_pixels(img: &RgbaImage) -> u64 {
    let mut count = 0u64;
    for pixel in img.pixels() {
        if pixel[0] > 200 && pixel[1] < 50 && pixel[2] < 50 && pixel[3] > 200 {
            count += 1;
        }
    }
    count
}

/// Count red diff pixels within a rectangular region.
pub fn count_red_pixels_in_rect(img: &RgbaImage, x1: i32, y1: i32, x2: i32, y2: i32) -> u64 {
    let mut count = 0u64;
    let img_w = img.width() as i32;
    let img_h = img.height() as i32;

    let x1 = x1.max(0);
    let y1 = y1.max(0);
    let x2 = x2.min(img_w);
    let y2 = y2.min(img_h);

    for y in y1..y2 {
        for x in x1..x2 {
            let pixel = img.get_pixel(x as u32, y as u32);
            if pixel[0] > 200 && pixel[1] < 50 && pixel[2] < 50 && pixel[3] > 200 {
                count += 1;
            }
        }
    }
    count
}

/// Correlate diff pixels with element bounding boxes.
pub fn correlate_diff_regions(
    diff_image: &RgbaImage,
    bboxes: &[ElementBBox],
) -> Vec<ElementDiffContribution> {
    let total_red = count_red_pixels(diff_image);
    if total_red == 0 {
        return Vec::new();
    }

    let mut contributions: Vec<ElementDiffContribution> = bboxes
        .iter()
        .map(|bbox| {
            let diff_in_bbox = count_red_pixels_in_rect(
                diff_image,
                bbox.x,
                bbox.y,
                bbox.x + bbox.width,
                bbox.y + bbox.height,
            );
            let total_in_bbox = (bbox.width as u64) * (bbox.height as u64);
            let local_diff = if total_in_bbox > 0 {
                diff_in_bbox as f64 / total_in_bbox as f64 * 100.0
            } else {
                0.0
            };
            let contribution = diff_in_bbox as f64 / total_red as f64 * 100.0;

            ElementDiffContribution {
                bbox: bbox.clone(),
                diff_pixels_in_bbox: diff_in_bbox,
                total_pixels_in_bbox: total_in_bbox,
                local_diff_percent: local_diff,
                contribution_to_total: contribution,
                classification: None,
                position_offset: None,
            }
        })
        .collect();

    // Sort by contribution descending
    contributions.sort_by(|a, b| {
        b.contribution_to_total
            .partial_cmp(&a.contribution_to_total)
            .unwrap_or(std::cmp::Ordering::Equal)
    });

    contributions
}

/// Analyze a label: parse ZPL → compute bboxes → load diff image → correlate.
///
/// Classification is NOT performed here (requires the original ZPL string and
/// optionally the Labelary API).  Use `analyze_label_with_classification()`
/// for the full pipeline.
pub fn analyze_label(
    label: &LabelInfo,
    diff_image_path: &Path,
) -> Result<Vec<ElementDiffContribution>, AnalyzeError> {
    // Compute bounding boxes
    let bboxes: Vec<ElementBBox> = label
        .elements
        .iter()
        .enumerate()
        .filter_map(|(i, el)| compute_element_bbox(el, i))
        .collect();

    if bboxes.is_empty() {
        return Err(AnalyzeError::NoElements);
    }

    // Load diff image
    let diff_img = image::open(diff_image_path)
        .map_err(|_| AnalyzeError::DiffImageNotFound {
            path: diff_image_path.display().to_string(),
        })?
        .to_rgba8();

    Ok(correlate_diff_regions(&diff_img, &bboxes))
}

/// Full pipeline: analyze + classify diffs as ContentDiff / PositionDiff / Mixed.
///
/// `label_zpl` is needed to extract isolated snippets for classification.
/// Pass `use_labelary = false` to skip network calls (offline/unit-test mode).
pub fn analyze_label_with_classification(
    label: &LabelInfo,
    diff_image_path: &Path,
    label_zpl: &str,
    use_labelary: bool,
) -> Result<Vec<ElementDiffContribution>, AnalyzeError> {
    use super::diff_classifier::{classify_element_diffs, ClassifyOptions};

    let mut contributions = analyze_label(label, diff_image_path)?;

    // Load diff image again for offset detection (already decoded once above,
    // but that image is not accessible here — open a second time).
    let diff_img = image::open(diff_image_path)
        .map_err(|_| AnalyzeError::DiffImageNotFound {
            path: diff_image_path.display().to_string(),
        })?
        .to_rgba8();

    let classify_opts = ClassifyOptions {
        use_labelary,
        ..Default::default()
    };

    classify_element_diffs(&mut contributions, label_zpl, &diff_img, &classify_opts)?;

    Ok(contributions)
}

/// Format analysis results as a human-readable report.
pub fn format_analysis_report(contributions: &[ElementDiffContribution]) -> String {
    use super::models::{DiffClassification, PositionOffsetInfo};

    let mut report = String::new();
    report.push_str("Element Diff Contribution Analysis\n");
    report.push_str("==================================\n\n");
    report.push_str(&format!(
        "{:<6} {:<16} {:<8} {:<12} {:<8} {:<10} {:<14} {}\n",
        "Index", "Type", "Command", "DiffPixels", "Local%", "Contrib%", "Classification", "Offset"
    ));
    report.push_str(&"-".repeat(95));
    report.push('\n');

    for c in contributions {
        if c.diff_pixels_in_bbox == 0 {
            continue;
        }
        let class_str = match &c.classification {
            None => "-".to_string(),
            Some(DiffClassification::ContentDiff) => "Content".to_string(),
            Some(DiffClassification::PositionDiff) => "Position".to_string(),
            Some(DiffClassification::Mixed) => "Mixed".to_string(),
        };
        let offset_str = match &c.position_offset {
            None => String::new(),
            Some(PositionOffsetInfo {
                dx, dy, confidence, ..
            }) => {
                format!("dx={:+} dy={:+} ({:.0}%)", dx, dy, confidence * 100.0)
            }
        };
        report.push_str(&format!(
            "{:<6} {:<16} {:<8} {:<12} {:<8.2} {:<10.2} {:<14} {}\n",
            c.bbox.element_index,
            format!("{:?}", c.bbox.element_type),
            c.bbox.zpl_command,
            c.diff_pixels_in_bbox,
            c.local_diff_percent,
            c.contribution_to_total,
            class_str,
            offset_str,
        ));
    }
    report
}