Skip to content

Commit

Permalink
Add new sample that is for a Google Workspace Add-on that adds sentim…
Browse files Browse the repository at this point in the history
…ent analysis capabilities to Gmail.
  • Loading branch information
chanelgreco committed Oct 18, 2024
1 parent 3a18325 commit 8760fa1
Show file tree
Hide file tree
Showing 6 changed files with 298 additions and 0 deletions.
67 changes: 67 additions & 0 deletions gmail-sentiment-analysis/Cards.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/


/**
* Builds the card for to display in the sidepanel of gmail.
* @return {CardService.Card} The card to show to the user.
*/

function buildCard_GmailHome(notifyOk=false){
const imageUrl ='https://icons.iconarchive.com/icons/roundicons/100-free-solid/48/spy-icon.png';
const image = CardService.newImage()
.setImageUrl(imageUrl);

const cardHeader = CardService.newCardHeader()
.setImageUrl(imageUrl)
.setImageStyle(CardService.ImageStyle.CIRCLE)
.setTitle("Analyze your GMail");

const action = CardService.newAction()
.setFunctionName('analyzeSentiment');
const button = CardService.newTextButton()
.setText('Identify angry customers')
.setOnClickAction(action)
.setTextButtonStyle(CardService.TextButtonStyle.FILLED);
const buttonSet = CardService.newButtonSet()
.addButton(button);

const section = CardService.newCardSection()
.setHeader("Emails sentiment analysis")
.addWidget(buttonSet);

const card = CardService.newCardBuilder()
.setHeader(cardHeader)
.addSection(section);

/**
* This builds the card that contains the footer that informs
* the user about the successful execution of the Add-on.
*/

if(notifyOk==true){
let fixedFooter = CardService.newFixedFooter()
.setPrimaryButton(
CardService.newTextButton()
.setText("Analysis complete")
.setOnClickAction(
CardService.newAction()
.setFunctionName(
"buildCard_GmailHome")));
card.setFixedFooter(fixedFooter);
}
return card.build();
}
25 changes: 25 additions & 0 deletions gmail-sentiment-analysis/Code.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
* Callback for rendering the homepage card.
* @return {CardService.Card} The card to show to the user.
*/
function onHomepage(e) {
if(e.hostApp =="gmail"){
return buildCard_GmailHome();
}
}
50 changes: 50 additions & 0 deletions gmail-sentiment-analysis/Gmail.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/**
* Callback for initiating the sentiment analysis.
* @return {CardService.Card} The card to show to the user.
*/

function analyzeSentiment(){
emailSentiment();
return buildCard_GmailHome(true);
}

/**
* Gets the last 10 threads in the inbox and the corresponding messages.
* Fetches the label that should be applied to negative messages.
* The processSentiment is called on each message
* and testet with RegExp to check for a negative answer from the model
*/

function emailSentiment() {
const threads = GmailApp.getInboxThreads(0, 10);
const msgs = GmailApp.getMessagesForThreads(threads);
const label_upset = GmailApp.getUserLabelByName("UPSET TONE 😡");
const regex = new RegExp('N');
let currentPrediction;

for (let i = 0 ; i < msgs.length; i++) {
for (let j = 0; j < msgs[i].length; j++) {
let emailText = msgs[i][j].getPlainBody();
currentPrediction = processSentiment(emailText);
if(regex.test(currentPrediction)){
label_upset.addToThread(msgs[i][j].getThread());
}
}
}
}
31 changes: 31 additions & 0 deletions gmail-sentiment-analysis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Gmail sentiment analysis with Vertex AI

## Project Description

Google Workspace Add-on that extends Gmail and adds sentiment analysis capabilities.

## Prerequisites

* Google Cloud Project (aka Standard Cloud Project for Apps Script) with billing enabled

## Set up your environment

1. Create a Cloud Project
1. Enable the Vertex AI API
1. Create a Service Account and grant the role `Vertex AI User`
1. Create a private key with type JSON. This will download the JSON file for use in the next section.
1. Open an Apps Script Project bound to a Google Sheets Spreadsheet
1. From Project Settings, change project to GCP project number of Cloud Project from step 1
1. Add a Script Property. Enter `service_account_key` as the property name and paste the JSON key from the service account as the value.
1. Add OAuth2 v43 Apps Script Library using the ID `1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF`.
1. Add the project code to Apps Script

## Usage

1. Create a label in Gmail with this exact text and emojy (case sensitive!): UPSET TONE 😡
1. In Gmail, click on the Productivity toolbox icon (icon of a spy) in the sidepanel.
1. The sidepanel will open up. Grant the Add-on autorization to run.
1. The Add-on will load. Click on the blue button "Identify angry customers."
1. Close the Add-on by clicking on the X in the top right corner.
1. It can take a couple of minutes until the label is applied to the messages that have a negative tone.
1. If you don't want to wait until the labels are added, you can refresh the browser.
92 changes: 92 additions & 0 deletions gmail-sentiment-analysis/Vertex.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

const PROJECT_ID = [ADD YOUR GCP PROJECT ID HERE];
const VERTEX_AI_LOCATION = 'europe-west2';
const MODEL_ID = 'text-bison';
const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key');

/**
* Packages prompt and necessary settings, then sends a request to
* Vertex API. Returns the response as an JSON object extracted from the
* Vertex API response object.
*
* @param emailText - Email message that is sent to the model.
*/

function processSentiment(emailText) {
const prompt = `Analyze the following message: ${emailText}. If the sentiment of this message is negative, answer with NEGATIVE. If the sentiment of this message is neutral or positive, answer with OK. Do not use any other words than the ones requested in this prompt as a response!`;
const request = {
"instances": [{
"prompt": prompt
}],
"parameters": {
"temperature": 0.9,
"maxOutputTokens": 1024,
"topK": 1,
"topP": 1
},

};

const credentials = credentialsForVertexAI();

const fetchOptions = {
method: 'POST',
headers: {
'Authorization': `Bearer ${credentials.accessToken}`
},
contentType: 'application/json',
muteHttpExceptions: true,
payload: JSON.stringify(request)
}

const url = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/`
+ `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:predict`

const response = UrlFetchApp.fetch(url, fetchOptions);
const payload = JSON.parse(response.getContentText());
console.log(payload.predictions[0].content);

return payload.predictions[0].content;
}

/**
* Gets credentials required to call Vertex API using a Service Account.
* Requires use of Service Account Key stored with project
*
* @return {!Object} Containing the Cloud Project Id and the access token.
*/

function credentialsForVertexAI() {
const credentials = SERVICE_ACCOUNT_KEY;
if (!credentials) {
throw new Error("service_account_key script property must be set.");
}

const parsedCredentials = JSON.parse(credentials);

const service = OAuth2.createService("Vertex")
.setTokenUrl('https://oauth2.googleapis.com/token')
.setPrivateKey(parsedCredentials['private_key'])
.setIssuer(parsedCredentials['client_email'])
.setPropertyStore(PropertiesService.getScriptProperties())
.setScope("https://www.googleapis.com/auth/cloud-platform");
return {
projectId: parsedCredentials['project_id'],
accessToken: service.getAccessToken(),
}
}
33 changes: 33 additions & 0 deletions gmail-sentiment-analysis/appsscript.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"timeZone": "Europe/Madrid",
"dependencies": {
"libraries": [
{
"userSymbol": "OAuth2",
"version": "43",
"libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
}
]
},
"addOns": {
"common": {
"name": "Productivity toolbox",
"logoUrl": "https://icons.iconarchive.com/icons/roundicons/100-free-solid/64/spy-icon.png",
"useLocaleFromApp": true,
"homepageTrigger": {
"runFunction": "onHomepage",
"enabled": true
}
},
"gmail": {
"contextualTriggers": [
{
"unconditional": {},
"onTriggerFunction": "onGmailMessage"
}
]
}
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}

0 comments on commit 8760fa1

Please sign in to comment.