- Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathModelDownloader.swift
71 lines (59 loc) · 2.14 KB
/
ModelDownloader.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import Foundation
extensionBundle{
vardisplayName:String?{
returnobject(forInfoDictionaryKey: kCFBundleNameKey asString)as?String
}
}
varcacheDirectory:URL{
letparent=FileManager.default.urls(for:.cachesDirectory, in:.userDomainMask)[0]
return parent.appending(path:Bundle.main.bundleIdentifier!)
}
classModelDownloader{
enumState{
case pending
case completed
case failed(Error?)
}
@Publishedvarstate=State.pending
letbaseURL=URL(string:"https://huggingface.co/datasets/ggerganov/whisper.cpp/resolve/main")!
letmodelName:String
letsession:URLSession
letfilename:String
letmodelURL:URL
vartask:URLSessionDownloadTask?
init(modelName:String, configuration:URLSessionConfiguration=.default){
self.modelName = modelName
session =URLSession(configuration: configuration)
filename ="\(modelName).bin"
modelURL = cacheDirectory.appending(path: filename)
}
func resume(){
if !FileManager.default.fileExists(atPath: cacheDirectory.absoluteURL.path){
try!FileManager.default.createDirectory(at: cacheDirectory, withIntermediateDirectories:false)
}
letdestination= modelURL.absoluteURL
ifFileManager.default.fileExists(atPath: destination.path){
state =.completed
return
}
letrequest=URLRequest(url: baseURL.appending(path: filename))
lettask= session.downloadTask(with: request){[weak self] location, response, error in
iflet error = error {
self?.state =.failed(error)
return
}
iflet location = location {
do{
tryFileManager.default.moveItem(at: location, to: destination)
self?.state =.completed
}catch{
self?.state =.failed(error)
}
}else{
self?.state =.failed(nil)
}
}
task.resume()
self.task = task
}
}