Skip to content

armgit / ente

Public Imported from GitHub
0

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

ML in rust rewrite MVP

laurenspriem668f50909aa9
diff --git a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
index 1f184c76df..d84d3e69eb 100644
--- a/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
+++ b/mobile/apps/photos/lib/services/machine_learning/ml_indexing_isolate.dart
@@ -2,6 +2,7 @@ import "dart:async";
import "package:flutter/foundation.dart" show debugPrint;
import "package:logging/logging.dart";
+import "package:photos/service_locator.dart" show flagService;
import 'package:photos/services/machine_learning/face_ml/face_detection/face_detection_service.dart';
import 'package:photos/services/machine_learning/face_ml/face_embedding/face_embedding_service.dart';
import "package:photos/services/machine_learning/ml_models_overview.dart";
@@ -66,12 +67,34 @@ class MLIndexingIsolate extends SuperIsolate {
late MLResult result;
try {
+ final useRustMl = _shouldUseRustMl;
+ String? faceDetectionModelPath;
+ String? faceEmbeddingModelPath;
+ String? clipImageModelPath;
+ if (useRustMl) {
+ final faceDetection =
+ await FaceDetectionService.instance.getModelNameAndPath();
+ faceDetectionModelPath = faceDetection.$2;
+ final faceEmbedding =
+ await FaceEmbeddingService.instance.getModelNameAndPath();
+ faceEmbeddingModelPath = faceEmbedding.$2;
+ final clipImage = await ClipImageEncoder.instance.getModelNameAndPath();
+ clipImageModelPath = clipImage.$2;
+ }
+
final resultJsonString =
await runInIsolate(IsolateOperation.analyzeImage, {
"enteFileID": instruction.fileKey,
"filePath": filePath,
+ "useRustMl": useRustMl,
"runFaces": instruction.shouldRunFaces,
"runClip": instruction.shouldRunClip,
+ "faceDetectionModelPath": faceDetectionModelPath,
+ "faceEmbeddingModelPath": faceEmbeddingModelPath,
+ "clipImageModelPath": clipImageModelPath,
+ "preferCoreml": true,
+ "preferNnapi": true,
+ "allowCpuFallback": true,
"faceDetectionAddress": FaceDetectionService.instance.sessionAddress,
"faceEmbeddingAddress": FaceEmbeddingService.instance.sessionAddress,
"clipImageAddress": ClipImageEncoder.instance.sessionAddress,
@@ -98,6 +121,8 @@ class MLIndexingIsolate extends SuperIsolate {
return result;
}
+ bool get _shouldUseRustMl => flagService.useRustForML;
+
void triggerModelsDownload() {
if (!areModelsDownloaded && !_downloadModelLock.locked) {
_logger.info("Models not downloaded, starting download");
@@ -133,6 +158,9 @@ class MLIndexingIsolate extends SuperIsolate {
}
Future<void> ensureLoadedModels(FileMLInstruction instruction) async {
+ if (_shouldUseRustMl) {
+ return;
+ }
return _initModelLock.synchronized(() async {
final faceDetectionLoaded = FaceDetectionService.instance.isInitialized;
final faceEmbeddingLoaded = FaceEmbeddingService.instance.isInitialized;
diff --git a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
index bd939f82bb..e22415e26f 100644
--- a/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
+++ b/mobile/apps/photos/lib/utils/isolate/isolate_operations.dart
@@ -12,6 +12,7 @@ import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_text_encoder.dart";
import "package:photos/services/machine_learning/semantic_search/clip/clip_text_tokenizer.dart";
import "package:photos/services/machine_learning/semantic_search/query_result.dart";
+import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
import "package:photos/src/rust/frb_generated.dart" show EntePhotosRust;
import "package:photos/utils/image_ml_util.dart";
import "package:photos/utils/ml_util.dart";
@@ -92,7 +93,13 @@ Future<dynamic> isolateFunction(
/// MLIndexingIsolate
case IsolateOperation.analyzeImage:
- final MLResult result = await analyzeImageStatic(args);
+ final bool useRustMl = args["useRustMl"] as bool? ?? false;
+ if (useRustMl) {
+ await _ensureRustLoaded();
+ }
+ final MLResult result = useRustMl
+ ? await analyzeImageRust(args)
+ : await analyzeImageStatic(args);
return result.toJsonString();
/// MLIndexingIsolate
@@ -213,7 +220,7 @@ Future<dynamic> isolateFunction(
/// Caching
case IsolateOperation.clearAllIsolateCache:
- _ensureRustDisposed();
+ await _ensureRustDisposed();
_isolateCache.clear();
return true;
@@ -229,9 +236,14 @@ Future<void> _ensureRustLoaded() async {
}
}
-void _ensureRustDisposed() {
+Future<void> _ensureRustDisposed() async {
final bool loaded = _isolateCache["rustLibLoaded"] as bool? ?? false;
if (loaded) {
+ try {
+ await rust_ml.releaseMlRuntime();
+ } catch (_) {
+ // no-op: runtime release is best-effort before process-wide bridge dispose.
+ }
EntePhotosRust.dispose();
_isolateCache.remove("rustLibLoaded");
}
diff --git a/mobile/apps/photos/lib/utils/ml_util.dart b/mobile/apps/photos/lib/utils/ml_util.dart
index 75f4a9b915..ded90f69f7 100644
--- a/mobile/apps/photos/lib/utils/ml_util.dart
+++ b/mobile/apps/photos/lib/utils/ml_util.dart
@@ -12,16 +12,20 @@ import "package:photos/models/file/extensions/file_props.dart";
import "package:photos/models/file/file.dart";
import "package:photos/models/file/file_type.dart";
import "package:photos/models/ml/clip.dart";
+import "package:photos/models/ml/face/dimension.dart";
import "package:photos/models/ml/face/face.dart";
import "package:photos/models/ml/ml_versions.dart";
import "package:photos/service_locator.dart";
import "package:photos/services/filedata/model/file_data.dart";
+import "package:photos/services/machine_learning/face_ml/face_alignment/alignment_result.dart";
+import "package:photos/services/machine_learning/face_ml/face_detection/detection.dart";
import "package:photos/services/machine_learning/face_ml/face_recognition_service.dart";
import "package:photos/services/machine_learning/ml_exceptions.dart";
import "package:photos/services/machine_learning/ml_result.dart";
import "package:photos/services/machine_learning/semantic_search/semantic_search_service.dart";
import "package:photos/services/search_service.dart";
import "package:photos/services/sync/local_sync_service.dart";
+import "package:photos/src/rust/api/ml_indexing_api.dart" as rust_ml;
import "package:photos/utils/file_util.dart";
import "package:photos/utils/image_ml_util.dart";
import "package:photos/utils/network_util.dart";
@@ -589,3 +593,112 @@ Future<MLResult> analyzeImageStatic(Map args) async {
rethrow;
}
}
+
+Future<MLResult> analyzeImageRust(Map args) async {
+ try {
+ final int enteFileID = args["enteFileID"] as int;
+ final String imagePath = args["filePath"] as String;
+ final bool runFaces = args["runFaces"] as bool;
+ final bool runClip = args["runClip"] as bool;
+ final String? faceDetectionModelPath =
+ args["faceDetectionModelPath"] as String?;
+ final String? faceEmbeddingModelPath =
+ args["faceEmbeddingModelPath"] as String?;
+ final String? clipImageModelPath = args["clipImageModelPath"] as String?;
+ final bool preferCoreml = args["preferCoreml"] as bool? ?? true;
+ final bool preferNnapi = args["preferNnapi"] as bool? ?? true;
+ final bool allowCpuFallback = args["allowCpuFallback"] as bool? ?? true;
+
+ if (runFaces || runClip) {
+ if (faceDetectionModelPath == null ||
+ faceEmbeddingModelPath == null ||
+ clipImageModelPath == null) {
+ throw Exception(
+ "RustMLMissingModelPath: Expected all model paths to be provided",
+ );
+ }
+ }
+
+ final providerPolicy = rust_ml.RustExecutionProviderPolicy(
+ preferCoreml: preferCoreml,
+ preferNnapi: preferNnapi,
+ allowCpuFallback: allowCpuFallback,
+ );
+ await rust_ml.initMlRuntime(
+ config: rust_ml.RustMlRuntimeConfig(
+ modelPaths: rust_ml.RustModelPaths(
+ faceDetection: faceDetectionModelPath ?? "",
+ faceEmbedding: faceEmbeddingModelPath ?? "",
+ clipImage: clipImageModelPath ?? "",
+ ),
+ providerPolicy: providerPolicy,
+ ),
+ );
+
+ final rustResult = await rust_ml.analyzeImageRust(
+ req: rust_ml.AnalyzeImageRequest(
+ fileId: enteFileID,
+ imagePath: imagePath,
+ runFaces: runFaces,
+ runClip: runClip,
+ modelPaths: rust_ml.RustModelPaths(
+ faceDetection: faceDetectionModelPath ?? "",
+ faceEmbedding: faceEmbeddingModelPath ?? "",
+ clipImage: clipImageModelPath ?? "",
+ ),
+ providerPolicy: providerPolicy,
+ ),
+ );
+
+ final result = MLResult.fromEnteFileID(enteFileID);
+ result.decodedImageSize = Dimensions(
+ width: rustResult.decodedImageSize.width,
+ height: rustResult.decodedImageSize.height,
+ );
+
+ if (runFaces) {
+ final rustFaces = rustResult.faces ?? const <rust_ml.RustFaceResult>[];
+ result.faces = rustFaces.map((face) {
+ final detection = FaceDetectionRelative(
+ score: face.detection.score,
+ box: face.detection.boxXyxy.toList(growable: false),
+ allKeypoints: face.detection.allKeypoints
+ .map((point) => point.toList(growable: false))
+ .toList(growable: false),
+ );
+ final alignment = AlignmentResult(
+ affineMatrix: face.alignment.affineMatrix
+ .map((row) => row.toList(growable: false))
+ .toList(growable: false),
+ center: face.alignment.center.toList(growable: false),
+ size: face.alignment.size,
+ rotation: face.alignment.rotation,
+ );
+ return FaceResult(
+ fileId: enteFileID,
+ faceId: face.faceId,
+ detection: detection,
+ blurValue: face.blurValue,
+ alignment: alignment,
+ embedding: face.embedding.toList(growable: false),
+ );
+ }).toList(growable: false);
+ }
+
+ if (runClip) {
+ final rustClip = rustResult.clip;
+ if (rustClip == null) {
+ throw Exception("RustMLMissingClipOutput: clip output was null");
+ }
+ result.clip = ClipResult(
+ fileID: enteFileID,
+ embedding: rustClip.embedding.toList(growable: false),
+ );
+ }
+
+ return result;
+ } catch (e, s) {
+ _logger.severe("Could not analyze image with Rust pipeline", e, s);
+ rethrow;
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
index fe67ea73ff..f67b31b1eb 100644
--- a/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
+++ b/mobile/apps/photos/plugins/ente_feature_flag/lib/src/service.dart
@@ -102,6 +102,8 @@ class FlagService {
bool get isSocialEnabled =>
internalUser || _isServerFlagEnabled(_commentsFlag);
+ bool get useRustForML => internalUser;
+
Future<void> tryRefreshFlags() async {
try {
await _fetch();
diff --git a/mobile/apps/photos/rust/Cargo.lock b/mobile/apps/photos/rust/Cargo.lock
index 6ac7e63afc..91367acb67 100644
--- a/mobile/apps/photos/rust/Cargo.lock
+++ b/mobile/apps/photos/rust/Cargo.lock
@@ -2,6 +2,22 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "ab_glyph"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2"
+dependencies = [
+ "ab_glyph_rasterizer",
+ "owned_ttf_parser",
+]
+
+[[package]]
+name = "ab_glyph_rasterizer"
+version = "0.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
+
[[package]]
name = "addr2line"
version = "0.25.1"
@@ -26,6 +42,24 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "aligned"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685"
+dependencies = [
+ "as-slice",
+]
+
+[[package]]
+name = "aligned-vec"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
+dependencies = [
+ "equator",
+]
+
[[package]]
name = "allo-isolate"
version = "0.1.27"
@@ -66,12 +100,102 @@ version = "1.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+[[package]]
+name = "approx"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+
+[[package]]
+name = "arg_enum_proc_macro"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "as-slice"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
+dependencies = [
+ "stable_deref_trait",
+]
+
[[package]]
name = "atomic"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c59bdb34bc650a32731b31bd8f0829cc15d24a708ee31559e0bb34f2bc320cba"
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "av-scenechange"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
+dependencies = [
+ "aligned",
+ "anyhow",
+ "arg_enum_proc_macro",
+ "arrayvec",
+ "log",
+ "num-rational",
+ "num-traits",
+ "pastey",
+ "rayon",
+ "thiserror",
+ "v_frame",
+ "y4m",
+]
+
+[[package]]
+name = "av1-grain"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
+dependencies = [
+ "anyhow",
+ "arrayvec",
+ "log",
+ "nom",
+ "num-rational",
+ "v_frame",
+]
+
+[[package]]
+name = "avif-serialize"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "375082f007bd67184fb9c0374614b29f9aaa604ec301635f72338bb65386a53d"
+dependencies = [
+ "arrayvec",
+]
+
[[package]]
name = "backtrace"
version = "0.3.76"
@@ -87,12 +211,27 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "bit_field"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"
+
[[package]]
name = "bitflags"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+[[package]]
+name = "bitstream-io"
+version = "4.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60d4bd9d1db2c6bdf285e223a7fa369d5ce98ec767dec949c6ca62863ce61757"
+dependencies = [
+ "core2",
+]
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -108,6 +247,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "832133bbabbbaa9fbdba793456a2827627a7d2b8fb96032fa1e7666d7895832b"
+[[package]]
+name = "built"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64"
+
[[package]]
name = "bumpalo"
version = "3.19.0"
@@ -126,6 +271,12 @@ version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
[[package]]
name = "cc"
version = "1.2.49"
@@ -133,6 +284,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90583009037521a116abf44494efecd645ba48b6622457080f080b85544e2215"
dependencies = [
"find-msvc-tools",
+ "jobserver",
+ "libc",
"shlex",
]
@@ -179,6 +332,12 @@ dependencies = [
"unicode-width",
]
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -189,6 +348,55 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "core2"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -304,6 +512,21 @@ dependencies = [
"crypto-common",
]
+[[package]]
+name = "document-features"
+version = "0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
+dependencies = [
+ "litrs",
+]
+
+[[package]]
+name = "either"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+
[[package]]
name = "ente_media_inspector"
version = "0.1.0"
@@ -316,10 +539,31 @@ name = "ente_photos_rust"
version = "0.0.1"
dependencies = [
"ente_media_inspector",
+ "fast_image_resize",
"flutter_rust_bridge",
+ "image",
+ "imageproc",
+ "kamadak-exif",
+ "libheif-rs",
+ "nalgebra 0.33.2",
+ "ndarray 0.16.1",
+ "once_cell",
+ "ort",
+ "thiserror",
"usearch",
]
+[[package]]
+name = "enumn"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f9ed6b3789237c8a0c1c505af1c7eb2c560df6186f01b098c3a1064ea532f38"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "env_filter"
version = "0.1.4"
@@ -330,18 +574,107 @@ dependencies = [
"regex",
]
+[[package]]
+name = "equator"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
+dependencies = [
+ "equator-macro",
+]
+
+[[package]]
+name = "equator-macro"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+[[package]]
+name = "exr"
+version = "1.74.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be"
+dependencies = [
+ "bit_field",
+ "half",
+ "lebe",
+ "miniz_oxide",
+ "rayon-core",
+ "smallvec",
+ "zune-inflate",
+]
+
+[[package]]
+name = "fast_image_resize"
+version = "5.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fbc7fe45cf92b43817ff62a3723e862b85bd1d06288f63007f7645d1d2f7a060"
+dependencies = [
+ "bytemuck",
+ "cfg-if",
+ "document-features",
+ "image",
+ "num-traits",
+ "rayon",
+ "thiserror",
+]
+
+[[package]]
+name = "fax"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab"
+dependencies = [
+ "fax_derive",
+]
+
+[[package]]
+name = "fax_derive"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844"
+[[package]]
+name = "flate2"
+version = "1.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+]
+
[[package]]
name = "flutter_rust_bridge"
version = "2.11.1"
@@ -390,6 +723,12 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "four-cc"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "795cbfc56d419a7ce47ccbb7504dd9a5b7c484c083c356e797de08bd988d9629"
+
[[package]]
name = "futures"
version = "0.3.31"
@@ -489,12 +828,58 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+]
+
+[[package]]
+name = "gif"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f5df2ba84018d80c213569363bdcd0c64e6933c67fe4c1d60ecf822971a3c35e"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
[[package]]
name = "gimli"
version = "0.32.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
[[package]]
name = "hashbrown"
version = "0.14.5"
@@ -520,60 +905,257 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
-name = "indexmap"
-version = "2.12.1"
+name = "image"
+version = "0.25.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
+checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a"
dependencies = [
- "equivalent",
- "hashbrown 0.16.1",
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "exr",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "qoi",
+ "ravif",
+ "rayon",
+ "rgb",
+ "tiff",
+ "zune-core 0.5.1",
+ "zune-jpeg 0.5.12",
]
[[package]]
-name = "js-sys"
-version = "0.3.83"
+name = "image-webp"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
dependencies = [
- "once_cell",
- "wasm-bindgen",
+ "byteorder-lite",
+ "quick-error",
]
[[package]]
-name = "lazy_static"
-version = "1.5.0"
+name = "imageproc"
+version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+checksum = "2393fb7808960751a52e8a154f67e7dd3f8a2ef9bd80d1553078a7b4e8ed3f0d"
+dependencies = [
+ "ab_glyph",
+ "approx",
+ "getrandom 0.2.17",
+ "image",
+ "itertools 0.12.1",
+ "nalgebra 0.32.6",
+ "num",
+ "rand 0.8.5",
+ "rand_distr",
+ "rayon",
+]
[[package]]
-name = "libc"
-version = "0.2.178"
+name = "imgref"
+version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
+checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8"
[[package]]
-name = "link-cplusplus"
-version = "1.0.12"
+name = "indexmap"
+version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
+checksum = "0ad4bb2b565bca0645f4d68c5c9af97fba094e9791da685bf83cb5f3ce74acf2"
dependencies = [
- "cc",
+ "equivalent",
+ "hashbrown 0.16.1",
]
[[package]]
-name = "lock_api"
-version = "0.4.14"
+name = "interpolate_name"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
dependencies = [
- "scopeguard",
+ "proc-macro2",
+ "quote",
+ "syn",
]
[[package]]
-name = "log"
-version = "0.4.29"
+name = "itertools"
+version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom 0.3.4",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.83"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "464a3709c7f55f1f721e5389aa6ea4e3bc6aba669353300af094b29ffbdde1d8"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "kamadak-exif"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1130d80c7374efad55a117d715a3af9368f0fa7a2c54573afc15a188cd984837"
+dependencies = [
+ "mutate_once",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
+
+[[package]]
+name = "lebe"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
+
+[[package]]
+name = "libc"
+version = "0.2.178"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37c93d8daa9d8a012fd8ab92f088405fb202ea0b6ab73ee2482ae66af4f42091"
+
+[[package]]
+name = "libfuzzer-sys"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f12a681b7dd8ce12bff52488013ba614b869148d54dd79836ab85aafdd53f08d"
+dependencies = [
+ "arbitrary",
+ "cc",
+]
+
+[[package]]
+name = "libheif-rs"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4a26370abb4723a3ce73083e479b98017604206cadb0e35da5eac4813600d85"
+dependencies = [
+ "enumn",
+ "four-cc",
+ "libc",
+ "libheif-sys",
+]
+
+[[package]]
+name = "libheif-sys"
+version = "3.1.0+1.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e663db80d4272b60c066c5a9d17370ffa0433a31d424152f95f1e1effb9b3860"
+dependencies = [
+ "libc",
+ "pkg-config",
+ "vcpkg",
+ "walkdir",
+]
+
+[[package]]
+name = "libloading"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60"
+dependencies = [
+ "cfg-if",
+ "windows-link",
+]
+
+[[package]]
+name = "libm"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"
+
+[[package]]
+name = "link-cplusplus"
+version = "1.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "litrs"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
+
+[[package]]
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "loop9"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"
+dependencies = [
+ "imgref",
+]
+
+[[package]]
+name = "matrixmultiply"
+version = "0.3.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"
+dependencies = [
+ "autocfg",
+ "rawpointer",
+]
+
+[[package]]
+name = "maybe-rayon"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
+dependencies = [
+ "cfg-if",
+ "rayon",
+]
[[package]]
name = "md-5"
@@ -598,6 +1180,201 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.7.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac9557c559cd6fc9867e122e20d2cbefc9ca29d80d027a8e39310920ed2f0a97"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "mutate_once"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13d2233c9842d08cfe13f9eac96e207ca6a2ea10b80259ebe8ad0268be27d2af"
+
+[[package]]
+name = "nalgebra"
+version = "0.32.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b5c17de023a86f59ed79891b2e5d5a94c705dbe904a5b5c9c952ea6221b03e4"
+dependencies = [
+ "approx",
+ "matrixmultiply",
+ "num-complex",
+ "num-rational",
+ "num-traits",
+ "simba 0.8.1",
+ "typenum",
+]
+
+[[package]]
+name = "nalgebra"
+version = "0.33.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26aecdf64b707efd1310e3544d709c5c0ac61c13756046aaaba41be5c4f66a3b"
+dependencies = [
+ "approx",
+ "matrixmultiply",
+ "nalgebra-macros",
+ "num-complex",
+ "num-rational",
+ "num-traits",
+ "simba 0.9.1",
+ "typenum",
+]
+
+[[package]]
+name = "nalgebra-macros"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "ndarray"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
+dependencies = [
+ "matrixmultiply",
+ "num-complex",
+ "num-integer",
+ "num-traits",
+ "portable-atomic",
+ "portable-atomic-util",
+ "rawpointer",
+]
+
+[[package]]
+name = "ndarray"
+version = "0.17.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
+dependencies = [
+ "matrixmultiply",
+ "num-complex",
+ "num-integer",
+ "num-traits",
+ "portable-atomic",
+ "portable-atomic-util",
+ "rawpointer",
+]
+
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "noop_proc_macro"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
+
+[[package]]
+name = "num"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
+dependencies = [
+ "num-bigint",
+ "num-complex",
+ "num-integer",
+ "num-iter",
+ "num-rational",
+ "num-traits",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-complex"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-iter"
+version = "0.1.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
+dependencies = [
+ "autocfg",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+ "libm",
]
[[package]]
@@ -625,6 +1402,25 @@ version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+[[package]]
+name = "ort"
+version = "2.0.0-rc.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a5df903c0d2c07b56950f1058104ab0c8557159f2741782223704de9be73c3c"
+dependencies = [
+ "libloading",
+ "ndarray 0.17.2",
+ "ort-sys",
+ "smallvec",
+ "tracing",
+]
+
+[[package]]
+name = "ort-sys"
+version = "2.0.0-rc.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06503bb33f294c5f1ba484011e053bfa6ae227074bdb841e9863492dc5960d4b"
+
[[package]]
name = "oslog"
version = "0.2.0"
@@ -636,6 +1432,15 @@ dependencies = [
"log",
]
+[[package]]
+name = "owned_ttf_parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b"
+dependencies = [
+ "ttf-parser",
+]
+
[[package]]
name = "parking_lot_core"
version = "0.9.12"
@@ -649,6 +1454,18 @@ dependencies = [
"windows-link",
]
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "pastey"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
+
[[package]]
name = "pin-project-lite"
version = "0.2.16"
@@ -661,12 +1478,49 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+[[package]]
+name = "pkg-config"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
[[package]]
name = "portable-atomic"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f84267b20a16ea918e43c6a88433c2d54fa145c92a811b5b047ccbe153674483"
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a9db96d7fa8782dd8c15ce32ffe8680bbd1e978a43bf51a34d39483540495f5"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.103"
@@ -676,6 +1530,49 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "profiling"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b"
+dependencies = [
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7186d3822593aa4393561d186d1393b3923e9d6163d3fbfd6e825e3e6cf3e6a8"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "qoi"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
[[package]]
name = "quick-xml"
version = "0.37.5"
@@ -694,6 +1591,157 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.8.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+dependencies = [
+ "libc",
+ "rand_chacha 0.3.1",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+dependencies = [
+ "rand_chacha 0.9.0",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.6.4",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
+dependencies = [
+ "getrandom 0.2.17",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+dependencies = [
+ "getrandom 0.3.4",
+]
+
+[[package]]
+name = "rand_distr"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32cb0b9bc82b0a0876c2dd994a7e7a2683d3e7390ca40e6886785ef0c7e3ee31"
+dependencies = [
+ "num-traits",
+ "rand 0.8.5",
+]
+
+[[package]]
+name = "rav1e"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
+dependencies = [
+ "aligned-vec",
+ "arbitrary",
+ "arg_enum_proc_macro",
+ "arrayvec",
+ "av-scenechange",
+ "av1-grain",
+ "bitstream-io",
+ "built",
+ "cfg-if",
+ "interpolate_name",
+ "itertools 0.14.0",
+ "libc",
+ "libfuzzer-sys",
+ "log",
+ "maybe-rayon",
+ "new_debug_unreachable",
+ "noop_proc_macro",
+ "num-derive",
+ "num-traits",
+ "paste",
+ "profiling",
+ "rand 0.9.2",
+ "rand_chacha 0.9.0",
+ "simd_helpers",
+ "thiserror",
+ "v_frame",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "ravif"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef69c1990ceef18a116855938e74793a5f7496ee907562bd0857b6ac734ab285"
+dependencies = [
+ "avif-serialize",
+ "imgref",
+ "loop9",
+ "quick-error",
+ "rav1e",
+ "rayon",
+ "rgb",
+]
+
+[[package]]
+name = "rawpointer"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
+
+[[package]]
+name = "rayon"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "redox_syscall"
version = "0.5.18"
@@ -732,6 +1780,12 @@ version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"
+[[package]]
+name = "rgb"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c6a884d2998352bb4daf0183589aec883f16a6da1f4dde84d8e2e9a5409a1ce"
+
[[package]]
name = "rustc-demangle"
version = "0.1.26"
@@ -744,6 +1798,24 @@ version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+[[package]]
+name = "safe_arch"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "same-file"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
[[package]]
name = "scopeguard"
version = "1.2.0"
@@ -792,6 +1864,47 @@ version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+[[package]]
+name = "simba"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "061507c94fc6ab4ba1c9a0305018408e312e17c041eb63bef8aa726fa33aceae"
+dependencies = [
+ "approx",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "wide",
+]
+
+[[package]]
+name = "simba"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95"
+dependencies = [
+ "approx",
+ "num-complex",
+ "num-traits",
+ "paste",
+ "wide",
+]
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
+
+[[package]]
+name = "simd_helpers"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
+dependencies = [
+ "quote",
+]
+
[[package]]
name = "slab"
version = "0.4.11"
@@ -804,6 +1917,12 @@ version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
[[package]]
name = "strsim"
version = "0.11.1"
@@ -830,6 +1949,26 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "threadpool"
version = "1.8.1"
@@ -839,6 +1978,20 @@ dependencies = [
"num_cpus",
]
+[[package]]
+name = "tiff"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg 0.4.21",
+]
+
[[package]]
name = "tokio"
version = "1.48.0"
@@ -848,6 +2001,31 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "ttf-parser"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31"
+
[[package]]
name = "typenum"
version = "1.19.0"
@@ -876,12 +2054,54 @@ dependencies = [
"cxx-build",
]
+[[package]]
+name = "v_frame"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
+dependencies = [
+ "aligned-vec",
+ "num-traits",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
[[package]]
name = "wasm-bindgen"
version = "0.2.106"
@@ -950,6 +2170,22 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "wide"
+version = "0.7.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"
+dependencies = [
+ "bytemuck",
+ "safe_arch",
+]
+
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -973,3 +2209,74 @@ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+
+[[package]]
+name = "y4m"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.39"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zune-core"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
+
+[[package]]
+name = "zune-core"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb8a0807f7c01457d0379ba880ba6322660448ddebc890ce29bb64da71fb40f9"
+
+[[package]]
+name = "zune-inflate"
+version = "0.2.54"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "zune-jpeg"
+version = "0.4.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
+dependencies = [
+ "zune-core 0.4.12",
+]
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "410e9ecef634c709e3831c2cfdb8d9c32164fae1c67496d5b68fff728eec37fe"
+dependencies = [
+ "zune-core 0.5.1",
+]
diff --git a/mobile/apps/photos/rust/Cargo.toml b/mobile/apps/photos/rust/Cargo.toml
index 763e852159..6f5952b027 100644
--- a/mobile/apps/photos/rust/Cargo.toml
+++ b/mobile/apps/photos/rust/Cargo.toml
@@ -10,6 +10,20 @@ crate-type = ["cdylib", "staticlib"]
flutter_rust_bridge = "=2.11.1"
usearch = "2.21.3"
ente_media_inspector = { path = "../../../../rust/photos" }
+fast_image_resize = { version = "5.5.0", features = ["image", "rayon"] }
+image = { version = "0.25.5", default-features = true }
+imageproc = "0.25.0"
+kamadak-exif = "0.6.1"
+libheif-rs = { version = "1.0.2", optional = true }
+nalgebra = "0.33.2"
+ndarray = "0.16.1"
+once_cell = "1.20.2"
+ort = { version = "2.0.0-rc.9", default-features = false, features = ["ndarray", "load-dynamic", "copy-dylibs", "coreml", "nnapi"] }
+thiserror = "2.0.11"
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(frb_expand)'] }
+
+[features]
+default = []
+heif = ["dep:libheif-rs"]
diff --git a/mobile/apps/photos/rust/src/api/ml_indexing_api.rs b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
new file mode 100644
index 0000000000..070e35e3fb
--- /dev/null
+++ b/mobile/apps/photos/rust/src/api/ml_indexing_api.rs
@@ -0,0 +1,209 @@
+use crate::ml::{
+ clip::image::run_clip_image,
+ decode::decode_image_from_path,
+ error::MlResult,
+ face::{align::run_face_alignment, detect::run_face_detection, embed::run_face_embedding},
+ runtime::{self, ExecutionProviderPolicy, MlRuntimeConfig, ModelPaths},
+};
+
+#[derive(Clone, Debug)]
+pub struct RustExecutionProviderPolicy {
+ pub prefer_coreml: bool,
+ pub prefer_nnapi: bool,
+ pub allow_cpu_fallback: bool,
+}
+
+impl Default for RustExecutionProviderPolicy {
+ fn default() -> Self {
+ Self {
+ prefer_coreml: true,
+ prefer_nnapi: true,
+ allow_cpu_fallback: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct RustModelPaths {
+ pub face_detection: String,
+ pub face_embedding: String,
+ pub clip_image: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustMlRuntimeConfig {
+ pub model_paths: RustModelPaths,
+ pub provider_policy: RustExecutionProviderPolicy,
+}
+
+#[derive(Clone, Debug)]
+pub struct AnalyzeImageRequest {
+ pub file_id: i64,
+ pub image_path: String,
+ pub run_faces: bool,
+ pub run_clip: bool,
+ pub model_paths: RustModelPaths,
+ pub provider_policy: RustExecutionProviderPolicy,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustDimensions {
+ pub width: i32,
+ pub height: i32,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustDetection {
+ pub score: f64,
+ pub box_xyxy: Vec<f64>,
+ pub all_keypoints: Vec<Vec<f64>>,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustAlignmentResult {
+ pub affine_matrix: Vec<Vec<f64>>,
+ pub center: Vec<f64>,
+ pub size: f64,
+ pub rotation: f64,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustFaceResult {
+ pub detection: RustDetection,
+ pub blur_value: f64,
+ pub alignment: RustAlignmentResult,
+ pub embedding: Vec<f64>,
+ pub face_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct RustClipResult {
+ pub embedding: Vec<f64>,
+}
+
+#[derive(Clone, Debug)]
+pub struct AnalyzeImageResult {
+ pub file_id: i64,
+ pub decoded_image_size: RustDimensions,
+ pub faces: Option<Vec<RustFaceResult>>,
+ pub clip: Option<RustClipResult>,
+}
+
+pub fn init_ml_runtime(config: RustMlRuntimeConfig) -> Result<(), String> {
+ runtime::ensure_runtime(&to_runtime_config(&config)).map_err(|e| e.to_string())
+}
+
+pub fn release_ml_runtime() -> Result<(), String> {
+ runtime::release_runtime().map_err(|e| e.to_string())
+}
+
+pub fn analyze_image_rust(req: AnalyzeImageRequest) -> Result<AnalyzeImageResult, String> {
+ analyze_image_rust_inner(req).map_err(|e| e.to_string())
+}
+
+fn analyze_image_rust_inner(req: AnalyzeImageRequest) -> MlResult<AnalyzeImageResult> {
+ let runtime_config = MlRuntimeConfig {
+ model_paths: to_model_paths(&req.model_paths),
+ provider_policy: to_provider_policy(&req.provider_policy),
+ };
+
+ let decoded = decode_image_from_path(&req.image_path)?;
+ let dims = RustDimensions {
+ width: decoded.dimensions.width as i32,
+ height: decoded.dimensions.height as i32,
+ };
+
+ runtime::with_runtime_mut(&runtime_config, |runtime| {
+ let faces = if req.run_faces {
+ let detections = run_face_detection(runtime, &decoded)?;
+ if detections.is_empty() {
+ Some(Vec::new())
+ } else {
+ let (aligned, mut face_results) =
+ run_face_alignment(req.file_id, &decoded, &detections)?;
+ run_face_embedding(runtime, &aligned, &mut face_results)?;
+ Some(face_results.into_iter().map(to_api_face_result).collect())
+ }
+ } else {
+ None
+ };
+
+ let clip = if req.run_clip {
+ let clip = run_clip_image(runtime, &decoded)?;
+ Some(RustClipResult {
+ embedding: clip.embedding.into_iter().map(|v| v as f64).collect(),
+ })
+ } else {
+ None
+ };
+
+ Ok(AnalyzeImageResult {
+ file_id: req.file_id,
+ decoded_image_size: dims,
+ faces,
+ clip,
+ })
+ })
+}
+
+fn to_runtime_config(config: &RustMlRuntimeConfig) -> MlRuntimeConfig {
+ MlRuntimeConfig {
+ model_paths: to_model_paths(&config.model_paths),
+ provider_policy: to_provider_policy(&config.provider_policy),
+ }
+}
+
+fn to_model_paths(paths: &RustModelPaths) -> ModelPaths {
+ ModelPaths {
+ face_detection: paths.face_detection.clone(),
+ face_embedding: paths.face_embedding.clone(),
+ clip_image: paths.clip_image.clone(),
+ }
+}
+
+fn to_provider_policy(policy: &RustExecutionProviderPolicy) -> ExecutionProviderPolicy {
+ ExecutionProviderPolicy {
+ prefer_coreml: policy.prefer_coreml,
+ prefer_nnapi: policy.prefer_nnapi,
+ allow_cpu_fallback: policy.allow_cpu_fallback,
+ }
+}
+
+fn to_api_face_result(result: crate::ml::types::FaceResult) -> RustFaceResult {
+ RustFaceResult {
+ detection: RustDetection {
+ score: result.detection.score as f64,
+ box_xyxy: result
+ .detection
+ .box_xyxy
+ .into_iter()
+ .map(|v| v as f64)
+ .collect(),
+ all_keypoints: result
+ .detection
+ .keypoints
+ .into_iter()
+ .map(|point| point.into_iter().map(|v| v as f64).collect())
+ .collect(),
+ },
+ blur_value: result.blur_value as f64,
+ alignment: RustAlignmentResult {
+ affine_matrix: result
+ .alignment
+ .affine_matrix
+ .into_iter()
+ .map(|row| row.into_iter().map(|v| v as f64).collect())
+ .collect(),
+ center: result
+ .alignment
+ .center
+ .into_iter()
+ .map(|v| v as f64)
+ .collect(),
+ size: result.alignment.size as f64,
+ rotation: result.alignment.rotation as f64,
+ },
+ embedding: result.embedding.into_iter().map(|v| v as f64).collect(),
+ face_id: result.face_id,
+ }
+}
diff --git a/mobile/apps/photos/rust/src/api/mod.rs b/mobile/apps/photos/rust/src/api/mod.rs
index 2d5dea2cd1..1c0956f642 100644
--- a/mobile/apps/photos/rust/src/api/mod.rs
+++ b/mobile/apps/photos/rust/src/api/mod.rs
@@ -1,3 +1,4 @@
pub mod init;
+pub mod ml_indexing_api;
pub mod motion_photo_api;
pub mod usearch_api;
diff --git a/mobile/apps/photos/rust/src/lib.rs b/mobile/apps/photos/rust/src/lib.rs
index cbb071f8bf..997cce5c00 100644
--- a/mobile/apps/photos/rust/src/lib.rs
+++ b/mobile/apps/photos/rust/src/lib.rs
@@ -1,2 +1,3 @@
pub mod api;
mod frb_generated;
+pub mod ml;
diff --git a/mobile/apps/photos/rust/src/ml/clip/image.rs b/mobile/apps/photos/rust/src/ml/clip/image.rs
new file mode 100644
index 0000000000..4f1ffccccc
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/clip/image.rs
@@ -0,0 +1,44 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx, preprocess,
+ runtime::MlRuntime,
+ types::{ClipResult, DecodedImage},
+};
+
+pub fn run_clip_image(runtime: &mut MlRuntime, decoded: &DecodedImage) -> MlResult<ClipResult> {
+ let input = preprocess::preprocess_clip(decoded)?;
+ let (shape, output) = onnx::run_f32(&mut runtime.clip_image, input, vec![1, 3, 256, 256])?;
+
+ let mut embedding = if shape.len() == 2 {
+ if shape[0] != 1 {
+ return Err(MlError::Postprocess(format!(
+ "unexpected CLIP batch size in shape {:?}",
+ shape
+ )));
+ }
+ output
+ } else if shape.len() == 1 {
+ output
+ } else {
+ return Err(MlError::Postprocess(format!(
+ "unsupported CLIP output shape {:?}",
+ shape
+ )));
+ };
+ normalize_embedding(&mut embedding);
+ Ok(ClipResult { embedding })
+}
+
+fn normalize_embedding(embedding: &mut [f32]) {
+ let mut norm = 0.0f32;
+ for value in embedding.iter() {
+ norm += value * value;
+ }
+ let norm = norm.sqrt();
+ if norm <= f32::EPSILON {
+ return;
+ }
+ for value in embedding.iter_mut() {
+ *value /= norm;
+ }
+}
diff --git a/mobile/apps/photos/rust/src/ml/clip/mod.rs b/mobile/apps/photos/rust/src/ml/clip/mod.rs
new file mode 100644
index 0000000000..14995d4228
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/clip/mod.rs
@@ -0,0 +1 @@
+pub mod image;
diff --git a/mobile/apps/photos/rust/src/ml/decode.rs b/mobile/apps/photos/rust/src/ml/decode.rs
new file mode 100644
index 0000000000..955fae8fd3
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/decode.rs
@@ -0,0 +1,109 @@
+use std::{io::Cursor, path::Path};
+
+use exif::{In, Reader as ExifReader, Tag};
+use image::{DynamicImage, RgbImage};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ types::{DecodedImage, Dimensions},
+};
+
+const HEIF_EXTENSIONS: [&str; 2] = ["heic", "heif"];
+
+pub fn decode_image_from_path(image_path: &str) -> MlResult<DecodedImage> {
+ let image_path_obj = Path::new(image_path);
+ let ext = image_path_obj
+ .extension()
+ .and_then(|e| e.to_str())
+ .unwrap_or_default()
+ .to_ascii_lowercase();
+
+ let file_bytes = std::fs::read(image_path)
+ .map_err(|e| MlError::Decode(format!("failed to read image file '{image_path}': {e}")))?;
+ let exif_orientation = read_exif_orientation(&file_bytes);
+
+ let decoded_rgb = if HEIF_EXTENSIONS.contains(&ext.as_str()) {
+ decode_heif_from_path(image_path)?
+ } else {
+ image::load_from_memory(&file_bytes)?.to_rgb8()
+ };
+ let oriented =
+ apply_exif_orientation(DynamicImage::ImageRgb8(decoded_rgb), exif_orientation).to_rgb8();
+
+ Ok(DecodedImage {
+ dimensions: Dimensions {
+ width: oriented.width(),
+ height: oriented.height(),
+ },
+ rgb: oriented.into_raw(),
+ })
+}
+
+fn read_exif_orientation(image_data: &[u8]) -> u32 {
+ let mut reader = Cursor::new(image_data);
+ let exif_reader = ExifReader::new();
+ let exif = exif_reader.read_from_container(&mut reader);
+ exif.ok()
+ .and_then(|data| {
+ data.get_field(Tag::Orientation, In::PRIMARY)
+ .and_then(|field| field.value.get_uint(0))
+ })
+ .unwrap_or(1)
+}
+
+fn apply_exif_orientation(image: DynamicImage, orientation: u32) -> DynamicImage {
+ match orientation {
+ 2 => image.fliph(),
+ 3 => image.rotate180(),
+ 4 => image.flipv(),
+ 5 => image.fliph().rotate270(),
+ 6 => image.rotate90(),
+ 7 => image.fliph().rotate90(),
+ 8 => image.rotate270(),
+ _ => image,
+ }
+}
+
+#[cfg(feature = "heif")]
+fn decode_heif_from_path(image_path: &str) -> MlResult<RgbImage> {
+ use image::{ImageBuffer, Rgb};
+ use libheif_rs::{ColorSpace, HeifContext, LibHeif, RgbChroma};
+
+ let context = HeifContext::read_from_file(image_path)
+ .map_err(|e| MlError::Decode(format!("failed to open HEIF file '{image_path}': {e}")))?;
+ let handle = context
+ .primary_image_handle()
+ .map_err(|e| MlError::Decode(format!("failed to read HEIF primary handle: {e}")))?;
+ let decoder = LibHeif::new();
+ let image = decoder
+ .decode(&handle, ColorSpace::Rgb(RgbChroma::Rgb), None)
+ .map_err(|e| MlError::Decode(format!("failed to decode HEIF image: {e}")))?;
+
+ let width = image.width();
+ let height = image.height();
+ let plane = image
+ .planes()
+ .interleaved
+ .ok_or_else(|| MlError::Decode("HEIF image has no interleaved RGB plane".to_string()))?;
+
+ let row_stride = plane.stride;
+ let row_width = width as usize * 3;
+ let mut rgb = vec![0u8; width as usize * height as usize * 3];
+ for y in 0..height as usize {
+ let src_start = y * row_stride;
+ let src_end = src_start + row_width;
+ let dst_start = y * row_width;
+ rgb[dst_start..(dst_start + row_width)].copy_from_slice(&plane.data[src_start..src_end]);
+ }
+
+ ImageBuffer::<Rgb<u8>, _>::from_raw(width as u32, height as u32, rgb)
+ .ok_or_else(|| MlError::Decode("failed to construct RGB image from HEIF plane".to_string()))
+}
+
+#[cfg(not(feature = "heif"))]
+fn decode_heif_from_path(image_path: &str) -> MlResult<RgbImage> {
+ let _ = image_path;
+ Err(MlError::Decode(
+ "HEIF decoding is unavailable because the `heif` cargo feature is disabled".to_string(),
+ ))
+}
diff --git a/mobile/apps/photos/rust/src/ml/error.rs b/mobile/apps/photos/rust/src/ml/error.rs
new file mode 100644
index 0000000000..86c1511556
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/error.rs
@@ -0,0 +1,31 @@
+use thiserror::Error;
+
+pub type MlResult<T> = Result<T, MlError>;
+
+#[derive(Debug, Error)]
+pub enum MlError {
+ #[error("invalid request: {0}")]
+ InvalidRequest(String),
+ #[error("decode error: {0}")]
+ Decode(String),
+ #[error("preprocess error: {0}")]
+ Preprocess(String),
+ #[error("onnx runtime error: {0}")]
+ Ort(String),
+ #[error("postprocess error: {0}")]
+ Postprocess(String),
+ #[error("runtime error: {0}")]
+ Runtime(String),
+}
+
+impl From<ort::Error> for MlError {
+ fn from(value: ort::Error) -> Self {
+ MlError::Ort(value.to_string())
+ }
+}
+
+impl From<image::ImageError> for MlError {
+ fn from(value: image::ImageError) -> Self {
+ MlError::Decode(value.to_string())
+ }
+}
diff --git a/mobile/apps/photos/rust/src/ml/face/align.rs b/mobile/apps/photos/rust/src/ml/face/align.rs
new file mode 100644
index 0000000000..02e833d2c7
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/face/align.rs
@@ -0,0 +1,384 @@
+use image::{ImageBuffer, Rgb, RgbImage};
+use imageproc::geometric_transformations::{Interpolation, Projection, warp_into};
+use nalgebra::{Matrix2, Matrix3, Vector2};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ types::{AlignmentResult, DecodedImage, FaceDetection, FaceResult, to_face_id},
+};
+
+const FACE_SIZE: u32 = 112;
+const LAPLACIAN_HARD_THRESHOLD: f32 = 10.0;
+const REMOVE_SIDE_COLUMNS: usize = 56;
+
+const MOBILEFACENET_IDEAL_5_LANDMARKS: [[f32; 2]; 5] = [
+ [38.2946 / 112.0, 51.6963 / 112.0],
+ [73.5318 / 112.0, 51.5014 / 112.0],
+ [56.0252 / 112.0, 71.7366 / 112.0],
+ [41.5493 / 112.0, 92.3655 / 112.0],
+ [70.7299 / 112.0, 92.2041 / 112.0],
+];
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+enum FaceDirection {
+ Left,
+ Right,
+ Straight,
+}
+
+#[derive(Clone, Debug)]
+struct FaceDetectionAbsolute {
+ keypoints: [[f32; 2]; 5],
+}
+
+pub fn run_face_alignment(
+ file_id: i64,
+ decoded: &DecodedImage,
+ detections: &[FaceDetection],
+) -> MlResult<(Vec<Vec<f32>>, Vec<FaceResult>)> {
+ let source = rgb_image_from_decoded(decoded)?;
+ let mut aligned_face_inputs = Vec::with_capacity(detections.len());
+ let mut face_results = Vec::with_capacity(detections.len());
+
+ for detection in detections {
+ let absolute_detection = to_absolute_detection(
+ detection,
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ );
+ let alignment = estimate_similarity_transform(&absolute_detection.keypoints)?;
+ let aligned = warp_face_image(&source, &alignment.affine_matrix)?;
+ let normalized = normalize_face_rgb_for_mobilefacenet(&aligned);
+ let blur_value = compute_blur_value(&aligned, face_direction(&absolute_detection));
+ let face_id = to_face_id(file_id, detection.box_xyxy);
+
+ aligned_face_inputs.push(normalized);
+ face_results.push(FaceResult {
+ detection: detection.clone(),
+ blur_value,
+ alignment,
+ embedding: Vec::new(),
+ face_id,
+ });
+ }
+
+ Ok((aligned_face_inputs, face_results))
+}
+
+fn rgb_image_from_decoded(decoded: &DecodedImage) -> MlResult<RgbImage> {
+ ImageBuffer::<Rgb<u8>, _>::from_raw(
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ decoded.rgb.clone(),
+ )
+ .ok_or_else(|| MlError::Preprocess("failed to build RGB source image".to_string()))
+}
+
+fn to_absolute_detection(
+ detection: &FaceDetection,
+ image_width: u32,
+ image_height: u32,
+) -> FaceDetectionAbsolute {
+ let width = image_width as f32;
+ let height = image_height as f32;
+ let mut keypoints = [[0.0f32; 2]; 5];
+ for (i, point) in detection.keypoints.iter().enumerate() {
+ keypoints[i] = [point[0] * width, point[1] * height];
+ }
+
+ FaceDetectionAbsolute { keypoints }
+}
+
+fn estimate_similarity_transform(src_points: &[[f32; 2]; 5]) -> MlResult<AlignmentResult> {
+ let src_mean = mean_2d(src_points);
+ let dst_mean = mean_2d(&MOBILEFACENET_IDEAL_5_LANDMARKS);
+ let n = src_points.len() as f32;
+
+ let mut a = Matrix2::<f32>::zeros();
+ let mut src_var_sum = 0.0f32;
+ for (src, dst) in src_points
+ .iter()
+ .zip(MOBILEFACENET_IDEAL_5_LANDMARKS.iter())
+ {
+ let src_d = Vector2::new(src[0] - src_mean.x, src[1] - src_mean.y);
+ let dst_d = Vector2::new(dst[0] - dst_mean.x, dst[1] - dst_mean.y);
+ a += dst_d * src_d.transpose();
+ src_var_sum += src_d.dot(&src_d);
+ }
+ a /= n;
+ src_var_sum /= n;
+
+ let mut d = Vector2::new(1.0f32, 1.0f32);
+ if a.determinant() < 0.0 {
+ d[1] = -1.0;
+ }
+
+ let svd = a.svd(true, true);
+ let u = svd
+ .u
+ .ok_or_else(|| MlError::Postprocess("SVD failed to produce U".to_string()))?;
+ let v_t = svd
+ .v_t
+ .ok_or_else(|| MlError::Postprocess("SVD failed to produce V^T".to_string()))?;
+ let singular = svd.singular_values;
+
+ let rank = singular.iter().filter(|v| **v > 1e-6).count();
+ if rank == 0 {
+ return Err(MlError::Postprocess(
+ "failed to estimate similarity transform (rank=0)".to_string(),
+ ));
+ }
+
+ let r;
+ if rank == 1 {
+ if u.determinant() * v_t.transpose().determinant() > 0.0 {
+ r = u * v_t;
+ } else {
+ let mut d_local = d;
+ let last = d_local[1];
+ d_local[1] = -1.0;
+ r = u * Matrix2::new(d_local[0], 0.0, 0.0, d_local[1]) * v_t;
+ d[1] = last;
+ }
+ } else {
+ r = u * Matrix2::new(d[0], 0.0, 0.0, d[1]) * v_t;
+ }
+
+ let scale = if src_var_sum <= f32::EPSILON {
+ 1.0
+ } else {
+ (singular[0] * d[0] + singular[1] * d[1]) / src_var_sum
+ };
+
+ let src_mean_v = Vector2::new(src_mean.x, src_mean.y);
+ let dst_mean_v = Vector2::new(dst_mean.x, dst_mean.y);
+ let translation = dst_mean_v - (r * src_mean_v) * scale;
+
+ let mut t = Matrix3::<f32>::identity();
+ let r_scaled = r * scale;
+ t[(0, 0)] = r_scaled[(0, 0)];
+ t[(0, 1)] = r_scaled[(0, 1)];
+ t[(1, 0)] = r_scaled[(1, 0)];
+ t[(1, 1)] = r_scaled[(1, 1)];
+ t[(0, 2)] = translation[0];
+ t[(1, 2)] = translation[1];
+
+ let size = if scale.abs() < f32::EPSILON {
+ 1.0
+ } else {
+ 1.0 / scale
+ };
+ let rotation = r[(1, 0)].atan2(r[(0, 0)]);
+ let mean_translation = (dst_mean_v - Vector2::new(0.5, 0.5)) * size;
+ let center = src_mean_v - mean_translation;
+
+ Ok(AlignmentResult {
+ affine_matrix: [
+ [t[(0, 0)], t[(0, 1)], t[(0, 2)]],
+ [t[(1, 0)], t[(1, 1)], t[(1, 2)]],
+ [t[(2, 0)], t[(2, 1)], t[(2, 2)]],
+ ],
+ center: [center[0], center[1]],
+ size,
+ rotation,
+ })
+}
+
+fn mean_2d(points: &[[f32; 2]]) -> Vector2<f32> {
+ let mut sum = Vector2::new(0.0f32, 0.0f32);
+ for point in points {
+ sum[0] += point[0];
+ sum[1] += point[1];
+ }
+ sum / points.len() as f32
+}
+
+fn warp_face_image(source: &RgbImage, affine_matrix: &[[f32; 3]; 3]) -> MlResult<RgbImage> {
+ let mut transform = [[0.0f32; 3]; 3];
+ for row in 0..3 {
+ for col in 0..3 {
+ let value = affine_matrix[row][col];
+ transform[row][col] = if (value - 1.0).abs() <= f32::EPSILON {
+ 1.0
+ } else {
+ value * FACE_SIZE as f32
+ };
+ }
+ }
+
+ let projection = Projection::from_matrix([
+ transform[0][0],
+ transform[0][1],
+ transform[0][2],
+ transform[1][0],
+ transform[1][1],
+ transform[1][2],
+ transform[2][0],
+ transform[2][1],
+ transform[2][2],
+ ])
+ .ok_or_else(|| MlError::Postprocess("invalid affine matrix projection".to_string()))?;
+
+ let mut output = RgbImage::from_pixel(FACE_SIZE, FACE_SIZE, Rgb([114, 114, 114]));
+ warp_into(
+ source,
+ &projection,
+ Interpolation::Bicubic,
+ Rgb([114, 114, 114]),
+ &mut output,
+ );
+ Ok(output)
+}
+
+fn normalize_face_rgb_for_mobilefacenet(face_image: &RgbImage) -> Vec<f32> {
+ let mut output = Vec::with_capacity((FACE_SIZE * FACE_SIZE * 3) as usize);
+ for y in 0..FACE_SIZE {
+ for x in 0..FACE_SIZE {
+ let px = face_image.get_pixel(x, y).0;
+ output.push(px[0] as f32 / 127.5 - 1.0);
+ output.push(px[1] as f32 / 127.5 - 1.0);
+ output.push(px[2] as f32 / 127.5 - 1.0);
+ }
+ }
+ output
+}
+
+fn face_direction(detection: &FaceDetectionAbsolute) -> FaceDirection {
+ let left_eye = detection.keypoints[0];
+ let right_eye = detection.keypoints[1];
+ let nose = detection.keypoints[2];
+ let left_mouth = detection.keypoints[3];
+ let right_mouth = detection.keypoints[4];
+
+ let eye_distance_x = (right_eye[0] - left_eye[0]).abs();
+ let eye_distance_y = (right_eye[1] - left_eye[1]).abs();
+ let mouth_distance_y = (right_mouth[1] - left_mouth[1]).abs();
+
+ let face_is_upright = left_eye[1].max(right_eye[1]) + 0.5 * eye_distance_y < nose[1]
+ && nose[1] + 0.5 * mouth_distance_y < left_mouth[1].min(right_mouth[1]);
+
+ let nose_sticking_out_left =
+ nose[0] < left_eye[0].min(right_eye[0]) && nose[0] < left_mouth[0].min(right_mouth[0]);
+ let nose_sticking_out_right =
+ nose[0] > left_eye[0].max(right_eye[0]) && nose[0] > left_mouth[0].max(right_mouth[0]);
+
+ let nose_close_to_left_eye = (nose[0] - left_eye[0]).abs() < 0.2 * eye_distance_x;
+ let nose_close_to_right_eye = (nose[0] - right_eye[0]).abs() < 0.2 * eye_distance_x;
+
+ if nose_sticking_out_left || (face_is_upright && nose_close_to_left_eye) {
+ FaceDirection::Left
+ } else if nose_sticking_out_right || (face_is_upright && nose_close_to_right_eye) {
+ FaceDirection::Right
+ } else {
+ FaceDirection::Straight
+ }
+}
+
+fn compute_blur_value(face_image: &RgbImage, direction: FaceDirection) -> f32 {
+ let gray = to_grayscale_matrix(face_image);
+ let lap = apply_laplacian(&gray, direction);
+ let variance = variance_2d(&lap);
+ if variance.is_finite() {
+ variance
+ } else {
+ LAPLACIAN_HARD_THRESHOLD + 1.0
+ }
+}
+
+fn to_grayscale_matrix(face_image: &RgbImage) -> Vec<Vec<i32>> {
+ let w = face_image.width() as usize;
+ let h = face_image.height() as usize;
+ let mut gray = vec![vec![0i32; w]; h];
+ for (y, row) in gray.iter_mut().enumerate().take(h) {
+ for (x, value) in row.iter_mut().enumerate().take(w) {
+ let px = face_image.get_pixel(x as u32, y as u32).0;
+ *value = (0.299 * px[0] as f32 + 0.587 * px[1] as f32 + 0.114 * px[2] as f32)
+ .round()
+ .clamp(0.0, 255.0) as i32;
+ }
+ }
+ gray
+}
+
+fn apply_laplacian(image: &[Vec<i32>], direction: FaceDirection) -> Vec<Vec<i32>> {
+ let padded = pad_image_for_direction(image, direction);
+ let rows = padded.len().saturating_sub(2);
+ let cols = padded
+ .first()
+ .map(|r| r.len().saturating_sub(2))
+ .unwrap_or(0);
+ let kernel = [[0i32, 1, 0], [1, -4, 1], [0, 1, 0]];
+ let mut out = vec![vec![0i32; cols]; rows];
+
+ for i in 0..rows {
+ for j in 0..cols {
+ let mut sum = 0i32;
+ for ki in 0..3 {
+ for kj in 0..3 {
+ sum += padded[i + ki][j + kj] * kernel[ki][kj];
+ }
+ }
+ out[i][j] = sum;
+ }
+ }
+ out
+}
+
+fn pad_image_for_direction(image: &[Vec<i32>], direction: FaceDirection) -> Vec<Vec<i32>> {
+ let rows = image.len();
+ let cols = image.first().map(|r| r.len()).unwrap_or(0);
+ let padded_cols = cols + 2 - REMOVE_SIDE_COLUMNS;
+ let padded_rows = rows + 2;
+ let mut padded = vec![vec![0i32; padded_cols]; padded_rows];
+
+ let start_col = match direction {
+ FaceDirection::Straight => REMOVE_SIDE_COLUMNS / 2,
+ FaceDirection::Left => REMOVE_SIDE_COLUMNS,
+ FaceDirection::Right => 0,
+ };
+ let copy_cols = padded_cols.saturating_sub(2);
+
+ for i in 0..rows {
+ for j in 0..copy_cols {
+ padded[i + 1][j + 1] = image[i][j + start_col];
+ }
+ }
+
+ for j in 1..=copy_cols {
+ padded[0][j] = padded[2][j];
+ padded[rows + 1][j] = padded[rows - 1][j];
+ }
+ for row in padded.iter_mut().take(rows + 2) {
+ row[0] = row[2];
+ row[padded_cols - 1] = row[padded_cols - 3];
+ }
+
+ padded
+}
+
+fn variance_2d(matrix: &[Vec<i32>]) -> f32 {
+ if matrix.is_empty() || matrix[0].is_empty() {
+ return 0.0;
+ }
+
+ let rows = matrix.len();
+ let cols = matrix[0].len();
+ let total = (rows * cols) as f32;
+
+ let mut mean = 0.0f32;
+ for row in matrix {
+ for value in row {
+ mean += *value as f32;
+ }
+ }
+ mean /= total;
+
+ let mut variance = 0.0f32;
+ for row in matrix {
+ for value in row {
+ let diff = *value as f32 - mean;
+ variance += diff * diff;
+ }
+ }
+ variance / total
+}
diff --git a/mobile/apps/photos/rust/src/ml/face/detect.rs b/mobile/apps/photos/rust/src/ml/face/detect.rs
new file mode 100644
index 0000000000..77265691ad
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/face/detect.rs
@@ -0,0 +1,147 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx, preprocess,
+ runtime::MlRuntime,
+ types::{DecodedImage, FaceDetection},
+};
+
+const INPUT_WIDTH: f32 = 640.0;
+const INPUT_HEIGHT: f32 = 640.0;
+const IOU_THRESHOLD: f32 = 0.4;
+const MIN_SCORE_THRESHOLD: f32 = 0.5;
+
+pub fn run_face_detection(
+ runtime: &mut MlRuntime,
+ decoded: &DecodedImage,
+) -> MlResult<Vec<FaceDetection>> {
+ let (input, scaled_width, scaled_height) = preprocess::preprocess_yolo(decoded)?;
+ let (output_shape, output_data) = onnx::run_f32(
+ &mut runtime.face_detection,
+ input,
+ vec![1, 3, INPUT_HEIGHT as i64, INPUT_WIDTH as i64],
+ )?;
+
+ let row_len = 16usize;
+ if output_data.len() < row_len {
+ return Err(MlError::Postprocess(
+ "unexpected face detector output size".to_string(),
+ ));
+ }
+
+ let detection_rows = output_data.len() / row_len;
+ let mut detections = Vec::with_capacity(detection_rows);
+ for i in 0..detection_rows {
+ let start = i * row_len;
+ let row = &output_data[start..(start + row_len)];
+ let score = row[4];
+ if score < MIN_SCORE_THRESHOLD {
+ continue;
+ }
+
+ let x_min_abs = row[0] - row[2] / 2.0;
+ let y_min_abs = row[1] - row[3] / 2.0;
+ let x_max_abs = row[0] + row[2] / 2.0;
+ let y_max_abs = row[1] + row[3] / 2.0;
+
+ let mut box_xyxy = [
+ x_min_abs / INPUT_WIDTH,
+ y_min_abs / INPUT_HEIGHT,
+ x_max_abs / INPUT_WIDTH,
+ y_max_abs / INPUT_HEIGHT,
+ ];
+ let mut keypoints = [
+ [row[5] / INPUT_WIDTH, row[6] / INPUT_HEIGHT],
+ [row[7] / INPUT_WIDTH, row[8] / INPUT_HEIGHT],
+ [row[9] / INPUT_WIDTH, row[10] / INPUT_HEIGHT],
+ [row[11] / INPUT_WIDTH, row[12] / INPUT_HEIGHT],
+ [row[13] / INPUT_WIDTH, row[14] / INPUT_HEIGHT],
+ ];
+
+ correct_for_maintained_aspect_ratio(
+ &mut box_xyxy,
+ &mut keypoints,
+ scaled_width,
+ scaled_height,
+ );
+
+ detections.push(FaceDetection {
+ score,
+ box_xyxy,
+ keypoints,
+ });
+ }
+
+ let _ = output_shape;
+ Ok(naive_non_max_suppression(detections, IOU_THRESHOLD))
+}
+
+fn correct_for_maintained_aspect_ratio(
+ box_xyxy: &mut [f32; 4],
+ keypoints: &mut [[f32; 2]; 5],
+ scaled_width: usize,
+ scaled_height: usize,
+) {
+ if scaled_width == INPUT_WIDTH as usize && scaled_height == INPUT_HEIGHT as usize {
+ return;
+ }
+
+ let scale_x = INPUT_WIDTH / scaled_width as f32;
+ let scale_y = INPUT_HEIGHT / scaled_height as f32;
+
+ box_xyxy[0] = (box_xyxy[0] * scale_x).clamp(0.0, 1.0);
+ box_xyxy[1] = (box_xyxy[1] * scale_y).clamp(0.0, 1.0);
+ box_xyxy[2] = (box_xyxy[2] * scale_x).clamp(0.0, 1.0);
+ box_xyxy[3] = (box_xyxy[3] * scale_y).clamp(0.0, 1.0);
+
+ for point in keypoints.iter_mut() {
+ point[0] = (point[0] * scale_x).clamp(0.0, 1.0);
+ point[1] = (point[1] * scale_y).clamp(0.0, 1.0);
+ }
+}
+
+fn naive_non_max_suppression(
+ mut detections: Vec<FaceDetection>,
+ iou_threshold: f32,
+) -> Vec<FaceDetection> {
+ detections.sort_by(|a, b| b.score.total_cmp(&a.score));
+
+ let mut i = 0usize;
+ while i + 1 < detections.len() {
+ let mut j = i + 1;
+ while j < detections.len() {
+ let iou = calculate_iou(&detections[i], &detections[j]);
+ if iou >= iou_threshold {
+ detections.remove(j);
+ } else {
+ j += 1;
+ }
+ }
+ i += 1;
+ }
+ detections
+}
+
+fn calculate_iou(a: &FaceDetection, b: &FaceDetection) -> f32 {
+ let area_a =
+ (a.box_xyxy[2] - a.box_xyxy[0]).max(0.0) * (a.box_xyxy[3] - a.box_xyxy[1]).max(0.0);
+ let area_b =
+ (b.box_xyxy[2] - b.box_xyxy[0]).max(0.0) * (b.box_xyxy[3] - b.box_xyxy[1]).max(0.0);
+
+ let intersection_min_x = a.box_xyxy[0].max(b.box_xyxy[0]);
+ let intersection_min_y = a.box_xyxy[1].max(b.box_xyxy[1]);
+ let intersection_max_x = a.box_xyxy[2].min(b.box_xyxy[2]);
+ let intersection_max_y = a.box_xyxy[3].min(b.box_xyxy[3]);
+
+ let intersection_width = intersection_max_x - intersection_min_x;
+ let intersection_height = intersection_max_y - intersection_min_y;
+ if intersection_width < 0.0 || intersection_height < 0.0 {
+ return 0.0;
+ }
+
+ let intersection_area = intersection_width * intersection_height;
+ let union_area = area_a + area_b - intersection_area;
+ if union_area <= 0.0 {
+ return 0.0;
+ }
+ intersection_area / union_area
+}
diff --git a/mobile/apps/photos/rust/src/ml/face/embed.rs b/mobile/apps/photos/rust/src/ml/face/embed.rs
new file mode 100644
index 0000000000..b05cd90c33
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/face/embed.rs
@@ -0,0 +1,94 @@
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx,
+ runtime::MlRuntime,
+ types::FaceResult,
+};
+
+const FACE_INPUT_WIDTH: i64 = 112;
+const FACE_INPUT_HEIGHT: i64 = 112;
+const FACE_INPUT_CHANNELS: i64 = 3;
+
+pub fn run_face_embedding(
+ runtime: &mut MlRuntime,
+ aligned_faces: &[Vec<f32>],
+ face_results: &mut [FaceResult],
+) -> MlResult<()> {
+ if aligned_faces.is_empty() {
+ return Ok(());
+ }
+ if aligned_faces.len() != face_results.len() {
+ return Err(MlError::Postprocess(format!(
+ "aligned faces count ({}) does not match face result count ({})",
+ aligned_faces.len(),
+ face_results.len()
+ )));
+ }
+
+ let per_face_len = (FACE_INPUT_WIDTH * FACE_INPUT_HEIGHT * FACE_INPUT_CHANNELS) as usize;
+ let mut input = Vec::with_capacity(per_face_len * aligned_faces.len());
+ for aligned in aligned_faces {
+ if aligned.len() != per_face_len {
+ return Err(MlError::Preprocess(format!(
+ "aligned face tensor length {} does not match expected {}",
+ aligned.len(),
+ per_face_len
+ )));
+ }
+ input.extend_from_slice(aligned);
+ }
+
+ let (shape, output) = onnx::run_f32(
+ &mut runtime.face_embedding,
+ input,
+ vec![
+ aligned_faces.len() as i64,
+ FACE_INPUT_HEIGHT,
+ FACE_INPUT_WIDTH,
+ FACE_INPUT_CHANNELS,
+ ],
+ )?;
+ if shape.is_empty() {
+ return Err(MlError::Postprocess(
+ "face embedding output shape is empty".to_string(),
+ ));
+ }
+ let batch = shape[0] as usize;
+ if batch != face_results.len() {
+ return Err(MlError::Postprocess(format!(
+ "face embedding batch mismatch: output={batch}, expected={}",
+ face_results.len()
+ )));
+ }
+ let embedding_size = output.len() / batch;
+ if embedding_size == 0 || output.len() != batch * embedding_size {
+ return Err(MlError::Postprocess(format!(
+ "invalid face embedding tensor shape {:?} for data length {}",
+ shape,
+ output.len()
+ )));
+ }
+
+ for (face_index, face_result) in face_results.iter_mut().enumerate() {
+ let start = face_index * embedding_size;
+ let mut embedding = output[start..(start + embedding_size)].to_vec();
+ normalize_embedding(&mut embedding);
+ face_result.embedding = embedding;
+ }
+
+ Ok(())
+}
+
+fn normalize_embedding(embedding: &mut [f32]) {
+ let mut norm = 0.0f32;
+ for value in embedding.iter() {
+ norm += value * value;
+ }
+ let norm = norm.sqrt();
+ if norm <= f32::EPSILON {
+ return;
+ }
+ for value in embedding.iter_mut() {
+ *value /= norm;
+ }
+}
diff --git a/mobile/apps/photos/rust/src/ml/face/mod.rs b/mobile/apps/photos/rust/src/ml/face/mod.rs
new file mode 100644
index 0000000000..470bf02d7f
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/face/mod.rs
@@ -0,0 +1,3 @@
+pub mod align;
+pub mod detect;
+pub mod embed;
diff --git a/mobile/apps/photos/rust/src/ml/mod.rs b/mobile/apps/photos/rust/src/ml/mod.rs
new file mode 100644
index 0000000000..b28627516d
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/mod.rs
@@ -0,0 +1,8 @@
+pub mod clip;
+pub mod decode;
+pub mod error;
+pub mod face;
+pub mod onnx;
+pub mod preprocess;
+pub mod runtime;
+pub mod types;
diff --git a/mobile/apps/photos/rust/src/ml/onnx.rs b/mobile/apps/photos/rust/src/ml/onnx.rs
new file mode 100644
index 0000000000..4f2d4f1bf0
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/onnx.rs
@@ -0,0 +1,55 @@
+use ort::{
+ ep,
+ session::{Session, builder::GraphOptimizationLevel},
+ value::Tensor,
+};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ runtime::ExecutionProviderPolicy,
+};
+
+pub fn build_session(model_path: &str, policy: &ExecutionProviderPolicy) -> MlResult<Session> {
+ let mut builder = Session::builder()?
+ .with_optimization_level(GraphOptimizationLevel::All)?
+ .with_intra_threads(1)?
+ .with_inter_threads(1)?;
+
+ let mut providers = Vec::new();
+
+ #[cfg(target_vendor = "apple")]
+ if policy.prefer_coreml {
+ providers.push(ep::CoreML::default().build());
+ }
+
+ #[cfg(target_os = "android")]
+ if policy.prefer_nnapi {
+ providers.push(ep::NNAPI::default().build());
+ }
+
+ if policy.allow_cpu_fallback {
+ providers.push(ep::CPU::default().build());
+ }
+
+ if !providers.is_empty() {
+ builder = builder.with_execution_providers(providers)?;
+ }
+
+ let session = builder.commit_from_file(model_path)?;
+ Ok(session)
+}
+
+pub fn run_f32(
+ session: &mut Session,
+ input: Vec<f32>,
+ input_shape: Vec<i64>,
+) -> MlResult<(Vec<i64>, Vec<f32>)> {
+ let input_tensor = Tensor::<f32>::from_array((input_shape, input))?;
+ let outputs = session.run(ort::inputs![input_tensor])?;
+ if outputs.len() == 0 {
+ return Err(MlError::Ort("missing first output tensor".to_string()));
+ }
+ let output = &outputs[0];
+ let (shape, data) = output.try_extract_tensor::<f32>()?;
+ Ok((shape.to_vec(), data.to_vec()))
+}
diff --git a/mobile/apps/photos/rust/src/ml/preprocess.rs b/mobile/apps/photos/rust/src/ml/preprocess.rs
new file mode 100644
index 0000000000..0608b603fb
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/preprocess.rs
@@ -0,0 +1,146 @@
+use fast_image_resize::{
+ FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer, images::Image as FirImage,
+};
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ types::DecodedImage,
+};
+
+const YOLO_INPUT_WIDTH: usize = 640;
+const YOLO_INPUT_HEIGHT: usize = 640;
+const CLIP_INPUT_WIDTH: usize = 256;
+const CLIP_INPUT_HEIGHT: usize = 256;
+const PAD_VALUE: f32 = 114.0;
+
+pub fn preprocess_yolo(decoded: &DecodedImage) -> MlResult<(Vec<f32>, usize, usize)> {
+ if decoded.dimensions.width == 0 || decoded.dimensions.height == 0 {
+ return Err(MlError::Preprocess(
+ "image dimensions cannot be zero".to_string(),
+ ));
+ }
+
+ let src_w = decoded.dimensions.width as f32;
+ let src_h = decoded.dimensions.height as f32;
+ let scale = (YOLO_INPUT_WIDTH as f32 / src_w).min(YOLO_INPUT_HEIGHT as f32 / src_h);
+ let scaled_width = (src_w * scale).round().clamp(0.0, YOLO_INPUT_WIDTH as f32) as usize;
+ let scaled_height = (src_h * scale).round().clamp(0.0, YOLO_INPUT_HEIGHT as f32) as usize;
+
+ let mut output = vec![0f32; 3 * YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT];
+ let green_offset = YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT;
+ let blue_offset = 2 * YOLO_INPUT_WIDTH * YOLO_INPUT_HEIGHT;
+
+ for y in 0..YOLO_INPUT_HEIGHT {
+ for x in 0..YOLO_INPUT_WIDTH {
+ let idx = y * YOLO_INPUT_WIDTH + x;
+ let rgb = if x >= scaled_width || y >= scaled_height {
+ [PAD_VALUE, PAD_VALUE, PAD_VALUE]
+ } else {
+ sample_bilinear_rgb(decoded, x as f32 / scale, y as f32 / scale)
+ };
+ output[idx] = rgb[0] / 255.0;
+ output[idx + green_offset] = rgb[1] / 255.0;
+ output[idx + blue_offset] = rgb[2] / 255.0;
+ }
+ }
+
+ Ok((output, scaled_width, scaled_height))
+}
+
+pub fn preprocess_clip(decoded: &DecodedImage) -> MlResult<Vec<f32>> {
+ if decoded.dimensions.width == 0 || decoded.dimensions.height == 0 {
+ return Err(MlError::Preprocess(
+ "image dimensions cannot be zero".to_string(),
+ ));
+ }
+
+ let src_w = decoded.dimensions.width as f32;
+ let src_h = decoded.dimensions.height as f32;
+ let scale = (CLIP_INPUT_WIDTH as f32 / src_w).max(CLIP_INPUT_HEIGHT as f32 / src_h);
+ let scaled_width = (src_w * scale).round().max(CLIP_INPUT_WIDTH as f32) as u32;
+ let scaled_height = (src_h * scale).round().max(CLIP_INPUT_HEIGHT as f32) as u32;
+
+ let src_image = FirImage::from_vec_u8(
+ decoded.dimensions.width,
+ decoded.dimensions.height,
+ decoded.rgb.clone(),
+ PixelType::U8x3,
+ )
+ .map_err(|e| MlError::Preprocess(format!("failed to create FIR source image: {e}")))?;
+
+ let mut resized_image = FirImage::new(scaled_width, scaled_height, PixelType::U8x3);
+ let mut resizer = Resizer::new();
+ let options = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear));
+ resizer
+ .resize(&src_image, &mut resized_image, Some(&options))
+ .map_err(|e| MlError::Preprocess(format!("failed to resize CLIP image input: {e}")))?;
+
+ let resized = resized_image.buffer();
+ let start_x = ((scaled_width as i32 - CLIP_INPUT_WIDTH as i32) / 2).max(0) as usize;
+ let start_y = ((scaled_height as i32 - CLIP_INPUT_HEIGHT as i32) / 2).max(0) as usize;
+ let scaled_width_usize = scaled_width as usize;
+
+ let mut output = vec![0f32; 3 * CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT];
+ let green_offset = CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT;
+ let blue_offset = 2 * CLIP_INPUT_WIDTH * CLIP_INPUT_HEIGHT;
+
+ for y in 0..CLIP_INPUT_HEIGHT {
+ for x in 0..CLIP_INPUT_WIDTH {
+ let src_x = start_x + x;
+ let src_y = start_y + y;
+ let src_idx = (src_y * scaled_width_usize + src_x) * 3;
+ let dst_idx = y * CLIP_INPUT_WIDTH + x;
+ output[dst_idx] = resized[src_idx] as f32 / 255.0;
+ output[dst_idx + green_offset] = resized[src_idx + 1] as f32 / 255.0;
+ output[dst_idx + blue_offset] = resized[src_idx + 2] as f32 / 255.0;
+ }
+ }
+
+ Ok(output)
+}
+
+pub fn sample_bilinear_rgb(decoded: &DecodedImage, fx: f32, fy: f32) -> [f32; 3] {
+ let max_x = (decoded.dimensions.width.saturating_sub(1)) as f32;
+ let max_y = (decoded.dimensions.height.saturating_sub(1)) as f32;
+ let fx = fx.clamp(0.0, max_x);
+ let fy = fy.clamp(0.0, max_y);
+
+ let x0 = fx.floor() as i32;
+ let x1 = fx.ceil() as i32;
+ let y0 = fy.floor() as i32;
+ let y1 = fy.ceil() as i32;
+ let dx = fx - x0 as f32;
+ let dy = fy - y0 as f32;
+ let dx1 = 1.0 - dx;
+ let dy1 = 1.0 - dy;
+
+ let p1 = read_rgb(decoded, x0, y0);
+ let p2 = read_rgb(decoded, x1, y0);
+ let p3 = read_rgb(decoded, x0, y1);
+ let p4 = read_rgb(decoded, x1, y1);
+
+ let blend = |v1: f32, v2: f32, v3: f32, v4: f32| -> f32 {
+ v1 * dx1 * dy1 + v2 * dx * dy1 + v3 * dx1 * dy + v4 * dx * dy
+ };
+
+ [
+ blend(p1[0], p2[0], p3[0], p4[0]),
+ blend(p1[1], p2[1], p3[1], p4[1]),
+ blend(p1[2], p2[2], p3[2], p4[2]),
+ ]
+}
+
+pub fn read_rgb(decoded: &DecodedImage, x: i32, y: i32) -> [f32; 3] {
+ let width = decoded.dimensions.width as i32;
+ let height = decoded.dimensions.height as i32;
+ if x < 0 || y < 0 || x >= width || y >= height {
+ return [PAD_VALUE, PAD_VALUE, PAD_VALUE];
+ }
+
+ let idx = ((y as usize * decoded.dimensions.width as usize) + x as usize) * 3;
+ [
+ decoded.rgb[idx] as f32,
+ decoded.rgb[idx + 1] as f32,
+ decoded.rgb[idx + 2] as f32,
+ ]
+}
diff --git a/mobile/apps/photos/rust/src/ml/runtime.rs b/mobile/apps/photos/rust/src/ml/runtime.rs
new file mode 100644
index 0000000000..65762d051a
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/runtime.rs
@@ -0,0 +1,107 @@
+use std::sync::Mutex;
+
+use once_cell::sync::Lazy;
+use ort::session::Session;
+
+use crate::ml::{
+ error::{MlError, MlResult},
+ onnx,
+};
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ExecutionProviderPolicy {
+ pub prefer_coreml: bool,
+ pub prefer_nnapi: bool,
+ pub allow_cpu_fallback: bool,
+}
+
+impl Default for ExecutionProviderPolicy {
+ fn default() -> Self {
+ Self {
+ prefer_coreml: true,
+ prefer_nnapi: true,
+ allow_cpu_fallback: true,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ModelPaths {
+ pub face_detection: String,
+ pub face_embedding: String,
+ pub clip_image: String,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct MlRuntimeConfig {
+ pub model_paths: ModelPaths,
+ pub provider_policy: ExecutionProviderPolicy,
+}
+
+#[derive(Debug)]
+pub struct MlRuntime {
+ pub face_detection: Session,
+ pub face_embedding: Session,
+ pub clip_image: Session,
+}
+
+#[derive(Debug)]
+struct RuntimeState {
+ config: MlRuntimeConfig,
+ runtime: MlRuntime,
+}
+
+static GLOBAL_RUNTIME: Lazy<Mutex<Option<RuntimeState>>> = Lazy::new(|| Mutex::new(None));
+
+fn create_runtime(config: &MlRuntimeConfig) -> MlResult<MlRuntime> {
+ let face_detection =
+ onnx::build_session(&config.model_paths.face_detection, &config.provider_policy)?;
+ let face_embedding =
+ onnx::build_session(&config.model_paths.face_embedding, &config.provider_policy)?;
+ let clip_image = onnx::build_session(&config.model_paths.clip_image, &config.provider_policy)?;
+ Ok(MlRuntime {
+ face_detection,
+ face_embedding,
+ clip_image,
+ })
+}
+
+fn lock_runtime() -> MlResult<std::sync::MutexGuard<'static, Option<RuntimeState>>> {
+ GLOBAL_RUNTIME
+ .lock()
+ .map_err(|e| MlError::Runtime(format!("runtime mutex poisoned: {e}")))
+}
+
+pub fn ensure_runtime(config: &MlRuntimeConfig) -> MlResult<()> {
+ let mut guard = lock_runtime()?;
+ let should_rebuild = match guard.as_ref() {
+ Some(existing) => existing.config != *config,
+ None => true,
+ };
+ if should_rebuild {
+ let runtime = create_runtime(config)?;
+ *guard = Some(RuntimeState {
+ config: config.clone(),
+ runtime,
+ });
+ }
+ Ok(())
+}
+
+pub fn with_runtime_mut<F, R>(config: &MlRuntimeConfig, func: F) -> MlResult<R>
+where
+ F: FnOnce(&mut MlRuntime) -> MlResult<R>,
+{
+ ensure_runtime(config)?;
+ let mut guard = lock_runtime()?;
+ let state = guard
+ .as_mut()
+ .ok_or_else(|| MlError::Runtime("runtime is not initialized".to_string()))?;
+ func(&mut state.runtime)
+}
+
+pub fn release_runtime() -> MlResult<()> {
+ let mut guard = lock_runtime()?;
+ *guard = None;
+ Ok(())
+}
diff --git a/mobile/apps/photos/rust/src/ml/types.rs b/mobile/apps/photos/rust/src/ml/types.rs
new file mode 100644
index 0000000000..bcca365e57
--- /dev/null
+++ b/mobile/apps/photos/rust/src/ml/types.rs
@@ -0,0 +1,57 @@
+#[derive(Clone, Debug, PartialEq)]
+pub struct Dimensions {
+ pub width: u32,
+ pub height: u32,
+}
+
+#[derive(Clone, Debug)]
+pub struct DecodedImage {
+ pub dimensions: Dimensions,
+ pub rgb: Vec<u8>,
+}
+
+#[derive(Clone, Debug)]
+pub struct FaceDetection {
+ pub score: f32,
+ pub box_xyxy: [f32; 4],
+ pub keypoints: [[f32; 2]; 5],
+}
+
+#[derive(Clone, Debug)]
+pub struct AlignmentResult {
+ pub affine_matrix: [[f32; 3]; 3],
+ pub center: [f32; 2],
+ pub size: f32,
+ pub rotation: f32,
+}
+
+#[derive(Clone, Debug)]
+pub struct FaceResult {
+ pub detection: FaceDetection,
+ pub blur_value: f32,
+ pub alignment: AlignmentResult,
+ pub embedding: Vec<f32>,
+ pub face_id: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct ClipResult {
+ pub embedding: Vec<f32>,
+}
+
+pub fn to_face_id(file_id: i64, box_xyxy: [f32; 4]) -> String {
+ fn to_face_segment(v: f32) -> String {
+ let clamped = v.clamp(0.0, 0.999_999);
+ let fixed = format!("{clamped:.5}");
+ fixed
+ .split_once('.')
+ .map(|(_, right)| right.to_string())
+ .unwrap_or_else(|| "00000".to_string())
+ }
+
+ let x_min = to_face_segment(box_xyxy[0]);
+ let y_min = to_face_segment(box_xyxy[1]);
+ let x_max = to_face_segment(box_xyxy[2]);
+ let y_max = to_face_segment(box_xyxy[3]);
+ format!("{file_id}_{x_min}_{y_min}_{x_max}_{y_max}")
+}