Sitemap / Advertise

Introduction

Record videos with various image effects and upload them to YouTube with given parameters via the YouTube Data API.


Tags

Share

YouTube Video Recorder and Uploader GUI with Night Vision on Raspberry Pi

Advertisement:


read_later

Read Later



read_later

Read Later

Introduction

Record videos with various image effects and upload them to YouTube with given parameters via the YouTube Data API.

Tags

Share





Advertisement

Advertisement


Banggood
Banggood


    Components :
  • [1]Raspberry Pi 3 Model B+
  • [1]Raspberry Pi SD Card (32GB)
  • [1]DFRobot 7'' HDMI Display (Capacitive)
  • [1]DFRobot 5MP Night Vision Camera

Description

I am fond of experimenting with the Raspberry Pi camera options (such as image effects and duration) while recording demonstration videos for my electronics projects, and especially when birdwatching in my balcony :) When I take a video with my Raspberry Pi for the mentioned reasons, I usually upload the video to my YouTube channel, as a private video, due to the storage limit on Pi. However, the process of recording and uploading through Raspberry Pi had miscellaneous and intricate steps to follow all over again: adjusting video settings manually, opening my YouTube channel, defining video parameters, etc.

Thus, I contemplated a GUI by which I could adjust the video recording settings and define the parameters to upload videos to YouTube without signing to my YouTube channel on the browser every time. After some research, I decided to use the Google APIs Client Library for Python to communicate with my YouTube channel through the YouTube Data API. In the end, I developed a GUI (YouTube Video Recorder and Uploader) in Python, including two interfaces - Record menu and Upload menu.

In the Record menu:

You can define filename (timestamp included automatically), annotation text (if required), the video duration, and select an image effect (predefined by the GUI, for instance, negative).

In the Upload menu:

You can upload the selected video to YouTube via the YouTube Data API without any further steps by merely entering the required parameters by YouTube - Title, Description, Keywords, Category, and Privacy Status.

You can find detailed information about the features of the GUI (YouTube Video Recorder and Uploader) in the Features.

After completing coding, to add mobility and night vision to my project - helpful while birdwatching or recording outside at night :) - I used a 7'' HDMI Display with Capacitive Touchscreen and a 5MP Night Vision Camera, kindly sponsored by DFRobot.

Sponsored Products by DFRobot:

- 7'' HDMI Display with Capacitive Touchscreen | Inspect

- 5MP Night Vision Camera for Raspberry Pi | Inspect

project-image
Figure - 43.1


project-image
Figure - 43.2

Preview: What You Will Learn

- How to register your application with Google so that it can use the OAuth 2.0 protocol to authorize access to user data

- How to install the Google APIs Client Library for Python on Raspberry Pi

- How to set up the night vision camera to record videos with the given settings

- How to program a GUI with the guizero module

- How to create a class in Python

- How to convert the H264 format to the MP4 format using MP4Box in Python

- How to upload videos to your YouTube channel using the YouTube Data API

Step 1: Registering an application with Google to use the OAuth 2.0 protocol to authorize access

You need to create an application on the Google API Console to run the Google APIs Client Library for Python properly, and your application must have authorization credentials to be able to use the YouTube Data API.

If you are a novice to the Google API Console, do not worry it is a simple process, apply the following steps only :)

- Go to the Google API Console and click to the 'New Project' button.

project-image
Figure - 43.3

- Enter the project name - YouTubeUploader - and create the project.

project-image
Figure - 43.4

- Open the API Library.

project-image
Figure - 43.5

- Enable the YouTube Data API v3.

project-image
Figure - 43.6

- Select 'Credentials' under the YouTube Data API v3 and click the 'CREATE CREDENTIALS' button.

project-image
Figure - 43.7

- Select the application type as 'Other' and enter the application name as 'Client'.

project-image
Figure - 43.8

- Copy the Client ID and the Client Secret. You will need them later when authorizing your Raspberry Pi with the Google APIs Client Library for Python as a user.

project-image
Figure - 43.9

Step 2: Installing the Google APIs Client Library for Python on Raspberry Pi

Open the terminal and enter the command below (it will take some time to install all packages):

$ sudo pip install --upgrade google-api-python-client

project-image
Figure - 43.10

If requested, you may need to install the oauth2client module.

$ sudo pip install --upgrade oauth2client

Step 3: Authorizing Raspberry Pi to upload videos via the YouTube Data API

First of all, create a new folder at this path:

/home/pi/YouTube-Recorder-and-Uploader/

Then, download the upload_video.py file in the Code. It is the sample code provided by Google for the YouTube Data API.

Create the client_secrets.json (there is a sample in the Code) file that contains information from the Google API Console (Client ID and Client Secret).

{
  "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"
  }
}

Inspect upload_video.py and client_secrets.json sample files I used from this guide by Google.

Do not forget to change the client secret path in the upload_video.py file.

project-image
Figure - 43.11

Now, to verify your Raspberry Pi, open the terminal and enter the following command.

$ sudo python /home/pi/YouTube-Recorder-and-Uploader/
                       --file="[[INSERT FILE PATH]]"
                       --title="Test"
                       --description="Test"
                       --keywords="test"
                       --category="22"
                       --privacyStatus="private"

Do not worry; it will throw an error message which says "Cannot access: ...upload_video.py-auth2.json" due to the absence of the confirmation tokens generated when you sign in to an application.

project-image
Figure - 43.12

To create the requested file, click the link generated by the API.

And, sign in with your selected account to the application.

project-image
Figure - 43.13


project-image
Figure - 43.14

Copy the verification code.

project-image
Figure - 43.15

Enter the verification code in the terminal and voila! Now, you can upload videos to your YouTube channel as many as you want without signing in again :)

project-image
Figure - 43.16

You can see the generated verification file named upload_video.py-auth2.json (/home/pi/YouTube-Recorder-and-Uploader/).

project-image
Figure - 43.17

Note: Do not forget to create a folder named Recorded in the parent folder (/home/pi/YouTube-Recorder-and-Uploader/) to save videos afterward.

Step 4: Developing a GUI (YouTube Video Recorder and Uploader) and programming Raspberry Pi

There are different modules by which you can create a GUI in Python; I chose to use the guizero module due to its simplicity and efficiency.

To be able to use all the provided widgets and events by the guizero module, install the module on Raspberry Pi:

$ sudo pip3 install guizero

After running the mentioned command on the terminal, you can use the code I provided (YouTube_Video_Recorder_and_Uploader_GUI.py) without any further requirements.

But, if you want to add new features or inspect the widget features, you can get more detailed information about the guizero module from here.

Unfortunately, Raspberry Pi captures video as a raw H264 video stream, and YouTube does not allow users to upload a video in the H264 format. So, we need to convert the video in the H264 format to the MP4 format by using MP4Box before uploading it to YouTube.

Install MP4Box with this command:

$ sudo apt install -y gpac

The code executes the following command automatically when the user records a new video using the GUI. So, while using the GUI (YouTube Video Recorder and Uploader), you do not need to take any further action to convert videos from the H264 format to the MP4 format to upload them to YouTube.

MP4Box -add [[INSERT PATH]].h264 [[INSERT PATH]].mp4

I will explain the code of the GUI step by step as follows, but if you want to inspect the features of the GUI (YouTube Video Recorder and Uploader), go to the Features.

Code Explanation:

- Import the required modules and libraries.

- Create the YouTube_Recorder_Uploader class with the required setting parameters - resolution and framerate:

- Define the camera module settings.

- In the open_folder function, open the parent folder (/home/pi/YouTube-Recorder-and-Uploader/) to inspect videos.

- In the about function, define the information box for the menubar.

- In the tutorial function, define the tutorial page link.

- In the get_existing_videos function:

- Get the mp4 videos in the Recorded folder using the glob module to be able to select a video to upload or play via this GUI.

- Insert the new list to the ListBox widget and remove the old items.

- In the show_selected_video function, create a pop-up, including the selected video information.

- In record function:

- Get the current date as the timestamp to generate unique file names.

- Get the entered video settings on the GUI to record a video.

- Define the video file path and location for both the H264 format and the MP4 format.

- Record a video with the given settings.

- Convert the H264 format to the MP4 format using the subprocess module (MP4Box) to upload videos to YouTube.

- Update the video list after recording a new video.

- In the upload function:

- Get the entered YouTube video parameters - title, description, keywords, category, and privacy status.

- Print the given uploading settings (parameters) in the shell.

- Upload video to the registered YouTube account by transferring the uploading settings to the upload_video.py file with the subprocess module; I explained this command in Step 3.

- In the play function, play the selected video using omxplayer.

- Define a new class object named 'video' and enter the resolution and framerate parameters.

- Create the YouTube Video Recorder and Uploader GUI.

- Define menu bar options.

- Design the application interface - Header, Record, and Upload.

- Create the record menu to be able to adjust the video recording settings - Filename, Annotate, Image Effect, and Duration.

- Create the upload menu to be able to enter the required parameters by YouTube - Title, Description, Keywords, Category, and Privacy Status - and select a video in the Recorded folder.

- You can find detailed information regarding the category numbers in the Features.

- Get the paths of the recorded videos in the Recorded folder.

- Initiate the application loop.

project-image
Figure - 43.18


project-image
Figure - 43.19


project-image
Figure - 43.20


project-image
Figure - 43.21


project-image
Figure - 43.22

Features

Record Menu:

1) You can define the filename and the annotation text (pinned on the video). For each video, the GUI (YouTube Video Recorder and Uploader) adds a timestamp at the end of the filename (example: test-05-06-2020_17.25.01.mp4). Also, you can define the video duration using the slider from 0 to 250 seconds.

project-image
Figure - 43.23


project-image
Figure - 43.24

2) You can choose one of the predefined image effects (solarize, negative, pastel, etc.,) provided by the GUI before recording.

project-image
Figure - 43.25

3) The GUI allows you to preview your video while recording.

project-image
Figure - 43.26

4) After taking a video by clicking the Record button, the GUI updates the video list to insert the recently recorded video's path automatically.

project-image
Figure - 43.27

5) The GUI saves videos in two file types - H264 (default) and MP4 (automatically generated by the GUI) - to the Recorded folder.

project-image
Figure - 43.28

Upload Menu:

1) You can define the video parameters required by the YouTube Data API - Title, Description, Keywords, and Privacy Status - in the GUI (YouTube Video Recorder and Uploader).

project-image
Figure - 43.29

2) YouTube has a category list in numbers by which you can change the default category (22) before uploading videos with the GUI. I added these categories which you can choose between:

You can inspect all categories from here.

project-image
Figure - 43.30

3) You can select the video you want to upload to YouTube on the list box. The GUI notifies you with an information (info) message, including the path of the selected video, to avoid selections by mistake.

project-image
Figure - 43.31


project-image
Figure - 43.32

4) You can play the video with the omxplayer before uploading it to YouTube if you want to check the video quality again.

project-image
Figure - 43.33

5) When you fill all the required parameters, you can upload the selected video with the given parameters to your YouTube channel by merely clicking the Upload button, without any further action :)

project-image
Figure - 43.34

6) Go to your YouTube Studio to view the video you upload with the YouTube Video Recorder and Uploader GUI.

project-image
Figure - 43.35


project-image
Figure - 43.36

Shell:

1) The GUI prints notification messages after every command: you can see the recording and uploading settings or check whether the video is uploaded to YouTube correctly - if it is, you should see the video ID.

project-image
Figure - 43.37


project-image
Figure - 43.38


project-image
Figure - 43.39

Menubar:

I added this menubar for fun :)

1) You can see the project explanation in a nutshell.

project-image
Figure - 43.40

2) And, you can access the videos and other files by clicking the Files button.

project-image
Figure - 43.41

Connections (Hardware)

If you are a novice in programming with Raspberry Pi, to go to the official Raspberry Pi setting up tutorial, click here.

project-image
Figure - 43.42

To learn how to connect the Raspberry Pi Camera Module to your Raspberry Pi and take pictures, record videos, and apply image effects, go to the official getting started with the camera module tutorial.

project-image
Figure - 43.43

Assemble the DFRobot 5MP Night Vision Camera and connect it to your Pi.

project-image-slide project-image-slide project-image-slide
Slide


DFRobot 7'' HDMI Display with Capacitive Touchscreen is a very reliable and compatible screen for your projects with Raspberry Pi. Attach your Raspberry Pi to the screen using the standoffs and machine screws. And, connect the Pi to the screen using the well-thought Raspberry Pi HDMI Adapter. As a bonus, you do not need any driver.

project-image-slide project-image-slide project-image-slide
Slide


You can fasten the camera to the back of the screen using the little band coming with the camera module.

project-image
Figure - 43.44

Now, you can use the GUI (YouTube Video Recorder and Uploader) with DFRobot 7'' HDMI Display with Capacitive Touchscreen and DFRobot 5MP Night Vision Camera :)

project-image
Figure - 43.45


project-image
Figure - 43.46


project-image
Figure - 43.47

Conclusion and Testing Features

You can see the recording and uploading processes in the project demonstration video.

The video uploaded with the parameters shown in the Features:

Video recording with the negative image effect setting:

project-image
Figure - 43.48


project-image
Figure - 43.49

Video recording and uploading with the solarize image effect setting:

Video recording and uploading in the dark to test the night vision camera:

project-image
Figure - 43.50

Outdoor testing while birdwatching :)

project-image
Figure - 43.51


project-image
Figure - 43.52

Code

YouTube_Video_Recorder_and_Uploader_GUI.py

Download



# YouTube Video Recorder and Uploader with Night Vision on Raspberry Pi
#
# Raspberry Pi 3B+
# 
# By Kutluhan Aktar
#
# Develop a GUI to record videos with the selected image settings and effects and upload them to your YouTube channel
# with the given parameters (description, title, category, e.g.,).
# 
# Get more information on the project page:
# https://theamplituhedron.com/projects/YouTube-Video-Recorder-and-Uploader-GUI-with-Night-Vision-on-Raspberry-Pi/


from guizero import App, Box, Text, TextBox, PushButton, ButtonGroup, Combo, Slider, ListBox, MenuBar, info
from picamera import PiCamera
from time import sleep
from subprocess import call, Popen
import datetime
import webbrowser
import glob

# Create the YouTube_Recorder_Uploader class with the required settings:
class YouTube_Recorder_Uploader:
    def __init__(self, r_x, r_y, framerate):
        # Define the camera module settings.
        self.camera = PiCamera()
        self.camera.resolution = (r_x, r_y)
        self.camera.framerate = framerate
    def open_folder(self):
        # Open the parent folder to inspect videos.
        webbrowser.open("//home//pi//YouTube-Recorder-and-Uploader//")
    def about(self):
        # Define the information box.
        info('About', 'Learn how create a GUI by which you can record videos with the selected image settings and upload them to your YouTube channel using Google API (YouTube Data v3) with the given parameters :)')
    def tutorial(self):
        # Go to the project tutorial page.
        webbrowser.open("https://theamplituhedron.com/projects/YouTube-Video-Recorder-and-Uploader-GUI-with-Night-Vision-on-Raspberry-Pi/")
    def get_existing_videos(self):
        # Get the mp4 videos in the Recorded folder to be able to select a video to upload or play via this GUI.
        files = [f for f in glob.glob("/home/pi/YouTube-Recorder-and-Uploader/Recorded/*.mp4")]
        # Insert new list to the ListBox and remove the old items.
        u_select_input.clear()
        for f in files:
            u_select_input.append(f)
    def show_selected_video(self):
        # Create a pop-up including the selected video.
        info("Selected Video", u_select_input.value)
    def record(self):
        # Get the current date as the timestamp to generate unique file names.
        date = datetime.datetime.now().strftime('%m-%d-%Y_%H.%M.%S')
        # Get the entered video settings to record a video.
        filename = r_name_input.value[:-1]
        annotate = r_annotate_input.value[:-1]
        effect = r_effect_input.value
        duration = r_duration_input.value
        # Define video file path and location.
        path = '/home/pi/YouTube-Recorder-and-Uploader/Recorded/'
        video_h264 = path + filename + '-' + date + '.h264'
        video_mp4 = path + filename + '-' + date + '.mp4'
        # Record a video with the given settings.
        print("\r\nRecording Settings:\r\nLocation => " + video_h264 + "\r\nAnnotate => " + annotate + "\r\nEffect => " + effect + "\r\nDuration => " + str(duration))
        self.camera.annotate_text = annotate
        self.camera.image_effect = effect
        self.camera.start_preview()
        self.camera.start_recording(video_h264)
        sleep(int(duration))
        self.camera.stop_recording()
        self.camera.stop_preview()
        print("Rasp_Pi => Video Recorded! \r\n")
        # Convert the h264 format to the mp4 format to upload videos in mp4 format to YouTube.
        command = "MP4Box -add " + video_h264 + " " + video_mp4
        call([command], shell=True)
        print("\r\nRasp_Pi => Video Converted! \r\n")
        # Update the video list after recording a new video.
        self.get_existing_videos()
    def upload(self):
        # Get the entered YouTube video parameters (title, description, e.g.,).
        title = u_title_input.value
        description = u_description_input.value
        keywords = u_keywords_input.value
        category = u_category_input.value
        privacy = u_privacy_input.value
        selected_video = u_select_input.value
        # Print the given uploading settings (parameters).
        print("\r\nYouTube Uploading Settings:\r\nTitle => " + title + "Description => " + description + "Keywords => " + keywords + "Category => " + category + "\r\nPrivacy Status => " + privacy + "\r\nSelected Video => " + selected_video)
        # Upload video to the registered YouTube account by transferring uploading settings to the upload_video.py file.
        command = (
           'sudo python /home/pi/YouTube-Recorder-and-Uploader/upload_video.py --file="'+ selected_video
         + '" --title="' + title[:-1]
         + '" --description="' + description[:-1]
         + '" --keywords="' + keywords[:-1]
         + '" --category="' + category
         + '" --privacyStatus="' + privacy + '"'
        )
        print("\r\nTerminal Command => " + command + "\r\n")
        call([command], shell=True)
        print("\r\nRasp_Pi => Attempted to upload the selected video via Google Client API! \r\n")
    def play(self):
        # Play the selected video using omxplayer.
        print("\r\nRasp_Pi => Selected Video Played on the omxplayer! \r\n")
        selected_video = u_select_input.value
        omxplayer = Popen(['omxplayer',selected_video])
      
        
# Define a new class object named as 'video'.
video = YouTube_Recorder_Uploader(800, 600, 15)
        
# Create the YouTube Video Recorder and Uploader GUI:
appWidth = 1024
appHeight = 600
app = App(title="YouTube Video Recorder and Uploader", bg="#1F2020", width=appWidth, height=appHeight)
# Define menu bar options.
menubar = MenuBar(app, toplevel=["Files", "About"],
                  options=[
                      [ ["Open In Folder", video.open_folder] ],
                      [ ["Tutorial", video.tutorial], ["Information", video.about] ]
                  ])
# Design the application interface.
app_header = Box(app, width="fill", height=50, align="top")
app_header_text = Text(app_header, text="YouTube Video Recorder and Uploader", color="white", size=20)
app_record = Box(app, width="fill", height="fill", layout="grid", align="left")
app_upload = Box(app, width="fill", height="fill", layout="grid", align="right")
app_upload.bg = "#A5282C"
# Create the record menu to be able to change the video settings.
r_name_label = Text(app_record, text="Filename : ", color="#A5282C", size=15, grid=[0,0], align="left")
r_name_input = TextBox(app_record, width=40, grid=[1,0], height=2, multiline=True)
r_name_input.bg = "#A5282C"
r_name_input.text_color = "white"
r_annotate_label = Text(app_record, text="Annotate : ", color="#A5282C", size=15, grid=[0,1], align="left")
r_annotate_input = TextBox(app_record, width=40, grid=[1,1], height=2, multiline=True)
r_annotate_input.bg = "#A5282C"
r_annotate_input.text_color = "white"
r_effect_label = Text(app_record, text="Image Effect : ", color="#A5282C", size=15, grid=[0,2], align="left")
r_effect_input = Combo(app_record, grid=[1,2], align="right", options=["none", "negative", "solarize", "sketch", "pastel", "watercolor", "film", "blur", "saturation", "posterise", "cartoon", "colorpoint", "colorbalance"], selected="none")
r_effect_input.bg = "#A5282C"
r_effect_input.text_color = "white"
r_effect_input.text_size = 20
r_duration_label = Text(app_record, text="Duration : ", color="#A5282C", size=15, grid=[0,3], align="left")
r_duration_input = Slider(app_record, end=250, grid=[1,3], align="right")
r_duration_input.bg = "#A5282C"
r_duration_input.text_color = "white"
r_duration_input.text_size = 20
r_submit = PushButton(app_record, text="Record", width=10, grid=[0,4], command=video.record, padx=15, pady=15)
r_submit.bg = "#A5282C"
r_submit.text_color = "white"
r_submit.text_size = 25
# Create the upload menu to be able to upload the selected video with the given parameters to YouTube.
u_title_label = Text(app_upload, text="Title : ", color="#F3D060", size=15, grid=[0,0], align="left")
u_title_input = TextBox(app_upload, grid=[1,0], width=35, height=2, multiline=True)
u_title_input.bg = "#F3D060"
u_title_input.text_color = "white"
u_description_label = Text(app_upload, text="Description : ", color="#F3D060", size=15, grid=[0,1], align="left")
u_description_input = TextBox(app_upload, grid=[1,1], width=35, height=2, multiline=True)
u_description_input.bg = "#F3D060"
u_description_input.text_color = "white"
u_keywords_label = Text(app_upload, text="Keywords : ", color="#F3D060", size=15, grid=[0,2], align="left")
u_keywords_input = TextBox(app_upload, grid=[1,2], width=35, height=2, multiline=True)
u_keywords_input.bg = "#F3D060"
u_keywords_input.text_color = "white"
u_category_label = Text(app_upload, text="Category : ", color="#F3D060", size=15, grid=[0,3], align="left")
# You can find more information regarding the YouTube category numbers on the project page.
u_category_input = Combo(app_upload, grid=[1,3], align="right", options=["22", "1", "10", "20", "21", "23", "24", "25", "26", "27", "28", "30"], selected="22")
u_category_input.bg = "#F3D060"
u_category_input.text_color = "white"
u_category_input.text_size = 20
u_privacy_label = Text(app_upload, text="Privacy Status : ", color="#F3D060", size=15, grid=[0,4], align="left")
u_privacy_input = ButtonGroup(app_upload, grid=[1,4], horizontal=True, align="right", options=["public", "private", "unlisted"], selected="private")
u_privacy_input.bg = "#F3D060"
u_privacy_input.text_color = "white"
u_privacy_input.text_size = 12
u_select_label = Text(app_upload, text="Select a Video : ", color="#F3D060", size=15, grid=[0,5], align="left")
# Get the paths of the recorded videos in the Recorded folder.
u_select_input = ListBox(app_upload, grid=[1,5], align="right", width=200, height=150, command=video.show_selected_video, items=["none"], scrollbar=True)
video.get_existing_videos()
u_select_input.bg = "#F3D060"
u_select_input.text_color = "white"
u_select_input.text_size = 15
u_p_submit = PushButton(app_upload, text="Play", grid=[0,6], align="left", command=video.play, padx=30, pady=10)
u_p_submit.bg = "#F3D060"
u_p_submit.text_color = "white"
u_p_submit.text_size = 25
u_u_submit = PushButton(app_upload, text="Upload", grid=[0,7], align="left", command=video.upload, padx=15, pady=10)
u_u_submit.bg = "#F3D060"
u_u_submit.text_color = "white"
u_u_submit.text_size = 25
# Initiate the application loop.
app.display()


upload_video.py

Download



#!/usr/bin/python

import httplib
import httplib2
import os
import random
import sys
import time

from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow


# Explicitly tell the underlying HTTP transport library not to retry, since
# we are handling retry logic ourselves.
httplib2.RETRIES = 1

# Maximum number of times to retry before giving up.
MAX_RETRIES = 10

# Always retry when these exceptions are raised.
RETRIABLE_EXCEPTIONS = (httplib2.HttpLib2Error, IOError, httplib.NotConnected,
  httplib.IncompleteRead, httplib.ImproperConnectionState,
  httplib.CannotSendRequest, httplib.CannotSendHeader,
  httplib.ResponseNotReady, httplib.BadStatusLine)

# 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.developers.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 = "/home/pi/YouTube-Recorder-and-Uploader/client_secrets.json"

# This OAuth 2.0 access scope allows an application to upload files to the
# authenticated user's YouTube channel, but doesn't allow other types of access.
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube.upload"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

# This variable defines a 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 will need to populate the client_secrets.json file
found at:

   %s

with information from the API Console
https://console.developers.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
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                   CLIENT_SECRETS_FILE))

VALID_PRIVACY_STATUSES = ("public", "private", "unlisted")


def get_authenticated_service(args):
  flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE,
    scope=YOUTUBE_UPLOAD_SCOPE,
    message=MISSING_CLIENT_SECRETS_MESSAGE)

  storage = Storage("%s-oauth2.json" % sys.argv[0])
  credentials = storage.get()

  if credentials is None or credentials.invalid:
    credentials = run_flow(flow, storage, args)

  return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
    http=credentials.authorize(httplib2.Http()))

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

  body=dict(
    snippet=dict(
      title=options.title,
      description=options.description,
      tags=tags,
      categoryId=options.category
    ),
    status=dict(
      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,
    # 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)

# This method implements an exponential backoff strategy to resume a
# failed upload.
def resumable_upload(insert_request):
  response = None
  error = None
  retry = 0
  while response is None:
    try:
      print "Uploading file..."
      status, response = insert_request.next_chunk()
      if response is not None:
        if 'id' in response:
          print "Video id '%s' was successfully uploaded." % response['id']
        else:
          exit("The upload failed with an unexpected response: %s" % response)
    except HttpError, e:
      if e.resp.status in RETRIABLE_STATUS_CODES:
        error = "A retriable HTTP error %d occurred:\n%s" % (e.resp.status,
                                                             e.content)
      else:
        raise
    except RETRIABLE_EXCEPTIONS, e:
      error = "A retriable error occurred: %s" % e

    if error is not None:
      print error
      retry += 1
      if retry > MAX_RETRIES:
        exit("No longer attempting to retry.")

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

if __name__ == '__main__':
  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, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)


client_secrets.json

Download



{
  "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"
  }
}


Schematics

project-image
Schematic - 42.1

Downloads

YouTube Video Recorder and Uploader GUI (Zipped)

Download