見出し画像

[Python]音声認識で自動ツイートしてみる

1.音声を文字に変換する

ふと思いました。Twitterでわざわざ打鍵してつぶやくのが面倒だなと。
そもそも、つぶ(呟)やくって漢字に口偏があるのに、矛盾しているじゃないか。本当の意味でTwitterでつぶやきたいと思い、今回は音声認識による自動ツイートプログラムを作成したいと思います。
 音声認識にはSpeechRecognitionという外部ライブラリを使用します。自動ツイートに関しては以前投稿した記事を参照ください。このライブラリを利用するのにMacで少し詰まりましたが、以下のコマンドの手順で解決できました。

brew install portaudio
brew link portaudio
pip install pyaudio
pip install SpeechRecognition

2.音声をテキストに変換するモジュール

今回は日本語の音声をテキストに変換するモジュールを作成します。以下がコードになります。モジュール名はvoice_to_text.pyとしました

import speech_recognition as sr
from sys import exit

def ja_voice_to_text():
    r = sr.Recognizer()
    #マイクの名称
    mic = sr.Microphone().list_microphone_names()
    print("マイク名称:{0}".format(mic[2]))

    with sr.Microphone() as source:
        #周囲の騒音対策
        r.adjust_for_ambient_noise(source)
        print("何か喋ってみてください")
        audio = r.listen(source)
        try:
            #音声認識にグーグルのサービスを利用
            text = r.recognize_google(audio, language="ja-JP")
            return text
        except:
            print("認識できませんでした。")
            exit()
            
if __name__ == "__main__":
    result = ja_voice_to_text()
    print(result)

3.完成形

自動ツイート機能と組み合わせます。

from selenium import webdriver
from time import sleep
from voice_to_text import ja_voice_to_text

DRIVER_PATH = "/Users/nobita/Desktop/Selenium/chromedriver"
URL = "http://twitter.com/login"

user_id = "各々のid"
password = "各々のパスワード"
content = ja_voice_to_text()

#つぶやく内容
tweet_content = "{0}".format(content)

driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.get(URL)

#ユーザーid入力フォーム要素の取得
user_box = driver.find_element_by_class_name('js-username-field')
#取得した要素へidを入力
user_box.send_keys(user_id)
sleep(1)
#パスワード入力フォーム要素の取得
password_box = driver.find_element_by_class_name('js-password-field')
#取得した要素へキー入力
password_box.send_keys(password)
sleep(1)
#ログインボタン様子の取得
login_btn = driver.find_element_by_css_selector('button.submit.EdgeButton.EdgeButton--primary.EdgeButtom--medium')
#ログインボタンを押下
login_btn.click()
sleep(1)

#ツイートフォームの取得
tweet_box = driver.find_element_by_id('tweet-box-home-timeline')
tweet_box.send_keys(tweet_content)
sleep(1)

#ツイートする
tweet_button = driver.find_element_by_css_selector('button.tweet-action.EdgeButton.EdgeButton--primary.js-tweet-btn')
tweet_button.click()

4.実行結果

発した言葉は「音声認識による自動ツイートです。」
gifでは容量が足りなかったため、こちらに結果を添付しました。
認識結果はご覧の通りです。滑舌を鍛えようと思います。




この記事が気に入ったらサポートをしてみませんか?