feat: improve workflow performance (#7539)

This commit is contained in:
darkskygit 2024-07-18 10:37:27 +00:00
parent 9440dc8dd5
commit 585003640f
No known key found for this signature in database
GPG Key ID: 97B7D036B1566E9D

View File

@ -44,6 +44,38 @@ export function createChatSession({
}); });
} }
async function resizeImage(blob: Blob | File): Promise<Blob | null> {
let src = '';
try {
src = URL.createObjectURL(blob);
const img = new Image();
img.src = src;
await new Promise(resolve => {
img.onload = resolve;
});
const canvas = document.createElement('canvas');
// keep aspect ratio
const scale = Math.min(1024 / img.width, 1024 / img.height);
canvas.width = Math.floor(img.width * scale);
canvas.height = Math.floor(img.height * scale);
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
return new Promise(resolve =>
canvas.toBlob(blob => resolve(blob), 'image/jpeg', 0.8)
);
}
} catch (e) {
console.error(e);
} finally {
if (src) URL.revokeObjectURL(src);
}
return null;
}
async function createSessionMessage({ async function createSessionMessage({
docId, docId,
workspaceId, workspaceId,
@ -77,17 +109,17 @@ async function createSessionMessage({
attachment => typeof attachment === 'string' attachment => typeof attachment === 'string'
) as [string[], (Blob | File)[]]; ) as [string[], (Blob | File)[]];
options.attachments = stringAttachments; options.attachments = stringAttachments;
options.blobs = await Promise.all( options.blobs = (
blobs.map(async blob => { await Promise.all(
if (blob instanceof File) { blobs.map(resizeImage).map(async blob => {
return blob; const file = await blob;
} else { if (!file) return null;
return new File([blob], sessionId, { return new File([file], sessionId, {
type: blob.type, type: file.type,
}); });
}
}) })
); )
).filter(Boolean) as File[];
} }
if (retry) if (retry)
return { return {