1. परिचय
खास जानकारी
इस कोडलैब में, Node.js में लिखा गया एक Cloud Run Job बनाया जाएगा. यह वीडियो के हर सीन की जानकारी देगा. सबसे पहले, आपका जॉब Video Intelligence API का इस्तेमाल करके, सीन बदलने के हर टाइमस्टैंप का पता लगाएगा. इसके बाद, आपका काम हर सीन-चेंज टाइमस्टैंप के लिए स्क्रीनशॉट कैप्चर करने के लिए, ffmpeg नाम के तीसरे पक्ष के बाइनरी का इस्तेमाल करेगा. आखिर में, Vertex AI की विज़ुअल कैप्शनिंग सुविधा का इस्तेमाल करके, स्क्रीनशॉट की विज़ुअल जानकारी दी जाती है.
इस कोडलैब में यह भी दिखाया गया है कि Cloud Run Job में ffmpeg का इस्तेमाल करके, किसी वीडियो से किसी दिए गए टाइमस्टैंप पर इमेज कैसे कैप्चर की जाती हैं. ffmpeg को अलग से इंस्टॉल करना होता है. इसलिए, इस कोडलैब में आपको Cloud Run जॉब के हिस्से के तौर पर ffmpeg को इंस्टॉल करने के लिए, Dockerfile बनाने का तरीका बताया गया है.
Cloud Run जॉब के काम करने का तरीका दिखाने वाला इलस्ट्रेशन यहां दिया गया है:

आपको क्या सीखने को मिलेगा
- तीसरे पक्ष की बाइनरी इंस्टॉल करने के लिए, Dockerfile का इस्तेमाल करके कंटेनर इमेज बनाने का तरीका
- Cloud Run Job के लिए सेवा खाता बनाकर, कम से कम ज़रूरी अनुमतियों के सिद्धांत का पालन कैसे करें, ताकि वह अन्य Google Cloud सेवाओं को कॉल कर सके
- Cloud Run Job से Video Intelligence क्लाइंट लाइब्रेरी का इस्तेमाल करने का तरीका
- Vertex AI से हर सीन की विज़ुअल जानकारी पाने के लिए, Google API को कॉल करने का तरीका
2. सेटअप और ज़रूरी शर्तें
ज़रूरी शर्तें
- आपने Cloud Console में लॉग इन किया हो.
- आपने पहले Cloud Run सेवा को डिप्लॉय किया हो. उदाहरण के लिए, शुरू करने के लिए सोर्स कोड से वेब सेवा डिप्लॉय करने के बारे में जानकारी पढ़ें.
Cloud Shell चालू करें
- Cloud Console में, Cloud Shell चालू करें
पर क्लिक करें.

अगर आपने Cloud Shell को पहली बार शुरू किया है, तो आपको एक इंटरमीडिएट स्क्रीन दिखेगी. इसमें Cloud Shell के बारे में जानकारी दी गई होगी. अगर आपको इंटरमीडिएट स्क्रीन दिखती है, तो जारी रखें पर क्लिक करें.

Cloud Shell से कनेक्ट होने में कुछ ही सेकंड लगेंगे.

इस वर्चुअल मशीन में, डेवलपमेंट के लिए ज़रूरी सभी टूल पहले से मौजूद हैं. यह 5 जीबी की होम डायरेक्ट्री उपलब्ध कराता है, जो हमेशा बनी रहती है. साथ ही, यह Google Cloud में काम करता है. इससे नेटवर्क की परफ़ॉर्मेंस और पुष्टि करने की प्रोसेस बेहतर होती है. इस कोडलैब में ज़्यादातर काम ब्राउज़र से किया जा सकता है.
Cloud Shell से कनेक्ट होने के बाद, आपको दिखेगा कि आपकी पुष्टि हो गई है और प्रोजेक्ट को आपके प्रोजेक्ट आईडी पर सेट कर दिया गया है.
- पुष्टि करें कि आपने 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`
- यह पुष्टि करने के लिए कि gcloud कमांड को आपके प्रोजेक्ट के बारे में पता है, Cloud Shell में यह कमांड चलाएं:
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)') 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 Job के लिए एक सेवा खाता बनाया जाएगा. इसका इस्तेमाल Cloud Storage, Vertex AI, और Video Intelligence API को ऐक्सेस करने के लिए किया जाएगा.
सबसे पहले, सेवा खाता बनाएं.
gcloud iam service-accounts create $SERVICE_ACCOUNT \ --display-name="Cloud Run Video Scene Image Describer service account"
इसके बाद, सेवा खाते को Cloud Storage बकेट और Vertex AI API का ऐक्सेस दें.
# 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. 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
6. Cloud Run जॉब बनाना
सबसे पहले, सोर्स कोड के लिए एक डायरेक्ट्री बनाएं और उस डायरेक्ट्री में cd करें.
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 नाम का फ़ोल्डर बनाएं. इस फ़ोल्डर में पांच हेल्पर फ़ाइलें होंगी.
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 नाम की फ़ाइल बनाएं. यह फ़ाइल, नोड ऐप्लिकेशन में ffmpeg कमांड चलाने के लिए, नोड पैकेज fluent-ffmpeg का इस्तेमाल करती है.
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 क्लाइंट लाइब्रेरी का इस्तेमाल करके, क्लाउड स्टोरेज से वीडियो डाउनलोड करेगी.
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 में हों.
cd .. && pwd
इसके बाद, इस निर्देश का इस्तेमाल करके Cloud Run Job को डिप्लॉय किया जा सकता है.
gcloud run jobs deploy $JOB_NAME --source . --region $REGION
अब, Cloud Run जॉब को इस कमांड की मदद से एक्ज़ीक्यूट किया जा सकता है:
gcloud run jobs execute $JOB_NAME
जॉब के पूरा होने के बाद, लॉग यूआरआई का लिंक पाने के लिए यह कमांड चलाएं. (इसके अलावा, Cloud Console का इस्तेमाल करके सीधे Cloud Run Jobs पर जाकर भी लॉग देखे जा सकते हैं.)
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. बधाई हो!
कोडलैब पूरा करने के लिए बधाई!
हमारा सुझाव है कि आप Video Intelligence API, Cloud Run, और Vertex AI की विज़ुअल कैप्शनिंग की सुविधा के बारे में दस्तावेज़ पढ़ें.
हमने क्या-क्या बताया
- तीसरे पक्ष की बाइनरी इंस्टॉल करने के लिए, Dockerfile का इस्तेमाल करके कंटेनर इमेज बनाने का तरीका
- Cloud Run Job के लिए सेवा खाता बनाकर, कम से कम ज़रूरी अनुमतियों के सिद्धांत का पालन कैसे करें, ताकि वह अन्य Google Cloud सेवाओं को कॉल कर सके
- Cloud Run Job से Video Intelligence क्लाइंट लाइब्रेरी का इस्तेमाल करने का तरीका
- Vertex AI से हर सीन की विज़ुअल जानकारी पाने के लिए, Google API को कॉल करने का तरीका
9. व्यवस्थित करें
अनजाने में लगने वाले शुल्क से बचने के लिए, Cloud Run जॉब को मिटा दें या चरण 2 में बनाया गया प्रोजेक्ट मिटा दें. उदाहरण के लिए, अगर इस Cloud Run जॉब को मुफ़्त टियर में Cloud Run जॉब को हर महीने कॉल करने की तय सीमा से ज़्यादा बार कॉल किया जाता है, तो अनजाने में शुल्क लग सकता है.
Cloud Run जॉब को मिटाने के लिए, Cloud Run Cloud Console पर जाएं. इसके लिए, https://console.cloud.google.com/run/ पर जाएं. इसके बाद, video-describer-job फ़ंक्शन (अगर आपने किसी दूसरे नाम का इस्तेमाल किया है, तो $JOB_NAME) को मिटाएं.
अगर आपको पूरा प्रोजेक्ट मिटाना है, तो https://console.cloud.google.com/cloud-resource-manager पर जाएं. इसके बाद, दूसरे चरण में बनाया गया प्रोजेक्ट चुनें और मिटाएं को चुनें. प्रोजेक्ट मिटाने पर, आपको Cloud SDK में प्रोजेक्ट बदलने होंगे. gcloud projects list कमांड चलाकर, सभी उपलब्ध प्रोजेक्ट की सूची देखी जा सकती है.