Conexão a uma API: analise o sentimento do feedback

Nível de programação: intermediário
Duração: 20 minutos
Tipo de projeto: automação com um menu personalizado

Objetivos

  • Entenda o que a solução faz.
  • Entenda o que os serviços do Apps Script fazem na solução.
  • Configurar o ambiente.
  • Configure o script.
  • Execute o script.

Sobre esta solução

É possível analisar dados de texto, como feedback aberto, em escala. Para realizar análises de entidade e de sentimento nas Planilhas Google, esta solução usa o UrlFetch Service para se conectar à API Google Cloud Natural Language.

diagrama de como funciona a análise de sentimento

Como funciona

O script coleta o texto da planilha e se conecta à API Google Cloud Natural Language para analisar as entidades e o sentimento presentes na string. Uma tabela dinâmica resume a pontuação de sentimento média de cada entidade mencionada em todas as linhas de dados de texto.

Serviços do Apps Script

Essa solução usa os seguintes serviços:

  • Serviço de planilha: envia os dados de texto para a API Google Cloud Natural Language e marca cada linha como "Concluída" depois que o sentimento é analisado.
  • Serviço UrlFetch: conecta-se à API Google Cloud Natural Language para realizar análises de entidade e de sentimento no texto.

Pré-requisitos

Para usar essa amostra, você precisa dos seguintes pré-requisitos:

  • Uma Conta do Google (contas do Google Workspace podem exigir a aprovação do administrador).
  • Um navegador da Web com acesso à Internet.

  • Um projeto do Google Cloud com uma conta de faturamento associada. Consulte Ativar o faturamento de um projeto.

configurar o ambiente

Abra seu projeto do Cloud no console do Google Cloud.

Se ainda não estiver aberto, abra o projeto do Cloud que você pretende usar para esta amostra:

  1. No console do Google Cloud, acesse a página Selecionar um projeto.

    Selecionar um projeto do Cloud

  2. Selecione o projeto do Google Cloud que você quer usar. Ou clique em Criar projeto e siga as instruções na tela. Se você criar um projeto do Google Cloud, talvez seja necessário ativar o faturamento dele.

Ative a API Google Cloud Natural Language

Esta solução se conecta à API Google Cloud Natural Language. Antes de usar as APIs do Google, é preciso ativá-las em um projeto do Google Cloud. É possível ativar uma ou mais APIs em um único projeto do Google Cloud.

  • No projeto do Cloud, ative a API Google Cloud Natural Language.

    Ativar a API

Essa solução requer um projeto do Cloud com uma tela de consentimento configurada. A configuração da tela de consentimento OAuth define o que o Google exibe aos usuários e registra seu app para que você possa publicá-lo mais tarde.

  1. No console do Google Cloud, acesse Menu > APIs e serviços > Tela de permissão OAuth.

    Acessar a tela de permissão OAuth

  2. Em Tipo de usuário, selecione Interno e clique em Criar.
  3. Preencha o formulário de registro do app e clique em Salvar e continuar.
  4. Por enquanto, é possível pular a adição de escopos e clicar em Salvar e continuar. No futuro, quando você criar um app para uso fora da sua organização do Google Workspace, será necessário alterar o Tipo de usuário para Externo e, em seguida, adicionar os escopos de autorização exigidos pelo app.

  5. Analise o resumo de registro do seu app. Para fazer mudanças, clique em Editar. Se o registro do app estiver correto, clique em Voltar para o painel.

Gerar uma chave de API para a API Google Cloud Natural Language

  1. Acesse o Console do Google Cloud. Verifique se o projeto com faturamento ativado está aberto.
  2. No console do Google Cloud, acesse Menu > APIs e serviços > Credenciais.

    Ir para Credenciais

  3. Clique em Criar credenciais > Chave de API.

  4. Anote sua chave de API para usar em uma etapa posterior.

Configurar o script

Criar o projeto do Apps Script

  1. Clique no botão abaixo para fazer uma cópia da planilha de amostra Análise de sentimento para feedback. O projeto do Apps Script para esta solução está anexado à planilha.
    Fazer uma cópia
  2. Clique em Extensões > Apps Script.
  3. Atualize a seguinte variável no arquivo de script com sua chave de API:
    const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.
  4. Clique em Salvar Ícone "Salvar".

Adicionar dados de texto

  1. Volte para a planilha.
  2. Adicione dados de texto às colunas id e comments. Você pode usar um exemplo de avaliações de propriedades de férias da Kaggle (link em inglês) ou seus próprios dados. É possível adicionar mais colunas, se necessário. No entanto, para ser executado com sucesso, o script precisa ter dados nas colunas id e comments.

Executar o script

  1. Na parte de cima da planilha, clique em Ferramentas de sentimento > Marcar entidades e sentimento. Talvez seja necessário atualizar a página para que esse menu personalizado apareça.
  2. Quando solicitado, autorize o script. Se a tela de permissão OAuth mostrar o aviso Este app não foi verificado, continue selecionando Avançado > Acessar {Nome do projeto} (não seguro).

  3. Clique em Ferramentas de sentimento > Marcar entidades e sentimento novamente.

  4. Quando o script for concluído, mude para a página Tabela dinâmica para ver os resultados.

Revisar o código

Para analisar o código do Apps Script para esta solução, clique em Ver código-fonte abaixo:

Ver o código-fonte

Code.gs

solutions/automations/feedback-sentiment-analysis/code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/feedback-sentiment-analysis

/*
Copyright 2022 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.
*/

// Sets API key for accessing Cloud Natural Language API.
const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.

// Matches column names in Review Data sheet to variables.
let COLUMN_NAME = {
  COMMENTS: 'comments',
  ENTITY: 'entity_sentiment',
  ID: 'id'
};

/**
 * Creates a Demo menu in Google Spreadsheets.
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Sentiment Tools')
    .addItem('Mark entities and sentiment', 'markEntitySentiment')
    .addToUi();
};

/**
* Analyzes entities and sentiment for each comment in  
* Review Data sheet and copies results into the 
* Entity Sentiment Data sheet.
*/
function markEntitySentiment() {
  // Sets variables for "Review Data" sheet
  let ss = SpreadsheetApp.getActiveSpreadsheet();
  let dataSheet = ss.getSheetByName('Review Data');
  let rows = dataSheet.getDataRange();
  let numRows = rows.getNumRows();
  let values = rows.getValues();
  let headerRow = values[0];

  // Checks to see if "Entity Sentiment Data" sheet is present, and
  // if not, creates a new sheet and sets the header row.
  let entitySheet = ss.getSheetByName('Entity Sentiment Data');
  if (entitySheet == null) {
   ss.insertSheet('Entity Sentiment Data');
   let entitySheet = ss.getSheetByName('Entity Sentiment Data');
   let esHeaderRange = entitySheet.getRange(1,1,1,6);
   let esHeader = [['Review ID','Entity','Salience','Sentiment Score',
                    'Sentiment Magnitude','Number of mentions']];
   esHeaderRange.setValues(esHeader);
  };

  // Finds the column index for comments, language_detected, 
  // and comments_english columns.
  let textColumnIdx = headerRow.indexOf(COLUMN_NAME.COMMENTS);
  let entityColumnIdx = headerRow.indexOf(COLUMN_NAME.ENTITY);
  let idColumnIdx = headerRow.indexOf(COLUMN_NAME.ID);
  if (entityColumnIdx == -1) {
    Browser.msgBox("Error: Could not find the column named " + COLUMN_NAME.ENTITY + 
                   ". Please create an empty column with header \"entity_sentiment\" on the Review Data tab.");
    return; // bail
  };

  ss.toast("Analyzing entities and sentiment...");
  for (let i = 0; i < numRows; ++i) {
    let value = values[i];
    let commentEnCellVal = value[textColumnIdx];
    let entityCellVal = value[entityColumnIdx];
    let reviewId = value[idColumnIdx];

    // Calls retrieveEntitySentiment function for each row that has a comment 
    // and also an empty entity_sentiment cell value.
    if(commentEnCellVal && !entityCellVal) {
        let nlData = retrieveEntitySentiment(commentEnCellVal);
        // Pastes each entity and sentiment score into Entity Sentiment Data sheet.
        let newValues = []
        for (let entity in nlData.entities) {
          entity = nlData.entities [entity];
          let row = [reviewId, entity.name, entity.salience, entity.sentiment.score, 
                     entity.sentiment.magnitude, entity.mentions.length
                    ];
          newValues.push(row);
        }
      if(newValues.length) {
        entitySheet.getRange(entitySheet.getLastRow() + 1, 1, newValues.length, newValues[0].length).setValues(newValues);
      }
        // Pastes "complete" into entity_sentiment column to denote completion of NL API call.
        dataSheet.getRange(i+1, entityColumnIdx+1).setValue("complete");
     }
   }
};

/**
 * Calls the Cloud Natural Language API with a string of text to analyze
 * entities and sentiment present in the string.
 * @param {String} the string for entity sentiment analysis
 * @return {Object} the entities and related sentiment present in the string
 */
function retrieveEntitySentiment (line) {
  let apiKey = myApiKey;
  let apiEndpoint = 'https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=' + apiKey;
  // Creates a JSON request, with text string, language, type and encoding
  let nlData = {
    document: {
      language: 'en-us',
      type: 'PLAIN_TEXT',
      content: line
    },
    encodingType: 'UTF8'
  };
  // Packages all of the options and the data together for the API call.
  let nlOptions = {
    method : 'post',
    contentType: 'application/json',  
    payload : JSON.stringify(nlData)
  };
  // Makes the API call.
  let response = UrlFetchApp.fetch(apiEndpoint, nlOptions);
  return JSON.parse(response);
};

Colaboradores

Esta amostra é mantida pelo Google com a ajuda de especialistas do Google Developers.

Próximas etapas