Oleksandr Myronchuk
Oleksandr Myronchuk

Reputation: 360

Cannot upload YouTube video with thumbnails and tags

This is the code that I used to upload a video with its title, description, thumbnails, and tags. While the video and its title and description were successfully uploaded, the thumbnails and tags were not. As a result, the video has no thumbnails and tags

import sys
import os
import base64
import io
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
from google.oauth2.credentials import Credentials
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload 
from oauth2client.file import Storage
from google.auth.transport.requests import Request

# Define scopes for authorization
scopes = ["https://www.googleapis.com/auth/youtube.upload"]
CLIENT_SECRETS_FILE = "client_secrets.json"
VIDEO_FILE = "video.mkv"
CREDENTIALS_FILE = "credentials.json"

def get_credentials():
    creds = None
    if os.path.exists(CREDENTIALS_FILE):
        # Load existing credentials from the storage file
        with open(CREDENTIALS_FILE, 'r') as f:
            creds = Credentials.from_authorized_user_info(eval(f.read()))

    if not creds or not creds.valid:
        # If there are no (valid) credentials available, let the user log in.
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            CLIENT_SECRETS_FILE, scopes)
        creds = flow.run_local_server(port=0)
        
        # Save the credentials for the next run
        with open(CREDENTIALS_FILE, 'w') as f:
            f.write(str(creds.to_json()))
    
    return creds

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    # Get credentials and create an API client
    credentials = get_credentials()
    youtube = googleapiclient.discovery.build(
        "youtube", "v3", credentials=credentials)

    # Define request body for video resource
    request_body = {
        "snippet": {
            "title": "My awesome video",
            "description": "This is a video that I made for YouTube.",
            "thumbnails": {
                "maxres": {
                    "url": "https://iili.io/HXD7zTg.jpg"
                }
            },
            "tags": ["youtube", "video", "awesome"],
            "categoryId": "22"
        },
        "status": { 
            "privacyStatus": "public"
        }
    }
    
    media_type = 'video/*'
        
    # Upload the video
    request = youtube.videos().insert(
        part="snippet,status",
        body=request_body,
        media_body=googleapiclient.http.MediaFileUpload(VIDEO_FILE,
                                                        mimetype=media_type,
                                                        resumable=True)
    )

    response = request.execute()

if __name__ == "__main__":
    main()

I am using the JSON structure format for video uploading from the following link: https://developers.google.com/youtube/v3/docs/videos.

maxres - The highest resolution version of the thumbnail image. This image size is available for some videos and other resources that refer to videos, like playlist items or search results. This image is 1280px wide and 720px tall.

The size of the image is 1280x720px

What is wrong with this code? Help find the error.

Upvotes: 0

Views: 193

Answers (1)

pauliec
pauliec

Reputation: 441

So, 2 things....on the thumbs, It's likely because the YouTube API v3 won't support uploading custom thumbs within a 'vidoes().insert()' request. and the tags aren't being uploaded because you didn't specify snippet.tags in the part parameter. for tags you'd just need to update that parameter to include them:

    
      request = youtube.videos().insert(
      part="snippet,status,snippet.tags",
         ...
        )

the thumbs would need to be uploaded separately using thumbnails().set() method. After the video is uploaded, you can use the video id to set the custom thumbs to update them after the upload:

    def set_thumbnail(youtube, video_id, thumbnail_url):
    request = youtube.thumbnails().set(
        videoId=video_id,
        media_body=googleapiclient.http.MediaFileUpload(thumbnail_url,
                                                         mimetype='image/jpeg',
                                                         resumable=True)
    )
    response = request.execute()
    print("Thumbnail was successfully set.")
    return response

then call this function after the upload is finished

    if __name__ == "__main__":
    response = main()
    video_id = response['id']
    thumbnail_url = "path/to/your/thumbnail.jpg"  # Provide the local path to your thumbnail image
    set_thumbnail(youtube, video_id, thumbnail_url)

last possible item/rememinder...you'd need to add https://www.googleapis.com/auth/youtube.force-ssl scope to your scopes list to set the custom thumbs

    scopes = ["https://www.googleapis.com/auth/youtube.upload", 
    "https://www.googleapis.com/auth/youtube.force-ssl"]

Upvotes: 1

Related Questions