File size: 7,426 Bytes
8f9eb25
 
 
f916d7c
 
 
 
 
 
 
 
 
 
 
 
8f9eb25
 
 
f916d7c
8f9eb25
 
 
 
f916d7c
 
1c59f51
 
f916d7c
1c59f51
 
 
f916d7c
1c59f51
2d03531
1c59f51
 
 
 
 
 
 
 
 
 
8f9eb25
f916d7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f9eb25
 
f916d7c
 
 
 
 
 
 
 
 
 
 
8f9eb25
f916d7c
 
 
 
 
 
8f9eb25
 
f916d7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f9eb25
 
 
 
 
 
 
 
 
 
 
 
 
 
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// 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;
}

/** A local folder laid out like the Hub repo (Node; used by the tests). */
export class LocalFiles {
  constructor(root) { this.root = root.replace(/\/$/, ""); }
  path(p) { return `${this.root}/${p}`; }
  async json(p) { const fs = await import("node:fs/promises"); return JSON.parse(await fs.readFile(this.path(p), "utf8")); }
  async bytes(p, onProgress) {
    const fs = await import("node:fs/promises"); const b = new Uint8Array(await fs.readFile(this.path(p)));
    onProgress?.({ file: p, loaded: b.length, total: b.length, fromCache: true }); return b;
  }
}

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; }