-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmediaAssetsManager.js
More file actions
339 lines (313 loc) · 11.4 KB
/
Copy pathmediaAssetsManager.js
File metadata and controls
339 lines (313 loc) · 11.4 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
'use strict';
const fs = require('fs');
const path = require('path');
const {
MEDIA_ASSET_PROFILES,
archToMediaProfile,
listAssetsForProfile,
} = require('./mediaAssetsCatalog');
function downloadHeaders(url, hfToken) {
const headers = { 'User-Agent': 'guIDE-media-assets' };
const token = hfToken || process.env.HF_TOKEN;
if (token && /huggingface\.co/i.test(url)) {
headers.Authorization = `Bearer ${token}`;
}
return headers;
}
function http401Hint(url) {
if (/huggingface\.co/i.test(url)) {
return ' Add your Hugging Face token in Settings → Media (or set HF_TOKEN).';
}
return '';
}
async function downloadFileWithRetry(url, dest, { onProgress, expectedBytes, retries = 3, hfToken } = {}) {
let lastErr;
for (let attempt = 0; attempt < retries; attempt++) {
try {
return await downloadFile(url, dest, { onProgress, expectedBytes, hfToken });
} catch (err) {
lastErr = err;
if (attempt < retries - 1) {
const isRateLimit = /HTTP 429/i.test(String(err.message));
const delayMs = isRateLimit ? 30000 * (attempt + 1) : 2000 * (attempt + 1);
console.warn(`[MediaAssets] Download retry ${attempt + 2}/${retries} for ${path.basename(dest)}: ${err.message}`);
await new Promise((r) => setTimeout(r, delayMs));
}
}
}
throw lastErr;
}
async function downloadFileWithMirrorRetry(urls, dest, opts = {}) {
const list = (Array.isArray(urls) ? urls : [urls]).filter(Boolean);
let lastErr;
for (let i = 0; i < list.length; i++) {
const url = list[i];
try {
return await downloadFileWithRetry(url, dest, opts);
} catch (err) {
lastErr = err;
const is401 = /HTTP 401/i.test(String(err.message));
if (is401 && i === list.length - 1) {
throw new Error(`${err.message}.${http401Hint(url)}`);
}
if (i < list.length - 1) {
console.warn(`[MediaAssets] Mirror fallback for ${path.basename(dest)}: ${err.message}`);
}
}
}
throw lastErr;
}
async function downloadFile(url, dest, { onProgress, expectedBytes, hfToken } = {}) {
const { Readable } = require('stream');
fs.mkdirSync(path.dirname(dest), { recursive: true });
const tmp = `${dest}.part`;
if (fs.existsSync(dest)) {
const got = fs.statSync(dest).size;
if (!expectedBytes || got >= expectedBytes * 0.95) return dest;
}
let startAt = 0;
if (fs.existsSync(tmp)) {
startAt = fs.statSync(tmp).size;
if (expectedBytes && startAt >= expectedBytes * 0.95) {
if (fs.existsSync(dest)) fs.unlinkSync(dest);
fs.renameSync(tmp, dest);
return dest;
}
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 60 * 60 * 1000);
let received = startAt;
let lastPct = -1;
try {
const headers = downloadHeaders(url, hfToken);
if (startAt > 0) headers.Range = `bytes=${startAt}-`;
const res = await fetch(url, {
headers,
redirect: 'follow',
signal: controller.signal,
});
if (startAt > 0 && res.status === 416) {
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
startAt = 0;
return downloadFile(url, dest, { onProgress, expectedBytes, hfToken });
}
if (!res.ok && res.status !== 206) {
throw new Error(`Download failed HTTP ${res.status}: ${url}`);
}
if (startAt > 0 && res.status === 200) {
if (fs.existsSync(tmp)) fs.unlinkSync(tmp);
startAt = 0;
received = 0;
}
const contentLen = Number(res.headers.get('content-length') || 0);
const total = expectedBytes || (startAt > 0 ? startAt + contentLen : contentLen);
const file = fs.createWriteStream(tmp, { flags: received > 0 ? 'a' : 'w' });
await new Promise((resolve, reject) => {
file.on('error', reject);
file.on('open', resolve);
});
for await (const chunk of Readable.fromWeb(res.body)) {
received += chunk.length;
if (!file.write(chunk)) {
await new Promise((resolve) => file.once('drain', resolve));
}
if (onProgress && total > 0) {
const pct = Math.floor((received / total) * 100);
if (pct >= lastPct + 10) {
lastPct = pct;
onProgress({ received, total, file: path.basename(dest) });
}
}
}
await new Promise((resolve, reject) => {
file.end(() => resolve());
file.on('error', reject);
});
if (expectedBytes && received < expectedBytes * 0.95) {
throw new Error(
`Download incomplete ${path.basename(dest)}: ${received} < ${expectedBytes}`,
);
}
if (fs.existsSync(dest)) fs.unlinkSync(dest);
fs.renameSync(tmp, dest);
return dest;
} catch (err) {
throw err;
} finally {
clearTimeout(timeout);
}
}
class MediaAssetsManager {
constructor(options = {}) {
this.userDataPath = options.userDataPath || require('os').tmpdir();
this.resourcesPath = options.resourcesPath || null;
this.rootDir = options.rootDir || __dirname;
this.onProgress = options.onProgress || null;
this._bundledDir = this.resourcesPath
? path.join(this.resourcesPath, 'media-assets')
: path.join(this.rootDir, 'resources', 'media-assets');
this._cacheDir = path.join(this.userDataPath, 'media-assets');
this._inflight = new Map();
if (!fs.existsSync(this._bundledDir)) {
console.warn(`[MediaAssets] Bundled dir missing: ${this._bundledDir}`);
} else {
console.log(`[MediaAssets] Bundled dir: ${this._bundledDir}`);
}
}
_hasBundled(relPath) {
const b = path.join(this._bundledDir, relPath);
return fs.existsSync(b) || fs.existsSync(`${b}.parts.json`);
}
_reassembleFromParts(srcBase, destPath) {
return new Promise((resolve, reject) => {
const metaPath = `${srcBase}.parts.json`;
if (!fs.existsSync(metaPath)) return reject(new Error(`missing parts meta for ${srcBase}`));
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
fs.mkdirSync(path.dirname(destPath), { recursive: true });
if (fs.existsSync(destPath)) fs.unlinkSync(destPath);
const out = fs.createWriteStream(destPath);
let i = 0;
const writeNext = () => {
if (i >= meta.chunks) {
out.end(() => resolve(destPath));
return;
}
const chunkPath = `${srcBase}.part${String(i).padStart(3, '0')}`;
if (!fs.existsSync(chunkPath)) {
out.destroy();
reject(new Error(`missing chunk ${chunkPath}`));
return;
}
const inp = fs.createReadStream(chunkPath);
inp.on('error', reject);
inp.on('end', () => { i++; writeNext(); });
inp.pipe(out, { end: false });
};
out.on('error', reject);
writeNext();
});
}
_assetPath(relPath) {
const bundled = path.join(this._bundledDir, relPath);
if (fs.existsSync(bundled)) return bundled;
const cached = path.join(this._cacheDir, relPath);
if (fs.existsSync(cached)) return cached;
return null;
}
async materializeAsset(relPath, onProgress) {
const existing = this._assetPath(relPath);
if (existing) return existing;
const bundled = path.join(this._bundledDir, relPath);
const dest = path.join(this._cacheDir, relPath);
if (fs.existsSync(`${bundled}.parts.json`)) {
if (onProgress) onProgress({ phase: 'assemble', file: path.basename(relPath) });
console.log(`[MediaAssets] Assembling ${relPath} from installer chunks…`);
await this._reassembleFromParts(bundled, dest);
console.log(`[MediaAssets] Ready ${relPath}`);
if (onProgress) onProgress({ phase: 'done', file: path.basename(relPath) });
return dest;
}
return null;
}
async materializeProfile(profileId, onProgress) {
if (this._inflight.has(`mat:${profileId}`)) return this._inflight.get(`mat:${profileId}`);
const job = (async () => {
for (const asset of listAssetsForProfile(profileId)) {
await this.materializeAsset(asset.relPath, onProgress);
}
})().finally(() => this._inflight.delete(`mat:${profileId}`));
this._inflight.set(`mat:${profileId}`, job);
return job;
}
getProfileStatus(profileId) {
const profile = MEDIA_ASSET_PROFILES[profileId];
if (!profile) return { profileId, ready: false, assets: [] };
const assets = profile.assets.map((asset) => {
const resolved = this._assetPath(asset.relPath);
const bundled = this._hasBundled(asset.relPath);
return {
id: asset.id,
relPath: asset.relPath,
ready: !!resolved || bundled,
path: resolved,
bytes: asset.bytes,
};
});
return {
profileId,
label: profile.label,
ready: assets.every((a) => a.ready),
assets,
};
}
resolveAux(arch, modelType) {
const profileId = archToMediaProfile(arch, modelType);
if (!profileId) return null;
const profile = MEDIA_ASSET_PROFILES[profileId];
const byId = Object.fromEntries(
profile.assets.map((a) => [a.id, this._assetPath(a.relPath)]).filter(([, p]) => p),
);
const aux = {};
for (const [key, assetId] of Object.entries(profile.auxKeys || {})) {
if (byId[assetId]) aux[key] = byId[assetId];
}
if (aux.llm) aux.clip = aux.llm;
return { profileId, ...aux };
}
async ensureForModel(arch, modelType, onProgress) {
return this.ensureForModelBackground(arch, modelType, onProgress);
}
ensureForModelBackground(arch, modelType, onProgress) {
const profileId = archToMediaProfile(arch, modelType);
if (!profileId) return Promise.resolve(this.resolveAux(arch, modelType));
if (this._inflight.has(profileId)) return this._inflight.get(profileId);
const job = this.ensureProfile(profileId, onProgress)
.then(() => this.resolveAux(arch, modelType))
.finally(() => this._inflight.delete(profileId));
this._inflight.set(profileId, job);
return job;
}
async _downloadAsset(asset, progress) {
const key = `asset:${asset.relPath}`;
if (this._inflight.has(key)) return this._inflight.get(key);
const dest = path.join(this._cacheDir, asset.relPath);
const sizeMb = asset.bytes ? Math.round(asset.bytes / 1e6) : '?';
const job = (async () => {
console.log(`[MediaAssets] Downloading ${asset.relPath} (~${sizeMb}MB)`);
if (progress) progress({ phase: 'start', asset: asset.id, file: path.basename(asset.relPath), total: asset.bytes || 0 });
let lastLogPct = -1;
await downloadFile(asset.url, dest, {
expectedBytes: asset.bytes || undefined,
onProgress: ({ received, total, file }) => {
const t = total || asset.bytes || 0;
const pct = t > 0 ? Math.floor((received / t) * 100) : 0;
if (pct >= lastLogPct + 10) {
lastLogPct = pct;
console.log(`[MediaAssets] ${file}: ${pct}%`);
}
},
});
if (progress) progress({ phase: 'done', asset: asset.id, file: path.basename(asset.relPath) });
return dest;
})().finally(() => this._inflight.delete(key));
this._inflight.set(key, job);
return job;
}
async ensureProfile(profileId, onProgress) {
const progress = onProgress || this.onProgress;
await this.materializeProfile(profileId, progress);
for (const asset of listAssetsForProfile(profileId)) {
if (this._assetPath(asset.relPath)) continue;
await this._downloadAsset(asset, progress);
}
return this.getProfileStatus(profileId);
}
}
module.exports = {
MediaAssetsManager,
downloadFile,
downloadFileWithRetry,
downloadFileWithMirrorRetry,
downloadHeaders,
http401Hint,
};