はじまり
Google Play Musicが12月末で終了というニュースが発表されました。
購入やアップロードした楽曲はYouTube musicへそのまま移行できるのですが、同サービスもいつ終了になるかわからないので、念のためローカル環境にもバックアップすることに。
楽曲をダウンロードしたところ、全データが同一フォルダ内に一括ダウンロードされる仕様だったので、Pythonを使って「アーティスト名」や「アルバム名」ごとにフォルダ分けを行う事にしました。
私のようなプログラミングのド素人でも、この程度の事はできそうです。
ダウンロード
楽曲のダウンロードは下記ページに従って行いました。
https://support.google.com/googleplaymusic/answer/1250232?hl=ja
フォルダ階層
フォルダ階層は以下の通りに設定する事とします。
Root
├アーティストA
│ └アルバム名
│ └ 楽曲_1.mp3
│ └ 楽曲_2.mp3
├アーティストB
├アーティストC
ディレクトリ構成図の記入方法はこちらを参考にしました。
https://qiita.com/paty-fakename/items/c82ed27b4070feeceff6
mp3のタグ情報を取得
楽曲名、アーティスト名、アルバム名など、mp3に内包されたタグ情報を取得するにはEasyID3
を利用します。
こちらのサイトを参考にさせていただきました。
https://note.nkmk.me/python-mutagen-mp3-id3/
完成したコード
いきなりですが完成したコードは下記の通りです。
from mutagen.easyid3 import EasyID3
import os
import shutil
import re
def replace(string):
return(re.sub(r'[\\/:*?"<>|]+', '-', string))
def arrange_data(mp3_path):
tags = EasyID3(mp3_path)
try:
artistname = (tags['albumartist'])
except KeyError:
artistname = (tags['artist'])
albumname = (tags['album'])
artistname = replace(artistname[0]).strip()
albumname = replace(albumname[0]).strip()
title = os.path.basename(mp3_path)
artist_dir = os.path.join(globalpath, artistname)
album_dir = os.path.join(artist_dir, albumname)
new_mp3_path = os.path.join(album_dir, title)
if not artistname in artist_list:
if not os.path.isdir(artist_dir):
os.makedirs(artist_dir)
artist_list.append(artistname)
if not albumname in album_list:
album_list.append(albumname)
if not os.path.isdir(album_dir):
os.makedirs(album_dir)
album_list.append(albumname)
try:
shutil.copyfile(mp3_path, new_mp3_path)
print(title + " is done.")
except shutil.SameFileError:
print(title + " is already exists.")
def data_check(file_list, path):
for i in file_list:
if os.path.isdir(os.path.join(path, i)):
new_path = os.path.join(path, i)
new_file_list = os.listdir(new_path)
data_check(new_file_list, new_path)
else:
arrange_data(os.path.join(path, i))
globalpath = r"楽曲が入っているフォルダ"
file_list = os.listdir(globalpath)
album_list = []
artist_list = []
data_check(file_list, globalpath)
引っかかったポイント
KeyError:が発生する
Windowsではファイル名として使えない無効文字\/:*?"<>|
があるのですが、アーティスト名やアルバム名の中に無効文字を含むものが複数ありました。こちらはre.sub
を利用して無効文字を_
に置き換えました。
ディレクトリpathに空白が入る
アーティスト名やアルバム名の末尾に空白が含まれているものがある場合、実際のフォルダ名とフォルダパスが不一致を起こして、読み込みエラーが発生しました。
こちらは.strip()
を利用して解決しました。
feat.問題
アーティスト名が「feat.〇〇」みたいになっていて、アーティスト名での振り分けが難しい楽曲に関してはアルバムアーティスト名を利用しました。アルバムアーティスト名がある楽曲はそれを優先し、ついてないものはアーティスト名を利用します。
おわりに
無事データを整理する事ができました。多少でもPythonが使えると便利ですね。
楽曲によっては正常に動作しないものがありそうですが、ローカルデータは全て処理できたので良しとします。
ありがとうございました!