يمكنك إنشاء خدمة لوصف الصور في مشهد ضمن فيديو باستخدام Cloud Run وVideo Intelligence API وVertex AI

1. مقدمة

نظرة عامة

في هذا الدرس التطبيقي حول الترميز، ستنشئ خدمة Cloud Run مكتوبة بلغة Node.js تقدّم وصفًا مرئيًا لكل مشهد في الفيديو. أولاً، ستستخدم خدمتك واجهة برمجة التطبيقات Video Intelligence API لرصد الطوابع الزمنية التي يتغير فيها المشهد. بعد ذلك، ستستخدم خدمتك برنامجًا ثنائيًا تابعًا لجهة خارجية باسم ffmpeg لالتقاط لقطة شاشة لكل طابع زمني لتغيير المشهد. أخيرًا، يتم استخدام ميزة "وصف الصور" في Vertex AI لتقديم وصف مرئي للقطات الشاشة.

يوضّح هذا الدرس التطبيقي حول الترميز أيضًا كيفية استخدام ffmpeg ضِمن خدمة Cloud Run لالتقاط صور من فيديو في طابع زمني محدّد. بما أنّه يجب تثبيت ffmpeg بشكل مستقل، يوضّح لك هذا الدرس التطبيقي حول الترميز كيفية إنشاء Dockerfile لتثبيت ffmpeg كجزء من خدمة Cloud Run.

في ما يلي رسم توضيحي لطريقة عمل خدمة Cloud Run:

مخطّط خدمة وصف الفيديو في Cloud Run

ما ستتعلمه

  • كيفية إنشاء صورة حاوية باستخدام ملف Dockerfile لتثبيت ملف ثنائي تابع لجهة خارجية
  • كيفية اتّباع مبدأ الامتياز الأقل من خلال إنشاء حساب خدمة لخدمة Cloud Run من أجل استدعاء خدمات Google Cloud الأخرى
  • كيفية استخدام مكتبة برامج Video Intelligence من خدمة Cloud Run
  • كيفية إجراء طلب بيانات من Google APIs للحصول على الوصف المرئي لكل مشهد من Vertex AI

2. الإعداد والمتطلبات

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

تفعيل Cloud Shell

  1. من Cloud Console، انقر على تفعيل Cloud Shell d1264ca30785e435.png.

cb81e7c8e34bc8d.png

إذا كانت هذه هي المرة الأولى التي تبدأ فيها Cloud Shell، ستظهر لك شاشة وسيطة توضّح ماهيتها. إذا ظهرت لك شاشة وسيطة، انقر على متابعة.

d95252b003979716.png

يستغرق توفير Cloud Shell والاتصال به بضع لحظات فقط.

7833d5e1c5d18f54.png

يتم تحميل هذا الجهاز الافتراضي بجميع أدوات التطوير اللازمة. توفّر هذه الخدمة دليلًا رئيسيًا دائمًا بسعة 5 غيغابايت وتعمل في Google Cloud، ما يؤدي إلى تحسين أداء الشبكة والمصادقة بشكل كبير. يمكن إنجاز معظم عملك في هذا الدرس العملي، إن لم يكن كله، باستخدام متصفح.

بعد الاتصال بـ Cloud Shell، من المفترض أن يظهر لك أنّه تم إثبات هويتك وأنّ المشروع مضبوط على رقم تعريف مشروعك.

  1. نفِّذ الأمر التالي في Cloud Shell للتأكّد من إكمال عملية المصادقة:
gcloud auth list

ناتج الأمر

 Credentialed Accounts
ACTIVE  ACCOUNT
*       <my_account>@<my_domain.com>

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  1. نفِّذ الأمر التالي في Cloud Shell للتأكّد من أنّ أمر gcloud يعرف مشروعك:
gcloud config list project

ناتج الأمر

[core]
project = <PROJECT_ID>

إذا لم يكن كذلك، يمكنك تعيينه من خلال هذا الأمر:

gcloud config set project <PROJECT_ID>

ناتج الأمر

Updated property [core/project].

3- تفعيل واجهات برمجة التطبيقات وضبط متغيرات البيئة

قبل البدء في استخدام هذا الدرس التطبيقي حول الترميز، عليك تفعيل العديد من واجهات برمجة التطبيقات. يتطلّب هذا الدرس التطبيقي حول الترميز استخدام واجهات برمجة التطبيقات التالية. يمكنك تفعيل واجهات برمجة التطبيقات هذه من خلال تنفيذ الأمر التالي:

gcloud services enable run.googleapis.com \
    storage.googleapis.com \
    cloudbuild.googleapis.com \
    videointelligence.googleapis.com \
    aiplatform.googleapis.com

بعد ذلك، يمكنك ضبط متغيرات البيئة التي سيتم استخدامها في جميع أنحاء هذا الدرس التطبيقي حول الترميز.

REGION=<YOUR-REGION>
PROJECT_ID=<YOUR-PROJECT-ID>

PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')
SERVICE_NAME=video-describer
export BUCKET_ID=$PROJECT_ID-video-describer

4. إنشاء حزمة في Cloud Storage

أنشئ حزمة Cloud Storage يمكنك من خلالها تحميل الفيديوهات لمعالجتها بواسطة خدمة Cloud Run باستخدام الأمر التالي:

gsutil mb -l us-central1 gs://$BUCKET_ID/

[اختياري] يمكنك استخدام هذا الفيديو النموذجي من خلال تنزيله على جهازك.

gsutil cp gs://cloud-samples-data/video/visionapi.mp4 testvideo.mp4

الآن، حمِّل ملف الفيديو إلى حزمة التخزين.

FILENAME=<YOUR-VIDEO-FILENAME>
gsutil cp $FILENAME gs://$BUCKET_ID

5- إنشاء تطبيق Node.js

أولاً، أنشئ دليلاً لرمز المصدر وانتقِل إلى هذا الدليل.

mkdir video-describer && cd $_

بعد ذلك، أنشِئ ملف package.json يتضمّن المحتوى التالي:

{
  "name": "video-describer",
  "version": "1.0.0",
  "private": true,
  "description": "describes the image in every scene for a given video",
  "main": "index.js",
  "author": "Google LLC",
  "license": "Apache-2.0",
  "scripts": {
    "start": "node index.js"
  },
  "dependencies": {
    "@google-cloud/storage": "^7.7.0",
    "@google-cloud/video-intelligence": "^5.0.1",
    "axios": "^1.6.2",
    "express": "^4.18.2",
    "fluent-ffmpeg": "^2.1.2",
    "google-auth-library": "^9.4.1"
  }
}

يتألف هذا التطبيق من عدة ملفات مصدر لتحسين إمكانية القراءة. أولاً، أنشِئ ملف مصدر index.js يتضمّن المحتوى أدناه. يحتوي هذا الملف على نقطة دخول الخدمة ويتضمّن المنطق الرئيسي للتطبيق.

const { captureImages } = require('./imageCapture.js');
const { detectSceneChanges } = require('./sceneDetector.js');
const transcribeScene = require('./imageDescriber.js');
const { Storage } = require('@google-cloud/storage');
const fs = require('fs').promises;
const path = require('path');
const express = require('express');
const app = express();

const bucketName = process.env.BUCKET_ID;

const port = parseInt(process.env.PORT) || 8080;
app.listen(port, () => {
  console.log(`video describer service ready: listening on port ${port}`);
});

// entry point for the service
app.get('/', async (req, res) => {

  try {

    // download the requested video from Cloud Storage
    let videoFilename =  req.query.filename; 
    console.log("processing file: " + videoFilename);

    // download the file to locally to the Cloud Run instance
    let localFilename = await downloadVideoFile(videoFilename);

    // detect all the scenes in the video & save timestamps to an array
    let timestamps = await detectSceneChanges(localFilename);
    console.log("Detected scene changes at the following timestamps: ", timestamps);

    // create an image of each scene change
    // and save to a local directory called "output"
    await captureImages(localFilename, timestamps);

    // get an access token for the Service Account to call the Google APIs 
    let accessToken = await transcribeScene.getAccessToken();
    console.log("got an access token");

    let imageBaseName = path.parse(localFilename).name;

    // the data structure for storing the scene description and timestamp
    // e.g. an array of json objects {timestamp: 1, description: "..."}, etc.    
    let scenes = []

    // for each timestamp, send the image to Vertex AI
    console.log("getting Vertex AI description all the timestamps");
    scenes = await Promise.all(
      timestamps.map(async (timestamp) => {

        let filepath = path.join("./output", imageBaseName + "-" + timestamp + ".png");

        // get the base64 encoded image
        const encodedFile = await fs.readFile(filepath, 'base64');

        // send each screenshot to Vertex AI for description
        let description = await transcribeScene.transcribeScene(accessToken, encodedFile)

        return { timestamp: timestamp, description: description };
      }));

    console.log("finished collecting all the scenes");
    //console.log(scenes);

    return res.json(scenes);

  } catch (error) {

    //return an error
    console.log("received error: ", error);
    return res.status(500).json("an internal error occurred");
  }

});

async function downloadVideoFile(videoFilename) {
  // Creates a client
  const storage = new Storage();

  // keep same name locally
  let localFilename = videoFilename;

  const options = {
    destination: localFilename
  };

  // Download the file
  await storage.bucket(bucketName).file(videoFilename).download(options);

  console.log(
    `gs://${bucketName}/${videoFilename} downloaded locally to ${localFilename}.`
  );

  return localFilename;
}

بعد ذلك، أنشِئ ملف sceneDetector.js بالمحتوى التالي. يستخدم هذا الملف Video Intelligence API لرصد التغييرات في المشاهد ضمن الفيديو.

const fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
const ffmpeg = require('fluent-ffmpeg');

const Video = require('@google-cloud/video-intelligence');
const client = new Video.VideoIntelligenceServiceClient();

module.exports = {
    detectSceneChanges: async function (downloadedFile) {

        // Reads a local video file and converts it to base64       
        const file = await readFile(downloadedFile);
        const inputContent = file.toString('base64');

        // setup request for shot change detection
        const videoContext = {
            speechTranscriptionConfig: {
                languageCode: 'en-US',
                enableAutomaticPunctuation: true,
            },
        };

        const request = {
            inputContent: inputContent,
            features: ['SHOT_CHANGE_DETECTION'],
        };

        // Detects camera shot changes
        const [operation] = await client.annotateVideo(request);
        console.log('Shot (scene) detection in progress...');
        const [operationResult] = await operation.promise();

        // Gets shot changes
        const shotChanges = operationResult.annotationResults[0].shotAnnotations;

        console.log("Shot (scene) changes detected: " + shotChanges.length);

        // data structure to be returned 
        let sceneChanges = [];

        // for the initial scene
        sceneChanges.push(1);

        // if only one scene, keep at 1 second
        if (shotChanges.length === 1) {
            return sceneChanges;
        }

        // get length of video
        const videoLength = await getVideoLength(downloadedFile);

        shotChanges.forEach((shot, shotIndex) => {
            if (shot.endTimeOffset === undefined) {
                shot.endTimeOffset = {};
            }
            if (shot.endTimeOffset.seconds === undefined) {
                shot.endTimeOffset.seconds = 0;
            }
            if (shot.endTimeOffset.nanos === undefined) {
                shot.endTimeOffset.nanos = 0;
            }

            // convert to a number
            let currentTimestampSecond = Number(shot.endTimeOffset.seconds);                  

            let sceneChangeTime = 0;
            // double-check no scenes were detected within the last second
            if (currentTimestampSecond + 1 > videoLength) {
                sceneChangeTime = currentTimestampSecond;                
            } else {
                // otherwise, for simplicity, just round up to the next second 
                sceneChangeTime = currentTimestampSecond + 1;
            }

            sceneChanges.push(sceneChangeTime);
        });

        return sceneChanges;
    }
}

async function getVideoLength(localFile) {
    let getLength = util.promisify(ffmpeg.ffprobe);
    let length = await getLength(localFile);

    console.log("video length: ", length.format.duration);
    return length.format.duration;
}

الآن، أنشئ ملفًا باسم imageCapture.js يتضمّن المحتوى التالي. يستخدم هذا الملف حزمة node fluent-ffmpeg لتشغيل أوامر ffmpeg من داخل تطبيق node.

const ffmpeg = require('fluent-ffmpeg');
const path = require('path');
const util = require('util');


module.exports = {
    captureImages: async function (localFile, scenes) {


        let imageBaseName = path.parse(localFile).name;


        try {
            for (scene of scenes) {
                console.log("creating screenshot for scene: ", + scene);
                await createScreenshot(localFile, imageBaseName, scene);
            }


        } catch (error) {
            console.log("error gathering screenshots: ", error);
        }


        console.log("finished gathering the screenshots");
    }
}


async function createScreenshot(localFile, imageBaseName, scene) {
    return new Promise((resolve, reject) => {
        ffmpeg(localFile)
            .screenshots({
                timestamps: [scene],
                filename: `${imageBaseName}-${scene}.png`,
                folder: 'output',
                size: '320x240'
            }).on("error", () => {
                console.log("Failed to create scene for timestamp: " + scene);
                return reject('Failed to create scene for timestamp: ' + scene);
            })
            .on("end", () => {
                return resolve();
            });
    })
}

أخيرًا، أنشئ ملفًا باسم `imageDescriber.js`` يتضمّن المحتوى التالي. يستخدم هذا الملف Vertex AI للحصول على وصف مرئي لكل صورة مشهد.

const axios = require("axios");
const { GoogleAuth } = require('google-auth-library');

const auth = new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/cloud-platform'
});

module.exports = {
    getAccessToken: async function () {

        return await auth.getAccessToken();
    }, 

    transcribeScene: async function(token, encodedFile) {

        let projectId = await auth.getProjectId();
    
        let config = {
            headers: {
                'Authorization': 'Bearer ' + token,
                'Content-Type': 'application/json; charset=utf-8'
            }
        }

        const json = {
            "instances": [
                {
                    "image": {
                        "bytesBase64Encoded": encodedFile
                    }
                }
            ],
            "parameters": {
                "sampleCount": 1,
                "language": "en"
            }
        }

        let response = await axios.post('https://us-central1-aiplatform.googleapis.com/v1/projects/' + projectId + '/locations/us-central1/publishers/google/models/imagetext:predict', json, config);

        return response.data.predictions[0];
    }
}

إنشاء ملف Dockerfile وملف ‎ .dockerignore

بما أنّ هذه الخدمة تستخدم ffmpeg، عليك إنشاء Dockerfile يثبّت ffmpeg.

أنشِئ ملفًا باسم Dockerfile يتضمّن المحتوى التالي:

# Copyright 2020 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
#
#    http://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.

# Use the official lightweight Node.js image.
# https://hub.docker.com/_/node
FROM node:20.10.0-slim

# Create and change to the app directory.
WORKDIR /usr/src/app

RUN apt-get update && apt-get install -y ffmpeg

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this separately prevents re-running npm install on every code change.
COPY package*.json ./

# Install dependencies.
# If you add a package-lock.json speed your build by switching to 'npm ci'.
# RUN npm ci --only=production
RUN npm install --production

# Copy local code to the container image.
COPY . .

# Run the web service on container startup.
CMD [ "npm", "start" ]

وأنشئ ملفًا باسم .dockerignore لتجاهل بعض الملفات عند إنشاء الحاويات.

Dockerfile
.dockerignore
node_modules
npm-debug.log

6. إنشاء حساب خدمة

عليك إنشاء حساب خدمة لتستخدمه خدمة Cloud Run للوصول إلى Cloud Storage وVertex AI وVideo Intelligence API.

SERVICE_ACCOUNT="cloud-run-video-description"
SERVICE_ACCOUNT_ADDRESS=$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com

gcloud iam service-accounts create $SERVICE_ACCOUNT \
  --display-name="Cloud Run Video Scene Image Describer service account"
 
# to view & download storage bucket objects
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member serviceAccount:$SERVICE_ACCOUNT_ADDRESS \
  --role=roles/storage.objectViewer

# to call the Vertex AI imagetext model
gcloud projects add-iam-policy-binding $PROJECT_ID \
  --member serviceAccount:$SERVICE_ACCOUNT_ADDRESS \
  --role=roles/aiplatform.user

7. نشر خدمة Cloud Run

يمكنك الآن استخدام عملية نشر مستندة إلى المصدر لتضمين خدمة Cloud Run تلقائيًا.

ملاحظة: مدة المعالجة التلقائية لإحدى خدمات Cloud Run هي 60 ثانية. يستخدم هذا الدرس التطبيقي حول الترميز مهلة 5 دقائق لأنّ مدة الفيديو التجريبي المقترَح هي دقيقتان. قد تحتاج إلى تعديل الوقت إذا كنت تستخدم فيديو مدته أطول.

gcloud run deploy $SERVICE_NAME \
  --region=$REGION \
  --set-env-vars BUCKET_ID=$BUCKET_ID \
  --no-allow-unauthenticated \
  --service-account $SERVICE_ACCOUNT_ADDRESS \
  --timeout=5m \
  --source=.

بعد نشرها، احفظ عنوان URL للخدمة في متغيّر بيئة.

SERVICE_URL=$(gcloud run services describe $SERVICE_NAME --platform managed --region $REGION --format 'value(status.url)')

8. استدعاء خدمة Cloud Run

يمكنك الآن استدعاء خدمتك من خلال تقديم اسم الفيديو الذي حمّلته إلى Cloud Storage.

curl -X GET -H "Authorization: Bearer $(gcloud auth print-identity-token)" ${SERVICE_URL}?filename=${FILENAME}

يجب أن تبدو النتائج مشابهة لناتج المثال أدناه:

[{"timestamp":1,"description":"an aerial view of a city with a bridge in the background"},{"timestamp":7,"description":"a man in a blue shirt sits in front of shelves of donuts"},{"timestamp":11,"description":"a black and white photo of people working in a bakery"},{"timestamp":12,"description":"a black and white photo of a man and woman working in a bakery"}]

9- تهانينا!

تهانينا على إكمال هذا الدرس العملي.

ننصحك بمراجعة المستندات حول Video Intelligence API وCloud Run والتعليق المرئي في Vertex AI.

المواضيع التي تناولناها

  • كيفية إنشاء صورة حاوية باستخدام ملف Dockerfile لتثبيت ملف ثنائي تابع لجهة خارجية
  • كيفية اتّباع مبدأ الامتياز الأقل من خلال إنشاء حساب خدمة لخدمة Cloud Run من أجل استدعاء خدمات Google Cloud الأخرى
  • كيفية استخدام مكتبة برامج Video Intelligence من خدمة Cloud Run
  • كيفية إجراء طلب بيانات من Google APIs للحصول على الوصف المرئي لكل مشهد من Vertex AI

10. تَنظيم

لتجنُّب فرض رسوم غير مقصودة (على سبيل المثال، إذا تم استدعاء خدمة Cloud Run هذه مرات أكثر من مخصص استدعاء Cloud Run الشهري في الطبقة المجانية)، يمكنك إما حذف خدمة Cloud Run أو حذف المشروع الذي أنشأته في الخطوة 2.

لحذف خدمة Cloud Run، انتقِل إلى Cloud Run Cloud Console على https://console.cloud.google.com/run/ واحذف الدالة video-describer (أو $SERVICE_NAME في حال استخدام اسم مختلف).

إذا اخترت حذف المشروع بأكمله، يمكنك الانتقال إلى https://console.cloud.google.com/cloud-resource-manager، واختيار المشروع الذي أنشأته في الخطوة 2، ثم النقر على "حذف". إذا حذفت المشروع، عليك تغيير المشاريع في Cloud SDK. يمكنك الاطّلاع على قائمة بجميع المشاريع المتاحة من خلال تنفيذ gcloud projects list.