// What `hf download --local-dir ` writes to disk (verified against huggingface_hub 2.1.1): // // / final file (moved in place when complete) // /.cache/huggingface/download/.metadata "\n\n\n" // /.cache/huggingface/download/.lock lock file, left behind // /.cache/huggingface/download/**/...incomplete partial download // /.cache/huggingface/trees/.json cached file tree // // The etag is the LFS sha256 for LFS/Xet files and the git blob SHA-1 for small files. // Partial files are NOT resumed: every run writes a new name, and a killed run leaves // its .incomplete file behind. We delete those before each run. import { readdir, readFile, rm, stat } from "node:fs/promises"; import { join, resolve, sep } from "node:path"; export const HF_CACHE_DIR = join(".cache", "huggingface"); const DOWNLOAD_DIR = join(HF_CACHE_DIR, "download"); /** Absolute local dir for a model; refuses paths that would escape MODELS_DIR. */ export function modelDir(modelsDir: string, localPath: string): string { const root = resolve(modelsDir); const dir = resolve(root, localPath); if (dir === root || !dir.startsWith(root + sep)) { throw new Error(`Refusing model path outside MODELS_DIR: ${localPath}`); } return dir; } export type FileMetadata = { commit: string; etag: string }; export async function readMetadata(dir: string, path: string): Promise { try { const text = await readFile(join(dir, DOWNLOAD_DIR, `${path}.metadata`), "utf8"); const [commit, etag] = text.split("\n"); return commit && etag ? { commit: commit.trim(), etag: etag.trim() } : null; } catch { return null; } } /** Size of a file, or null if it doesn't exist. */ export async function fileSize(path: string): Promise { try { const s = await stat(path); return s.isFile() ? s.size : null; } catch { return null; } } /** Extract the etag (40 or 64 hex chars) from an .incomplete file name. */ export function etagFromIncompleteName(name: string): string | null { if (!name.endsWith(".incomplete")) return null; for (const part of name.split(".")) { if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(part)) return part; } return null; } export type IncompleteFile = { path: string; etag: string | null; size: number }; /** All partial files under the local dir's download cache. */ export async function listIncomplete(dir: string): Promise { const root = join(dir, DOWNLOAD_DIR); let entries; try { entries = await readdir(root, { recursive: true, withFileTypes: true }); } catch { return []; } const out: IncompleteFile[] = []; for (const e of entries) { if (!e.isFile() || !e.name.endsWith(".incomplete")) continue; const full = join(e.parentPath, e.name); const size = await fileSize(full); if (size == null) continue; // finished and moved between readdir and stat out.push({ path: full, etag: etagFromIncompleteName(e.name), size }); } return out; } /** Delete leftover partial files from earlier runs. Only call while no hf process uses the dir. */ export async function removeStaleIncomplete(dir: string): Promise<{ count: number; bytes: number }> { const files = await listIncomplete(dir); for (const f of files) await rm(f.path, { force: true }); return { count: files.length, bytes: files.reduce((s, f) => s + f.size, 0) }; } export type ExpectedFile = { path: string; size: number; etags: string[] }; /** * Bytes present for one expected file: * - final file with the expected size and matching (or missing) metadata etag → complete * - otherwise the size of its in-progress .incomplete file (matched by etag), else 0 */ export async function bytesOnDisk( dir: string, file: ExpectedFile, incomplete: IncompleteFile[], ): Promise<{ done: number; complete: boolean }> { const size = await fileSize(join(dir, file.path)); if (size === file.size) { const meta = await readMetadata(dir, file.path); if (!meta || file.etags.includes(meta.etag)) return { done: file.size, complete: true }; } let partial = 0; for (const inc of incomplete) { if (inc.etag && file.etags.includes(inc.etag)) partial = Math.max(partial, inc.size); } return { done: Math.min(partial, file.size), complete: false }; } /** Delete a downloaded file and hf's metadata/lock for it, so the next `hf download` fetches it again. */ export async function removeLocalFile(dir: string, path: string): Promise { const full = join(dir, path); const existed = (await fileSize(full)) != null; await rm(full, { force: true }); await rm(join(dir, DOWNLOAD_DIR, `${path}.metadata`), { force: true }); await rm(join(dir, DOWNLOAD_DIR, `${path}.lock`), { force: true }); return existed; } /** All files under `dir` (relative, "/"-separated), skipping hf's .cache and .git folders. */ export async function listLocalFiles(dir: string): Promise<{ path: string; size: number }[]> { let entries; try { entries = await readdir(dir, { recursive: true, withFileTypes: true }); } catch { return []; } const out: { path: string; size: number }[] = []; for (const e of entries) { if (!e.isFile()) continue; const rel = join(e.parentPath, e.name).slice(dir.length + 1).split(sep).join("/"); if (rel.startsWith(".cache/") || rel.startsWith(".git/")) continue; out.push({ path: rel, size: (await fileSize(join(dir, rel))) ?? 0 }); } return out.sort((a, b) => a.path.localeCompare(b.path)); }