วิธีใช้ Cloud Run Jobs Video Intelligence API สำหรับการประมวลผลวิดีโอ

1. บทนำ

ภาพรวม

ใน Codelab นี้ คุณจะได้สร้างงาน Cloud Run ที่เขียนด้วย Node.js ซึ่งจะให้คำอธิบายภาพของทุกฉากในวิดีโอ โดยขั้นแรก งานจะใช้ Video Intelligence API เพื่อตรวจหาการประทับเวลาเมื่อใดก็ตามที่มีการเปลี่ยนฉาก จากนั้น งานจะใช้ไบนารีของบุคคลที่สามที่เรียกว่า ffmpeg เพื่อจับภาพหน้าจอสำหรับการประทับเวลาการเปลี่ยนฉากแต่ละรายการ และสุดท้าย ระบบจะใช้คำบรรยายภาพของ Vertex AI เพื่อให้คำอธิบายภาพของภาพหน้าจอ

นอกจากนี้ Codelab นี้ยังแสดงวิธีใช้ ffmpeg ภายในงาน Cloud Run เพื่อจับภาพจากวิดีโอที่การประทับเวลาที่กำหนด เนื่องจากต้องติดตั้ง ffmpeg แยกกัน Codelab นี้จึงแสดงวิธีสร้าง 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 เป็นครั้งแรก ระบบจะแสดงหน้าจอระดับกลางที่อธิบายว่า Cloud Shell คืออะไร หากระบบแสดงหน้าจอระดับกลาง ให้คลิกต่อไป

d95252b003979716.png

การจัดเตรียมและเชื่อมต่อกับ Cloud Shell จะใช้เวลาไม่นาน

7833d5e1c5d18f54.png

เครื่องเสมือนนี้โหลดเครื่องมือพัฒนาทั้งหมดที่จำเป็น โดยมีไดเรกทอรีแรกขนาด 5 GB แบบถาวรและทำงานใน Google Cloud ซึ่งช่วยเพิ่มประสิทธิภาพของเครือข่ายและการตรวจสอบสิทธิ์ได้อย่างมาก คุณสามารถทำงานส่วนใหญ่หรือทั้งหมดใน Codelab นี้ได้ด้วยเบราว์เซอร์

เมื่อเชื่อมต่อกับ 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. เปิดใช้ API และตั้งค่าตัวแปรสภาพแวดล้อม

คุณต้องเปิดใช้ API หลายรายการก่อนจึงจะเริ่มใช้ Codelab นี้ได้ Codelab นี้กำหนดให้ใช้ API ต่อไปนี้ คุณสามารถเปิดใช้ API เหล่านั้นได้โดยเรียกใช้คำสั่งต่อไปนี้

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

จากนั้นคุณสามารถตั้งค่าตัวแปรสภาพแวดล้อมที่จะใช้ตลอด Codelab นี้

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. สร้างบัญชีบริการ

คุณจะสร้างบัญชีบริการสำหรับงาน Cloud Run เพื่อใช้เข้าถึง Cloud Storage, Vertex AI และ Video Intelligence API

ขั้นแรก ให้สร้างบัญชีบริการ

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

จากนั้นให้สิทธิ์เข้าถึง Bucket ของ Cloud Storage และ Vertex AI APIs แก่บัญชีบริการ

# 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. สร้าง Bucket ของ Cloud Storage

สร้าง Bucket ของ Cloud Storage ที่คุณสามารถอัปโหลดวิดีโอเพื่อให้งาน Cloud Run ประมวลผลได้ด้วยคำสั่งต่อไปนี้

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

[ไม่บังคับ] คุณสามารถใช้วิดีโอตัวอย่างนี้ได้โดยดาวน์โหลดลงในเครื่อง

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

ตอนนี้ให้อัปโหลดไฟล์วิดีโอไปยัง Bucket ของพื้นที่เก็บข้อมูล

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

6. สร้างงาน Cloud Run

ขั้นแรก ให้สร้างไดเรกทอรีสำหรับซอร์สโค้ดและเปลี่ยนไดเรกทอรีเป็นไดเรกทอรีนั้น

mkdir video-describer-job && cd $_

จากนั้นสร้างไฟล์ package.json ที่มีเนื้อหาต่อไปนี้

{
  "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"
  }
}

แอปนี้ประกอบด้วยไฟล์ซอร์สหลายไฟล์เพื่อให้สามารถอ่านได้ง่ายขึ้น ขั้นแรก ให้สร้างไฟล์ซอร์ส app.js ที่มีเนื้อหาด้านล่าง ไฟล์นี้มีจุดแรกเข้าสำหรับงานและมีตรรกะหลักสำหรับแอป

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

จากนั้นสร้าง 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" ]

และสร้างไฟล์ที่ชื่อว่า .dockerignore เพื่อไม่ให้คอนเทนเนอร์สร้างไฟล์บางไฟล์

Dockerfile
.dockerignore
node_modules
npm-debug.log

ตอนนี้ให้สร้างโฟลเดอร์ที่ชื่อว่า helpers โฟลเดอร์นี้จะมีไฟล์ Helper 5 ไฟล์

mkdir helpers
cd helpers

จากนั้นสร้างไฟล์ 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 ที่มีเนื้อหาต่อไปนี้ ไฟล์นี้ใช้แพ็กเกจ fluent-ffmpeg ของ Node เพื่อเรียกใช้คำสั่ง 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");
        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();
            });
    });
}

สุดท้าย ให้สร้างไฟล์ที่ชื่อว่า imageCaptioning.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 = {
    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];
    }
};

สร้างไฟล์ที่ชื่อว่า auth.js ไฟล์นี้จะใช้ไลบรารีของไคลเอ็นต์การตรวจสอบสิทธิ์ของ Google เพื่อรับโทเค็นเพื่อการเข้าถึงที่จำเป็นในการเรียกใช้ปลายทาง 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();
    }
};

สุดท้าย ให้สร้างไฟล์ที่ชื่อว่า storage.js ไฟล์นี้จะใช้ไลบรารีไคลเอ็นต์ Cloud Storage เพื่อดาวน์โหลดวิดีโอจาก Cloud Storage

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. ทำให้งาน Cloud Run ใช้งานได้และเรียกใช้งาน

ขั้นแรก ให้ตรวจสอบว่าคุณอยู่ในไดเรกทอรีราก video-describer-job สำหรับ Codelab

cd .. && pwd

จากนั้นคุณสามารถใช้คำสั่งนี้เพื่อทำให้งาน Cloud Run ใช้งานได้

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

ตอนนี้คุณสามารถเรียกใช้งาน Cloud Run Job ได้โดยเรียกใช้คำสั่งต่อไปนี้

gcloud run jobs execute $JOB_NAME

เมื่อเรียกใช้งานเสร็จแล้ว คุณสามารถเรียกใช้คำสั่งต่อไปนี้เพื่อรับลิงก์ไปยัง URI ของบันทึก (หรือคุณสามารถใช้ Cloud Console แล้วไปที่งาน Cloud Run โดยตรงเพื่อดูบันทึก)

gcloud run jobs executions describe <JOB_EXECUTION_ID>

คุณควรเห็นเอาต์พุตต่อไปนี้ในบันทึก

[{ 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. ยินดีด้วย

ขอแสดงความยินดีที่ทำ Codelab นี้เสร็จสมบูรณ์

เราขอแนะนำให้คุณอ่านเอกสารประกอบเกี่ยวกับ Video Intelligence API, Cloud Run และ คำบรรยายภาพของ Vertex AI

สิ่งที่เราได้กล่าวถึง

  • วิธีสร้างอิมเมจคอนเทนเนอร์โดยใช้ Dockerfile เพื่อติดตั้งไบนารีของบุคคลที่สาม
  • วิธีปฏิบัติตามหลักการให้สิทธิ์ขั้นต่ำที่สุดโดยการสร้างบัญชีบริการสำหรับงาน Cloud Run เพื่อเรียกใช้บริการอื่นๆ ของ Google Cloud
  • วิธีใช้ไลบรารีของไคลเอ็นต์ Video Intelligence จากงาน Cloud Run
  • วิธีเรียกใช้ Google APIs เพื่อรับคำอธิบายภาพของแต่ละฉากจาก Vertex AI

9. ล้างข้อมูล

หากต้องการหลีกเลี่ยงค่าใช้จ่ายโดยไม่ตั้งใจ (เช่น หากระบบเรียกใช้งาน Cloud Run Job นี้โดยไม่ตั้งใจมากกว่าจำนวน การเรียกใช้งาน Cloud Run ที่จัดสรรให้รายเดือนในระดับฟรี) คุณสามารถลบ Cloud Run Job หรือลบโปรเจ็กต์ที่สร้างในขั้นตอนที่ 2

หากต้องการลบ Cloud Run Job ให้ไปที่ Cloud Run Cloud Console ที่ https://console.cloud.google.com/run/ แล้วลบฟังก์ชัน video-describer-job (หรือ $JOB_NAME ในกรณีที่คุณใช้ชื่ออื่น)

หากต้องการลบโปรเจ็กต์ทั้งหมด ให้ไปที่ https://console.cloud.google.com/cloud-resource-manager เลือกโปรเจ็กต์ที่สร้างในขั้นตอนที่ 2 แล้วเลือก "ลบ" หากลบโปรเจ็กต์ คุณจะต้องเปลี่ยนโปรเจ็กต์ใน Cloud SDK คุณสามารถดูรายการโปรเจ็กต์ทั้งหมดที่มีได้โดยเรียกใช้ gcloud projects list