-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
656 lines (557 loc) · 22.1 KB
/
main.ts
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
import { WebUI } from "./deno-webui/mod.ts";
import { dynamicImport, importString } from './dynamic-import/mod.ts';
import { encodeHex } from "https://deno.land/std@0.202.0/encoding/hex.ts";
import { decodeBase64, encodeBase64 } from "https://deno.land/std@0.206.0/encoding/base64.ts";
import { generateText, openai } from "npm:modelfusion";
setInterval(() => {
console.log(new Date().toTimeString());
}, 60 * 1000);
const DEBUG = Deno.env.get("DEV");
const OPENAI_KEY = Deno.env.get("OPENAI_KEY");
const GOOGLE_KEY = Deno.env.get("GOOGLE_KEY");
const GALAXY_PATH = `${Deno.env.get("HOME")}/.galaxy`;
const firstWindow = new WebUI({
'clearCache': DEBUG ? true : false,
'libPath': DEBUG ? './webui/dist/webui-2.dylib' : undefined,
});
// const secondWindow = new WebUI({
// })
// secondWindow.showBrowser.show('<html>second</html>');
firstWindow.setProfile('', '');
const KV_PATH = `${GALAXY_PATH}/meta.json`;
// --- Directory and Metadata functions ---
async function ensureGalaxyDirectory() {
try {
await Deno.mkdir(GALAXY_PATH, { recursive: true });
console.log(`Ensured directory exists: ${GALAXY_PATH}`);
} catch (error) {
if (error instanceof Deno.errors.AlreadyExists) {
console.log(`Directory already exists: ${GALAXY_PATH}`);
} else {
console.error(`Error creating directory: ${error.message}`);
throw error;
}
}
}
async function storeMetaData(date: string) {
await Deno.writeTextFile(KV_PATH, JSON.stringify({ lastDownloadDate: date }));
console.log(`Stored metadata with date: ${date}`);
}
async function getLastDownloadDate(): Promise<Date | null> {
try {
const kvContent = await Deno.readTextFile(KV_PATH);
const data = JSON.parse(kvContent);
console.log(`Last download date from metadata: ${data.lastDownloadDate}`);
return new Date(data.lastDownloadDate);
} catch (error) {
console.log("No previous download date found.");
return null;
}
}
// --- GitHub related functions ---
async function getLastCommitDate(user: string, repo: string): Promise<Date> {
const url = `https://api.github.com/repos/${user}/${repo}/commits/main`;
const response = await fetch(url, {
headers: {
'Accept': 'application/vnd.github.v3+json'
}
});
if (!response.ok) {
console.error(`Failed to fetch last commit date: ${response.statusText}`);
throw new Error(`Failed to fetch last commit date: ${response.statusText}`);
}
const data = await response.json();
return new Date(data.commit.committer.date);
}
async function loadFilesFromGitHubDirs(user: string, repo: string, dirList: string[]): Promise<MemoryFiles> {
const files = new Map();
const baseURL = `https://api.github.com/repos/${user}/${repo}/contents/`;
for (const dir of dirList) {
// Fetch the directory listing using GitHub API
const response = await fetch(baseURL + dir, {
headers: {
'Accept': 'application/vnd.github.v3+json'
}
});
if (!response.ok) {
throw new Error(`Failed to fetch directory ${dir}: ${response.statusText}`);
}
const contents: { name: string, download_url: string }[] = await response.json();
const fetchPromises: Promise<void>[] = contents.map(async (content) => {
if (content.download_url) { // Ensure it's a file, not another directory or other type
const fileResponse = await fetch(content.download_url);
if (!fileResponse.ok) {
throw new Error(`Failed to fetch ${content.download_url}: ${fileResponse.statusText}`);
}
const fileContent = await fileResponse.arrayBuffer(); //.text();
files.set(content.name, new Uint8Array(fileContent));
}
});
await Promise.all(fetchPromises);
}
return files;
}
async function fetchFilesFromGitHub() {
console.log("Fetching files from GitHub...");
return await loadFilesFromGitHubDirs('7flash',
'galaxy-dist',
['', 'assets', 'excalidraw-assets']);
}
type MemoryFiles =
Map<string, Uint8Array>;
async function saveFilesToLocal(files: MemoryFiles) {
await ensureGalaxyDirectory();
for (const [filename, content] of files.entries()) {
await Deno.writeFile(`${GALAXY_PATH}/${filename}`, content);
}
console.log(`Saved ${files.size} files to ${GALAXY_PATH}`);
}
// --- File handling functions ---
async function loadFilesFromLocalDirectory(): Promise<MemoryFiles> {
console.log("Loading files from local directory...");
return await loadFilesAsync([GALAXY_PATH]);
}
async function loadFilesAsync(pathList: string[]): Promise<MemoryFiles> {
const files = new Map();
for (const path of pathList) {
for await (const entry of Deno.readDir(path)) {
if (entry.isFile) {
const fileContent = await Deno.readFile(`${path}/${entry.name}`);
console.log(entry.name, fileContent.length);
files.set(entry.name, fileContent);
}
}
}
return files;
}
async function registerMacrosAsync(macrosDir: string): Promise<Map<string, string>> {
const registeredMacros = new Map<string, string>();
for await (const entry of Deno.readDir(macrosDir)) {
if (entry.isFile && entry.name.endsWith('.ts')) {
const scriptContent = await Deno.readTextFile(`${macrosDir}/${entry.name}`);
console.log(`Registering macro: ${entry.name}`, scriptContent);
registeredMacros.set(entry.name, scriptContent);
try {
const dit = `${JSON.stringify(scriptContent)}`;
// console.log('dit', dit);
const cit = `return window.ga.defaultDenoMacro({ "type": "text", "text": ${dit} })`;
// console.log('cit', cit)
const bit = await firstWindow.script(cit);
console.log('bit', bit);
} catch (err) {
console.error('register macro error', err);
}
}
}
return registeredMacros;
}
// Main Execution
(async () => {
const lastDownloadDate = await getLastDownloadDate();
let lastCommitDate;
try {
if (DEBUG) lastCommitDate = 0;
else lastCommitDate = await getLastCommitDate('7flash', 'galaxy-dist');
} catch (err) {
console.log('skip', err);
}
if (!lastDownloadDate || lastCommitDate > lastDownloadDate) {
const filesFromGitHub = await fetchFilesFromGitHub();
await saveFilesToLocal(filesFromGitHub);
const currentDate = new Date().toISOString();
await storeMetaData(currentDate);
}
async function getFiles(): Promise<Map<string, Uint8Array>> {
if (DEBUG) {
console.log("Debug mode: Loading local files only...");
return await loadFilesAsync([
'../dist', '../dist/assets', '../dist/excalidraw-assets'
]);
} else {
const lastDownloadDate = await getLastDownloadDate();
let lastCommitDate;
try {
lastCommitDate = await getLastCommitDate('7flash', 'galaxy-dist');
} catch (err) {
console.error('skip update', err);
}
if (!lastDownloadDate || lastCommitDate > lastDownloadDate) {
const filesFromGitHub = await fetchFilesFromGitHub();
await saveFilesToLocal(filesFromGitHub);
const currentDate = new Date().toISOString();
await storeMetaData(currentDate);
}
return await loadFilesFromLocalDirectory();
}
}
const files = await getFiles();
console.log(`Loaded ${files.size} files.`);
firstWindow.setFileHandler(({ pathname }) => {
if (pathname.startsWith("/public")) {
pathname = pathname.replace("/public", "");
}
const filename = pathname.substring(pathname.lastIndexOf('/') + 1);
if (files.has(filename)) {
console.log('has ', filename, files.get(filename).length);
return files.get(filename);
} else {
console.error(`Unknown file request: ${filename}`);
if (filename.endsWith('.jpg') || filename.endsWith('.png')) {
const engineId = 'stable-diffusion-xl-1024-v1-0'
const apiHost = Deno.env.get('API_HOST') ?? 'https://api.stability.ai'
const apiKey = Deno.env.get('STABILITY_API_KEY')
if (!apiKey) throw new Error('Missing Stability API key.')
async function anit() {
const response = await fetch(
`${apiHost}/v1/generation/${engineId}/text-to-image`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
text_prompts: [
{
text: `An image on website with name "${filename}"`,
},
],
cfg_scale: 7,
height: 1024,
width: 1024,
steps: 30,
samples: 1,
}),
}
)
if (!response.ok) {
throw new Error(`Non-200 response: ${await response.text()}`)
}
interface GenerationResponse {
artifacts: Array<{
base64: string
seed: number
finishReason: string
}>
}
const responseJSON = (await response.json()) as GenerationResponse
responseJSON.artifacts.forEach((image, index) => {
// Deno.writeTextFile(filename, image.base64);
// fs.writeFileSync(
// `./out/v1_txt2img_${index}.png`,
// Buffer.from(image.base64, 'base64')
// )
// Convert Base64 string to a Buffer
// console.log('image', image.base64);
// const buffer = Deno.Buffer.from(image.base64, 'base64');
// Convert the Buffer to Uint8Array
// const uint8Array = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.length);
// console.log(image.base64.substr(0, 10));
const manit = decodeBase64(image.base64)
// const mit = Buffer.from(image.base64, 'base64');
files.set(filename, manit);
console.log('generated ' + filename);
})
}
anit().then(console.log).catch(console.error);
}
throw 'Unknown file ' + filename;
}
});
firstWindow.bind('setMemoryFile', async (e: WebUI.Event) => {
try {
// const bit = e.arg.string(0);
const cit = e.arg.string(0);
const lit = e.arg.string(1);
const rit = e.arg.string(2);
const messageBuffer = new TextEncoder().encode(cit);
const hashBuffer = await crypto.subtle.digest("SHA-256", messageBuffer);
const bit = encodeHex(hashBuffer);
const acit = new TextEncoder().encode(cit);
// const hasher = createHash("md5");
// hasher.update(cit);
// const bit = hasher.toString();
files.set(bit + '.' + lit, acit);
console.log(new Date(), 'setMemoryFile', bit, cit.length, rit);
await firstWindow.script(`return window.webuiCallbacks["${rit}"]("${bit}")`);
} catch (err) {
console.error('setMemoryFile', err);
firstWindow.script(`ea.setToast({ message: "${err.toString()}" })`);
}
});
firstWindow.bind('executeDeno', (e: WebUI.Event) => {
async function nov16() {
try {
let rawCode = e.arg.string(0);
console.log('rawCode ', rawCode);
const input = e.arg.string(1);
console.log('input ', input);
const taskId = e.arg.string(2);
console.log('taskId ', taskId);
let output = JSON.stringify({});
try {
output = e.arg.string(3);
} catch (e) {
console.error('ignore', e);
}
console.log('output ', output);
let label = '';
try {
label = e.arg.string(4);
} catch (e) {
console.error('ignore label', e);
}
// Extract function details from the rawCode
const functionNameMatch = rawCode.match(/(async\s*)?function (\w+)/);
if (!functionNameMatch) {
throw new Error('Invalid function format in rawCode.');
}
const asyncKeyword = functionNameMatch[1] || '';
const functionName = functionNameMatch[2];
rawCode = rawCode.replace(/\s+/g, ' ');
// Modify rawCode
rawCode = rawCode.replace(/(async\s*)?function \w+/, `${asyncKeyword}function ${functionName}`);
rawCode = `export default ${rawCode}`;
rawCode = rawCode.replace(/import\(/g, 'dynamicImport(');
// Use importString to get the module, passing dynamicImport as a parameter
const { default: fn } = await importString(rawCode, {
parameters: {
dynamicImport: (moduleName) => dynamicImport(moduleName, {
force: true,
}),
label: label,
input: JSON.parse(input),
output: JSON.parse(output),
firstWindow,
galaxyPath: GALAXY_PATH,
modules: {},
decodeBase64,
encodeBase64,
apiKey: OPENAI_KEY,
encodeHex,
googleKey: GOOGLE_KEY,
}
});
console.log('begin execution', new Date())
const result = await fn();
console.log('completed execution', new Date());
// console.log("result executeDeno", result);
const response = { result };
const serializedResponse = JSON.stringify(response)
.replace(/\\/g, '\\\\') // Escape backslashes
.replace(/'/g, "\\'") // Escape single quotes
.replace(/"/g, '\\"') // Escape double quotes
.replace(/`/g, '\\`') // Escape backticks
.replace(/\$/g, '\\$'); // Escape dollar signs (for template literals)
await firstWindow.script(`return window.webuiCallbacks["${taskId}"]('${serializedResponse}')`);
} catch (err) {
console.error('executeDeno error', err);
firstWindow.run(`ea.setToast({ message: "${err.toString()}" })`);
}
}
nov16().catch(console.error);
return 'ok';
});
// note, it's temporary binding until the issue resolved
// https://github.com/webui-dev/webui/issues/231
firstWindow.bind('saveScene', async (inputData) => {
try {
let { sceneName, sceneData } = JSON.parse(inputData.data);
// console.log(sceneName, sceneData);
const kvBlob = await import('https://deno.land/x/kv_toolbox@0.0.4/blob.ts');
const kv = await Deno.openKv();
const blob = new TextEncoder().encode(sceneData);
// await kvBlob.set(kv, ["layers", sceneName], blob);
// await kv.close();
// await new Promise(resolve => setTimeout(resolve, 1000));
// const blob = '';
return { success: true, } // data: `saved size ${blob.length}` };
} catch (error) {
return { success: false, error: error.message };
}
});
firstWindow.bind('executePython', async (pythonCode: string) => {
if (typeof pythonCode !== 'string') {
return { success: false, error: 'Invalid Python code provided' };
}
const process = Deno.run({
cmd: ["python", "-c", pythonCode],
stdout: "piped",
stderr: "piped"
});
try {
const { code } = await process.status();
const [rawOutput, rawError] = await Promise.all([process.output(), process.stderrOutput()]);
const errorStr = new TextDecoder().decode(rawError);
const outputStr = new TextDecoder().decode(rawOutput);
if (code !== 0 || errorStr) {
return {
success: false,
error: `Python process exited with code ${code}. Error: ${errorStr.trim()}`
};
}
return { success: true, data: outputStr.trim() };
} catch (error) {
return { success: false, error: `Execution error: ${error.message}` };
} finally {
// Clean up resources
process.stdout.close();
process.stderr.close();
process.close();
}
});
const openNow = async () => {
await firstWindow.script(`
async function waitForIt(selector) {
while (true) {
const it = document.querySelector(selector);
if (it) {
return it;
} else {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
}
async function doIt() {
while (!window.ea) {
await new Promise(resolve => setTimeout(resolve, 500));
}
ea.updateScene({
elements: [{...window.convertToExcalidrawElements([{ type: 'frame', name: 'now', x: 0, y: 0, width: 100, height: 100 }])[0], customData: { macros: { save: true, open: true, publish: true } }}]
})
ea.updateScene({ appState: { selectedElementIds: {[ea.getSceneElements()[0].id]: true} } })
await waitForIt('[data-testid="macro-button-open"]').then(it => it.click())
await waitForIt('[data-testid="modal-input"]').then(it => {
it.value = 'now';
it.dispatchEvent(new Event('change', { bubbles: true }));
})
await waitForIt('[data-testid="modal-button"]').then(it => it.click())
ea.scrollToContent();
}
doIt();
`);
}
try {
await firstWindow.show('./dist/index.html');
// TODO: load macros from macros folder & register each as deno macro with window.ga.addMacro wrapped into defaultDenoMacro
// await openNow();
// TODO:
// -- saving elements of each frame into separate git-like storage object represented by json diff plus base excalidraw snapshot
// -- those elements outside of any frame - save them into "now" frame
// -- when frame includes other frames inside of it, only save its frame element but not nested elements (transclusion)
// -- also when saving "now" frame save all opened frames positions but not their nested elements
// TODO:
// -- by default should open INDEX frame with listing and comments of others auto uploaded unless already present
// -- (listen by frame with name but not loaded)
// when pressing open on a frame which has a name - it should not invoke opening window because it already has name - also will simplify openNow
// TODO:
// -- use special symbol (option+O) like ø543c-321 inside of any string to reference links to other text elements by beginning of their ids
// -- in this case macros can compute full content of text element like save macro can get full file from its functions individually editable
// -- and bash macro can execute command with given parameters
setInterval(() => {
console.log("firstWindow isShown", firstWindow.isShown);
if (!firstWindow.isShown) {
try {
// firstWindow.clean();
firstWindow.close();
firstWindow.show('./dist/index.html');
// openNow();
} catch (err) {
console.error("reopen", err);
}
}
}, 5000);
Deno.addSignalListener(
"SIGTERM",
() => {
firstWindow.close();
}
);
// TODO: strip away all comments in macros files
// TODO: strip away everything before function definition - there can be unit test running
while (true) {
const ready = await firstWindow.script(`return window.ga != null;`);
if (ready) {
break;
} else {
await new Promise(resolve => setTimeout(resolve, 1000));
}
registerMacrosAsync(`./macros`);
}
} catch (err) {
console.error('err', err);
}
console.assert(firstWindow.isShown, true)
let mux = false;
async function saveScene(sceneName) {
if (mux) return;
mux = true;
try {
// const globalFrame = JSON.parse(await firstWindow.script(`return window.convertToExcalidrawElements([{ type: 'frame' }])[0]`));
// await firstWindow.script(
// `ea.updateScene({ elements: [
// ...ea.getSceneElements().filter(it => it.id && it.id != globalFrame.id).map(it => {
// it.frameId = '${globalFrame.id}';
// return it;
// }), ${JSON.stringify(globalFrame)}]
// })`
// )
// await firstWindow.script(`const globalFrame = ${JSON.stringify(globalFrame)};
// return ga.executeMacro('save', globalFrame, globalFrame)`)
let bufferSize = await firstWindow.script('return JSON.stringify(window.ea.getSceneElements()).length.toString();');
bufferSize *= 4;
bufferSize += 4;
const els = JSON.parse(await firstWindow.script(`return JSON.stringify(window.ea.getSceneElements());`, { bufferSize: Number.parseInt(bufferSize) + 1 }));
const encoder = new TextEncoder();
const fileIds = [...new Set(els.filter(function(it) { return it.type === 'image'; }).map(function(it) { return it.fileId; }))];
// TODO: load macros from macros folder & register each as deno macro with window.ga.addMacro wrapped into defaultDenoMacro
for (var i = 0; i < fileIds.length; i++) {
var fileId = fileIds[i];
let existingOne = false;
try {
await Deno.stat(GALAXY_PATH + '/' + fileId + '.png');
existingOne = true;
} catch (_) { }
if (existingOne) continue;
try {
let bufferSize = await firstWindow.script('return window.ea.getFiles()["' + fileId + '"].dataURL.length.toString();');
bufferSize *= 4;
bufferSize += 4;
var fileDataURL = await firstWindow.script('return window.ea.getFiles()["' + fileId + '"].dataURL;', { bufferSize: Number.parseInt(bufferSize) + 1 });
var base64Index = fileDataURL.indexOf(';base64,');
if (base64Index === -1) {
throw new Error('Base64 data not found in data URL');
}
var base64Data = fileDataURL.substring(base64Index + 8);
var decodedData = decodeBase64(base64Data);
var fileType = fileDataURL.substring(11, base64Index);
await Deno.writeFile(GALAXY_PATH + '/' + fileId + '.' + fileType, decodedData);
console.log('auto save', fileId);
} catch (error) {
console.error('Error saving image with fileId:', fileId, error);
}
}
var sceneData = JSON.stringify({ elements: els.filter(it => it.name != 'now') }, null, 2);
await Deno.writeTextFile(GALAXY_PATH + '/' + sceneName + '.json', sceneData);
console.log('auto save', sceneName);
} catch (err) {
console.error('saveScene', err);
}
mux = false;
}
function decodeBase64(base64) {
const binaryString = window.atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
setInterval(() => {
saveScene('now')
.catch(console.error);
}, 60 * 1000);
// TODO: show contextual notes in bottom right
await WebUI.wait();
})();