gmail読み上げ (タイトル取得まで)

gmail読み上げ (タイトル取得まで)

ダウンロードしたファイルをコピーしてリネームする
詳細は
https://developers.google.com/gmail/api/quickstart/python?hl=ja
にあるが
とりあえず
credentials.json
にしておく

cd Downloads
cp client_secret_336287491272-faqvqnb4hjrg4ragurjh8nfhn2s3ujkg.apps.googleusercontent.com.json credentials.json

のあと作業ディレクトリ作成

mkdir -p mail_auto

ここへ認証ファイルの credentials.json をコピーする

あとはライブラリのインストール

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

次に
quickstart.py
を作成し
コピペして動作確認

from __future__ import print_function

import os.path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']


def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.json 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.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # 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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        # Call the Gmail API
        service = build('gmail', 'v1', credentials=creds)
        results = service.users().labels().list(userId='me').execute()
        labels = results.get('labels', [])

        if not labels:
            print('No labels found.')
            return
        print('Labels:')
        for label in labels:
            print(label['name'])

    except HttpError as error:
        # TODO(developer) - Handle errors from gmail API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

保存したら

python3 quickstart.py

で実行

この時に認証画面が出るが
セキュリティの危険があるような警告が出る
これはサーバーのオレオレ証明書の時のようなものなので
気にせず続ける

認証が終わると
メールのラベル一覧が表示される

Mac で音声認識 pyttsx3

Mac で音声認識

Python で音声認識をする

Pythonで日本語を音声認識をして音声をテキスト化し、それを音声合成して発音する方法簡単解説【オウム返し by Mac その1:音声認識編】
を参考に

pip install speechrecognition

でインストール

import subprocess
import tempfile
 
 
# 音声入力
while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("何かお話しして下さい。")
        audio = r.listen(source)
 
    try:
        # Google Web Speech APIで音声認識
        text = r.recognize_google(audio, language="ja-JP")
    except sr.UnknownValueError:
        print("Google Web Speech APIは音声を認識できませんでした。")
    except sr.RequestError as e:
        print("GoogleWeb Speech APIに音声認識を要求できませんでした;"
              " {0}".format(e))
    else:
        print(text)
    if text == "終わりだよ":
        break
print("完了。")

Mic,py

として実行したけど

Traceback (most recent call last):
  File "/Users/snowpool/mic.py", line 7, in <module>
    r = sr.Recognizer()
NameError: name 'sr' is not defined. Did you mean: 'str'?

となる

pip install Pyaudio

を実行したが

Building wheel for Pyaudio (pyproject.toml) ... error
  error: subprocess-exited-with-error
  
  × Building wheel for Pyaudio (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [18 lines of output]
      running bdist_wheel
      running build
      running build_py
      creating build
      creating build/lib.macosx-12.5-arm64-cpython-310
      creating build/lib.macosx-12.5-arm64-cpython-310/pyaudio
      copying src/pyaudio/__init__.py -> build/lib.macosx-12.5-arm64-cpython-310/pyaudio
      running build_ext
      building 'pyaudio._portaudio' extension
      creating build/temp.macosx-12.5-arm64-cpython-310
      creating build/temp.macosx-12.5-arm64-cpython-310/src
      creating build/temp.macosx-12.5-arm64-cpython-310/src/pyaudio
      clang -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include -DMACOS=1 -I/usr/local/include -I/usr/include -I/opt/homebrew/include -I/Users/snowpool/.pyenv/versions/3.10.6/include/python3.10 -c src/pyaudio/device_api.c -o build/temp.macosx-12.5-arm64-cpython-310/src/pyaudio/device_api.o
      src/pyaudio/device_api.c:9:10: fatal error: 'portaudio.h' file not found
      #include "portaudio.h"
               ^~~~~~~~~~~~~
      1 error generated.
      error: command '/usr/bin/clang' failed with exit code 1
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for Pyaudio
Failed to build Pyaudio
ERROR: Could not build wheels for Pyaudio, which is required to install pyproject.toml-based projects

となる

PythonのSpeechRecognitionでマイク録音と文字起こしを簡単実装
を参考に

brew install portaudio

のあと

pip install PyAudio

でインストール成功

しかし

pip install speech_recognition

を実行すると

ERROR: Could not find a version that satisfies the requirement speech_recognition (from versions: none)
ERROR: No matching distribution found for speech_recognition

となる

とりあえず

Mkdir test_cpt
Cd test_gpt
Vim mic.py

として

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as input:
    print("録音中:")
    audio = r.listen(input)

で保存し

Python mic.py

を実行すれば
録音中
と表示された

あとは

text = r.recognize_google(audio, language='ja-JP')

として
録音したデータをrecognize_google関数の引数に与えるだけ
第二引数のlanguageを変えれば英語とか他の言語として文字起こしできるらしい

入れる場所がいまいちわからんので
音声入力で文章作成するアプリの作り方【Python】

を参考にやってみる

Python】音声認識ライブラリのSpeechRecognitionでサクッと文字起こし
を参考に

もう少しやりやすく実際にマイクの認識と文字列かだけにしたいので

# micro.py

import speech_recognition as sr

for index, name in enumerate(sr.Microphone.list_microphone_names()):
    print("Microphone with name \"{1}\" found for `Microphone(device_index={0})`".format(index, name))

の実行結果は

Microphone with name "MacBook Airのマイク" found for `Microphone(device_index=0)`
Microphone with name "MacBook Airのスピーカー" found for `Microphone(device_index=1)`

これをもとに

# voice_test.py

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone(device_index=0) as source:
    print('録音中: ')
    audio = r.listen(source)

try:
    text = r.recognize_google(audio, language='ja-JP')
    print(text)
except:
    print("録音されていません")

を実行

しかし
録音されていません
となる

# voice_test.py

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone(device_index=0) as source:
    print('録音中: ')
    audio = r.listen(source)

try:
    text = r.recognize_google(audio, language='ja-JP')
    print(text)

    # 録音された音声をファイルへ保存
    with open("record.wav", "wb") as f:
        f.write(audio.get_raw_data())
except:
    print("録音されていません")

でテキストにできるらしいけど
そもそもマイクを認識していない?

参考サイトはwin10
Mac での動いているのを探す

Pythonで日本語を音声認識をして音声をテキスト化し、それを音声合成して発音する方法簡単解説【オウム返し by Mac その1:音声認識編】
を参考に

import speech_recognition as sr
import subprocess
import tempfile
 
 
# 音声入力
while True:
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("何かお話しして下さい。")
        audio = r.listen(source)
 
    try:
        # Google Web Speech APIで音声認識
        text = r.recognize_google(audio, language="ja-JP")
    except sr.UnknownValueError:
        print("Google Web Speech APIは音声を認識できませんでした。")
    except sr.RequestError as e:
        print("GoogleWeb Speech APIに音声認識を要求できませんでした;"
              " {0}".format(e))
    else:
        print(text)
    if text == "終わりだよ":
        break
print("完了。")

を実行したけど

Traceback (most recent call last):
  File "/Users/snowpool/test_gpt/voice_text.py", line 15, in <module>
    text = r.recognize_google(audio, language="ja-JP")
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/speech_recognition/__init__.py", line 879, in recognize_google
    flac_data = audio_data.get_flac_data(
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/speech_recognition/__init__.py", line 495, in get_flac_data
    flac_converter = get_flac_converter()
  File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/speech_recognition/__init__.py", line 1744, in get_flac_converter
    raise OSError("FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent")
OSError: FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent

となる

OSError: FLAC conversion utility not available - consider installing the FLAC command line application by running `apt-get install flac` or your operating system's equivalent

で検索したら

音声データをテキスト変換 / Speech to Text / Python
によれば
Flac が必要らしい

https://xiph.org/flac/download.html
で調べて

FLAC tools for OS X from Homebrew.
で検索
https://formulae.brew.sh/formula/flac

brew install flac

でインストール

import speech_recognition as sr

r = sr.Recognizer()
with sr.Microphone() as input:
    print("録音中:")
    audio = r.listen(input)
text = r.recognize_google(audio, language='ja-JP')
print(text)

として保存

これで再度実行すると

result2:
{   'alternative': [   {'confidence': 0.77176797, 'transcript': 'チャート GPT'},
                       {'transcript': 'チャート jpg'},
                       {'transcript': 'チャート jpt'},
                       {'transcript': 'チャート gpd'},
                       {'transcript': 'じゃあ と jpg'}],
    'final': True}
チャート GPT

となり
音声の認識とテキストにすることができた

次に

import speech_recognition as sr

r = sr.Recognizer()

with sr.Microphone(device_index=0) as source:
    print('録音中: ')
    audio = r.listen(source)

try:
    text = r.recognize_google(audio, language='ja-JP')
    print(text)

    # 録音された音声をファイルへ保存
    with open("record.wav", "wb") as f:
        f.write(audio.get_raw_data())
except:
    print("録音されていません")
を
voice_rec.py

として実行

これでマイクの音声のファイル化ができた

https://dev.classmethod.jp/articles/pyenv-command-not-found/
を参考に

brew unlink pyenv && brew link pyenv

したけど
Notebook が起動しない….

JupyterLabとJupyter Notebookの違いを簡単に解説【Mac】

https://miyukimedaka.com/2020/06/07/0143-jupyterlab-explanation/
を参考に

pip install jupyterlab


インストール

 jupyter lab

で起動

!pip install pyttsx3
import pyttsx3

engine = pyttsx3.init()
engine.say("音声読み上げライブラリ")
engine.runAndWait()

を実行したら日本語の読み上げができた

経済指標の値の取得と計算

経済指標の値の取得と計算

とりあえず経済指標の基準値は調べたので

まずは売買するロジックを作成する

経済指標で結果が予測値より悪いなら売り

結果が予想より良いのなら書い

という簡単なロジックを実装する

def dealing_logic(forecast,actual_news):

    deal_flag = actual_news - forecast

    if deal_flag <0:

        print("売り")

    else:

        print("書い")

まずは簡単に実験

forecast = 962

actual = 853

dealing_logic(forecast,actual)

で売りになったので

次は
マイナスの値で
マイナスの値でも動作するのを確認

次に判定
フラグ変数を用意し

経済指標
債権
株価指数
Vix
といった値で売買判定をする

Vix は警戒とかはマイナスの値を多くすることにする

つまり

Vix は0〜100で
20までは安定しているとみるので

値を0
30で警戒なので-1
40を超えたらパニックなので-2
50 以上はリーマンショッククラスなので-3
とする

このように結果をもとにして

判定するフラグのトータルが+なら書い

マイナスなら売りとする

ダウの下げとかを気にするのではなく

これらをフラグとしておけば市場の数値ではなく

売り買いのみの判定に使える

https://note.nkmk.me/python-pandas-read-excel/

をみた感じだと

read_excel()

Pandas でexcel を読み込んでいる

Vix の取得は

import investpy

from datetime import datetime, date, timedelta

from dateutil.relativedelta import relativedelta

import altair as alt

import pandas as pd



today = datetime.today().strftime('%d/%m/%Y')



vix = investpy.get_index_historical_data(index='S&P 500 VIX',country='united states',

                                        from_date='01/01/2010',to_date=today)



vix.loc["2022-06-02"]["High"]

25.78

と Hight の値を取得できた

あとは日付の部分を自動で取得したいので

index_date に格納して指定する

index_today = datetime.today().strftime('%Y-%m-%d')

vix.loc[index_today]["High"]

としても同じ

25.78

となったので成功

問題はこれが数値か文字列かによるので

if flag_vix > 50:

    print("市場はパニック")

elif flag_vix > 20:

    print("市場は正常")

で判定できているので数字になっている

同様に経済指標カレンダーの

Forecast actual previous

の値も取り出してみる

あとtwitter で取得したツイート内容の切り出し

数字以外は削除しないと比較できない

とりあえず  broomberg のツイートを取得し

不要な部分を削除し経済指標の数値のみにする

https://teratail.com/questions/266272
によれば

特定ユーザの特定キーワード検索が可能

for tweet in tweepy.Cursor(api.search, q='"2020年05月28日" from:@TakumiSoftware').items(10):

    if (tweet.text[:2] == 'RT'): continue



    print(tweet.user.name)

    print(tweet.text)

    print('-----------------------------------------------')


しかしエラーになる

api.search_tweets(q='"RBA Rate Statemen"', lang='ja', result_type='recent',count=12)

もだめ

api.search_tweets(q='"#経済指標"', lang='ja', result_type='recent',count=12)

は動作する

ツイート取得したあとはテキストから数字のみ取り出せればいいので

これを先にやる

for tweet in tweepy.Cursor(api.search_tweets, q='GDP(YoY)').items(10):

    print(tweet.text)

としたら10件取得できた

結果が

⠀#EU 1Q 2022

#GDP = 5,4% YoY (5,1% previous)

#GDP = 0,6% QoQ (0,3% previous)

Grammar check: Eurozone GDP in Q1 better than estimated, QoQ +0,6% (estimated +0,3%) vs 0,3% in Q4 2021, YoY +5,4%… https://t.co/T2QYk1MzMT

RT @PatelisAlex: Powering ahead.



Greek real GDP surges 7.0%yoy in Q1 (real, not nominal) https://t.co/pWQqFZB8bi

BNP inom EURO-området bättre än väntat.



European Gross Domestic Product (GDP) YoY 5.4% - https://t.co/R9Ra2BQVGK

Euro area GDP came in stronger than expected for Q1:

+5.4% YoY (est. 5.1%); .6% QoQ (est. .3%).



Output rose .5% Q… https://t.co/U2xUt4c083

RT @Financialjuice1: EUROZONE GDP REVISED YOY ACTUAL 5.4% (FORECAST 5.1%, PREVIOUS 5.1%) $MACRO

EUROZONE GDP REVISED YOY ACTUAL 5.4% (FORECAST 5.1%, PREVIOUS 5.1%) $MACRO


 European GDP Growth Rate YoY 3rd Est (Q1)



Actual: 5.4%


Expected: 5.1%

Previous: 4.7%



#EUR

Euro Zone Econ. Stats Released:

GDP (YoY) (Q1)

Actual:  5.4%

Expected: 5.1%

Prior: 5.1%

Better Than Expected


 GDP Growth Rate YoY 3rd Est (Q1)

Actual: 5.4%

Expected: 5.1%

Previous: 4.7%

https://t.co/p0AAzoJmBh

なので

ほぼ取得したい内容がある

あとはここから数値のみ取り出して比較できるようにすr

https://docs.tweepy.org/en/stable/client.html#tweepy.Client.search_recent_tweets
のリファレンスを見た感じだと

since_id を指定すればユーザ指定ができそう

なので bloomberg のid を調べる

34713362
がid 

あとはこれを指定してできるかどうか

screen_name だと

@business
なので

bloomberg = api.user_timeline(screen_name='@business')

# bloomberg

for tweet in bloomberg:

    print(tweet.text)

で表示できた

あとは取得したついーとから数字だけ取り出す


for tweet in tweepy.Cursor(api.search_tweets, q='"French oil and gas" from:@business').items(10):

    if (tweet.text[:2] == 'RT'): continue



    print(tweet.user.name)

    print(tweet.text)

    print('-----------------------------------------------')

としたら特定のアカウントで検索もできた

あとはここから数値の抜き取り

https://teratail.com/questions/266272

を参考に特定ユーザツイート検索ができた

marketnews = api.user_timeline(screen_name='@Financialjuice1')

# bloomberg

for tweet in marketnews:

    print(tweet.text)

で経済指標の最も早いニュースを英語で取得

marketnews =list(marketnews)

marketnews_data = []

for tweet in marketnews:

    marketnews_data.append(tweet.text)

   

print(marketnews_data[9])

で経済指標発表時のツイート取得

次にこのツイートの中身を数字だけにする

【Python】文字列から数字だけを取り出す方法

を参考に

Re.sub()

を使い

marketnews_data[3]

を数値だけにする

actual = re.sub(r"\D","",marketnews_data[3])

actual

だと

'025'

となるので

少数だけにしたい

以前、経済指標で数値以外を削除した方法を使う

分かりやすいpythonの正規表現の例

を参考に

actual = re.sub(r"[^0-9.-]","",marketnews_data[3])

actual

としたが

'.0.25.'

となる

とりあえずリストにすれば正規表現で抜き出しはできるので
あとは処理を調べる

actual = re.sub(r"[^0-9.-]|.$","",marketnews_data[3])

というように

| で条件を追加して

.$ というように末尾が. であるものを削除

ただし最初の . が消せない

また

HONG KONG CPI MOM NSA ACTUAL -0.20% (FORECAST -, PREVIOUS -0.20%) $MACRO

を削除してみると

actual2 = re.sub(r"[^0-9.-]|.$","",marketnews_data[2])

actual2

の結果は

'-0.20--0.20'

となるので

少数を条件式に組み込んだ方がいいかもしれない

"ECB'S DE GUINDOS: EURO-ZONE INFLATION TO STAY ABOVE 8% IN COMING MONTHS."

を処理すると
-8 になる

数値とマッチする正規表現

を参考に小数点と不等号を含む数値のみ抽出する正規表現にする

しかし

[+-]?(?:\d*\.)?\d+(?:(?<!(\.\d+))\.\d*)?

だとエラ〜になる

actual2 = re.sub(r"[^\d.]|.$","",marketnews_data[2])

print(actual2)

にしたら

となった

Python の正規表現で . (ドット) を含む数値のみを抽出したい

を参考にした

ただしこれだと複数の数値を1つにしてしまうので

区切る必要がある

findall()

で試したが

actual2 = re.findall(r"\d+",marketnews_data[1])

print(actual2)

とすると

['53', '1', '52', '4', '53', '1']

となって小数点で区切ってしまう

文字列から浮動小数点数を抽出する方法

を参考に

actual2 = re.findall("\d+\.\d+",marketnews_data[1])

print(actual2[0])

としたら

53.1

が抽出できた

actual2 = re.findall("[-+]?\d*\.\d+|\d+",marketnews_data[1])

print(actual2)

とすることでマイナスの数値にも対応できた

しかし文字列なので

print(actual2+1)

としたらエラ〜となった

変換すればできそうだが小数点なので
Float になる

Vix を抽出した時
flag_vix の値は少数で比較もできた

flag_vix +1

としても演算し

+1 されている

【Python】型を確認・判定する(type関数、isinstance関数)

を参考に

type(flag_vix)

でデータ型を確認したら

numpy.float64

となった

なので float へ変換してみる

[解決!Python]文字列と数値を変換するには(int/float/str/bin/oct/hex関数)

を参考に

float(actual2)

としたがエラ〜

type(actual2)

で調べたら list だった

Python でリストを Float に変換する

を参考に

リスト内のアイテムを Python で numpy.float_() 関数を使用して Float に変換する

import numpy as np
actual2_float = np.float_(actual2)

print(actual2_float+1)

とすれば計算ができるようになった

 

ラズパイ4のセットアップ

ラズパイ4のセットアップ

半導体不足のためほぼ手に入らない状態だったので
KSY でラズパイ4の教材セットのものを購入

すでにOSの書き込みはされているので
ディスプレイとキーボード、マウスなどを用意すれば
すぐに起動できる

今回は
bluetooth キーボードを使用したが
初期設定はマウスだけでもできる

パスワード入力などではキーボードが必要になる

今回は
Anker の bluetooth キーボードを使用したが
ペアリングや日本語入力で手間取った

ペアリングは
Fn + z キーの長押しで行い

日本語変換と英語の切り替えは
スペース + Control で行う

とりあえずインストールができたら端末を起動し

sudo raspi-config

を実行

Interfacing Options を Select

I2 SSH
をクリックし

はい
をクリック

これでSSHが有効になるので

ここから後は ubuntu から操作できる

なお

Warning: Permanently added '192.168.1.48' (ECDSA) to the list of known hosts.
Received disconnect from 192.168.1.48 port 22:2: Too many authentication failures
packet_write_wait: Connection to 192.168.1.48 port 22: Broken pipe

となったときには

 ssh -o IdentitiesOnly=yes pi@192.168.1.48

とすることで
接続できる

今回はUSBカメラを使用する

ロジクールLogicool C270n

次に公開鍵認証にするので
Ubuntu で ssh-keygenコマンドで作成

-t で暗号形式を rsa
-b で4096ビットに指定
なおデフォルトでは2048ビット

cd .ssh
ssh-keygen -t rsa -b 4096

で作成

Enter file in which to save the key (/home/snowpool/.ssh/id_rsa): 

となったらファイル名を入力

今回は raspi4
としておく

パスフレーズは省略するので

Enter passphrase (empty for no passphrase): 

Enter same passphrase again: 


Enter にすればパスフレーズなしとなる

次に公開鍵の登録

これは
ssh-copy-id コマンドを使う

なお接続するラズパイ4のIPは
Android ならFing で調べることが可能

 scp -o IdentitiesOnly=yes .ssh/raspi4.pub pi@192.168.1.48:/home/pi/

で作成したファイルをコピー

次に
ラズパイにログイン

cat raspi4.pub >> .ssh/authorized_keys
chmod 700 .ssh/
chmod 600 .ssh/authorized_keys 
sudo apt install vim


vim をインストール

sudo vim /etc/ssh/sshd_config

で設定ファイルを開き

パスワード認証を禁止

PermitEmptyPasswords no
PasswordAuthentication no

AuthorizedKeyFile .ssh/authorized_keys

を設定

sudo /usr/sbin/sshd -t

で設定の確認

sudo /etc/init.d/ssh restart


ssh の再起動

これで

ssh pi@192.168.1.48

でログインが可能になる

次に opencv のインストール

sudo apt update -y
sudo apt upgrade -y
sudo apt autoremove -y

でリポジトリ更新とアップデート
そして不要なパッケージの削除

次に opencv に必要なライブラリをインストール

sudo apt install -y libhdf5-103
sudo apt install -y libatlas-base-dev
sudo apt install -y libjasper-dev

しかし

sudo apt install -y libqt4-test

を実行したところ

E: パッケージ libqt4-test が見つかりません

となる

python : pip install OpenCVでRaspbianでこのエラーが発生するのはなぜですか?2021-12-27 06:48

によれば
Qt4はもうパッケージ化されていない
とのこと

このため
Linuxでdebパッケージをインストールする方法

を見ながら

wget http://ftp.de.debian.org/debian/pool/main/q/qt4-x11/libqt4-test_4.8.7+dfsg-18+deb10u1_arm64.deb
sudo dpkg -i libqt4-test_4.8.7+dfsg-18+deb10u1_arm64.deb

としたが

パッケージアーキテクチャ (arm64) がシステム (armhf) と一致しません
処理中にエラーが発生しました:

となるため

wget http://ftp.us.debian.org/debian/pool/main/q/qt4-x11/libqt4-test_4.8.7+dfsg-18+deb10u1_armhf.deb
sudo dpkg -i libqt4-test_4.8.7+dfsg-18+deb10u1_armhf.deb

としたが

dpkg: 依存関係の問題により libqt4-test:armhf の設定ができません:
 libqt4-test:armhf は以下に依存 (depends) します: libqtcore4 (= 4:4.8.7+dfsg-18+deb10u1) ...しかし:
  パッケージ libqtcore4 はまだインストールされていません。

dpkg: パッケージ libqt4-test:armhf の処理中にエラーが発生しました (--install):
 依存関係の問題 - 設定を見送ります
libc-bin (2.31-13+rpt2+rpi1+deb11u2) のトリガを処理しています ...
処理中にエラーが発生しました:
 libqt4-test:armhf

となってしまう

きにせずそのまま

sudo pip install opencv-python

としたら
インストールできた

sudo python3 -m pip install pip --upgrade


pip もアップデートしておく

次に仮想環境を構築するツール
virtualenv

virtualenvwrapper
をインストール

sudo pip3 install virtualenv

を実行すると
インストールは成功するが

WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

となる

意味は

警告:「root」ユーザーとしてpipを実行すると、権限が破損し、システムパッケージマネージャーとの動作が競合する可能性があります。代わりに仮想環境を使用することをお勧めします
とのこと

pip install virtualenvwrapper

でインストールすると

  WARNING: The script virtualenv-clone is installed in '/home/pi/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

とでてくる

これは
.bashrc へ設定追加が必要

virtualenvとvirtualenvwrapperを使う

を参考に

whichコマンドを使って、virtualenvwrapper.shの場所を探す

which virtualenvwrapper.sh

結果は

/home/pi/.local/bin/virtualenvwrapper.sh

だったので

vim .bashrc 

でファイルを開き
最終行に

if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
    export WORKON_HOME=$HOME/.virtualenvs
    source /home/pi/.local/bin/virtualenvwrapper.sh #ここはwhichコマンドの結果に変えてください。
fi

を追記

source .bashrc

で有効化

しかし
mkvirtualenv コマンドが見つからないので
再度設定を変更

Raspberry Pi で virtualenv のインストール

を参考に

追記部分の

if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
    export WORKON_HOME=$HOME/.virtualenvs
    source /home/pi/.local/bin/virtualenvwrapper.sh #ここはwhichコマンドの結果に変えてください。
fi

を削除し

代わりに

export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /home/pi/.local/bin/virtualenvwrapper.sh

を追記

source のパスは

which virtualenvwrapper.sh

のものを使用

これで

source .bashrc 

を実行すると
mkvirtualenv コマンドが使えるようになる

このコマンドの詳細については
コマンドリファレンス

を参考に

WordPress 2 段階認証プラグイン Two-Factor

WordPress 2 段階認証プラグイン Two-Factor

新規プラグインで
Two Factor
で検索

インストール後に有効化

ユーザ > あなたのプロフィール

Time Based One-Time Password (TOTP)
をクリック

QRコードを
Android アプリの
Google認証システムで読み取り
認証コードを入力する

注意点としては
スペースをいれること

これでプロフィールを更新すると
次回からログインのときに2段階認証が有効化され
ログインID、パスワードのあとに
認証アプリで表示された6つの値を入力しないとログインできないようになる

Text-to-Speech API

GCP の Text-to-Speech API を使って
テキストから音声を生成する

入力したテキストを
音声を男性か女性か選択して
生成する

音声の文字起こしなら
Speech toText
のほうになる

GCP へログインし
認証情報 > API とサービスの有効化

Cloud Text-toSpeech API
をクリック

これには無料枠があるようでhttps://cloud.google.com/text-to-speech/pricing/?hl=JA
に記載されている

1ヶ月あたり
0〜100 万文字

音声合成マークアップ言語(SSML)タグも文字数カウントに含まれる

有効化のときに課金設定があるので注意

有効化できたら
認証情報で
認証情報を作成

サービスアカウントを作成する

続行
で完了
をクリック

これでサービスアカウントが作成される

このアドレスをクリックし
キーをクリック

鍵を追加

新しい鍵を追加
でタイプをJSONにする

これでJSONファイルをダウンロードしたら
環境変数を設定する

GOOGLE_APPLICATION_CREDENTIALS
を設定する

これにパスを設定する
ダウンロードしたJSONファイルを
secret.json に名前を変えておく

ダウンロードしたファイルを新しい順にするなら

lsコマンドでファイルを新しい順番、古い順番にソートする方法

を参考に

ls -lt

で表示されるので

cp raspberryPi-b787a5abd4d5.json secret.json

でコピーし

mv secret.json ~/notebook/


jupyter notebook で扱えるようにしておく

次に
notebook でos ライブラリをインポートすることで使っていく

import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'secret.json'

でOK

次にライブラリのインストール

Text-to-Speech クライアント ライブラリ

を参考に

pip install --upgrade google-cloud-texttospeech

をいれる

notebook でやるなら

!pip install --upgrade google-cloud-texttospeech

とする

これで準備できたので
音声の再生

from google.cloud import texttospeech

client = texttospeech.TextToSpeechClient()

synthesis_input = texttospeech.SynthesisInput(text="Hello, World!")

voice = texttospeech.VoiceSelectionParams(
    language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
)

audio_config = texttospeech.AudioConfig(
    audio_encoding=texttospeech.AudioEncoding.MP3
)

response = client.synthesize_speech(
    input=synthesis_input, voice=voice, audio_config=audio_config
)

with open("output.mp3", "wb") as out:
    out.write(response.audio_content)
    print('Audio content written to file "output.mp3"')

クライアント ライブラリの使用

からコピペして
コメント部分を削除

client = texttospeech.TextToSpeechClient()

の部分で認証をしている

synthesis_input = texttospeech.SynthesisInput(text="Hello, World!")


出力する音声をセット
今回なら
Hello, World
となる

voice = texttospeech.VoiceSelectionParams(
    language_code="en-US", ssml_gender=texttospeech.SsmlVoiceGender.NEUTRAL
)

で声の設定
language_code で言語の指定
en-US なら英語

ssml_gender は性別の設定
NEUTRAL だとどっちでもないような音声になる

audio_config = texttospeech.AudioConfig(
    audio_encoding=texttospeech.AudioEncoding.MP3
)

で音声形式の指定
今回は MP3 にしている

これらのパラメータを

response = client.synthesize_speech(
    input=synthesis_input, voice=voice, audio_config=audio_config
)

でセットして音声を作成する

filename ="output.mp3"
with open(filename, "wb") as out:
    out.write(response.audio_content)
    print(f'Audio content written to file {filename}')

と最後を変えることで音声ファイル名を簡単に変更できる

wb なので
バイナリ形式で書き込み

しかし Cloud SDK がないと実行できないみたいなので
Google Cloud SDK のインストール

を参考に

echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list


Cloud SDK の配布 URI をパッケージ ソースとして追加

sudo apt-get install apt-transport-https ca-certificates gnupg


apt-transport-https がインストールされているのを確認

curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -


公開鍵のインポート

sudo apt-get update
sudo apt-get install google-cloud-sdk


リポジトリ更新と
google-cloud-sdk のインストール

しかしマニュアルを読んでみたら
全機能は使えないので
Linux 用インストールでないとダメと気づいた
Ubuntu 18.04 (WSL) に、Google Cloud SDK をインストールする

も参考に

一度

sudo apt-get remove google-cloud-sdk
sudo apt remove python3-crcmod 

で削除

curl -O https://dl.google.com/dl/cloudsdk/channels/rapid/downloads/google-cloud-sdk-337.0.0-linux-x86_64.tar.gz

でファイルを取得

tar zxvf google-cloud-sdk-337.0.0-linux-x86_64.tar.gz 


圧縮ファイルを展開

/google-cloud-sdk/install.sh

を実行し
Google Cloud SDK のパスを通すことでコマンド補完ができるようになる

source .bashrc

を実行して設定反映を忘れずに

./google-cloud-sdk/bin/gcloud init


SDK初期化と認証開始

You must log in to continue. Would you like to log in (Y/n)?  

となるので
Y
とすると
ブラウザが立ち上がり
認証画面になる

認証成功なら
https://cloud.google.com/sdk/auth_success
の画面がでる

次にどのプロジェクトをデフォルトにするか聞かれる

Please enter numeric choice or text value (must exactly match list 
item):  
Please enter a value between 1 and 12, or a value present in the list: 

となるので
任意のプロジェクト No を入力すると終了

gcloud components update

でコンポーネントを更新

しかしこれでもダメ

GCPの Text-to-Speech で 文字読み上げ を作る

を参考に

pip install pydub


MP3再生に必要なパッケージをいれる

pip install google-cloud-storage

をしたけどダメ

もう一回APIの確認をしたら
Cloud Speech Text API が無効になっていたので
再度有効化してから
もう一度鍵ファイルを作成することで有効化された

これで再度実行したら無事に音声が作成された

ubuntu 16 へ streamlit インストール

ubuntu 16 へ streamlit インストール

【Streamlit】インストールしてみた

を参考に

pip install streamlit

でインストール

streamlit hello

でデモのサンプルを起動できる

  If you're one of our development partners or you're interested in getting
  personal technical support or Streamlit updates, please enter your email
  address below. Otherwise, you may leave the field blank.

とでるけど気にせずに
Enter

これでブラウザで webアプリが起動する

ubuntu VLC が落ちるときの対処

ubuntu VLC が落ちるときの対処

ubuntu16.04 で動画から静止画切り出し
で以前静止画の取り出しをしたので
今回も行おうとしたが
VLC を起動し動画を再生しようとしても
落ちてしまう

VLC で動画再生に問題

を参考に

ツール > 設定

ビデオの出力を自動から
X11ビデオ出力(XCB)
にすることで解決

Mac へ FlashPrint のインストール

Mac へ FlashPrint のインストール

Fusion 360 は ubuntu が対応していないため
MacBook Air でデータを作ることに

まずは FlashPrint をその前にインストール

これがないと STL データを作成しても
Adventurer3 でプリントできない

https://flashforge.co.jp/support/
へアクセスして
MacOS をクリック

これでダウンロードされるので
ファイルをダブルクリック

解凍されるので
FlashPrint.pkg をダブルクリック
しても開発元が未確認のため開けられないので

画面左上のApple のアイコンをクリックし
システム環境設定


セキュリティーとプライバシーを開き
鍵アイコンをクリックし
管理者パスワードを入力

これでそのまま開くをクリックすると
インストール画面になる

ラズパイzero で Google Drive のマウント

ラズパイzero で Google Drive のマウント

ラズパイzero の残り容量が少なく
撮影した動画を転送後に削除していかないと容量がいっぱいになる

しかし処理に時間がかかりそうなので
Google Drive をラズパイzero にマウントする

まず Google Drive でアップロード用のディレクトリ作成

新規 > フォルダ
で任意のフォルダを作成

今回は
raspizero
とした

次に
SSH接続のRaspberry PiにGoogle Driveをマウントする

を参考に
google-drive-ocamlfuseのインストール

sudo apt-get install opam mccs
opam init --solver=mccs

まで実行したところフリーズしたので

google-drive-ocamlfuseでGoogleドライブをマウント

を参考に
ubuntu で先に認証をしておく

sudo add-apt-repository ppa:alessandro-strada/ppa
sudo apt-get update
sudo apt-get install google-drive-ocamlfuse

でインストール

google-drive-ocamlfuse

で認証

mkdir google-drive

で同期ディレクトリの作成

次にマウントフォルダの指定

google-drive-ocamlfuse 複数のGoogleDriveアカウントをubuntuで使う

を参考に

vim .gdfuse/default/config

で設定ファイルを開き

56行目の

root_folder=

で作成した Google Drive のフォルダIDを書き込む

あとは

google-drive-ocamlfuse google-drive/

でマウント

これで
cp コマンドなどでここへファイルをコピーすると
Google Drive にファイルがコピーされる

次に
Raspberry Pi 3 Model BにGoogleドライブをマウントする

を参考に
ラズパイzero にインストール

sudo apt-get upgrade
sudo apt-get install opam
opam init
opam update
opam install depext
opam depext google-drive-ocamlfuse
opam install google-drive-ocamlfuse

を実行

かなり時間がかかり
私の環境の場合1時間以上かかった

次に
SSH接続のRaspberry PiにGoogle Driveをマウントする

を参考に
偽のfirefox を作成し認証に介入

次に

nano firefox

でファイルを作成

#! /bin/sh
echo $* > /dev/stderr

として保存し

chmod 777 firefox 

で権限付与

PATH=`pwd`:$PATH ~/.opam/system/bin/google-drive-ocamlfuse


URLが端末に表示されるので
これを
ubuntu の firefox で開く

すると認証画面になるので
これを認証ししばらくすると

Access token retrieved correctly.

と表示されれば成功

これで次に Google Drive で書き込むフォルダの指定をするので

nano .gdfuse/default/config

で設定ファイルを開き

56行目の

root_folder=


ubuntuのときと同じように
作成した Google Drive のフォルダIDを書き込む

次にマウントするディレクトリの作成

mkdir googleDrive

そしてマウント

~/.opam/system/bin/google-drive-ocamlfuse ~/googleDrive/

これでマウントができたので
試しに

cp test2.wav googleDrive/

というようにファイルを
コピーしてみるとアップロードされているのがわかる

なお、マウントしてるか確認するには
df コマンドを使う

df -h

今回の場合

ファイルシス               サイズ  使用  残り 使用% マウント位置
/dev/root                    5.7G  4.4G  1.1G   81% /
devtmpfs                     152M     0  152M    0% /dev
tmpfs                        185M     0  185M    0% /dev/shm
tmpfs                        185M  5.2M  180M    3% /run
tmpfs                        5.0M  4.0K  5.0M    1% /run/lock
tmpfs                        185M     0  185M    0% /sys/fs/cgroup
/dev/mmcblk0p6                68M   24M   45M   35% /boot
//192.168.1.6/pizero_photo   916G   48G  869G    6% /mnt/nas
tmpfs                         37M  4.0K   37M    1% /run/user/1000
/dev/mmcblk0p5                30M  398K   28M    2% /media/pi/SETTINGS1
google-drive-ocamlfuse       100G   20G   81G   20% /home/pi/googleDrive

となり
マウントできているのが確認できる

とりあえず自宅での場合は定期的にバックアップをし
外出先で撮影するなら
容量をもっと大きなmicroSD にして
帰宅したら Google Drive に転送するようにすれば
ネットワーク遅延などは気にせずバックアップができそう