blazediff-interpret 6.4.1

Structured region analysis for image diffs: classify what changed, not just where
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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use super::content_analysis::{ContentEvidence, BG_BLEND_THRESHOLD};
use super::types::{
    BoundingBox, ChangeType, ChromaStats, ClassificationSignals, ColorDeltaStats, GradientStats,
    ShapeStats,
};

/// NCC threshold above which the luminance pattern is treated as preserved
/// (i.e. the edit is a recolor on existing structure rather than a structural
/// replacement). Tuned against inpaint-style edits where pure binary edge
/// agreement saturates but raw luminance still tracks closely.
const STRUCTURE_PRESERVED_NCC: f32 = 0.55;
/// NCC threshold below which the structure is treated as genuinely replaced
/// (content change rather than recolor). Calibrated against inpaintcoco
/// where the ColorChange/ContentChange label boundary sits near NCC=0 — we
/// gate ContentChange on *both* low NCC and a patchy color delta so noisy
/// but structurally preserved recolors still get the ColorChange label.
const STRUCTURE_REPLACED_NCC: f32 = 0.05;
/// Asymmetry margin required to claim Addition/Deletion when the bg-blend
/// signal is ambiguous. Computed as `edge_score_img2 - edge_score_img1`.
const STRUCTURE_ASYMMETRY_MARGIN: f32 = 0.04;
/// Minimum YIQ-normalized mean delta needed to admit a ColorChange when the
/// `low_color_delta` flag is otherwise true. YIQ weights chroma less than
/// luminance, so a clearly visible chromatic-only recolor (e.g. Tailwind
/// `text-blue-600` → `text-red-600`, both ~equal luminance) lands around
/// 0.005–0.05 here — well above this floor but below `low_color_delta=0.05`.
/// Sub-threshold recolors (every pixel under the refine floor, kept by the
/// coarse-mask fallback) dilute the mean well below 0.001, so the floor sits
/// just above single-LSB jitter (~2.8e-5); the NCC>0.88 + correlated-edges
/// gate carries the rest of the burden.
const RECOLOR_MIN_MEAN_DELTA: f32 = 0.00005;
/// Stricter NCC gate for the low-delta chromatic-recolor branch. Tighter than
/// `STRUCTURE_PRESERVED_NCC` so we don't admit photographic edits where
/// structure is only weakly preserved — empirical floor on html_color_pairs
/// UI recolors is NCC=0.88, so 0.88 keeps them while filtering noise.
const CHROMATIC_RECOLOR_NCC: f32 = 0.88;
/// Mean chroma-delta magnitude above which a photographic edit moved color
/// mass enough to read as a recolor, provided the movement is coherent.
/// Calibrated on inpaintcoco's ColorChange/ContentChange boundary.
const CHROMA_DELTA_RECOLOR_FLOOR: f32 = 0.131;
/// Chroma cosine below which the hues genuinely rotated (a recolor). Above
/// it the colors stayed in the same family, which for a large chroma delta
/// means texture moved rather than hue — a content change.
const CHROMA_SAME_HUE_COS: f32 = 0.235;
/// Mean |ΔQ| floor: even same-hue-family edits with substantial movement on
/// the Q axis (purple↔green) read as recolors.
const CHROMA_DQ_RECOLOR_FLOOR: f32 = 0.071;
/// img1 saturation below which a large chroma delta means color was
/// *introduced* onto drab content — a recolor, whatever the hue cosine says.
const CHROMA_DRAB_SAT: f32 = 0.072;
/// Chroma-delta roughness above which a large chroma move is scattered
/// pixel noise (checkerboard-style replacement), not a recolor. Real
/// recolors — even diffusion-regenerated ones — stay below ~0.3.
const CHROMA_ROUGH_CEIL: f32 = 0.75;
/// Consistent luminance push (signed mean ΔY) that reads as a lighten/darken
/// recolor when the chroma barely moved.
const LUMA_PUSH_UP: f32 = 0.268;
const LUMA_PUSH_DOWN: f32 = -0.150;
/// Edge-density ceiling for the darken-recolor branch: darkening that also
/// grows new structure is a content change, not a recolor.
const LUMA_PUSH_EDGE_CEIL: f32 = 0.101;

pub fn classify_change_type(
    content: &ContentEvidence,
    color_delta: &ColorDeltaStats,
    gradient: &GradientStats,
    shape_stats: &ShapeStats,
    chroma: &ChromaStats,
    bbox: &BoundingBox,
    luminance_ncc: f32,
) -> (ChangeType, ClassificationSignals) {
    let bbox_area = bbox.width as u64 * bbox.height as u64;
    let tiny_region = bbox_area <= 25;
    let low_color_delta = color_delta.mean_delta < 0.05;
    let low_edge_change = gradient.edge_score < 0.05;
    let low_edge_img2 = gradient.edge_score_img2 < 0.05;
    let both_low_edges = low_edge_change && low_edge_img2;
    let edges_correlated = both_low_edges || gradient.edge_correlation > 0.85;
    let dense_fill = shape_stats.fill_ratio > 0.6;
    let sparse_fill = shape_stats.fill_ratio < 0.35;
    let blends_bg1 = content.bg_distance_img1 < BG_BLEND_THRESHOLD
        || (content.bg_distance_img2 > BG_BLEND_THRESHOLD
            && content.bg_distance_img1 < content.bg_distance_img2 * 0.5);
    let blends_bg2 = content.bg_distance_img2 < BG_BLEND_THRESHOLD
        || (content.bg_distance_img1 > BG_BLEND_THRESHOLD
            && content.bg_distance_img2 < content.bg_distance_img1 * 0.5);
    let structure_asymmetry = gradient.edge_score_img2 - gradient.edge_score;
    let structure_preserved = luminance_ncc > STRUCTURE_PRESERVED_NCC;
    let structure_replaced = luminance_ncc < STRUCTURE_REPLACED_NCC;

    let mut signals = ClassificationSignals {
        blends_with_bg_in_img1: blends_bg1,
        blends_with_bg_in_img2: blends_bg2,
        low_color_delta,
        low_edge_change,
        dense_fill,
        sparse_fill,
        tiny_region,
        edges_correlated,
        luminance_ncc,
        structure_asymmetry,
        bg_distance_img1: content.bg_distance_img1 as f32,
        bg_distance_img2: content.bg_distance_img2 as f32,
        confidence: 0.0,
    };

    // Strong bg-blend asymmetry is the addition/deletion signature: one image
    // blends into the local background where the other holds distinct content.
    // Sparse-but-real edits (thin strokes, faint text, a block vacated to
    // background fill) carry it, so it vetoes the sparse-noise rule below.
    let strong_bg_asymmetry = (blends_bg1
        && !blends_bg2
        && content.bg_distance_img2 > content.bg_distance_img1 * 2.0)
        || (blends_bg2 && !blends_bg1 && content.bg_distance_img1 > content.bg_distance_img2 * 2.0);

    // Rule 1: RenderingNoise - tiny regions with subtle color delta
    if tiny_region && low_color_delta {
        signals.confidence = 1.0;
        return (ChangeType::RenderingNoise, signals);
    }

    // Rule 2: RenderingNoise - sparse, subtle noise without an add/delete
    // signature
    if sparse_fill && low_color_delta && low_edge_change && !strong_bg_asymmetry {
        signals.confidence = matched_ratio(&[sparse_fill, low_color_delta, low_edge_change]);
        return (ChangeType::RenderingNoise, signals);
    }

    // Rule 3: Addition - img1 blends with bg, img2 carries distinct content.
    // Require either a strong bg-blend asymmetry or img2 gaining structure
    // that img1 didn't have, so inpaint-style ColorChange edits (where both
    // images carry plausible content) don't get pulled in.
    if blends_bg1 && !blends_bg2 {
        let strong_bg_asymmetry = content.bg_distance_img2 > content.bg_distance_img1 * 2.0;
        let gained_structure = structure_asymmetry > STRUCTURE_ASYMMETRY_MARGIN;
        if strong_bg_asymmetry || gained_structure || !structure_preserved {
            let edge_boost = low_edge_change && !low_edge_img2;
            signals.confidence = if edge_boost { 1.0 } else { 0.9 };
            return (ChangeType::Addition, signals);
        }
    }

    // Rule 4: Deletion - mirror of Rule 3.
    if !blends_bg1 && blends_bg2 {
        let strong_bg_asymmetry = content.bg_distance_img1 > content.bg_distance_img2 * 2.0;
        let lost_structure = structure_asymmetry < -STRUCTURE_ASYMMETRY_MARGIN;
        if strong_bg_asymmetry || lost_structure || !structure_preserved {
            let edge_boost = !low_edge_change && low_edge_img2;
            signals.confidence = if edge_boost { 1.0 } else { 0.9 };
            return (ChangeType::Deletion, signals);
        }
    }

    // Rule 5: ColorChange - meaningful color shift over an existing visual
    // pattern, evidenced by preserved luminance structure. This is the
    // graphical/UI recolor path: high NCC means the edit recolored existing
    // content rather than replacing it.
    //
    // The `!low_color_delta` gate is loosened when structure is strongly
    // preserved (high NCC, correlated edges): YIQ weights luminance heavily,
    // so chromatic-only recolors on rendered UI (Tailwind text-blue → text-red
    // at matching luminance) produce a tiny mean delta but are unmistakably
    // visible. Rules 1 and 2 still take RenderingNoise cases first, so this
    // only affects non-tiny, non-sparse regions with confirmed structure.
    let highly_patchy = color_delta.delta_stddev > color_delta.mean_delta * 2.0 + 0.1;
    let chromatic_recolor = luminance_ncc > CHROMATIC_RECOLOR_NCC
        && edges_correlated
        && color_delta.mean_delta > RECOLOR_MIN_MEAN_DELTA;
    let delta_evidence = !low_color_delta || chromatic_recolor;
    if delta_evidence && !(structure_replaced && highly_patchy) && structure_preserved {
        let ncc_boost = luminance_ncc.max(0.0);
        signals.confidence =
            ((color_delta.mean_delta * 5.0).min(1.0) * 0.5 + ncc_boost * 0.5).clamp(0.0, 1.0);
        return (ChangeType::ColorChange, signals);
    }

    // Rule 5b: photographic recolor. Inpaint-style edits regenerate texture,
    // so pixel-level NCC saturates low for recolors and replacements alike;
    // what separates them is how the *chroma* moved. A recolor moves color
    // mass coherently — a hue rotation (low chroma cosine), color introduced
    // onto drab content, or a strong movement on the Q axis — while a
    // replacement shuffles texture and leaves hues in the same family.
    let big_chroma_move =
        chroma.mean_abs_dc > CHROMA_DELTA_RECOLOR_FLOOR && chroma.chroma_rough < CHROMA_ROUGH_CEIL;
    if big_chroma_move {
        let same_hue_family = chroma.chroma_cos > CHROMA_SAME_HUE_COS
            && chroma.mean_abs_dq <= CHROMA_DQ_RECOLOR_FLOOR
            && chroma.sat1 > CHROMA_DRAB_SAT;
        if !same_hue_family {
            signals.confidence = (chroma.mean_abs_dc * 3.0).clamp(0.0, 1.0) * 0.5 + 0.25;
            return (ChangeType::ColorChange, signals);
        }
    } else {
        // Small chroma move: only a consistent luminance push (lighten/darken
        // of the same content) still reads as a recolor. Darkening that also
        // grows new edge structure is content, not color.
        let lighten = chroma.mean_dy > LUMA_PUSH_UP;
        let darken =
            chroma.mean_dy <= LUMA_PUSH_DOWN && gradient.edge_score_img2 <= LUMA_PUSH_EDGE_CEIL;
        if lighten || darken {
            signals.confidence = 0.6;
            return (ChangeType::ColorChange, signals);
        }
    }

    // Rule 6: ContentChange - fallback
    signals.confidence = 0.5;
    (ChangeType::ContentChange, signals)
}

fn matched_ratio(conditions: &[bool]) -> f32 {
    let matched = conditions.iter().filter(|&&c| c).count();
    matched as f32 / conditions.len() as f32
}

#[cfg(test)]
mod tests {
    use super::*;

    fn neutral_chroma() -> ChromaStats {
        ChromaStats {
            mean_abs_dy: 0.0,
            mean_dy: 0.0,
            mean_abs_di: 0.0,
            mean_abs_dq: 0.0,
            mean_abs_dc: 0.0,
            chroma_cos: 1.0,
            sat1: 0.0,
            sat2: 0.0,
            chroma_rough: 0.0,
        }
    }

    fn default_shape_stats() -> ShapeStats {
        ShapeStats {
            fill_ratio: 0.5,
            border_ratio: 0.3,
            inner_fill_ratio: 0.5,
            center_density: 0.5,
            row_occupancy: 0.5,
            col_occupancy: 0.5,
        }
    }

    fn square_bbox() -> BoundingBox {
        BoundingBox {
            x: 0,
            y: 0,
            width: 100,
            height: 100,
        }
    }

    fn blends_both() -> ContentEvidence {
        ContentEvidence {
            bg_distance_img1: 0.01,
            bg_distance_img2: 0.01,
        }
    }

    fn no_blends() -> ContentEvidence {
        ContentEvidence {
            bg_distance_img1: 0.50,
            bg_distance_img2: 0.50,
        }
    }

    /// Gradient stats where both images have no edges (flat regions, high correlation).
    fn flat_gradient() -> GradientStats {
        GradientStats {
            edge_score: 0.01,
            edge_score_img2: 0.01,
            edge_correlation: 0.99,
        }
    }

    /// Gradient stats where both images have similar edge structure.
    fn correlated_edges() -> GradientStats {
        GradientStats {
            edge_score: 0.20,
            edge_score_img2: 0.18,
            edge_correlation: 0.92,
        }
    }

    /// Gradient stats where img1 has edges but img2 doesn't (content removed).
    fn img1_only_edges() -> GradientStats {
        GradientStats {
            edge_score: 0.30,
            edge_score_img2: 0.02,
            edge_correlation: 0.40,
        }
    }

    /// Gradient stats where img2 has edges but img1 doesn't (content added).
    fn img2_only_edges() -> GradientStats {
        GradientStats {
            edge_score: 0.02,
            edge_score_img2: 0.30,
            edge_correlation: 0.40,
        }
    }

    /// Gradient stats with high edges in both but low correlation (structural change).
    fn uncorrelated_edges() -> GradientStats {
        GradientStats {
            edge_score: 0.30,
            edge_score_img2: 0.25,
            edge_correlation: 0.40,
        }
    }

    #[test]
    fn test_rendering_noise_tiny() {
        let (ct, signals) = classify_change_type(
            &blends_both(),
            &ColorDeltaStats {
                mean_delta: 0.01,
                max_delta: 0.02,
                delta_stddev: 0.005,
            },
            &flat_gradient(),
            &default_shape_stats(),
            &neutral_chroma(),
            &BoundingBox {
                x: 50,
                y: 50,
                width: 1,
                height: 1,
            },
            1.0,
        );
        assert_eq!(ct, ChangeType::RenderingNoise);
        assert!(signals.tiny_region);
        assert_eq!(signals.confidence, 1.0);
    }

    #[test]
    fn test_rendering_noise_sparse() {
        let stats = ShapeStats {
            fill_ratio: 0.10,
            ..default_shape_stats()
        };
        let (ct, signals) = classify_change_type(
            &blends_both(),
            &ColorDeltaStats {
                mean_delta: 0.02,
                max_delta: 0.04,
                delta_stddev: 0.01,
            },
            &flat_gradient(),
            &stats,
            &neutral_chroma(),
            &square_bbox(),
            1.0,
        );
        assert_eq!(ct, ChangeType::RenderingNoise);
        assert!(signals.sparse_fill);
        assert!(signals.low_color_delta);
        assert!(signals.low_edge_change);
    }

    #[test]
    fn test_addition() {
        let content = ContentEvidence {
            bg_distance_img1: 0.02,
            bg_distance_img2: 0.40,
        };
        let (ct, signals) = classify_change_type(
            &content,
            &ColorDeltaStats {
                mean_delta: 0.30,
                max_delta: 0.50,
                delta_stddev: 0.05,
            },
            &img2_only_edges(),
            &default_shape_stats(),
            &neutral_chroma(),
            &square_bbox(),
            0.0,
        );
        assert_eq!(ct, ChangeType::Addition);
        assert!(signals.blends_with_bg_in_img1);
        assert!(!signals.blends_with_bg_in_img2);
        // Edge boost: img1 has no edges, img2 does
        assert_eq!(signals.confidence, 1.0);
    }

    #[test]
    fn test_deletion() {
        let content = ContentEvidence {
            bg_distance_img1: 0.40,
            bg_distance_img2: 0.02,
        };
        let (ct, signals) = classify_change_type(
            &content,
            &ColorDeltaStats {
                mean_delta: 0.30,
                max_delta: 0.50,
                delta_stddev: 0.05,
            },
            &img1_only_edges(),
            &default_shape_stats(),
            &neutral_chroma(),
            &square_bbox(),
            0.0,
        );
        assert_eq!(ct, ChangeType::Deletion);
        assert!(!signals.blends_with_bg_in_img1);
        assert!(signals.blends_with_bg_in_img2);
        // Edge boost: img1 has edges, img2 lost them
        assert_eq!(signals.confidence, 1.0);
    }

    #[test]
    fn test_color_change_correlated_edges() {
        // Both images have similar edge structure, moderate color delta → ColorChange
        let (ct, signals) = classify_change_type(
            &no_blends(),
            &ColorDeltaStats {
                mean_delta: 0.20,
                max_delta: 0.30,
                delta_stddev: 0.03,
            },
            &correlated_edges(),
            &default_shape_stats(),
            &neutral_chroma(),
            &square_bbox(),
            0.95,
        );
        assert_eq!(ct, ChangeType::ColorChange);
        assert!(signals.edges_correlated);
        assert!(signals.confidence > 0.5);
    }

    #[test]
    fn test_color_change_flat_both() {
        // Both images are flat (no edges), high correlation, meaningful color delta → ColorChange
        let (ct, _) = classify_change_type(
            &no_blends(),
            &ColorDeltaStats {
                mean_delta: 0.20,
                max_delta: 0.30,
                delta_stddev: 0.03,
            },
            &flat_gradient(),
            &default_shape_stats(),
            &neutral_chroma(),
            &square_bbox(),
            1.0,
        );
        assert_eq!(ct, ChangeType::ColorChange);
    }

    #[test]
    fn test_low_delta_preserved_structure_is_color_change() {
        // Both flat, low color delta, NCC=1.0, edges correlated → ColorChange.
        // Chromatic-only recolors on UI (matching luminance) live in this
        // regime: YIQ delta is small but the structure is unchanged.
        let stats = ShapeStats {
            fill_ratio: 0.95,
            ..default_shape_stats()
        };
        let (ct, _) = classify_change_type(
            &no_blends(),
            &ColorDeltaStats {
                mean_delta: 0.02,
                max_delta: 0.04,
                delta_stddev: 0.01,
            },
            &flat_gradient(),
            &stats,
            &neutral_chroma(),
            &square_bbox(),
            1.0,
        );
        assert_eq!(ct, ChangeType::ColorChange);
    }

    #[test]
    fn test_subnoise_delta_falls_through_to_content_change() {
        // Even with preserved structure, a delta below RECOLOR_MIN_MEAN_DELTA
        // does not get upgraded — keeps sub-noise jitter out of ColorChange.
        let stats = ShapeStats {
            fill_ratio: 0.95,
            ..default_shape_stats()
        };
        let (ct, _) = classify_change_type(
            &no_blends(),
            &ColorDeltaStats {
                mean_delta: 0.00002,
                max_delta: 0.00003,
                delta_stddev: 0.00001,
            },
            &flat_gradient(),
            &stats,
            &neutral_chroma(),
            &square_bbox(),
            1.0,
        );
        assert_eq!(ct, ChangeType::ContentChange);
    }

    #[test]
    fn test_content_change_uncorrelated_edges() {
        // Both have edges but in different places → ContentChange
        let (ct, signals) = classify_change_type(
            &no_blends(),
            &ColorDeltaStats {
                mean_delta: 0.50,
                max_delta: 0.80,
                delta_stddev: 0.25,
            },
            &uncorrelated_edges(),
            &default_shape_stats(),
            &neutral_chroma(),
            &square_bbox(),
            0.0,
        );
        assert_eq!(ct, ChangeType::ContentChange);
        assert!(!signals.edges_correlated);
        assert_eq!(signals.confidence, 0.5);
    }

    #[test]
    fn test_tiny_region_high_color_not_noise() {
        let content = ContentEvidence {
            bg_distance_img1: 0.01,
            bg_distance_img2: 0.40,
        };
        let (ct, _) = classify_change_type(
            &content,
            &ColorDeltaStats {
                mean_delta: 0.50,
                max_delta: 0.50,
                delta_stddev: 0.02,
            },
            &img2_only_edges(),
            &default_shape_stats(),
            &neutral_chroma(),
            &BoundingBox {
                x: 50,
                y: 50,
                width: 1,
                height: 1,
            },
            0.0,
        );
        assert_eq!(ct, ChangeType::Addition);
    }
}