تحليل آراء العملاء باستخدام Google Cloud Natural Language API

مستوى الترميز: متوسط
المدة: 20 دقيقة
نوع المشروع: أتمتة باستخدام قائمة مخصّصة

الأهداف

  • فهم ما يفعله الحلّ
  • فهم وظائف خدمات Apps Script ضمن الحلّ
  • إعداد البيئة
  • إعداد النص البرمجي
  • شغِّل النص البرمجي.

لمحة عن هذا الحل

يمكنك تحليل البيانات النصية، مثل التعليقات المفتوحة، على نطاق واسع. لإجراء تحليل للكيانات والمشاعر من داخل "جداول بيانات Google"، يستخدم هذا الحل خدمة UrlFetch للاتصال بواجهة Google Cloud Natural Language API.

مخطّط يوضّح طريقة عمل تحليل المشاعر

آلية العمل

يجمع النص البرمجي النص من جدول البيانات ويتصل بواجهة Google Cloud Natural Language API لتحليل الكيانات والمشاعر الواردة في السلسلة. يلخّص الجدول المحوري متوسط نتيجة المشاعر لكل كيان مذكور في جميع صفوف البيانات النصية.

خدمات "برمجة تطبيقات Google"

يستخدم هذا الحل الخدمات التالية:

  • خدمة جداول البيانات: ترسل بيانات النص إلى واجهة برمجة التطبيقات Natural Language API من Google Cloud، وتضع علامة "مكتمل" على كل صف بعد تحليل المشاعر فيه.
  • خدمة UrlFetch: تتصل هذه الخدمة بواجهة Google Cloud Natural Language API لإجراء تحليل للعناصر والمشاعر في النص.

المتطلبات الأساسية

لاستخدام هذا النموذج، يجب استيفاء المتطلبات الأساسية التالية:

  • حساب Google (قد تتطلّب حسابات Google Workspace موافقة المشرف).
  • متصفّح ويب يمكنه الوصول إلى الإنترنت

  • مشروع Google Cloud مرتبط بحساب فوترة راجِع مقالة تفعيل الفوترة لمشروع.

إعداد البيئة

افتح مشروعك على السحابة الإلكترونية في Google Cloud Console

افتح مشروع Cloud الذي تريد استخدامه لهذا النموذج إذا لم يكن مفتوحًا من قبل:

  1. في وحدة تحكّم Google Cloud، انتقِل إلى صفحة اختيار مشروع.

    اختيار مشروع على السحابة الإلكترونية

  2. اختَر مشروع Google Cloud الذي تريد استخدامه. أو انقر على إنشاء مشروع واتّبِع التعليمات الظاهرة على الشاشة. في حال إنشاء مشروع على Google Cloud، قد تحتاج إلى تفعيل الفوترة للمشروع.

تفعيل Google Cloud Natural Language API

يرتبط هذا الحلّ بواجهة Google Cloud Natural Language API. قبل استخدام واجهات Google APIs، عليك تفعيلها في مشروع على Google Cloud. يمكنك تفعيل واجهة برمجة تطبيق واحدة أو أكثر في مشروع واحد على Google Cloud.

يتطلّب هذا الحلّ مشروعًا على السحابة الإلكترونية يتضمّن شاشة موافقة تم إعدادها. يحدّد إعداد شاشة طلب الموافقة المتعلّقة ببروتوكول OAuth ما تعرضه Google للمستخدمين، كما يسجّل تطبيقك لتتمكّن من نشره لاحقًا.

  1. في "وحدة تحكّم Google Cloud"، انتقِل إلى "القائمة" > Google Auth platform > العلامة التجارية.

    الانتقال إلى "الهوية البصرية للعلامة التجارية"

  2. إذا سبق لك ضبط Google Auth platform، يمكنك ضبط إعدادات "شاشة طلب الموافقة المتعلّقة ببروتوكول OAuth" التالية في العلامة التجارية والجمهور والوصول إلى البيانات. إذا ظهرت لك الرسالة Google Auth platform لم يتم ضبطه بعد، انقر على البدء:
    1. ضمن معلومات التطبيق، في اسم التطبيق، أدخِل اسمًا للتطبيق.
    2. في البريد الإلكتروني لدعم المستخدمين، اختَر عنوان بريد إلكتروني للدعم يمكن للمستخدمين التواصل معك من خلاله إذا كانت لديهم أسئلة حول موافقتهم.
    3. انقر على التالي.
    4. ضمن الجمهور، اختَر داخلي.
    5. انقر على التالي.
    6. ضمن معلومات الاتصال، أدخِل عنوان بريد إلكتروني يمكنك تلقّي إشعارات فيه بشأن أي تغييرات تطرأ على مشروعك.
    7. انقر على التالي.
    8. ضمن إنهاء، راجِع سياسة بيانات المستخدمين في خدمات Google API، وإذا كنت توافق عليها، ضَع علامة في المربّع أوافق على "سياسة بيانات المستخدمين في خدمات Google API".
    9. انقر على متابعة.
    10. انقر على إنشاء.
  3. يمكنك حاليًا تخطّي إضافة النطاقات. في المستقبل، عند إنشاء تطبيق لاستخدامه خارج مؤسسة Google Workspace، عليك تغيير نوع المستخدم إلى خارجي. بعد ذلك، أضِف نطاقات التفويض التي يتطلّبها تطبيقك. لمزيد من المعلومات، يُرجى الاطّلاع على الدليل الكامل حول ضبط موافقة OAuth.

الحصول على مفتاح واجهة برمجة التطبيقات لخدمة Google Cloud Natural Language API

  1. انتقِل إلى وحدة تحكّم Google Cloud. تأكَّد من فتح مشروعك الذي تم تفعيل الفوترة فيه.
  2. في Google Cloud Console، انتقِل إلى "القائمة" > واجهات برمجة التطبيقات والخدمات > بيانات الاعتماد.

    الانتقال إلى "بيانات الاعتماد"

  3. انقر على إنشاء بيانات اعتماد > مفتاح واجهة برمجة التطبيقات.

  4. دوِّن مفتاح واجهة برمجة التطبيقات لاستخدامه في خطوة لاحقة.

إعداد النص البرمجي

إنشاء مشروع "برمجة تطبيقات Google"

  1. انقر على الزر أدناه لإنشاء نسخة من نموذج جدول البيانات تحليل المشاعر بشأن الملاحظات. مشروع Apps Script الخاص بهذا الحلّ مرتبط بجدول البيانات.
    إنشاء نسخة
  2. انقر على الإضافات > برمجة تطبيقات Google.
  3. عدِّل المتغيّر التالي في ملف البرنامج النصي باستخدام مفتاح واجهة برمجة التطبيقات:
    const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.
  4. انقر على "حفظ" رمز الحفظ.

إضافة بيانات نصية

  1. ارجع إلى جدول البيانات.
  2. أضِف بيانات نصية إلى العمودَين id وcomments. يمكنك استخدام عيّنات من مراجعات الأماكن المتاحة للاستئجار من Kaggle أو استخدام بياناتك الخاصة. يمكنك إضافة المزيد من الأعمدة إذا لزم الأمر، ولكن لكي يتم تشغيل النص البرمجي بنجاح، يجب أن يتضمّن بيانات في العمودَين id وcomments.

تشغيل النص البرمجي

  1. في أعلى جدول البيانات، انقر على أدوات تحليل المشاعر > وضع علامة على الكيانات والمشاعر. قد تحتاج إلى إعادة تحميل الصفحة لتظهر هذه القائمة المخصّصة.
  2. امنح الإذن للنصّ البرمجي عند مطالبتك بذلك. إذا عرضت شاشة الموافقة على OAuth التحذير لم يتم التحقّق من هذا التطبيق، يمكنك المتابعة من خلال النقر على خيارات متقدمة > الانتقال إلى {اسم المشروع} (غير آمن).

  3. انقر على أدوات تحليل المشاعر > وضع علامة على الكيانات والمشاعر مرة أخرى.

  4. عند انتهاء النص البرمجي، انتقِل إلى ورقة الجدول المحوري للاطّلاع على النتائج.

مراجعة الرمز البرمجي

لمراجعة رمز 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.
const 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
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const dataSheet = ss.getSheetByName("Review Data");
  const rows = dataSheet.getDataRange();
  const numRows = rows.getNumRows();
  const values = rows.getValues();
  const 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.
  const entitySheet = ss.getSheetByName("Entity Sentiment Data");
  if (entitySheet == null) {
    ss.insertSheet("Entity Sentiment Data");
    const entitySheet = ss.getSheetByName("Entity Sentiment Data");
    const esHeaderRange = entitySheet.getRange(1, 1, 1, 6);
    const 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.
  const textColumnIdx = headerRow.indexOf(COLUMN_NAME.COMMENTS);
  const entityColumnIdx = headerRow.indexOf(COLUMN_NAME.ENTITY);
  const 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) {
    const value = values[i];
    const commentEnCellVal = value[textColumnIdx];
    const entityCellVal = value[entityColumnIdx];
    const reviewId = value[idColumnIdx];

    // Calls retrieveEntitySentiment function for each row that has a comment
    // and also an empty entity_sentiment cell value.
    if (commentEnCellVal && !entityCellVal) {
      const nlData = retrieveEntitySentiment(commentEnCellVal);
      // Pastes each entity and sentiment score into Entity Sentiment Data sheet.
      const newValues = [];
      for (let entity in nlData.entities) {
        entity = nlData.entities[entity];
        const 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) {
  const apiKey = myApiKey;
  const apiEndpoint = `https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=${apiKey}`;
  // Creates a JSON request, with text string, language, type and encoding
  const 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.
  const nlOptions = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(nlData),
  };
  // Makes the API call.
  const response = UrlFetchApp.fetch(apiEndpoint, nlOptions);
  return JSON.parse(response);
}

المساهمون

تحتفظ Google بهذا النموذج بمساعدة خبراء Google Developer Experts.

الخطوات التالية