Skip to content

Commit 43ae46d

Browse files
authored
Add more default hfToken locations (#149)
1 parent 44e2c04 commit 43ae46d

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

Sources/Hub/HubApi.swift

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public struct HubApi {
1717
public typealias Repo = Hub.Repo
1818

1919
public init(downloadBase: URL? = nil, hfToken: String? = nil, endpoint: String = "https://huggingface.co", useBackgroundSession: Bool = false) {
20-
self.hfToken = hfToken ?? ProcessInfo.processInfo.environment["HUGGING_FACE_HUB_TOKEN"]
20+
self.hfToken = hfToken ?? Self.hfTokenFromEnv()
2121
if let downloadBase {
2222
self.downloadBase = downloadBase
2323
} else {
@@ -31,6 +31,37 @@ public struct HubApi {
3131
public static let shared = HubApi()
3232
}
3333

34+
private extension HubApi {
35+
static func hfTokenFromEnv() -> String? {
36+
let possibleTokens = [
37+
{ ProcessInfo.processInfo.environment["HF_TOKEN"] },
38+
{ ProcessInfo.processInfo.environment["HUGGING_FACE_HUB_TOKEN"] },
39+
{
40+
ProcessInfo.processInfo.environment["HF_TOKEN_PATH"].flatMap {
41+
try? String(
42+
contentsOf: URL(filePath: NSString(string: $0).expandingTildeInPath),
43+
encoding: .utf8
44+
)
45+
}
46+
},
47+
{
48+
ProcessInfo.processInfo.environment["HF_HOME"].flatMap {
49+
try? String(
50+
contentsOf: URL(filePath: NSString(string: $0).expandingTildeInPath).appending(path: "token"),
51+
encoding: .utf8
52+
)
53+
}
54+
},
55+
{ try? String(contentsOf: .homeDirectory.appendingPathComponent(".huggingface/token"), encoding: .utf8) }
56+
]
57+
return possibleTokens
58+
.lazy
59+
.compactMap({ $0() })
60+
.filter({ !$0.isEmpty })
61+
.first
62+
}
63+
}
64+
3465
/// File retrieval
3566
public extension HubApi {
3667
/// Model data for parsed filenames

0 commit comments

Comments
 (0)