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

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 

このブログの人気の投稿

RSSからYoutube/Podcast配信

皆さん、情報収集はどの様にされていますでしょうか? 私は最先端に情報に触れる為、海外ニュースをRSSで購読しているのですが、私の英語力/語彙力では時間が掛かかってしょうがない。 また、できれば目で読むのではなく、音声で聞き流しながら通勤や他の作業中に行いたい。 という事で自動でニュースを収集・要約・翻訳し、それをブログ・ポッドキャスト・Youtubeに自動投稿するPythonプログラムを作成して時短化しました。 その手法を公開してますので参考にしてください。 Bloggerの立ち上げ方 GCPとBloggerの連携 情報収集自動化 Blogger自動投稿 本文要約 翻訳 音声作成 動画作成 Youtubeにアップロード Youtubeの投稿制限の回避方法 Podcast配信 翻訳・要約の改善(GPT-3) 以下のURLで上記から作成したブログやYoutubeを公開しています。参考までに見てください。 ブログ:海外ニュースを仕入れてお届け YouTube:海外Newsを仕入れてお届け Amazon Music:海外ニュースを仕入れてお届け。 Google Podcasts:海外ニュースを仕入れてお届け。 Apple Podcasts:海外ニュースを仕入れてお届け。

本文要約

要約 今回は現在使用している方法とは異なり、実装が簡単な要約方法になります。 参考元にはニューラルネットワーク(accel-brain-base)を使用した例などもありますので、そちらを参考にしてください。 Pythonライブラリの追加 以下のライブラリをインストールしてください。 $ pip install pysummarization Pythonプログラム test.pyに以下のコードを記述します。 ここでソース記事の各行を重みづけしてから、重要度の高い5つの行だけを選択します。 test.py from pysummarization.nlpbase.auto_abstractor import AutoAbstractor from pysummarization.tokenizabledoc.simple_tokenizer import SimpleTokenizer from pysummarization.abstractabledoc.top_n_rank_abstractor import TopNRankAbstractor def getSummary ( text ): # Object of automatic summarization. auto_abstractor = AutoAbstractor () # Set tokenizer. auto_abstractor . tokenizable_doc = SimpleTokenizer () # Set delimiter for making a list of sentence. auto_abstractor . delimiter_list = [ ". " , ". \n " , " \n " ] # Object of abstracting and filtering document. abstractable_doc = TopNRankAbstractor () # Summarize document. result_dict = auto_abstrac

Bloggerの立ち上げ

Bloggerとは BloggerはGoogleのサービスの一つで、無料でブログを始めることができます。 Googleアカウントが必要となりますので、ない方はアカウントの作成をお願いします。 Bloggerサイトへのログイン https://www.blogger.com/から「ブログの作成」を選択してください。 Googleアカウントを聞かれるので、Googleアカウントとパスワードを入力してください。 ブログの名前を入力 作成するブログの名前を決めます。これは後から変えられるのでとりあえずは書こうとしてる内容に沿ったものを記入してください。 ブログのURL(インターネット上の所在地)を作成します。 こちらも変更できる(※)のですがので、頻繁に変更すると読者や検索などから外されてしますので、個人名や法人名など変更しないことを前提に名付けた方が良いと思います。 (※「.blogspot.com」以外のカスタムドメインを自分でとって、それを設定することもできます) プロファイルの作成 ブログが作成されるとプロファイルの作成画面が出てきます。ブログ読者に見られることを意識して、ユーザー名やわかりやすい説明を記入しましょう。 以上でブログが作成できました。作成したURLをブラウザに打ち込んでみましょう! 貴方だけのブログサイトが立ち上がりました。 次は GCP(Google Cloud Platform)とBloggerを連携 させてみましょう。 参考: Blogger Help