Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
}
24 changes: 24 additions & 0 deletions gmail-sentiment-analysis/Code.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/*
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) {
return buildCard_GmailHome();
}

49 changes: 49 additions & 0 deletions gmail-sentiment-analysis/Gmail.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
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 tested 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 😡");
let currentPrediction;

for (let i = 0 ; i < msgs.length; i++) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Prefer for..of or arr.forEach()

Examples:

for(let msg of msgs) {
 ...

or

msgs.forEach(msg => {
   ...
});

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My personal preference is the forEach method when looping over an array.
But the traditional for loop is significantly quicker. I've tested it and I think we should keep the code as is to make sure there aren't any timeouts.

for (let j = 0; j < msgs[i].length; j++) {
let emailText = msgs[i][j].getPlainBody();
currentPrediction = processSentiment(emailText);
if(currentPrediction === true){
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.
97 changes: 97 additions & 0 deletions gmail-sentiment-analysis/Vertex.gs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
/*
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 = 'gemini-1.5-pro-002';
const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key');

/**
* Packages prompt and necessary settings, then sends a request to
* Vertex API.
* A check is performed to see if the response from Vertex AI contains FALSE as a value.
* Returns the outcome of that check which is a boolean.
*
* @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 FALSE. If the sentiment of this message is neutral or positive, answer with TRUE. Do not use any other words than the ones requested in this prompt as a response!`;

const request = {
"contents": [{
"role": "user",
"parts": [{
"text": prompt
}]
}],
"generationConfig": {
"temperature": 0.9,
"maxOutputTokens": 1024,

}
};

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}:generateContent`

const response = UrlFetchApp.fetch(url, fetchOptions);
const payload = JSON.parse(response.getContentText());

const regex = /FALSE/;

return regex.test(payload.candidates[0].content.parts[0].text);

}

/**
* 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(),
}
}
27 changes: 27 additions & 0 deletions gmail-sentiment-analysis/appsscript.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"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
},
"gmail": {
"homepageTrigger": {
"runFunction": "onHomepage",
"enabled": true
}
}
},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8"
}
Loading