|
| 1 | +/** |
| 2 | + * Rename Files in Google Drive using Gemini AI |
| 3 | + * |
| 4 | + * Author: Amit Agarwal |
| 5 | + * Email: amit@labnol.org |
| 6 | + * Web: https://digitalinspiration.com/ |
| 7 | + * |
| 8 | + * MIT License |
| 9 | + */ |
| 10 | + |
| 11 | +const GoogleDriveFolderId = 'Your Drive Folder Id'; |
| 12 | +const GoogleGeminiAPIKey = 'Your Gemini AI key'; |
| 13 | + |
| 14 | +const getFilesInFolder_ = (folderId) => { |
| 15 | + const mimeTypes = ['image/png', 'image/jpeg', 'image/webp']; |
| 16 | + const { files = [] } = Drive.Files.list({ |
| 17 | + q: `'${folderId}' in parents and (${mimeTypes.map((type) => `mimeType='${type}'`).join(' or ')})`, |
| 18 | + fields: 'files(id,thumbnailLink,mimeType)', |
| 19 | + pageSize: 10, |
| 20 | + }); |
| 21 | + return files; |
| 22 | +}; |
| 23 | + |
| 24 | +const getFileAsBase64_ = (thumbnailLink) => { |
| 25 | + const blob = UrlFetchApp.fetch(thumbnailLink).getBlob(); |
| 26 | + const base64 = Utilities.base64Encode(blob.getBytes()); |
| 27 | + return base64; |
| 28 | +}; |
| 29 | + |
| 30 | +const getSuggestedFilename_ = (base64, mimeType) => { |
| 31 | + 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. Append the extension based on file's mimeType which is ${mimeType}`; |
| 32 | + const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${GoogleGeminiAPIKey}`; |
| 33 | + const inlineData = { |
| 34 | + mimeType, |
| 35 | + data: base64, |
| 36 | + }; |
| 37 | + |
| 38 | + try { |
| 39 | + const response = UrlFetchApp.fetch(apiUrl, { |
| 40 | + method: 'POST', |
| 41 | + headers: { |
| 42 | + 'Content-Type': 'application/json', |
| 43 | + }, |
| 44 | + payload: JSON.stringify({ |
| 45 | + contents: [{ parts: [{ inlineData }, { text }] }], |
| 46 | + }), |
| 47 | + }); |
| 48 | + const data = JSON.parse(response); |
| 49 | + return data.candidates[0].content.parts[0].text.trim(); |
| 50 | + } catch (f) { |
| 51 | + return null; |
| 52 | + } |
| 53 | +}; |
| 54 | + |
| 55 | +const renameFilesInGoogleDrive = () => { |
| 56 | + const files = getFilesInFolder_(GoogleDriveFolderId); |
| 57 | + files.forEach((file) => { |
| 58 | + const { id, thumbnailLink, mimeType } = file; |
| 59 | + const base64 = getFileAsBase64_(thumbnailLink); |
| 60 | + const name = getSuggestedFilename_(base64, mimeType); |
| 61 | + if (name) { |
| 62 | + Drive.Files.update({ name }, id); |
| 63 | + } |
| 64 | + }); |
| 65 | +}; |
0 commit comments