नया संदर्भ अपलोड करना

ध्यान दें: YouTube Content ID API का इस्तेमाल, YouTube कॉन्टेंट पार्टनर करते हैं. इसे सभी डेवलपर या YouTube का इस्तेमाल करने वाले सभी लोग ऐक्सेस नहीं कर सकते. अगर आपको Google API कंसोल में दी गई सेवाओं में से एक सेवा के तौर पर YouTube Content ID API नहीं दिख रहा है, तो YouTube Partner Program के बारे में ज़्यादा जानने के लिए YouTube सहायता केंद्र पर जाएं.

यह कोड सैंपल बताता है कि YouTube Content ID API का इस्तेमाल करके, reference को कैसे अपलोड किया जाता है. reference अपलोड करने के लिए, आपको सबसे पहले asset बनाना होगा. साथ ही, एसेट के मालिकाना हक और मिलते-जुलते वीडियो से जुड़ी नीति को कॉन्फ़िगर करना होगा. इस उदाहरण में इन सभी चरणों के बारे में बताया गया है.

यह उदाहरण, कोड के काम के सेक्शन के साथ शामिल चरणों की सीरीज़ के तौर पर दिखाया गया है. इस पेज के आखिर में आपको पूरी स्क्रिप्ट मिल सकती है. कोड को Python में लिखा गया है. दूसरी लोकप्रिय प्रोग्रामिंग भाषाओं के लिए क्लाइंट लाइब्रेरी भी उपलब्ध हैं.

सैंपल स्क्रिप्ट कोई गड़बड़ी ठीक नहीं करती है.

ज़रूरी शर्तें

इस चरण में, हम स्क्रिप्ट में OAuth 2.0 की अनुमति शामिल करेंगे. इससे स्क्रिप्ट चलाने वाला उपयोगकर्ता, उपयोगकर्ता के खाते से जुड़े एपीआई अनुरोधों को पूरा करने के लिए, स्क्रिप्ट को अनुमति दे पाता है.

client_secrets.json फ़ाइल बनाएं

YouTube Content ID API की पुष्टि करने के लिए, एक client_secrets.json फ़ाइल की ज़रूरत होती है. इस फ़ाइल में एपीआई कंसोल से मिली जानकारी शामिल होती है. आपको अपना ऐप्लिकेशन भी रजिस्टर करना होगा. पुष्टि करने के तरीके के बारे में ज़्यादा जानने के लिए, पुष्टि करने की गाइड देखें.

 {
  "web": {
    "client_id": "INSERT CLIENT ID HERE",
    "client_secret": "INSERT CLIENT SECRET HERE",
    "redirect_uris": [],
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token"
  }
}

अपनी स्क्रिप्ट में पुष्टि करने वाला कोड जोड़ें

उपयोगकर्ता की पुष्टि और अनुमति देने के लिए, आपको ये import स्टेटमेंट जोड़ने होंगे:

from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

इसके बाद, हम दूसरे चरण में कॉन्फ़िगर किए गए क्लाइंट सीक्रेट का इस्तेमाल करके, FLOW ऑब्जेक्ट बनाएंगे. अगर उपयोगकर्ता, हमारे ऐप्लिकेशन को उपयोगकर्ता की ओर से एपीआई अनुरोध सबमिट करने की अनुमति देता है, तो मिलने वाले क्रेडेंशियल, बाद में इस्तेमाल करने के लिए Storage ऑब्जेक्ट में सेव किए जाते हैं. क्रेडेंशियल की समयसीमा खत्म होने पर, उपयोगकर्ता को हमारे ऐप्लिकेशन को फिर से अनुमति देनी होगी.

main फ़ंक्शन के आखिर में यह कोड जोड़ें:

  # Set up a Flow object to be used if we need to authenticate.
  FLOW = flow_from_clientsecrets('client_secrets.json',
      scope='https://www.googleapis.com/auth/youtubepartner',
      message='error message')

  # The Storage object stores the credentials. If it doesn't exist, or if
  # the credentials are invalid or expired, run through the native client flow.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()
  
  if (credentials is None or credentials.invalid or
      credentials.token_expiry <= datetime.now()):
    credentials = run(FLOW, storage)

httplib2 ऑब्जेक्ट बनाएं और क्रेडेंशियल अटैच करें

जब उपयोगकर्ता हमारी स्क्रिप्ट को अनुमति देता है, तब हम एक httplib2.Http ऑब्जेक्ट बनाते हैं. यह एपीआई अनुरोधों को मैनेज करता है और उस ऑब्जेक्ट के लिए ऑथराइज़ेशन क्रेडेंशियल अटैच करता है.

यह इंपोर्ट स्टेटमेंट जोड़ें:

  import httplib2

इस कोड को main फ़ंक्शन के आखिर में जोड़ें:

  # Create httplib2.Http object to handle HTTP requests and
  # attach auth credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

सेवाएं पाएं

अनुमति मिलने के बाद, कोड को उन कामों के लिए ज़रूरी सेवाएं मिल जाती हैं जो वह करेगा. यह सबसे पहले एक service ऑब्जेक्ट बनाता है, जिससे YouTube Content ID API की सभी सेवाओं को ऐक्सेस किया जा सकता है. इसके बाद, यह कोड service ऑब्जेक्ट का इस्तेमाल करके, उन चार संसाधनों से जुड़ी सेवाएं हासिल करता है जिन्हें कॉल किया जाता है.

from apiclient.discovery import build

# ...

service = build("youtubePartner", "v1", http=http, static_discovery=False)
# ...
asset_service = service.assets()
# ...
ownership_service = service.ownership()
# ...
match_policy_service = service.assetMatchPolicy()
# ...
reference_service = service.references()

एसेट बनाना

reference अपलोड करने का पहला स्टेप है, asset बनाना. सबसे पहले, हम एक आसान metadata ऑब्जेक्ट बनाते हैं, जो सिर्फ़ एसेट का टाइटल सेट करता है. इसके बाद कोड, उस ऑब्जेक्ट को asset_body में जोड़ देता है. इससे यह भी पता चलता है कि एसेट किस तरह की है. इसके बदले में, asset_body ऑब्जेक्ट का इस्तेमाल asset_service.insert() तरीके में इनपुट के तौर पर किया जाता है. वह तरीका एसेट बनाता है और अपना यूनीक आईडी दिखाता है.

def _create_asset(service, title, metadata_type):
  metadata = {'title': title}
  asset_body = {'metadata': metadata, 'type': metadata_type}
  # Retrieve asset service.
  asset_service = service.assets()

  # Create and execute insert request.
  request = asset_service.insert(body=asset_body)
  response = request.execute()
  logger.info('Asset has been created.\n%s', response)
  asset_id = response['id']
  return asset_id

मालिकाना हक की जानकारी अपडेट करना

asset बनाने के बाद, स्क्रिप्ट एसेट की ownership को कॉन्फ़िगर करती है. इस उदाहरण से पता चलता है कि कॉन्टेंट के मालिक के पास 100% एसेट है, लेकिन यह मालिकाना हक पोलैंड (PL) और ग्रेट ब्रिटेन (GB) तक ही सीमित है.

def _create_asset_ownership(service, asset_id, owner_name):
  ownership = {
      'owner': owner_name,
      'ratio' : 100,
      'type': 'include',
      'territories': ['PL', 'GB']}
  ownership_body = {'general': [ownership]}
  ownership_service = service.ownership()

  request = ownership_service.update(assetId=asset_id, body=ownership_body)
  response = request.execute()
  logger.info('Asset ownership has been created.\n%s', response)

ऐसेट की मिलते-जुलते वीडियो से जुड़ी नीति को अपडेट करना

पहचान फ़ाइल बनाने से पहले, कोड को एसेट से जुड़े assetMatchPolicy संसाधन को अपडेट करके, एसेट की मिलते-जुलते वीडियो से जुड़ी नीति को भी कॉन्फ़िगर करना होगा. एसेट की मिलते-जुलते वीडियो से जुड़ी नीति से यह पता चलता है कि जब YouTube पर कोई वीडियो, एसेट से जुड़ी किसी पहचान फ़ाइल से मिलता-जुलता है, तो YouTube क्या कार्रवाई करेगा. इस उदाहरण में, एक सामान्य नीति बनाई गई है. इसमें, 10 सेकंड से ज़्यादा समय के मिलते-जुलते वीडियो को दुनिया भर में ट्रैक किया जाता है.

def _create_match_policy(service, asset_id):
  match_policy_service = service.assetMatchPolicy()
  everywhere_policy_condition = {
      'requiredTerritories': {
          'type': 'exclude', 'territories': []},
      'requiredReferenceDuration': [{'low': 10}],
      'contentMatchType': 'video'}
  track_everywhere_rule = {
      'action': 'track',
      'condition': everywhere_policy_condition}
  request = match_policy_service.update(
      assetId=asset_id,
      body={
        'name': 'Track Everywhere 10s.',
        'description': 'Track Everywhere matches longer than 10s.',
        'rules': [track_everywhere_rule]})
  response = request.execute()
  logger.info('Asset match policy has been created.\n%s', response)

पहचान फ़ाइल अपलोड करें

asset, ownership, और assetMatchPolicy तय होने के बाद, स्क्रिप्ट reference अपलोड करती है. यह MediaFileUpload तरीके का इस्तेमाल करता है, ताकि यह फिर से शुरू होने वाली अपलोडिंग का फ़ायदा ले सके. ध्यान दें कि reference_file पैरामीटर, अपलोड की जाने वाली लोकल फ़ाइल का नाम बताता है. साथ ही, reference_file कमांड लाइन विकल्प का इस्तेमाल करके, वह वैल्यू स्क्रिप्ट को भेजी जाती है.

def _create_reference(service, asset_id, reference_file):
  reference_service = service.reference()
  media = MediaFileUpload(reference_file, resumable=True)
  request = reference_service.insert(
      body={'assetId': asset_id, 'contentType': 'video'},
      media_body=media)
  status, response = request.next_chunk()
  while response is None:
    status, response = request.next_chunk()
    if status:
      logger.info("Uploaded %d%%.", int(status.progress() * 100))
  logger.info('Reference has been created.\n%s', response)
    

Full code sample

The complete working sample asset_reference_upload_example.py is listed below:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Google Inc.
#
# 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.

"""Simple command-line sample for Youtube partner API.

Command-line application that creates asset, asset ownership, match policy
and reference.

Usage:
  $ python asset_reference_upload_example.py --reference_file=REFERENCE_FILE \
      --asset_title=ASSET_TITLE --owner=OWNER

You can also get help on all the command-line flags the program understands
by running:

  $ python asset_reference_upload_example.py --help
"""

__author__ = '[email protected] (Mateusz Zięba)'

import httplib2
import logging
import sys
import optparse
import os

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run

# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google API Console at
# https://console.cloud.google.com/.
# See the "Registering your application" instructions for an explanation
# of how to find these values:
# https://developers.google.com/youtube/partner/guides/registering_an_application
CLIENT_SECRETS = 'client_secrets.json'

# Helpful message to display if the CLIENT_SECRETS file is missing.
MISSING_CLIENT_SECRETS_MESSAGE = """
WARNING: Please configure OAuth 2.0

To make this sample run you need to populate the client_secrets.json
file found at:

%s

with information from the API Console
<https://console.cloud.google.com/>.

""" % os.path.join(os.path.dirname(__file__), CLIENT_SECRETS)

# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets(CLIENT_SECRETS,
           scope='https://www.googleapis.com/auth/youtubepartner',
           message=MISSING_CLIENT_SECRETS_MESSAGE)

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())


def _create_asset(service, title, metadata_type):
  metadata = {'title': title}
  asset_body = {'metadata': metadata, 'type': metadata_type}
  # Retrieve asset service.
  asset_service = service.assets()

  # Create and execute insert request.
  request = asset_service.insert(body=asset_body)
  response = request.execute()
  logger.info('Asset has been created.\n%s', response)
  asset_id = response['id']
  return asset_id


def _create_asset_ownership(service, asset_id, owner_name):
  ownership = {
      'owner': owner_name,
      'ratio' : 100,
      'type': 'include',
      'territories': ['PL', 'GB']}
  ownership_body = {'general': [ownership]}
  ownership_service = service.ownership()

  request = ownership_service.update(assetId=asset_id, body=ownership_body)
  response = request.execute()
  logger.info('Asset ownership has been created.\n%s', response)


def _create_match_policy(service, asset_id):
  match_policy_service = service.assetMatchPolicy()
  everywhere_policy_condition = {
      'requiredTerritories': {
          'type': 'exclude', 'territories': []},
      'requiredReferenceDuration': [{'low': 10}],
      'contentMatchType': 'video'}
  track_everywhere_rule = {
      'action': 'track',
      'condition': everywhere_policy_condition}
  request = match_policy_service.update(
      assetId=asset_id,
      body={
        'name': 'Track Everywhere 10s.',
        'description': 'Track Everywhere matches longer than 10s.',
        'rules': [track_everywhere_rule]})
  response = request.execute()
  logger.info('Asset match policy has been created.\n%s', response)


def _create_reference(service, asset_id, reference_file):
  reference_service = service.references()
  media = MediaFileUpload(reference_file, resumable=True)
  request = reference_service.insert(
      body={'assetId': asset_id, 'contentType': 'video'},
      media_body=media)
  status, response = request.next_chunk()
  while response is None:
    status, response = request.next_chunk()
    if status:
      logger.info("Uploaded %d%%.", int(status.progress() * 100))
  logger.info('Reference has been created.\n%s', response)


def _parse_options():
  parser = optparse.OptionParser(
      description='Creates asset, asset ownership, match policy and reference.')
  parser.add_option('--version',
                    default='v1',
                    type=str, help='API version.')
  parser.add_option('--reference_file', type=str,
                    help='File containing reference to be uploaded. Required')
  parser.add_option('--asset_title',
                    type=str, help='Asset title. Required')
  parser.add_option('--owner',
                    type=str, help='Content owner name. Required')
  (options, args) = parser.parse_args()

  if not options.reference_file:
    parser.error("--reference_file is required")
  if not options.asset_title:
    parser.error("--asset_title is required")
  if not options.owner:
    parser.error("--owner is required")
  return options


def main(argv):
  options = _parse_options()
  # If the Credentials don't exist or are invalid run through the native client
  # flow. The Storage object ensures that if successful the good
  # Credentials are written back to a file.
  storage = Storage('yt_partner_api.dat')
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    credentials = run(FLOW, storage)

  # Create an httplib2.Http object to handle our HTTP requests and authorize it
  # with our good Credentials.
  http = httplib2.Http()
  http = credentials.authorize(http)

  service = build("youtubePartner", options.version, http=http, static_discovery=False)

  try:
    asset_id = _create_asset(service, options.asset_title, 'web')
    _create_asset_ownership(service, asset_id, options.owner)
    _create_match_policy(service, asset_id)
    _create_reference(service, asset_id, options.reference_file)

  except AccessTokenRefreshError:
    logger.info("The credentials have been revoked or expired, please re-run"
      " the application to re-authorize")

if __name__ == '__main__':
  main(sys.argv)