Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update upload_video.py #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 65 additions & 27 deletions utils/upload_video.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
import sys
import time

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
Expand All @@ -25,6 +25,17 @@
# Always retry when an apiclient.errors.HttpError with one of these status
# codes is raised.
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

# 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/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
# https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRETS_FILE = "client_secrets.json"

# This OAuth 2.0 access scope allows an application to upload files to the
Expand All @@ -44,7 +55,7 @@
%s

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

For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
Expand All @@ -70,26 +81,37 @@ def get_authenticated_service(args):

def initialize_upload(youtube, options):
tags = None
# if options.keywords:
# tags = options.keywords.split(",")
if options.keywords:
tags = options.keywords.split(",")

body=dict(
snippet=dict(
title=options['title'],
description=options['description'],
title=options.title,
description=options.description,
tags=tags,
#categoryId=options['category']
categoryId=options.category
),
status=dict(
privacyStatus=options['privacyStatus']
privacyStatus=options.privacyStatus
)
)

# Call the API's videos.insert method to create and upload the video.
insert_request = youtube.videos().insert(
part=",".join(body.keys()),
body=body,
media_body=MediaFileUpload(options['file'], chunksize=-1, resumable=True)
# The chunksize parameter specifies the size of each chunk of data, in
# bytes, that will be uploaded at a time. Set a higher value for
# reliable connections as fewer chunks lead to faster uploads. Set a lower
# value for better recovery on less reliable connections.
#
# Setting "chunksize" equal to -1 in the code below means that the entire
# file will be uploaded in a single HTTP request. (If the upload fails,
# it will still be retried where it left off.) This is usually a best
# practice, but if you're using Python older than 2.6 or if you're
# running on App Engine, you should set the chunksize to something like
# 1024 * 1024 (1 megabyte).
media_body=MediaFileUpload(options.file, chunksize=-1, resumable=True)
)

resumable_upload(insert_request)
Expand All @@ -106,17 +128,16 @@ def resumable_upload(insert_request):
status, response = insert_request.next_chunk()
if response is not None:
if 'id' in response:
print("Video id '%s' was successfully uploaded." % response['id'])
print(f"Video id '%s' was successfully uploaded. {response['id']}")
else:
exit("The upload failed with an unexpected response: %s" % response)
except HttpError as e:
if e.resp.status in RETRIABLE_STATUS_CODES:
error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
e.content)
error = (f"A retriable HTTP error %d occurred:{e.resp.status,e.content}")
else:
raise
except RETRIABLE_EXCEPTIONS as e:
error = "A retriable error occurred: %s" % e
error = (f"A retriable error occurred:{e}")

if error is not None:
print(error)
Expand All @@ -126,26 +147,43 @@ def resumable_upload(insert_request):

max_sleep = 2 ** retry
sleep_seconds = random.random() * max_sleep
print("Sleeping %f seconds and then retrying..." % sleep_seconds)
print(f"Sleeping {sleep_seconds} seconds and then retrying...")
time.sleep(sleep_seconds)

def upload_video(video_data):
args = argparser.parse_args()
if not os.path.exists(video_data['file']):
exit("Please specify a valid file using the --file= parameter.")

youtube = get_authenticated_service(args)
try:
initialize_upload(youtube, video_data)
except HttpError as e:
print("An HTTP error %d occurred:\n%s" % (e.resp.status, e.content))

if __name__ == '__main__':
video_data = {
video_data = {
"file": "video.mp4",
"title": "Best of memes!",
"description": "#shorts \n Giving you the hottest memes of the day with funny comments!",
"keywords":"meme,reddit",
"privacyStatus":"private"
}
update_video(video_data)
update_video(video_data)

# argparser.add_argument("--file", required=True, help="Video file to upload")
# argparser.add_argument("--title", help="Video title", default="Test Title")
# argparser.add_argument("--description", help="Video description",
# default="Test Description")
# argparser.add_argument("--category", default="22",
# help="Numeric video category. " +
# "See https://developers.google.com/youtube/v3/docs/videoCategories/list")
# argparser.add_argument("--keywords", help="Video keywords, comma separated",
# default="")
# argparser.add_argument("--privacyStatus", choices=VALID_PRIVACY_STATUSES,
# default=VALID_PRIVACY_STATUSES[0], help="Video privacy status.")
# args = argparser.parse_args()

# if not os.path.exists(args.file):
# exit("Please specify a valid file using the --file= parameter.")

# youtube = get_authenticated_service(args)
# try:
# initialize_upload(youtube, args)
# except HttpError as e:
# print(f"An HTTP error %d occurred: {e.resp.status, e.content}")



# python3 upload_video.py --file="/Users/hm/Downloads/vid-17489.mp4" --privacyStatus="unlisted" --title="Hello YouTube Data API (Like, Comment, Subscribe)" --description="The results of uploading my first video to YouTube via API." --keywords="youtube api, hello world, like, comment, subscribe" --category |="22"