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

RSSからYoutube/Podcast配信

Blogger自動投稿

GCP連携を使って自動投稿

Blogger APIを使用することでプログラムからBloggerへ投稿できるようになります。
この作業にはGCPとBloggerの連携の手続きが先に必要です。

Pythonライブラリの追加

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

Pythonプログラム
RSSのタイトルと内容をBloggerへ記事をポストするプログラムを作成します。
test.py
# coding: utf-8
import feedparser
import requests
import os
import pickle
from extractcontent3 import ExtractContent
from apiclient.discovery import build
from apiclient.errors import HttpError
from apiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

extractor = ExtractContent()
# オプション値を指定する
opt = {"threshold":50}
extractor.set_option(opt)

TOKEN_PICKLE = 'token.pickle'
CLIENT_SECRETS_FILE = "client_secret.json"

TRANS_REQUEST_SCOPE = "https://www.googleapis.com/auth/cloud-translation"
TRANS_API_SERVICE_NAME = "translate"
TRANS_API_VERSION = "v3"
TTS_REQUEST_SCOPE = "https://www.googleapis.com/auth/cloud-platform"
TTS_API_SERVICE_NAME = "texttospeech"
TTS_API_VERSION = "v1"
BLOGGER_UPLOAD_SCOPE = "https://www.googleapis.com/auth/blogger"
BLOGGER_API_SERVICE_NAME = "blogger"
BLOGGER_API_VERSION = "v3"
YOUTUBE_UPLOAD_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

def get_authenticated_service(api,version):
    scope = [BLOGGER_UPLOAD_SCOPE,YOUTUBE_UPLOAD_SCOPE,TTS_REQUEST_SCOPE,TRANS_REQUEST_SCOPE]
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(TOKEN_PICKLE):
        #print ('exists')
        with open(TOKEN_PICKLE, 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRETS_FILE, scope)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(TOKEN_PICKLE, 'wb') as token:
            pickle.dump(creds, token)

    try:
        # simulate calling a method that's not defined
        auth = build(api, version, credentials=creds)
    except Exception as e:
        print(e)
        return None

    return auth

def postBlog(title ,description, tag ):
    blogger = get_authenticated_service(BLOGGER_API_SERVICE_NAME,BLOGGER_API_VERSION)
    blog_id = "your blog id"
    jsondata = {
    "kind": "blogger#post",
    "blog": {
        "id": blog_id,
    },
    "title": title,
    "content": description,
    "labels" : [tag],
    }

    try:
        # simulate calling a method that's not defined
        posts = blogger.posts()
        insert = posts.insert(blogId=blog_id, isDraft=False, body=jsondata)
        posts_doc = insert.execute()
    except Exception as e:
        print(e)
        return None
    return posts_doc["url"]
"your blog id"  は作成したBloggerのURL( https://www.blogger.com/blog/posts/XXXXXXX?hl=ja&tab=jj )のXXXXXXXの部分になります。
以前のgetBody()から上記のpostBlog()を呼び出します。
test.py
def getBody(link):
    try :
        res = requests.get(link)
        extractor.analyse(res.text)
        text, title = extractor.as_text()
        postBlog(title,text,'TECHNOLOGY')
    except Exception as e :
        print(e)
上記プログラムを実行すると表示される以下の様なURLをコピーしてブラウザで表示してください。
※OSや設定によっては自動的にブラウザが開きます。
$ python3 test.py 

Please visit this URL to authorize this application: https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=xxxxxxxxxx-uik2iaamo4jl5fjugidabsv7iqb6c0n6.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A60533%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fblogger+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-platform+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcloud-translation&state=XXXXXXXXXXXXXXXXXXX&access_type=offline 
以下の画面から「(安全ではないページ)に移動」をクリックしてください。


付与するAPIを選択してアクセス権限を付与します。


これでGoogleのAPIが使用できますので無事動作が正常すればBloggerにブログが投稿されているはずです。

このブログの人気の投稿

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