-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtool.ts
More file actions
875 lines (824 loc) · 27.9 KB
/
Copy pathtool.ts
File metadata and controls
875 lines (824 loc) · 27.9 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
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
import LLMTool from 'api/llms/llmTool.ts';
import type { LLMToolInputSchema, LLMToolLogEntryFormattedResult, LLMToolRunResult } from 'api/llms/llmTool.ts';
import {
formatLogEntryToolResult as formatLogEntryToolResultBrowser,
formatLogEntryToolUse as formatLogEntryToolUseBrowser,
} from './formatter.browser.tsx';
import {
formatLogEntryToolResult as formatLogEntryToolResultConsole,
formatLogEntryToolUse as formatLogEntryToolUseConsole,
} from './formatter.console.ts';
import type LLMConversationInteraction from 'api/llms/conversationInteraction.ts';
import type { CollaborationLogEntryContentToolResult } from 'shared/types.ts';
import type {
LLMAnswerToolUse,
LLMMessageContentParts,
//LLMMessageContentPartImageBlock,
LLMMessageContentPartTextBlock,
} from 'api/llms/llmMessage.ts';
import type ProjectEditor from 'api/editor/projectEditor.ts';
import { createError, ErrorType } from 'api/utils/error.ts';
import type {
DataSourceHandlingErrorOptions,
FileHandlingErrorOptions,
ResourceHandlingErrorOptions,
ToolHandlingErrorOptions,
} from 'api/errors/error.ts';
import { logger } from 'shared/logger.ts';
import { encodeBase64 } from '@std/encoding';
import { extname, join } from '@std/path';
import type { ImageOperation, LLMToolImageProcessingInput, LLMToolImageProcessingResultData } from './types.ts';
// Import magick-wasm
import {
//AlphaAction,
ImageMagick,
type IMagickImage,
initialize,
MagickColor,
MagickFormat,
Percentage,
} from 'imagemagick';
export default class LLMToolImageProcessing extends LLMTool {
get inputSchema(): LLMToolInputSchema {
return {
type: 'object',
properties: {
dataSourceId: {
type: 'string',
description:
"Data source ID to operate on. Defaults to the primary data source if omitted. Examples: 'primary', 'filesystem-1', 'db-staging'. Data sources are identified by their name (e.g., 'primary', 'local-2', 'supabase').",
},
inputPath: {
type: 'string',
description: `The source image to process. Can be either:
1. Resource path relative to data source root
2. URL (http:// or https://) for remote images
Examples:
* "assets/images/original.jpg"
* "https://example.com/image.png"`,
},
outputPath: {
type: 'string',
description: `Where to save the processed image, relative to data source root.
Must be within the data source.
Format is determined by file extension.
Examples:
* "assets/images/processed.jpg"
* "public/thumbnails/image.webp"`,
},
operations: {
type: 'array',
description:
`Array of operations to apply in sequence. Each operation has a type and parameters specific to that operation.
Supported operations:
* resize: Change image dimensions
* crop: Cut out a portion of the image
* rotate: Rotate by specified angle
* flip: Flip horizontally or vertically
* blur: Apply Gaussian blur
* sharpen: Enhance image details
* grayscale: Convert to black and white
* format: Convert to different format
* quality: Set compression quality
* brightness: Adjust brightness
* contrast: Adjust contrast
* removeBackground: Create transparent background
Example:
[
{ "type": "resize", "params": { "width": 800, "height": 600 } },
{ "type": "grayscale", "params": {} }
]`,
items: {
type: 'object',
properties: {
type: {
type: 'string',
enum: [
'resize',
'crop',
'rotate',
'flip',
'blur',
'sharpen',
'grayscale',
'format',
'quality',
'brightness',
'contrast',
'removeBackground',
],
},
params: {
type: 'object',
properties: {
// Resize operation parameters
width: {
type: 'number',
description: 'New width in pixels',
},
height: {
type: 'number',
description: 'New height in pixels',
},
fit: {
type: 'string',
description: 'How the image should fit within dimensions',
enum: ['contain', 'cover', 'fill', 'inside', 'outside'],
},
position: {
type: 'string',
description: 'Position for cropping when fit is cover',
},
// Crop operation parameters
left: {
type: 'number',
description: 'Left edge of crop area in pixels',
},
top: {
type: 'number',
description: 'Top edge of crop area in pixels',
},
// Rotate operation parameters
angle: {
type: 'number',
description: 'Degrees to rotate the image (0-360)',
},
background: {
type: 'string',
description: 'Background color for empty space after rotation',
},
// Flip operation parameters
direction: {
type: 'string',
description: 'Direction to flip the image',
enum: ['horizontal', 'vertical', 'both'],
},
// Blur operation parameters
sigma: {
type: 'number',
description: 'Blur radius (higher values create more blur)',
},
// Sharpen operation parameters
amount: {
type: 'number',
description: 'Sharpening amount (1-5 recommended)',
},
// Format operation parameters
format: {
type: 'string',
description: 'Target format (jpeg, png, webp, etc.)',
enum: ['jpeg', 'png', 'webp', 'gif', 'avif'],
},
// Quality operation parameters
quality: {
type: 'number',
description: 'JPEG/WebP quality (1-100)',
minimum: 1,
maximum: 100,
},
// Brightness operation parameters
brightness: {
type: 'number',
description: 'Brightness adjustment (-100 to 100)',
minimum: -100,
maximum: 100,
},
// Contrast operation parameters
contrast: {
type: 'number',
description: 'Contrast adjustment (-100 to 100)',
minimum: -100,
maximum: 100,
},
// RemoveBackground operation parameters
color: {
type: 'string',
description: 'Background color to remove (e.g., "white", "black", "#FF0000")',
default: 'white',
},
fuzz: {
type: 'number',
description: 'Tolerance for color matching (0-100%)',
minimum: 0,
maximum: 100,
default: 10,
},
method: {
type: 'string',
description: 'Background removal method',
enum: ['color', 'floodfill'],
default: 'color',
},
},
},
},
required: ['type', 'params'],
},
},
createMissingDirectories: {
type: 'boolean',
description: "Whether to create output directory if it doesn't exist",
default: true,
},
overwrite: {
type: 'boolean',
description: 'Whether to overwrite output file if it exists',
default: false,
},
},
required: ['inputPath', 'outputPath', 'operations'],
};
}
formatLogEntryToolUse(
toolInput: LLMToolInputSchema,
format: 'console' | 'browser',
): LLMToolLogEntryFormattedResult {
return format === 'console' ? formatLogEntryToolUseConsole(toolInput) : formatLogEntryToolUseBrowser(toolInput);
}
formatLogEntryToolResult(
resultContent: CollaborationLogEntryContentToolResult,
format: 'console' | 'browser',
): LLMToolLogEntryFormattedResult {
return format === 'console'
? formatLogEntryToolResultConsole(resultContent)
: formatLogEntryToolResultBrowser(resultContent);
}
async runTool(
_interaction: LLMConversationInteraction,
toolUse: LLMAnswerToolUse,
projectEditor: ProjectEditor,
): Promise<LLMToolRunResult> {
const { toolInput } = toolUse;
const {
inputPath,
outputPath,
operations,
createMissingDirectories = true,
overwrite = false,
dataSourceId = undefined,
} = toolInput as LLMToolImageProcessingInput;
const { primaryDsConnection, dsConnections, notFound } = this.getDsConnectionsById(
projectEditor,
dataSourceId ? [dataSourceId] : undefined,
);
if (!primaryDsConnection) {
throw createError(ErrorType.DataSourceHandling, `No primary data source`, {
name: 'datasource',
dataSourceIds: dataSourceId ? [dataSourceId] : undefined,
} as DataSourceHandlingErrorOptions);
}
const dsConnectionToUse = dsConnections[0] || primaryDsConnection;
const dsConnectionToUseId = dsConnectionToUse.id;
if (!dsConnectionToUseId) {
throw createError(ErrorType.DataSourceHandling, `No data source id`, {
name: 'datasource',
dataSourceIds: dataSourceId ? [dataSourceId] : undefined,
} as DataSourceHandlingErrorOptions);
}
const dataSourceRoot = dsConnectionToUse.getDataSourceRoot();
if (!dataSourceRoot) {
throw createError(ErrorType.DataSourceHandling, `No data source root`, {
name: 'datasource',
dataSourceIds: dataSourceId ? [dataSourceId] : undefined,
} as DataSourceHandlingErrorOptions);
}
// Input is a local file
const inputResourceUri = dsConnectionToUse.getUriForResource(`file:./${inputPath}`);
// Validate output path is within data source
const outputResourceUri = dsConnectionToUse.getUriForResource(`file:./${outputPath}`);
if (!await dsConnectionToUse.isResourceWithinDataSource(outputResourceUri)) {
throw createError(
ErrorType.FileHandling,
`Access denied: ${outputPath} is outside the data source`,
{
name: 'image-processing',
filePath: outputPath,
operation: 'write',
} as FileHandlingErrorOptions,
);
}
const fullOutputPath = join(dataSourceRoot, outputPath);
logger.info(`LLMToolImageProcessing: Processing image, output to: ${fullOutputPath}`);
try {
const resourceAccessor = await dsConnectionToUse.getResourceAccessor();
if (!resourceAccessor.writeResource) {
throw createError(ErrorType.ToolHandling, `No writeResource method on resourceAccessor`, {
toolName: 'image_manipulation',
operation: 'tool-run',
} as ToolHandlingErrorOptions);
}
// Handled by writeResource
/*
// Check if output file exists and whether we should overwrite
const resourceExists = await dsConnectionToUse.resourceExists(outputResourceUri, { isFile: true });
if (resourceExists && !overwrite) {
throw createError(
ErrorType.FileHandling,
`Output file ${outputPath} already exists and overwrite is set to false`,
{
name: 'image-processing',
filePath: outputPath,
operation: 'write',
} as FileHandlingErrorOptions,
);
}
// Create output directory if needed
if (createMissingDirectories) {
await dsConnectionToUse.ensureResourcePathExists(outputResourceUri);
}
*/
// Load image data based on whether inputPath is a URL or local file
let imageData: Uint8Array;
if (inputPath.startsWith('http://') || inputPath.startsWith('https://')) {
// Input is a URL - use native fetch instead of FetchManager
const response = await fetch(inputPath);
if (!response.ok) {
throw new Error(`Failed to fetch image from URL: ${response.status} ${response.statusText}`);
}
imageData = new Uint8Array(await response.arrayBuffer());
} else {
if (!await dsConnectionToUse.isResourceWithinDataSource(inputResourceUri)) {
throw createError(
ErrorType.FileHandling,
`Access denied: ${inputPath} is outside the data source`,
{
name: 'image-processing',
filePath: inputPath,
operation: 'read',
} as FileHandlingErrorOptions,
);
}
const resource = await resourceAccessor.loadResource(inputResourceUri);
if (!resource) {
throw createError(ErrorType.DataSourceHandling, `Could not load resource`, {
operation: 'read',
} as ResourceHandlingErrorOptions);
}
imageData = resource.content as Uint8Array;
}
await initialize(); // Make sure to initialize ImageMagick first
// Process the image with magick-wasm
const { processedData, processedMetadata, completedOperations } = await this.processImageWithMagick(
imageData,
operations,
outputPath,
);
// Write the processed image
const results = await resourceAccessor.writeResource(outputResourceUri, processedData, {
overwrite,
createMissingDirectories,
});
// success: true,
// uri: resourceUri,
// metadata: resourceMetadata,
// bytesWritten: typeof content === 'string' ? new TextEncoder().encode(content).length : content.length,
if (!results.success) {
throw createError(
ErrorType.FileHandling,
`Writing image data failed for ${inputPath}`,
{
name: 'image-processing',
filePath: inputPath,
operation: 'write',
} as FileHandlingErrorOptions,
);
}
logger.info(
`LLMToolImageProcessing: Wrote ${results.bytesWritten} bytes for processed image: ${results.uri}`,
);
// Create a thumbnail of the result to display in the conversation
const thumbnailData = processedData;
//let thumbnailData: Uint8Array;
//try {
// thumbnailData = (await this.createThumbnail(processedData)).thumbnailData;
//} catch (error) {
// logger.error(
// `LLMToolImageProcessing: Failed to generate thumbnail - using processed image: ${
// (error as Error).message
// }`,
// );
// thumbnailData = processedData;
//}
//const { thumbnailData } = await this.createThumbnail(processedData);
const thumbnailBase64 = encodeBase64(thumbnailData);
// const toolResultContentPart: LLMMessageContentParts = [{
// 'type': 'image',
// 'source': {
// 'type': 'base64',
// // thumbnail is always png
// 'media_type': 'image/png', //this.getMediaTypeFromPath(outputPath),
// 'data': thumbnailBase64,
// },
// } as LLMMessageContentPartImageBlock];
const completedOperationsSummary = completedOperations.join('\n');
const toolResultContentParts: LLMMessageContentParts = [{
'type': 'text',
'text':
`Completed:\n${completedOperationsSummary}\n\nNew Image: width: ${processedMetadata.width}, height: ${processedMetadata.height}, format: ${processedMetadata.format}, size: ${processedMetadata.size},`,
} as LLMMessageContentPartTextBlock];
// Get basic image metadata
//const metadata = await this.getImageMetadata(processedData);
// //logger.info('LLMToolImageProcessing: ', thumbnailBase64);
// const thumbnailImagePath = join(dataSourceRoot, 'test-thumbnail.png');
// await Deno.writeFile(thumbnailImagePath, thumbnailData);
const dsConnectionStatus = notFound.length > 0
? `Could not find data source for: [${notFound.join(', ')}]`
: `Data source: ${dsConnectionToUse.name} [${dsConnectionToUse.id}]`;
toolResultContentParts.unshift({
type: 'text',
text: `Used data source: ${dsConnectionToUse.name}`,
});
// Prepare result data
const resultData: LLMToolImageProcessingResultData = {
inputPath,
outputPath,
operations,
success: true,
thumbnail: {
// thumbnail is always png
'mediaType': 'image/png', //this.getMediaTypeFromPath(outputPath),
'data': thumbnailBase64,
},
meta: processedMetadata,
dataSource: {
dsConnectionId: dsConnectionToUse.id,
dsConnectionName: dsConnectionToUse.name,
dsProviderType: dsConnectionToUse.providerType,
},
};
//logger.error(`LLMToolImageProcessing:`, { resultData });
// Format operations for response
const operationsSummary = operations.map((op) => `${op.type}`).join(', ');
return {
toolResults: toolResultContentParts,
toolResponse:
`${dsConnectionStatus}\nSuccessfully processed image from ${inputPath} to ${outputPath} with operations: ${operationsSummary}`,
bbResponse: {
data: resultData,
},
};
} catch (error) {
logger.error(`LLMToolImageProcessing: Failed to process image: ${(error as Error).message}`);
const toolResults = `\u26a0\ufe0f ${(error as Error).message}`;
const bbResponse = `BB failed to process image. Error: ${(error as Error).message}`;
const toolResponse = `Failed to process image. Error: ${(error as Error).message}`;
return { toolResults, toolResponse, bbResponse };
}
}
private async processImageWithMagick(
imageData: Uint8Array,
operations: ImageOperation[],
outputPath: string,
): Promise<{
processedData: Uint8Array;
processedMetadata: {
width?: number;
height?: number;
format?: string;
size?: number;
};
completedOperations: string[];
}> {
return new Promise((resolve, reject) => {
try {
ImageMagick.read(imageData, (image: IMagickImage) => {
try {
const completedOperations: string[] = [];
// Apply each operation in sequence
for (const operation of operations) {
switch (operation.type) {
case 'resize': {
const params = operation.params as {
width?: number;
height?: number;
fit?: string;
};
let resizedTo = '';
if (params.width && params.height) {
image.resize(params.width, params.height);
resizedTo = `Width: ${params.width}, Height: ${params.height}`;
} else if (params.width) {
image.resize(params.width, 0);
resizedTo = `Width: ${params.width}`;
} else if (params.height) {
image.resize(0, params.height);
resizedTo = `Height: ${params.height}`;
}
completedOperations.push(`Resized to: ${resizedTo}`);
break;
}
case 'crop': {
const params = operation.params as {
width: number;
height: number;
left?: number;
top?: number;
};
let croppedTo = '';
// For cropping with x,y coordinates we need to use geometry
if (typeof params.left === 'number' && typeof params.top === 'number') {
// Create a geometry that specifies the crop with offset
// Instead of using chopHorizontal/chopVertical (which don't exist), we'll use the standard crop
// MagickWasm doesn't appear to have an offset parameter in crop, so we might need to do multiple operations
// Create a temporary cropped area
image.crop({
x: params.left,
y: params.top,
width: params.width,
height: params.height,
aspectRatio: false,
fillArea: false,
greater: false,
ignoreAspectRatio: false,
isPercentage: false,
less: false,
limitPixels: false,
});
croppedTo =
`Left: ${params.left}, Top: ${params.top}, Width: ${params.width}, Height: ${params.height}`;
} else {
// Simple center crop if no coordinates given
image.crop(params.width, params.height);
croppedTo = `Width: ${params.width}, Height: ${params.height}`;
}
completedOperations.push(`Cropped to: ${croppedTo}`);
break;
}
case 'rotate': {
const params = operation.params as { angle: number };
image.rotate(params.angle);
completedOperations.push(`Rotated to: ${params.angle}`);
break;
}
case 'flip': {
const params = operation.params as {
direction: 'horizontal' | 'vertical' | 'both';
};
let flippedDirection = '';
if (params.direction === 'horizontal') {
image.flip();
flippedDirection = `horizontally`;
} else if (params.direction === 'vertical') {
image.flop();
flippedDirection = `vertically`;
} else if (params.direction === 'both') {
image.flip();
image.flop();
flippedDirection = `vertically and horizontally`;
}
completedOperations.push(`Flipped: ${flippedDirection}`);
break;
}
case 'blur': {
const params = operation.params as { sigma: number };
image.gaussianBlur(params.sigma);
completedOperations.push(`Blurred to: ${params.sigma}`);
break;
}
case 'sharpen': {
const params = operation.params as { amount: number };
image.sharpen(0, params.amount);
completedOperations.push(`Sharpened to: ${params.amount}`);
break;
}
case 'grayscale':
image.grayscale();
completedOperations.push(`Grayscale applied`);
break;
case 'brightness': {
const params = operation.params as { brightness: number };
// Convert -100..100 to 0..200% (where 100% is unchanged)
const brightnessPercent = (params.brightness + 100) / 2;
// brightnessContrast requires Percentage objects
image.brightnessContrast(
new Percentage(brightnessPercent),
new Percentage(100),
);
completedOperations.push(`Brightness changed: ${params.brightness}`);
break;
}
case 'contrast': {
const params = operation.params as { contrast: number };
// Convert -100..100 to 0..200% (where 100% is unchanged)
const contrastPercent = (params.contrast + 100) / 2;
// brightnessContrast requires Percentage objects
image.brightnessContrast(
new Percentage(100),
new Percentage(contrastPercent),
);
completedOperations.push(`Contrast changed: ${params.contrast}`);
break;
}
case 'quality': {
const params = operation.params as { quality: number };
image.quality = params.quality;
completedOperations.push(`Format quality set to: ${params.quality}`);
break;
}
case 'format': {
// Format is handled in the write step
const params = operation.params as { format: string };
completedOperations.push(`Converted to format: ${params.format}`);
break;
}
case 'removeBackground': {
const params = operation.params as {
color?: string;
fuzz?: number;
method?: 'color' | 'floodfill';
};
const backgroundColor = params.color || 'white';
const fuzzValue = params.fuzz || 10;
let backgroundRemoval = `Color: ${backgroundColor}, Fuzz: ${fuzzValue}`;
// Ensure the image has an alpha channel and supports transparency
image.hasAlpha = true;
// Set the format to support transparency if it doesn't already
if (image.format !== MagickFormat.Png && image.format !== MagickFormat.WebP) {
image.format = MagickFormat.Png;
}
// Set the color fuzz factor (how much tolerance for color matching)
image.colorFuzz = new Percentage(fuzzValue);
// Create a MagickColor object for the background color
const magickColor = new MagickColor(backgroundColor);
// Based on selected method, create the transparency
if (params.method === 'floodfill') {
// This would use flood fill to identify background regions
// Since floodfill isn't directly exposed, we fall back to the color method
console.warn(
'Floodfill method not fully implemented, using color-based removal',
);
image.transparent(magickColor);
image.alpha(1); //AlphaAction.Activate
backgroundRemoval = `${backgroundRemoval}, Flood Fill: <not available>`;
} else {
// Simple color-based transparency - this makes all pixels of a certain color transparent
image.transparent(magickColor);
image.alpha(1); //AlphaAction.Activate
backgroundRemoval = `${backgroundRemoval}, Flood Fill: none`;
}
completedOperations.push(`Background removed for: ${backgroundRemoval}`);
break;
}
}
}
const processedMetadata = {
width: image.width,
height: image.height,
format: image.format.toString(),
size: 0,
};
// Determine output format from file extension or format operation
let format = this.getFormatFromPath(outputPath);
const formatOperation = operations.find((op) => op.type === 'format');
if (formatOperation) {
const formatParams = formatOperation.params as { format: string };
format = this.getFormatFromString(formatParams.format);
}
// Write the image to a buffer
image.write(format, (processedData: Uint8Array) => {
processedMetadata.size = processedData.length;
resolve({ processedData, processedMetadata, completedOperations });
});
} catch (err) {
reject(new Error(`Error processing image: ${(err as Error).message}`));
}
});
} catch (err) {
reject(new Error(`Error loading image: ${(err as Error).message}`));
}
});
}
/*
private async createThumbnail(imageData: Uint8Array): Promise<{
thumbnailData: Uint8Array;
thumbnailMetadata: {
width?: number;
height?: number;
format?: string;
size?: number;
};
}> {
// Create a thumbnail for display in the conversation (max 800px wide/tall)
return new Promise((resolve, reject) => {
try {
ImageMagick.read(imageData, (image: IMagickImage) => {
try {
// Resize the image to create a thumbnail if it's large
const MAX_THUMBNAIL_SIZE = 450;
if (image.width > MAX_THUMBNAIL_SIZE || image.height > MAX_THUMBNAIL_SIZE) {
if (image.width > image.height) {
image.resize(MAX_THUMBNAIL_SIZE, 0);
} else {
image.resize(0, MAX_THUMBNAIL_SIZE);
}
}
const thumbnailMetadata = {
width: image.width,
height: image.height,
format: image.format.toString(),
size: 0,
};
// Convert to PNG for consistent thumbnail format
image.write(MagickFormat.Png, (thumbnailData: Uint8Array) => {
thumbnailMetadata.size = thumbnailData.length;
resolve({ thumbnailData, thumbnailMetadata });
});
} catch (err) {
reject(new Error(`Error creating thumbnail: ${(err as Error).message}`));
}
});
} catch (err) {
reject(new Error(`Error loading image for thumbnail: ${(err as Error).message}`));
}
});
}
*/
/*
private async getImageMetadata(imageData: Uint8Array): Promise<{
width?: number;
height?: number;
format?: string;
size?: number;
}> {
return new Promise((resolve, reject) => {
try {
ImageMagick.read(imageData, (image: IMagickImage) => {
try {
// Extract basic metadata from the image
const metadata = {
width: image.width,
height: image.height,
format: image.format.toString(),
size: imageData.length,
};
resolve(metadata);
} catch (err) {
reject(new Error(`Error extracting metadata: ${(err as Error).message}`));
}
});
} catch (_err) {
// If we can't get detailed metadata, return basic info
resolve({
size: imageData.length,
});
}
});
}
*/
/*
private getMediaTypeFromPath(path: string): string {
const ext = extname(path).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return 'image/jpeg';
case '.png':
return 'image/png';
case '.gif':
return 'image/gif';
case '.webp':
return 'image/webp';
case '.svg':
return 'image/svg+xml';
case '.avif':
return 'image/avif';
default:
return 'application/octet-stream';
}
}
*/
private getFormatFromPath(path: string): MagickFormat {
const ext = extname(path).toLowerCase();
switch (ext) {
case '.jpg':
case '.jpeg':
return MagickFormat.Jpeg;
case '.png':
return MagickFormat.Png;
case '.gif':
return MagickFormat.Gif;
case '.webp':
return MagickFormat.WebP;
case '.avif':
return MagickFormat.Avif;
default:
return MagickFormat.Jpeg; // Default to JPEG
}
}
private getFormatFromString(formatString: string): MagickFormat {
switch (formatString.toLowerCase()) {
case 'jpeg':
return MagickFormat.Jpeg;
case 'png':
return MagickFormat.Png;
case 'gif':
return MagickFormat.Gif;
case 'webp':
return MagickFormat.WebP;
case 'avif':
return MagickFormat.Avif;
default:
return MagickFormat.Jpeg;
}
}
}