-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.html
274 lines (231 loc) · 11.4 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Bulk File Transformer</title>
</head>
<body>
<style>
body {
font-family: monospace;
}
* {
font-family: inherit;
}
</style>
<h1>Bulk File Transformer</h1>
<div style="max-height: 150px; overflow-y: auto; border: 1px solid grey; margin-bottom: 0.5rem; padding: 0.5rem; background:#ececec;">
<p style="margin-top:0;">This is a browser-based tool that allows you to define a custom JavaScript function which is used to bulk-convert a folder of files (using the new <a target="_blank" href="https://web.dev/file-system-access/">File System Access API</a>).</p>
<p>Your data folder should contain an '<b>input</b>' folder (filled with files and/or sub-folders) and an empty '<b>output</b>' folder. Your data folder can <i>optionally</i> contain '<b>transform.js</b>' which defines an async function called 'transform' that takes as input an object like this: <b>{fileHandle, path, i, n}</b> (the input file handle, the folder path to that file, the file index, and total number of files) and returns an object like this: <b>{blob, name}</b> (or an array of these objects, if each input should be converted into multiple output files). If the output name contains forward-slashes, sub-folders are made in the output folder to match the given path. If the data folder doesn't contain transform.js, you can use the code editor below to write the transform function.</p>
<p>The files in the input folder will be copied, transformed, and placed into the output folder with the new filenames as specified by the transform function. Note that your transform function is executed in Web Workers, using as many threads as you like (specified below).</p>
<p>The code for this web app is at <a href="https://github.com/josephrocca/bulk-file-transformer" target="_blank">@josephrocca/bulk-file-transformer</a> on Github.</p>
</div>
<button id="dataFolderChooserBtn" style="font-weight:bold;" onclick="window.showDirectoryPicker().then(handleDataFolderUpdate)">choose data folder</button>
<hr>
threads: <input type=number id=numThreadsEl value="1" style="width:60px;"> <script>numThreadsEl.value=navigator.hardwareConcurrency</script>
<button onclick="start()">transform data</button>
<div style="display: flex;align-items: center;margin-top: 0.5rem;">
<input id="firstNFilesOnlyCheckbox" type="checkbox"> first <input type="number" value="50" id="firstNFilesInput" style="width: 50px; text-align: center; margin: 0 0.25rem;"> files only (for testing)
</div>
<hr>
<progress id="generationProgressEl" style="width:100%;" value="0" max="100"></progress>
<div id="statusEl"></div>
<div id="errorLogEl"></div>
<br><br>
<button id="saveChangesBtn" disabled>save changes to <b>transform.js</b></button>
<div id="code-editor" style="border: 1px solid grey; margin-bottom:20rem;"></div>
<script src="./codemirror/codemirror6-bundle-may-2021.js"></script>
<script src="./codemirror/setup.js"></script>
<script src="./greenlet-edited.js"></script>
<script>
if(!window.showDirectoryPicker) {
alert("Your browser doesn't support the File System Access API. Chrome and Edge both have full support, and other browsers should soon follow.");
}
async function handleDataFolderUpdate(dataFolder) {
window.dataFolder = dataFolder;
let transformJsFile = await window.dataFolder.getFileHandle("transform.js", { create: true });
let transformJsText = await transformJsFile.getFile().then(f => f.text());
if(transformJsText) {
updateEditorWithText(transformJsText);
saveChangesBtn.disabled = true;
thereAreUnsavedChanges = false;
}
dataFolderChooserBtn.style.fontWeight = "normal";
}
async function recursiveFileCounter(directory) {
let count = 0;
for await (const [name, handle] of directory.entries()) {
count += handle.kind==="directory" ? await recursiveFileCounter(handle) : 1;
}
return count;
}
async function start() {
if(!window.dataFolder) return alert("please choose a data folder first");
try {
eval(`function foobar289d29fk79X85d322asfj20() {${window.editorView.state.doc.toString()}}`);
} catch(e) {
alert(`There's a syntax error in your transform code: ${e.stack}`);
return;
}
errorLogEl.innerHTML = "";
statusEl.innerHTML = "setting up...";
generationProgressEl.value = 0;
let inputFilesFolder = await window.dataFolder.getDirectoryHandle("input");
let outputFilesFolder = await window.dataFolder.getDirectoryHandle("output");
let maxNumberOfInputFilesToProcess = firstNFilesOnlyCheckbox.checked ? Number(firstNFilesInput.value) : Infinity;
// let numInputs = 0;
// for await (let k of inputFilesFolder.keys()) {
// numInputs++;
// if(maxNumberOfInputFilesToProcess && numInputs === maxNumberOfInputFilesToProcess) break;
// }
let numInputs = await recursiveFileCounter(inputFilesFolder);
numInputs = Math.min(numInputs, maxNumberOfInputFilesToProcess);
console.log(`${numInputs} files to process.`);
let editorText = editorView.state.doc.toString();
let transformFns = [];
let transformFnsBusyFlags = [];
let workerCount = Math.min(numInputs, Number(numThreadsEl.value));
for(let i = 0; i < workerCount; i++) {
let fn = greenletEdited(`
let __folderHandleCache = {};
async function __createOrGetFolderPath(rootFolderHandle, folderNames) {
let pathString = folderNames.join("/");
if(__folderHandleCache[pathString]) {
return __folderHandleCache[pathString];
}
let lastFolder = rootFolderHandle;
for(let folderName of folderNames) {
if(folderName.includes("..") || folderName == "..") throw new Error(\`invalid folder name: \${folderName} in path: \${pathString}\`);
lastFolder = await lastFolder.getDirectoryHandle(folderName, {create: true});
}
__folderHandleCache[pathString] = lastFolder;
return lastFolder;
}
async function __transformWrapper(rootFolderHandle, data) {
try {
let outputData = await transform(data);
if(!Array.isArray(outputData)) {
outputData = [outputData];
}
for(let outputDatum of outputData) {
let filename = outputDatum.name;
let outputFolder = rootFolderHandle;
if(filename.startsWith("/") || filename.includes("//")) throw new Error("File name cannot start with a forward-slash or contain more than one consecutive forward-slash.");
let pathArr = filename.split("/");
if(pathArr.length > 1) {
outputFolder = await __createOrGetFolderPath(rootFolderHandle, pathArr.slice(0, -1));
filename = pathArr[pathArr.length-1];
}
let outputFile = await outputFolder.getFileHandle(filename, { create: true });
let writable = await outputFile.createWritable();
await outputDatum.blob.stream().pipeTo(writable);
}
return true;
} catch(e) {
console.error(e);
return false;
}
};
${editorText}
`);
fn.isBusy = false;
transformFns.push(fn);
}
function getAvailableWorker() {
for(let fn of transformFns) {
if(!fn.isBusy) {
fn.isBusy = true;
return fn;
}
}
return false;
}
function sleep(ms) {
return new Promise(r => setTimeout(r, ms));
}
let completedCount = 0;
function updateStatus() {
generationProgressEl.value = Math.round(100*completedCount/numInputs);
let timeRemainingText = estimatedSecondsRemaining ? (estimatedSecondsRemaining/60 > 60 ? `(~${(estimatedSecondsRemaining/3600).toFixed(1)} hours remaining)` : `(~${(estimatedSecondsRemaining/60).toFixed(1)} mins remaining)`) : "";
statusEl.innerHTML = completedCount < numInputs ? `transforming... ${completedCount}/${numInputs} ${timeRemainingText}` : "<b>finished! 🥳</b>";
}
let estimatedSecondsRemaining;
let lastCompletedCount = 0;
let lastEstimateCalculationTime = performance.now();
let timeRemainingInterval = setInterval(() => {
let filesProcessedSinceEstimateUpdate = (completedCount-lastCompletedCount);;
if(filesProcessedSinceEstimateUpdate < 10) {
return;
}
let filesProcessedPerSecond = filesProcessedSinceEstimateUpdate / ((performance.now() - lastEstimateCalculationTime)/1000)
estimatedSecondsRemaining = (numInputs-completedCount) / filesProcessedPerSecond;
lastCompletedCount = completedCount;
lastEstimateCalculationTime = performance.now();
}, 1000);
// let i = 0;
// for await (const fileHandle of inputFilesFolder.values()) {
// updateStatus();
// if(i === maxNumberOfInputFilesToProcess) {
// break;
// }
// let transformFn;
// while(true) {
// transformFn = getAvailableWorker();
// if(transformFn) break;
// await sleep(1);
// }
// // now that we have an available worker, dispatch it (note the lack of `await` here):
// (async function(fileHandle, i){
// let success = await transformFn(outputFilesFolder, {fileHandle, i, n:numInputs});
// if(!success) {
// console.error(`Failed to transform ${fileHandle.name}.`);
// }
// transformFn.isBusy = false;
// completedCount++;
// })(fileHandle, i++);
// }
let i = 0;
async function recursivelyProcessFiles(directory, path) {
for await (const [name, handle] of directory.entries()) {
if(handle.kind === "directory") {
let p = path.slice(0);
p.push(name);
await recursivelyProcessFiles(handle, p);
continue;
}
updateStatus();
if(i === maxNumberOfInputFilesToProcess) {
break;
}
let transformFn;
while(true) {
transformFn = getAvailableWorker();
if(transformFn) break;
await sleep(1);
}
// now that we have an available worker, dispatch it (note the lack of `await` here):
(async function(fileHandle, i, path){
let success = await transformFn(outputFilesFolder, {fileHandle, i, n:numInputs, path});
if(!success) {
console.error(`Failed to transform ${fileHandle.name}.`);
errorLogEl.innerHTML = "<b style='color:red;'>One or more errors have occurred during processing. Please open the browser console (ctrl+shift+j) to see the error messages.</b>";
}
transformFn.isBusy = false;
completedCount++;
})(handle, i++, path.slice(0));
}
}
await recursivelyProcessFiles(inputFilesFolder, []);
updateStatus();
while(completedCount < numInputs) {
await sleep(10);
}
updateStatus();
clearInterval(timeRemainingInterval);
window.greenletWorkers.forEach(w => w.terminate());
window.greenletWorkers = [];
}
</script>
</body>
</html>