You are on the right track that you precompiled a source model (.mlpackage or .mlmodel) to .mlmodelc manually before adding it to Swift Package. Currently SPM doesn't support compiling the source model in .process(:) rule.
Let's say, you have a source model named model.mlpackage. The first step is to compile it to .mlmodelc.
xcrun coremlcompiler compile model.mlpackage /tmp/
Then, copy the compiled model to your Swift Package.
cp -r /tmp/model.mlmodelc /path/to/ModelInSwiftPackage/Sources/ModelInSwiftPackage/
In my test, the resultant directory structure is something like this.
.
├── Package.swift
├── Sources
│ └── ModelInSwiftPackage
│ ├── ModelInSwiftPackage.swift
│ └── model.mlmodelc
│ ├── analytics
│ │ └── coremldata.bin
│ ├── coremldata.bin
│ └── model.mil
└── Tests
└── ModelInSwiftPackageTests
└── ModelInSwiftPackageTests.swift
Now, edit Package.swift as follows, using copy rule.
import PackageDescription
let package = Package(
:
targets: [
.target(
name: "ModelInSwiftPackage",
resources: [
.copy("model.mlmodelc")]
),
)
Now, you should be able to build the package with the model.
To access the model, you can use Bundle.module.url().
public func loadModel() throws -> MLModel? {
guard let modelURL = Bundle.module.url(forResource: "model", withExtension: "mlmodelc") else {
return nil
}
return try MLModel(contentsOf: modelURL)
}
Hope it works!
Topic:
Machine Learning & AI
SubTopic:
Core ML
Tags: