run formatter

This commit is contained in:
ChaotiCryptidz 2022-02-06 16:18:14 +00:00
parent 468dcf2f00
commit 791213481f
11 changed files with 108 additions and 46 deletions

View file

@ -21,4 +21,4 @@ if args.subparser_name == "process":
elif args.subparser_name == "copy": elif args.subparser_name == "copy":
CopyCommand(get_copy_args(args)).run() CopyCommand(get_copy_args(args)).run()
elif args.subparser_name == "transcode": elif args.subparser_name == "transcode":
TranscodeCommand(get_transcode_args(args)).run() TranscodeCommand(get_transcode_args(args)).run()

View file

@ -15,6 +15,7 @@ class CopyCommandState:
files: list[File] = [] files: list[File] = []
transcoded_files: list[File] = [] transcoded_files: list[File] = []
class CopyCommandArgs(): class CopyCommandArgs():
src: str src: str
dest: str dest: str
@ -24,6 +25,7 @@ class CopyCommandArgs():
skip_existing: bool skip_existing: bool
skip_replaygain: bool skip_replaygain: bool
def add_copy_command(subparsers): def add_copy_command(subparsers):
copy_parser = subparsers.add_parser('copy') copy_parser = subparsers.add_parser('copy')
copy_parser.add_argument( copy_parser.add_argument(
@ -53,6 +55,7 @@ def add_copy_command(subparsers):
'--single-directory', '--single-directory',
action='store_true') action='store_true')
def get_copy_args(args) -> CopyCommandArgs: def get_copy_args(args) -> CopyCommandArgs:
print(args) print(args)
command_args = CopyCommandArgs() command_args = CopyCommandArgs()
@ -65,6 +68,7 @@ def get_copy_args(args) -> CopyCommandArgs:
command_args.skip_replaygain = args.skip_replaygain command_args.skip_replaygain = args.skip_replaygain
return command_args return command_args
class CopyCommand(): class CopyCommand():
def __init__(self, args: CopyCommandArgs): def __init__(self, args: CopyCommandArgs):
self.args = args self.args = args
@ -137,7 +141,10 @@ class CopyCommand():
self.state.transcoded_files.append(file) self.state.transcoded_files.append(file)
def _transcode_with_config(self, file: File, trans_config: TranscodeConfig): def _transcode_with_config(
self,
file: File,
trans_config: TranscodeConfig):
src = file.join_path_to() src = file.join_path_to()
new_file = deep_copy(file) new_file = deep_copy(file)
@ -147,7 +154,8 @@ class CopyCommand():
) if self.args.single_directory else new_file.join_path_from_src() ) if self.args.single_directory else new_file.join_path_from_src()
dest_filepath = self.args.dest + "/" + dest_filepath dest_filepath = self.args.dest + "/" + dest_filepath
if (self.args.skip_existing and path_exists(dest_filepath)): if (self.args.skip_existing and path_exists(
dest_filepath)):
print("Skipping transcoding", dest_filepath) print("Skipping transcoding", dest_filepath)
self.state.transcoded_files.append(new_file) self.state.transcoded_files.append(new_file)
return return
@ -167,7 +175,8 @@ class CopyCommand():
directories.add(file.path_from_src) directories.add(file.path_from_src)
for dir in directories: for dir in directories:
make_directories( make_directories(
self.args.dest + "/" + dir, exist_ok=True) self.args.dest + "/" + dir,
exist_ok=True)
is_transcode_config_set = self.args.custom_transcoder_config is not None is_transcode_config_set = self.args.custom_transcoder_config is not None
@ -183,7 +192,8 @@ class CopyCommand():
trans_config = TranscodeConfig() trans_config = TranscodeConfig()
trans_config.load_from_file(f) trans_config.load_from_file(f)
else: else:
trans_config = get_transcode_config(self.args.transcode_preset) trans_config = get_transcode_config(
self.args.transcode_preset)
print(trans_config) print(trans_config)
@ -201,6 +211,7 @@ class CopyCommand():
print("Adding ReplayGain Tags") print("Adding ReplayGain Tags")
for file in self.state.files: for file in self.state.files:
print(f"Adding ReplayGain Tags to \"{file.filename}.{file.extension}\"") print(
f"Adding ReplayGain Tags to \"{file.filename}.{file.extension}\"")
do_replaygain(file) do_replaygain(file)

View file

@ -11,11 +11,13 @@ from os import rename as rename_file
class ProcessCommandState: class ProcessCommandState:
files: list[File] = [] files: list[File] = []
class ProcessCommandArgs: class ProcessCommandArgs:
src: str src: str
dry_run: bool dry_run: bool
skip_replaygain: bool skip_replaygain: bool
def add_process_command(subparsers): def add_process_command(subparsers):
process_parser = subparsers.add_parser('process') process_parser = subparsers.add_parser('process')
process_parser.add_argument( process_parser.add_argument(
@ -28,6 +30,7 @@ def add_process_command(subparsers):
'--skip-replaygain', '--skip-replaygain',
action='store_true') action='store_true')
def get_process_args(args) -> ProcessCommandArgs: def get_process_args(args) -> ProcessCommandArgs:
command_args = ProcessCommandArgs() command_args = ProcessCommandArgs()
command_args.src = args.src command_args.src = args.src
@ -35,6 +38,7 @@ def get_process_args(args) -> ProcessCommandArgs:
command_args.skip_replaygain = args.skip_replaygain command_args.skip_replaygain = args.skip_replaygain
return command_args return command_args
class ProcessCommand(): class ProcessCommand():
def __init__(self, args: ProcessCommandArgs): def __init__(self, args: ProcessCommandArgs):
self.args = args self.args = args
@ -45,7 +49,8 @@ class ProcessCommand():
self.scan_for_music() self.scan_for_music()
self.load_tag_information() self.load_tag_information()
self.rename_files() self.rename_files()
if (not self.args.skip_replaygain) and (not self.args.dry_run): if (not self.args.skip_replaygain) and (
not self.args.dry_run):
self.add_replaygain_tags() self.add_replaygain_tags()
def scan_for_music(self): def scan_for_music(self):
@ -96,6 +101,7 @@ class ProcessCommand():
print("Adding ReplayGain Tags") print("Adding ReplayGain Tags")
for file in self.state.files: for file in self.state.files:
print(f"Adding ReplayGain Tags to \"{file.filename}.{file.extension}\"") print(
f"Adding ReplayGain Tags to \"{file.filename}.{file.extension}\"")
do_replaygain(file) do_replaygain(file)

View file

@ -6,6 +6,7 @@ from ..transcode_presets import print_transcode_presets, transcode_presets
from pathlib import Path from pathlib import Path
from json import load as load_json_file from json import load as load_json_file
class TranscodeCommandArgs: class TranscodeCommandArgs:
src: str src: str
dest: str dest: str
@ -14,6 +15,7 @@ class TranscodeCommandArgs:
custom_transcoder_config_path: str custom_transcoder_config_path: str
skip_replaygain: bool skip_replaygain: bool
def add_transcode_command(subparsers): def add_transcode_command(subparsers):
transcode_parser = subparsers.add_parser('transcode') transcode_parser = subparsers.add_parser('transcode')
transcode_parser.add_argument( transcode_parser.add_argument(
@ -35,11 +37,12 @@ def add_transcode_command(subparsers):
transcode_parser.add_argument( transcode_parser.add_argument(
'--custom-transcoder-config', '--custom-transcoder-config',
type=str, type=str,
help='custom transcoder config') help='custom transcoder config')
transcode_parser.add_argument( transcode_parser.add_argument(
'--skip-replaygain', '--skip-replaygain',
action='store_true') action='store_true')
def get_transcode_args(args) -> TranscodeCommandArgs: def get_transcode_args(args) -> TranscodeCommandArgs:
command_args = TranscodeCommandArgs() command_args = TranscodeCommandArgs()
command_args.src = args.src command_args.src = args.src
@ -50,6 +53,7 @@ def get_transcode_args(args) -> TranscodeCommandArgs:
command_args.skip_replaygain = args.skip_replaygain command_args.skip_replaygain = args.skip_replaygain
return command_args return command_args
class TranscodeCommand: class TranscodeCommand:
def __init__(self, args: TranscodeCommandArgs): def __init__(self, args: TranscodeCommandArgs):
self.args = args self.args = args
@ -61,26 +65,28 @@ class TranscodeCommand:
print("Transcoding...") print("Transcoding...")
input_file = file_from_path(Path(self.args.src), "") input_file = file_from_path(Path(self.args.src), "")
if self.args.custom_transcoder_config_path is None or len(self.args.custom_transcoder_config_path) == 0: if self.args.custom_transcoder_config_path is None or len(
trans_config = get_transcode_config(self.args.transcode_preset) self.args.custom_transcoder_config_path) == 0:
trans_config = get_transcode_config(
self.args.transcode_preset)
else: else:
with open(self.args.custom_transcoder_config_path, "r+") as file: with open(self.args.custom_transcoder_config_path, "r+") as file:
trans_config = TranscodeConfig() trans_config = TranscodeConfig()
trans_config.load_from_file(file) trans_config.load_from_file(file)
output_file = file_from_path(Path(self.args.dest), "") output_file = file_from_path(
Path(self.args.dest), "")
if trans_config.file_extension != output_file.extension and not self.args.ignore_extension: if trans_config.file_extension != output_file.extension and not self.args.ignore_extension:
print( print(
f"{output_file.extension} is not the recommended "+ f"{output_file.extension} is not the recommended " +
f"extension for transcode config "+ f"extension for transcode config " +
f"please change it to {trans_config.file_extension} "+ f"please change it to {trans_config.file_extension} " +
f"or run with --ignore-extension" f"or run with --ignore-extension")
)
exit() exit()
transcode(input_file, trans_config, self.args.dest) transcode(input_file, trans_config, self.args.dest)
if not self.args.skip_replaygain: if not self.args.skip_replaygain:
print("Adding ReplayGain Tags") print("Adding ReplayGain Tags")
do_replaygain(output_file, False) do_replaygain(output_file, False)

View file

@ -11,4 +11,4 @@ substitutions = {
# Patch to whatever path ffmpeg is at # Patch to whatever path ffmpeg is at
ffmpeg_path = "ffmpeg" ffmpeg_path = "ffmpeg"
ffprobe_path = "ffprobe" ffprobe_path = "ffprobe"
r128gain_path = "r128gain" r128gain_path = "r128gain"

View file

@ -1,9 +1,13 @@
from functools import reduce from functools import reduce
def add_to_arr(arr: list[str], items: list[str]) -> list[str]:
def add_to_arr(
arr: list[str],
items: list[str]) -> list[str]:
for item in items: for item in items:
arr.append(item) arr.append(item)
# does not include copy # does not include copy
transcode_presets = {} transcode_presets = {}
@ -14,14 +18,30 @@ add_to_arr(transcode_presets["mp3"], [
f"mp3-v{quality}" for quality in range(0, 10) f"mp3-v{quality}" for quality in range(0, 10)
]) ])
# mp3 bitrates # mp3 bitrates
mp3_bitrates = [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320] mp3_bitrates = [
8,
16,
24,
32,
40,
48,
64,
80,
96,
112,
128,
160,
192,
224,
256,
320]
add_to_arr(transcode_presets["mp3"], [ add_to_arr(transcode_presets["mp3"], [
f"mp3-{bitrate}k" for bitrate in mp3_bitrates f"mp3-{bitrate}k" for bitrate in mp3_bitrates
]) ])
transcode_presets["opus"] = [] transcode_presets["opus"] = []
opus_bitrates = ["16", "24", "32", "64", "96", "128", "256"] opus_bitrates = ["16", "24", "32", "64", "96", "128", "256"]
add_to_arr(transcode_presets["opus"], [ add_to_arr(transcode_presets["opus"], [
f"opus-{bitrate}k" for bitrate in opus_bitrates f"opus-{bitrate}k" for bitrate in opus_bitrates
]) ])
@ -37,10 +57,10 @@ transcode_presets["speex"] = []
add_to_arr(transcode_presets["speex"], [ add_to_arr(transcode_presets["speex"], [
f"speex-q{quality}" for quality in range(0, 11) f"speex-q{quality}" for quality in range(0, 11)
]) ])
transcode_presets["g726"] = [] transcode_presets["g726"] = []
g726_bitrates = ["16", "24", "32", "40"] g726_bitrates = ["16", "24", "32", "40"]
add_to_arr(transcode_presets["g726"], [ add_to_arr(transcode_presets["g726"], [
f"g726-{bitrate}k" for bitrate in g726_bitrates f"g726-{bitrate}k" for bitrate in g726_bitrates
]) ])
@ -74,10 +94,13 @@ transcode_presets["vorbis"].sort()
transcode_presets["speex"].sort() transcode_presets["speex"].sort()
transcode_presets["g726"].sort() transcode_presets["g726"].sort()
def print_transcode_presets(): def print_transcode_presets():
for category in transcode_presets.keys(): for category in transcode_presets.keys():
print(f"Category {category}:") print(f"Category {category}:")
for preset in transcode_presets[category]: for preset in transcode_presets[category]:
print(f"- {preset}") print(f"- {preset}")
transcode_presets_list = reduce(lambda a, b: a+b, transcode_presets.values())
transcode_presets_list = reduce(
lambda a, b: a + b, transcode_presets.values())

View file

@ -3,7 +3,10 @@ from ..meta import r128gain_path, ffmpeg_path
from subprocess import run as run_command from subprocess import run as run_command
def do_replaygain(file: File, skip_if_existing: bool = True) -> None:
def do_replaygain(
file: File,
skip_if_existing: bool = True) -> None:
command_args = [ command_args = [
r128gain_path, r128gain_path,
"-f", ffmpeg_path, "-f", ffmpeg_path,
@ -11,6 +14,6 @@ def do_replaygain(file: File, skip_if_existing: bool = True) -> None:
file.join_path_to() file.join_path_to()
] ]
if skip_if_existing: if skip_if_existing:
command_args.append("-s") command_args.append("-s")
run_command(command_args) run_command(command_args)

View file

@ -7,6 +7,7 @@ from json import loads as load_json_string
from mutagen.mp3 import EasyMP3 as MP3 from mutagen.mp3 import EasyMP3 as MP3
from mutagen.flac import FLAC from mutagen.flac import FLAC
def load_tag_information_mutagen(file: File) -> Tags: def load_tag_information_mutagen(file: File) -> Tags:
path = file.join_path_to() path = file.join_path_to()
tags = Tags() tags = Tags()
@ -23,7 +24,6 @@ def load_tag_information_mutagen(file: File) -> Tags:
return tags return tags
def load_tag_information_ffmpeg(file: File) -> Tags: def load_tag_information_ffmpeg(file: File) -> Tags:
path = file.join_path_to() path = file.join_path_to()
tags = Tags() tags = Tags()
@ -35,8 +35,9 @@ def load_tag_information_ffmpeg(file: File) -> Tags:
"-show_format", "-show_format",
path path
] ]
ffprobe_output = run_command(command_args, capture_output=True).stdout ffprobe_output = run_command(
command_args, capture_output=True).stdout
data = load_json_string(ffprobe_output) data = load_json_string(ffprobe_output)
file_tags = data["format"]["tags"] file_tags = data["format"]["tags"]
@ -65,6 +66,7 @@ def load_tag_information_ffmpeg(file: File) -> Tags:
tags.artist = artist tags.artist = artist
return tags return tags
def load_tag_information(file: File) -> Tags: def load_tag_information(file: File) -> Tags:
try: try:
tags = load_tag_information_mutagen(file) tags = load_tag_information_mutagen(file)
@ -72,6 +74,7 @@ def load_tag_information(file: File) -> Tags:
except Exception as _: except Exception as _:
tags = load_tag_information_ffmpeg(file) tags = load_tag_information_ffmpeg(file)
return tags return tags
except: except BaseException:
print(f"Could not get tags for file {file.filename}. Exiting.") print(
f"Could not get tags for file {file.filename}. Exiting.")
exit() exit()

View file

@ -4,6 +4,7 @@ from os.path import relpath
from ..types import File from ..types import File
from ..meta import supported_formats from ..meta import supported_formats
def file_from_path(path: Path, src: str) -> File: def file_from_path(path: Path, src: str) -> File:
file = File() file = File()
file.path_to = str(path.parent) file.path_to = str(path.parent)
@ -13,6 +14,7 @@ def file_from_path(path: Path, src: str) -> File:
file.extension = path.suffix.replace(".", "") file.extension = path.suffix.replace(".", "")
return file return file
def scan_for_music(src: str) -> list[File]: def scan_for_music(src: str) -> list[File]:
files: list[File] = [] files: list[File] = []
for format in supported_formats: for format in supported_formats:

View file

@ -1,6 +1,7 @@
from ..meta import sub_char, substitutions from ..meta import sub_char, substitutions
from fold_to_ascii import fold from fold_to_ascii import fold
def reduce_to_ascii_and_substitute(filename: str): def reduce_to_ascii_and_substitute(filename: str):
filename = filename.replace("/", sub_char) filename = filename.replace("/", sub_char)
filename = filename.replace("\\", sub_char) filename = filename.replace("\\", sub_char)

View file

@ -6,6 +6,7 @@ from yaml import load as load_yaml_file
from yaml import Loader as YamlLoader from yaml import Loader as YamlLoader
from subprocess import run as run_command from subprocess import run as run_command
class TranscodeConfig: class TranscodeConfig:
use_quality = False use_quality = False
use_bitrate = False use_bitrate = False
@ -18,7 +19,9 @@ class TranscodeConfig:
channels = "" channels = ""
def load_from_file(self, file): def load_from_file(self, file):
self.load_from_dict(load_yaml_file(file, Loader=YamlLoader)) self.load_from_dict(
load_yaml_file(
file, Loader=YamlLoader))
def load_from_dict(self, data): def load_from_dict(self, data):
if "use_quality" in data: if "use_quality" in data:
@ -41,6 +44,7 @@ class TranscodeConfig:
self.channels = data["channels"] self.channels = data["channels"]
return self return self
def get_transcode_config(preset: str): def get_transcode_config(preset: str):
conf = TranscodeConfig() conf = TranscodeConfig()
if preset in preset_transcode_presets.keys(): if preset in preset_transcode_presets.keys():
@ -54,7 +58,7 @@ def get_transcode_config(preset: str):
"sample_rate": "8000", "sample_rate": "8000",
"channels": "1", "channels": "1",
"use_bitrate": True, "use_bitrate": True,
"bitrate": preset.replace("g726-", "") "bitrate": preset.replace("g726-", "")
}) })
return conf return conf
@ -64,7 +68,7 @@ def get_transcode_config(preset: str):
"file_extension": "opus", "file_extension": "opus",
"encoder": "libopus", "encoder": "libopus",
"use_bitrate": True, "use_bitrate": True,
"bitrate": preset.replace("opus-", "") "bitrate": preset.replace("opus-", "")
}) })
return conf return conf
@ -81,8 +85,8 @@ def get_transcode_config(preset: str):
return conf return conf
elif preset.startswith("mp3-") and preset.endswith("k"): elif preset.startswith("mp3-") and preset.endswith("k"):
conf.use_bitrate = True conf.use_bitrate = True
conf.bitrate = preset.replace("mp3-", "") conf.bitrate = preset.replace("mp3-", "")
return conf return conf
if preset.startswith("vorbis-q"): if preset.startswith("vorbis-q"):
conf.load_from_dict({ conf.load_from_dict({
@ -107,7 +111,11 @@ def get_transcode_config(preset: str):
print("Unknown Level") print("Unknown Level")
exit() exit()
def transcode(file: File, config: TranscodeConfig, dest: str):
def transcode(
file: File,
config: TranscodeConfig,
dest: str):
ffmpeg_command = [ ffmpeg_command = [
ffmpeg_path, ffmpeg_path,
"-y", "-y",
@ -132,14 +140,13 @@ def transcode(file: File, config: TranscodeConfig, dest: str):
ffmpeg_command.append("-ac") ffmpeg_command.append("-ac")
ffmpeg_command.append(config.channels) ffmpeg_command.append(config.channels)
if config.use_quality: if config.use_quality:
ffmpeg_command.append("-q:a") ffmpeg_command.append("-q:a")
ffmpeg_command.append(config.quality) ffmpeg_command.append(config.quality)
elif config.use_bitrate: elif config.use_bitrate:
ffmpeg_command.append("-b:a") ffmpeg_command.append("-b:a")
ffmpeg_command.append(config.bitrate) ffmpeg_command.append(config.bitrate)
else: else:
pass pass
ffmpeg_command.append(dest) ffmpeg_command.append(dest)