react-native-face-match-sdk 0.0.0-stage → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/FaceMatch.podspec +55 -0
- package/LICENSE +21 -0
- package/README.md +190 -2
- package/android/build.gradle +59 -0
- package/android/consumer-rules.pro +5 -0
- package/android/src/main/AndroidManifest.xml +11 -0
- package/android/src/main/java/com/facematch/sdk/AntiSpoofHelper.kt +216 -0
- package/android/src/main/java/com/facematch/sdk/BitmapUtils.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/CameraFrameView.kt +75 -0
- package/android/src/main/java/com/facematch/sdk/FaceAlignmentHelper.kt +156 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraView.kt +628 -0
- package/android/src/main/java/com/facematch/sdk/FaceCameraViewManager.kt +79 -0
- package/android/src/main/java/com/facematch/sdk/FaceCandidateFilter.kt +65 -0
- package/android/src/main/java/com/facematch/sdk/FaceDetectionHelper.kt +225 -0
- package/android/src/main/java/com/facematch/sdk/FaceEmbeddingHelper.kt +242 -0
- package/android/src/main/java/com/facematch/sdk/FaceFrameAnalyzer.kt +228 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchModule.kt +249 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchPackage.kt +14 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatchRuntime.kt +138 -0
- package/android/src/main/java/com/facematch/sdk/FaceMatcherHelper.kt +92 -0
- package/android/src/main/java/com/facematch/sdk/FaceOverlayView.kt +236 -0
- package/android/src/main/java/com/facematch/sdk/LivenessDetector.kt +483 -0
- package/android/src/main/java/com/facematch/sdk/LivenessPrompts.kt +137 -0
- package/android/src/main/java/com/facematch/sdk/LivenessVoice.kt +270 -0
- package/android/src/main/java/com/facematch/sdk/PrivateCaptureStore.kt +50 -0
- package/ios/Sources/AntiSpoofHelper.swift +239 -0
- package/ios/Sources/FaceAlignmentHelper.swift +169 -0
- package/ios/Sources/FaceCameraView.swift +1161 -0
- package/ios/Sources/FaceCameraViewManager.m +28 -0
- package/ios/Sources/FaceCameraViewManager.swift +57 -0
- package/ios/Sources/FaceCandidateFilter.swift +62 -0
- package/ios/Sources/FaceDetectionHelper.swift +283 -0
- package/ios/Sources/FaceEmbeddingHelper.swift +188 -0
- package/ios/Sources/FaceFrameAnalyzer.swift +179 -0
- package/ios/Sources/FaceFrameResult.swift +96 -0
- package/ios/Sources/FaceMatchBundle.swift +26 -0
- package/ios/Sources/FaceMatchEngine.swift +136 -0
- package/ios/Sources/FaceMatchError.swift +40 -0
- package/ios/Sources/FaceMatchModule.m +55 -0
- package/ios/Sources/FaceMatchModule.swift +288 -0
- package/ios/Sources/FaceMatcherHelper.swift +107 -0
- package/ios/Sources/FaceOverlayView.swift +285 -0
- package/ios/Sources/ImageUtils.swift +322 -0
- package/ios/Sources/LivenessDetector.swift +505 -0
- package/ios/Sources/LivenessPrompts.swift +121 -0
- package/ios/Sources/LivenessVoice.swift +229 -0
- package/ios/Sources/OnnxRuntime/ORTShim.h +91 -0
- package/ios/Sources/OnnxRuntime/ORTShim.mm +260 -0
- package/ios/Sources/PrivateCaptureStore.swift +71 -0
- package/ios/Sources/VisionFaceFallback.swift +95 -0
- package/ios/onnxruntime-c.podspec +47 -0
- package/models/anti_spoof_minifasnet_v2.onnx +0 -0
- package/models/w600k_mbf.onnx +0 -0
- package/package.json +47 -4
- package/react-native.config.js +16 -0
- package/src/FaceCameraView.tsx +75 -0
- package/src/FaceMatch.ts +66 -0
- package/src/index.ts +4 -0
- package/src/types.ts +87 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import AVFoundation
|
|
2
|
+
import Foundation
|
|
3
|
+
|
|
4
|
+
/// Port of `LivenessVoice.kt`.
|
|
5
|
+
///
|
|
6
|
+
/// Speaks liveness prompts through `AVSpeechSynthesizer` in the caller's chosen
|
|
7
|
+
/// language (English or Hindi). A prompt is spoken once when it first appears;
|
|
8
|
+
/// repeats of the same prompt are ignored.
|
|
9
|
+
///
|
|
10
|
+
/// Prompts are never dropped, only deferred: one raised within `minGap` of the
|
|
11
|
+
/// previous one used to be discarded for good — the camera only re-emits a
|
|
12
|
+
/// prompt when the step changes, so that step stayed silent. The newest prompt
|
|
13
|
+
/// is now held as pending and spoken once the gap has elapsed, so the latest
|
|
14
|
+
/// instruction always wins.
|
|
15
|
+
///
|
|
16
|
+
/// Main thread only (the liveness frame callback already runs there).
|
|
17
|
+
final class LivenessVoice {
|
|
18
|
+
private static let minGap: TimeInterval = 1.4
|
|
19
|
+
/// After `stopSpeaking(at: .immediate)` the synthesizer needs a beat before
|
|
20
|
+
/// it accepts the next utterance; speaking straight away intermittently
|
|
21
|
+
/// discarded the new prompt without a sound.
|
|
22
|
+
private static let restartDelay: TimeInterval = 0.12
|
|
23
|
+
|
|
24
|
+
/// Audio-session work never runs on the main thread: activating a session
|
|
25
|
+
/// that ducks other audio talks to mediaserverd and routinely blocks the
|
|
26
|
+
/// caller for 100ms or more. `speak` is driven from the liveness frame
|
|
27
|
+
/// callback on the main thread, so doing it there stalls UIKit mid-frame
|
|
28
|
+
/// and React Native commits a torn, half-rendered layout.
|
|
29
|
+
private static let audioQueue = DispatchQueue(label: "com.facematch.sdk.voice")
|
|
30
|
+
/// Application-lifetime, like the Android engine: the speech service and
|
|
31
|
+
/// voice data load on the first utterance, which delayed the opening
|
|
32
|
+
/// instruction of every session by up to a second. Shared and warmed once.
|
|
33
|
+
private static let synthesizer = AVSpeechSynthesizer()
|
|
34
|
+
private static var audioSessionConfigured = false
|
|
35
|
+
private static var warmedUp = false
|
|
36
|
+
/// Voice lookups hit the speech asset store; resolve each language once.
|
|
37
|
+
private static var voiceCache: [String: AVSpeechSynthesisVoice] = [:]
|
|
38
|
+
private static let voiceCacheLock = NSLock()
|
|
39
|
+
/// Bumped per enqueued utterance so a delayed start never plays over a newer one.
|
|
40
|
+
private static var utteranceToken = 0
|
|
41
|
+
|
|
42
|
+
private var language = "none"
|
|
43
|
+
private var gender = "female"
|
|
44
|
+
private var lastKey: String?
|
|
45
|
+
private var lastSpokeAt: TimeInterval = 0
|
|
46
|
+
private var pending: (key: String, text: String)?
|
|
47
|
+
private var flushWork: DispatchWorkItem?
|
|
48
|
+
|
|
49
|
+
/// Resolve the voice assets ahead of time. Touches no audio session, so it
|
|
50
|
+
/// is safe at module load without ducking whatever the user is playing.
|
|
51
|
+
static func prewarmVoices() {
|
|
52
|
+
Self.audioQueue.async {
|
|
53
|
+
for language in ["en", "hi"] {
|
|
54
|
+
for gender in ["female", "male"] {
|
|
55
|
+
_ = Self.cachedVoice(for: language, gender: gender)
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Configure the session and spin the synthesizer up before the first
|
|
62
|
+
/// prompt. Called when a camera view selects a language.
|
|
63
|
+
private static func warmUp(language: String, gender: String) {
|
|
64
|
+
Self.audioQueue.async {
|
|
65
|
+
Self.configureAudioSessionLocked()
|
|
66
|
+
let voice = Self.cachedVoice(for: language, gender: gender)
|
|
67
|
+
guard !Self.warmedUp else { return }
|
|
68
|
+
Self.warmedUp = true
|
|
69
|
+
// A silent utterance forces the speech service to load now rather
|
|
70
|
+
// than on the first real prompt.
|
|
71
|
+
let warm = AVSpeechUtterance(string: " ")
|
|
72
|
+
warm.volume = 0
|
|
73
|
+
warm.voice = voice
|
|
74
|
+
Self.synthesizer.speak(warm)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// "female" (default) or "male" — preferred India voice; falls back to any
|
|
79
|
+
/// voice for the language when that gender is not installed.
|
|
80
|
+
func setGender(_ value: String) {
|
|
81
|
+
gender = value.lowercased() == "male" ? "male" : "female"
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
func setLanguage(_ value: String) {
|
|
85
|
+
let normalized = value.lowercased()
|
|
86
|
+
if normalized == language { return }
|
|
87
|
+
language = normalized
|
|
88
|
+
lastKey = nil
|
|
89
|
+
if normalized == "none" {
|
|
90
|
+
stop()
|
|
91
|
+
} else {
|
|
92
|
+
// Warm the session and voice up now, well before the first prompt.
|
|
93
|
+
Self.warmUp(language: normalized, gender: gender)
|
|
94
|
+
flush()
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Announce a prompt. `key` is the `LivenessPrompt` raw value; `text` is
|
|
99
|
+
/// already localized.
|
|
100
|
+
func speak(key: String, text: String) {
|
|
101
|
+
guard language != "none", !text.trimmingCharacters(in: .whitespaces).isEmpty else { return }
|
|
102
|
+
if key == lastKey && pending == nil { return }
|
|
103
|
+
pending = (key, text)
|
|
104
|
+
flush()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/// Forget the last prompt so the next call speaks even if the key is unchanged.
|
|
108
|
+
func resetSpokenHistory() {
|
|
109
|
+
lastKey = nil
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
func stop() {
|
|
113
|
+
clearPending()
|
|
114
|
+
Self.audioQueue.async {
|
|
115
|
+
Self.utteranceToken += 1
|
|
116
|
+
Self.synthesizer.stopSpeaking(at: .immediate)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
func shutdown() {
|
|
121
|
+
// The synthesizer is shared; only this view's pending prompt is dropped.
|
|
122
|
+
stop()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private func flush() {
|
|
126
|
+
flushWork?.cancel()
|
|
127
|
+
flushWork = nil
|
|
128
|
+
guard let next = pending else { return }
|
|
129
|
+
guard language != "none" else {
|
|
130
|
+
clearPending()
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
let wait = Self.minGap - (Date.timeIntervalSinceReferenceDate - lastSpokeAt)
|
|
134
|
+
if wait > 0 {
|
|
135
|
+
let work = DispatchWorkItem { [weak self] in self?.flush() }
|
|
136
|
+
flushWork = work
|
|
137
|
+
DispatchQueue.main.asyncAfter(deadline: .now() + wait, execute: work)
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
pending = nil
|
|
141
|
+
if next.key == lastKey { return }
|
|
142
|
+
lastKey = next.key
|
|
143
|
+
lastSpokeAt = Date.timeIntervalSinceReferenceDate
|
|
144
|
+
enqueue(next.text, language: language, gender: gender)
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
private func clearPending() {
|
|
148
|
+
flushWork?.cancel()
|
|
149
|
+
flushWork = nil
|
|
150
|
+
pending = nil
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private func enqueue(_ text: String, language: String, gender: String) {
|
|
154
|
+
// Enqueue off the main thread too — stopSpeaking/speak reach the speech
|
|
155
|
+
// daemon and are not guaranteed to return immediately.
|
|
156
|
+
Self.audioQueue.async {
|
|
157
|
+
Self.configureAudioSessionLocked()
|
|
158
|
+
let utterance = AVSpeechUtterance(string: text)
|
|
159
|
+
utterance.voice = Self.cachedVoice(for: language, gender: gender)
|
|
160
|
+
// Slightly under the default: clearer for step-by-step guidance.
|
|
161
|
+
utterance.rate = AVSpeechUtteranceDefaultSpeechRate * 0.95
|
|
162
|
+
|
|
163
|
+
Self.utteranceToken += 1
|
|
164
|
+
let token = Self.utteranceToken
|
|
165
|
+
let synthesizer = Self.synthesizer
|
|
166
|
+
// QUEUE_FLUSH equivalent: the newest instruction always wins.
|
|
167
|
+
if synthesizer.isSpeaking || synthesizer.isPaused {
|
|
168
|
+
synthesizer.stopSpeaking(at: .immediate)
|
|
169
|
+
Self.audioQueue.asyncAfter(deadline: .now() + Self.restartDelay) {
|
|
170
|
+
guard token == Self.utteranceToken else { return }
|
|
171
|
+
synthesizer.speak(utterance)
|
|
172
|
+
}
|
|
173
|
+
} else {
|
|
174
|
+
synthesizer.speak(utterance)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/// The best installed India voice for `language`: `AVSpeechSynthesisVoice(language:)`
|
|
180
|
+
/// returns whichever voice iOS defaults to, which is often the low-quality
|
|
181
|
+
/// compact one and ignores gender. Ranked by gender match, then quality
|
|
182
|
+
/// (premium > enhanced > default). Falls back to any English voice for `en`.
|
|
183
|
+
private static func cachedVoice(for language: String, gender: String) -> AVSpeechSynthesisVoice? {
|
|
184
|
+
voiceCacheLock.lock()
|
|
185
|
+
defer { voiceCacheLock.unlock() }
|
|
186
|
+
let cacheKey = "\(language)-\(gender)"
|
|
187
|
+
if let cached = voiceCache[cacheKey] { return cached }
|
|
188
|
+
|
|
189
|
+
let code: String
|
|
190
|
+
switch language {
|
|
191
|
+
case "hi": code = "hi-IN"
|
|
192
|
+
case "en": code = "en-IN"
|
|
193
|
+
default: return nil
|
|
194
|
+
}
|
|
195
|
+
let wanted: AVSpeechSynthesisVoiceGender = gender == "male" ? .male : .female
|
|
196
|
+
let candidates = AVSpeechSynthesisVoice.speechVoices().filter {
|
|
197
|
+
$0.language.caseInsensitiveCompare(code) == .orderedSame
|
|
198
|
+
}
|
|
199
|
+
func rank(_ voice: AVSpeechSynthesisVoice) -> Int {
|
|
200
|
+
let genderScore: Int
|
|
201
|
+
switch voice.gender {
|
|
202
|
+
case wanted: genderScore = 2
|
|
203
|
+
case .unspecified: genderScore = 1
|
|
204
|
+
default: genderScore = 0
|
|
205
|
+
}
|
|
206
|
+
return genderScore * 10 + voice.quality.rawValue
|
|
207
|
+
}
|
|
208
|
+
let resolved = candidates.max { rank($0) < rank($1) }
|
|
209
|
+
?? AVSpeechSynthesisVoice(language: code)
|
|
210
|
+
?? (language == "en" ? AVSpeechSynthesisVoice(language: "en-US") : nil)
|
|
211
|
+
if let resolved { voiceCache[cacheKey] = resolved }
|
|
212
|
+
return resolved
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/// Configured exactly once, on `audioQueue`. Ducks other audio instead of
|
|
216
|
+
/// interrupting it, and never deactivates the session — the host app may
|
|
217
|
+
/// be using it.
|
|
218
|
+
private static func configureAudioSessionLocked() {
|
|
219
|
+
guard !audioSessionConfigured else { return }
|
|
220
|
+
audioSessionConfigured = true
|
|
221
|
+
let session = AVAudioSession.sharedInstance()
|
|
222
|
+
try? session.setCategory(
|
|
223
|
+
.playback,
|
|
224
|
+
mode: .voicePrompt,
|
|
225
|
+
options: [.duckOthers, .mixWithOthers]
|
|
226
|
+
)
|
|
227
|
+
try? session.setActive(true, options: [])
|
|
228
|
+
}
|
|
229
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Minimal stand-in for the `onnxruntime-objc` pod.
|
|
2
|
+
//
|
|
3
|
+
// The official onnxruntime-objc 1.22.0 pod can no longer be installed: its
|
|
4
|
+
// archive on download.onnxruntime.ai returns 404, and its sources on
|
|
5
|
+
// github.com/microsoft/onnxruntime are unavailable too. This shim re-implements
|
|
6
|
+
// the small part of that API FaceMatch uses (same class, method and enum names,
|
|
7
|
+
// so the Swift call sites are unchanged) on top of the ONNX Runtime C++ API
|
|
8
|
+
// from the `onnxruntime-c` pod (see ios/onnxruntime-c.podspec in this package).
|
|
9
|
+
//
|
|
10
|
+
// Do NOT add the real onnxruntime-objc pod alongside this file: the ObjC class
|
|
11
|
+
// names would collide. If that pod becomes installable again, delete this
|
|
12
|
+
// directory, restore `import onnxruntime_objc` in AntiSpoofHelper.swift and
|
|
13
|
+
// FaceEmbeddingHelper.swift, and depend on onnxruntime-objc again.
|
|
14
|
+
//
|
|
15
|
+
// This header must stay plain Objective-C (no C++), because it is part of the
|
|
16
|
+
// FaceMatch module's umbrella header that Swift imports.
|
|
17
|
+
|
|
18
|
+
#import <Foundation/Foundation.h>
|
|
19
|
+
|
|
20
|
+
NS_ASSUME_NONNULL_BEGIN
|
|
21
|
+
|
|
22
|
+
typedef NS_ENUM(int32_t, ORTLoggingLevel) {
|
|
23
|
+
ORTLoggingLevelVerbose,
|
|
24
|
+
ORTLoggingLevelInfo,
|
|
25
|
+
ORTLoggingLevelWarning,
|
|
26
|
+
ORTLoggingLevelError,
|
|
27
|
+
ORTLoggingLevelFatal,
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
typedef NS_ENUM(int32_t, ORTTensorElementDataType) {
|
|
31
|
+
ORTTensorElementDataTypeUndefined,
|
|
32
|
+
ORTTensorElementDataTypeFloat,
|
|
33
|
+
ORTTensorElementDataTypeInt8,
|
|
34
|
+
ORTTensorElementDataTypeUInt8,
|
|
35
|
+
ORTTensorElementDataTypeInt32,
|
|
36
|
+
ORTTensorElementDataTypeUInt32,
|
|
37
|
+
ORTTensorElementDataTypeInt64,
|
|
38
|
+
ORTTensorElementDataTypeUInt64,
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/// The ONNX Runtime environment.
|
|
42
|
+
@interface ORTEnv : NSObject
|
|
43
|
+
- (instancetype)init NS_UNAVAILABLE;
|
|
44
|
+
- (nullable instancetype)initWithLoggingLevel:(ORTLoggingLevel)loggingLevel
|
|
45
|
+
error:(NSError**)error;
|
|
46
|
+
@end
|
|
47
|
+
|
|
48
|
+
/// Session options. Defaults match `Ort::SessionOptions()` (and therefore the
|
|
49
|
+
/// defaults of the official ORTSessionOptions).
|
|
50
|
+
@interface ORTSessionOptions : NSObject
|
|
51
|
+
- (instancetype)init NS_UNAVAILABLE;
|
|
52
|
+
- (nullable instancetype)initWithError:(NSError**)error NS_SWIFT_NAME(init());
|
|
53
|
+
@end
|
|
54
|
+
|
|
55
|
+
/// Per-run options. Present only so `runOptions: nil` call sites compile.
|
|
56
|
+
@interface ORTRunOptions : NSObject
|
|
57
|
+
@end
|
|
58
|
+
|
|
59
|
+
/// A tensor value.
|
|
60
|
+
@interface ORTValue : NSObject
|
|
61
|
+
- (instancetype)init NS_UNAVAILABLE;
|
|
62
|
+
|
|
63
|
+
/// Wraps `tensorData` (not copied; it is retained for the value's lifetime).
|
|
64
|
+
- (nullable instancetype)initWithTensorData:(NSMutableData*)tensorData
|
|
65
|
+
elementType:(ORTTensorElementDataType)elementType
|
|
66
|
+
shape:(NSArray<NSNumber*>*)shape
|
|
67
|
+
error:(NSError**)error;
|
|
68
|
+
|
|
69
|
+
/// A copy of the tensor's bytes.
|
|
70
|
+
- (nullable NSMutableData*)tensorDataWithError:(NSError**)error;
|
|
71
|
+
@end
|
|
72
|
+
|
|
73
|
+
/// An inference session for one model.
|
|
74
|
+
@interface ORTSession : NSObject
|
|
75
|
+
- (instancetype)init NS_UNAVAILABLE;
|
|
76
|
+
|
|
77
|
+
- (nullable instancetype)initWithEnv:(ORTEnv*)env
|
|
78
|
+
modelPath:(NSString*)path
|
|
79
|
+
sessionOptions:(nullable ORTSessionOptions*)sessionOptions
|
|
80
|
+
error:(NSError**)error;
|
|
81
|
+
|
|
82
|
+
- (nullable NSArray<NSString*>*)inputNamesWithError:(NSError**)error;
|
|
83
|
+
- (nullable NSArray<NSString*>*)outputNamesWithError:(NSError**)error;
|
|
84
|
+
|
|
85
|
+
- (nullable NSDictionary<NSString*, ORTValue*>*)runWithInputs:(NSDictionary<NSString*, ORTValue*>*)inputs
|
|
86
|
+
outputNames:(NSSet<NSString*>*)outputNames
|
|
87
|
+
runOptions:(nullable ORTRunOptions*)runOptions
|
|
88
|
+
error:(NSError**)error;
|
|
89
|
+
@end
|
|
90
|
+
|
|
91
|
+
NS_ASSUME_NONNULL_END
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// See ORTShim.h for why this exists.
|
|
2
|
+
|
|
3
|
+
#import "ORTShim.h"
|
|
4
|
+
|
|
5
|
+
#include <exception>
|
|
6
|
+
#include <optional>
|
|
7
|
+
#include <string>
|
|
8
|
+
#include <vector>
|
|
9
|
+
|
|
10
|
+
#include <onnxruntime/onnxruntime_cxx_api.h>
|
|
11
|
+
|
|
12
|
+
NS_ASSUME_NONNULL_BEGIN
|
|
13
|
+
|
|
14
|
+
static NSString* const kORTShimErrorDomain = @"onnxruntime";
|
|
15
|
+
|
|
16
|
+
static void ORTShimSetError(NSError** error, int code, const char* message) {
|
|
17
|
+
if (error == nullptr) return;
|
|
18
|
+
NSString* description = message ? [NSString stringWithUTF8String:message] : nil;
|
|
19
|
+
*error = [NSError errorWithDomain:kORTShimErrorDomain
|
|
20
|
+
code:code
|
|
21
|
+
userInfo:@{NSLocalizedDescriptionKey : description ?: @"ONNX Runtime error"}];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Converts C++ exceptions into NSError, like the official ObjC binding does.
|
|
25
|
+
#define ORT_SHIM_TRY try {
|
|
26
|
+
#define ORT_SHIM_CATCH(error, failValue) \
|
|
27
|
+
} \
|
|
28
|
+
catch (const Ort::Exception& e) { \
|
|
29
|
+
ORTShimSetError(error, static_cast<int>(e.GetOrtErrorCode()), e.what()); \
|
|
30
|
+
return failValue; \
|
|
31
|
+
} \
|
|
32
|
+
catch (const std::exception& e) { \
|
|
33
|
+
ORTShimSetError(error, -1, e.what()); \
|
|
34
|
+
return failValue; \
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static OrtLoggingLevel ORTShimLoggingLevel(ORTLoggingLevel level) {
|
|
38
|
+
switch (level) {
|
|
39
|
+
case ORTLoggingLevelVerbose: return ORT_LOGGING_LEVEL_VERBOSE;
|
|
40
|
+
case ORTLoggingLevelInfo: return ORT_LOGGING_LEVEL_INFO;
|
|
41
|
+
case ORTLoggingLevelWarning: return ORT_LOGGING_LEVEL_WARNING;
|
|
42
|
+
case ORTLoggingLevelError: return ORT_LOGGING_LEVEL_ERROR;
|
|
43
|
+
case ORTLoggingLevelFatal: return ORT_LOGGING_LEVEL_FATAL;
|
|
44
|
+
}
|
|
45
|
+
return ORT_LOGGING_LEVEL_WARNING;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
static ONNXTensorElementDataType ORTShimElementType(ORTTensorElementDataType type) {
|
|
49
|
+
switch (type) {
|
|
50
|
+
case ORTTensorElementDataTypeFloat: return ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT;
|
|
51
|
+
case ORTTensorElementDataTypeInt8: return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8;
|
|
52
|
+
case ORTTensorElementDataTypeUInt8: return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8;
|
|
53
|
+
case ORTTensorElementDataTypeInt32: return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32;
|
|
54
|
+
case ORTTensorElementDataTypeUInt32: return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32;
|
|
55
|
+
case ORTTensorElementDataTypeInt64: return ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64;
|
|
56
|
+
case ORTTensorElementDataTypeUInt64: return ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64;
|
|
57
|
+
case ORTTensorElementDataTypeUndefined: break;
|
|
58
|
+
}
|
|
59
|
+
return ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
static size_t ORTShimElementSize(ONNXTensorElementDataType type) {
|
|
63
|
+
switch (type) {
|
|
64
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: return sizeof(float);
|
|
65
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: return sizeof(int8_t);
|
|
66
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: return sizeof(uint8_t);
|
|
67
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: return sizeof(int32_t);
|
|
68
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: return sizeof(uint32_t);
|
|
69
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: return sizeof(int64_t);
|
|
70
|
+
case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: return sizeof(uint64_t);
|
|
71
|
+
default: return 0;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
#pragma mark - ORTEnv
|
|
76
|
+
|
|
77
|
+
@implementation ORTEnv {
|
|
78
|
+
@public
|
|
79
|
+
std::optional<Ort::Env> _env;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
- (nullable instancetype)initWithLoggingLevel:(ORTLoggingLevel)loggingLevel error:(NSError**)error {
|
|
83
|
+
if ((self = [super init]) == nil) return nil;
|
|
84
|
+
ORT_SHIM_TRY
|
|
85
|
+
_env.emplace(ORTShimLoggingLevel(loggingLevel), "FaceMatch");
|
|
86
|
+
return self;
|
|
87
|
+
ORT_SHIM_CATCH(error, nil)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
@end
|
|
91
|
+
|
|
92
|
+
#pragma mark - ORTSessionOptions
|
|
93
|
+
|
|
94
|
+
@implementation ORTSessionOptions {
|
|
95
|
+
@public
|
|
96
|
+
std::optional<Ort::SessionOptions> _options;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
- (nullable instancetype)initWithError:(NSError**)error {
|
|
100
|
+
if ((self = [super init]) == nil) return nil;
|
|
101
|
+
ORT_SHIM_TRY
|
|
102
|
+
_options.emplace();
|
|
103
|
+
return self;
|
|
104
|
+
ORT_SHIM_CATCH(error, nil)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
@end
|
|
108
|
+
|
|
109
|
+
#pragma mark - ORTRunOptions
|
|
110
|
+
|
|
111
|
+
@implementation ORTRunOptions
|
|
112
|
+
@end
|
|
113
|
+
|
|
114
|
+
#pragma mark - ORTValue
|
|
115
|
+
|
|
116
|
+
@interface ORTValue ()
|
|
117
|
+
- (instancetype)initWithOrtValue:(Ort::Value&&)value;
|
|
118
|
+
@end
|
|
119
|
+
|
|
120
|
+
@implementation ORTValue {
|
|
121
|
+
@public
|
|
122
|
+
std::optional<Ort::Value> _value;
|
|
123
|
+
// Backing store for input tensors created from NSMutableData; ORT does not
|
|
124
|
+
// copy it, so it must outlive _value.
|
|
125
|
+
NSMutableData* _Nullable _backingData;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
- (nullable instancetype)initWithTensorData:(NSMutableData*)tensorData
|
|
129
|
+
elementType:(ORTTensorElementDataType)elementType
|
|
130
|
+
shape:(NSArray<NSNumber*>*)shape
|
|
131
|
+
error:(NSError**)error {
|
|
132
|
+
if ((self = [super init]) == nil) return nil;
|
|
133
|
+
ORT_SHIM_TRY
|
|
134
|
+
const ONNXTensorElementDataType ortType = ORTShimElementType(elementType);
|
|
135
|
+
if (ORTShimElementSize(ortType) == 0) {
|
|
136
|
+
ORTShimSetError(error, ORT_INVALID_ARGUMENT, "Unsupported tensor element type");
|
|
137
|
+
return nil;
|
|
138
|
+
}
|
|
139
|
+
std::vector<int64_t> dims;
|
|
140
|
+
dims.reserve(shape.count);
|
|
141
|
+
for (NSNumber* dim in shape) dims.push_back(dim.longLongValue);
|
|
142
|
+
|
|
143
|
+
const Ort::MemoryInfo memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU);
|
|
144
|
+
_value.emplace(Ort::Value::CreateTensor(memoryInfo, tensorData.mutableBytes, tensorData.length,
|
|
145
|
+
dims.data(), dims.size(), ortType));
|
|
146
|
+
_backingData = tensorData;
|
|
147
|
+
return self;
|
|
148
|
+
ORT_SHIM_CATCH(error, nil)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
- (instancetype)initWithOrtValue:(Ort::Value&&)value {
|
|
152
|
+
if ((self = [super init]) == nil) return nil;
|
|
153
|
+
_value.emplace(std::move(value));
|
|
154
|
+
return self;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
- (nullable NSMutableData*)tensorDataWithError:(NSError**)error {
|
|
158
|
+
ORT_SHIM_TRY
|
|
159
|
+
if (!_value || !_value->IsTensor()) {
|
|
160
|
+
ORTShimSetError(error, ORT_INVALID_ARGUMENT, "Value is not a tensor");
|
|
161
|
+
return nil;
|
|
162
|
+
}
|
|
163
|
+
const auto info = _value->GetTensorTypeAndShapeInfo();
|
|
164
|
+
const size_t elementSize = ORTShimElementSize(info.GetElementType());
|
|
165
|
+
if (elementSize == 0) {
|
|
166
|
+
ORTShimSetError(error, ORT_NOT_IMPLEMENTED, "Unsupported tensor element type");
|
|
167
|
+
return nil;
|
|
168
|
+
}
|
|
169
|
+
const size_t byteCount = info.GetElementCount() * elementSize;
|
|
170
|
+
const void* bytes = _value->GetTensorRawData();
|
|
171
|
+
return [NSMutableData dataWithBytes:bytes length:byteCount];
|
|
172
|
+
ORT_SHIM_CATCH(error, nil)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
@end
|
|
176
|
+
|
|
177
|
+
#pragma mark - ORTSession
|
|
178
|
+
|
|
179
|
+
@implementation ORTSession {
|
|
180
|
+
ORTEnv* _env; // keeps the Ort::Env alive for the session's lifetime
|
|
181
|
+
std::optional<Ort::Session> _session;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
- (nullable instancetype)initWithEnv:(ORTEnv*)env
|
|
185
|
+
modelPath:(NSString*)path
|
|
186
|
+
sessionOptions:(nullable ORTSessionOptions*)sessionOptions
|
|
187
|
+
error:(NSError**)error {
|
|
188
|
+
if ((self = [super init]) == nil) return nil;
|
|
189
|
+
ORT_SHIM_TRY
|
|
190
|
+
if (sessionOptions == nil) {
|
|
191
|
+
sessionOptions = [[ORTSessionOptions alloc] initWithError:error];
|
|
192
|
+
if (sessionOptions == nil) return nil;
|
|
193
|
+
}
|
|
194
|
+
_env = env;
|
|
195
|
+
_session.emplace(*env->_env, path.UTF8String, *sessionOptions->_options);
|
|
196
|
+
return self;
|
|
197
|
+
ORT_SHIM_CATCH(error, nil)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
- (nullable NSArray<NSString*>*)namesWithError:(NSError**)error inputs:(BOOL)inputs {
|
|
201
|
+
ORT_SHIM_TRY
|
|
202
|
+
Ort::AllocatorWithDefaultOptions allocator;
|
|
203
|
+
const size_t count = inputs ? _session->GetInputCount() : _session->GetOutputCount();
|
|
204
|
+
NSMutableArray<NSString*>* names = [NSMutableArray arrayWithCapacity:count];
|
|
205
|
+
for (size_t i = 0; i < count; ++i) {
|
|
206
|
+
auto name = inputs ? _session->GetInputNameAllocated(i, allocator)
|
|
207
|
+
: _session->GetOutputNameAllocated(i, allocator);
|
|
208
|
+
[names addObject:[NSString stringWithUTF8String:name.get()]];
|
|
209
|
+
}
|
|
210
|
+
return names;
|
|
211
|
+
ORT_SHIM_CATCH(error, nil)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
- (nullable NSArray<NSString*>*)inputNamesWithError:(NSError**)error {
|
|
215
|
+
return [self namesWithError:error inputs:YES];
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
- (nullable NSArray<NSString*>*)outputNamesWithError:(NSError**)error {
|
|
219
|
+
return [self namesWithError:error inputs:NO];
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
- (nullable NSDictionary<NSString*, ORTValue*>*)runWithInputs:(NSDictionary<NSString*, ORTValue*>*)inputs
|
|
223
|
+
outputNames:(NSSet<NSString*>*)outputNameSet
|
|
224
|
+
runOptions:(nullable ORTRunOptions*)runOptions
|
|
225
|
+
error:(NSError**)error {
|
|
226
|
+
ORT_SHIM_TRY
|
|
227
|
+
std::vector<std::string> inputNameStorage;
|
|
228
|
+
std::vector<const OrtValue*> inputValues;
|
|
229
|
+
for (NSString* name in inputs) {
|
|
230
|
+
ORTValue* value = inputs[name];
|
|
231
|
+
inputNameStorage.emplace_back(name.UTF8String);
|
|
232
|
+
inputValues.push_back(static_cast<const OrtValue*>(*value->_value));
|
|
233
|
+
}
|
|
234
|
+
std::vector<const char*> inputNames;
|
|
235
|
+
for (const auto& name : inputNameStorage) inputNames.push_back(name.c_str());
|
|
236
|
+
|
|
237
|
+
NSArray<NSString*>* outputNameList = outputNameSet.allObjects;
|
|
238
|
+
std::vector<std::string> outputNameStorage;
|
|
239
|
+
for (NSString* name in outputNameList) outputNameStorage.emplace_back(name.UTF8String);
|
|
240
|
+
std::vector<const char*> outputNames;
|
|
241
|
+
for (const auto& name : outputNameStorage) outputNames.push_back(name.c_str());
|
|
242
|
+
|
|
243
|
+
std::vector<OrtValue*> outputValues(outputNames.size(), nullptr);
|
|
244
|
+
Ort::ThrowOnError(Ort::GetApi().Run(*_session, nullptr, inputNames.data(), inputValues.data(),
|
|
245
|
+
inputValues.size(), outputNames.data(), outputNames.size(),
|
|
246
|
+
outputValues.data()));
|
|
247
|
+
|
|
248
|
+
NSMutableDictionary<NSString*, ORTValue*>* result =
|
|
249
|
+
[NSMutableDictionary dictionaryWithCapacity:outputValues.size()];
|
|
250
|
+
for (size_t i = 0; i < outputValues.size(); ++i) {
|
|
251
|
+
// Ort::Value takes ownership and releases the OrtValue.
|
|
252
|
+
result[outputNameList[i]] = [[ORTValue alloc] initWithOrtValue:Ort::Value(outputValues[i])];
|
|
253
|
+
}
|
|
254
|
+
return result;
|
|
255
|
+
ORT_SHIM_CATCH(error, nil)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
@end
|
|
259
|
+
|
|
260
|
+
NS_ASSUME_NONNULL_END
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Strictly scoped lifecycle management for temporary biometric captures.
|
|
4
|
+
/// Port of `PrivateCaptureStore.kt`; captures live in the app's Caches
|
|
5
|
+
/// directory and nothing outside `face-match/capture-*.jpg` can be deleted
|
|
6
|
+
/// through the bridge.
|
|
7
|
+
enum PrivateCaptureStore {
|
|
8
|
+
private static let directoryName = "face-match"
|
|
9
|
+
private static let prefix = "capture-"
|
|
10
|
+
private static let suffix = ".jpg"
|
|
11
|
+
|
|
12
|
+
static func create() throws -> URL {
|
|
13
|
+
let dir = directory()
|
|
14
|
+
if !FileManager.default.fileExists(atPath: dir.path) {
|
|
15
|
+
do {
|
|
16
|
+
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
|
17
|
+
} catch {
|
|
18
|
+
throw FaceMatchError("E_CAPTURE_FILE", "Unable to create the capture directory")
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return dir.appendingPathComponent("\(prefix)\(UUID().uuidString)\(suffix)")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
@discardableResult
|
|
25
|
+
static func deleteIfOwned(_ uriString: String) -> Bool {
|
|
26
|
+
guard let url = URL(string: uriString), url.isFileURL else { return false }
|
|
27
|
+
let target = url.standardizedFileURL.resolvingSymlinksInPath()
|
|
28
|
+
let dir = directory().standardizedFileURL.resolvingSymlinksInPath()
|
|
29
|
+
guard target.deletingLastPathComponent().path == dir.path, isCapture(target) else {
|
|
30
|
+
return false
|
|
31
|
+
}
|
|
32
|
+
if !FileManager.default.fileExists(atPath: target.path) { return true }
|
|
33
|
+
return (try? FileManager.default.removeItem(at: target)) != nil
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
static func clear() {
|
|
37
|
+
let dir = directory().standardizedFileURL.resolvingSymlinksInPath()
|
|
38
|
+
guard let files = try? FileManager.default.contentsOfDirectory(
|
|
39
|
+
at: dir,
|
|
40
|
+
includingPropertiesForKeys: nil
|
|
41
|
+
) else { return }
|
|
42
|
+
for file in files where isCapture(file) {
|
|
43
|
+
try? FileManager.default.removeItem(at: file)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The sandbox roots a `file://` URI is allowed to point at. The Android
|
|
48
|
+
/// build restricts decoding to app-private storage; this is the iOS
|
|
49
|
+
/// equivalent (Documents, Caches, Application Support, tmp).
|
|
50
|
+
static func allowedRoots() -> [URL] {
|
|
51
|
+
var roots: [URL] = [URL(fileURLWithPath: NSTemporaryDirectory())]
|
|
52
|
+
for directory in [FileManager.SearchPathDirectory.documentDirectory,
|
|
53
|
+
.cachesDirectory,
|
|
54
|
+
.applicationSupportDirectory] {
|
|
55
|
+
if let url = FileManager.default.urls(for: directory, in: .userDomainMask).first {
|
|
56
|
+
roots.append(url)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return roots.map { $0.standardizedFileURL.resolvingSymlinksInPath() }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private static func directory() -> URL {
|
|
63
|
+
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
|
|
64
|
+
return caches.appendingPathComponent(directoryName, isDirectory: true)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
private static func isCapture(_ url: URL) -> Bool {
|
|
68
|
+
let name = url.lastPathComponent
|
|
69
|
+
return name.hasPrefix(prefix) && name.hasSuffix(suffix)
|
|
70
|
+
}
|
|
71
|
+
}
|