Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Better image selection

laurenspriem9fd2a2ac082f
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/aesthetics_candidate_builder.dart b/mobile/apps/photos/lib/services/wrapped/builders/aesthetics_candidate_builder.dart
index dfbff7b90a..e87af79d7d 100644
--- a/mobile/apps/photos/lib/services/wrapped/builders/aesthetics_candidate_builder.dart
+++ b/mobile/apps/photos/lib/services/wrapped/builders/aesthetics_candidate_builder.dart
@@ -15,8 +15,10 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
static const int _kMinBlurryFiles = 3;
static const int _kMinColorBuckets = 2;
static const int _kMinColorMatchesPerBucket = 10;
- static const int _kMinMonochromeMedia = 4;
- static const int _kTopWowTarget = 4;
+ static const int _kMinMonochromeMedia = 6;
+ static const int _kTopWowMediaCount = 6;
+ static const int _kTopWowCandidateMultiplier = 4;
+ static const int _kTopWowMinIntersection = 3;
static const List<_ColorSpec> _colorSpecs = <_ColorSpec>[
_ColorSpec(
@@ -91,22 +93,22 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
final List<WrappedCard> cards = <WrappedCard>[];
- final WrappedCard? blurryCard = _buildBlurryFacesCard(snapshot);
+ final WrappedCard? blurryCard = _buildBlurryFacesCard(context, snapshot);
if (blurryCard != null) {
cards.add(blurryCard);
}
- final WrappedCard? colorCard = _buildYearInColorCard(snapshot);
+ final WrappedCard? colorCard = _buildYearInColorCard(context, snapshot);
if (colorCard != null) {
cards.add(colorCard);
}
- final WrappedCard? monochromeCard = _buildMonochromeCard(snapshot);
+ final WrappedCard? monochromeCard = _buildMonochromeCard(context, snapshot);
if (monochromeCard != null) {
cards.add(monochromeCard);
}
- final WrappedCard? wowCard = _buildTopWowCard(snapshot);
+ final WrappedCard? wowCard = _buildTopWowCard(context, snapshot);
if (wowCard != null) {
cards.add(wowCard);
}
@@ -114,20 +116,49 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
return cards;
}
- WrappedCard? _buildBlurryFacesCard(_AestheticsSnapshot snapshot) {
+ WrappedCard? _buildBlurryFacesCard(
+ WrappedEngineContext context,
+ _AestheticsSnapshot snapshot,
+ ) {
final List<_BlurryCandidate> candidates = snapshot.blurryCandidates;
if (candidates.length < _kMinBlurryFiles) {
return null;
}
- final List<_BlurryCandidate> selected =
- candidates.take(_kMaxMediaPerCard).toList(growable: false);
- final List<MediaRef> mediaRefs = selected
- .map((candidate) => MediaRef(candidate.uploadedFileID))
+ final Map<int, double> scoreHints = <int, double>{
+ for (final _BlurryCandidate candidate in candidates)
+ candidate.uploadedFileID: candidate.faceScore,
+ };
+
+ final List<MediaRef> mediaRefs = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs:
+ candidates.map((c) => c.uploadedFileID).toList(growable: false),
+ maxCount: math.min(_kMaxMediaPerCard, candidates.length),
+ scoreHints: scoreHints,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 21),
+ );
+
+ if (mediaRefs.isEmpty) {
+ return null;
+ }
+
+ final Map<int, _BlurryCandidate> candidateById = <int, _BlurryCandidate>{
+ for (final _BlurryCandidate candidate in candidates)
+ candidate.uploadedFileID: candidate,
+ };
+ final List<_BlurryCandidate> selectedCandidates = mediaRefs
+ .map((MediaRef ref) => candidateById[ref.uploadedFileID])
+ .whereType<_BlurryCandidate>()
.toList(growable: false);
+ if (selectedCandidates.isEmpty) {
+ return null;
+ }
+
final Set<String> nameSet = <String>{
- for (final _BlurryCandidate candidate in selected)
+ for (final _BlurryCandidate candidate in selectedCandidates)
...candidate.personNames,
}..removeWhere((String name) => name.isEmpty);
@@ -138,17 +169,19 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
];
final double averageBlur = _average(
- selected.map((candidate) => candidate.blurScore).toList(growable: false),
+ selectedCandidates
+ .map((candidate) => candidate.blurScore)
+ .toList(growable: false),
);
final double averageScore = _average(
- selected.map((candidate) => candidate.faceScore).toList(growable: false),
+ selectedCandidates
+ .map((candidate) => candidate.faceScore)
+ .toList(growable: false),
);
final Map<String, Object?> meta = <String, Object?>{
"totalCandidates": candidates.length,
"detailChips": detailChips,
- "uploadedFileIDs":
- selected.map((candidate) => candidate.uploadedFileID).toList(),
if (nameSet.isNotEmpty) "personNames": nameSet.toList(growable: false),
"averageBlur": averageBlur,
"averageFaceScore": averageScore,
@@ -159,11 +192,21 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
title: "Perfectly imperfect moments",
subtitle: _buildBlurrySubtitle(nameSet),
media: mediaRefs,
- meta: meta,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ "uploadedFileIDs": mediaRefs
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildYearInColorCard(_AestheticsSnapshot snapshot) {
+ WrappedCard? _buildYearInColorCard(
+ WrappedEngineContext context,
+ _AestheticsSnapshot snapshot,
+ ) {
final List<_ColorBucket> eligibleBuckets =
snapshot.colorBuckets.where((bucket) {
return bucket.matches.length >= _kMinColorMatchesPerBucket;
@@ -190,19 +233,41 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
List<_ClipMatch> heroMatches = chosenBucket.matches
.where((match) => match.score >= _kDisplayThreshold)
.take(_kMaxMatchesPerQuery)
- .toList(growable: false);
+ .toList();
+ if (heroMatches.length < _kMaxMediaPerCard) {
+ final Set<int> seen =
+ heroMatches.map((match) => match.uploadedFileID).toSet();
+ for (final _ClipMatch match in chosenBucket.matches) {
+ if (seen.length >= _kMaxMediaPerCard) {
+ break;
+ }
+ if (seen.add(match.uploadedFileID)) {
+ heroMatches.add(match);
+ }
+ }
+ }
if (heroMatches.isEmpty) {
heroMatches = chosenBucket.matches
.take(_kMaxMatchesPerQuery)
.toList(growable: false);
}
- final List<MediaRef> media = heroMatches
- .take(_kMaxMediaPerCard)
- .map((match) => MediaRef(match.uploadedFileID))
- .toList(growable: false);
+ final Map<int, double> scoreHints = <int, double>{
+ for (final _ClipMatch match in heroMatches)
+ match.uploadedFileID: match.score,
+ };
- if (media.isEmpty) {
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs:
+ heroMatches.map((match) => match.uploadedFileID),
+ maxCount: math.min(_kMaxMediaPerCard, heroMatches.length),
+ scoreHints: scoreHints,
+ minimumSpacing: const Duration(days: 30),
+ enforceDistinctness: false,
+ );
+
+ if (media.length < _kMaxMediaPerCard) {
return null;
}
@@ -221,7 +286,7 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
"query": chosenBucket.spec.query,
"count": chosenBucket.matches.length,
"uploadedFileIDs":
- heroMatches.map((match) => match.uploadedFileID).toList(),
+ media.map((MediaRef ref) => ref.uploadedFileID).toList(),
},
],
"detailChips": detailChips,
@@ -239,7 +304,10 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
);
}
- WrappedCard? _buildMonochromeCard(_AestheticsSnapshot snapshot) {
+ WrappedCard? _buildMonochromeCard(
+ WrappedEngineContext context,
+ _AestheticsSnapshot snapshot,
+ ) {
final List<_ClipMatch> matches = snapshot.monochromeMatches;
if (matches.length < _kMinMonochromeMedia) {
return null;
@@ -247,23 +315,46 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
final List<_ClipMatch> heroes = matches
.where((match) => match.score >= _kMonochromeDisplayThreshold)
- .take(_kMaxMediaPerCard)
- .toList(growable: false);
+ .toList();
- if (heroes.length < _kMinMonochromeMedia) {
- return null;
+ if (heroes.length < _kMaxMediaPerCard) {
+ final Set<int> seen = heroes.map((match) => match.uploadedFileID).toSet();
+ for (final _ClipMatch match in matches) {
+ if (seen.length >= _kMaxMediaPerCard) {
+ break;
+ }
+ if (seen.add(match.uploadedFileID)) {
+ heroes.add(match);
+ }
+ }
}
- final List<MediaRef> media = heroes
- .map((match) => MediaRef(match.uploadedFileID))
- .toList(growable: false);
+ final Map<int, double> scoreHints = <int, double>{
+ for (final _ClipMatch match in heroes) match.uploadedFileID: match.score,
+ };
+
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs:
+ heroes.map((match) => match.uploadedFileID).toList(growable: false),
+ maxCount: math.min(_kMaxMediaPerCard, heroes.length),
+ scoreHints: scoreHints,
+ minimumSpacing: const Duration(days: 21),
+ enforceDistinctness: false,
+ );
+
+ if (media.length < _kMaxMediaPerCard) {
+ return null;
+ }
final Map<String, Object?> meta = <String, Object?>{
"matchCount": matches.length,
"detailChips": <String>[
"${matches.length} black-and-white frames",
],
- "uploadedFileIDs": heroes.map((match) => match.uploadedFileID).toList(),
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
};
return WrappedCard(
@@ -275,24 +366,78 @@ class AestheticsCandidateBuilder extends WrappedCandidateBuilder {
);
}
- WrappedCard? _buildTopWowCard(_AestheticsSnapshot snapshot) {
- final List<_ClipMatch> wowMatches = snapshot.topWowMatches;
- if (wowMatches.length < _kTopWowTarget) {
+ WrappedCard? _buildTopWowCard(
+ WrappedEngineContext context,
+ _AestheticsSnapshot snapshot,
+ ) {
+ final List<_ClipMatch> intersection = snapshot.topWowMatches;
+ if (intersection.length < _kTopWowMinIntersection) {
return null;
}
- final List<_ClipMatch> heroes =
- wowMatches.take(_kTopWowTarget).toList(growable: false);
- final List<MediaRef> media = heroes
- .map((match) => MediaRef(match.uploadedFileID))
- .toList(growable: false);
+ const int desiredCount = _kTopWowMediaCount;
+ final Map<int, _ClipMatch> candidateMap = <int, _ClipMatch>{
+ for (final _ClipMatch match in intersection) match.uploadedFileID: match,
+ };
+
+ if (candidateMap.length < desiredCount) {
+ for (final String query in AestheticsCandidateBuilder._kWowQueries) {
+ final List<_ClipMatch> queryMatches =
+ snapshot.matchesForQuery(query).toList(growable: false);
+ for (final _ClipMatch match in queryMatches) {
+ candidateMap.putIfAbsent(match.uploadedFileID, () => match);
+ if (candidateMap.length >=
+ desiredCount * _kTopWowCandidateMultiplier) {
+ break;
+ }
+ }
+ if (candidateMap.length >= desiredCount * _kTopWowCandidateMultiplier) {
+ break;
+ }
+ }
+ }
+
+ final List<_ClipMatch> candidates =
+ candidateMap.values.toList(growable: false)
+ ..sort(
+ (_ClipMatch a, _ClipMatch b) => b.score.compareTo(a.score),
+ );
+
+ if (candidates.length < desiredCount) {
+ return null;
+ }
+
+ final Set<int> intersectionIds =
+ intersection.map((match) => match.uploadedFileID).toSet();
+ final Map<int, double> scoreHints = <int, double>{
+ for (final _ClipMatch match in candidates)
+ match.uploadedFileID: match.score *
+ (intersectionIds.contains(match.uploadedFileID) ? 1.5 : 1.0),
+ };
+
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: candidates
+ .map((match) => match.uploadedFileID)
+ .toList(growable: false),
+ maxCount: desiredCount,
+ scoreHints: scoreHints,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 21),
+ );
+
+ if (media.length < desiredCount) {
+ return null;
+ }
final Map<String, Object?> meta = <String, Object?>{
"queries": AestheticsCandidateBuilder._kWowQueries,
"detailChips": <String>[
- "${wowMatches.length} CLIP-approved stunners",
+ "${media.length} CLIP-approved stunners",
],
- "uploadedFileIDs": heroes.map((match) => match.uploadedFileID).toList(),
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
};
return WrappedCard(
@@ -396,6 +541,11 @@ class _AestheticsSnapshot {
return _cachedTopWowMatches ??= _computeTopWow();
}
+ List<_ClipMatch> matchesForQuery(String query) {
+ final List<_ClipMatch> matches = _matchesForQuery(query);
+ return List<_ClipMatch>.from(matches, growable: false);
+ }
+
factory _AestheticsSnapshot.fromContext(
WrappedEngineContext context, {
required List<_ColorSpec> colorSpecs,
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/curation_candidate_builder.dart b/mobile/apps/photos/lib/services/wrapped/builders/curation_candidate_builder.dart
index c1c39ad7dc..9078e0e97f 100644
--- a/mobile/apps/photos/lib/services/wrapped/builders/curation_candidate_builder.dart
+++ b/mobile/apps/photos/lib/services/wrapped/builders/curation_candidate_builder.dart
@@ -38,8 +38,64 @@ class CurationCandidateBuilder extends WrappedCandidateBuilder {
return const <WrappedCard>[];
}
- final List<MediaRef> heroMedia =
- galleryGroups.first.map(MediaRef.new).toList(growable: false);
+ final List<int> uploadedIds = favoriteFiles
+ .map((EnteFile file) => file.uploadedFileID)
+ .whereType<int>()
+ .toList(growable: false);
+ if (uploadedIds.length < _kMinFavoritesForCard) {
+ return const <WrappedCard>[];
+ }
+
+ final Set<int> seenHeroIds = <int>{};
+ final List<int> heroCandidates = <int>[];
+ const int baseLimit = _kGalleryGroupSize * _kMaxGalleryGroups;
+ final int extendedLimit = math.min(
+ uploadedIds.length,
+ baseLimit * 4,
+ );
+
+ for (final List<int> group in galleryGroups) {
+ for (final int id in group) {
+ if (id <= 0 || !seenHeroIds.add(id)) {
+ continue;
+ }
+ heroCandidates.add(id);
+ if (heroCandidates.length >= extendedLimit) {
+ break;
+ }
+ }
+ if (heroCandidates.length >= extendedLimit) {
+ break;
+ }
+ }
+
+ if (heroCandidates.length < extendedLimit) {
+ for (final int id in uploadedIds) {
+ if (heroCandidates.length >= extendedLimit) {
+ break;
+ }
+ if (id <= 0 || !seenHeroIds.add(id)) {
+ continue;
+ }
+ heroCandidates.add(id);
+ }
+ }
+
+ if (heroCandidates.length < _kGalleryGroupSize) {
+ return const <WrappedCard>[];
+ }
+
+ final List<MediaRef> heroMedia = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: heroCandidates,
+ maxCount: math.min(_kGalleryGroupSize, heroCandidates.length),
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 30),
+ );
+
+ if (heroMedia.length < _kGalleryGroupSize) {
+ return const <WrappedCard>[];
+ }
final NumberFormat numberFormat = NumberFormat.decimalPattern();
final int favoritesCount = favoriteFiles.length;
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart b/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart
new file mode 100644
index 0000000000..ebf0c2547d
--- /dev/null
+++ b/mobile/apps/photos/lib/services/wrapped/builders/media_selector.dart
@@ -0,0 +1,483 @@
+part of "package:photos/services/wrapped/candidate_builders.dart";
+
+/// Shared helper that picks a diverse, people-forward set of media for
+/// Wrapped cards while filtering obvious screenshots/documents.
+class WrappedMediaSelector {
+ const WrappedMediaSelector._();
+
+ static const String _kScreenshotQuery =
+ "Screenshot of a phone or computer screen";
+ static const String _kDocumentQuery =
+ "Scanned document, receipt or whiteboard photo";
+ static const String _kPeopleDelightQuery =
+ "Candid photograph of friends laughing together";
+
+ static const double _kBaseScoreFloor = 1.0;
+ static const double _kFavoriteBoost = 0.25;
+ static const double _kNamedPersonBaseBoost = 0.22;
+ static const double _kNamedPersonExtraBoost = 0.06;
+ static const double _kFacePresenceBoost = 0.05;
+ static const double _kPeopleDelightWeight = 0.25;
+ static const double _kFaceCountWeight = 0.02;
+
+ static const double _kScreenshotPenaltyStart = 0.19;
+ static const double _kDocumentPenaltyStart = 0.18;
+ static const double _kScreenshotPenaltyWeight = 1.15;
+ static const double _kDocumentPenaltyWeight = 0.95;
+ static const double _kScreenshotHardPenalty = 0.75;
+ static const double _kScreenshotHardCutoff = 0.34;
+
+ static const double _kSimilarityPenaltyStart = 0.70;
+ static const double _kSimilarityPenaltyWeight = 3.0;
+ static const double _kSimilarityRejectThreshold = 0.92;
+
+ static const double _kTimePenaltyWeight = 0.8;
+
+ static final Expando<_MediaSelectorCache> _cache =
+ Expando<_MediaSelectorCache>("wrappedMediaSelectorCache");
+
+ static Set<String> get requiredTextQueries {
+ return <String>{
+ _kScreenshotQuery,
+ _kDocumentQuery,
+ _kPeopleDelightQuery,
+ };
+ }
+
+ static List<MediaRef> selectMediaRefs({
+ required WrappedEngineContext context,
+ required Iterable<int> candidateUploadedFileIDs,
+ int maxCount = 3,
+ Map<int, double>? scoreHints,
+ bool preferNamedPeople = false,
+ Duration? minimumSpacing,
+ bool enforceDistinctness = true,
+ }) {
+ final List<int> ids = select(
+ context: context,
+ candidateUploadedFileIDs: candidateUploadedFileIDs,
+ maxCount: maxCount,
+ scoreHints: scoreHints,
+ preferNamedPeople: preferNamedPeople,
+ minimumSpacing: minimumSpacing,
+ enforceDistinctness: enforceDistinctness,
+ );
+ return ids.map(MediaRef.new).toList(growable: false);
+ }
+
+ static List<int> select({
+ required WrappedEngineContext context,
+ required Iterable<int> candidateUploadedFileIDs,
+ int maxCount = 3,
+ Map<int, double>? scoreHints,
+ bool preferNamedPeople = false,
+ Duration? minimumSpacing,
+ bool enforceDistinctness = true,
+ }) {
+ if (maxCount <= 0) {
+ return const <int>[];
+ }
+
+ final _MediaSelectorCache cache =
+ _cache[context] ??= _MediaSelectorCache.fromEngineContext(context);
+
+ final Set<int> seen = <int>{};
+ final List<_ScoredCandidate> candidates = <_ScoredCandidate>[];
+ for (final int id in candidateUploadedFileIDs) {
+ if (id <= 0 || !seen.add(id)) {
+ continue;
+ }
+ final _MediaAsset? asset = cache.assetFor(id);
+ if (asset == null) {
+ continue;
+ }
+ final double hint = scoreHints?[id] ?? 0.0;
+ candidates.add(
+ _ScoredCandidate(
+ asset: asset,
+ initialScore: hint,
+ preferNamedPeople: preferNamedPeople,
+ ),
+ );
+ }
+
+ if (candidates.isEmpty) {
+ return const <int>[];
+ }
+
+ candidates.sort(
+ (_ScoredCandidate a, _ScoredCandidate b) =>
+ b.baseScore.compareTo(a.baseScore),
+ );
+
+ final List<_ScoredCandidate> selected = <_ScoredCandidate>[];
+ final int? spacingMicros = minimumSpacing?.inMicroseconds;
+ final int targetCount = math.min(maxCount, candidates.length);
+
+ while (selected.length < targetCount && candidates.isNotEmpty) {
+ _ScoredCandidate? bestCandidate;
+ double bestScore = -double.infinity;
+
+ for (final _ScoredCandidate candidate in candidates) {
+ final double score = candidate.adjustedScore(
+ selected,
+ spacingMicros: spacingMicros,
+ enforceDistinctness: enforceDistinctness,
+ );
+ if (score > bestScore + 1e-6) {
+ bestScore = score;
+ bestCandidate = candidate;
+ }
+ }
+
+ if (bestCandidate == null) {
+ break;
+ }
+
+ selected.add(bestCandidate);
+ candidates.remove(bestCandidate);
+ }
+
+ return selected
+ .map((_ScoredCandidate candidate) => candidate.asset.uploadedFileID)
+ .toList(growable: false);
+ }
+}
+
+class _ScoredCandidate {
+ _ScoredCandidate({
+ required this.asset,
+ required double initialScore,
+ required bool preferNamedPeople,
+ }) : baseScore = _computeBaseScore(
+ asset: asset,
+ initialScore: initialScore,
+ preferNamedPeople: preferNamedPeople,
+ );
+
+ final _MediaAsset asset;
+ final double baseScore;
+
+ double adjustedScore(
+ List<_ScoredCandidate> alreadySelected, {
+ int? spacingMicros,
+ required bool enforceDistinctness,
+ }) {
+ double score = baseScore;
+
+ for (final _ScoredCandidate other in alreadySelected) {
+ if (enforceDistinctness) {
+ final double? similarity = asset.embeddingSimilarity(other.asset);
+ if (similarity != null) {
+ if (similarity >= WrappedMediaSelector._kSimilarityRejectThreshold) {
+ return double.negativeInfinity;
+ }
+ if (similarity >= WrappedMediaSelector._kSimilarityPenaltyStart) {
+ final double proximity =
+ ((similarity - WrappedMediaSelector._kSimilarityPenaltyStart) /
+ (WrappedMediaSelector._kSimilarityRejectThreshold -
+ WrappedMediaSelector._kSimilarityPenaltyStart))
+ .clamp(0.0, 1.0);
+ final double multiplier =
+ 1 - proximity * WrappedMediaSelector._kSimilarityPenaltyWeight;
+ score *= math.max(multiplier, 0.05);
+ }
+ }
+ }
+
+ if (spacingMicros != null &&
+ spacingMicros > 0 &&
+ asset.captureMicros > 0 &&
+ other.asset.captureMicros > 0) {
+ final int delta =
+ (asset.captureMicros - other.asset.captureMicros).abs();
+ if (delta < spacingMicros) {
+ final double ratio =
+ 1 - (delta.toDouble() / math.max(spacingMicros.toDouble(), 1.0));
+ score -= ratio * WrappedMediaSelector._kTimePenaltyWeight;
+ }
+ }
+ }
+
+ return score;
+ }
+
+ static double _computeBaseScore({
+ required _MediaAsset asset,
+ required double initialScore,
+ required bool preferNamedPeople,
+ }) {
+ double score = WrappedMediaSelector._kBaseScoreFloor + initialScore;
+ if (!score.isFinite || score.isNaN) {
+ score = WrappedMediaSelector._kBaseScoreFloor;
+ }
+
+ if (asset.isFavorite) {
+ score += WrappedMediaSelector._kFavoriteBoost;
+ }
+
+ if (preferNamedPeople) {
+ if (asset.namedPersonCount > 0) {
+ score += WrappedMediaSelector._kNamedPersonBaseBoost;
+ final int extras = asset.namedPersonCount - 1;
+ if (extras > 0) {
+ score += math.min(extras, 4) *
+ WrappedMediaSelector._kNamedPersonExtraBoost;
+ }
+ if (asset.peopleDelightScore > 0) {
+ score += asset.peopleDelightScore *
+ WrappedMediaSelector._kPeopleDelightWeight;
+ }
+ } else if (asset.totalFaceCount > 0) {
+ score += WrappedMediaSelector._kFacePresenceBoost;
+ }
+ } else if (asset.totalFaceCount > 1) {
+ score += math.min(asset.totalFaceCount, 4) *
+ WrappedMediaSelector._kFaceCountWeight;
+ }
+
+ if (asset.documentSimilarity > 0) {
+ score -= _penalize(
+ asset.documentSimilarity,
+ WrappedMediaSelector._kDocumentPenaltyStart,
+ WrappedMediaSelector._kDocumentPenaltyWeight,
+ );
+ }
+
+ if (asset.screenshotSimilarity > 0) {
+ score -= _penalize(
+ asset.screenshotSimilarity,
+ WrappedMediaSelector._kScreenshotPenaltyStart,
+ WrappedMediaSelector._kScreenshotPenaltyWeight,
+ );
+ if (asset.screenshotSimilarity >=
+ WrappedMediaSelector._kScreenshotHardCutoff) {
+ score -= WrappedMediaSelector._kScreenshotHardPenalty;
+ }
+ }
+
+ return score;
+ }
+
+ static double _penalize(
+ double similarity,
+ double startThreshold,
+ double weight,
+ ) {
+ if (similarity <= startThreshold) {
+ return 0.0;
+ }
+ final double excess = similarity - startThreshold;
+ return excess * weight;
+ }
+}
+
+class _MediaSelectorCache {
+ _MediaSelectorCache._({
+ required Map<int, _MediaAsset> assets,
+ }) : _assets = assets;
+
+ final Map<int, _MediaAsset> _assets;
+
+ _MediaAsset? assetFor(int uploadedFileID) {
+ return _assets[uploadedFileID];
+ }
+
+ factory _MediaSelectorCache.fromEngineContext(
+ WrappedEngineContext context,
+ ) {
+ final Map<int, EnteFile> fileById = <int, EnteFile>{
+ for (final EnteFile file in context.files)
+ if (file.uploadedFileID != null) file.uploadedFileID!: file,
+ };
+
+ final Map<int, _EmbeddingVector> imageVectors = <int, _EmbeddingVector>{};
+ context.aesthetics.clipEmbeddings.forEach(
+ (int fileID, List<double> values) {
+ if (values.isEmpty) {
+ return;
+ }
+ final _EmbeddingVector? vector = _EmbeddingVector.tryFromList(values);
+ if (vector == null) {
+ return;
+ }
+ imageVectors[fileID] = vector;
+ },
+ );
+
+ final Set<int> favorites = Set<int>.from(context.favoriteUploadedFileIDs);
+
+ final Map<int, _PeopleCounts> peopleCounts =
+ _buildPeopleCounts(context.people);
+
+ final _EmbeddingVector? screenshotQuery = _vectorForTextQuery(
+ context,
+ WrappedMediaSelector._kScreenshotQuery,
+ );
+ final _EmbeddingVector? documentQuery = _vectorForTextQuery(
+ context,
+ WrappedMediaSelector._kDocumentQuery,
+ );
+ final _EmbeddingVector? peopleDelightQuery = _vectorForTextQuery(
+ context,
+ WrappedMediaSelector._kPeopleDelightQuery,
+ );
+
+ final Map<int, _MediaAsset> assets = <int, _MediaAsset>{};
+ fileById.forEach((int id, EnteFile file) {
+ final _EmbeddingVector? embedding = imageVectors[id];
+ final _PeopleCounts counts = peopleCounts[id] ?? const _PeopleCounts();
+ final double screenshotSim = embedding == null || screenshotQuery == null
+ ? 0.0
+ : _cosineSimilarity(embedding, screenshotQuery);
+ final double documentSim = embedding == null || documentQuery == null
+ ? 0.0
+ : _cosineSimilarity(embedding, documentQuery);
+ final double peopleDelight =
+ embedding == null || peopleDelightQuery == null
+ ? 0.0
+ : _cosineSimilarity(embedding, peopleDelightQuery);
+
+ assets[id] = _MediaAsset(
+ uploadedFileID: id,
+ captureMicros: file.creationTime ?? 0,
+ embedding: embedding,
+ isFavorite: favorites.contains(id),
+ namedPersonCount: counts.namedCount,
+ totalFaceCount: counts.totalFaces,
+ screenshotSimilarity: screenshotSim,
+ documentSimilarity: documentSim,
+ peopleDelightScore: peopleDelight,
+ );
+ });
+
+ return _MediaSelectorCache._(assets: assets);
+ }
+
+ static Map<int, _PeopleCounts> _buildPeopleCounts(
+ WrappedPeopleContext context,
+ ) {
+ if (!context.hasPeople) {
+ return const <int, _PeopleCounts>{};
+ }
+ final Map<int, _PeopleCounts> counts = <int, _PeopleCounts>{};
+
+ for (final WrappedPeopleFile file in context.files) {
+ if (file.faces.isEmpty) {
+ continue;
+ }
+
+ final Set<String> namedPersonIds = <String>{};
+ int totalFaces = 0;
+
+ for (final WrappedFaceRef face in file.faces) {
+ totalFaces += 1;
+ final String? personID = face.personID;
+ if (personID == null) {
+ continue;
+ }
+ final WrappedPersonEntry? entry = context.persons[personID];
+ if (entry == null || entry.isHidden) {
+ continue;
+ }
+ namedPersonIds.add(personID);
+ }
+
+ if (totalFaces == 0 && namedPersonIds.isEmpty) {
+ continue;
+ }
+
+ counts[file.uploadedFileID] = _PeopleCounts(
+ namedCount: namedPersonIds.length,
+ totalFaces: totalFaces,
+ );
+ }
+ return counts;
+ }
+
+ static _EmbeddingVector? _vectorForTextQuery(
+ WrappedEngineContext context,
+ String query,
+ ) {
+ final List<double>? values = context.aesthetics.textEmbeddings[query];
+ if (values == null || values.isEmpty) {
+ return null;
+ }
+ return _EmbeddingVector.tryFromList(values);
+ }
+}
+
+class _MediaAsset {
+ const _MediaAsset({
+ required this.uploadedFileID,
+ required this.captureMicros,
+ required this.embedding,
+ required this.isFavorite,
+ required this.namedPersonCount,
+ required this.totalFaceCount,
+ required this.screenshotSimilarity,
+ required this.documentSimilarity,
+ required this.peopleDelightScore,
+ });
+
+ final int uploadedFileID;
+ final int captureMicros;
+ final _EmbeddingVector? embedding;
+ final bool isFavorite;
+ final int namedPersonCount;
+ final int totalFaceCount;
+ final double screenshotSimilarity;
+ final double documentSimilarity;
+ final double peopleDelightScore;
+
+ double? embeddingSimilarity(_MediaAsset other) {
+ final _EmbeddingVector? a = embedding;
+ final _EmbeddingVector? b = other.embedding;
+ if (a == null || b == null) {
+ return null;
+ }
+ return _cosineSimilarity(a, b);
+ }
+}
+
+class _EmbeddingVector {
+ _EmbeddingVector._({
+ required this.vector,
+ required this.norm,
+ });
+
+ static _EmbeddingVector? tryFromList(List<double> values) {
+ final Vector vector = Vector.fromList(values, dtype: DType.float32);
+ final double norm = vector.norm();
+ if (!norm.isFinite || norm <= 0) {
+ return null;
+ }
+ return _EmbeddingVector._(vector: vector, norm: norm);
+ }
+
+ final Vector vector;
+ final double norm;
+
+ bool get hasMagnitude => norm > 0;
+}
+
+class _PeopleCounts {
+ const _PeopleCounts({
+ this.namedCount = 0,
+ this.totalFaces = 0,
+ });
+
+ final int namedCount;
+ final int totalFaces;
+}
+
+double _cosineSimilarity(_EmbeddingVector a, _EmbeddingVector b) {
+ if (!a.hasMagnitude || !b.hasMagnitude) {
+ return 0.0;
+ }
+ final double denom = a.norm * b.norm;
+ if (denom <= 0) {
+ return 0.0;
+ }
+ return a.vector.dot(b.vector) / denom;
+}
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/people_candidate_builder.dart b/mobile/apps/photos/lib/services/wrapped/builders/people_candidate_builder.dart
index 395cff305b..4bcd938791 100644
--- a/mobile/apps/photos/lib/services/wrapped/builders/people_candidate_builder.dart
+++ b/mobile/apps/photos/lib/services/wrapped/builders/people_candidate_builder.dart
@@ -21,22 +21,24 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
final List<WrappedCard> cards = <WrappedCard>[];
- final WrappedCard? topPersonCard = _buildTopPersonCard(dataset);
+ final WrappedCard? topPersonCard = _buildTopPersonCard(context, dataset);
if (topPersonCard != null) {
cards.add(topPersonCard);
}
- final WrappedCard? topThreeCard = _buildTopThreePeopleCard(dataset);
+ final WrappedCard? topThreeCard =
+ _buildTopThreePeopleCard(context, dataset);
if (topThreeCard != null) {
cards.add(topThreeCard);
}
- final WrappedCard? groupVsSoloCard = _buildGroupVsSoloCard(dataset);
+ final WrappedCard? groupVsSoloCard =
+ _buildGroupVsSoloCard(context, dataset);
if (groupVsSoloCard != null) {
cards.add(groupVsSoloCard);
}
- final WrappedCard? newFacesCard = _buildNewFacesCard(dataset);
+ final WrappedCard? newFacesCard = _buildNewFacesCard(context, dataset);
if (newFacesCard != null) {
cards.add(newFacesCard);
}
@@ -44,7 +46,10 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
return cards;
}
- WrappedCard? _buildTopPersonCard(_PeopleDataset dataset) {
+ WrappedCard? _buildTopPersonCard(
+ WrappedEngineContext context,
+ _PeopleDataset dataset,
+ ) {
final _PersonStats? topPerson = dataset.topNamedPerson;
if (topPerson == null || topPerson.faceCount < _kMinFacesForTopPerson) {
return null;
@@ -70,8 +75,13 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
? "${numberFormat.format(uniqueMoments)} moments with $mention."
: "One unforgettable moment with $mention.";
- final List<MediaRef> media =
- topPerson.topMediaFileIDs(3).map(MediaRef.new).toList(growable: false);
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: topPerson.topMediaFileIDs(6),
+ maxCount: 3,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 30),
+ );
final Map<String, Object?> meta = <String, Object?>{
"personId": topPerson.personEntry.personID,
@@ -88,11 +98,22 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
title: "${topPerson.displayNameForTitle} starred in your ${dataset.year}",
subtitle: subtitle,
media: media,
- meta: meta,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildTopThreePeopleCard(_PeopleDataset dataset) {
+ WrappedCard? _buildTopThreePeopleCard(
+ WrappedEngineContext context,
+ _PeopleDataset dataset,
+ ) {
if (dataset.topNamedPeople.length < 3) {
return null;
}
@@ -110,13 +131,19 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
],
);
- final List<MediaRef> media = topThree
- .map((_PersonStats stats) => stats.topMediaFileIDs(1))
+ final List<int> candidateIds = topThree
+ .map((_PersonStats stats) => stats.topMediaFileIDs(3))
.expand((List<int> ids) => ids)
- .where((int id) => id > 0)
- .map(MediaRef.new)
.toList(growable: false);
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: candidateIds,
+ maxCount: 3,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 21),
+ );
+
final Map<String, Object?> meta = <String, Object?>{
"personIds": topThree
.map((_PersonStats stats) => stats.personEntry.personID)
@@ -129,12 +156,23 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
type: WrappedCardType.topThreePeople,
title: "Your top crew",
subtitle: "${_formatNameList(names)} lit up your ${dataset.year}.",
- media: media.take(3).toList(growable: false),
- meta: meta,
+ media: media,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildGroupVsSoloCard(_PeopleDataset dataset) {
+ WrappedCard? _buildGroupVsSoloCard(
+ WrappedEngineContext context,
+ _PeopleDataset dataset,
+ ) {
if (!dataset.hasFaceMoments) {
return null;
}
@@ -170,10 +208,18 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
"${numberFormat.format(dataset.soloMoments)} solo portraits",
]);
- final List<MediaRef> media = <int>[
- ...dataset.groupSampleFileIDs(2),
- ...dataset.soloSampleFileIDs(1),
- ].where((int id) => id > 0).map(MediaRef.new).toList(growable: false);
+ final List<int> candidateIds = <int>[
+ ...dataset.groupSampleFileIDs(4),
+ ...dataset.soloSampleFileIDs(2),
+ ]..removeWhere((int id) => id <= 0);
+
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: candidateIds,
+ maxCount: 3,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 45),
+ );
final Map<String, Object?> meta = <String, Object?>{
"groupShots": dataset.groupMoments,
@@ -194,11 +240,22 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
? "You balanced time with friends and quiet moments."
: subtitleParts.join(" Β· "),
media: media,
- meta: meta,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildNewFacesCard(_PeopleDataset dataset) {
+ WrappedCard? _buildNewFacesCard(
+ WrappedEngineContext context,
+ _PeopleDataset dataset,
+ ) {
final List<_PersonStats> newPeople = dataset.topPeople.where(
(_PersonStats stats) {
final int? firstSeenYear = stats.firstSeenYear;
@@ -237,13 +294,19 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
"Spotlight: ${_formatNameList(highlightNames)}",
]);
- final List<MediaRef> media = highlights
- .map((_PersonStats stats) => stats.topMediaFileIDs(1))
+ final List<int> candidateIds = highlights
+ .map((_PersonStats stats) => stats.topMediaFileIDs(3))
.expand((List<int> ids) => ids)
- .where((int id) => id > 0)
- .map(MediaRef.new)
.toList(growable: false);
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: candidateIds,
+ maxCount: 3,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 30),
+ );
+
final Map<String, Object?> meta = <String, Object?>{
"newPersonCount": count,
"highlightNames": highlightNames,
@@ -258,7 +321,15 @@ class PeopleCandidateBuilder extends WrappedCandidateBuilder {
? "Fresh connections defined your ${dataset.year}."
: subtitleNames,
media: media,
- meta: meta,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
}
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/places_candidate_builder.dart b/mobile/apps/photos/lib/services/wrapped/builders/places_candidate_builder.dart
index 6fd14c2244..fde3ea0d68 100644
--- a/mobile/apps/photos/lib/services/wrapped/builders/places_candidate_builder.dart
+++ b/mobile/apps/photos/lib/services/wrapped/builders/places_candidate_builder.dart
@@ -11,6 +11,8 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
static const double _kMaxCityLabelDistanceKm = 120.0;
static const int _kTopCityMediaCount = 4;
static const int _kSpotMediaCount = 6;
+ static const int _kSelectionPoolMultiplier = 5;
+ static const int _kSelectionPoolMinimum = 18;
@override
String get debugLabel => "places";
@@ -83,6 +85,14 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
return null;
}
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: mediaIds,
+ maxCount: _kTopCityMediaCount,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 45),
+ );
+
final Map<String, Object?> meta = <String, Object?>{
"year": context.year,
"totalGeotaggedCount": dataset.totalCount,
@@ -111,8 +121,16 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
type: WrappedCardType.topCities,
title: title,
subtitle: subtitle,
- media: mediaIds.map(MediaRef.new).toList(growable: false),
- meta: meta,
+ media: media,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
@@ -146,8 +164,6 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
return null;
}
- const String title = "Your favorite spot";
-
final String subtitle;
if (cluster.distinctDays <= 0) {
subtitle =
@@ -160,6 +176,14 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
"You made ${numberFormat.format(cluster.totalCount)} memories here across ${numberFormat.format(cluster.distinctDays)} different days.";
}
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: mediaIds,
+ maxCount: _kSpotMediaCount,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 30),
+ );
+
final Map<String, Object?> meta = <String, Object?>{
"year": context.year,
"displayDurationMillis": 6500,
@@ -182,10 +206,18 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
return WrappedCard(
type: WrappedCardType.mostVisitedSpot,
- title: title,
+ title: "Your favorite spot",
subtitle: subtitle,
- media: mediaIds.map(MediaRef.new).toList(growable: false),
- meta: meta,
+ media: media,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
@@ -207,9 +239,24 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
}) {
final Set<int> seen = exclude != null ? Set<int>.from(exclude) : <int>{};
final List<int> collected = <int>[];
+ if (clusters.isEmpty || maxCount <= 0) {
+ return collected;
+ }
+
+ final int candidateLimit = math.max(
+ maxCount,
+ math.max(maxCount * _kSelectionPoolMultiplier, _kSelectionPoolMinimum),
+ );
for (final _PlaceClusterSummary cluster in clusters) {
+ final int perClusterLimit = math.min(
+ cluster.totalCount,
+ math.max(
+ maxCount,
+ (candidateLimit / clusters.length).ceil(),
+ ),
+ );
final List<int> clusterIds = cluster.sampleMediaIds(
- maxCount,
+ perClusterLimit,
preferDistinctDays: preferDistinctDays,
);
for (final int id in clusterIds) {
@@ -218,7 +265,7 @@ class PlacesCandidateBuilder extends WrappedCandidateBuilder {
}
collected.add(id);
seen.add(id);
- if (collected.length >= maxCount) {
+ if (collected.length >= candidateLimit) {
return collected;
}
}
diff --git a/mobile/apps/photos/lib/services/wrapped/builders/stats_candidate_builder.dart b/mobile/apps/photos/lib/services/wrapped/builders/stats_candidate_builder.dart
index c9b7a31534..fe665e658e 100644
--- a/mobile/apps/photos/lib/services/wrapped/builders/stats_candidate_builder.dart
+++ b/mobile/apps/photos/lib/services/wrapped/builders/stats_candidate_builder.dart
@@ -14,14 +14,14 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
}
final List<WrappedCard> cards = <WrappedCard>[];
- cards.add(_buildTotalsCard(snapshot));
+ cards.add(_buildTotalsCard(context, snapshot));
- final WrappedCard? rhythmCard = _buildRhythmCard(snapshot);
+ final WrappedCard? rhythmCard = _buildRhythmCard(context, snapshot);
if (rhythmCard != null) {
cards.add(rhythmCard);
}
- final WrappedCard? busiestDayCard = _buildBusiestDayCard(snapshot);
+ final WrappedCard? busiestDayCard = _buildBusiestDayCard(context, snapshot);
if (busiestDayCard != null) {
cards.add(busiestDayCard);
}
@@ -31,7 +31,10 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
return cards;
}
- WrappedCard _buildTotalsCard(_StatsSnapshot snapshot) {
+ WrappedCard _buildTotalsCard(
+ WrappedEngineContext context,
+ _StatsSnapshot snapshot,
+ ) {
final NumberFormat numberFormat = NumberFormat.decimalPattern();
final DateFormat fullDateFormat = DateFormat("MMMM d");
@@ -70,6 +73,15 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
snapshot.busiestDayMediaUploadedIDs,
snapshot.lastCaptureUploadedIDs,
],
+ selectionTarget: 6,
+ );
+
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: heroIds,
+ maxCount: 6,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 45),
);
final String? firstCaptureLine = snapshot.firstCaptureDay != null
@@ -98,12 +110,23 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
type: WrappedCardType.statsTotals,
title: title,
subtitle: subtitle,
- media: heroIds.map(MediaRef.new).toList(growable: false),
- meta: meta,
+ media: media,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildRhythmCard(_StatsSnapshot snapshot) {
+ WrappedCard? _buildRhythmCard(
+ WrappedEngineContext context,
+ _StatsSnapshot snapshot,
+ ) {
if (snapshot.elapsedDays <= 0) {
return null;
}
@@ -147,6 +170,15 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
snapshot.busiestMonthHighlightUploadedIDs,
snapshot.breakReturnUploadedIDs,
],
+ selectionTarget: 6,
+ );
+
+ final List<MediaRef> media = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: rhythmIds,
+ maxCount: 6,
+ preferNamedPeople: true,
+ minimumSpacing: const Duration(days: 21),
);
final Map<String, Object?> meta = <String, Object?>{
@@ -180,12 +212,23 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
type: WrappedCardType.statsVelocity,
title: title,
subtitle: subtitleParts.join(" Β· "),
- media: rhythmIds.map(MediaRef.new).toList(growable: false),
- meta: meta,
+ media: media,
+ meta: meta
+ ..addAll(
+ <String, Object?>{
+ if (media.isNotEmpty)
+ "uploadedFileIDs": media
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
+ },
+ ),
);
}
- WrappedCard? _buildBusiestDayCard(_StatsSnapshot snapshot) {
+ WrappedCard? _buildBusiestDayCard(
+ WrappedEngineContext context,
+ _StatsSnapshot snapshot,
+ ) {
if (snapshot.busiestDay == null || snapshot.busiestDayCount == 0) {
return null;
}
@@ -195,10 +238,12 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
final NumberFormat numberFormat = NumberFormat.decimalPattern();
final DateTime day = snapshot.busiestDay!;
- final List<MediaRef> mediaRefs = snapshot.busiestDayMediaUploadedIDs
- .take(6)
- .map(MediaRef.new)
- .toList(growable: false);
+ final List<MediaRef> mediaRefs = WrappedMediaSelector.selectMediaRefs(
+ context: context,
+ candidateUploadedFileIDs: snapshot.busiestDayMediaUploadedIDs,
+ maxCount: 6,
+ preferNamedPeople: true,
+ );
final Map<String, Object?> meta = <String, Object?>{
"date": day.toIso8601String(),
@@ -209,7 +254,9 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
weekdayFormat.format(day),
],
if (mediaRefs.isNotEmpty)
- "uploadedFileIDs": snapshot.busiestDayMediaUploadedIDs,
+ "uploadedFileIDs": mediaRefs
+ .map((MediaRef ref) => ref.uploadedFileID)
+ .toList(growable: false),
};
return WrappedCard(
@@ -255,16 +302,20 @@ class StatsCandidateBuilder extends WrappedCandidateBuilder {
];
}
- List<int> _collectUniqueIds(List<List<int>> sources) {
+ List<int> _collectUniqueIds(
+ List<List<int>> sources, {
+ required int selectionTarget,
+ }) {
final Set<int> seen = <int>{};
final List<int> result = <int>[];
+ final int poolTarget = math.max(selectionTarget * 4, selectionTarget + 6);
for (final List<int> source in sources) {
for (final int id in source) {
if (id <= 0) continue;
if (seen.add(id)) {
result.add(id);
}
- if (result.length >= 6) {
+ if (result.length >= poolTarget) {
return result;
}
}
diff --git a/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart b/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart
index 7772277773..a81ff8f469 100644
--- a/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart
+++ b/mobile/apps/photos/lib/services/wrapped/candidate_builders.dart
@@ -3,6 +3,8 @@ import "dart:typed_data";
import "package:flutter/foundation.dart" show immutable;
import "package:intl/intl.dart";
+import "package:ml_linalg/dtype.dart";
+import "package:ml_linalg/vector.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/models/location/location.dart";
@@ -17,6 +19,7 @@ part "builders/aesthetics_candidate_builder.dart";
part "builders/curation_candidate_builder.dart";
part "builders/narrative_candidate_builder.dart";
part "builders/badge_selector.dart";
+part "builders/media_selector.dart";
/// Provides basic context details for candidate builders.
@immutable
diff --git a/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart b/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart
index e7790e930f..24b6e36918 100644
--- a/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart
+++ b/mobile/apps/photos/lib/services/wrapped/wrapped_engine.dart
@@ -333,6 +333,7 @@ class WrappedEngine {
final Set<String> queries = <String>{
...AestheticsCandidateBuilder.requiredTextQueries,
...WrappedBadgeSelector.requiredTextQueries,
+ ...WrappedMediaSelector.requiredTextQueries,
};
final Map<String, List<double>> textEmbeddings = <String, List<double>>{};
for (final String query in queries) {