flacinfo/flacinfo.py

197 lines
5.5 KiB
Python
Raw Normal View History

2018-01-18 17:38:14 +01:00
#!/usr/bin/env python3
"""
flacinfo
A script analoguous to `mp3info`, allowing one to easily tag their music
collection, but for flac files.
"""
import argparse
2018-01-18 18:53:28 +01:00
import subprocess
import os
import sys
2018-01-18 17:38:14 +01:00
2018-01-18 19:06:26 +01:00
VORBIS_ARG_NAME = {
2021-03-21 23:18:36 +01:00
"title": "TITLE",
"track": "TRACKNUMBER",
"artist": "ARTIST",
"album": "ALBUM",
2021-03-21 23:21:32 +01:00
"albumartist": "ALBUMARTIST",
2021-03-21 23:18:36 +01:00
"albumnumber": "DISCNUMBER",
"genre": "GENRE",
"year": "DATE",
"comment": "COMMENT",
2018-01-18 19:06:26 +01:00
}
class NoSuchTag(Exception):
2021-03-21 23:53:20 +01:00
"""Raised when trying to reverse the `VORBIS_ARG_NAME` dict on an invalid tag name"""
def __init__(self, tag):
2021-03-21 23:53:20 +01:00
super().__init__()
self.tag = tag
def __str__(self):
return "No such Vorbis tag {}".format(self.tag)
2021-03-21 23:53:20 +01:00
class MetaflacError(Exception):
"""Raised when an invocation of metaflac failed."""
2021-03-21 23:53:20 +01:00
2018-01-18 17:38:14 +01:00
def argparser():
"""Parses the arguments from sys.argv"""
2018-01-18 17:38:14 +01:00
parser = argparse.ArgumentParser(
2018-01-18 22:36:19 +01:00
description="Edit flac files' metadata",
2021-03-21 23:18:36 +01:00
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")
2021-03-21 23:21:32 +01:00
parser.add_argument("-A", "--albumartist", help="Specify album artist")
2021-03-21 23:18:36 +01:00
parser.add_argument(
"file", nargs="+", metavar="FILE", help="The file(s) to work on"
)
2018-01-18 17:38:14 +01:00
return parser.parse_args()
2018-01-18 23:17:54 +01:00
def is_flac_file(path):
"""Checks whether `path` refers to an existing, writeable flac file"""
2018-01-18 18:53:28 +01:00
if not os.path.isfile(path) or not os.access(path, os.W_OK):
return False
2021-03-21 23:53:20 +01:00
try:
subprocess.run(
["metaflac", "--list", path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
except subprocess.CalledProcessError:
2018-01-18 18:53:28 +01:00
return False # Metaflac failed to list the files' metadata
return True
2018-01-18 23:17:54 +01:00
def make_metaflac_args(in_args):
out_args = []
2018-01-18 18:53:28 +01:00
2018-01-18 23:17:54 +01:00
for arg in in_args:
arg_val = in_args[arg]
if arg not in VORBIS_ARG_NAME or arg_val is None:
2018-01-18 18:53:28 +01:00
continue
2018-01-18 23:17:54 +01:00
arg_name = VORBIS_ARG_NAME[arg]
2018-01-18 18:53:28 +01:00
2021-03-21 23:18:36 +01:00
out_args.append("--remove-tag={}".format(arg_name))
if arg_val:
out_args.append("--set-tag={}={}".format(arg_name, arg_val))
2018-01-18 18:53:28 +01:00
2018-01-18 23:17:54 +01:00
return out_args
2018-01-18 18:53:28 +01:00
2018-01-18 23:17:54 +01:00
def edit_flac(args):
"""Perfoms the requested edition operations"""
2018-01-18 23:17:54 +01:00
metaflac_args = make_metaflac_args(args)
2021-03-21 23:18:36 +01:00
metaflac_args += args["file"]
metaflac_args.insert(0, "metaflac")
2021-03-21 23:53:20 +01:00
try:
subprocess.run(metaflac_args, check=True)
except subprocess.CalledProcessError as exn:
raise MetaflacError(
"Failed to edit tags: metaflac exited with error {}. Output:\n{}".format(
exn.returncode, exn.stderr
)
) from exn
2018-01-18 23:17:54 +01:00
def reverse_tag(vorbis_tag):
"""Reverses a Vorbis tag to an argument name"""
for tag in VORBIS_ARG_NAME:
2022-07-05 11:39:35 +02:00
if VORBIS_ARG_NAME[tag].upper() == vorbis_tag.upper():
return tag
2018-01-18 23:17:54 +01:00
raise NoSuchTag(vorbis_tag)
2018-01-18 23:17:54 +01:00
def get_tags(path):
"""Retrieves the relevant tags for a single file"""
2021-03-21 23:18:36 +01:00
metaflac_args = ["metaflac"]
for tag in VORBIS_ARG_NAME:
2021-03-21 23:18:36 +01:00
metaflac_args += ["--show-tag", VORBIS_ARG_NAME[tag]]
2018-01-18 23:17:54 +01:00
metaflac_args.append(path)
2021-03-21 23:53:20 +01:00
try:
metaflac_run = subprocess.run(metaflac_args, check=True, stdout=subprocess.PIPE)
except subprocess.CalledProcessError as exn:
raise MetaflacError(
(
"Failed to get tags for {}: metaflac exited with error {}."
"Output:\n{}"
).format(path, exn.returncode, exn.stderr)
) from exn
2021-03-21 23:18:36 +01:00
meta_out = metaflac_run.stdout.decode("utf-8")
output = {}
2021-03-21 23:18:36 +01:00
for line in meta_out.split("\n"):
split = line.split("=")
tag, value = split[0], "=".join(split[1:])
if not tag:
continue
2018-01-18 23:17:54 +01:00
tag = reverse_tag(tag)
output[tag] = value
return output
2018-01-18 23:17:54 +01:00
def show_tags(path):
"""Shows the relevant tags already present in the given flac file"""
2018-01-18 23:17:54 +01:00
tags = get_tags(path)
print("File: {}".format(path))
2021-03-21 23:53:20 +01:00
tag_len = max([len(tag) for tag in tags]) + 1
for tag in tags:
2021-03-21 23:53:20 +01:00
print((" {:<" + str(tag_len) + "} {}").format(tag + ":", tags[tag]))
print("")
2018-01-18 17:38:14 +01:00
def main():
"""Entrypoint function"""
args = vars(argparser())
2018-01-18 18:53:28 +01:00
2018-01-18 23:17:54 +01:00
has_errors = False
2021-03-21 23:18:36 +01:00
for cur_file in args["file"]:
2018-01-18 23:17:54 +01:00
if not is_flac_file(cur_file):
2021-03-21 23:18:36 +01:00
print(
(
"Error: file {} does not exist, or is not writeable by " "metaflac"
).format(cur_file),
file=sys.stderr,
)
2018-01-18 23:17:54 +01:00
has_errors = True
if has_errors:
2021-03-21 23:18:36 +01:00
print("One or more file cannot be manipulated. Aborting.", file=sys.stderr)
2018-01-18 18:53:28 +01:00
sys.exit(1)
2018-01-18 23:17:54 +01:00
edit_mode = False
for tag in VORBIS_ARG_NAME:
if args[tag] is not None:
2018-01-18 23:17:54 +01:00
edit_mode = True
break
2018-01-18 23:17:54 +01:00
if edit_mode:
edit_flac(args)
else:
2021-03-21 23:18:36 +01:00
for path in args["file"]:
2018-01-18 23:17:54 +01:00
show_tags(path)
2018-01-18 17:38:14 +01:00
2021-03-21 23:18:36 +01:00
if __name__ == "__main__":
2018-01-18 17:38:14 +01:00
main()