M1 Dati e libreria: modello, archivi SQLite con scrittore unico, nomi dei file, scrittura sicura, miniature, impronte, _febe.jsonl, copie, eliminazione e ricostruzione

Modello del dominio e interfacce degli archivi in Febe.Core; implementazione SQLite in Febe.Data (WAL, chiavi esterne, migrazioni numerate in transazione, coda di scrittura su un solo thread); logica della libreria in Febe.Core/Library; 164 prove MSTest, compresa la ricostruzione del database da una libreria di prova e la scala a 200.000 elementi.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
This commit is contained in:
Claude committed 2026-10-13 16:06:15 +00:00
1 parent c803bd98b5
commit 3aeaa17da7
69 files changed
+12472

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
using System.Numerics;
using SkiaSharp;
namespace Febe.Core.Library;
/// <summary>
/// 64-bit perceptual hash of photos (spec §8.4, «impronta visiva»): the classic DCT pHash.
/// <list type="number">
/// <item>the image is decoded upright and reduced to 32×32 grey levels by area averaging (aspect ratio is not kept:
/// resizing does not change the hash);</item>
/// <item>a 2-D DCT-II is computed and the 8×8 lowest frequencies are kept;</item>
/// <item>each of the 64 coefficients gives a bit: 1 when above the median of the 64.</item>
/// </list>
/// Two photos are probable duplicates when the Hamming distance of their hashes is at most
/// <see cref="DuplicateThreshold"/>. Videos have no perceptual hash: for them only SHA-256 counts (spec §9.3).
/// </summary>
public static class PerceptualHash
{
/// <summary>
/// Maximum Hamming distance (out of 64 bits) for two photos to be probable duplicates.
/// <para>
/// Calibrated on 2026-10-13 by <c>Febe.Tests.Library.PerceptualHashTests</c> on 24 generated scenes (gradients,
/// shapes, lines and grain; 1200×900 and 900×1200), each compared with its variants:
/// <list type="bullet">
/// <item>resized to 50%, 25%, 8% (96 px) and 150%, recompressed as JPEG at quality 95, 70, 40 and 20, resized to a
/// third and recompressed twice, saved as PNG: largest distance <b>4</b> (only the 96-px reduction; all others ≤ 2);</item>
/// <item>cropped — central 80%, 75% and 60% of each side, one side cut by 10% or 25%, top third removed, square and
/// 4:5 crops, a corner quarter: smallest distance <b>8</b>;</item>
/// <item>different scenes: smallest distance <b>20</b> (average 31).</item>
/// </list>
/// Every hash has exactly 32 bits set (median split), so distances are always even: 6 sits in the middle of the
/// gap between 4 and 8. A very light crop (5% on every side) measured 6–18 and may be proposed as a duplicate:
/// the pair is only shown to Alberto, never resolved automatically (rule 12).
/// </para>
/// </summary>
public const int DuplicateThreshold = 6;
private const int Size = 32;
private const int Low = 8;
private static readonly double[,] Cosines = BuildCosines();
/// <summary>Hamming distance between two hashes (0–64).</summary>
public static int Distance(ulong a, ulong b) => BitOperations.PopCount(a ^ b);
/// <summary>True when two hashes are within <see cref="DuplicateThreshold"/>.</summary>
public static bool AreSimilar(ulong a, ulong b, int threshold = DuplicateThreshold) => Distance(a, b) <= threshold;
/// <summary>Hash of an encoded image; null when the content is not a decodable image.</summary>
public static ulong? Compute(Stream encodedImage)
{
ArgumentNullException.ThrowIfNull(encodedImage);
using var bitmap = ImageDecoding.DecodeUpright(encodedImage, minLongSide: 256);
return bitmap is null ? null : Compute(bitmap);
}
/// <summary>Hash of an image file; null when it is not a decodable image.</summary>
public static ulong? ComputeFromFile(string path)
{
using var stream = File.OpenRead(path);
return Compute(stream);
}
/// <summary>Hash of a decoded bitmap (any size, premultiplied RGBA 8888 or convertible).</summary>
internal static ulong Compute(SKBitmap bitmap)
{
ArgumentNullException.ThrowIfNull(bitmap);
using var rgba = bitmap.ColorType == SKColorType.Rgba8888 && bitmap.AlphaType == SKAlphaType.Premul
? null
: bitmap.Copy(SKColorType.Rgba8888);
var source = rgba ?? bitmap;
var grey = Luminance(source);
var small = AreaResample(grey, source.Width, source.Height, Size, Size);
return HashOf(small);
}
/// <summary>The hash of a 32×32 grey image (row-major).</summary>
internal static ulong HashOf(double[] pixels)
{
// Separable DCT-II, only the 8 lowest frequencies in each direction.
var rows = new double[Size * Low];
for (var y = 0; y < Size; y++)
{
for (var u = 0; u < Low; u++)
{
double sum = 0;
for (var x = 0; x < Size; x++)
{
sum += pixels[(y * Size) + x] * Cosines[u, x];
}
rows[(y * Low) + u] = sum;
}
}
var coefficients = new double[Low * Low];
for (var v = 0; v < Low; v++)
{
for (var u = 0; u < Low; u++)
{
double sum = 0;
for (var y = 0; y < Size; y++)
{
sum += rows[(y * Low) + u] * Cosines[v, y];
}
coefficients[(v * Low) + u] = sum;
}
}
var sorted = (double[])coefficients.Clone();
Array.Sort(sorted);
var median = (sorted[31] + sorted[32]) / 2;
ulong hash = 0;
for (var i = 0; i < coefficients.Length; i++)
{
if (coefficients[i] > median)
{
hash |= 1UL << i;
}
}
return hash;
}
/// <summary>Grey levels (0–255) of an RGBA premultiplied bitmap, composited over white.</summary>
private static double[] Luminance(SKBitmap bitmap)
{
var width = bitmap.Width;
var height = bitmap.Height;
var result = new double[width * height];
var pixels = bitmap.GetPixelSpan();
var rowBytes = bitmap.RowBytes;
for (var y = 0; y < height; y++)
{
var row = pixels.Slice(y * rowBytes, width * 4);
for (var x = 0; x < width; x++)
{
var r = row[x * 4];
var g = row[(x * 4) + 1];
var b = row[(x * 4) + 2];
var a = row[(x * 4) + 3];
var white = 255 - a; // premultiplied: over white, each channel gains (255 − alpha)
result[(y * width) + x] = (0.299 * (r + white)) + (0.587 * (g + white)) + (0.114 * (b + white));
}
}
return result;
}
/// <summary>Area-averaging resample with exact fractional coverage (no aliasing when reducing).</summary>
internal static double[] AreaResample(double[] source, int sw, int sh, int dw, int dh)
{
var horizontal = new double[dw * sh];
var xs = Weights(sw, dw);
for (var y = 0; y < sh; y++)
{
for (var dx = 0; dx < dw; dx++)
{
double sum = 0;
foreach (var (index, weight) in xs[dx])
{
sum += source[(y * sw) + index] * weight;
}
horizontal[(y * dw) + dx] = sum;
}
}
var result = new double[dw * dh];
var ys = Weights(sh, dh);
for (var dy = 0; dy < dh; dy++)
{
for (var dx = 0; dx < dw; dx++)
{
double sum = 0;
foreach (var (index, weight) in ys[dy])
{
sum += horizontal[(index * dw) + dx] * weight;
}
result[(dy * dw) + dx] = sum;
}
}
return result;
}
/// <summary>For each target cell, the source cells it covers and their normalized weights.</summary>
private static List<(int Index, double Weight)>[] Weights(int sourceLength, int targetLength)
{
var scale = (double)sourceLength / targetLength;
var weights = new List<(int, double)>[targetLength];
for (var t = 0; t < targetLength; t++)
{
var start = t * scale;
var end = start + scale;
var list = new List<(int, double)>();
if (scale <= 1)
{
// Enlarging: nearest source cell by centre.
list.Add((Math.Min(sourceLength - 1, (int)((t + 0.5) * scale)), 1.0));
}
else
{
for (var s = (int)Math.Floor(start); s < Math.Ceiling(end) && s < sourceLength; s++)
{
var overlap = Math.Min(end, s + 1) - Math.Max(start, s);
if (overlap > 0)
{
list.Add((s, overlap / scale));
}
}
}
weights[t] = list;
}
return weights;
}
private static double[,] BuildCosines()
{
var table = new double[Low, Size];
for (var u = 0; u < Low; u++)
{
for (var x = 0; x < Size; x++)
{
table[u, x] = Math.Cos(((2 * x) + 1) * u * Math.PI / (2 * Size));
}
}
return table;
}
}