| | | 1 | | using Anichron.Core; |
| | | 2 | | using Anichron.Core.Data; |
| | | 3 | | using Anichron.Core.Data.Repository; |
| | | 4 | | using Anichron.Core.Domain; |
| | | 5 | | using Anichron.Core.Work; |
| | | 6 | | using Anichron.Worker.Settings; |
| | | 7 | | using Anichron.Worker.Work; |
| | | 8 | | using Microsoft.Extensions.Options; |
| | | 9 | | using NodaTime; |
| | | 10 | | using System.IO.Abstractions; |
| | | 11 | | |
| | | 12 | | namespace Anichron.Worker.Bursts; |
| | | 13 | | |
| | | 14 | | public sealed record BurstDetectionResult |
| | | 15 | | { |
| | | 16 | | public int Checked { get; init; } |
| | | 17 | | public int Created { get; init; } |
| | | 18 | | public int Merged { get; init; } |
| | | 19 | | public int Dissolved { get; init; } |
| | | 20 | | public int Matched { get; init; } |
| | | 21 | | public int NotMatched { get; init; } |
| | | 22 | | } |
| | | 23 | | |
| | 63 | 24 | | internal sealed partial class BurstDetectionHandler( |
| | 63 | 25 | | ActiveStorageConfigs activeConfigs, |
| | 63 | 26 | | IBurstRepository bursts, |
| | 63 | 27 | | IUnitOfWork unitOfWork, |
| | 63 | 28 | | IOriginalPhotoReader reader, |
| | 63 | 29 | | IThumbnailMatcher matcher, |
| | 63 | 30 | | IFileSystem fileSystem, |
| | 63 | 31 | | IClock clock, |
| | 63 | 32 | | IGuidFactory guids, |
| | 63 | 33 | | IOptions<WorkerSettings> options, |
| | 63 | 34 | | ILogger<BurstDetectionHandler> logger) : IWorkHandler<BurstDetectionPayload> |
| | | 35 | | { |
| | | 36 | | internal const int BatchSize = 100; |
| | | 37 | | |
| | | 38 | | public async Task<object?> RunAsync(BurstDetectionPayload payload, WorkRun run, CancellationToken ct) |
| | 62 | 39 | | { |
| | 62 | 40 | | if (await activeConfigs.FindAsync(BurstDetectionPayload.Kind, payload.StorageConfigId, ct) is not { } config) |
| | 2 | 41 | | return StorageConfigSkipped.MissingOrInactive; |
| | | 42 | | |
| | 60 | 43 | | if (!fileSystem.Directory.Exists(config.RootPath)) |
| | 1 | 44 | | throw new DirectoryNotFoundException($"The storage config's root {config.RootPath} is missing."); |
| | | 45 | | |
| | 59 | 46 | | var tally = new Tally(); |
| | 59 | 47 | | await RepairAsync(config.Id, tally, ct); |
| | 59 | 48 | | await CheckAsync(config, tally, run.Progress, ct); |
| | | 49 | | |
| | 58 | 50 | | Log.Finished(logger, config.Id, tally.Checked, tally.Created, tally.Merged, tally.Dissolved, tally.Matched, tall |
| | 58 | 51 | | return tally.ToResult(); |
| | 60 | 52 | | } |
| | | 53 | | |
| | | 54 | | private async Task RepairAsync(Guid configId, Tally tally, CancellationToken ct) |
| | 59 | 55 | | { |
| | 215 | 56 | | foreach (var burst in await bursts.GetInConfigWithMembersAsync(configId, ct)) |
| | 19 | 57 | | { |
| | 19 | 58 | | if (burst.Assets.Count(a => !a.IsSoftDeleted) < 2) |
| | 3 | 59 | | { |
| | 3 | 60 | | bursts.Remove(burst); |
| | 3 | 61 | | tally.Dissolved++; |
| | 3 | 62 | | } |
| | | 63 | | else |
| | 16 | 64 | | { |
| | 16 | 65 | | burst.PrimaryAssetId = BurstGrouping.Cover(burst.Assets).Id; |
| | 16 | 66 | | } |
| | 19 | 67 | | } |
| | | 68 | | |
| | 59 | 69 | | await unitOfWork.SaveChangesAsync(ct); |
| | 59 | 70 | | tally.Dissolved += await bursts.DeleteMemberlessAsync(ct); |
| | 59 | 71 | | } |
| | | 72 | | |
| | | 73 | | private async Task CheckAsync(UserStorageConfig config, Tally tally, IWorkProgress progress, CancellationToken ct) |
| | 59 | 74 | | { |
| | 59 | 75 | | var total = await bursts.CountUncheckedPhotosAsync(config.Id, ct); |
| | 59 | 76 | | MediaAsset? last = null; |
| | 115 | 77 | | while (await bursts.GetUncheckedPhotosAsync(config.Id, last, BatchSize, ct) is { Count: > 0 } batch) |
| | 57 | 78 | | { |
| | 772 | 79 | | foreach (var photo in batch) |
| | 301 | 80 | | { |
| | 301 | 81 | | await CheckAsync(config, photo, tally, ct); |
| | 300 | 82 | | progress.Report(++tally.Checked, total, "Checking photos for bursts"); |
| | 300 | 83 | | } |
| | | 84 | | |
| | 56 | 85 | | last = batch[^1]; |
| | 56 | 86 | | bursts.ForgetLoaded(); |
| | 56 | 87 | | matcher.Forget(); |
| | 56 | 88 | | } |
| | 58 | 89 | | } |
| | | 90 | | |
| | | 91 | | private async Task CheckAsync(UserStorageConfig config, MediaAsset photo, Tally tally, CancellationToken ct) |
| | 301 | 92 | | { |
| | 301 | 93 | | var facts = reader.Read(fileSystem.Path.Combine(config.RootPath, photo.FilePath)); |
| | 301 | 94 | | var check = new BurstCheck |
| | 301 | 95 | | { |
| | 301 | 96 | | AssetId = photo.Id, |
| | 301 | 97 | | CheckedAt = clock.GetCurrentInstant(), |
| | 301 | 98 | | IsCandidate = photo.Metadata is { Description: { CameraMake: not null, CameraModel: not null } } |
| | 301 | 99 | | && photo.ProxyFiles.Any(p => p.ProxyType == ProxyType.Thumbnail), |
| | 301 | 100 | | CameraBurstId = facts.CameraBurstId, |
| | 301 | 101 | | }; |
| | 301 | 102 | | bursts.AddCheck(check); |
| | 301 | 103 | | if (check.IsCandidate) |
| | 298 | 104 | | await GroupAsync(config.Id, photo, check.CameraBurstId, tally, ct); |
| | | 105 | | |
| | 300 | 106 | | await unitOfWork.SaveChangesAsync(ct); |
| | 300 | 107 | | } |
| | | 108 | | |
| | | 109 | | private async Task GroupAsync(Guid configId, MediaAsset photo, string? label, Tally tally, CancellationToken ct) |
| | 298 | 110 | | { |
| | 298 | 111 | | var labelled = label is null ? [] : await bursts.GetCandidatesLabelledAsync(configId, label, ct); |
| | 298 | 112 | | var similar = await SimilarNeighboursAsync(configId, photo, labelled, tally, ct); |
| | 297 | 113 | | if (labelled.Count + similar.Count == 0) |
| | 255 | 114 | | return; |
| | | 115 | | |
| | 42 | 116 | | var joined = await bursts.GetWithMembersAsync( |
| | 42 | 117 | | [.. labelled.Concat(similar).Select(a => a.BurstId).OfType<Guid>().Distinct()], ct); |
| | 42 | 118 | | if (BurstGrouping.Join(photo, labelled, similar, joined, options.Value.BurstSpanSeconds) is not { } join) |
| | 2 | 119 | | return; |
| | | 120 | | |
| | 40 | 121 | | var target = join.Target; |
| | 40 | 122 | | if (target is null) |
| | 25 | 123 | | { |
| | 25 | 124 | | target = new Burst { Id = guids.NewGuid(), CreatedAt = clock.GetCurrentInstant() }; |
| | 25 | 125 | | bursts.Add(target); |
| | 25 | 126 | | tally.Created++; |
| | 25 | 127 | | } |
| | | 128 | | |
| | 126 | 129 | | foreach (var merged in join.Merged) |
| | 3 | 130 | | { |
| | 3 | 131 | | bursts.Remove(merged); |
| | 3 | 132 | | tally.Merged++; |
| | 3 | 133 | | } |
| | | 134 | | |
| | 328 | 135 | | foreach (var member in join.Members) |
| | 104 | 136 | | member.BurstId = target.Id; |
| | 40 | 137 | | target.PrimaryAssetId = join.Cover.Id; |
| | 297 | 138 | | } |
| | | 139 | | |
| | | 140 | | private async Task<IReadOnlyList<MediaAsset>> SimilarNeighboursAsync( |
| | | 141 | | Guid configId, MediaAsset photo, IReadOnlyCollection<MediaAsset> labelled, Tally tally, CancellationToken ct) |
| | 298 | 142 | | { |
| | 298 | 143 | | var labelledBursts = labelled.Select(a => a.BurstId).OfType<Guid>().ToHashSet(); |
| | 298 | 144 | | var gap = options.Value.BurstGapSeconds; |
| | 298 | 145 | | var neighbours = await bursts.GetCandidatesNearAsync( |
| | 298 | 146 | | configId, |
| | 298 | 147 | | photo.Metadata!.Description.CameraMake!, |
| | 298 | 148 | | photo.Metadata.Description.CameraModel!, |
| | 298 | 149 | | photo.DateCaptured!.Value.PlusSeconds(-gap), |
| | 298 | 150 | | photo.DateCaptured.Value.PlusSeconds(gap), |
| | 298 | 151 | | ct); |
| | | 152 | | |
| | 297 | 153 | | var similar = new List<MediaAsset>(); |
| | 1375 | 154 | | foreach (var neighbour in neighbours.Where(n => !labelled.Contains(n) && !(n.BurstId is { } id && labelledBursts |
| | 242 | 155 | | { |
| | 242 | 156 | | var score = await matcher.ScoreAsync(Thumbnail(photo), Thumbnail(neighbour), ct); |
| | 242 | 157 | | Log.Compared(logger, photo.Id, neighbour.Id, score); |
| | 242 | 158 | | if (score >= options.Value.BurstSimilarityThreshold) |
| | 25 | 159 | | { |
| | 25 | 160 | | similar.Add(neighbour); |
| | 25 | 161 | | tally.Matched++; |
| | 25 | 162 | | } |
| | | 163 | | else |
| | 217 | 164 | | { |
| | 217 | 165 | | tally.NotMatched++; |
| | 217 | 166 | | } |
| | 242 | 167 | | } |
| | | 168 | | |
| | 297 | 169 | | return similar; |
| | 297 | 170 | | } |
| | | 171 | | |
| | | 172 | | private static string Thumbnail(MediaAsset asset) |
| | | 173 | | // Stryker disable once Linq |
| | 484 | 174 | | => asset.ProxyFiles.First(p => p.ProxyType == ProxyType.Thumbnail).ProxyPath; |
| | | 175 | | |
| | | 176 | | private sealed class Tally |
| | | 177 | | { |
| | | 178 | | public int Checked { get; set; } |
| | | 179 | | public int Created { get; set; } |
| | | 180 | | public int Merged { get; set; } |
| | | 181 | | public int Dissolved { get; set; } |
| | | 182 | | public int Matched { get; set; } |
| | | 183 | | public int NotMatched { get; set; } |
| | | 184 | | |
| | 58 | 185 | | public BurstDetectionResult ToResult() => new() |
| | 58 | 186 | | { |
| | 58 | 187 | | Checked = Checked, |
| | 58 | 188 | | Created = Created, |
| | 58 | 189 | | Merged = Merged, |
| | 58 | 190 | | Dissolved = Dissolved, |
| | 58 | 191 | | Matched = Matched, |
| | 58 | 192 | | NotMatched = NotMatched, |
| | 58 | 193 | | }; |
| | | 194 | | } |
| | | 195 | | |
| | | 196 | | private static partial class Log |
| | | 197 | | { |
| | | 198 | | [LoggerMessage(Level = LogLevel.Information, Message = "Burst detection for storage config {Id} checked {Checked |
| | | 199 | | public static partial void Finished(ILogger logger, Guid id, int @checked, int created, int merged, int dissolve |
| | | 200 | | |
| | | 201 | | [LoggerMessage(Level = LogLevel.Debug, Message = "Burst detection compared photo {Photo} with {Neighbour}: score |
| | | 202 | | public static partial void Compared(ILogger logger, Guid photo, Guid neighbour, double score); |
| | | 203 | | } |
| | | 204 | | } |