Skip to content

Instantly share code, notes, and snippets.

@yufengg
Created May 29, 2020 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yufengg/113d0fdcb5a53d074eb5586a715d6fc3 to your computer and use it in GitHub Desktop.
Save yufengg/113d0fdcb5a53d074eb5586a715d6fc3 to your computer and use it in GitHub Desktop.
// Corresponding spreadsheet: https://docs.google.com/spreadsheets/d/11pse2j9nLimlgyGsxVCtcHY7vBRYchMFslR_rIReNiQ/edit?usp=sharing
function myFunction(event) {
Logger.log(SpreadsheetApp.getActive().getUrl());
Logger.log(JSON.stringify(event));
row_num = event.range.rowStart;
col_num = event.range.columnEnd;
drive_url = event["namedValues"]["Upload your spirit duck image"][0];
Logger.log(drive_url);
//get image from drive
// URL looks like: "https://drive.google.com/open?id=1RvOL6wT_7rXnOdjEsPl4Qi3Tm8F1K8Kk"
var id = drive_url.split('=')[1];
var file = DriveApp.getFileById(id);
var file_bytes = file.getBlob().getBytes();
labels = callVisionAPI(file_bytes);
SpreadsheetApp.getActiveSheet().getRange(row_num, col_num+1).setValue(labels.join(", "));
}
function form_stub() {
test_json = {"authMode":"FULL","namedValues":{"Upload your spirit duck image":["https://drive.google.com/open?id=1RvOL6wT_7rXnOdjEsPl4Qi3Tm8F1K8Kk"],"What is your favorite colour? ":[""],"Timestamp":["5/29/2020 15:43:02"],"What is your name?":["asdf"]},"range":{"columnEnd":4,"columnStart":1,"rowEnd":6,"rowStart":6},"source":{},"triggerUid":"3695078","values":["5/29/2020 15:43:02","asdf","","https://drive.google.com/open?id=1RvOL6wT_7rXnOdjEsPl4Qi3Tm8F1K8Kk"]}
myFunction(test_json);
}
function callVisionAPI(image_bytes) {
const payload = JSON.stringify({
requests: [{
image: {
content: Utilities.base64Encode(image_bytes)
},
features: [
{
type:"LABEL_DETECTION",
maxResults: 10
},
]
}]
});
// API_KEY should be defined in a separate file (or in this one)
// Get your API Key by going to APIs & Services > Credentials in your GCP Console: https://console.cloud.google.com/apis/credentials
const url = 'https://vision.googleapis.com/v1/images:annotate?key=' + API_KEY;
const response = UrlFetchApp.fetch(url, {
method: 'POST',
contentType: 'application/json',
payload: payload,
muteHttpExceptions: true
}).getContentText();
const json_resp = JSON.parse(response)
Logger.log(json_resp)
var labels = []
json_resp.responses[0].labelAnnotations.forEach(function (label) {
labels.push(label.description)
})
return labels
}
@PappuKP
Copy link

PappuKP commented May 29, 2020

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment