Automate Google Drive File Renaming with Apps Script and AI

Google AI @ Freshers.in

This detailed guide provides step-by-step instructions for creating a script that utilizes AI to suggest descriptive filenames for your images, enhancing organization and accessibility.

The article provides a detailed guide to automating the process of renaming files in Google Drive using Google Apps Script and AI. It covers setting up a Google Apps Script project, fetching image files from a Drive folder, converting images to Base64 for AI processing, generating new filenames with AI, and renaming the files in Drive. The steps include accessing Google Apps Script, writing code to interact with Drive and AI, executing the script, and troubleshooting. It’s designed for users with basic scripting knowledge, aiming to enhance file organization through automation. For comprehensive details and step-by-step instructions, please refer to the original source at Digital Inspiration.

Prerequisites

  1. Basic knowledge of Google Apps Script.
  2. Access to Google Drive and the ability to create scripts.
  3. An AI API key (if using external AI services).

Setting Up Your Script

  1. Instructions on accessing Google Apps Script.
  2. Step-by-step guide to creating a new script project.
Code
// Define a function to fetch image files from a specified Google Drive folder
function fetchImageFiles(folderIdentifier) {
  // Define MIME types for images
  const imageMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
  // Use the Drive API to list files matching the image MIME types
  const fileList = DriveApp.getFolderById(folderIdentifier).getFilesByType(imageMimeTypes.join(' or '));
  let images = [];
  while (fileList.hasNext()) {
    let file = fileList.next();
    images.push({id: file.getId(), url: file.getThumbnail(), mimeType: file.getMimeType()});
  }
  return images;
}

// Convert image file to Base64
function imageToBase64(imageUrl) {
  let response = UrlFetchApp.fetch(imageUrl);
  let blob = response.getBlob();
  return Utilities.base64Encode(blob.getBytes());
}

// Generate a new filename using an AI model
function generateFilename(imageBase64, imageType) {
  const aiPrompt = "Suggest a descriptive and concise filename for this image, avoiding underscores and favoring spaces.";
  const apiKey = "YOUR_API_KEY_HERE"; // Replace with your actual API key
  const requestUrl = `https://example.ai.api/url?key=${apiKey}`; // Placeholder API URL

  let payload = JSON.stringify({
    image: {data: imageBase64, type: imageType},
    prompt: aiPrompt
  });

  let options = {
    method: 'post',
    contentType: 'application/json',
    payload: payload,
  };

  try {
    let aiResponse = UrlFetchApp.fetch(requestUrl, options);
    let json = JSON.parse(aiResponse.getContentText());
    return json.suggestedName.trim();
  } catch (error) {
    console.error('Error generating filename: ', error);
    return null;
  }
}

// Main function to rename image files in a Drive folder
function renameDriveFiles(folderId) {
  const images = fetchImageFiles(folderId);
  images.forEach(image => {
    const base64String = imageToBase64(image.url);
    const newFilename = generateFilename(base64String, image.mimeType);
    if (newFilename) {
      DriveApp.getFileById(image.id).setName(newFilename);
    }
  });
}

// Example usage
// Replace 'YOUR_FOLDER_ID_HERE' with your actual Google Drive folder ID
//renameDriveFiles('YOUR_FOLDER_ID_HERE');

Let’s break down the code step by step:

  1. fetchImageFiles(folderIdentifier):
    • This function takes a folder identifier (presumably the ID of a Google Drive folder) as input.
    • It defines an array called imageMimeTypes containing MIME types for images (JPEG, PNG, GIF).
    • It then utilizes Google Apps Script’s DriveApp service to get a list of files within the specified folder that match the image MIME types.
    • It iterates over the files and creates an array of image objects, each containing the file ID, URL of its thumbnail, and MIME type.
    • Finally, it returns the array of image objects.
  2. imageToBase64(imageUrl):
    • This function takes an image URL as input.
    • It uses UrlFetchApp.fetch() to fetch the image from the specified URL.
    • It then converts the fetched image into a Blob object.
    • Finally, it encodes the Blob object into a Base64 string and returns it.
  3. generateFilename(imageBase64, imageType):
    • This function generates a new filename for an image based on its Base64 representation and MIME type using an AI model.
    • It constructs a JSON payload containing the image data (Base64 string) and MIME type, along with a prompt for the AI model.
    • It sends a POST request to an AI API endpoint (placeholder URL in this case) with the constructed payload.
    • Upon receiving a response from the AI model, it parses the JSON response and extracts the suggested filename.
    • It trims the suggested filename and returns it.
  4. renameDriveFiles(folderId):
    • This is the main function responsible for renaming image files within a Google Drive folder.
    • It first fetches the image files from the specified Drive folder using fetchImageFiles().
    • It then iterates over each image, converting its thumbnail URL to Base64 using imageToBase64() and generating a new filename using generateFilename().
    • Finally, it renames the image file in the Drive folder with the new filename obtained from the AI model.
  5. Example usage:
    • This part is commented out but provides an example of how to use the renameDriveFiles() function. You need to replace 'YOUR_FOLDER_ID_HERE' with the actual Google Drive folder ID you want to rename the files in.
Author: user