E4: filtro «Video fermi» della libreria (kind=stillvideos)

Risposta 40 di Alberto: fra i filtri «Tipo», dopo «Video», solo nella
Libreria. Mostra gli elementi di ogni tipo con un video in libreria la
cui ultima analisi (l'algoritmo più alto) dice «Fermo»; in «Tutte le
foto» solo quei video. Un video mai analizzato non c'è: l'analisi è
solo a richiesta.

L'elenco degli elementi si legge una volta per istruzione dagli esiti
fermi (ix_video_analysis_still) ai file (ix_media_sha256_entry), su
indici coprenti; CROSS JOIN e il + unario tengono SQLite su quei piani:
senza, i conteggi per elemento giravano tutti gli SHA-256 fermi a ogni
elemento (107 s per un account con 10.000 video fermi).

LibraryScaleTests riempie 21.000 analisi (11.000 «Fermo») e misura
finestre (55-105 ms, limite 250), totali e giorni. Prove del filtro sul
database e via API. L'interfaccia (la voce in library.js) è di WP6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-29 16:00:10 +01:00
1 parent 51150fb611
commit 78502e9c14
7 files changed
+361 -9

No files matched your search

+80 -5
View File
@@ -81,17 +81,20 @@ public sealed class LibraryScaleTests
}
var copies = await FillCopiesAsync(db, temp, accountIds, ct);
var still = await FillStillVideosAsync(db, accountIds, ct);
fill.Stop();
TestContext.WriteLine($"Riempimento: {Entries:N0} elementi in {fill.Elapsed.TotalSeconds:F1} s");
TestContext.WriteLine($"Copie: {copies.Copied:N0} copiate (di cui {copies.Converted:N0} convertite), {copies.Removed:N0} tolte, {copies.Superseded:N0} superate, {copies.Frames:N0} fotogrammi, su {copies.Due:N0} file da copiare");
TestContext.WriteLine($"Video fermi: {still.Analyses:N0} analisi, {still.Still:N0} «Fermo» (di cui {still.Overruled:N0} superati da un algoritmo più nuovo), {still.Entries:N0} elementi e {still.Files:N0} file nel filtro");
Assert.IsGreaterThan(0, copies.Converted, "converted copies in the fill");
Assert.IsGreaterThan(0, copies.Frames, "frames in the fill");
Assert.IsGreaterThan(0, still.Overruled, "still videos overruled by a newer algorithm in the fill");
// Plans differ with and without ANALYZE statistics: both must be fast.
// The fill stays outside the timings.
await MeasureAll(db, accountIds, copies, "senza statistiche", ct);
await MeasureAll(db, accountIds, copies, still, "senza statistiche", ct);
await db.WriteAsync(w => w.Command("ANALYZE").ExecuteNonQuery(), ct);
await MeasureAll(db, accountIds, copies, "con ANALYZE", ct);
await MeasureAll(db, accountIds, copies, still, "con ANALYZE", ct);
}
/// <summary>
@@ -103,8 +106,6 @@ public sealed class LibraryScaleTests
/// </summary>
private static async Task<CopiesWorld> FillCopiesAsync(FebeDatabase db, TempFolder temp, List<long> accountIds, CancellationToken ct)
{
const string Hash = "((m.id * 2654435761) % 1000003)";
const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
var general = await db.Exports.AddDestinationAsync(
new ExportDestination { Scope = ExportScope.General, RootPath = temp.Combine("usb"), ContentTypes = ContentTypes.All, CreatedAt = Make.T0 }, ct);
var own = await db.Exports.AddDestinationAsync(
@@ -148,6 +149,55 @@ public sealed class LibraryScaleTests
ct);
}
// A hash of the media id that mixes the ids (see FillCopiesAsync).
private const string Hash = "((m.id * 2654435761) % 1000003)";
private const string Spread = "((" + Hash + " * " + Hash + " + m.id) % 999983)";
/// <summary>
/// Tappa E4, the filter «Video fermi»: seven videos in ten analysed (about 20,000 of the 28,600 videos), half of them
/// «Fermo» (about 10,000, frame at 1 s) and half «In movimento»; one «Fermo» in ten has a newer algorithm that says
/// «In movimento», so it is out of the filter. The expected entries and files are counted here with a join on the
/// highest algorithm, another form than the filter's own.
/// </summary>
private static Task<StillWorld> FillStillVideosAsync(FebeDatabase db, List<long> accountIds, CancellationToken ct) =>
db.WriteAsync(
w =>
{
var videos = $"FROM media m WHERE m.kind = 'Video' AND m.sha256 IS NOT NULL AND {Spread} % 10 < 7";
var analyses = w.Command($"""
INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note)
SELECT m.sha256, 1, CASE WHEN {Spread} % 2 = 0 THEN 'Still' ELSE 'Moving' END, 1767225600000,
CASE WHEN {Spread} % 2 = 0 THEN 1000 END, NULL
{videos}
""").ExecuteNonQuery();
var overruled = w.Command($"""
INSERT INTO video_analysis (sha256, algorithm, outcome, analyzed_at, frame_at_ms, note)
SELECT m.sha256, 2, 'Moving', 1767225600000, NULL, NULL
{videos} AND {Spread} % 2 = 0 AND {Spread} % 20 < 2
""").ExecuteNonQuery();
var still = (int)w.Command("SELECT COUNT(*) FROM video_analysis WHERE outcome = 'Still'").ScalarInt64();
const string Latest = """
FROM media m JOIN video_analysis va ON va.sha256 = m.sha256
WHERE m.kind = 'Video' AND m.state IN ('Downloaded', 'Imported') AND va.outcome = 'Still'
AND va.algorithm = (SELECT MAX(x.algorithm) FROM video_analysis x WHERE x.sha256 = va.sha256)
""";
var entries = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest}").ScalarInt64();
var files = (int)w.Command($"SELECT COUNT(*) {Latest}").ScalarInt64();
var account = (int)w.Command($"SELECT COUNT(DISTINCT m.entry_id) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)")
.With("@a", accountIds[3]).ScalarInt64();
var accountFiles = (int)w.Command($"SELECT COUNT(*) {Latest} AND m.entry_id IN (SELECT id FROM entry WHERE account_id = @a)")
.With("@a", accountIds[3]).ScalarInt64();
return new StillWorld(analyses + overruled, still, overruled, entries, files, account, accountFiles);
},
ct);
/// <summary>
/// What the fill of the analyses wrote: rows, «Fermo» rows, those overruled by a newer algorithm, and the entries
/// and files the filter must find (<paramref name="AccountEntries"/> and <paramref name="AccountFiles"/>: those of
/// account 3).
/// </summary>
private sealed record StillWorld(int Analyses, int Still, int Overruled, int Entries, int Files, int AccountEntries, int AccountFiles);
/// <summary>The form of the copies an insert writes: variant, format and instant (SQL), name suffix, copy SHA (SQL).</summary>
private sealed record Form(string Variant, string Format, string FrameAt, string Suffix, string? CopySha)
{
@@ -162,7 +212,7 @@ public sealed class LibraryScaleTests
_ => 1 + (n % 5 == 0 ? 1 : 0),
});
private async Task MeasureAll(FebeDatabase db, List<long> accountIds, CopiesWorld copies, string label, CancellationToken ct)
private async Task MeasureAll(FebeDatabase db, List<long> accountIds, CopiesWorld copies, StillWorld still, string label, CancellationToken ct)
{
var times = new List<(string Name, double Bound, Timing<object?> Timing)>();
async Task<T> Measure<T>(string name, double bound, Func<Task<T>> query)
@@ -232,6 +282,31 @@ public sealed class LibraryScaleTests
await Measure("scheda account: Post, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts } }));
await Measure("scheda account: conteggi dei Post", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { AccountIds = [accountIds[3]], Kind = LibraryKindFilter.Posts }, TestZones.Rome));
await Measure("tutte le foto: conteggi del filtro Video", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(new LibraryFilter { Kind = LibraryKindFilter.Videos }, TestZones.Rome, MosaicMode.Files));
// «Video fermi» (tappa E4): the windows at the bound of the windows, totals and days at those of «Foto» and «Video».
var stillFilter = new LibraryFilter { Kind = LibraryKindFilter.StillVideos };
var stillWindow = await Measure("filtro Video fermi", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter }));
Assert.HasCount(200, stillWindow.Tiles);
var stillMiddle = await Measure("Video fermi: finestra a metà", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillFilter, Cursor = middleCursor }));
Assert.HasCount(200, stillMiddle.Tiles);
var stillFiles = await Measure("Video fermi: tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillFilter }));
Assert.HasCount(200, stillFiles.Tiles);
Assert.IsTrue(stillFiles.Tiles.All(t => t.CoverKind == MediaKind.Video));
var stillAccount = stillFilter with { AccountIds = [accountIds[3]] };
var stillOwn = await Measure("Video fermi: un account", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Filter = stillAccount }));
Assert.HasCount(Math.Min(200, still.AccountEntries), stillOwn.Tiles);
await Measure("Video fermi: un account, tutte le foto", IndexBoundMs, () => db.Entries.QueryLibraryAsync(new LibraryQuery { Limit = 200, Mode = MosaicMode.Files, Filter = stillAccount }));
var stillTotals = await Measure("totali del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.GetLibraryTotalsAsync(stillFilter));
Assert.AreEqual(still.Entries, stillTotals.Entries);
var stillDays = await Measure("conteggi per giorno del filtro Video fermi", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome));
Assert.AreEqual(still.Entries, stillDays.Sum(d => d.Count));
var stillFileDays = await Measure("Video fermi: conteggi, tutte le foto", FilteredAggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillFilter, TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(still.Files, stillFileDays.Sum(d => d.Count));
var stillAccountDays = await Measure("Video fermi: conteggi di un account", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome));
Assert.AreEqual(still.AccountEntries, stillAccountDays.Sum(d => d.Count));
// With accounts «Tutte le foto» counts each entry apart: a count that went from the SHA-256 index would walk
// every still video for each entry (107 s for one account in the first version).
var stillAccountFiles = await Measure("Video fermi: conteggi di un account, tutte le foto", AggregateBoundMs, () => db.Entries.CountLibraryByDayAsync(stillAccount, TestZones.Rome, MosaicMode.Files));
Assert.AreEqual(still.AccountFiles, stillAccountFiles.Sum(d => d.Count));
await Measure("è già noto? (pagina di 12)", IndexBoundMs, async () => await db.Entries.GetKnownInstagramIdsAsync(accountIds[5], EntryKind.Post, Enumerable.Range(0, 12).Select(i => $"id{5 + (i * 40)}").ToList()));
await Measure("SHA-256 in tutta la libreria", IndexBoundMs, () => db.Media.FindBySha256Async(Make.Sha(150_001)));
var summaries = await Measure("elenco account con conteggi", AggregateBoundMs, () => db.Accounts.ListSummariesAsync(new DateTimeOffset(2026, 10, 1, 0, 0, 0, TimeSpan.Zero)));