1. Browser Task (JavaScript) - Image to WebP Conversion
This browser task uses native JavaScript to convert images to WebP format.
exportdefaultasyncfunction(files, params, onProgressMsg) {constquality=params.quality ||0.8;constconvertedFiles= [];onProgressMsg(`Progressing...0/${files.length}`);for (constfileof files) {if (!file.type.startsWith('image/')) {thrownewError('Input file must be an image.'); }constimg=awaitcreateImageBitmap(file);constcanvas=document.createElement('canvas');canvas.width =img.width;canvas.height =img.height;constctx=canvas.getContext('2d');ctx.drawImage(img,0,0);constwebpBlob=awaitnewPromise(resolve => {canvas.toBlob(resolve,'image/webp', quality); });constwebpFile=newFile([webpBlob],file.name.replace(/\.[^/.]+$/,'.webp'), { type:'image/webp' });convertedFiles.push(webpFile);onProgressMsg(`Progressing...${convertedFiles.length}/${files.length}`); }return convertedFiles;}
Explanation:
Uses params.quality to control WebP conversion quality, default is 0.8.
Utilizes createImageBitmap and Canvas API for image processing.
Generates WebP format Blob using canvas.toBlob.
Returns an array of converted File objects.
2. Browser Task (TypeScript) - Image to WebP Conversion
This task is functionally identical to the previous one but written in TypeScript, providing better type safety.
interfaceTaskParams { quality?:number;}exportdefaultasyncfunction(files:FileList, params:TaskParams,onProgressMsg: (progressMsg:string) =>void):Promise<File[]> {constquality=params.quality ||0.8;constconvertedFiles:File[] = [];onProgressMsg(`Progressing...${convertedFiles.length}/${files.length}`);for (let i =0; i <files.length; i++) {constfile= files[i];if (!file.type.startsWith('image/')) {thrownewError('Input file must be an image.'); }constimg=awaitcreateImageBitmap(file);constcanvas=document.createElement('canvas');canvas.width =img.width;canvas.height =img.height;constctx=canvas.getContext('2d');if (ctx) {ctx.drawImage(img,0,0);constwebpBlob=awaitnewPromise<Blob>(resolve => {canvas.toBlob(blob =>resolve(blob!),'image/webp', quality); });constwebpFile=newFile([webpBlob],file.name.replace(/\.[^/.]+$/,'.webp'), { type:'image/webp' });convertedFiles.push(webpFile); }onProgressMsg(`Progressing...${convertedFiles.length}/${files.length}`); }return convertedFiles;}
Explanation:
Uses TypeScript interface to define TaskParams, improving code readability and type safety.
Function signature explicitly specifies input and output types.
Logic is the same as the JavaScript version, but with added type checking.
3. Server Task (JavaScript) - PDF Translation using ChatGPT
This server task uses the ChatGPT API to translate PDF files into a specified language.
import { PDFDocument } from'pdf-lib';import fetch from'node-fetch';exportdefaultasyncfunction(files, params) {consttargetLanguage=params.targetLanguage ||'Spanish';constopenaiKey=process.env.OPENAI_API_KEY;if (!openaiKey) {thrownewError('OpenAI API key is not set in environment variables.'); }consttranslatedFiles= [];for (constfileof files) {if (file.type !=='application/pdf') {thrownewError('Input file must be a PDF.'); }constpdfBytes=awaitfile.arrayBuffer();constpdfDoc=awaitPDFDocument.load(pdfBytes);constpages=pdfDoc.getPages();for (let i =0; i <pages.length; i++) {constpage= pages[i];consttext=awaitpage.getText();consttranslatedText=awaittranslateText(text, targetLanguage, openaiKey);page.drawText(translatedText, { x:50, y:page.getHeight() -50, size:12, }); }consttranslatedPdfBytes=awaitpdfDoc.save();consttranslatedFile=newFile([translatedPdfBytes],file.name.replace('.pdf',`_${targetLanguage}.pdf`), { type:'application/pdf' });translatedFiles.push(translatedFile); }return translatedFiles;}asyncfunctiontranslateText(text, targetLanguage, apiKey) {// ChatGPT API call implementation}
Explanation:
Uses the pdf-lib library to handle PDF files.
Retrieves the OpenAI API key from environment variables, ensuring security.
Iterates through each page of the PDF, extracts text, translates it, and rewrites it.
Uses the ChatGPT API for text translation.
Returns an array of translated PDF files.
4. Server Task (TypeScript) - PDF Translation using ChatGPT
This task is functionally identical to the previous one but written in TypeScript, providing better type definitions and error checking.
import { PDFDocument } from'pdf-lib';import fetch from'node-fetch';interfaceTaskParams { targetLanguage?:string;}exportdefaultasyncfunction(files:FileList, params:TaskParams):Promise<File[]> {consttargetLanguage=params.targetLanguage ||'Spanish';constopenaiKey=process.env.OPENAI_API_KEY;if (!openaiKey) {thrownewError('OpenAI API key is not set in environment variables.'); }consttranslatedFiles:File[] = [];for (let i =0; i <files.length; i++) {constfile= files[i];if (file.type !=='application/pdf') {thrownewError('Input file must be a PDF.'); }// PDF processing and translation logic }return translatedFiles;}asyncfunctiontranslateText(text:string, targetLanguage:string, apiKey:string):Promise<string> {// ChatGPT API call implementation}
Explanation:
Uses TypeScript interface to define TaskParams, enhancing code readability and type safety.
Function signature explicitly specifies input and output types.
Logic is the same as the JavaScript version, but with added type checking, improving code robustness.
These examples demonstrate how to create different types of tasks in FilesWorkflow, handle various file formats, and utilize external APIs. They showcase parameter usage, environment variable access, error handling, and how to return processed files. In practical applications, adjustments may be needed based on the specific environment and available libraries in FilesWorkflow.