Skip to content

Instantly share code, notes, and snippets.

@pfelipm
Last active April 28, 2021 07:22
Show Gist options
  • Save pfelipm/5d25d3af531da446f400dce41f6a7a1d to your computer and use it in GitHub Desktop.
Save pfelipm/5d25d3af531da446f400dce41f6a7a1d to your computer and use it in GitHub Desktop.
Get faces generated from scratch by AI using generated.photos API
/**
* generated.photos API demo >> Faces generated from scratch by AI
*
* 1. Get API key at https://generated.photos/api
* 2. Make a copy of https://docs.google.com/spreadsheets/d/1RkLy6e0h1QURtsOj1gsAfWGzvAUua0yIky_THy8ut1Q
* 3. Write your API key inside cell C3 (don't share!)
*
* Please, note:
* - Just 50 API calls/month! (API free plan)
* - Some trait combinations apparently fail to return results :-?
* - Script does not check for any errors
*
* @OnlyCurrentDoc
*/
function getPhotos() {
// Some constants...
const PARAM_RANGE = 'A3:C15';
const PIC_256 = 3;
const PIC_HEIGHT = 256;
const ROW_PICS = 17;
const COL_PICS = 2;
const ENDPOINT = 'https://api.generated.photos/api/v1/faces';
// Pull params from spreadsheet
const sheet = SpreadsheetApp.getActiveSheet();
const params = sheet.getRange(PARAM_RANGE).getValues();
// Build query string
const queryString = params.reduce((stringSoFar, param) => `${stringSoFar}${param[0]}=${param[2]}&`, `${ENDPOINT}?`).slice(0, -1);
// Get faces
const apiResponse = JSON.parse(UrlFetchApp.fetch(queryString).getContentText());
const picUrls = apiResponse.faces.map(faceUrl => faceUrl.urls[PIC_256]['256']);
// Remove previous images in spreadsheet
sheet.getImages().forEach(image => image.remove());
// Make room for pics, if necessary
const availableRows = sheet.getMaxRows() - ROW_PICS + 1;
const neededRows = Math.ceil(picUrls.length / 2);
if (neededRows > availableRows) {
sheet.insertRowsAfter(ROW_PICS - 1, neededRows - availableRows);
// Flush new rows (does not seem to be required?)
SpreadsheetApp.flush();
sheet.setRowHeights(ROW_PICS, neededRows, PIC_HEIGHT);
}
// Insert pics, 2 per row
picUrls.forEach((picUrl, index) => {
const row = Math.floor(index / 2);
const col = index % 2;
sheet.insertImage(picUrl, COL_PICS + col, ROW_PICS + row);
});
// Flush changes (does not seem to be required!)
SpreadsheetApp.flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment