קישור ל-API: ניתוח סנטימנט של משוב

רמת הקידוד: בינונית
משך הזמן: 20 דקות
סוג הפרויקט: אוטומציה עם תפריט בהתאמה אישית

מטרות

  • להבין מה הפתרון עושה.
  • הסבר על הפעולות של שירותי Apps Script בפתרון.
  • מגדירים את הסביבה.
  • מגדירים את הסקריפט.
  • מריצים את הסקריפט.

מידע על הפתרון הזה

אתם יכולים לנתח כמויות גדולות של נתוני טקסט, כמו משוב פתוח. כדי לבצע ניתוח של ישויות וסנטימנטים מתוך Google Sheets, הפתרון הזה משתמש ב-UrlFetch Service כדי להתחבר אל Google Cloud Natural Language API.

תרשים שמציג איך ניתוח סנטימנטים עובד

איך זה עובד

הסקריפט אוסף טקסט מגיליון אלקטרוני ומתחבר אל Google Cloud Natural Language API כדי לנתח את היישויות והסנטימנט שמופיעים במחרוזת. בטבלת צירים מוצג סיכום של ציון הסנטימנט הממוצע לכל ישות שהוזכרה בכל השורות של נתוני הטקסט.

שירותי Apps Script

הפתרון הזה משתמש בשירותים הבאים:

  • שירות גיליון אלקטרוני – שולח את נתוני הטקסט אל Google Cloud Natural Language API ומסמן כל שורה כ-Complete (הושלם) אחרי ניתוח הסנטימנט שלה.
  • שירות UrlFetch – מתחבר אל Google Cloud Natural Language API כדי לבצע ניתוח של ישויות ושל סנטימנט בטקסט.

דרישות מוקדמות

כדי להשתמש בדוגמה הזו, אתם צריכים לעמוד בדרישות המוקדמות הבאות:

  • חשבון Google (יכול להיות שחשבונות Google Workspace ידרשו אישור אדמין).
  • דפדפן אינטרנט עם גישה לאינטרנט.

  • פרויקט ב-Google Cloud עם חשבון לחיוב שמשויך אליו. אפשר להיעזר במאמר הפעלת החיוב בפרויקט.

הגדרת הסביבה

פותחים את פרויקט Cloud במסוף Google Cloud

אם הוא לא פתוח, פותחים את פרויקט Cloud שבו רוצים להשתמש בדוגמה הזו:

  1. נכנסים לדף Select a project במסוף Google Cloud.

    בוחרים פרויקט ב-Cloud

  2. בוחרים את הפרויקט ב-Google Cloud שבו רוצים להשתמש. לחלופין, לוחצים על Create project ופועלים לפי ההוראות במסך. אם יוצרים פרויקט ב-Google Cloud, יכול להיות שיהיה צורך להפעיל את החיוב בפרויקט.

הפעלת Google Cloud Natural Language API

הפתרון הזה מתחבר ל-Google Cloud Natural Language API. לפני שאתם משתמשים בממשקי Google API, אם צריכים להפעיל אותם בפרויקט ב-Google Cloud. בכל פרויקט אפשר להפעיל ממשק API אחד או יותר.

  • בפרויקט Cloud, מפעילים את Google Cloud Natural Language API.

    הפעלת ה-API

הפתרון הזה דורש פרויקט ב-Cloud עם מסך הסכמה מוגדר. הגדרת מסך ההסכמה ל-OAuth קובעת מה Google מציגה למשתמשים, ורושמת את האפליקציה כדי שתוכלו לפרסם אותה בהמשך.

  1. במסוף Google Cloud, עוברים אל תפריט > Google Auth platform > Branding.

    מעבר לדף Branding

  2. אם כבר הגדרתם את Google Auth platform, אתם יכולים לקבוע את ההגדרות הבאות של מסך ההסכמה ל-OAuth בקטעים Branding,‏ Audience וData Access. אם מופיעה ההודעה Google Auth platform not configured yet, לוחצים על Get Started:
    1. בקטע App Information בשדה App name, מזינים שם לאפליקציה.
    2. בקטע User support email, בוחרים כתובת אימייל לתמיכה שאליה משתמשים יפנו אם יש להם שאלות לגבי ההסכמה שלהם.
    3. לוחצים על Next.
    4. בקטע Audience, לוחצים על Internal.
    5. לוחצים על Next.
    6. בקטע Contact Information, מזינים כתובת אימייל שאליה אפשר לשלוח התראות על שינויים בפרויקט.
    7. לוחצים על Next.
    8. בקטע Finish, קוראים את המדיניות של Google בנושא נתוני משתמשים בשירותי API. אם אתם מסכימים, מסמנים את התיבה I agree to the Google API Services: User Data Policy.
    9. לוחצים על Continue.
    10. לוחצים על Create.
  3. כרגע אתם יכולים לדלג על הוספת היקפי הרשאות. בעתיד, כשתיצרו אפליקציה לשימוש מחוץ לארגון שלכם ב-Google Workspace, תצטרכו לשנות את סוג המשתמש ל-External. לאחר מכן מוסיפים את היקפי ההרשאות שהאפליקציה דורשת. למידע נוסף, אפשר לעיין במדריך המלא בנושא הגדרת הסכמה ל-OAuth.

קבלת מפתח API ל-Google Cloud Natural Language API

  1. נכנסים למסוף Google Cloud. מוודאים שהפרויקט שמוגדר בו חיוב פתוח.
  2. במסוף Google Cloud, לוחצים על סמל התפריט > APIs & Services> Credentials.

    כניסה לדף Credentials

  3. לוחצים על Create credentials > API key.

  4. חשוב לשמור את מפתח ה-API כי תצטרכו אותו בשלב מאוחר יותר.

הגדרת הסקריפט

יצירת פרויקט Apps Script

  1. לוחצים על הלחצן שלמטה כדי ליצור עותק של גיליון אלקטרוני לדוגמה של ניתוח סנטימנט למשוב. פרויקט Apps Script של הפתרון הזה מצורף לגיליון האלקטרוני.
    יצירת עותק
  2. לוחצים על תוספים > Apps Script.
  3. מעדכנים את המשתנה הבא בקובץ הסקריפט עם מפתח ה-API:
    const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.
  4. לוחצים על סמל השמירה סמל השמירה.

הוספת נתוני טקסט

  1. חוזרים לגיליון האלקטרוני.
  2. מוסיפים נתוני טקסט לעמודות id וcomments. אתם יכולים להשתמש בדוגמאות לביקורות על נכסי נופש מ-Kaggle או להשתמש בנתונים שלכם. אפשר להוסיף עוד עמודות לפי הצורך, אבל כדי שהסקריפט יפעל בצורה תקינה, צריך להזין נתונים בעמודות id ו-comments.

הפעלת הסקריפט

  1. בחלק העליון של הגיליון האלקטרוני, לוחצים על Sentiment Tools (כלי ניתוח סנטימנט) > Mark entities and sentiment (סימון ישויות וסנטימנט). יכול להיות שתצטרכו לרענן את הדף כדי שהתפריט המותאם אישית יופיע.
  2. כשמוצגת בקשה, מאשרים את הסקריפט. אם במסך ההסכמה ל-OAuth מוצגת האזהרה האפליקציה הזו לא אומתה, ממשיכים בתהליך על ידי בחירה באפשרות מתקדם > מעבר אל {שם הפרויקט} (לא בטוח).

  3. לוחצים על Sentiment Tools (כלים לניתוח סנטימנט) > Mark entities and sentiment (סימון ישויות וסנטימנט) שוב.

  4. כשהסקריפט יסיים את הפעולה, עוברים לגיליון Pivot Table כדי לראות את התוצאות.

בדיקת הקוד

כדי לבדוק את קוד Apps Script של הפתרון הזה, לוחצים על הצגת קוד המקור למטה:

הצגת קוד המקור

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

תורמים

הדוגמה הזו מתוחזקת על ידי Google בעזרת מומחי Google לפיתוח.

השלבים הבאים