videre-core 0.49.1

Shared SQLite, caching, and search helpers for the videre media library CLI
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
//! Aggregate library statistics for dashboard-style callers.
//! Plain queries over an open `rusqlite::Connection`, shared source of truth
//! for the gallery's stats tile, `videre stats`, and any other embedder.

use rusqlite::{Connection, Result};
use serde::Serialize;

#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct LibraryStats {
    pub total_files: i64,
    pub total_size_bytes: i64,
    pub total_photos: i64,
    pub total_videos: i64,
    pub duplicate_group_count: i64,
    pub duplicate_file_count: i64,
    pub wasted_bytes: i64,
    pub faces_detected: i64,
    pub people_named: i64,
    /// Counts of rated/picked/labelled/liked photos.
    #[serde(default)]
    pub marks: crate::marks::MarksSummary,
    /// One entry per model with an embedding database for this library.
    /// Empty when nothing has been embedded, which is a normal state.
    #[serde(default)]
    pub embeddings: Vec<crate::embeddings_db::ModelEmbeddingCount>,
}

use crate::db::table_exists;

const PHOTO_MIME_LIST: &str =
    "'image/jpeg','image/png','image/gif','image/webp','image/bmp','image/tiff','image/heic'";
const VIDEO_MIME_LIST: &str = "'video/quicktime','video/mp4'";

const PHOTO_EXTS: &str = "'jpg','jpeg','png','gif','webp','bmp','tiff','heic','dng'";
const VIDEO_EXTS: &str = "'mov','mp4'";

// `VIDEO_EXTS`'s values must stay in sync with
// `crate::embeddings::is_video_ext` (the shared "is this a video" check).
// The SQL below uses `lower(ext)` so this list stays case-insensitive,
// matching that helper.

pub fn compute(conn: &Connection) -> Result<LibraryStats> {
    let total_files: i64 = conn.query_row("SELECT COUNT(*) FROM file_hashes", [], |r| r.get(0))?;
    let total_size_bytes: i64 = conn.query_row(
        "SELECT COALESCE(SUM(size_bytes), 0) FROM file_hashes",
        [],
        |r| r.get(0),
    )?;
    let total_photos: i64 = conn.query_row(
        &format!(
            "SELECT COUNT(*) FROM file_hashes
             WHERE mime IN ({PHOTO_MIME_LIST})
                OR (mime IS NULL AND lower(ext) IN ({PHOTO_EXTS}))"
        ),
        [],
        |r| r.get(0),
    )?;
    let total_videos: i64 = conn.query_row(
        &format!(
            "SELECT COUNT(*) FROM file_hashes
             WHERE mime IN ({VIDEO_MIME_LIST})
                OR (mime IS NULL AND lower(ext) IN ({VIDEO_EXTS}))"
        ),
        [],
        |r| r.get(0),
    )?;

    let duplicate_group_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM \
         (SELECT hash FROM file_hashes GROUP BY hash HAVING COUNT(*) > 1)",
        [],
        |r| r.get(0),
    )?;
    let duplicate_file_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM file_hashes \
         WHERE hash IN (SELECT hash FROM file_hashes GROUP BY hash HAVING COUNT(*) > 1)",
        [],
        |r| r.get(0),
    )?;
    let wasted_bytes: i64 = conn.query_row(
        "SELECT COALESCE(SUM(size_bytes * (cnt - 1)), 0) FROM \
         (SELECT hash, size_bytes, COUNT(*) as cnt \
          FROM file_hashes GROUP BY hash HAVING cnt > 1)",
        [],
        |r| r.get(0),
    )?;

    let (faces_detected, people_named) = if table_exists(conn, "faces")? {
        let faces_detected: i64 = conn.query_row("SELECT COUNT(*) FROM faces", [], |r| r.get(0))?;
        let people_named: i64 = conn.query_row(
            "SELECT COUNT(DISTINCT person_label) FROM faces \
             WHERE confirmed = 1 AND person_label IS NOT NULL",
            [],
            |r| r.get(0),
        )?;
        (faces_detected, people_named)
    } else {
        (0, 0)
    };

    Ok(LibraryStats {
        total_files,
        total_size_bytes,
        total_photos,
        total_videos,
        duplicate_group_count,
        duplicate_file_count,
        wasted_bytes,
        faces_detected,
        people_named,
        marks: crate::marks::summary(conn)?,
        embeddings: Vec::new(),
    })
}

/// Compute database and model-store statistics for one selected library.
pub fn compute_full_in(
    conn: &Connection,
    ctx: &crate::library::LibraryContext,
) -> anyhow::Result<LibraryStats> {
    ctx.ensure_root_identity()?;
    let mut stats = compute(conn)?;
    stats.embeddings = crate::embeddings_db::counts_by_model_in(ctx)?;
    Ok(stats)
}

/// What the library is made of, by file type.
///
/// `stats` could say how many files there were and how big they were in total,
/// but not what they *are* - and "70,601 files, 480GB" answers a different
/// question from "12,000 of those are HEIC and they are 22GB of it".
///
/// Grouped by extension rather than mime, with the mime shown alongside,
/// because extension is what a user recognises and types into `--ext`.
#[derive(Debug, Clone, Serialize)]
pub struct TypeBreakdown {
    pub ext: String,
    pub mime: String,
    pub files: i64,
    pub bytes: i64,
}

pub fn by_type(conn: &rusqlite::Connection, limit: usize) -> rusqlite::Result<Vec<TypeBreakdown>> {
    let mut stmt = conn.prepare(
        "SELECT LOWER(COALESCE(NULLIF(ext,''),'(none)')),
                COALESCE(NULLIF(mime,''),'(unknown)'),
                COUNT(*), COALESCE(SUM(size_bytes),0)
           FROM file_hashes
          GROUP BY 1, 2
          ORDER BY 4 DESC",
    )?;
    let rows = stmt.query_map([], |r| {
        Ok(TypeBreakdown {
            ext: r.get(0)?,
            mime: r.get(1)?,
            files: r.get(2)?,
            bytes: r.get(3)?,
        })
    })?;
    let mut out: Vec<TypeBreakdown> = rows.collect::<rusqlite::Result<_>>()?;
    out.truncate(limit);
    Ok(out)
}

/// A scanned path whose filename extension conflicts with detected content.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MismatchFile {
    pub path: String,
    pub ext: String,
    pub mime: String,
}

/// Exact mismatch count with a bounded or complete path list.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct MismatchReport {
    pub count: usize,
    pub files: Vec<MismatchFile>,
    pub truncated: bool,
}

/// Report disagreements from the last scan without opening source files.
///
/// `Some(limit)` retains at most that many paths; `None` retains all paths.
/// Every row is still examined so `count` is exact even for a bounded report.
pub fn mismatched_files(conn: &Connection, limit: Option<usize>) -> Result<MismatchReport> {
    let mut stmt = conn.prepare("SELECT path, ext, mime FROM file_hashes ORDER BY path")?;
    let rows = stmt.query_map([], |r| {
        Ok((
            r.get::<_, String>(0)?,
            r.get::<_, Option<String>>(1)?,
            r.get::<_, Option<String>>(2)?,
        ))
    })?;
    let mut count = 0;
    let mut files = Vec::new();
    for row in rows {
        let (path, ext, mime) = row?;
        let (Some(ext), Some(mime)) = (ext, mime) else {
            continue;
        };
        if crate::mime_probe::is_content_mismatch(&ext, Some(&mime)) {
            count += 1;
            if limit.is_none_or(|bound| files.len() < bound) {
                files.push(MismatchFile { path, ext, mime });
            }
        }
    }
    Ok(MismatchReport {
        count,
        truncated: count > files.len(),
        files,
    })
}

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

    fn test_db() -> Connection {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch(
            "CREATE TABLE file_hashes (
                path        TEXT PRIMARY KEY,
                hash        TEXT NOT NULL,
                size_bytes  INTEGER,
                ext         TEXT
            );",
        )
        .unwrap();
        crate::library_db::ensure_scan_schema(&conn).unwrap();
        conn
    }

    fn insert_file(conn: &Connection, path: &str, hash: &str, size_bytes: i64, ext: &str) {
        conn.execute(
            "INSERT INTO file_hashes (path, hash, size_bytes, ext) VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![path, hash, size_bytes, ext],
        )
        .unwrap();
    }

    fn insert_scanned_file(conn: &Connection, path: &str, hash: &str, ext: &str, mime: &str) {
        conn.execute(
            "INSERT INTO file_hashes (path, hash, ext, mime) VALUES (?1, ?2, ?3, ?4)",
            rusqlite::params![path, hash, ext, mime],
        )
        .unwrap();
    }

    #[test]
    fn mismatched_files_counts_paths_not_hashes() {
        let conn = test_db();
        insert_scanned_file(&conn, "/a/1.png", "same", "png", "image/jpeg");
        insert_scanned_file(&conn, "/a/2.png", "same", "png", "image/jpeg");
        insert_scanned_file(&conn, "/a/3.jpg", "same", "jpg", "image/jpeg");

        let report = mismatched_files(&conn, Some(10)).unwrap();
        assert_eq!(report.count, 2);
        assert_eq!(report.files.len(), 2);
        assert_eq!(report.files[0].path, "/a/1.png");
        assert_eq!(report.files[0].ext, "png");
        assert_eq!(report.files[0].mime, "image/jpeg");
        assert_eq!(report.files[1].path, "/a/2.png");
        assert!(!report.truncated);
    }

    #[test]
    fn mismatched_files_samples_in_path_order() {
        let conn = test_db();
        for i in (0..12).rev() {
            insert_scanned_file(
                &conn,
                &format!("/a/{i:02}.png"),
                &format!("hash-{i}"),
                "png",
                "image/jpeg",
            );
        }
        insert_scanned_file(&conn, "/a/movie.mov", "movie", "mov", "video/mp4");
        insert_scanned_file(
            &conn,
            "/a/unknown.jpg",
            "unknown",
            "jpg",
            crate::mime_probe::UNKNOWN_MIME,
        );

        let bounded = mismatched_files(&conn, Some(10)).unwrap();
        assert_eq!(bounded.count, 12);
        assert_eq!(bounded.files.len(), 10);
        assert_eq!(bounded.files.first().unwrap().path, "/a/00.png");
        assert_eq!(bounded.files.last().unwrap().path, "/a/09.png");
        assert!(bounded.truncated);

        let full = mismatched_files(&conn, None).unwrap();
        assert_eq!(full.count, 12);
        assert_eq!(full.files.len(), 12);
        assert_eq!(full.files.first().unwrap().path, "/a/00.png");
        assert_eq!(full.files.last().unwrap().path, "/a/11.png");
        assert!(!full.truncated);
    }

    #[test]
    fn mismatched_files_propagates_sql_errors() {
        let conn = test_db();
        conn.execute_batch("DROP TABLE file_hashes").unwrap();
        assert!(mismatched_files(&conn, Some(10)).is_err());
    }

    #[test]
    fn compute_counts_total_files_and_size() {
        let conn = test_db();
        insert_file(&conn, "/a/1.jpg", "h1", 1000, "jpg");
        insert_file(&conn, "/a/2.png", "h2", 2500, "png");

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.total_files, 2);
        assert_eq!(stats.total_size_bytes, 3500);
    }

    #[test]
    fn compute_on_empty_db_returns_zeros() {
        let conn = test_db();
        let stats = compute(&conn).unwrap();
        assert_eq!(stats.total_files, 0);
        assert_eq!(stats.total_size_bytes, 0);
    }

    #[test]
    fn compute_splits_photos_and_videos_by_extension() {
        let conn = test_db();
        insert_file(&conn, "/a/1.jpg", "h1", 100, "jpg");
        insert_file(&conn, "/a/2.heic", "h2", 100, "heic");
        insert_file(&conn, "/a/3.mov", "h3", 100, "mov");
        insert_file(&conn, "/a/4.mp4", "h4", 100, "mp4");
        insert_file(&conn, "/a/5.unknown", "h5", 100, "xyz");

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.total_photos, 2);
        assert_eq!(stats.total_videos, 2);
        assert_eq!(stats.total_files, 5); // unrecognized ext still counts toward total_files
    }

    #[test]
    fn compute_counts_video_exts_case_insensitively() {
        let conn = test_db();
        insert_file(&conn, "/a/1.MOV", "h1", 100, "MOV");
        insert_file(&conn, "/a/2.Mp4", "h2", 100, "Mp4");
        insert_file(&conn, "/a/3.mov", "h3", 100, "mov");

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.total_videos, 3); // uppercase/mixed-case exts still count as video
    }

    #[test]
    fn compute_counts_duplicate_groups_and_wasted_bytes() {
        let conn = test_db();
        insert_file(&conn, "/a/1.jpg", "dup-hash", 1000, "jpg");
        insert_file(&conn, "/b/1-copy.jpg", "dup-hash", 1000, "jpg");
        insert_file(&conn, "/a/2.jpg", "dup-hash", 1000, "jpg");
        insert_file(&conn, "/a/3.jpg", "unique-hash", 500, "jpg");

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.duplicate_group_count, 1);
        assert_eq!(stats.duplicate_file_count, 3); // all 3 members of the dup group
        assert_eq!(stats.wasted_bytes, 2000); // (3 - 1) * 1000
    }

    #[test]
    fn compute_with_no_duplicates_reports_zero() {
        let conn = test_db();
        insert_file(&conn, "/a/1.jpg", "h1", 500, "jpg");
        insert_file(&conn, "/a/2.jpg", "h2", 500, "jpg");

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.duplicate_group_count, 0);
        assert_eq!(stats.duplicate_file_count, 0);
        assert_eq!(stats.wasted_bytes, 0);
    }

    #[test]
    fn compute_counts_faces_and_named_people() {
        let conn = test_db();
        conn.execute_batch(
            "CREATE TABLE faces (
                id            INTEGER PRIMARY KEY,
                hash          TEXT NOT NULL,
                bbox          TEXT NOT NULL,
                landmark      TEXT,
                embedding     BLOB NOT NULL,
                cluster_id    INTEGER,
                person_label  TEXT,
                confirmed     INTEGER DEFAULT 0,
                is_primary    INTEGER DEFAULT 0
            );",
        )
        .unwrap();
        conn.execute(
            "INSERT INTO faces (id, hash, bbox, embedding, person_label, confirmed) \
             VALUES (1, 'h1', '[]', X'00', 'Alice', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO faces (id, hash, bbox, embedding, person_label, confirmed) \
             VALUES (2, 'h1', '[]', X'00', 'Alice', 1)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO faces (id, hash, bbox, embedding, person_label, confirmed) \
             VALUES (3, 'h2', '[]', X'00', NULL, 0)",
            [],
        )
        .unwrap();

        let stats = compute(&conn).unwrap();
        assert_eq!(stats.faces_detected, 3);
        assert_eq!(stats.people_named, 1); // distinct confirmed person_label
    }

    #[test]
    fn compute_without_faces_table_returns_zero_not_error() {
        let conn = test_db(); // no faces table created
        let stats = compute(&conn).unwrap();
        assert_eq!(stats.faces_detected, 0);
        assert_eq!(stats.people_named, 0);
    }

    #[test]
    fn compute_full_in_reads_models_without_creating_missing_stores() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path().join("library");
        let cache = temp.path().join("cache");
        std::fs::create_dir(&root).unwrap();
        let ctx = crate::library::LibraryContext::new(&root, &cache).unwrap();
        let conn = crate::library_db::initialize(&ctx).unwrap();
        let stats = compute_full_in(&conn, &ctx).unwrap();
        assert!(stats.embeddings.is_empty());
        assert!(!ctx.paths.embeddings.exists());
    }
}