Quickly rename files in Google Drive with Apps Script and Google Gemini AI. The script will automatically rename the files with a descriptive name based on the image content.
Your Google Drive contains image files with generic names IMG_123456.jpg
or Screenshot.png
Which provides no context about the image? Wouldn’t it be great to have an assistant that could look at these images and automatically suggest descriptive filenames for the images?
Rename files in Google Drive with AI
Well, you can use Google’s Gemini AI and Google Apps Script to automatically rename files in Google Drive with a descriptive name based on the image content.
The following example uses Google’s Gemini AI but the steps can easily be adapted to OpenAI’s GPT-4 Vision or other AI models.
To begin, open script.new
Create a new Google Script and copy and paste the following code snippets into the editor. You can also enable the Advanced Drive API from the Google Script Editor under the Resources menu.
1. Get a list of files in a folder
The first step is to get a list of files in a folder. We will use Drive.Files.list
Method to get a list of files in a folder. A search query includes mimeType
Parameter to filter the results and drive files to return only image formats supported by Google Gemini AI.
const getFilesInFolder = (folderId) => {
const mimeTypes = ('image/png', 'image/jpeg', 'image/webp');
const { files = () } = Drive.Files.list({
q: `'${folderId}' in parents and (${mimeTypes.map((type) => `mimeType='${type}'`).join(' or ')})`,
fields: 'files(id,thumbnailLink,mimeType)',
pageSize: 10,
});
return files;
};
2. Get the file thumbnail as Base64
Files returned by Drive.Files.list
includes method thumbnailLink
A property to show a thumbnail image of a file. We will use the UrlFetchApp service to fetch the thumbnail image and convert it to a Base64 encoded string.
const getFileAsBase64 = (thumbnailLink) => {
const blob = UrlFetchApp.fetch(thumbnailLink).getBlob();
const base64 = Utilities.base64Encode(blob.getBytes());
return base64;
};
3. Get suggested file name from Google Gemini AI
We will use the Google Gemini API to analyze the visual content of the image and suggest a descriptive filename for the image. Our text prompt looks like this:
Analyze the image content and propose a brief, descriptive filename in 5-15 words without providing any explanation or additional text. Use spaces for file names instead of underscores.
You need an API key which you can generate from Google AI Studio.
const getSuggestedFilename = (base64, fileMimeType) => {
try {
const text = `Analyze the image content and propose a concise, descriptive filename in 5-15 words without providing any explanation or additional text. Use spaces instead of underscores.`;
const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${GEMINI_API_KEY}`;
const inlineData = {
mimeType: fileMimeType,
data: base64,
};
const response = UrlFetchApp.fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
payload: JSON.stringify({
contents: ({ parts: ({ inlineData }, { text }) }),
}),
});
const data = JSON.parse(response);
return data.candidates(0).content.parts(0).text.trim();
} catch (f) {
return null;
}
};
4. Automatically rename files in Google Drive
The final step is to put all the pieces together. We’ll get a list of files in a folder, fetch a thumbnail image of each file, analyze the image content with Google Gemini AI, and rename the file in Google Drive with the suggested filename.
const renameFilesInGoogleDrive = () => {
const folderId = 'Put your folder ID here';
const files = getFilesInFolder(folderId);
files.forEach((file) => {
const { id, thumbnailLink, mimeType } = file;
const base64 = getFileAsBase64(thumbnailLink);
const name = getSuggestedFilename(base64, mimeType);
Drive.Files.update({ name }, id);
});
};
Google Script has a 6-minute execution time limit but you can set up a time-driven trigger so that the script runs automatically at certain time intervals (say every 10 minutes). You can extend the script to move files to a different folder after renaming them so they don’t get processed again.
The full source code is available on GitHub