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

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 

このブログの人気の投稿

StableDiffusionを使った画像生成&動画生成

  StableDiffusionが世を賑わかせているので、便乗してニュースのテキストから画像を生成し、TTSの音声と併せて動画にしてみた。 まずは画像生成用のモジュールから。 ! pip install accelerate diffusers transformers scipy ftfy # make sure you're logged in with `huggingface-cli login` from  torch  import  autocast from  diffusers  import  StableDiffusionPipeline import  gc SDpipe = StableDiffusionPipeline.from_pretrained (      "stabilityai/stable-diffusion-2" ,     use_auth_token= "enter your token" ) .to ( "cuda" ) def   getImgFromPrompt ( prompt , imgName ) :     gc.collect ( generation= 0 )     gc.collect ( generation= 1 )     gc.collect ( generation= 2 )     image = SDpipe ( prompt , height= 512 ,  width= 512 ) .images [ 0 ]     display ( image )     image.save ( im...

GPT-3を使った翻訳・要約

GPT-3とは 「Generative Pre-trained Transformer - 3」の略で、イーロン・マスクなどが出資しているOpenAIという団体が出している自然言語処理モデルになります。 以前までは予約しないと使えないものでしたが、今はアカウントを作成すれば誰でも使用することができるようになったので、この翻訳・要約機能を試してみました。 OpenAIのアカウントを作成 Googleアカウントでログインできるため、Googleアカウントを持っている方ならそのまま「Continue with Google」で入ってください。 このままPlaygroundで遊んでも良いですが、Pythonプログラムに使用するため、以下のURLから「Create New Secret Key」を押してAPI-Keyを作成しておいてください。 https://beta.openai.com/account/api-keys Pythonライブラリ openaiのライブラリやこれまでのRSSリーダー機能に必要なライブラリもインストールします。 $ pip install openai feedparser extractcontent3 Pythonプログラム RSSからURLを取得してHTML本文を取得する箇所に関しては以前のものを使いまわします。要約・翻訳のサンプルはPlaygroundから見れますがこれを少し手を加えつつ、パラメータをチューニングしておきました。 # coding: utf-8 import  os import  openai import  requests import  feedparser from  extractcontent3  import  ExtractContent openai.api_key =  "YourOpenAI-API-Key" extractor = ExtractContent () # オプション値を指定する opt =  { "threshold" : 50 } extractor.set_option ( opt )   ...