-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathopfs.ts
More file actions
63 lines (58 loc) · 1.85 KB
/
opfs.ts
File metadata and controls
63 lines (58 loc) · 1.85 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
export async function writeBlob(url: string, blob: Blob): Promise<void> {
// only store models
if (!url.match('https://huggingface.co')) return;
try {
const root = await navigator.storage.getDirectory();
const dir = await root.getDirectoryHandle('piper', {
create: true,
});
const path = url.split('/').at(-1)!;
const file = await dir.getFileHandle(path, { create: true });
if (file.createWritable) {
const writable = await file.createWritable();
await writable.write(blob);
await writable.close();
} else if (self.WorkerGlobalScope) {
console.log(
'createWritable not supported, trying syncronous API with createSyncAccessHandle as we are a worker',
);
// use the synchronous write API to write to the file. Only works in web workers
const writer = await file.createSyncAccessHandle();
writer.write(await blob.arrayBuffer());
writer.close();
} else {
console.error(
"Cannot write to OPFS file using createWritable and we are not a worker, so can't use createSyncAccessHandle",
);
// Remove the empty file
await dir.removeEntry(path);
}
} catch (e) {
console.error(e);
}
}
export async function removeBlob(url: string) {
try {
const root = await navigator.storage.getDirectory();
const dir = await root.getDirectoryHandle('piper');
const path = url.split('/').at(-1)!;
const file = await dir.getFileHandle(path); // @ts-ignore
await file.remove();
} catch (e) {
console.error(e);
}
}
export async function readBlob(url: string): Promise<Blob | undefined> {
if (!url.match('https://huggingface.co')) return;
try {
const root = await navigator.storage.getDirectory();
const dir = await root.getDirectoryHandle('piper', {
create: true,
});
const path = url.split('/').at(-1)!;
const file = await dir.getFileHandle(path);
return await file.getFile();
} catch (e) {
return undefined;
}
}