Skip to content

Commit 1e5f10a

Browse files
committed
Put gmail sentiment analysis into ai folder.
1 parent 9847368 commit 1e5f10a

File tree

6 files changed

+295
-0
lines changed

6 files changed

+295
-0
lines changed

ai/gmail-sentiment-analysis/Cards.gs

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
18+
/**
19+
* Builds the card for to display in the sidepanel of gmail.
20+
* @return {CardService.Card} The card to show to the user.
21+
*/
22+
23+
function buildCard_GmailHome(notifyOk=false){
24+
const imageUrl ='https://icons.iconarchive.com/icons/roundicons/100-free-solid/48/spy-icon.png';
25+
const image = CardService.newImage()
26+
.setImageUrl(imageUrl);
27+
28+
const cardHeader = CardService.newCardHeader()
29+
.setImageUrl(imageUrl)
30+
.setImageStyle(CardService.ImageStyle.CIRCLE)
31+
.setTitle("Analyze your GMail");
32+
33+
const action = CardService.newAction()
34+
.setFunctionName('analyzeSentiment');
35+
const button = CardService.newTextButton()
36+
.setText('Identify angry customers')
37+
.setOnClickAction(action)
38+
.setTextButtonStyle(CardService.TextButtonStyle.FILLED);
39+
const buttonSet = CardService.newButtonSet()
40+
.addButton(button);
41+
42+
const section = CardService.newCardSection()
43+
.setHeader("Emails sentiment analysis")
44+
.addWidget(buttonSet);
45+
46+
const card = CardService.newCardBuilder()
47+
.setHeader(cardHeader)
48+
.addSection(section);
49+
50+
/**
51+
* This builds the card that contains the footer that informs
52+
* the user about the successful execution of the Add-on.
53+
*/
54+
55+
if(notifyOk==true){
56+
let fixedFooter = CardService.newFixedFooter()
57+
.setPrimaryButton(
58+
CardService.newTextButton()
59+
.setText("Analysis complete")
60+
.setOnClickAction(
61+
CardService.newAction()
62+
.setFunctionName(
63+
"buildCard_GmailHome")));
64+
card.setFixedFooter(fixedFooter);
65+
}
66+
return card.build();
67+
}

ai/gmail-sentiment-analysis/Code.gs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
/**
18+
* Callback for rendering the homepage card.
19+
* @return {CardService.Card} The card to show to the user.
20+
*/
21+
function onHomepage(e) {
22+
return buildCard_GmailHome();
23+
}
24+

ai/gmail-sentiment-analysis/Gmail.gs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
/**
18+
* Callback for initiating the sentiment analysis.
19+
* @return {CardService.Card} The card to show to the user.
20+
*/
21+
22+
function analyzeSentiment(){
23+
emailSentiment();
24+
return buildCard_GmailHome(true);
25+
}
26+
27+
/**
28+
* Gets the last 10 threads in the inbox and the corresponding messages.
29+
* Fetches the label that should be applied to negative messages.
30+
* The processSentiment is called on each message
31+
* and tested with RegExp to check for a negative answer from the model
32+
*/
33+
34+
function emailSentiment() {
35+
const threads = GmailApp.getInboxThreads(0, 10);
36+
const msgs = GmailApp.getMessagesForThreads(threads);
37+
const label_upset = GmailApp.getUserLabelByName("UPSET TONE 😡");
38+
let currentPrediction;
39+
40+
for (let i = 0 ; i < msgs.length; i++) {
41+
for (let j = 0; j < msgs[i].length; j++) {
42+
let emailText = msgs[i][j].getPlainBody();
43+
currentPrediction = processSentiment(emailText);
44+
if(currentPrediction === true){
45+
label_upset.addToThread(msgs[i][j].getThread());
46+
}
47+
}
48+
}
49+
}

ai/gmail-sentiment-analysis/README.md

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Gmail sentiment analysis with Vertex AI
2+
3+
## Project Description
4+
5+
Google Workspace Add-on that extends Gmail and adds sentiment analysis capabilities.
6+
7+
## Prerequisites
8+
9+
* Google Cloud Project (aka Standard Cloud Project for Apps Script) with billing enabled
10+
11+
## Set up your environment
12+
13+
1. Create a Cloud Project
14+
1. Enable the Vertex AI API
15+
1. Create a Service Account and grant the role `Vertex AI User`
16+
1. Create a private key with type JSON. This will download the JSON file for use in the next section.
17+
1. Open an Apps Script Project bound to a Google Sheets Spreadsheet
18+
1. From Project Settings, change project to GCP project number of Cloud Project from step 1
19+
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.
20+
1. Add OAuth2 v43 Apps Script Library using the ID `1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF`.
21+
1. Add the project code to Apps Script
22+
23+
## Usage
24+
25+
1. Create a label in Gmail with this exact text and emojy (case sensitive!): UPSET TONE 😡
26+
1. In Gmail, click on the Productivity toolbox icon (icon of a spy) in the sidepanel.
27+
1. The sidepanel will open up. Grant the Add-on autorization to run.
28+
1. The Add-on will load. Click on the blue button "Identify angry customers."
29+
1. Close the Add-on by clicking on the X in the top right corner.
30+
1. It can take a couple of minutes until the label is applied to the messages that have a negative tone.
31+
1. If you don't want to wait until the labels are added, you can refresh the browser.

ai/gmail-sentiment-analysis/Vertex.gs

+97
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
/*
2+
Copyright 2024 Google LLC
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
https://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
const PROJECT_ID = [ADD YOUR GCP PROJECT ID HERE];
18+
const VERTEX_AI_LOCATION = 'europe-west2';
19+
const MODEL_ID = 'gemini-1.5-pro-002';
20+
const SERVICE_ACCOUNT_KEY = PropertiesService.getScriptProperties().getProperty('service_account_key');
21+
22+
/**
23+
* Packages prompt and necessary settings, then sends a request to
24+
* Vertex API.
25+
* A check is performed to see if the response from Vertex AI contains FALSE as a value.
26+
* Returns the outcome of that check which is a boolean.
27+
*
28+
* @param emailText - Email message that is sent to the model.
29+
*/
30+
31+
function processSentiment(emailText) {
32+
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!`;
33+
34+
const request = {
35+
"contents": [{
36+
"role": "user",
37+
"parts": [{
38+
"text": prompt
39+
}]
40+
}],
41+
"generationConfig": {
42+
"temperature": 0.9,
43+
"maxOutputTokens": 1024,
44+
45+
}
46+
};
47+
48+
const credentials = credentialsForVertexAI();
49+
50+
const fetchOptions = {
51+
method: 'POST',
52+
headers: {
53+
'Authorization': `Bearer ${credentials.accessToken}`
54+
},
55+
contentType: 'application/json',
56+
muteHttpExceptions: true,
57+
payload: JSON.stringify(request)
58+
}
59+
60+
const url = `https://${VERTEX_AI_LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/`
61+
+ `locations/${VERTEX_AI_LOCATION}/publishers/google/models/${MODEL_ID}:generateContent`
62+
63+
const response = UrlFetchApp.fetch(url, fetchOptions);
64+
const payload = JSON.parse(response.getContentText());
65+
66+
const regex = /FALSE/;
67+
68+
return regex.test(payload.candidates[0].content.parts[0].text);
69+
70+
}
71+
72+
/**
73+
* Gets credentials required to call Vertex API using a Service Account.
74+
* Requires use of Service Account Key stored with project
75+
*
76+
* @return {!Object} Containing the Cloud Project Id and the access token.
77+
*/
78+
79+
function credentialsForVertexAI() {
80+
const credentials = SERVICE_ACCOUNT_KEY;
81+
if (!credentials) {
82+
throw new Error("service_account_key script property must be set.");
83+
}
84+
85+
const parsedCredentials = JSON.parse(credentials);
86+
87+
const service = OAuth2.createService("Vertex")
88+
.setTokenUrl('https://oauth2.googleapis.com/token')
89+
.setPrivateKey(parsedCredentials['private_key'])
90+
.setIssuer(parsedCredentials['client_email'])
91+
.setPropertyStore(PropertiesService.getScriptProperties())
92+
.setScope("https://www.googleapis.com/auth/cloud-platform");
93+
return {
94+
projectId: parsedCredentials['project_id'],
95+
accessToken: service.getAccessToken(),
96+
}
97+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
{
2+
"timeZone": "Europe/Madrid",
3+
"dependencies": {
4+
"libraries": [
5+
{
6+
"userSymbol": "OAuth2",
7+
"version": "43",
8+
"libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
9+
}
10+
]
11+
},
12+
"addOns": {
13+
"common": {
14+
"name": "Productivity toolbox",
15+
"logoUrl": "https://icons.iconarchive.com/icons/roundicons/100-free-solid/64/spy-icon.png",
16+
"useLocaleFromApp": true
17+
},
18+
"gmail": {
19+
"homepageTrigger": {
20+
"runFunction": "onHomepage",
21+
"enabled": true
22+
}
23+
}
24+
},
25+
"exceptionLogging": "STACKDRIVER",
26+
"runtimeVersion": "V8"
27+
}

0 commit comments

Comments
 (0)