Python के साथ Video Intelligence API का इस्तेमाल करना

1. खास जानकारी

cfaa6ffa7bc5ca70.png

Video Intelligence API की मदद से, Google की वीडियो विश्लेषण टेक्नोलॉजी को अपने ऐप्लिकेशन में इस्तेमाल किया जा सकता है.

इस लैब में, Python के साथ Video Intelligence API का इस्तेमाल करने पर फ़ोकस किया जाएगा.

आपको क्या सीखने को मिलेगा

  • अपना एनवायरमेंट सेट अप करने का तरीका
  • Python को सेट अप करने का तरीका
  • शॉट में हुए बदलावों का पता कैसे लगाएं
  • लेबल का पता कैसे लगाया जाता है
  • अश्लील कॉन्टेंट का पता कैसे लगाया जाता है
  • बोली को लेख में बदलने का तरीका
  • टेक्स्ट का पता लगाने और उसे ट्रैक करने का तरीका
  • ऑब्जेक्ट का पता लगाने और उन्हें ट्रैक करने का तरीका
  • लोगो का पता लगाने और उन्हें ट्रैक करने का तरीका

आपको इन चीज़ों की ज़रूरत होगी

  • Google Cloud प्रोजेक्ट
  • कोई ब्राउज़र, जैसे कि Chrome या Firefox
  • Python का इस्तेमाल करने की जानकारी

सर्वे

इस ट्यूटोरियल का इस्तेमाल कैसे किया जाएगा?

सिर्फ़ इसे पढ़ें इसे पढ़ें और एक्सरसाइज़ पूरी करें

Python के साथ अपने अनुभव को आप क्या रेटिंग देंगे?

शुरुआती सामान्य एडवांस

Google Cloud की सेवाओं को इस्तेमाल करने का आपका अनुभव कैसा रहा?

शुरुआती सामान्य एडवांस

2. सेटअप और ज़रूरी शर्तें

अपने हिसाब से एनवायरमेंट सेट अप करना

  1. Google Cloud Console में साइन इन करें और नया प्रोजेक्ट बनाएं या किसी मौजूदा प्रोजेक्ट का फिर से इस्तेमाल करें. अगर आपके पास पहले से कोई Gmail या Google Workspace खाता नहीं है, तो आपको एक खाता बनाना होगा.

b35bf95b8bf3d5d8.png

a99b7ace416376c4.png

bd84a6d3004737c5.png

  • प्रोजेक्ट का नाम, इस प्रोजेक्ट में हिस्सा लेने वाले लोगों के लिए डिसप्ले नेम होता है. यह एक वर्ण स्ट्रिंग है, जिसका इस्तेमाल Google API नहीं करते. इसे कभी भी अपडेट किया जा सकता है.
  • प्रोजेक्ट आईडी, सभी Google Cloud प्रोजेक्ट के लिए यूनीक होता है. साथ ही, इसे बदला नहीं जा सकता. Cloud Console, यूनीक स्ट्रिंग को अपने-आप जनरेट करता है. आम तौर पर, आपको इससे कोई फ़र्क़ नहीं पड़ता कि यह क्या है. ज़्यादातर कोडलैब में, आपको अपने प्रोजेक्ट आईडी (आम तौर पर PROJECT_ID के तौर पर पहचाना जाता है) का रेफ़रंस देना होगा. अगर आपको जनरेट किया गया आईडी पसंद नहीं है, तो कोई दूसरा रैंडम आईडी जनरेट किया जा सकता है. इसके अलावा, आपके पास अपना नाम आज़माने का विकल्प भी है. इससे आपको पता चलेगा कि वह नाम उपलब्ध है या नहीं. इस चरण के बाद, इसे बदला नहीं जा सकता. यह प्रोजेक्ट की अवधि तक बना रहता है.
  • आपकी जानकारी के लिए बता दें कि एक तीसरी वैल्यू भी होती है, जिसे प्रोजेक्ट नंबर कहते हैं. इसका इस्तेमाल कुछ एपीआई करते हैं. इन तीनों वैल्यू के बारे में ज़्यादा जानने के लिए, दस्तावेज़ देखें.
  1. इसके बाद, आपको Cloud Console में बिलिंग चालू करनी होगी, ताकि Cloud संसाधनों/एपीआई का इस्तेमाल किया जा सके. इस कोडलैब को पूरा करने में ज़्यादा समय नहीं लगेगा. इस ट्यूटोरियल के बाद बिलिंग से बचने के लिए, संसाधनों को बंद किया जा सकता है. इसके लिए, बनाए गए संसाधनों को मिटाएं या प्रोजेक्ट को मिटाएं. Google Cloud के नए उपयोगकर्ताओं को, 300 डॉलर का क्रेडिट मिलेगा. वे इसे मुफ़्त में आज़मा सकते हैं.

Cloud Shell शुरू करें

Google Cloud को अपने लैपटॉप से रिमोटली ऑपरेट किया जा सकता है. हालांकि, इस कोडलैब में Cloud Shell का इस्तेमाल किया जाएगा. यह क्लाउड में चलने वाला कमांड लाइन एनवायरमेंट है.

Cloud Shell चालू करें

  1. Cloud Console में, Cloud Shell चालू करें 853e55310c205094.png पर क्लिक करें.

55efc1aaa7a4d3ad.png

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

9c92662c6a846a5c.png

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

9f0e51b578fecce5.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. यह पुष्टि करने के लिए कि gcloud कमांड को आपके प्रोजेक्ट के बारे में पता है, Cloud Shell में यह कमांड चलाएं:
gcloud config list project

कमांड आउटपुट

[core]
project = <PROJECT_ID>

अगर ऐसा नहीं है, तो इस कमांड का इस्तेमाल करके इसे सेट किया जा सकता है:

gcloud config set project <PROJECT_ID>

कमांड आउटपुट

Updated property [core/project].

3. एनवायरमेंट सेटअप करना

Video Intelligence API का इस्तेमाल शुरू करने से पहले, Cloud Shell में यह कमांड चलाकर एपीआई को चालू करें:

gcloud services enable videointelligence.googleapis.com

आपको कुछ ऐसा दिखेगा:

Operation "operations/..." finished successfully.

अब Video Intelligence API का इस्तेमाल किया जा सकता है!

अपनी होम डायरेक्ट्री पर जाएं:

cd ~

डिपेंडेंसी को अलग करने के लिए, Python का वर्चुअल एनवायरमेंट बनाएं:

virtualenv venv-videointel

वर्चुअल एनवायरमेंट चालू करें:

source venv-videointel/bin/activate

IPython और Video Intelligence API की क्लाइंट लाइब्रेरी इंस्टॉल करें:

pip install ipython google-cloud-videointelligence

आपको कुछ ऐसा दिखेगा:

...
Installing collected packages: ..., ipython, google-cloud-videointelligence
Successfully installed ... google-cloud-videointelligence-2.11.0 ...

अब Video Intelligence API की क्लाइंट लाइब्रेरी का इस्तेमाल किया जा सकता है!

अगले चरणों में, आपको IPython नाम के इंटरैक्टिव Python इंटरप्रेटर का इस्तेमाल करना होगा. इसे आपने पिछले चरण में इंस्टॉल किया था. Cloud Shell में ipython चलाकर सेशन शुरू करें:

ipython

आपको कुछ ऐसा दिखेगा:

Python 3.9.2 (default, Feb 28 2021, 17:03:44)
Type 'copyright', 'credits' or 'license' for more information
IPython 8.12.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]:

4. सैंपल वीडियो

Cloud Storage में सेव किए गए या डेटा बाइट के तौर पर दिए गए वीडियो में एनोटेशन जोड़ने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है.

अगले चरणों में, Cloud Storage में सेव किए गए सैंपल वीडियो का इस्तेमाल किया जाएगा. आपके पास ब्राउज़र में वीडियो देखने का विकल्प है.

afe058b29c480d42.png

तैयार हो जाएं, शुरू करें!

5. शॉट में हुए बदलावों का पता लगाना

वीडियो में शॉट के बदलावों का पता लगाने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है. शॉट, वीडियो का एक हिस्सा होता है. यह विज़ुअल कंटिन्यूटी वाले फ़्रेम की एक सीरीज़ होती है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from typing import cast

from google.cloud import videointelligence_v1 as vi


def detect_shot_changes(video_uri: str) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.SHOT_CHANGE_DETECTION]
    request = vi.AnnotateVideoRequest(input_uri=video_uri, features=features)

    print(f'Processing video: "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें. इसमें बताया गया है कि वीडियो का विश्लेषण करने और शॉट में हुए बदलावों का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.SHOT_CHANGE_DETECTION

वीडियो का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"

results = detect_shot_changes(video_uri)

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

वीडियो के शॉट प्रिंट करने के लिए, इस फ़ंक्शन को जोड़ें:

def print_video_shots(results: vi.VideoAnnotationResults):
    shots = results.shot_annotations
    print(f" Video shots: {len(shots)} ".center(40, "-"))
    for i, shot in enumerate(shots):
        t1 = shot.start_time_offset.total_seconds()
        t2 = shot.end_time_offset.total_seconds()
        print(f"{i+1:>3} | {t1:7.3f} | {t2:7.3f}")
        

फ़ंक्शन को कॉल करें:

print_video_shots(results)

आपको कुछ ऐसा दिखेगा:

----------- Video shots: 34 ------------
  1 |   0.000 |  12.880
  2 |  12.920 |  21.680
  3 |  21.720 |  27.880
...
 32 | 135.160 | 138.320
 33 | 138.360 | 146.200
 34 | 146.240 | 162.520

अगर हर शॉट के बीच वाले फ़्रेम को निकालकर, उन्हें फ़्रेम की दीवार में व्यवस्थित किया जाता है, तो वीडियो की विज़ुअल समरी जनरेट की जा सकती है:

25bbffa59f7ed71d.png

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में शॉट बदलने की सुविधा का इस्तेमाल किया. शॉट में हुए बदलावों का पता लगाने के बारे में ज़्यादा जानें.

6. लेबल का पता लगाना

वीडियो में लेबल का पता लगाने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है. लेबल, वीडियो में मौजूद विज़ुअल कॉन्टेंट के आधार पर उसके बारे में बताते हैं.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def detect_labels(
    video_uri: str,
    mode: vi.LabelDetectionMode,
    segments: Optional[Sequence[vi.VideoSegment]] = None,
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.LABEL_DETECTION]
    config = vi.LabelDetectionConfig(label_detection_mode=mode)
    context = vi.VideoContext(segments=segments, label_detection_config=config)
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें और जानें कि वीडियो का विश्लेषण करने और लेबल का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.LABEL_DETECTION

वीडियो के शुरुआती 37 सेकंड का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
mode = vi.LabelDetectionMode.SHOT_MODE
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=0),
    end_time_offset=timedelta(seconds=37),
)

results = detect_labels(video_uri, mode, [segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

वीडियो लेवल पर लेबल प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_video_labels(results: vi.VideoAnnotationResults):
    labels = sorted_by_first_segment_confidence(results.segment_label_annotations)

    print(f" Video labels: {len(labels)} ".center(80, "-"))
    for label in labels:
        categories = category_entities_to_str(label.category_entities)
        for segment in label.segments:
            confidence = segment.confidence
            t1 = segment.segment.start_time_offset.total_seconds()
            t2 = segment.segment.end_time_offset.total_seconds()
            print(
                f"{confidence:4.0%}",
                f"{t1:7.3f}",
                f"{t2:7.3f}",
                f"{label.entity.description}{categories}",
                sep=" | ",
            )


def sorted_by_first_segment_confidence(
    labels: Sequence[vi.LabelAnnotation],
) -> Sequence[vi.LabelAnnotation]:
    def first_segment_confidence(label: vi.LabelAnnotation) -> float:
        return label.segments[0].confidence

    return sorted(labels, key=first_segment_confidence, reverse=True)


def category_entities_to_str(category_entities: Sequence[vi.Entity]) -> str:
    if not category_entities:
        return ""
    entities = ", ".join([e.description for e in category_entities])
    return f" ({entities})"
    

फ़ंक्शन को कॉल करें:

print_video_labels(results)

आपको कुछ ऐसा दिखेगा:

------------------------------- Video labels: 10 -------------------------------
 96% |   0.000 |  36.960 | nature
 74% |   0.000 |  36.960 | vegetation
 59% |   0.000 |  36.960 | tree (plant)
 56% |   0.000 |  36.960 | forest (geographical feature)
 49% |   0.000 |  36.960 | leaf (plant)
 43% |   0.000 |  36.960 | flora (plant)
 38% |   0.000 |  36.960 | nature reserve (geographical feature)
 38% |   0.000 |  36.960 | woodland (forest)
 35% |   0.000 |  36.960 | water resources (water)
 32% |   0.000 |  36.960 | sunlight (light)

वीडियो-लेवल के इन लेबल की मदद से, यह समझा जा सकता है कि वीडियो की शुरुआत में ज़्यादातर जानकारी, प्रकृति और पेड़-पौधों के बारे में है.

शॉट लेवल पर लेबल प्रिंट करने के लिए, इस फ़ंक्शन को जोड़ें:

def print_shot_labels(results: vi.VideoAnnotationResults):
    labels = sorted_by_first_segment_start_and_confidence(
        results.shot_label_annotations
    )

    print(f" Shot labels: {len(labels)} ".center(80, "-"))
    for label in labels:
        categories = category_entities_to_str(label.category_entities)
        print(f"{label.entity.description}{categories}")
        for segment in label.segments:
            confidence = segment.confidence
            t1 = segment.segment.start_time_offset.total_seconds()
            t2 = segment.segment.end_time_offset.total_seconds()
            print(f"{confidence:4.0%} | {t1:7.3f} | {t2:7.3f}")


def sorted_by_first_segment_start_and_confidence(
    labels: Sequence[vi.LabelAnnotation],
) -> Sequence[vi.LabelAnnotation]:
    def first_segment_start_and_confidence(label: vi.LabelAnnotation):
        first_segment = label.segments[0]
        ms = first_segment.segment.start_time_offset.total_seconds()
        return (ms, -first_segment.confidence)

    return sorted(labels, key=first_segment_start_and_confidence)
    

फ़ंक्शन को कॉल करें:

print_shot_labels(results)

आपको कुछ ऐसा दिखेगा:

------------------------------- Shot labels: 29 --------------------------------
planet (astronomical object)
 83% |   0.000 |  12.880
earth (planet)
 53% |   0.000 |  12.880
water resources (water)
 43% |   0.000 |  12.880
aerial photography (photography)
 43% |   0.000 |  12.880
vegetation
 32% |   0.000 |  12.880
 92% |  12.920 |  21.680
 83% |  21.720 |  27.880
 77% |  27.920 |  31.800
 76% |  31.840 |  34.720
...
butterfly (insect, animal)
 84% |  34.760 |  36.960
...

शॉट-लेवल के इन लेबल की मदद से, यह समझा जा सकता है कि वीडियो की शुरुआत किसी ग्रह (शायद पृथ्वी) के शॉट से होती है, 34.760-36.960s शॉट में एक तितली है,...

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में लेबल का पता लगाया. लेबल का पता लगाने के बारे में ज़्यादा जानें.

7. अश्लील कॉन्टेंट का पता लगाना

वीडियो में अश्लील कॉन्टेंट का पता लगाने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है. अश्लील कॉन्टेंट, वयस्कों के लिए बना ऐसा कॉन्टेंट होता है जो आम तौर पर 18 साल से कम उम्र के लोगों के लिए सही नहीं होता. इसमें नग्नता, सेक्शुअल ऐक्ट, और पॉर्नोग्राफ़ी शामिल है. हालांकि, इसमें और भी कॉन्टेंट शामिल हो सकता है. वीडियो में मौजूद हर फ़्रेम के विज़ुअल सिग्नल के आधार पर ही, ऑब्जेक्ट का पता लगाया जाता है. इसमें ऑडियो का इस्तेमाल नहीं किया जाता. जवाब में, संभावना की वैल्यू शामिल होती हैं. इनकी रेंज VERY_UNLIKELY से VERY_LIKELY तक होती है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def detect_explicit_content(
    video_uri: str,
    segments: Optional[Sequence[vi.VideoSegment]] = None,
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.EXPLICIT_CONTENT_DETECTION]
    context = vi.VideoContext(segments=segments)
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें और जानें कि वीडियो का विश्लेषण करने और आपत्तिजनक कॉन्टेंट का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.EXPLICIT_CONTENT_DETECTION

वीडियो के शुरुआती 10 सेकंड का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=0),
    end_time_offset=timedelta(seconds=10),
)

results = detect_explicit_content(video_uri, [segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

अलग-अलग संभावनाओं की संख्या को प्रिंट करने के लिए, इस फ़ंक्शन को जोड़ें:

def print_explicit_content(results: vi.VideoAnnotationResults):
    from collections import Counter

    frames = results.explicit_annotation.frames
    likelihood_counts = Counter([f.pornography_likelihood for f in frames])

    print(f" Explicit content frames: {len(frames)} ".center(40, "-"))
    for likelihood in vi.Likelihood:
        print(f"{likelihood.name:<22}: {likelihood_counts[likelihood]:>3}")
        

फ़ंक्शन को कॉल करें:

print_explicit_content(results)

आपको कुछ ऐसा दिखेगा:

----- Explicit content frames: 10 ------
LIKELIHOOD_UNSPECIFIED:   0
VERY_UNLIKELY         :  10
UNLIKELY              :   0
POSSIBLE              :   0
LIKELY                :   0
VERY_LIKELY           :   0

फ़्रेम की जानकारी प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_frames(results: vi.VideoAnnotationResults, likelihood: vi.Likelihood):
    frames = results.explicit_annotation.frames
    frames = [f for f in frames if f.pornography_likelihood == likelihood]

    print(f" {likelihood.name} frames: {len(frames)} ".center(40, "-"))
    for frame in frames:
        print(frame.time_offset)
        

फ़ंक्शन को कॉल करें:

print_frames(results, vi.Likelihood.VERY_UNLIKELY)

आपको कुछ ऐसा दिखेगा:

------- VERY_UNLIKELY frames: 10 -------
0:00:00.365992
0:00:01.279206
0:00:02.268336
0:00:03.289253
0:00:04.400163
0:00:05.291547
0:00:06.449558
0:00:07.452751
0:00:08.577405
0:00:09.554514

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में अश्लील कॉन्टेंट का पता लगाया. साफ़ तौर पर सेक्शुअल ऐक्ट दिखाने वाले कॉन्टेंट का पता लगाने के बारे में ज़्यादा जानें.

8. बोले जा रहे शब्दों को लेख में बदलना

वीडियो में मौजूद आवाज़ को टेक्स्ट में बदलने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def transcribe_speech(
    video_uri: str,
    language_code: str,
    segments: Optional[Sequence[vi.VideoSegment]] = None,
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.SPEECH_TRANSCRIPTION]
    config = vi.SpeechTranscriptionConfig(
        language_code=language_code,
        enable_automatic_punctuation=True,
    )
    context = vi.VideoContext(
        segments=segments,
        speech_transcription_config=config,
    )
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें. साथ ही, देखें कि यह वीडियो का विश्लेषण करने और स्पीच को ट्रांसक्राइब करने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे करता है.SPEECH_TRANSCRIPTION

वीडियो के 55 से 80 सेकंड तक के हिस्से का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
language_code = "en-GB"
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=55),
    end_time_offset=timedelta(seconds=80),
)

results = transcribe_speech(video_uri, language_code, [segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

बोली को लिखाई में बदले गए टेक्स्ट को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_video_speech(results: vi.VideoAnnotationResults, min_confidence: float = 0.8):
    def keep_transcription(transcription: vi.SpeechTranscription) -> bool:
        return min_confidence <= transcription.alternatives[0].confidence

    transcriptions = results.speech_transcriptions
    transcriptions = [t for t in transcriptions if keep_transcription(t)]

    print(f" Speech transcriptions: {len(transcriptions)} ".center(80, "-"))
    for transcription in transcriptions:
        first_alternative = transcription.alternatives[0]
        confidence = first_alternative.confidence
        transcript = first_alternative.transcript
        print(f" {confidence:4.0%} | {transcript.strip()}")
        

फ़ंक्शन को कॉल करें:

print_video_speech(results)

आपको कुछ ऐसा दिखेगा:

--------------------------- Speech transcriptions: 2 ---------------------------
  91% | I was keenly aware of secret movements in the trees.
  92% | I looked into his large and lustrous eyes. They seem somehow to express his entire personality.

पहचाने गए शब्दों और उनके टाइमस्टैंप की सूची प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_word_timestamps(
    results: vi.VideoAnnotationResults,
    min_confidence: float = 0.8,
):
    def keep_transcription(transcription: vi.SpeechTranscription) -> bool:
        return min_confidence <= transcription.alternatives[0].confidence

    transcriptions = results.speech_transcriptions
    transcriptions = [t for t in transcriptions if keep_transcription(t)]

    print(" Word timestamps ".center(80, "-"))
    for transcription in transcriptions:
        first_alternative = transcription.alternatives[0]
        confidence = first_alternative.confidence
        for word in first_alternative.words:
            t1 = word.start_time.total_seconds()
            t2 = word.end_time.total_seconds()
            word = word.word
            print(f"{confidence:4.0%} | {t1:7.3f} | {t2:7.3f} | {word}")
            

फ़ंक्शन को कॉल करें:

print_word_timestamps(results)

आपको कुछ ऐसा दिखेगा:

------------------------------- Word timestamps --------------------------------
 93% |  55.000 |  55.700 | I
 93% |  55.700 |  55.900 | was
 93% |  55.900 |  56.300 | keenly
 93% |  56.300 |  56.700 | aware
 93% |  56.700 |  56.900 | of
...
 94% |  76.900 |  77.400 | express
 94% |  77.400 |  77.600 | his
 94% |  77.600 |  78.200 | entire
 94% |  78.200 |  78.500 | personality.

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके किसी वीडियो में बोले गए शब्दों को टेक्स्ट में बदला. ऑडियो को टेक्स्ट में बदलने के बारे में ज़्यादा जानें.

9. टेक्स्ट का पता लगाना और उसे ट्रैक करना

वीडियो में टेक्स्ट का पता लगाने और उसे ट्रैक करने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def detect_text(
    video_uri: str,
    language_hints: Optional[Sequence[str]] = None,
    segments: Optional[Sequence[vi.VideoSegment]] = None,
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.TEXT_DETECTION]
    config = vi.TextDetectionConfig(
        language_hints=language_hints,
    )
    context = vi.VideoContext(
        segments=segments,
        text_detection_config=config,
    )
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें और जानें कि वीडियो का विश्लेषण करने और टेक्स्ट का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.TEXT_DETECTION

वीडियो के 13 से 27 सेकंड तक के हिस्से का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=13),
    end_time_offset=timedelta(seconds=27),
)

results = detect_text(video_uri, segments=[segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

पहचाने गए टेक्स्ट को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_video_text(results: vi.VideoAnnotationResults, min_frames: int = 15):
    annotations = sorted_by_first_segment_end(results.text_annotations)

    print(" Detected text ".center(80, "-"))
    for annotation in annotations:
        for text_segment in annotation.segments:
            frames = len(text_segment.frames)
            if frames < min_frames:
                continue
            text = annotation.text
            confidence = text_segment.confidence
            start = text_segment.segment.start_time_offset
            seconds = segment_seconds(text_segment.segment)
            print(text)
            print(f"  {confidence:4.0%} | {start} + {seconds:.1f}s | {frames} fr.")


def sorted_by_first_segment_end(
    annotations: Sequence[vi.TextAnnotation],
) -> Sequence[vi.TextAnnotation]:
    def first_segment_end(annotation: vi.TextAnnotation) -> int:
        return annotation.segments[0].segment.end_time_offset.total_seconds()

    return sorted(annotations, key=first_segment_end)


def segment_seconds(segment: vi.VideoSegment) -> float:
    t1 = segment.start_time_offset.total_seconds()
    t2 = segment.end_time_offset.total_seconds()
    return t2 - t1
    

फ़ंक्शन को कॉल करें:

print_video_text(results)

आपको कुछ ऐसा दिखेगा:

-------------------------------- Detected text ---------------------------------
GOMBE NATIONAL PARK
   99% | 0:00:15.760000 + 1.7s | 15 fr.
TANZANIA
  100% | 0:00:15.760000 + 4.8s | 39 fr.
With words and narration by
  100% | 0:00:23.200000 + 3.6s | 31 fr.
Jane Goodall
   99% | 0:00:23.080000 + 3.8s | 33 fr.

पहचाने गए टेक्स्ट फ़्रेम और बाउंडिंग बॉक्स की सूची को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_text_frames(results: vi.VideoAnnotationResults, contained_text: str):
    # Vertex order: top-left, top-right, bottom-right, bottom-left
    def box_top_left(box: vi.NormalizedBoundingPoly) -> str:
        tl = box.vertices[0]
        return f"({tl.x:.5f}, {tl.y:.5f})"

    def box_bottom_right(box: vi.NormalizedBoundingPoly) -> str:
        br = box.vertices[2]
        return f"({br.x:.5f}, {br.y:.5f})"

    annotations = results.text_annotations
    annotations = [a for a in annotations if contained_text in a.text]
    for annotation in annotations:
        print(f" {annotation.text} ".center(80, "-"))
        for text_segment in annotation.segments:
            for frame in text_segment.frames:
                frame_ms = frame.time_offset.total_seconds()
                box = frame.rotated_bounding_box
                print(
                    f"{frame_ms:>7.3f}",
                    box_top_left(box),
                    box_bottom_right(box),
                    sep=" | ",
                )
                

यह देखने के लिए कि किन फ़्रेम में नरेटर का नाम दिखता है, फ़ंक्शन को कॉल करें:

contained_text = "Goodall"
print_text_frames(results, contained_text)

आपको कुछ ऐसा दिखेगा:

--------------------------------- Jane Goodall ---------------------------------
 23.080 | (0.39922, 0.49861) | (0.62752, 0.55888)
 23.200 | (0.38750, 0.49028) | (0.62692, 0.56306)
...
 26.800 | (0.36016, 0.49583) | (0.61094, 0.56048)
 26.920 | (0.45859, 0.49583) | (0.60365, 0.56174)

अगर आपने बाउंडिंग बॉक्स को फ़्रेम के ऊपर बनाया है, तो आपको यह दिखेगा:

7e530d3d25f2f40e.gif

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में टेक्स्ट का पता लगाने और उसे ट्रैक करने की सुविधा का इस्तेमाल किया. टेक्स्ट का पता लगाने और उसे ट्रैक करने के बारे में ज़्यादा जानें.

10. ऑब्जेक्ट का पता लगाना और उन्हें ट्रैक करना

वीडियो में मौजूद ऑब्जेक्ट का पता लगाने और उन्हें ट्रैक करने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def track_objects(
    video_uri: str, segments: Optional[Sequence[vi.VideoSegment]] = None
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.OBJECT_TRACKING]
    context = vi.VideoContext(segments=segments)
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें और जानें कि वीडियो का विश्लेषण करने और ऑब्जेक्ट का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.OBJECT_TRACKING

वीडियो के 98 से 112 सेकंड तक के हिस्से का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=98),
    end_time_offset=timedelta(seconds=112),
)

results = track_objects(video_uri, [segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

पता लगाए गए ऑब्जेक्ट की सूची को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_detected_objects(
    results: vi.VideoAnnotationResults,
    min_confidence: float = 0.7,
):
    annotations = results.object_annotations
    annotations = [a for a in annotations if min_confidence <= a.confidence]

    print(
        f" Detected objects: {len(annotations)}"
        f" ({min_confidence:.0%} <= confidence) ".center(80, "-")
    )
    for annotation in annotations:
        entity = annotation.entity
        description = entity.description
        entity_id = entity.entity_id
        confidence = annotation.confidence
        t1 = annotation.segment.start_time_offset.total_seconds()
        t2 = annotation.segment.end_time_offset.total_seconds()
        frames = len(annotation.frames)
        print(
            f"{description:<22}",
            f"{entity_id:<10}",
            f"{confidence:4.0%}",
            f"{t1:>7.3f}",
            f"{t2:>7.3f}",
            f"{frames:>2} fr.",
            sep=" | ",
        )
        

फ़ंक्शन को कॉल करें:

print_detected_objects(results)

आपको कुछ ऐसा दिखेगा:

------------------- Detected objects: 3 (70% <= confidence) --------------------
insect                 | /m/03vt0   |  87% |  98.840 | 101.720 | 25 fr.
insect                 | /m/03vt0   |  71% | 108.440 | 111.080 | 23 fr.
butterfly              | /m/0cyf8   |  91% | 111.200 | 111.920 |  7 fr.

पहचाने गए ऑब्जेक्ट फ़्रेम और बाउंडिंग बॉक्स की सूची को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_object_frames(
    results: vi.VideoAnnotationResults,
    entity_id: str,
    min_confidence: float = 0.7,
):
    def keep_annotation(annotation: vi.ObjectTrackingAnnotation) -> bool:
        return (
            annotation.entity.entity_id == entity_id
            and min_confidence <= annotation.confidence
        )

    annotations = results.object_annotations
    annotations = [a for a in annotations if keep_annotation(a)]
    for annotation in annotations:
        description = annotation.entity.description
        confidence = annotation.confidence
        print(
            f" {description},"
            f" confidence: {confidence:.0%},"
            f" frames: {len(annotation.frames)} ".center(80, "-")
        )
        for frame in annotation.frames:
            t = frame.time_offset.total_seconds()
            box = frame.normalized_bounding_box
            print(
                f"{t:>7.3f}",
                f"({box.left:.5f}, {box.top:.5f})",
                f"({box.right:.5f}, {box.bottom:.5f})",
                sep=" | ",
            )
            

कीड़ों के लिए, इकाई आईडी के साथ फ़ंक्शन को कॉल करें:

insect_entity_id = "/m/03vt0"
print_object_frames(results, insect_entity_id)

आपको कुछ ऐसा दिखेगा:

--------------------- insect, confidence: 87%, frames: 25 ----------------------
 98.840 | (0.49327, 0.19617) | (0.69905, 0.69633)
 98.960 | (0.49559, 0.19308) | (0.70631, 0.69671)
...
101.600 | (0.46668, 0.19776) | (0.76619, 0.69371)
101.720 | (0.46805, 0.20053) | (0.76447, 0.68703)
--------------------- insect, confidence: 71%, frames: 23 ----------------------
108.440 | (0.47343, 0.10694) | (0.63821, 0.98332)
108.560 | (0.46960, 0.10206) | (0.63033, 0.98285)
...
110.960 | (0.49466, 0.05102) | (0.65941, 0.99357)
111.080 | (0.49572, 0.04728) | (0.65762, 0.99868)

अगर आपने बाउंडिंग बॉक्स को फ़्रेम के ऊपर बनाया है, तो आपको यह दिखेगा:

8f5796f6e73d1a46.gif

c195a2dca4573f95.gif

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में ऑब्जेक्ट का पता लगाया और उसे ट्रैक किया. ऑब्जेक्ट का पता लगाने और उन्हें ट्रैक करने के बारे में ज़्यादा जानें.

11. लोगो का पता लगाना और उन्हें ट्रैक करना

वीडियो में मौजूद लोगो का पता लगाने और उन्हें ट्रैक करने के लिए, Video Intelligence API का इस्तेमाल किया जा सकता है. एक लाख से ज़्यादा ब्रैंड और लोगो का पता लगाया जा सकता है.

नीचे दिए गए कोड को अपने IPython सेशन में कॉपी करें:

from datetime import timedelta
from typing import Optional, Sequence, cast

from google.cloud import videointelligence_v1 as vi


def detect_logos(
    video_uri: str, segments: Optional[Sequence[vi.VideoSegment]] = None
) -> vi.VideoAnnotationResults:
    video_client = vi.VideoIntelligenceServiceClient()
    features = [vi.Feature.LOGO_RECOGNITION]
    context = vi.VideoContext(segments=segments)
    request = vi.AnnotateVideoRequest(
        input_uri=video_uri,
        features=features,
        video_context=context,
    )

    print(f'Processing video "{video_uri}"...')
    operation = video_client.annotate_video(request)

    # Wait for operation to complete
    response = cast(vi.AnnotateVideoResponse, operation.result())
    # A single video is processed
    results = response.annotation_results[0]

    return results
    

कोड को ध्यान से देखें. साथ ही, यह देखें कि वीडियो का विश्लेषण करने और लोगो का पता लगाने के लिए, annotate_video पैरामीटर के साथ annotate_video क्लाइंट लाइब्रेरी के तरीके का इस्तेमाल कैसे किया जाता है.LOGO_RECOGNITION

वीडियो के आखिरी से पहले वाले क्रम का विश्लेषण करने के लिए, फ़ंक्शन को कॉल करें:

video_uri = "gs://cloud-samples-data/video/JaneGoodall.mp4"
segment = vi.VideoSegment(
    start_time_offset=timedelta(seconds=146),
    end_time_offset=timedelta(seconds=156),
)

results = detect_logos(video_uri, [segment])

वीडियो के प्रोसेस होने का इंतज़ार करें:

Processing video: "gs://cloud-samples-data/video/JaneGoodall.mp4"...

पहचाने गए लोगो की सूची प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_detected_logos(results: vi.VideoAnnotationResults):
    annotations = results.logo_recognition_annotations

    print(f" Detected logos: {len(annotations)} ".center(80, "-"))
    for annotation in annotations:
        entity = annotation.entity
        entity_id = entity.entity_id
        description = entity.description
        for track in annotation.tracks:
            confidence = track.confidence
            t1 = track.segment.start_time_offset.total_seconds()
            t2 = track.segment.end_time_offset.total_seconds()
            logo_frames = len(track.timestamped_objects)
            print(
                f"{confidence:4.0%}",
                f"{t1:>7.3f}",
                f"{t2:>7.3f}",
                f"{logo_frames:>3} fr.",
                f"{entity_id:<15}",
                f"{description}",
                sep=" | ",
            )
            

फ़ंक्शन को कॉल करें:

print_detected_logos(results)

आपको कुछ ऐसा दिखेगा:

------------------------------ Detected logos: 1 -------------------------------
 92% | 150.680 | 155.720 |  43 fr. | /m/055t58       | Google Maps

पहचाने गए लोगो फ़्रेम और बाउंडिंग बॉक्स की सूची को प्रिंट करने के लिए, यह फ़ंक्शन जोड़ें:

def print_logo_frames(results: vi.VideoAnnotationResults, entity_id: str):
    def keep_annotation(annotation: vi.LogoRecognitionAnnotation) -> bool:
        return annotation.entity.entity_id == entity_id

    annotations = results.logo_recognition_annotations
    annotations = [a for a in annotations if keep_annotation(a)]
    for annotation in annotations:
        description = annotation.entity.description
        for track in annotation.tracks:
            confidence = track.confidence
            print(
                f" {description},"
                f" confidence: {confidence:.0%},"
                f" frames: {len(track.timestamped_objects)} ".center(80, "-")
            )
            for timestamped_object in track.timestamped_objects:
                t = timestamped_object.time_offset.total_seconds()
                box = timestamped_object.normalized_bounding_box
                print(
                    f"{t:>7.3f}",
                    f"({box.left:.5f}, {box.top:.5f})",
                    f"({box.right:.5f}, {box.bottom:.5f})",
                    sep=" | ",
                )
                

Google Maps के लोगो की इकाई के आईडी के साथ फ़ंक्शन को कॉल करें:

maps_entity_id = "/m/055t58"
print_logo_frames(results, maps_entity_id)

आपको कुछ ऐसा दिखेगा:

------------------- Google Maps, confidence: 92%, frames: 43 -------------------
150.680 | (0.42024, 0.28633) | (0.58192, 0.64220)
150.800 | (0.41713, 0.27822) | (0.58318, 0.63556)
...
155.600 | (0.41775, 0.27701) | (0.58372, 0.63986)
155.720 | (0.41688, 0.28005) | (0.58335, 0.63954)

अगर आपने बाउंडिंग बॉक्स को फ़्रेम के ऊपर बनाया है, तो आपको यह दिखेगा:

554743aff6d8824c.gif

खास जानकारी

इस चरण में, आपने Video Intelligence API का इस्तेमाल करके, किसी वीडियो में लोगो का पता लगाने और उसे ट्रैक करने की सुविधा का इस्तेमाल किया. लोगो का पता लगाने और उन्हें ट्रैक करने के बारे में ज़्यादा जानें.

12. एक से ज़्यादा सुविधाओं का पता लगाना

एक साथ सभी अहम जानकारी पाने के लिए, इस तरह का अनुरोध किया जा सकता है:

from google.cloud import videointelligence_v1 as vi

video_client = vi.VideoIntelligenceServiceClient()
video_uri = "gs://..."
features = [
    vi.Feature.SHOT_CHANGE_DETECTION,
    vi.Feature.LABEL_DETECTION,
    vi.Feature.EXPLICIT_CONTENT_DETECTION,
    vi.Feature.SPEECH_TRANSCRIPTION,
    vi.Feature.TEXT_DETECTION,
    vi.Feature.OBJECT_TRACKING,
    vi.Feature.LOGO_RECOGNITION,
    vi.Feature.FACE_DETECTION,  # NEW
    vi.Feature.PERSON_DETECTION,  # NEW
]
context = vi.VideoContext(
    segments=...,
    shot_change_detection_config=...,
    label_detection_config=...,
    explicit_content_detection_config=...,
    speech_transcription_config=...,
    text_detection_config=...,
    object_tracking_config=...,
    face_detection_config=...,  # NEW
    person_detection_config=...,  # NEW
)
request = vi.AnnotateVideoRequest(
    input_uri=video_uri,
    features=features,
    video_context=context,
)

# video_client.annotate_video(request)

13. बधाई हो!

cfaa6ffa7bc5ca70.png

आपने Python का इस्तेमाल करके, Video Intelligence API का इस्तेमाल करना सीख लिया है!

व्यवस्थित करें

Cloud Shell से, डेवलपमेंट एनवायरमेंट को क्लीन अप करने के लिए:

  • अगर आप अब भी IPython सेशन में हैं, तो शेल पर वापस जाएं: exit
  • Python वर्चुअल एनवायरमेंट का इस्तेमाल बंद करें: deactivate
  • अपना वर्चुअल एनवायरमेंट फ़ोल्डर मिटाएं: cd ~ ; rm -rf ./venv-videointel

Google Cloud प्रोजेक्ट मिटाने के लिए, Cloud Shell में जाकर यह तरीका अपनाएं:

  • अपना मौजूदा प्रोजेक्ट आईडी पाएं: PROJECT_ID=$(gcloud config get-value core/project)
  • पक्का करें कि आपको यही प्रोजेक्ट मिटाना है: echo $PROJECT_ID
  • प्रोजेक्ट मिटाएं: gcloud projects delete $PROJECT_ID

ज़्यादा जानें

लाइसेंस

इस काम के लिए, Creative Commons एट्रिब्यूशन 2.0 जेनेरिक लाइसेंस के तहत लाइसेंस मिला है.