الربط بواجهة برمجة التطبيقات: تحليل مدى توافق الآراء

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

الأهداف

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

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

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

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

آلية العمل

يجمع النص البرمجي النص من جدول البيانات ويتصل بواجهة برمجة تطبيقات اللغة الطبيعية في Google Cloud لتحليل الكيانات والمشاعر الموجودة في السلسلة. يلخص الجدول المحوري متوسط نتيجة الآراء لكل كيان مذكور في جميع صفوف البيانات النصية.

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

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

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

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

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

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

  • مشروع على Google Cloud مع حساب فوترة مرتبط به يمكنك الرجوع إلى تفعيل الفوترة لمشروع.

إعداد البيئة

فتح مشروعك على Google Cloud في Google Cloud Console

إذا لم يكن المشروع مفتوحًا، افتح المشروع الذي تنوي استخدامه في هذا النموذج من خلال الخطوات التالية:

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

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

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

تفعيل واجهة برمجة تطبيقات Google Cloud Natural Language

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

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

  1. في وحدة تحكُّم Google Cloud، انتقِل إلى القائمة > واجهات برمجة التطبيقات والخدمات > شاشة موافقة OAuth.

    الانتقال إلى شاشة طلب الموافقة المتعلّقة ببروتوكول OAuth

  2. في حقل نوع المستخدم، اختَر داخلي، ثم انقر على إنشاء.
  3. املأ نموذج تسجيل التطبيق، ثم انقر على حفظ ومتابعة.
  4. في الوقت الحالي، يمكنك تخطّي إضافة النطاقات والنقر على حفظ ومتابعة. في المستقبل، عند إنشاء تطبيق للاستخدام خارج مؤسسة Google Workspace، عليك تغيير نوع المستخدم إلى خارجي، ثم إضافة نطاقات التفويض التي يتطلبها تطبيقك.

  5. مراجعة ملخص تسجيل التطبيق لإجراء تغييرات، انقر على تعديل. إذا كان تسجيل التطبيق يبدو جيدًا، انقر على الرجوع إلى لوحة البيانات.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

مراجعة الرمز

لمراجعة رمز برمجة التطبيقات لهذا الحلّ، انقر على عرض رمز المصدر أدناه:

عرض رمز المصدر

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.

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