Last active
April 13, 2023 11:46
-
-
Save Joony/7f715c871f9a5439c27c48c8a6432262 to your computer and use it in GitHub Desktop.
Download and compile an MLModel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreML | |
extension MLModel { | |
/** | |
Use the model: `let model = try MLModel(contentsOf: permanentURL)` | |
*/ | |
func download(url: URL) async throws -> URL { | |
let request = URLRequest(url: url) | |
let (data, _) = try await URLSession.shared.data(from: url) | |
let tempUrl = try FileManager.default.url( | |
for: .cachesDirectory, | |
in: .userDomainMask, | |
appropriateFor: .temporaryDirectory, | |
create: true | |
) | |
.appendingPathComponent("temp.mlmodel") | |
try data.write(to: tempUrl) | |
let compiledModelUrl = try await MLModel.compileModel(at: tempUrl) | |
let permanentUrl = try FileManager.default.url( | |
for: .applicationSupportDirectory, | |
in: .userDomainMask, | |
appropriateFor: nil, | |
create: true | |
) | |
.appendingPathComponent("mlmodels") | |
.appendingPathComponent(compiledModelUrl.lastPathComponent) | |
_ = try FileManager.default.replaceItemAt(permanentUrl, withItemAt: compiledModelUrl) | |
try FileManager.default.removeItem(at: tempUrl) | |
return permanentUrl | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment