GoogleDriveにUSBカメラの画像をアップロード(Pythonスクリプト)

softdown-icon-linux-tux.png GoogleDriveにUSBカメラの画像をアップロード(Pythonスクリプト)
Google Drive Uploader for USB camera image



戻る一つ前のメニューに戻る

目次

ソフトウエアのダウンロード

soft-ico-download.gif PythonソースコードをSubversionブラウザよりダウンロード

機能の概略

Webカメラで撮影した画像ファイルを、Googleドライブにアップロードします。

Linux サーバ(Raspberry Piも含む)でcronを用いて定期的に実行することで、監視カメラとして使うことを意図しています。画像ファイル保存場所を外部(Googleドライブ)とすることで、サーバを破壊されても画像は残ります。

対象OS,依存ソフト等

  • Linux
  • Python

スクリプト

撮影・Googleドライブ保存スクリプト

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# PyDrive : web camera jpeg uploader for Google Drive
# Webカメラのjpeg画像をGoogle Driveにアップロードするスクリプト
 
# (C) INOUE Hirokazu
# GNU GPL Free Software (http://www.opensource.jp/gpl/gpl.ja.html)
#
# version 1.0 (2019/Feb/07)
 
import datetime
import commands
import sys
import os
 
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
 
# 指定フォルダのID
# GoogleドライブをWebブラウザで表示した時のURLよりID部分をコピーする
drive_folder_id = '5Ycn_hYk36Niemo-mRcZua3j1bQV2u8Df'
 
# スクリプト自身のディレクトリに、client_secrets.json と settings.yaml が保存されていること
os.chdir(os.path.dirname(os.path.abspath(__file__)))
 
# Webカメラ画像の取得
time_now = datetime.datetime.now()
image_filename = format(time_now, "image_%Y%m%d-%H%M%S.jpg")
temp_filename = "/tmp/temp_webcamera.jpg"
if os.path.exists(temp_filename) :
    os.remove(temp_filename)
str_result = commands.getoutput("fswebcam -D 3 -S 50 -v -r 640x480 %s" % temp_filename)
 
if( os.path.exists(temp_filename) is not True) :
    sys.exit()
 
try :
    # PyDriveでGoogleドライブに接続
    gauth = GoogleAuth()
    gauth.CommandLineAuth()
    drive = GoogleDrive(gauth)
 
    # 画像ファイルのアップロード
    file = drive.CreateFile({'title' : image_filename,
                'parents' : [{'id' : drive_folder_id}],
                'mimeType' : 'image/jpeg'})
    file.SetContentFile(temp_filename)
    file.Upload()
except Exception, e:
    print "===== PyDrive fatal error ====="
    print e
    sys.exit()
finally:
    if os.path.exists(temp_filename) :
        os.remove(temp_filename)

ファイル数上限を越えた場合、古い順に削除するスクリプト

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
# PyDrive : auto delete old files
# 指定されたGoogleDriveフォルダ内の古いファイルを一括削除するスクリプト
 
# (C) INOUE Hirokazu
# GNU GPL Free Software (http://www.opensource.jp/gpl/gpl.ja.html)
#
# version 1.0 (2019/Feb/07)
 
import sys
import datetime
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
 
# 指定フォルダのID
# GoogleドライブをWebブラウザで表示した時のURLよりID部分をコピーする
drive_folder_id = '5Ycn_hYk36Niemo-mRcZua3j1bQV2u8Df'
# ファイル名のパターン(ファイル名の先頭または末尾に一致)
filename_pattern = 'image_20'
# 24h * 2回/h * 20日 = 960回
max_files_limit = 960
# メッセージ出力の有効化
message_enable = 1
 
if len(sys.argv) == 2 and sys.argv[1] == '--nomessage':
    message_enable = 0
else :
    print("PyDrive auto delete old files\n  usage :\n  %s [--nomessage]\n" % sys.argv[0])
 
# スクリプト自身のディレクトリに、client_secrets.json と settings.yaml が保存されていること
import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
 
try :
 
    if message_enable == 1 :
        print('connect to Google Drive ...')
 
    gauth = GoogleAuth()
    gauth.CommandLineAuth()
    drive = GoogleDrive(gauth)
 
    if message_enable == 1 :
        print('caluculate number of files ...')
 
    # ファイル数を数えるため、ファイル一覧を得る
    file_list = drive.ListFile({'q': "'%s' in parents and trashed=false and mimeType='image/jpeg' and title contains '%s'" %
                    (drive_folder_id, filename_pattern)}).GetList()
 
    current_files_count = len(file_list)
 
    # ファイル数が規定に達していない時は、削除処理を行わない
    if current_files_count <= max_files_limit :
        if message_enable == 1 :
            print("current %d files, is under limit %d\nexit script" %
            (current_files_count, max_files_limit))
        sys.exit()
 
    if message_enable == 1 :
        print("current %d files, now exec task to delete %d files" %
        (current_files_count, current_files_count - max_files_limit))
 
    if message_enable == 1 :
        print('getting file list ...')
 
    # 削除のためのファイル一覧を得る
    file_list = drive.ListFile({'q': "'%s' in parents and trashed=false and mimeType='image/jpeg' and title contains '%s'" %
                    (drive_folder_id, filename_pattern),
                    'maxResults' : (current_files_count - max_files_limit),
                    'orderBy' : 'createdDate'}).GetList()
 
    # ファイルを削除する
    for file1 in file_list:
        if message_enable == 1 :
            print('delete title: %s' % file1['title'])
        file1.Delete()
 
except Exception, e:
    print "===== PyDrive fatal error ====="
    print e
    sys.exit()
 
if message_enable == 1 :
    print("done all")

設定ファイル

PyDrive ドキュメントのOAuth made easyの通りに作成する。

settings.yaml
client_config_backend: settings
client_config:
    client_id: 123456789012-aHyiTb7kAw3Nuq4mPueWqcLk5iGjdxp2.apps.googleusercontent.com
    client_secret: hjY6oh4Th387Jeirsy3lHiec
 
save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json
get_refresh_token: True
oauth_scope:
    - https://www.googleapis.com/auth/drive.file
    - https://www.googleapis.com/auth/drive.install

Google API ConsoleからダウンロードするIDと秘密鍵ファイルもスクリプトと同じディレクトリに保存する。

client_secret.json
{"installed":{"client_id":"123456789012-aHyiTb7kAw3Nuq4mPueWqcLk5iGjdxp2.apps.googleusercontent.com","project_id":"project-id-156354","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"hjY6oh4Th387Jeirsy3lHiec","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}

Google API Consoleでプロジェクト作成と秘密鍵などのダウンロード

Google Developers Consolesより、Google API Consoleを開いて新しいプロジェクトを作成する。

gdrive-pydrive-console02.jpg

画面最上部、プロジェクト名(赤で囲んだところ)をクリックして、さらに「新しいプロジェクトの作成」をクリック。

プロジェクトが作成されたら、「認証情報」→「OAuthクライアントID」を作成する。

gdrive-pydrive-console03.jpg

gdrive-pydrive-console04.jpg

クライアントの認証にコマンドラインを使う(Raspberry Piなどsshで接続した機器ではコマンドライン以外では最初の認証が難しいため)ので、アプリケーションの種類は「その他」。

gdrive-pydrive-console05.jpg

認証情報(OAuth)の作成が完了したら、表示してJSONファイル(client_secret.json)をダウンロードする。

gdrive-pydrive-console06.jpg

初回の認証(credentials.jsonの自動作成)

初回にGoogleAPIにアクセスした時に、認証URLが表示される。

/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access credentials.json: No such file or directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Go to the following link in your browser:
()
    https://accounts.google.com/o/oauth2/auth?redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=123456789012-aHyiTb7kAw3Nuq4mPueWqcLk5iGjdxp2.apps.googleusercontent.com&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.file+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.install&approval_prompt=force&access_type=offline
()
Enter verification code:

これをブラウザにコピーして認証を行い、表示された確認コードをコンソールに貼り付けて認証が完了する。

gdrive-pydrive-accessrequest01.jpg

gdrive-pydrive-accessrequest02.jpg

使用許諾条件

GNU GPL フリーソフトウエア


戻る一つ前のメニューに戻る