Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat: Implement pet detection and display pet faces in file details.

Amrithesh Kakkoth Ente725ac5ba9e89
diff --git a/mobile/apps/photos/lib/db/ml/db.dart b/mobile/apps/photos/lib/db/ml/db.dart
index e2f067c077..34282580e3 100644
--- a/mobile/apps/photos/lib/db/ml/db.dart
+++ b/mobile/apps/photos/lib/db/ml/db.dart
@@ -621,7 +621,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<DBPetFace>?> getPetFacesForFileID(int fileUploadID) async {
final db = await asyncDB;
- final String query = '''
+ const String query = '''
SELECT * FROM $petFacesTable
WHERE $fileIDColumn = ?
''';
@@ -638,7 +638,7 @@ class MLDataDB with SqlDbBase implements IMLDataDB<int> {
@override
Future<List<DBPetBody>?> getPetBodiesForFileID(int fileUploadID) async {
final db = await asyncDB;
- final String query = '''
+ const String query = '''
SELECT * FROM $petBodiesTable
WHERE $fileIDColumn = ?
''';
diff --git a/mobile/apps/photos/lib/l10n/intl_en.arb b/mobile/apps/photos/lib/l10n/intl_en.arb
index 020361e036..5e9aa000c1 100644
--- a/mobile/apps/photos/lib/l10n/intl_en.arb
+++ b/mobile/apps/photos/lib/l10n/intl_en.arb
@@ -2830,5 +2830,7 @@
"offlineFacesBannerSubtitle": "Sign up to tag people and easily find them later.",
"offlineNameFaceBannerTitle": "Give this face a name",
"offlineNameFaceBannerSubtitle": "Sign up to tag them and easily find their photos later.",
- "signUp": "Sign up"
+ "signUp": "Sign up",
+ "dog": "Dog",
+ "cat": "Cat"
}
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
index 7bab2d7d7b..c678348b8b 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_service.dart
@@ -276,7 +276,7 @@ class MLService {
fetchEmbeddingsAndInstructions(
fileDownloadMlLimit,
mode: mode,
- forceAll: debugPetOnlyMode || flagService.petEnabled,
+ forceAll: debugPetOnlyMode,
);
int fileAnalyzedCount = 0;
diff --git a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
index 274b6bc805..49f3f35c8b 100644
--- a/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/semantic_search/semantic_search_service.dart
@@ -16,8 +16,8 @@ import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/collections_service.dart";
import "package:photos/services/machine_learning/ml_computer.dart";
-import "package:photos/services/machine_learning/ml_service.dart";
import "package:photos/services/machine_learning/ml_result.dart";
+import "package:photos/services/machine_learning/ml_service.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_image_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
import "package:photos/services/search_service.dart";
diff --git a/mobile/apps/photos/lib/ui/social/widgets/comment_input_widget.dart b/mobile/apps/photos/lib/ui/social/widgets/comment_input_widget.dart
index d1e40d8963..84d9abb5d6 100644
--- a/mobile/apps/photos/lib/ui/social/widgets/comment_input_widget.dart
+++ b/mobile/apps/photos/lib/ui/social/widgets/comment_input_widget.dart
@@ -83,7 +83,6 @@ class _CommentInputWidgetState extends State<CommentInputWidget>
});
}
-
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
diff --git a/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart b/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart
index 23acd876b3..1898e96b48 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/file_details_widget.dart
@@ -30,6 +30,7 @@ import 'package:photos/ui/viewer/file_details/backed_up_time_item_widget.dart';
import "package:photos/ui/viewer/file_details/creation_time_item_widget.dart";
import 'package:photos/ui/viewer/file_details/exif_item_widgets.dart';
import "package:photos/ui/viewer/file_details/file_info_faces_item_widget.dart";
+import "package:photos/ui/viewer/file_details/file_info_pets_item_widget.dart";
import "package:photos/ui/viewer/file_details/file_properties_item_widget.dart";
import "package:photos/ui/viewer/file_details/location_tags_widget.dart";
import "package:photos/ui/viewer/file_details/preview_properties_item_widget.dart";
@@ -305,6 +306,12 @@ class _FileDetailsWidgetState extends State<FileDetailsWidget> {
FacesItemWidget(file),
const FileDetailsDivider(),
]);
+ if (flagService.petEnabled) {
+ fileDetailsTiles.addAll([
+ PetsItemWidget(file),
+ const FileDetailsDivider(),
+ ]);
+ }
}
if (file.uploadedFileID != null && file.updationTime != null) {
diff --git a/mobile/apps/photos/lib/ui/viewer/file/text_detection_overlay_button.dart b/mobile/apps/photos/lib/ui/viewer/file/text_detection_overlay_button.dart
index ca17fcbc08..6250c21d60 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/text_detection_overlay_button.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/text_detection_overlay_button.dart
@@ -294,4 +294,4 @@ class _DetectionResult {
final String? localPath;
const _DetectionResult({required this.hasText, this.localPath});
-}
\ No newline at end of file
+}
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
new file mode 100644
index 0000000000..e72bf764c2
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/file_info_pets_item_widget.dart
@@ -0,0 +1,223 @@
+import "dart:convert";
+import "dart:typed_data";
+
+import "package:flutter/material.dart";
+import "package:logging/logging.dart";
+import "package:photos/db/ml/db.dart";
+import "package:photos/generated/intl/app_localizations.dart";
+import "package:photos/models/file/file.dart";
+import "package:photos/models/ml/face/box.dart";
+import "package:photos/models/ml/face/detection.dart";
+import "package:photos/models/ml/face/face.dart";
+import "package:photos/theme/ente_theme.dart";
+import "package:photos/ui/common/loading_widget.dart";
+import "package:photos/ui/components/buttons/icon_button_widget.dart";
+import "package:photos/ui/viewer/people/face_thumbnail_squircle.dart";
+import "package:photos/ui/viewer/people/file_face_widget.dart";
+import "package:photos/utils/face/face_thumbnail_cache.dart";
+
+final Logger _logger = Logger("PetsItemWidget");
+
+class PetsItemWidget extends StatefulWidget {
+ final EnteFile file;
+ const PetsItemWidget(this.file, {super.key});
+
+ @override
+ State<PetsItemWidget> createState() => _PetsItemWidgetState();
+}
+
+class _PetsItemWidgetState extends State<PetsItemWidget> {
+ bool _isLoading = true;
+ List<_PetFaceInfo> _petFaces = [];
+
+ @override
+ void initState() {
+ super.initState();
+ _loadPetFaces();
+ }
+
+ Future<void> _loadPetFaces() async {
+ try {
+ final fileKey = widget.file.uploadedFileID;
+ if (fileKey == null) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+
+ final dbPetFaces = await MLDataDB.instance.getPetFacesForFileID(fileKey);
+ if (dbPetFaces == null || dbPetFaces.isEmpty) {
+ if (mounted) setState(() => _isLoading = false);
+ return;
+ }
+
+ // Convert DBPetFace to Face objects for crop generation.
+ // The detection JSON stores box as [xMin, yMin, xMax, yMax] (xyxy),
+ // so we parse it into FaceBox(x, y, width, height) manually.
+ final faces = <Face>[];
+ for (final dbPetFace in dbPetFaces) {
+ final json = jsonDecode(dbPetFace.detection) as Map<String, dynamic>;
+ final boxList = (json['box'] as List).cast<double>();
+ final detection = Detection(
+ box: FaceBox(
+ x: boxList[0],
+ y: boxList[1],
+ width: boxList[2] - boxList[0],
+ height: boxList[3] - boxList[1],
+ ),
+ landmarks: const [],
+ );
+ faces.add(
+ Face(
+ dbPetFace.petFaceId,
+ dbPetFace.fileId,
+ const <double>[],
+ dbPetFace.faceScore,
+ detection,
+ 0.0,
+ ),
+ );
+ }
+
+ final faceCrops = await getCachedFaceCrops(
+ widget.file,
+ faces,
+ useTempCache: true,
+ );
+
+ if (!mounted) return;
+ if (faceCrops == null) {
+ setState(() => _isLoading = false);
+ return;
+ }
+
+ final petFaceInfos = <_PetFaceInfo>[];
+ for (final dbPetFace in dbPetFaces) {
+ final crop = faceCrops[dbPetFace.petFaceId];
+ if (crop != null) {
+ petFaceInfos.add(
+ _PetFaceInfo(
+ petFaceId: dbPetFace.petFaceId,
+ species: dbPetFace.species,
+ faceCrop: crop,
+ ),
+ );
+ }
+ }
+
+ if (mounted) {
+ setState(() {
+ _petFaces = petFaceInfos;
+ _isLoading = false;
+ });
+ }
+ } catch (e, s) {
+ _logger.severe("Failed to load pet faces", e, s);
+ if (mounted) setState(() => _isLoading = false);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ if (!_isLoading && _petFaces.isEmpty) {
+ return const SizedBox.shrink();
+ }
+
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const IconButtonWidget(
+ icon: Icons.pets,
+ iconButtonType: IconButtonType.secondary,
+ ),
+ const SizedBox(width: 12),
+ _buildContent(context),
+ ],
+ );
+ }
+
+ Widget _buildContent(BuildContext context) {
+ if (_isLoading) {
+ return const Expanded(
+ child: Padding(
+ padding: EdgeInsets.only(top: 8, right: 12),
+ child: Center(
+ child: EnteLoadingWidget(
+ padding: 6,
+ size: 20,
+ alignment: Alignment.center,
+ ),
+ ),
+ ),
+ );
+ }
+
+ final screenWidth = MediaQuery.of(context).size.width;
+ final thumbnailWidth = screenWidth * 0.16;
+ final textTheme = getEnteTextTheme(context);
+
+ return Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ AppLocalizations.of(context).discover_pets,
+ style: textTheme.small,
+ ),
+ const SizedBox(height: 10),
+ Padding(
+ padding: const EdgeInsets.only(right: 12.0),
+ child: Wrap(
+ runSpacing: 8,
+ spacing: 12,
+ children: _petFaces
+ .map((info) => _buildPetThumbnail(info, thumbnailWidth))
+ .toList(),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _buildPetThumbnail(_PetFaceInfo info, double thumbnailWidth) {
+ final l10n = AppLocalizations.of(context);
+ final speciesLabel = info.species == "dog" ? l10n.dog : l10n.cat;
+
+ return SizedBox(
+ width: thumbnailWidth,
+ child: Column(
+ children: [
+ SizedBox(
+ height: thumbnailWidth,
+ width: thumbnailWidth,
+ child: FaceThumbnailSquircleClip(
+ child: FileFaceWidget(
+ widget.file,
+ faceCrop: info.faceCrop,
+ ),
+ ),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ speciesLabel,
+ style: getEnteTextTheme(context).mini,
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _PetFaceInfo {
+ final String petFaceId;
+ final String species;
+ final Uint8List faceCrop;
+
+ _PetFaceInfo({
+ required this.petFaceId,
+ required this.species,
+ required this.faceCrop,
+ });
+}
diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
index 51d207f359..c21438625c 100644
--- a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -231,7 +231,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe
} else {
let t = std::time::Instant::now();
let (aligned, mut face_results) =
- run_face_alignment(req.file_id, &decoded, &detections)?;
+ run_face_alignment(req.file_id, &decoded, detections)?;
ml_log(&format!("file={} face alignment: {} faces in {:?} rss={}MB", req.file_id, face_results.len(), t.elapsed(), vm_rss_kb() / 1024));
let t = std::time::Instant::now();
run_face_embedding(runtime, &aligned, &mut face_results)?;
@@ -251,7 +251,7 @@ fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageRe
runtime.unload_clip_session();
ml_log(&format!("file={} clip session unloaded rss={}MB", req.file_id, vm_rss_kb() / 1024));
Some(RustClipResult {
- embedding: clip.embedding.into_iter().map(|v| v as f64).collect(),
+ embedding: clip.embedding,
})
} else {
None
diff --git a/mobile/apps/photos/rust/src/ml/pet/detect.rs b/mobile/apps/photos/rust/src/ml/pet/detect.rs
index 04f3ac1376..254d1178ce 100644
--- a/mobile/apps/photos/rust/src/ml/pet/detect.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/detect.rs
@@ -37,7 +37,7 @@ pub fn run_pet_face_detection(
let (output_shape, output_data) = onnx::run_f32(
pet_face_detection,
input,
- vec![1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
+ [1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
// Row format: [x, y, w, h, obj_conf, lx, ly, rx, ry, nx, ny, cls_conf...]
@@ -137,7 +137,7 @@ pub fn run_pet_body_detection(
let (_output_shape, output_data) = onnx::run_f32(
body_detection,
input,
- vec![1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
+ [1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
)?;
// YOLOv5 output format: [x, y, w, h, obj_conf, cls0, cls1, ..., cls79]
diff --git a/mobile/apps/photos/rust/src/ml/pet/embed.rs b/mobile/apps/photos/rust/src/ml/pet/embed.rs
index 8c89d49e3e..850343654e 100644
--- a/mobile/apps/photos/rust/src/ml/pet/embed.rs
+++ b/mobile/apps/photos/rust/src/ml/pet/embed.rs
@@ -59,7 +59,7 @@ pub fn run_pet_face_embedding(
let (shape, output) = onnx::run_f32(
session,
input,
- vec![
+ [
aligned_faces.len() as i64,
FACE_EMBED_CHANNELS,
FACE_EMBED_INPUT_SIZE,
@@ -117,7 +117,7 @@ pub fn run_pet_body_embedding(
let (_shape, output) = onnx::run_f32(
session,
input,
- vec![
+ [
1,
BODY_EMBED_CHANNELS,
BODY_EMBED_INPUT_SIZE,
diff --git a/mobile/apps/photos/rust_builder/cargokit/build_tool/lib/src/android_environment.dart b/mobile/apps/photos/rust_builder/cargokit/build_tool/lib/src/android_environment.dart
index 757bf2dcbc..e1abd27645 100644
--- a/mobile/apps/photos/rust_builder/cargokit/build_tool/lib/src/android_environment.dart
+++ b/mobile/apps/photos/rust_builder/cargokit/build_tool/lib/src/android_environment.dart
@@ -119,8 +119,8 @@ class AndroidEnvironment {
final cxxFlagsKey = 'CXXFLAGS_${target.rust}';
final cxxFlagsValue = targetArg;
- final linkerKey = 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'
- .toUpperCase();
+ final linkerKey =
+ 'cargo_target_${target.rust.replaceAll('-', '_')}_linker'.toUpperCase();
final ranlibKey = 'RANLIB_${target.rust}';
final ranlibValue = path.join(toolchainPath, 'llvm-ranlib$exe');
@@ -129,13 +129,13 @@ class AndroidEnvironment {
final rustFlagsKey = 'CARGO_ENCODED_RUSTFLAGS';
final rustFlagsValue = _libGccWorkaround(targetTempDir, ndkVersionParsed);
- final runRustTool = Platform.isWindows
- ? 'run_build_tool.cmd'
- : 'run_build_tool.sh';
+ final runRustTool =
+ Platform.isWindows ? 'run_build_tool.cmd' : 'run_build_tool.sh';
final packagePath = (await Isolate.resolvePackageUri(
Uri.parse('package:build_tool/buildtool.dart'),
- ))!.toFilePath();
+ ))!
+ .toFilePath();
final selfPath = Uri.file(
path.join(packagePath, '..', '..', '..', runRustTool),
).normalizePath().toFilePath(windows: Platform.isWindows);