アプリのインストール後に、ユーザーのデバイスにCore MLモデルを配信します。
概要
特定のユースケースでは、モデルをアプリにバンドルするよりも、ユーザーのデバイスでモデルをダウンロードしてコンパイルする方が有益です。さまざまなモデルによってサポートされる多様な機能を持つアプリの場合、バックグラウンドで個々にモデルをダウンロードすると、ユーザーがすべてのモデルをダウンロードする必要がなく、帯域幅とストレージを節約できる可能性があります。同様に、ロケールや地域によって、使用するCore MLモデルが異なる場合があります。また、ユーザーがオフラインの時にモデルが更新され、アップデートがワイヤレスで提供される場合も考えられます。
バックグラウンドでのダウンロードとコンパイルの実装
モデル定義ファイル(.mlmodel)をコンパイルする前に、このファイルがデバイス上にあることが必要です。URLSession(英語)、CloudKit(英語)、またはその他のネットワーキングツールキットを使って、ユーザーのデバイス上にアプリで使うモデルをダウンロードします。
compileModel(at:)(英語)を呼び出して、.mlmodelcファイルを生成します。このファイルはMLModel(英語)のインスタンス初期化に使用されます。このモデルの機能は、アプリにバンドルされたモデルと同じです。
モデルファイルのコンパイルと、コンパイル版からの MLModel インスタンスの作成
let compiledUrl = try MLModel.compileModel(at: modelUrl)
let model = try MLModel(contentsOf: compiledUrl)
再使用可能なモデルの永続的な場所への移動
帯域幅の使用を制限するため、可能であれば、ダウンロードとコンパイルのプロセスを繰り返さずにすむようにします。モデルは一時的な場所にコンパイルされます。コンパイルされたモデルを再使用できる場合は、アプリのサポートディレクトリなど、永続的な場所にモデルを移動します。
.mlmodelc
ファイルをアプリのサブディレクトリにコピー
// find the app support directory
let fileManager = FileManager.default
let appSupportDirectory = try! fileManager.url(for: .applicationSupportDirectory,
in: .userDomainMask, appropriateFor: compiledUrl, create: true)
// create a permanent URL in the app support directory
let permanentUrl = appSupportDirectory.appendingPathComponent(compiledUrl.lastPathComponent)
do {
// if the file exists, replace it. Otherwise, copy the file to the destination.
if fileManager.fileExists(atPath: permanentUrl.absoluteString) {
_ = try fileManager.replaceItemAt(permanentUrl, withItemAt: compiledUrl)
} else {
try fileManager.copyItem(at: compiledUrl, to: permanentUrl)
}
} catch {
print("Error during copy: \(error.localizedDescription)")
}