1// 2// ETCoreMLModelCompiler.mm 3// 4// Copyright © 2024 Apple Inc. All rights reserved. 5// 6// Please refer to the license found in the LICENSE file in the root directory of the source tree. 7 8#import <ETCoreMLModelCompiler.h> 9#import <ETCoreMLLogging.h> 10#import <TargetConditionals.h> 11 12@implementation ETCoreMLModelCompiler 13 14+ (nullable NSURL *)compileModelAtURL:(NSURL *)modelURL 15 maxWaitTimeInSeconds:(NSTimeInterval)maxWaitTimeInSeconds 16 error:(NSError* __autoreleasing *)error { 17#if TARGET_OS_WATCH 18 (void)modelURL; 19 (void)maxWaitTimeInSeconds; 20 (void)error; 21 ETCoreMLLogErrorAndSetNSError(error, 22 ETCoreMLErrorModelCompilationNotSupported, 23 "%@: Model compilation is not supported on the target, please make sure to export a compiled model.", 24 NSStringFromClass(ETCoreMLModelCompiler.class)); 25 return nil; 26#else 27 __block NSError *localError = nil; 28 __block NSURL *result = nil; 29 30 dispatch_semaphore_t sema = dispatch_semaphore_create(0); 31 [MLModel compileModelAtURL:modelURL completionHandler:^(NSURL * _Nullable tempURL, NSError * _Nullable compilationError) { 32 result = [tempURL copy]; 33 localError = compilationError; 34 dispatch_semaphore_signal(sema); 35 }]; 36 37 long status = dispatch_semaphore_wait(sema, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(maxWaitTimeInSeconds * NSEC_PER_SEC))); 38 if (status != 0) { 39 ETCoreMLLogErrorAndSetNSError(error, 40 ETCoreMLErrorCompilationFailed, 41 "%@: Failed to compile model in %f seconds.", 42 NSStringFromClass(ETCoreMLModelCompiler.class), 43 maxWaitTimeInSeconds); 44 return nil; 45 } 46 47 return result; 48#endif 49} 50 51@end 52