Cách sử dụng công việc trong Cloud Run và Video Intelligence API để xử lý video

1. Giới thiệu

Tổng quan

Trong lớp học lập trình này, bạn sẽ tạo một Cloud Run Job được viết bằng Node.js, cung cấp nội dung mô tả trực quan về mọi cảnh trong video. Trước tiên, công việc của bạn sẽ sử dụng Video Intelligence API để phát hiện dấu thời gian mỗi khi cảnh thay đổi. Tiếp theo, công việc của bạn sẽ sử dụng một tệp nhị phân của bên thứ ba có tên là ffmpeg để chụp ảnh màn hình cho từng dấu thời gian thay đổi cảnh. Cuối cùng, tính năng chú thích hình ảnh của Vertex AI được dùng để cung cấp nội dung mô tả bằng hình ảnh cho ảnh chụp màn hình.

Lớp học lập trình này cũng minh hoạ cách sử dụng ffmpeg trong Cloud Run Job để chụp ảnh từ một video tại một dấu thời gian nhất định. Vì ffmpeg cần được cài đặt độc lập, nên lớp học lập trình này hướng dẫn bạn cách tạo một Dockerfile để cài đặt ffmpeg như một phần của Công việc Cloud Run.

Sau đây là hình minh hoạ về cách hoạt động của Cloud Run Job:

Hình minh hoạ nội dung mô tả video về công việc trên Cloud Run

Kiến thức bạn sẽ học được

  • Cách tạo một hình ảnh vùng chứa bằng Dockerfile để cài đặt một tệp nhị phân của bên thứ ba
  • Cách tuân theo nguyên tắc đặc quyền tối thiểu bằng cách tạo tài khoản dịch vụ cho Cloud Run Job để gọi các dịch vụ khác của Google Cloud
  • Cách sử dụng thư viện ứng dụng Video Intelligence từ một Tác vụ Cloud Run
  • Cách gọi API của Google để nhận nội dung mô tả bằng hình ảnh của từng cảnh từ Vertex AI

2. Thiết lập và yêu cầu

Điều kiện tiên quyết

Kích hoạt Cloud Shell

  1. Trong Cloud Console, hãy nhấp vào Kích hoạt Cloud Shell d1264ca30785e435.png.

cb81e7c8e34bc8d.png

Nếu đây là lần đầu tiên bạn khởi động Cloud Shell, bạn sẽ thấy một màn hình trung gian mô tả về Cloud Shell. Nếu bạn thấy màn hình trung gian, hãy nhấp vào Tiếp tục.

d95252b003979716.png

Quá trình cung cấp và kết nối với Cloud Shell chỉ mất vài giây.

7833d5e1c5d18f54.png

Máy ảo này được trang bị tất cả các công cụ phát triển cần thiết. Nền tảng này cung cấp một thư mục chính có dung lượng 5 GB và chạy trong Google Cloud, giúp tăng cường đáng kể hiệu suất mạng và hoạt động xác thực. Bạn có thể thực hiện hầu hết, nếu không muốn nói là tất cả, công việc của mình trong lớp học lập trình này bằng trình duyệt.

Sau khi kết nối với Cloud Shell, bạn sẽ thấy rằng mình đã được xác thực và dự án được đặt thành mã dự án của bạn.

  1. Chạy lệnh sau trong Cloud Shell để xác nhận rằng bạn đã được xác thực:
gcloud auth list

Đầu ra của lệnh

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

To set the active account, run:
    $ gcloud config set account `ACCOUNT`
  1. Chạy lệnh sau trong Cloud Shell để xác nhận rằng lệnh gcloud biết về dự án của bạn:
gcloud config list project

Đầu ra của lệnh

[core]
project = <PROJECT_ID>

Nếu không, bạn có thể đặt nó bằng lệnh sau:

gcloud config set project <PROJECT_ID>

Đầu ra của lệnh

Updated property [core/project].

3. Bật API và đặt các biến môi trường

Để có thể bắt đầu sử dụng lớp học lập trình này, bạn cần bật một số API. Lớp học lập trình này yêu cầu bạn sử dụng các API sau. Bạn có thể bật các API đó bằng cách chạy lệnh sau:

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

Sau đó, bạn có thể thiết lập các biến môi trường sẽ được dùng trong suốt lớp học lập trình này.

REGION=<YOUR-REGION>
PROJECT_ID=<YOUR-PROJECT-ID>
PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')
JOB_NAME=video-describer-job
BUCKET_ID=$PROJECT_ID-video-describer
SERVICE_ACCOUNT="cloud-run-job-video"
SERVICE_ACCOUNT_ADDRESS=$SERVICE_ACCOUNT@$PROJECT_ID.iam.gserviceaccount.com

4. Tạo tài khoản dịch vụ

Bạn sẽ tạo một tài khoản dịch vụ cho Cloud Run Job để sử dụng nhằm truy cập vào Cloud Storage, Vertex AI và Video Intelligence API.

Trước tiên, hãy tạo tài khoản dịch vụ.

gcloud iam service-accounts create $SERVICE_ACCOUNT \
  --display-name="Cloud Run Video Scene Image Describer service account"

Sau đó, cấp cho tài khoản dịch vụ quyền truy cập vào bộ chứa Cloud Storage và các API Vertex AI.

# 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

5. Tạo bộ chứa Cloud Storage

Tạo một bộ chứa Cloud Storage để bạn có thể tải video lên để Cloud Run Job xử lý bằng lệnh sau:

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

[Không bắt buộc] Bạn có thể sử dụng video mẫu này bằng cách tải video xuống thiết bị.

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

Bây giờ, hãy tải tệp video lên nhóm lưu trữ của bạn.

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

6. Tạo Cloud Run Job

Trước tiên, hãy tạo một thư mục cho mã nguồn và chuyển đến thư mục đó.

mkdir video-describer-job && cd $_

Sau đó, hãy tạo một tệp package.json có nội dung sau:

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

Ứng dụng này bao gồm một số tệp nguồn để cải thiện khả năng đọc. Trước tiên, hãy tạo một tệp nguồn app.js có nội dung bên dưới. Tệp này chứa điểm truy cập cho công việc và chứa logic chính cho ứng dụng.

const bucketName = "<YOUR_BUCKET_ID>";
const videoFilename = "<YOUR-VIDEO-FILENAME>";

const { captureImages } = require("./helpers/imageCapture.js");
const { detectSceneChanges } = require("./helpers/sceneDetector.js");
const { getImageCaption } = require("./helpers/imageCaptioning.js");
const storageHelper = require("./helpers/storage.js");
const authHelper = require("./helpers/auth.js");

const fs = require("fs").promises;
const path = require("path");

const main = async () => {

    try {

        // download the file to locally to the Cloud Run Job instance
        let localFilename = await storageHelper.downloadVideoFile(
            bucketName,
            videoFilename
        );

        // PART 1 - Use Video Intelligence API
        // detect all the scenes in the video & save timestamps to an array

        // EXAMPLE OUTPUT
        // Detected scene changes at the following timestamps:
        // [1, 7, 11, 12]
        let timestamps = await detectSceneChanges(localFilename);
        console.log(
            "Detected scene changes at the following timestamps: ",
            timestamps
        );

        // PART 2 - Use ffmpeg via dockerfile install
        // create an image of each scene change
        // and save to a local directory called "output"
        // returns the base filename for the generated images

        // EXAMPLE OUTPUT
        // creating screenshot for scene:  1 at output/video-filename-1.png
        // creating screenshot for scene:  7 at output/video-filename-7.png
        // creating screenshot for scene:  11 at output/video-filename-11.png
        // creating screenshot for scene:  12 at output/video-filename-12.png
        // returns the base filename for the generated images
        let imageBaseName = await captureImages(localFilename, timestamps);

        // PART 3a - get Access Token to call Vertex AI APIs via REST
        // needed for the image captioning
        // since we're calling the Vertex AI APIs directly
        let accessToken = await authHelper.getAccessToken();
        console.log("got an access token");

        // PART 3b - use Image Captioning to describe each scene per screenshot
        // EXAMPLE OUTPUT
        /*
        [
            {
                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"
            }
        ]; */

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

        // for each timestamp, send the image to Vertex AI
        console.log("getting Vertex AI description for each timestamps");
        scenes = await Promise.all(
            timestamps.map(async (timestamp) => {
                let filepath = path.join(
                    "./output",
                    imageBaseName + "-" + timestamp + ".png"
                );

                // get the base64 encoded image bc sending via REST
                const encodedFile = await fs.readFile(filepath, "base64");

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

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

        console.log("finished collecting all the scenes");
        console.log(scenes);
    } catch (error) {
        //return an error
        console.error("received error: ", error);
    }
};

// Start script
main().catch((err) => {
    console.error(err);
});

Tiếp theo, hãy tạo 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 job on container startup.
CMD [ "npm", "start" ]

Tạo một tệp có tên là .dockerignore để bỏ qua việc chứa một số tệp nhất định.

Dockerfile
.dockerignore
node_modules
npm-debug.log

Bây giờ, hãy tạo một thư mục có tên là helpers. Thư mục này sẽ chứa 5 tệp trợ giúp.

mkdir helpers
cd helpers

Tiếp theo, hãy tạo tệp sceneDetector.js có nội dung sau. Tệp này sử dụng Video Intelligence API để phát hiện thời điểm các cảnh thay đổi trong video.

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

Bây giờ, hãy tạo một tệp có tên là imageCapture.js với nội dung sau. Tệp này sử dụng gói nút fluent-ffmpeg để chạy các lệnh ffmpeg trong một ứng dụng nút.

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");
        return imageBaseName; // return the base filename for each image
    }
};

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

Cuối cùng, hãy tạo một tệp có tên là imageCaptioning.js với nội dung sau. Tệp này sử dụng Vertex AI để nhận nội dung mô tả bằng hình ảnh của từng hình ảnh cảnh.

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

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

module.exports = {
    getImageCaption: async function (token, encodedFile) {
        // this example shows you how to call the Vertex REST APIs directly
        // https://cloud.google.com/vertex-ai/generative-ai/docs/image/image-captioning#get-captions-short
        // https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/image-captioning

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

Tạo một tệp có tên là auth.js. Tệp này sẽ sử dụng thư viện ứng dụng xác thực của Google để lấy mã truy cập cần thiết nhằm gọi trực tiếp các điểm cuối Vertex AI.

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

Cuối cùng, hãy tạo một tệp có tên là storage.js. Tệp này sẽ sử dụng các thư viện ứng dụng Cloud Storage để tải video xuống từ bộ nhớ đám mây.

const { Storage } = require("@google-cloud/storage");

module.exports = {
    downloadVideoFile: async function (bucketName, 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;
    }
};

7. Triển khai và thực thi Cloud Run Job

Trước tiên, hãy đảm bảo bạn đang ở thư mục gốc video-describer-job cho codelab của mình.

cd .. && pwd

Sau đó, bạn có thể dùng lệnh này để triển khai Cloud Run Job.

gcloud run jobs deploy $JOB_NAME  --source . --region $REGION

Giờ đây, bạn có thể thực thi Cloud Run Job bằng cách chạy lệnh sau:

gcloud run jobs execute $JOB_NAME

Sau khi công việc thực thi xong, bạn có thể chạy lệnh sau để lấy đường liên kết đến URI nhật ký. (Hoặc bạn có thể sử dụng Cloud Console và chuyển thẳng đến Cloud Run Jobs để xem nhật ký.)

gcloud run jobs executions describe <JOB_EXECUTION_ID>

Bạn sẽ thấy kết quả sau trong nhật ký:

[{ timestamp: 1, description: 'what is google cloud vision api ? is written on a white background .'},
{ timestamp: 3, description: 'a woman wearing a google cloud vision api shirt sits at a table'},
{ timestamp: 18, description: 'a person holding a cell phone with the words what is cloud vision api on the bottom' }, ...]

8. Xin chúc mừng!

Chúc mừng bạn đã hoàn thành lớp học lập trình này!

Bạn nên xem tài liệu về Video Intelligence API, Cloud Runchú thích trực quan của Vertex AI.

Nội dung đã đề cập

  • Cách tạo một hình ảnh vùng chứa bằng Dockerfile để cài đặt một tệp nhị phân của bên thứ ba
  • Cách tuân theo nguyên tắc đặc quyền tối thiểu bằng cách tạo tài khoản dịch vụ cho Cloud Run Job để gọi các dịch vụ khác của Google Cloud
  • Cách sử dụng thư viện ứng dụng Video Intelligence từ một Tác vụ Cloud Run
  • Cách gọi API của Google để nhận nội dung mô tả bằng hình ảnh của từng cảnh từ Vertex AI

9. Dọn dẹp

Để tránh bị tính phí ngoài ý muốn (ví dụ: nếu vô tình gọi lệnh này nhiều lần hơn hạn mức gọi Cloud Run hằng tháng của bạn trong cấp miễn phí), bạn có thể xoá lệnh Cloud Run này hoặc xoá dự án mà bạn đã tạo ở Bước 2.

Để xoá lệnh Cloud Run, hãy truy cập vào Cloud Run Cloud Console tại https://console.cloud.google.com/run/ rồi xoá hàm video-describer-job (hoặc $JOB_NAME nếu bạn dùng tên khác).

Nếu chọn xoá toàn bộ dự án, bạn có thể truy cập vào https://console.cloud.google.com/cloud-resource-manager, chọn dự án bạn đã tạo ở Bước 2 rồi chọn Xoá. Nếu xoá dự án, bạn sẽ cần thay đổi dự án trong Cloud SDK. Bạn có thể xem danh sách tất cả các dự án có sẵn bằng cách chạy gcloud projects list.