Task examples

1. Browser Task (JavaScript) - Image to WebP Conversion

This browser task uses native JavaScript to convert images to WebP format.

export default async function(files, params, onProgressMsg) {
  const quality = params.quality || 0.8;
  const convertedFiles = [];

  onProgressMsg(`Progressing...0/${files.length}`);
  for (const file of files) {
    if (!file.type.startsWith('image/')) {
      throw new Error('Input file must be an image.');
    }

    const img = await createImageBitmap(file);
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;

    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);

    const webpBlob = await new Promise(resolve => {
      canvas.toBlob(resolve, 'image/webp', quality);
    });

    const webpFile = new File([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.

interface TaskParams {
  quality?: number;
}

export default async function(files: FileList, params: TaskParams, onProgressMsg: (progressMsg: string) => void): Promise<File[]> {
  const quality = params.quality || 0.8;
  const convertedFiles: File[] = [];

  onProgressMsg(`Progressing...${convertedFiles.length}/${files.length}`);
  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    if (!file.type.startsWith('image/')) {
      throw new Error('Input file must be an image.');
    }

    const img = await createImageBitmap(file);
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;

    const ctx = canvas.getContext('2d');
    if (ctx) {
      ctx.drawImage(img, 0, 0);

      const webpBlob = await new Promise<Blob>(resolve => {
        canvas.toBlob(blob => resolve(blob!), 'image/webp', quality);
      });

      const webpFile = new File([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';

export default async function(files, params) {
  const targetLanguage = params.targetLanguage || 'Spanish';
  const openaiKey = process.env.OPENAI_API_KEY;

  if (!openaiKey) {
    throw new Error('OpenAI API key is not set in environment variables.');
  }

  const translatedFiles = [];

  for (const file of files) {
    if (file.type !== 'application/pdf') {
      throw new Error('Input file must be a PDF.');
    }

    const pdfBytes = await file.arrayBuffer();
    const pdfDoc = await PDFDocument.load(pdfBytes);
    const pages = pdfDoc.getPages();

    for (let i = 0; i < pages.length; i++) {
      const page = pages[i];
      const text = await page.getText();

      const translatedText = await translateText(text, targetLanguage, openaiKey);

      page.drawText(translatedText, {
        x: 50,
        y: page.getHeight() - 50,
        size: 12,
      });
    }

    const translatedPdfBytes = await pdfDoc.save();
    const translatedFile = new File([translatedPdfBytes], file.name.replace('.pdf', `_${targetLanguage}.pdf`), {
      type: 'application/pdf'
    });

    translatedFiles.push(translatedFile);
  }

  return translatedFiles;
}

async function translateText(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';

interface TaskParams {
  targetLanguage?: string;
}

export default async function(files: FileList, params: TaskParams): Promise<File[]> {
  const targetLanguage = params.targetLanguage || 'Spanish';
  const openaiKey = process.env.OPENAI_API_KEY;

  if (!openaiKey) {
    throw new Error('OpenAI API key is not set in environment variables.');
  }

  const translatedFiles: File[] = [];

  for (let i = 0; i < files.length; i++) {
    const file = files[i];
    if (file.type !== 'application/pdf') {
      throw new Error('Input file must be a PDF.');
    }

    // PDF processing and translation logic
  }

  return translatedFiles;
}

async function translateText(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.

Last updated