Menghubungkan ke API: Menganalisis sentimen masukan

Level coding: Menengah
Durasi: 20 menit
Jenis project: Otomatisasi dengan menu kustom

Tujuan

  • Pahami fungsi solusi tersebut.
  • Pahami fungsi layanan Apps Script dalam solusi tersebut.
  • Menyiapkan lingkungan Anda.
  • Siapkan skrip.
  • Jalankan skrip.

Tentang solusi ini

Anda dapat menganalisis data teks, seperti masukan terbuka, dalam skala besar. Untuk menjalankan analisis sentimen dan entity dari dalam Google Spreadsheet, solusi ini menggunakan UrlFetch Service untuk terhubung ke Google Cloud Natural Language API.

diagram cara kerja analisis sentimen

Cara kerjanya

Skrip ini mengumpulkan teks dari spreadsheet dan terhubung ke Google Cloud Natural Language API untuk menganalisis entity dan sentimen yang ada dalam string. Tabel pivot merangkum skor sentimen rata-rata untuk setiap entity yang disebutkan di semua baris data teks.

Layanan Apps Script

Solusi ini menggunakan layanan berikut:

  • Layanan spreadsheet–Mengirim data teks ke Google Cloud Natural Language API dan menandai setiap baris sebagai "Selesai" setelah sentimennya dianalisis.
  • Layanan UrlFetch–Menghubungkan ke Google Cloud Natural Language API untuk melakukan analisis entity dan sentimen pada teks.

Prasyarat

Untuk menggunakan sampel ini, Anda memerlukan prasyarat berikut:

  • Akun Google (akun Google Workspace mungkin memerlukan persetujuan administrator).
  • Browser web dengan akses ke internet.

  • Project Google Cloud dengan akun penagihan terkait. Lihat Mengaktifkan penagihan untuk project.

Menyiapkan lingkungan Anda

Buka project Cloud Anda di konsol Google Cloud

Jika belum terbuka, buka project Cloud yang ingin Anda gunakan untuk contoh ini:

  1. Di konsol Google Cloud, buka halaman Select a project.

    Memilih project Cloud

  2. Pilih project Google Cloud yang ingin Anda gunakan. Atau, klik Buat project dan ikuti petunjuk di layar. Jika membuat project Google Cloud, Anda mungkin perlu mengaktifkan penagihan untuk project tersebut.

Mengaktifkan Google Cloud Natural Language API

Solusi ini terhubung ke Google Cloud Natural Language API. Sebelum menggunakan Google API, Anda harus mengaktifkannya di project Google Cloud. Anda dapat mengaktifkan satu atau beberapa API dalam satu project Google Cloud.

Solusi ini memerlukan project Cloud dengan layar izin yang telah dikonfigurasi. Mengonfigurasi layar izin OAuth akan menentukan apa yang ditampilkan Google kepada pengguna dan mendaftarkan aplikasi Anda agar dapat dipublikasikan nanti.

  1. Di konsol Google Cloud, buka Menu > APIs & Services > OAuth consent screen.

    Buka layar izin OAuth

  2. Untuk Jenis pengguna, pilih Internal, lalu klik Buat.
  3. Lengkapi formulir pendaftaran aplikasi, lalu klik Simpan dan Lanjutkan.
  4. Untuk saat ini, Anda dapat melewati penambahan cakupan dan mengklik Simpan dan Lanjutkan. Pada masa mendatang, saat membuat aplikasi untuk digunakan di luar organisasi Google Workspace, Anda harus mengubah User type menjadi External, lalu tambahkan cakupan otorisasi yang diperlukan aplikasi Anda.

  5. Tinjau ringkasan pendaftaran aplikasi Anda. Untuk melakukan perubahan, klik Edit. Jika pendaftaran aplikasi terlihat baik-baik saja, klik Back to Dashboard.

Mendapatkan kunci API untuk Google Cloud Natural Language API

  1. Buka Konsol Google Cloud. Pastikan project Anda yang mendukung penagihan terbuka.
  2. Di konsol Google Cloud, buka Menu > APIs & Services > Credentials.

    Buka Kredensial

  3. Klik Create credentials > API key.

  4. Catat kunci API Anda untuk digunakan di langkah berikutnya.

Menyiapkan skrip

Membuat project Apps Script

  1. Klik tombol di bawah untuk membuat salinan spreadsheet contoh Analisis sentimen untuk masukan. Project Apps Script untuk solusi ini dilampirkan pada spreadsheet.
    Buat salinan
  2. Klik Ekstensi > Apps Script.
  3. Perbarui variabel berikut di file skrip dengan kunci API Anda:
    const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.
  4. Klik Simpan Ikon simpan.

Menambahkan data teks

  1. Kembali ke {i>spreadsheet<i}.
  2. Tambahkan data teks ke kolom id dan comments. Anda dapat menggunakan contoh ulasan properti liburan dari Kaggle atau menggunakan data Anda sendiri. Anda dapat menambahkan lebih banyak kolom jika diperlukan, tetapi agar berhasil dijalankan, skrip harus memiliki data di kolom id dan comments.

Jalankan skrip:

  1. Di bagian atas spreadsheet, klik Sentiment Tools > Tandai entity dan sentimen. Anda mungkin perlu memuat ulang halaman agar menu kustom ini muncul.
  2. Jika diminta, izinkan skrip. Jika layar izin OAuth menampilkan peringatan, This app don't verified, lanjutkan dengan memilih Advanced > Buka {Project Name} (unsafe).

  3. Klik Sentiment Tools > Tandai entity dan sentimen lagi.

  4. Setelah skrip selesai, beralihlah ke sheet Pivot Table untuk melihat hasilnya.

Meninjau kode

Untuk meninjau kode Apps Script untuk solusi ini, klik Lihat kode sumber di bawah:

Melihat kode sumber

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);
};

Kontributor

Contoh ini dikelola oleh Google dengan bantuan Pakar Google Developers.

Langkah berikutnya