oximedia-dedup 0.1.3

Media deduplication and duplicate detection for OxiMedia
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
//! Policy types for controlling deduplication behaviour.
//!
//! Provides `DedupAction`, `DedupPolicy`, `DedupPolicyConfig`, and
//! `DedupDecision` so callers can codify rules about what to do when
//! duplicates are found.

#![allow(dead_code)]

/// Action to take when a duplicate is detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DedupAction {
    /// Delete the duplicate immediately.
    Delete,
    /// Move the duplicate to a quarantine directory.
    Quarantine,
    /// Create a symbolic link pointing to the canonical copy.
    Symlink,
    /// Keep both copies and emit a warning.
    Keep,
    /// Flag the item for manual review.
    Review,
    /// Skip (do nothing, log only).
    Skip,
}

impl DedupAction {
    /// Return `true` if this action permanently modifies or removes data.
    #[must_use]
    pub const fn is_destructive(self) -> bool {
        matches!(self, Self::Delete | Self::Quarantine)
    }

    /// Return a human-readable description of the action.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::Delete => "delete duplicate",
            Self::Quarantine => "move to quarantine",
            Self::Symlink => "replace with symlink",
            Self::Keep => "keep both copies",
            Self::Review => "flag for review",
            Self::Skip => "skip / log only",
        }
    }
}

/// Configures the deduplication policy.
#[derive(Debug, Clone)]
pub struct DedupPolicyConfig {
    /// Enable strict mode: require all selected methods to agree before acting.
    pub strict_mode: bool,
    /// Minimum similarity score (0.0–1.0) required to consider items duplicates.
    pub min_similarity: f64,
    /// Action applied when an exact duplicate is found (similarity == 1.0).
    pub exact_action: DedupAction,
    /// Action applied when a near-duplicate is found.
    pub near_action: DedupAction,
    /// Whether to protect files marked as originals from deletion.
    pub protect_originals: bool,
}

impl Default for DedupPolicyConfig {
    fn default() -> Self {
        Self {
            strict_mode: false,
            min_similarity: 0.95,
            exact_action: DedupAction::Quarantine,
            near_action: DedupAction::Review,
            protect_originals: true,
        }
    }
}

impl DedupPolicyConfig {
    /// Return `true` if strict mode is enabled.
    #[must_use]
    pub const fn strict_mode(&self) -> bool {
        self.strict_mode
    }

    /// Return the minimum similarity threshold.
    #[must_use]
    pub fn min_similarity(&self) -> f64 {
        self.min_similarity
    }
}

/// The computed deduplication decision for a candidate pair.
#[derive(Debug, Clone)]
pub struct DedupDecision {
    /// Similarity score in 0.0–1.0.
    pub similarity: f64,
    /// Chosen action.
    pub action: DedupAction,
    /// Whether the decision needs human review.
    pub needs_review: bool,
    /// Optional explanation string.
    pub reason: Option<String>,
}

impl DedupDecision {
    /// Create a new `DedupDecision`.
    #[must_use]
    pub fn new(similarity: f64, action: DedupAction, reason: Option<String>) -> Self {
        let needs_review =
            matches!(action, DedupAction::Review) || (action.is_destructive() && similarity < 1.0);
        Self {
            similarity,
            action,
            needs_review,
            reason,
        }
    }

    /// Return `true` if the decision requires human review before execution.
    #[must_use]
    pub fn requires_review(&self) -> bool {
        self.needs_review
    }
}

/// Evaluates pairs of media items according to a `DedupPolicyConfig`.
#[derive(Debug, Clone)]
pub struct DedupPolicy {
    config: DedupPolicyConfig,
}

impl DedupPolicy {
    /// Create a new `DedupPolicy` from a config.
    #[must_use]
    pub fn new(config: DedupPolicyConfig) -> Self {
        Self { config }
    }

    /// Decide whether two items with the given `similarity` should be deduped.
    ///
    /// Returns a `DedupDecision` describing what to do.
    #[must_use]
    pub fn should_dedup(&self, similarity: f64, is_original: bool) -> DedupDecision {
        // Guard: similarity below threshold → skip.
        if similarity < self.config.min_similarity {
            return DedupDecision::new(
                similarity,
                DedupAction::Skip,
                Some(format!(
                    "similarity {similarity:.3} below threshold {:.3}",
                    self.config.min_similarity
                )),
            );
        }

        // Guard: protect originals.
        if is_original && self.config.protect_originals {
            return DedupDecision::new(
                similarity,
                DedupAction::Keep,
                Some("file is marked as original".to_string()),
            );
        }

        // Exact duplicate.
        #[allow(clippy::float_cmp)]
        if similarity == 1.0 {
            let action = if self.config.strict_mode {
                self.config.exact_action
            } else {
                self.config.exact_action
            };
            return DedupDecision::new(
                similarity,
                action,
                Some("exact duplicate detected".to_string()),
            );
        }

        // Near-duplicate.
        DedupDecision::new(
            similarity,
            self.config.near_action,
            Some(format!("near-duplicate at {similarity:.3}")),
        )
    }

    /// Access the underlying config.
    #[must_use]
    pub const fn config(&self) -> &DedupPolicyConfig {
        &self.config
    }
}

impl Default for DedupPolicy {
    fn default() -> Self {
        Self::new(DedupPolicyConfig::default())
    }
}

// ---------------------------------------------------------------------------
// Per-group configurable dedup actions
// ---------------------------------------------------------------------------

/// Criteria for selecting which file to keep within a duplicate group.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeepCriterion {
    /// Keep the file with the most recent modification timestamp.
    Newest,
    /// Keep the file with the oldest modification timestamp.
    Oldest,
    /// Keep the file with the largest size (typically highest quality).
    LargestFile,
    /// Keep the file with the smallest size (most compressed).
    SmallestFile,
    /// Keep the file with the shortest path (likely the "original" location).
    ShortestPath,
    /// Keep the file with the longest path.
    LongestPath,
}

/// Per-group policy that determines both which file to keep and what
/// action to apply to the remaining duplicates.
#[derive(Debug, Clone)]
pub struct GroupPolicy {
    /// How to select the file to keep.
    pub keep: KeepCriterion,
    /// Action to apply to duplicates (non-kept files).
    pub action: DedupAction,
    /// Minimum similarity for this policy to apply.
    pub min_similarity: f64,
}

impl Default for GroupPolicy {
    fn default() -> Self {
        Self {
            keep: KeepCriterion::LargestFile,
            action: DedupAction::Review,
            min_similarity: 0.95,
        }
    }
}

/// Result of applying a `GroupPolicy` to a duplicate group.
#[derive(Debug, Clone)]
pub struct GroupDecision {
    /// Index of the file to keep (within the group's file list).
    pub keep_index: usize,
    /// Path of the file to keep.
    pub keep_path: String,
    /// Indices and paths of files to act upon.
    pub duplicates: Vec<(usize, String)>,
    /// The action to apply to duplicates.
    pub action: DedupAction,
    /// Optional reason.
    pub reason: String,
}

/// Score a file path according to a `KeepCriterion`.
///
/// Higher is better for all criteria (the file with the highest score is kept).
fn score_file(path: &str, criterion: KeepCriterion) -> f64 {
    match criterion {
        KeepCriterion::LargestFile => std::fs::metadata(path)
            .map(|m| m.len() as f64)
            .unwrap_or(0.0),
        KeepCriterion::SmallestFile => {
            let size = std::fs::metadata(path)
                .map(|m| m.len() as f64)
                .unwrap_or(f64::MAX);
            // Invert: smaller → higher score
            if size <= 0.0 {
                0.0
            } else {
                1.0 / size
            }
        }
        KeepCriterion::Newest => std::fs::metadata(path)
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|t| {
                t.duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs_f64())
                    .ok()
            })
            .unwrap_or(0.0),
        KeepCriterion::Oldest => {
            let ts = std::fs::metadata(path)
                .ok()
                .and_then(|m| m.modified().ok())
                .and_then(|t| {
                    t.duration_since(std::time::UNIX_EPOCH)
                        .map(|d| d.as_secs_f64())
                        .ok()
                })
                .unwrap_or(f64::MAX);
            if ts >= f64::MAX {
                0.0
            } else {
                1.0 / (ts + 1.0)
            }
        }
        KeepCriterion::ShortestPath => {
            if path.is_empty() {
                0.0
            } else {
                1.0 / path.len() as f64
            }
        }
        KeepCriterion::LongestPath => path.len() as f64,
    }
}

/// Apply a `GroupPolicy` to a list of file paths.
///
/// Returns `None` if fewer than 2 files are provided.
#[must_use]
pub fn apply_group_policy(files: &[String], policy: &GroupPolicy) -> Option<GroupDecision> {
    if files.len() < 2 {
        return None;
    }

    let mut best_idx = 0;
    let mut best_score = f64::NEG_INFINITY;

    for (i, path) in files.iter().enumerate() {
        let s = score_file(path, policy.keep);
        if s > best_score {
            best_score = s;
            best_idx = i;
        }
    }

    let duplicates: Vec<(usize, String)> = files
        .iter()
        .enumerate()
        .filter(|(i, _)| *i != best_idx)
        .map(|(i, p)| (i, p.clone()))
        .collect();

    Some(GroupDecision {
        keep_index: best_idx,
        keep_path: files[best_idx].clone(),
        duplicates,
        action: policy.action,
        reason: format!(
            "keep by {:?}, apply {:?} to {} duplicate(s)",
            policy.keep,
            policy.action,
            files.len() - 1
        ),
    })
}

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

    #[test]
    fn test_action_is_destructive_delete() {
        assert!(DedupAction::Delete.is_destructive());
    }

    #[test]
    fn test_action_is_destructive_quarantine() {
        assert!(DedupAction::Quarantine.is_destructive());
    }

    #[test]
    fn test_action_not_destructive_keep() {
        assert!(!DedupAction::Keep.is_destructive());
    }

    #[test]
    fn test_action_not_destructive_symlink() {
        assert!(!DedupAction::Symlink.is_destructive());
    }

    #[test]
    fn test_action_description_nonempty() {
        for action in [
            DedupAction::Delete,
            DedupAction::Quarantine,
            DedupAction::Symlink,
            DedupAction::Keep,
            DedupAction::Review,
            DedupAction::Skip,
        ] {
            assert!(!action.description().is_empty());
        }
    }

    #[test]
    fn test_policy_config_defaults() {
        let cfg = DedupPolicyConfig::default();
        assert!(!cfg.strict_mode());
        assert!((cfg.min_similarity() - 0.95).abs() < 1e-9);
        assert!(cfg.protect_originals);
    }

    #[test]
    fn test_policy_skip_below_threshold() {
        let policy = DedupPolicy::default();
        let decision = policy.should_dedup(0.50, false);
        assert_eq!(decision.action, DedupAction::Skip);
        assert!(!decision.requires_review());
    }

    #[test]
    fn test_policy_exact_duplicate() {
        let policy = DedupPolicy::default();
        let decision = policy.should_dedup(1.0, false);
        assert_eq!(decision.action, DedupAction::Quarantine);
    }

    #[test]
    fn test_policy_near_duplicate() {
        let policy = DedupPolicy::default();
        let decision = policy.should_dedup(0.97, false);
        assert_eq!(decision.action, DedupAction::Review);
    }

    #[test]
    fn test_policy_protect_original() {
        let policy = DedupPolicy::default();
        let decision = policy.should_dedup(1.0, true);
        assert_eq!(decision.action, DedupAction::Keep);
    }

    #[test]
    fn test_decision_requires_review_for_review_action() {
        let d = DedupDecision::new(0.97, DedupAction::Review, None);
        assert!(d.requires_review());
    }

    #[test]
    fn test_decision_requires_review_destructive_near_dup() {
        let d = DedupDecision::new(0.97, DedupAction::Delete, None);
        assert!(d.requires_review());
    }

    #[test]
    fn test_decision_no_review_for_exact_destructive() {
        // similarity == 1.0, destructive → NOT near-dup branch, no review flag
        let d = DedupDecision::new(1.0, DedupAction::Delete, None);
        assert!(!d.requires_review());
    }

    #[test]
    fn test_decision_skip_no_review() {
        let d = DedupDecision::new(0.5, DedupAction::Skip, None);
        assert!(!d.requires_review());
    }

    #[test]
    fn test_policy_config_strict_mode_toggle() {
        let mut cfg = DedupPolicyConfig::default();
        cfg.strict_mode = true;
        assert!(cfg.strict_mode());
    }

    // ---- GroupPolicy / KeepCriterion tests ----

    #[test]
    fn test_keep_criterion_shortest_path() {
        let files = vec![
            "/a/b/c/deep/path/file.mp4".to_string(),
            "/short.mp4".to_string(),
            "/medium/file.mp4".to_string(),
        ];
        let policy = GroupPolicy {
            keep: KeepCriterion::ShortestPath,
            action: DedupAction::Delete,
            min_similarity: 0.95,
        };
        let decision = apply_group_policy(&files, &policy).expect("should produce a decision");
        assert_eq!(decision.keep_path, "/short.mp4");
        assert_eq!(decision.duplicates.len(), 2);
        assert_eq!(decision.action, DedupAction::Delete);
    }

    #[test]
    fn test_keep_criterion_longest_path() {
        let files = vec![
            "/short.mp4".to_string(),
            "/a/b/c/deep/path/file.mp4".to_string(),
        ];
        let policy = GroupPolicy {
            keep: KeepCriterion::LongestPath,
            action: DedupAction::Quarantine,
            min_similarity: 0.95,
        };
        let decision = apply_group_policy(&files, &policy).expect("should produce a decision");
        assert_eq!(decision.keep_path, "/a/b/c/deep/path/file.mp4");
    }

    #[test]
    fn test_group_policy_default() {
        let policy = GroupPolicy::default();
        assert_eq!(policy.keep, KeepCriterion::LargestFile);
        assert_eq!(policy.action, DedupAction::Review);
        assert!((policy.min_similarity - 0.95).abs() < f64::EPSILON);
    }

    #[test]
    fn test_group_policy_too_few_files() {
        let files = vec!["only_one.mp4".to_string()];
        let policy = GroupPolicy::default();
        assert!(apply_group_policy(&files, &policy).is_none());
    }

    #[test]
    fn test_group_decision_reason_contains_criterion() {
        let files = vec!["a.mp4".to_string(), "b.mp4".to_string()];
        let policy = GroupPolicy {
            keep: KeepCriterion::Newest,
            action: DedupAction::Symlink,
            min_similarity: 0.9,
        };
        let decision = apply_group_policy(&files, &policy).expect("should produce a decision");
        assert!(decision.reason.contains("Newest"));
        assert!(decision.reason.contains("Symlink"));
    }

    #[test]
    fn test_keep_criterion_all_variants_non_destructive() {
        // Ensure all KeepCriterion variants can be used without panic
        let files = vec!["a.mp4".to_string(), "b.mp4".to_string()];
        for criterion in [
            KeepCriterion::Newest,
            KeepCriterion::Oldest,
            KeepCriterion::LargestFile,
            KeepCriterion::SmallestFile,
            KeepCriterion::ShortestPath,
            KeepCriterion::LongestPath,
        ] {
            let policy = GroupPolicy {
                keep: criterion,
                action: DedupAction::Skip,
                min_similarity: 0.5,
            };
            let decision = apply_group_policy(&files, &policy);
            assert!(decision.is_some());
        }
    }
}