#!/usr/bin/env python3 """ flacinfo A script analoguous to `mp3info`, allowing one to easily tag their music collection, but for flac files. """ import argparse import subprocess import os import sys VORBIS_ARG_NAME = { 'title': 'TITLE', 'track': 'TRACKNUMBER', 'artist': 'ARTIST', 'album': 'ALBUM', 'albumnumber': 'DISCNUMBER', 'genre': 'GENRE', 'year': 'DATE', 'comment': 'COMMENT', } class NoSuchTag(Exception): def __init__(self, tag): self.tag = tag super(NoSuchTag, self).__init__() def __str__(self): return "No such Vorbis tag {}".format(self.tag) def argparser(): """ Parses the arguments from sys.argv """ parser = argparse.ArgumentParser( description="Edit flac files' metadata", epilog=('When no option modifying the tags is passed, the currently ' 'set tags are shown.')) parser.add_argument('-a', '--artist', help="Specify artist name") parser.add_argument('-c', '--comment', help="Specify an arbitrary comment") parser.add_argument('-g', '--genre', help="Specify genre (in plain text)") parser.add_argument('-l', '--album', help="Specify album name") parser.add_argument('-m', '--albumnumber', help="Specify album number") parser.add_argument('-n', '--track', help="Specify track number") parser.add_argument('-t', '--title', help="Specify track title") parser.add_argument('-y', '--year', help="Specify album year") parser.add_argument('file', nargs='+', metavar='FILE', help="The file(s) to work on") return parser.parse_args() def isFlacFile(path): """ Checks whether `path` refers to an existing, writeable flac file """ if not os.path.isfile(path) or not os.access(path, os.W_OK): return False flacRun = subprocess.run(['metaflac', '--list', path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if flacRun.returncode != 0: return False # Metaflac failed to list the files' metadata return True def makeMetaflacArgs(inArgs): outArgs = [] for arg in inArgs: argVal = inArgs[arg] if arg not in VORBIS_ARG_NAME or argVal is None: continue argName = VORBIS_ARG_NAME[arg] outArgs.append('--remove-tag={}'.format(argName)) outArgs.append("--set-tag={}={}".format(argName, argVal)) return outArgs def editFlac(args): """ Perfoms the requested edition operations """ metaflacArgs = makeMetaflacArgs(args) metaflacArgs += args.file metaflacArgs.insert(0, 'metaflac') metaflacRun = subprocess.run(metaflacArgs) if metaflacRun.returncode != 0: print(('\n\nMetaflac exited with return code {}. There was an error ' 'during the execution, you should look at the output to ' 'investigate it.').format(metaflacRun.returncode), file=sys.stderr) sys.exit(metaflacRun.returncode) def reverseTag(vorbisTag): """ Reverses a Vorbis tag to an argument name """ for tag in VORBIS_ARG_NAME: if VORBIS_ARG_NAME[tag] == vorbisTag: return tag raise NoSuchTag(vorbisTag) def getTags(path): """ Retrieves the relevant tags for a single file """ metaflacArgs = ['metaflac'] for tag in VORBIS_ARG_NAME: metaflacArgs += ['--show-tag', VORBIS_ARG_NAME[tag]] metaflacArgs.append(path) metaflacRun = subprocess.run(metaflacArgs, stdout=subprocess.PIPE) metaOut = metaflacRun.stdout.decode('utf-8') output = {} for line in metaOut.split('\n'): split = line.split('=') tag, value = split[0], '='.join(split[1:]) if not tag: continue tag = reverseTag(tag) output[tag] = value return output def showTags(path): """ Shows the relevant tags already present in the given flac file """ tags = getTags(path) print("File: {}".format(path)) maxLen = max([len(tag) for tag in tags]) for tag in tags: print(' {}: {}{}'.format(tag, ' '*(maxLen - len(tag)), tags[tag])) print("") def main(): args = vars(argparser()) hasErrors = False for cFile in args['file']: if not isFlacFile(cFile): print(("Error: file {} does not exist, or is not writeable by " "metaflac").format(cFile), file=sys.stderr) hasErrors = True if hasErrors: print("One or more file cannot be manipulated. Aborting.", file=sys.stderr) sys.exit(1) editMode = False for tag in VORBIS_ARG_NAME: if args[tag] is not None: editMode = True break if editMode: editFlac(args) else: for path in args['file']: showTags(path) if __name__ == '__main__': main()