スキップしてメイン コンテンツに移動

RSSからYoutube/Podcast配信

Youtubeへの自動投稿

YouTube Data API

YouTube Data APIを使って動画ファイルをアップロードします。
この作業にはGCPとBloggerの連携の手続きが先に必要です。

ライブラリの追加

$ pip install google-api-python-client
$ pip install google-auth-httplib2
$ pip install google-auth-oauthlib

Pythonプログラム
test.pyに以下のコードを記述します。
公式のサンプルを一部変更して持ってきています。

test.py
MAX_RETRIES = 10
RETRIABLE_STATUS_CODES = [500, 502, 503, 504]

def resumable_upload(insert_request):
    response = None
    error = None
    retry = 0
    id = None
    while response is None:
        try:
            #print ("Uploading file...")
            status, response = insert_request.next_chunk()
            if response is not None:
                if 'id' in response:
                    id = response['id']
                    #print ("Video id '%s' was successfully uploaded." % 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)
            else:
                raise
        except RETRIABLE_EXCEPTIONS as 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)

    return id

def youtube_upload(title ,description, tags):
    youtube = get_authenticated_service(YOUTUBE_API_SERVICE_NAME,YOUTUBE_API_VERSION)
    body=dict(
      snippet=dict(
        title=title,
        description=description,
        tags=tags,
        categoryId=22
      ),
      status=dict(
        privacyStatus='public'
      )
    )
    vid = None
    try:

        # 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('/tmp/output.mp4', chunksize=-1, resumable=True)
        )

        vid = resumable_upload(insert_request)

    except Exception as e:
        print (e)
        vid = None

    return vid

以前のgetRss()から上記のyoutube_upload()を呼び出します。

test.py
def getRss():
    with open('/tmp/temp.mp3' ,mode='wb+') as f:
        f.truncate(0) 
    rssUrl = 'https://news.google.com/news/rss/headlines/section/topic/TECHNOLOGY'
    rssLang = '?hl=en-US&gl=US&ceid=US:en'
    feed = feedparser.parse(rssUrl + rssLang)
    for entry in feed.entries:
            link = entry.get('link')
            getBody(link)
    makeVideo()
    youtube_upload('この動画のタイトル','この記事の説明',['この動画のタグ']) 

音声ファイルが追加されていくので、連続で動作させていくとサイズが大きくなっていきます。適宜音声ファイルを0にtruncateしています。

ともかくこれで動画の自動アップロードまでできました!
RSSを自分のお気に入りに変更すると
YouTubeで自分だけのニュースが聞けます!
今までのスマホ片手に見ていたニュースを、聞き流ししましょう!
私のニュースを公開しているのでよかったら見てください。

https://www.youtube.com/channel/UCHlLpnqvCqyX82Vlsd0MaxA
注意 :投稿制限がある様で上限に達するとパブリックでアップロードした動画がロックされる様です。
   不完全ですが投稿制限の回避方法を参考にしてください。

参考URL:

https://developers.google.com/youtube/v3/guides/uploading_a_video?hl=ja 

このブログの人気の投稿

PodCastでの音声配信

PodCastでの音声配信 Fire Base Hostingを使用してのPodCast配信 静的コンテンツ配信にFire Base Hostingが使えそうなので、ここからRSSフィードとmp3音声ファイルを配信します。 以前のBlogger連携と同様にFirebaseのAPIも管理できるように変更してください。 Fire Base Hostingの設定 Fire Baseコンソールにアクセスしてプロジェクトを作成します。 またプロジェクト内に入り「+アプリを追加」をクリックして、次に(</>)をクリックしてWebアプリケーションの設定ワークフローを起動します。 FireBaseHostingを有効にして、指示された通りにnpmを実行していくと、プロジェクトとアプリが作成されます。 作成が終わると表示されるプロジェクトの設定画面にあるプロジェクト-IDをプログラムの中で使うので覚えていてください。 また[プロジェクトの設定] > [サービス アカウント] を開きます。 [新しい秘密鍵の生成] をクリックし、[キーを生成] をクリックして確定します。 キーを含む JSON ファイルを「firebase.json」ファイルとして保管します。 ライブラリの追加 $ pip install firebase_admin Pythonプログラム test.pyに以下のコードを記述します。 公式のサンプルを一部変更して持ってきています。 test.py FIREBASE_SECRETS_FILE = "./firebase.json" FIREBASE_HOSTING_URL = "https://firebasehosting.googleapis.com/v1beta1" FIREBASE_HOSTING_SITE = FIREBASE_HOSTING_URL + "/sites/project-id" def fb_getToken (): cred = credentials . Certificate ( FIREBASE_SECRETS_FILE ) token = cred . get_access_token () r...