Created
May 29, 2020 20:24
-
-
Save yufengg/113d0fdcb5a53d074eb5586a715d6fc3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you