見出し画像

PaperspaceでStable Diffusionを動かす設定のメモ

Google Colab から Paperspace に乗り換えた理由

Stable Diffusion での画像生成に興味があり、Google Colabで画像生成をしていた。(元にしたNotebook は https://github.com/TheLastBen/fast-stable-diffusion  、Youtubeで紹介されていた。他にも多数あり。)
Google ColabはProを選択した。

Google Colabのプラン選択
Google Colabプラン選択

プロンプトを手入力してGenerateして生成画像を確認する。1枚、2枚と作成するうちに興が乗ってきて、batch countを増やしたり、script でx/y/z plotで条件を変えて生成したりしているうちに、気が付けば一か月あたりのコンピューティングユニット 100 を使いきってしまった。Pay As You Goで100コンピューティングユニット 100を 1,179円で追加購入する。このペースでは月に 500コンピューティングユニット以上になりそうである。遊びのためにはコストがかかりすぎるので、代替方法を探すことにした。ローカルPCであれば計算自体は電気代だけで済むが、一定程度のスペックのGPUを持つPCの導入は初期費がかかる。 そこで別のサービスを探しているうちに、@javacommonsさんの記事(【Paperspace】Stable Diffusion Web UI を月額定額で使う )に辿り着いた。

Paperspaceの導入

導入手順については、@javacommonsさんの記事(【Paperspace】Stable Diffusion Web UI を月額定額で使う )にて画面付きで詳しく説明されているので迷うことはない。@javacommonsさん、ありがとうございます!
実際に手順に従って設定したときの感想は以下。

  1. Paperspace Proの申込は特に問題なし。

  2. consoleの設定については、説明に従い、設定用のファイル(webui2.ipynb)をアップロードすることで完了した。

  3. Stable Diffusion Web UI の起動、停止についても説明通りで問題なし。

  4. Stable Diffusionの使い方、別のモデルのダウンロード方法についても解説がある。

PaperspaceでStable Diffusionを動かしてみて

FREEのMachineがなかなか空かないが、なんどかページをリロードすると、空きが見つかるので、すかさず選択してSTARTする。これまで1週間くらい、主に夜に操作して、最上位クラスが使えることはなかったが、どれかは使うことができた。

Free-A4000を使用中の表示

Google Colab Proと比べた生成速度は、厳密に速度を測定していないが、体感的には同じくらい、場合によってはPaperspaceのほうが早い感じのときもあった。なによりも助かるのは、Google Colab Proだと、しばらく画面を操作していないと勝手に切れてしまう(インタラクティブな使用前提のため)が、Paperspaceでは6時間までは放置できることである。おかげで、定額のこともあり、Generate forever を気兼ねなく実行できるようになった。  

Generate foreverで実行

Paperspaceに大きなファイル(モデルなど)を配置するには

まず、@javacommonsさんの解説記事(Paperspace および Stable Diffusion Web UI に関する FAQ (随時追加))にて、設定用のファイル(webui2.ipynb)への追記方法が記されているので、ほとんどの場合(civitaiやhugging faceからURL指定してダウンロードできる場合)はこれで解決できる。

ただし、google driveやMegaなどに限定公開で置かれているファイルは、ローカルにダウンロードはできるが、Paperespaceから直接URLを指定してwgetすることは難しい(wgetするとダウンロード画面がダウンロードされて、その先までダウンロードできない)。ローカルファイルをPaperspaceにアップロードできるものの、1GBあたり1時間以上時間がかかっていて、これでは4GBくらいのモデルファイルをアップするのは厳しい。ファイルを分割してアップすることも考えたが面倒である。色々探していたら、Hugging face の privateなファイルをダウンロードする記事(devgruHT さん、Paperspaceで使うファイルの置き場を変えてみた)に辿り着いた。devgruHT さん、ありがとうございます!
実際に手順に従って設定した結果は以下。

  1. Hugging faceに private な modelのrepositoryを生成する部分は問題なし。

  2. 参照用のトークン作成も問題なし

  3.  記事に書かれているスクリプトを、Paperspaceのターミナルから実行すると、ダウンロードに成功した。

  4. しかし、Jupyter Notebookのコードに記載すると、ダウンロードに失敗する。

  5. ChatGPT4に質問すると、『Jupyter Notebookでエラーが発生しているのは、!curlコマンドの一部です。Jupyter Notebookでは、!に加えて、<(), |, >といった特殊なシェル構文がサポートされていません。』とのことで、修正コードを提示してくれた。

import os
import subprocess

# ディレクトリの移動
os.chdir('/notebooks/stable-diffusion-webui/models/Stable-diffusion')

# コマンドの実行
token = '****今回設定したトークン'
url = 'https://huggingface.co/今回設置したリポジトリ/'
file_name = 'ダウンロードするファイル'
command = f'curl -u :{token} -Lo {file_name} {url}{file_name}'
subprocess.call(command, shell=True)

これを実行したら、Jupyter Notebookでもダウンロードできた。
もっとうまい方法があるかもしれないが、動いたので先に進む。

<注>PaperspaceのドキュメントにはGoogleDriveからgdownを使ってダウンロードする方法の説明がある。Google Driveのファイルに対して "Anyone with the Link." で permission を与えるのは、アクセス制限を解除することになるので、URLが知られることはないといっても、躊躇いを感じざるを得ない。一時的に共有して、ダウンロードしたら共有を外すとかすればよいのかもしれない。

Transferring files from Google Drive (Paperspaceドキュメントより)

2023/08/01 追記:なぜか Huggingfaceにアクセスすると、「Invalid username or password.」となるようになった。コマンドから実行してもかわらず。そこで上記のgdownを実施する。

root@nbrqt9txif:/notebooks# pip install gdown
Requirement already satisfied: gdown in /usr/local/lib/python3.10/dist-packages (4.7.1)
Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from gdown) (3.12.2)
Requirement already satisfied: requests[socks] in /usr/local/lib/python3.10/dist-packages (from gdown) (2.31.0)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from gdown) (1.14.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from gdown) (4.65.0)
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.10/dist-packages (from gdown) (4.12.2)
Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.10/dist-packages (from beautifulsoup4->gdown) (2.4.1)
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (3.2.0)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests[socks]->gdown) (2.8)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (1.26.16)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests[socks]->gdown) (2019.11.28)
Requirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (1.7.1)
DEPRECATION: torchsde 0.2.5 has a non-standard dependency specifier numpy>=1.19.*; python_version >= "3.7". pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of torchsde or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063
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@nbrqt9txif:/notebooks# pip install --upgrade gdown
Requirement already satisfied: gdown in /usr/local/lib/python3.10/dist-packages (4.7.1)
Requirement already satisfied: filelock in /usr/local/lib/python3.10/dist-packages (from gdown) (3.12.2)
Requirement already satisfied: requests[socks] in /usr/local/lib/python3.10/dist-packages (from gdown) (2.31.0)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from gdown) (1.14.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.10/dist-packages (from gdown) (4.65.0)
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.10/dist-packages (from gdown) (4.12.2)
Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.10/dist-packages (from beautifulsoup4->gdown) (2.4.1)
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (3.2.0)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3/dist-packages (from requests[socks]->gdown) (2.8)
Requirement already satisfied: urllib3<3,>=1.21.1 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (1.26.16)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3/dist-packages (from requests[socks]->gdown) (2019.11.28)
Requirement already satisfied: PySocks!=1.5.7,>=1.5.6 in /usr/local/lib/python3.10/dist-packages (from requests[socks]->gdown) (1.7.1)
DEPRECATION: torchsde 0.2.5 has a non-standard dependency specifier numpy>=1.19.*; python_version >= "3.7". pip 23.3 will enforce this behaviour change. A possible replacement is to upgrade to a newer version of torchsde or contact the author to suggest that they release a version with a conforming dependency specifiers. Discussion can be found at https://github.com/pypa/pip/issues/12063
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

GoogleDrive上でリンクを知っている全員にアクセス権を付与し、リンクをコピーした

https://drive.google.com/file/d/1QCBz8twNbtlOYSf2DiZPiUh5KLY3twiy/view?usp=sharing

これをもとにダウンロード実施

root@nbrqt9txif:/notebooks/stable-diffusion-webui/models/Stable-diffusion# gdown "1QCBz8twNbtlOYSf2DiZPiUh5KLY3twiy&confirm=t"
Downloading...
From: https://drive.google.com/uc?id=1QCBz8twNbtlOYSf2DiZPiUh5KLY3twiy&confirm=t
To: /notebooks/stable-diffusion-webui/models/Stable-diffusion/_BlazingDrive_V02.safetensors
100%|█████████████████████████████████████████████████████████████████████████████████████| 2.13G/2.13G [00:24<00:00, 87.1MB/s]

ダウンロード後、GoogleDriveのファイルは削除した。



Paperspaceの出力ファイルをGoogleDriveに転送して、削除したい

(1)Paperspace→Google Driveへの転送

6時間定額で使い放題のため、Generate foreverでどんどん画像を生成していくと、Paperspace側のディスク使用量が増えてしまう。使わないモデルは削除したが、ControlNetをインストールして(@javacommonsさんの記事 『【ControlNet v1.1】を Paperspace 上の Web UI にインストールする』参照)、Paperspaceの定額の範囲15GBを超えているので、節約のため貯めないようにする。
Paperspceから直接ファイルをダウンロードすることはできるが、一つずつダウンロードするのは面倒である。

Filesの様子。ディレクトリ指定してダウンロードするメニューは無し。

ターミナルから圧縮してダウンロード、ローカルPCで解凍していたが、これも面倒である。

# 2023-06-23 のフォルダを圧縮する場合
tar cfz 2023-06-23.tgz 2023-06-23
#ファイルを解凍する場合(Windowsでも可能)
tar xfz 2023-06-23.tgz

方法を探していたら、えぬの備忘録さんの記事、『AUTOMATIC1111をPaperspace Gradientで実行し, Google Driveに画像を送る(認証にサービスアカウントを利用するVer.)』辿り着いた。

こちらの手順を要約すると以下のようになる。

  1. Paperspace Gradientの有料版の契約(必須):済

  2. GCPの「Google Drive API」を、認証ファイルを使って認証可能にする。認証ファイルは、①GCPのプロジェクトの作成、②プロジェクトでのGoogle Drive API の有効化、③サービスアカウント作成 ④サービスアカウントの「鍵」の作成(認証ファイル:JSON形式 service_account.json)⑤共有フォルダのID取得

  3. 認証ファイル(service_account.json)をPaperspace Gradientに配置

  4. Paperspace Gradient に、Google Drive APIを使うためのラッパー(pydrive2)をインストールする

  5. Paperspace Gradient (webui2.ipynb)にアップロードスクリプトを追記する。スクリプトのパラメータは、今回用に変更する。

これらの手順の詳細は、以下。

  1.  説明済

  2. Google API サービスアカウントファイル作成・設定手順』の記載参照

  3. AUTOMATIC1111をPaperspace Gradientで実行し, Google Driveに画像を送る(認証にサービスアカウントを利用するVer.)』の記載とは、Stable Diffusion の設定が異なるせいか、service_account.json は、/notebooks 下に置いた。

  4. 参考記事『PyDriveによりPythonからGoogleドライブを操作する【OAuth使わず】』記載の内容を、Junyper Notebook(webui2.ipynb) に反映

  5. アップロードスクリプトの追加内容は、『量子プログラミング入門→量子コンピューティングサービス構築入門』のコードをコピーして、『AUTOMATIC1111をPaperspace Gradientで実行し, Google Driveに画像を送る(認証にサービスアカウントを利用するVer.)』の指定通りに修正する。具体的には以下。

#4. pydrive2のインストール
!pip list
!python -m pip install --upgrade pip
!pip install PyDrive
!pip list
!pip install pydrive2
#5. アップロードスクリプト
# #4の実施後、ディレクトリが /notebooks/stable-diffusion-webui に変わることがあったので、ディレクトリ設定を追加。
%cd /notebooks
!pwd

import os
import sys
import datetime

from pydrive2.auth import GoogleAuth #pydrive2に変更
from pydrive2.drive import GoogleDrive #pydrive2に変更
from oauth2client.service_account import ServiceAccountCredentials #追加

def auth_gd():
    JSON_FILE = "service_account.json" #追加
    gauth = GoogleAuth()
    # 削除 gauth.CommandLineAuth()
    scope = ["https://www.googleapis.com/auth/drive"] #追加
    gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_FILE, scope) #追加
    drive = GoogleDrive(gauth)
    return drive

def upload2googledrive():
    drive = auth_gd()
    
    parentid = '共有フォルダのID' #project-root directory
    path = "/notebooks/stable-diffusion-webui/outputs/txt2img-images" #path to local data

    # "test"フォルダをGoogle Drive上に作成
    t_folder = create_dir(parentid, os.path.basename(path), drive)

    # ローカルのディレクトリ一覧取得
    flag = ""
    dir_list=get_dirlist(path)
    for d in dir_list:
        d_folder = create_dir(t_folder['id'], os.path.basename(d), drive)
        #ローカルのファイル一覧取得
        file_list=get_filelist(d)
        for f in file_list:
            upload_file(d_folder['id'], f, drive)

# ディレクトリがGoogle Drive上に存在するかどうかをチェックし、
# 存在しなければ作成、すでに存在すれば既存のフォルダを返す
def create_dir(pid, fname, drive=None):
    if drive == None:
        drive = auth_gd()

    ret = check_files(pid, fname, drive)
    if ret == False:
        folder = drive.CreateFile({'title': fname,
                                 'mimeType': 'application/vnd.google-apps.folder'})
        folder['parents']= [{'id': pid}]
        folder.Upload()
    else:
        folder = ret
        print(folder['title']+" exists")

    return folder

#同じ名前のファイルがGoogle Drive上に存在するかチェックし、
#存在しなければアップロード、存在すれば既存のファイルを返す
def upload_file(pid, fname, drive=None):
    if drive == None:
        drive = auth_gd()

    ret = check_files(pid, fname, drive)
    if ret == False:
        gf = drive.CreateFile()
        gf['parents']= [{'id': pid}]
        gf.SetContentFile(fname)
        gf['title'] = os.path.basename(fname)
        gf.Upload()
    else:
        gf = ret
        print(gf['title']+" exists")

    return gf

#Google Drive上にその名前のファイル/フォルダがあるかチェック、なければFalseを、あれば既存のファイル/フォルダを返す
def check_files(pid, fname, drive=None):
    if drive == None:
        drive = auth_gd()

    query = '"{}" in parents'.format(pid)
    query += ' and title = "' + os.path.basename(fname) + '"'

    list =  drive.ListFile({'q': query}).GetList()
    if len(list)> 0:
        return list[0]
    return False
            
def get_dirlist(basedir):
    ret = []
    for path, dirnames, filenames in os.walk(basedir):
        for dir in sorted(dirnames):
            d = os.path.join(path, dir)
            ret.append(d)
    return ret

def get_filelist(basedir):
    ret = []
    for path, dirnames, filenames in os.walk(basedir):
        for filename in sorted(filenames):
            fullpath = os.path.join(path, filename)
            ret.append(fullpath)
    return ret

if __name__ == '__main__':
    upload2googledrive()

#ファイル削除は様子をみてから。今のところはコメント。
#!rm -rf /notebooks/stable-diffusion-webui/outputs/txt2img-images/*

(2)GoogleDrive上のファイルをPaperspaceから削除

GoogleDrive上でファイルを確認して、不要なファイルを削除すると、以下のようなメッセージが表示された。

GoogleDrive上(スマホ)でファイルを削除するときのメッセージ

Paperspace側から削除しないとファイルが残るらしい。えぬの備忘録さんの記事、『【Paperspace Gradient】google-drive-ocamlfuseやrcloneで,Google Driveをマウントしたかった.』に従って、確認していく。

①rcloneのインストールと設定
 説明の手順どおりでエラー無く進む。コマンドログは以下。

root@n4v5jzvzwr:/notebooks# echo "[Terminal 1]"
[Terminal 1]
root@n4v5jzvzwr:/notebooks# sudo -v ; curl https://rclone.org/install.sh | sudo bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  4707  100  4707    0     0  12225      0 --:--:-- --:--:-- --:--:-- 12225


### 中略 ###

rclone v1.62.2 has successfully installed.
Now run "rclone config" for setup. Check https://rclone.org/docs/ for more details.

root@n4v5jzvzwr:/notebooks# rclone config
2023/06/17 07:57:33 NOTICE: Config file "/root/.config/rclone/rclone.conf" not found - using defaults
No remotes found, make a new one?
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n

Enter name for new remote.
name> PyDrive

Option Storage.
Type of storage to configure.
Choose a number from below, or type in your own value.
 1 / 1Fichier
   \ (fichier)
 2 / Akamai NetStorage
   \ (netstorage)
 3 / Alias for an existing remote
   \ (alias)
 4 / Amazon Drive
   \ (amazon cloud drive)
 5 / Amazon S3 Compliant Storage Providers including AWS, Alibaba, Ceph, China Mobile, Cloudflare, ArvanCloud, DigitalOcean, Dreamhost, Huawei OBS, IBM COS, IDrive e2, IONOS Cloud, Liara, Lyve Cloud, Minio, Netease, RackCorp, Scaleway, SeaweedFS, StackPath, Storj, Tencent COS, Qiniu and Wasabi
   \ (s3)
 6 / Backblaze B2
   \ (b2)
 7 / Better checksums for other remotes
   \ (hasher)
 8 / Box
   \ (box)
 9 / Cache a remote
   \ (cache)
10 / Citrix Sharefile
   \ (sharefile)
11 / Combine several remotes into one
   \ (combine)
12 / Compress a remote
   \ (compress)
13 / Dropbox
   \ (dropbox)
14 / Encrypt/Decrypt a remote
   \ (crypt)
15 / Enterprise File Fabric
   \ (filefabric)
16 / FTP
   \ (ftp)
17 / Google Cloud Storage (this is not Google Drive)
   \ (google cloud storage)
18 / Google Drive
   \ (drive)
19 / Google Photos
   \ (google photos)
20 / HTTP
   \ (http)
21 / Hadoop distributed file system
   \ (hdfs)
22 / HiDrive
   \ (hidrive)
23 / In memory object storage system.
   \ (memory)
24 / Internet Archive
   \ (internetarchive)
25 / Jottacloud
   \ (jottacloud)
26 / Koofr, Digi Storage and other Koofr-compatible storage providers
   \ (koofr)
27 / Local Disk
   \ (local)
28 / Mail.ru Cloud
   \ (mailru)
29 / Mega
   \ (mega)
30 / Microsoft Azure Blob Storage
   \ (azureblob)
31 / Microsoft OneDrive
   \ (onedrive)
32 / OpenDrive
   \ (opendrive)
33 / OpenStack Swift (Rackspace Cloud Files, Memset Memstore, OVH)
   \ (swift)
34 / Oracle Cloud Infrastructure Object Storage
   \ (oracleobjectstorage)
35 / Pcloud
   \ (pcloud)
36 / Put.io
   \ (putio)
37 / QingCloud Object Storage
   \ (qingstor)
38 / SMB / CIFS
   \ (smb)
39 / SSH/SFTP
   \ (sftp)
40 / Sia Decentralized Cloud
   \ (sia)
41 / Storj Decentralized Cloud Storage
   \ (storj)
42 / Sugarsync
   \ (sugarsync)
43 / Transparently chunk/split large files
   \ (chunker)
44 / Union merges the contents of several upstream fs
   \ (union)
45 / Uptobox
   \ (uptobox)
46 / WebDAV
   \ (webdav)
47 / Yandex Disk
   \ (yandex)
48 / Zoho
   \ (zoho)
49 / premiumize.me
   \ (premiumizeme)
50 / seafile
   \ (seafile)
Storage> 18

Option client_id.
Google Application Client Id
Setting your own is recommended.
See https://rclone.org/drive/#making-your-own-client-id for how to create your own.
If you leave this blank, it will use an internal key which is low performance.
Enter a value. Press Enter to leave empty.
client_id> ### service_account.json の client_id の値を記載 ###

Option client_secret.
OAuth Client Secret.
Leave blank normally.
Enter a value. Press Enter to leave empty.
client_secret> 

Option scope.
Scope that rclone should use when requesting access from drive.
Choose a number from below, or type in your own value.
Press Enter to leave empty.
 1 / Full access all files, excluding Application Data Folder.
   \ (drive)
 2 / Read-only access to file metadata and file contents.
   \ (drive.readonly)
   / Access to files created by rclone only.
 3 | These are visible in the drive website.
   | File authorization is revoked when the user deauthorizes the app.
   \ (drive.file)
   / Allows read and write access to the Application Data folder.
 4 | This is not visible in the drive website.
   \ (drive.appfolder)
   / Allows read-only access to file metadata but
 5 | does not allow any access to read or download file content.
   \ (drive.metadata.readonly)
scope> 1

Option service_account_file.
Service Account Credentials JSON file path.
Leave blank normally.
Needed only if you want use SA instead of interactive login.
Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
Enter a value. Press Enter to leave empty.
service_account_file> /service_account.json

Edit advanced config?
y) Yes
n) No (default)
y/n> n

Configure this as a Shared Drive (Team Drive)?

y) Yes
n) No (default)
y/n> n

Configuration complete.
Options:
- type: drive
- client_id: ### service_account.json の client_id の値 ###
- scope: drive
- service_account_file: /service_account.json
- team_drive: 
Keep this "PyDrive" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y

Current remotes:

Name                 Type
====                 ====
PyDrive              drive

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> q
root@n4v5jzvzwr:/notebooks# 

上記の設定では、serivce_account_file のパスを間違えている。rclone config で修正した。

root@n4v5jzvzwr:/notebooks# rclone config
Current remotes:

Name                 Type
====                 ====
PyDrive              drive

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> e

Select remote.
Choose a number from below, or type in an existing value.
 1 > PyDrive
remote> 1

Editing existing "PyDrive" remote with options:
- type: drive
- client_id: ### service_account.json の client_id の値 ###
- scope: drive
- service_account_file: /service_account.json
- team_drive: 

Option client_id.
Google Application Client Id
Setting your own is recommended.
See https://rclone.org/drive/#making-your-own-client-id for how to create your own.
If you leave this blank, it will use an internal key which is low performance.
Enter a string value. Press Enter for the default (### service_account.json の client_id の値 ###).
client_id> 

Option client_secret.
OAuth Client Secret.
Leave blank normally.
Enter a value. Press Enter to leave empty.
client_secret> 

Option scope.
Scope that rclone should use when requesting access from drive.
Choose a number from below, or type in your own string value.
Press Enter for the default (drive).
 1 / Full access all files, excluding Application Data Folder.
   \ (drive)
 2 / Read-only access to file metadata and file contents.
   \ (drive.readonly)
   / Access to files created by rclone only.
 3 | These are visible in the drive website.
   | File authorization is revoked when the user deauthorizes the app.
   \ (drive.file)
   / Allows read and write access to the Application Data folder.
 4 | This is not visible in the drive website.
   \ (drive.appfolder)
   / Allows read-only access to file metadata but
 5 | does not allow any access to read or download file content.
   \ (drive.metadata.readonly)
scope> 1

Option service_account_file.
Service Account Credentials JSON file path.
Leave blank normally.
Needed only if you want use SA instead of interactive login.
Leading `~` will be expanded in the file name as will environment variables such as `${RCLONE_CONFIG_DIR}`.
Enter a string value. Press Enter for the default (/service_account.json).
service_account_file> /notebooks/service_account.json

Edit advanced config?
y) Yes
n) No (default)
y/n> n

Configure this as a Shared Drive (Team Drive)?

y) Yes
n) No (default)
y/n> n

Configuration complete.
Options:
- type: drive
- client_id: ### service_account.json の client_id の値 ###
- scope: drive
- service_account_file: /notebooks/service_account.json
- team_drive: 
Keep this "PyDrive" remote?
y) Yes this is OK (default)
e) Edit this remote
d) Delete this remote
y/e/d> y

Current remotes:

Name                 Type
====                 ====
PyDrive              drive

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> q
root@n4v5jzvzwr:/notebooks# 

②実行(容量の確認)

root@n4v5jzvzwr:/notebooks# rclone about PyDrive:
Total:   15 GiB
Used:    371.810 MiB
Free:    14.637 GiB
Trashed: 0 B
Other:   0 B

ファイルのリストを表示する。GoogleDrive側で削除したディレクトリやファイルが表示される。削除しないファイルやディレクトリが表示されないのはなぜか、追々調べる。

root@n4v5jzvzwr:/notebooks# rclone lsd PyDrive:
          -1 2023-06-15 15:42:44        -1 2023-06-15
          -1 2023-06-16 16:19:23        -1 2023-06-16

③ファイルを削除する。dry-runで確認してから。

root@n4v5jzvzwr:/notebooks# rclone --dry-run delete PyDrive:
### 中略 ###
2023/06/17 09:05:20 NOTICE: 2023-06-16/00051-26507430.png: Skipped delete as --dry-run is set (size 1.899Mi)
root@n4v5jzvzwr:/notebooks# rclone delete PyDrive:
root@n4v5jzvzwr:/notebooks# rclone lsd PyDrive:
          -1 2023-06-15 15:42:44        -1 2023-06-15
          -1 2023-06-16 16:19:23        -1 2023-06-16
root@n4v5jzvzwr:/notebooks# rclone lsl PyDrive:
root@n4v5jzvzwr:/notebooks# rclone about PyDrive:
Total:   15 GiB
Used:    371.810 MiB
Free:    14.637 GiB
Trashed: 314.018 MiB
Other:   0 B
root@n4v5jzvzwr:/notebooks# rclone cleanup PyDrive:
2023/06/17 09:17:01 NOTICE: Google drive root '': Note that emptying the trash happens in the background and can take some time.
### 2,3分後 ###
root@n4v5jzvzwr:/notebooks# rclone about PyDrive:
Total:   15 GiB
Used:    0 B
Free:    15 GiB
Trashed: 0 B
Other:   0 B
### ディレクトリが残っているので削除した ###
root@n4v5jzvzwr:~# rclone rmdirs PyDrive: --leave-root

(3)Google Drive ファイル削除を Jupyter notebook から実行する

①rclone のインストールと設定<動作確認がまだ>

#(7-1) rcloneのインストールとセットアップ
import os
import subprocess

# rcloneのインストール
!curl https://rclone.org/install.sh | sudo bash

#X#install_rclone = subprocess.run(["curl", "https://rclone.org/install.sh", "|", "sudo", "bash"], capture_output=True)
#X#if install_rclone.returncode != 0:
#X#    print("rcloneのインストールに失敗しました:")
#X#    print(install_rclone.stderr.decode())

# 必要なディレクトリが存在するかを確認し、存在しない場合は作成します
config_dir = os.path.expanduser("~/.config/rclone")
os.makedirs(config_dir, exist_ok=True)

# rcloneの設定内容を定義します
rclone_config = """
[PyDrive]
type = drive
client_id = ### service_account.json の client_id の値 ###
scope = drive
service_account_file = /notebooks/service_account.json
team_drive = 
"""

# 設定内容をファイルに書き出します
with open(os.path.join(config_dir, "rclone.conf"), "w") as f:
    f.write(rclone_config)

②rcloneの削除ファイルを確認

#(7-2) rcloneによるgoogle drive転送ファイルの削除(ファイル確認)
!rclone about PyDrive:
!rclone lsd PyDrive:
!rclone lsl PyDrive:
!rclone --dry-run delete PyDrive:

Google Driveの共有側(自分のアカウントの方)に残っているファイルは、こちらの一覧に表示されない。このあとの削除コマンドを実施しても消えなかった。運用としては、GoogleDriveで消した後、実施することとする。

③rcloneでファイル削除

#(7-3) rcloneによるgoogle drive転送ファイルの削除(ファイル削除)
!rclone delete PyDrive:
!rclone rmdirs PyDrive: --leave-root
!rclone cleanup PyDrive:
#削除後のファイルとDisk使用量確認
!rclone lsd PyDrive:
!rclone lsl PyDrive:
!rclone about PyDrive:

改めて考えてみると、rclone でGoogle Driveへのファイル転送もできそうな気がする。時間のあるときに調べてみよう。

(4)Paperspace上のファイル削除

Paperspace上のファイルをまとめて削除する。txt2img-grids, img2img-images は Google Driveに送っていないので、必要な場合は転送する。

#(7-4)Paperspace上のファイルを削除
!rm -rf /notebooks/stable-diffusion-webui/outputs/txt2img-images/*
!rm -rf /notebooks/stable-diffusion-webui/outputs/txt2img-grids/*
!rm -rf /notebooks/stable-diffusion-webui/outputs/img2img-images/*

GoogleDriveへの転送が以外と手間がかかった。これなら tar で固めてローカルに落とす方が楽かもしれない。。。

(5)GoogleDrive上でPaperspace用アカウントから自分用アカウントにファイルをコピーしたい

Paperspace用Googleアカウントだと 15GBしか容量がないので、自分のアカウントにコピーしたい。しかし、GoogleDrive画面メニューから、ディレクトリのコピーが無いので、以外と面倒である。

まず次の方法が思い当たる
①Paperspace用アカウントのGoogle Drive上でフォルダーをローカルPCにダウンロードする。zipファイルになる。
②zipファイルのままローカルPCから自分のアカウントのGoogle Drive上のアップロードする。
③Google Drive上で、zipファイルを解凍する。

ファイルの数が多いと、ダウンロード・アップロードに時間を要するので、zipで固める方が早い。
(以下、実施例を記載予定。次回)
①Paperspace用のGoogleDriveからフォルダーをzipファイルとしてダウンロード
②zipファイルを自分のアカウントのGoogleDriveにアップする。
③zip解凍はGoogleDriveのメニューから選択できる。


<補足>別の方法としては、パソコン版ドライブをインストールして、一度パソコンに同期してからアップロードする方法がありそうだ。
①Googleドライブヘルプより

パソコン版Googleドライブの説明

パソコン版ドライブをインストールする

パソコン版ドライブのインストール

ダウンロードして、インストールを実行したら、すでにインストール済だった。

インストール済メッセージ

インストール済ではあるが、別のGoogleアカウント用に設定していたため、複数アカウントの設定から行わざるを得ない。これも後で時間のあるときにやってみよう。



補足

  • キービジュアル画像の左側はGoogle Colaboratory、右はPaperspaceのサイトです。中央の隙間は、Photoshopのジェネレーティブ塗りつぶしで埋めています。

  • 本文章は 2023年6月18日時点の調査に基づきます。調査不足や勘違いにより、誤っていることを書いているかもしれません。ここの記載内容はあくまで参考としていただき、ご自身のご判断、ご責任にて実施のほどよろしくお願いいたします。


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