linoyts's picture
linoyts HF Staff
Style transfer test: Jeveration image-to-image on WebGPU
0718f73 verified
Raw History Blame Contribute Delete
6.96 kB
// Vendored from diffusers-js (js/src/hub.js): Hub file access with a content-addressed Cache API cache.
// File access for pipelines. A pipeline only asks for paths inside a model repo ("transformer/config.json");
// where the bytes come from (Hub + browser Cache API, or a local folder in Node) is decided here.
/** Cache API keys must be http(s) URLs; this host is reserved (RFC 2606) so it can never collide with a real file. */
const CONTENT_ORIGIN = "https://diffusers-js.invalid";
const contentKey = (sha256) => `${CONTENT_ORIGIN}/sha256/${sha256}`;
/**
* Hub repo, cached in the browser's Cache API (survives reloads, same idea as transformers.js).
*
* Large (LFS) files are cached by content: the key is the file's SHA-256 from the Hub's file listing, not its URL.
* A renamed repo, a new revision that leaves a file unchanged, or the same file in two repos is downloaded once.
* Every download is checked against that hash before it is cached. Copies cached by URL by earlier versions are
* adopted after the same check, so moving to content keys costs no re-download.
*/
export class HubFiles {
constructor(repo, { revision = "main", endpoint = "https://huggingface.co", cacheName = "diffusers-js" } = {}) {
this.repo = repo; this.revision = revision; this.endpoint = endpoint; this.cacheName = cacheName;
this._manifest = null; this._legacy = null;
}
url(path) { return `${this.endpoint}/${this.repo}/resolve/${this.revision}/${path}`; }
async _cache() { try { return await caches.open(this.cacheName); } catch { return null; } } // no Cache API (some private modes)
/**
* Configs are small and change when the repo is updated, so they always come from the network (the cached copy is
* only a fallback when offline).
*/
async json(path) {
const url = this.url(path);
const cache = await this._cache();
try {
const res = await fetch(url, { cache: "no-cache" }); // revalidate: unchanged files come back as 304
if (!res.ok) throw new Error(`${res.status} fetching ${url}`);
const text = await res.text();
if (cache) { try { await cache.put(url, new Response(text, { headers: { "content-type": "application/json" } })); } catch { /* quota */ } }
return JSON.parse(text);
} catch (e) {
const hit = cache ? await cache.match(url) : undefined;
if (hit) return JSON.parse(await hit.text());
throw e;
}
}
/** path -> {sha256, size} for every LFS file in the repo, from the Hub's tree listing (cached for offline use). */
manifest() {
return (this._manifest ??= (async () => {
const cache = await this._cache();
const key = `${CONTENT_ORIGIN}/manifest/${this.repo}@${this.revision}`;
let entries = null;
try {
entries = [];
let next = `${this.endpoint}/api/models/${this.repo}/tree/${encodeURIComponent(this.revision)}?recursive=true`;
while (next) {
const res = await fetch(next, { cache: "no-cache" });
if (!res.ok) throw new Error(`${res.status} listing ${this.repo}`);
entries.push(...(await res.json()));
next = /<([^>]+)>;\s*rel="next"/.exec(res.headers.get("link") ?? "")?.[1] ?? null;
}
if (cache) { try { await cache.put(key, new Response(JSON.stringify(entries))); } catch { /* quota */ } }
} catch {
const hit = cache ? await cache.match(key) : undefined;
entries = hit ? await hit.json() : null; // offline and never listed: fall back to URL keys
}
if (!entries) return null;
const map = new Map();
for (const e of entries) if (e.type === "file" && e.lfs?.oid) map.set(e.path, { sha256: e.lfs.oid, size: e.lfs.size });
return map;
})());
}
/** @param {(e:{file:string,loaded:number,total:number,fromCache:boolean})=>void} [onProgress] */
async bytes(path, onProgress) {
const url = this.url(path);
const cache = await this._cache();
const entry = (await this.manifest())?.get(path);
const key = entry ? contentKey(entry.sha256) : url; // small non-LFS files keep URL keys
if (cache) {
const hit = await cache.match(key);
if (hit) return read(hit, path, onProgress, true);
if (entry) {
const adopted = await this._adopt(cache, path, entry, onProgress);
if (adopted) return adopted;
}
}
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status} fetching ${url}`);
const buf = await read(res, path, onProgress, false);
if (entry && (await sha256(buf)) !== entry.sha256) throw new Error(`checksum mismatch for ${path}; the download was corrupted, please retry`);
if (cache) { try { await cache.put(key, new Response(buf, { headers: { "content-length": String(buf.length) } })); } catch { /* quota */ } }
return buf;
}
/** A copy of `path` cached by URL (older versions, possibly under another repo name or revision) with the right hash. */
async _adopt(cache, path, entry, onProgress) {
this._legacy ??= cache.keys().then((reqs) => reqs.map((r) => r.url).filter((u) => !u.startsWith(CONTENT_ORIGIN) && u.includes("/resolve/")));
for (const u of await this._legacy) {
if (!u.endsWith("/" + path)) continue;
const res = await cache.match(u);
if (!res || Number(res.headers.get("content-length") || entry.size) !== entry.size) continue;
const buf = await read(res, path, onProgress, true);
if (buf.length !== entry.size || (await sha256(buf)) !== entry.sha256) continue;
try { await cache.put(contentKey(entry.sha256), new Response(buf, { headers: { "content-length": String(buf.length) } })); await cache.delete(u); } catch { /* quota */ }
return buf;
}
return null;
}
}
/** Read a response body into one Uint8Array, reporting progress. */
async function read(res, path, onProgress, fromCache) {
const total = Number(res.headers.get("content-length")) || 0;
const reader = res.body.getReader();
// content-length is only a hint (it is the compressed size when the body is gzipped), so overflow goes to `parts`.
const out = new Uint8Array(total || 0); const parts = []; let loaded = 0, filled = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
if (!parts.length && filled + value.length <= total) { out.set(value, filled); filled += value.length; } else parts.push(value);
loaded += value.length;
onProgress?.({ file: path, loaded, total: Math.max(total, loaded), fromCache });
}
if (filled === total && !parts.length) return out;
return concat([out.subarray(0, filled), ...parts], loaded);
}
async function sha256(buf) {
const d = new Uint8Array(await crypto.subtle.digest("SHA-256", buf));
let s = ""; for (const b of d) s += b.toString(16).padStart(2, "0");
return s;
}
function concat(parts, n) { const o = new Uint8Array(n); let k = 0; for (const p of parts) { o.set(p, k); k += p.length; } return o; }