はじめに
書籍をもとにコードを書いている際、GitHub等にあるデータを読み込みたい場合がある.
例えば、"Deep Learning with PyTorch"の"2.2.2 CycleGAN"において馬の画像をシマウマの画像に変換するために、"https://github.com/deep-learning-with-pytorch/dlwpt-code/tree/master/data/p1ch2/horse2zebra_0.4.0.pth" をダウンロードする必要がある.
この際、Google Colabなどで作業している場合、愚直にやれば上記ファイルをローカルでダウンロードし、それをGoogle Drive等にアップロードするという手順を踏むことになると思うが、面倒&時間がかかるためGoogle Colab内で完結させたい.
先に結論:
> wget -nH --cut-dirs=4 -r --no-parent <URL>
wget
当然、wgetで以下のようにダウンロードすることができる.
> wget https://github.com/deep-learning-with-pytorch/dlwpt-code/tree/master/data/p1ch2/horse2zebra_0.4.0.pth
だが、毎回これをするのは面倒なので、当該リポジトリのdata
フォルダごとGoogle Driveにダウンロードし、以下のようにデータへのアクセスを省力化することを考える.
# Google Colabでの処理
from google.colab import drive
drive.mount('/content/gdrive')
data_path = './gdrive/My Drive/Colab Notebooks/<dir_name>/data/'
問題
- 普通に
wget -r
すると、親ディレクトリのファイル等も含む関係ないものまでダウンロードしてしまう- ->
--no-parent
オプションを用いる
- ->
- 最後の
data/
だけダウンロードしたいのに、github.com
フォルダからの階層を維持してダウンロードされる(ディレクトリ構成の例:github/deep-learning-with-pytorch/dlwpt-code/tree/master/data/
)- ->
-nH
オプションと--cut-dirs
オプションの組み合わせ-
-nH
オプション: ホストを無視(github.com) -
--cut-dirs
オプション:--cut-dirs=n
の形式でcutする階層数をn
で指定する(上の例で-nH
オプションと組み合わせた場合、n=2
とすると、github/deep-learning-with-pytorch/dlwpt-code/
までcutできる)
-
- ->
よって、以下のコマンドをたたけばよい.
> wget -nH --cut-dirs=4 -r --no-parent \
https://github.com/deep-learning-with-pytorch/dlwpt-code/tree/master/data/ (-P ./<dir_name>/)
必要であれば、-P
でダウンロード先のディレクトリを指定する.