put everything in main(), zero mypy issues

This commit is contained in:
Lynne Megido 2020-10-26 22:41:01 +10:00
parent a6409c9c35
commit 7334f67e45
Signed by: lynnesbian
GPG key ID: F0A184B5213D9F90

100
bcao.py
View file

@ -34,6 +34,7 @@ from PIL import Image
fully_supported: List[str] = ["ogg", "flac", "mp3", "m4a", "wav"]
MutagenFile = Union[MP3, FLAC, OggVorbis, mutagen.FileType]
MutagenTags = Union[mutagen.id3.ID3Tags, mutagen.mp4.Tags, mutagen.oggvorbis.OggVCommentDict]
args: argparse.Namespace
class SongInfo:
tag_lookup: Dict[str, Dict[str, str]] = {
@ -61,6 +62,7 @@ class SongInfo:
if fallbacks is None:
die("Couldn't determine fallback tags!")
return # needed for mypy
# set default values for the tags, in case the file is missing any (or all!) of them
self.tags: Dict[str, str] = {
"track": fallbacks.group("track"),
@ -210,40 +212,43 @@ def sanitise(in_str: str) -> str:
return re.sub(r"[?\\/:|*\"<>]", "_", in_str)
return in_str
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(usage='%(prog)s zip [options]',
def main():
# noinspection PyTypeChecker
parser = argparse.ArgumentParser(usage='%(prog)s zip [options]',
formatter_class=argparse.RawTextHelpFormatter,
description="Extracts the given zip file downloaded from Bandcamp and organises it.",
epilog=f"Cover art can only be embedded in files of the following types: {', '.join(fully_supported).upper()}.\n"
"If the song is in any other format, %(prog)s will behave as though you passed '-c n', "
"but will otherwise work normally.\nIf the song files contain no metadata, %(prog)s will attempt "
"to parse the song's filenames to retrieve the artist, album, title, and track number.")
parser.add_argument('zip', help='The zip file to use.')
parser.add_argument('-c', '--add-cover-images', dest='process_cover', default='w', choices=['n', 'a', 'w'],
"If the song is in any other format, %(prog)s will behave as though you passed '-c n', "
"but will otherwise work normally.\nIf the song files contain no metadata, %(prog)s will attempt "
"to parse the song's filenames to retrieve the artist, album, title, and track number.")
parser.add_argument('zip', help='The zip file to use.')
parser.add_argument('-c', '--add-cover-images', dest='process_cover', default='w', choices=['n', 'a', 'w'],
help="When to embed cover art into songs.\nOptions: [n]ever, [a]lways, [w]hen necessary.\nDefault: %(default)s")
parser.add_argument('-d', '--destination', dest='destination', default='/home/lynne/Music/Music/',
parser.add_argument('-d', '--destination', dest='destination', default='/home/lynne/Music/Music/',
help="The directory to organise the music into.\nDefault: %(default)s")
parser.add_argument('-q', '--quiet', dest='quiet', action='store_true',
parser.add_argument('-q', '--quiet', dest='quiet', action='store_true',
help='Disable non-error output and assume default artist name.')
parser.add_argument('-u', '--unsanitised', dest='sanitise', action='store_false',
parser.add_argument('-u', '--unsanitised', dest='sanitise', action='store_false',
help="Don't replace NTFS-unsafe characters with underscores. Not recommended.")
parser.add_argument('-t', '--threshold', dest='threshold', nargs=1, default=300,
parser.add_argument('-t', '--threshold', dest='threshold', nargs=1, default=300,
help="Maximum acceptable file size for cover art, in kilobytes.\nDefault: %(default)s")
args = parser.parse_args()
# convert args.threshold to bytes
args.threshold *= 1024
global args
args = parser.parse_args()
# convert args.threshold to bytes
args.threshold *= 1024
if not path.exists(args.zip):
if not path.exists(args.zip):
die(f"Couldn't find {args.zip}.", 2)
log("Extracting...")
tmp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory()
tmp: str = tmp_dir.name
cover: Optional[str] = None
song_names: List[str] = []
log("Extracting...")
tmp_dir: tempfile.TemporaryDirectory = tempfile.TemporaryDirectory()
tmp: str = tmp_dir.name
cover: Optional[str] = None
song_names: List[str] = []
with ZipFile(args.zip, 'r') as zip_file:
with ZipFile(args.zip, 'r') as zip_file:
for file in zip_file.namelist():
if re.match(r"^(.+ - ){2}\d{2,} .+\.(ogg|flac|alac|aiff|wav|mp3|m4a)$", file):
# bandcamp zips contains songs with names formatted like "Album - Artist - 01 Song.mp3"
@ -257,18 +262,18 @@ with ZipFile(args.zip, 'r') as zip_file:
cover = file
zip_file.extract(file, tmp)
# save the format of the songs (ogg, mp3, etc)
# we'll need this to know what metadata format we should write
song_format: str = path.splitext(song_names[0])[1][1:]
if song_format not in fully_supported:
# save the format of the songs (ogg, mp3, etc)
# we'll need this to know what metadata format we should write
song_format: str = path.splitext(song_names[0])[1][1:]
if song_format not in fully_supported:
log(f"Format {song_format} is not fully supported - cover images will not be modified", 1)
args.process_cover = 'n'
if cover is None:
if cover is None:
die("Unable to find cover image!")
# return # needed for mypy
return # needed for mypy
if args.process_cover != 'n':
if args.process_cover != 'n':
log("Resizing album art to embed in songs...")
with Image.open(str(Path(tmp, cover))) as image:
temp_cover: Path = Path(tmp, "cover-lq.jpg")
@ -352,13 +357,13 @@ if args.process_cover != 'n':
imageformat=MP4Cover.FORMAT_JPEG
)
artists: List[str] = []
album: Optional[str] = None
songs: Dict[str, str] = {}
zeroes = min(len(song_names), 2)
first_loop: bool = True
artists: List[str] = []
album: Optional[str] = None
songs: Dict[str, str] = {}
zeroes = min(len(song_names), 2)
first_loop: bool = True
for song_name in song_names:
for song_name in song_names:
song = SongInfo(Path(tmp, song_name))
if first_loop:
# the first item in the artists list should be the album artist
@ -373,14 +378,14 @@ for song_name in song_names:
if args.process_cover == 'a' or (args.process_cover == 'w' and song.has_cover() is False):
song.set_cover(embed_cover)
# remove duplicate artists
artists = list(dict.fromkeys(artists))
# remove duplicate artists
artists = list(dict.fromkeys(artists))
if len(artists) > 1 and "Various Artists" not in artists:
if len(artists) > 1 and "Various Artists" not in artists:
artists.append("Various Artists")
artist: Optional[str] = None
while artist is None:
artist: Optional[str] = None
while artist is None:
log("Artist directory:")
for i, artist_name in enumerate(artists):
log(f"{i+1}) {artist_name}")
@ -400,13 +405,16 @@ while artist is None:
else:
log(f"Please choose a number between 1 and {len(artists) + 1}")
destination: Path = Path(args.destination, artist, album)
log(f"Moving files to \"{destination}\"...")
os.makedirs(destination, exist_ok=True)
destination: Path = Path(args.destination, artist, album)
log(f"Moving files to \"{destination}\"...")
os.makedirs(destination, exist_ok=True)
for source_name, dest_name in songs.items():
for source_name, dest_name in songs.items():
shutil.move(str(Path(tmp, source_name)), str(Path(destination, dest_name)))
shutil.move(str(Path(tmp, cover)), str(Path(destination, cover)))
shutil.move(str(Path(tmp, cover)), str(Path(destination, cover)))
tmp_dir.cleanup()
log("Done!")
tmp_dir.cleanup()
log("Done!")
if __name__ == "__main__":
main()