Rewritten Musort for v1.0

This commit is contained in:
tdeerenberg
2023-11-25 01:10:06 +01:00
parent f243f6da08
commit fbc3c3aea3
10 changed files with 1750 additions and 187 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
src/__pycache__

View File

@ -1,12 +1,12 @@
https://user-images.githubusercontent.com/113618658/214463785-49c419e9-c959-4849-91d2-f3407ecaa73d.mp4
# Musort # Musort
Ogranize your music library. A Python3 program that renames all selected music/audio files in a folder with a specified naming convention. Names are generated from the metadata (ID3) from the audio files. Before using this program, use a metadata editor like MusicBrainz Picard, Beets or EasyTAG to add the correct metadata to the audio files. Musort: Effortlessly organize your music library with this Python3 program. Rename selected music/audio files in a folder using a customizable naming convention based on metadata (ID3) from the audio files. Ensure accurate metadata by using popular tools like MusicBrainz Picard, Beets, or EasyTAG before running Musort. Simplify your music organization and enhance file names for a more enjoyable library experience.
## Features ## Features
* Rename many audio files at once * Rename many audio files at once
* Rename all files in subdirectories as well (recursive) * Rename audio files in subdirectories as well (recursive)
* Choose the naming convention (ex. track.title.flac or artist.track.year.mp3) * Choose the naming convention (ex. track.title.flac or artist.track.year.mp3)
* Give a separator for the naming of the file (ex. track.title.flac or track_title.flac) * Give a separator for the naming of the file (ex. track.title.flac or track_title.flac)
* Works on all systems that can run Python * Works on all systems that can run Python
@ -21,13 +21,17 @@ Ogranize your music library. A Python3 program that renames all selected music/a
* AIFF/AIFF-C * AIFF/AIFF-C
## Dependencies ## Dependencies
**Note: When using the install script, TinyTag will be automatically installed** **Make sure to install these programs to be able to run Musort**
- [Python3](https://www.python.org/) - [Python3](https://www.python.org/)
- [TinyTag](https://pypi.org/project/tinytag/) (Installable from Python Package Index) - [Docker (Optional)](https://docker.com)
The Python3 library TinyTag is also used, but is already included in this repository. Therefore, there is no need to install TinyTag for only this project.
## Installation and Usage ## Installation and Usage
### Method 1: Run installation script (Unix/Linux based OS only) ### Method 1: Run installation script (Unix/Linux based OS only)
The installation script will move the python program to `~/.local/bin`. Make sure that `~/.local/bin` exists and that is added to $PATH.
The installation script will move the python program to `~/.local/bin`. The installation directory can be changed in the `install.sh` script. **Note: The installation directory should be added to $PATH**
``` Bash ``` Bash
git clone https://github.com/tdeerenberg/Musort.git git clone https://github.com/tdeerenberg/Musort.git
cd Musort.git cd Musort.git
@ -35,7 +39,10 @@ chmod +x install.sh
./install.sh ./install.sh
``` ```
After that, simply use the command `musort` to use the program. After that, simply use the command `musort` to use the program.
<hr>
### Method 2: Clone repo and run manually (All Operating Systems) ### Method 2: Clone repo and run manually (All Operating Systems)
Clone the repository and run the Python program Clone the repository and run the Python program
``` Bash ``` Bash
git clone https://github.com/tdeerenberg/Musort.git git clone https://github.com/tdeerenberg/Musort.git
@ -43,32 +50,42 @@ cd Musort
pip install requirements.txt pip install requirements.txt
``` ```
After that, run the program with `python3 musort.py`. After that, run the program with `python3 musort.py`.
<hr>
### Method 3: Docker installation ### Method 3: Docker installation
``` Bash ``` Bash
git clone https://github.com/tdeerenberg/Musort.git git clone https://github.com/tdeerenberg/Musort.git
cd Musort cd Musort
docker build -t musort . docker build -t musort .
``` ```
After the docker installation is complete, musort can be run with: `docker run --name musort --rm -v "/:/HostMountedFS" -it musort` After the Docker installation/build is complete, Musort can be run with:
> Tip: You could alias something like `alias musortd="docker run --name musort --rm -v "/:/HostMountedFS" -it musort"` then use `musortd` juse like `musort` usage is explained above `docker run --name musort --rm -v "[music_directory_host]:[music_directory_container]" -it musort [music_directory_container]`
## Manual (options and arguments) `musort --help` The music folder must be mounted to the Docker container, therefore the `-v` option must be used to mount the directory.
An example of running Musort in Docker, using `/home/user/music` as music folder:
`docker run --name musort --rm -v '/home/user/music:/music' -it musort /music`
## Manual with options and arguments (`musort --help`)
``` ```
USAGE: USAGE:
musort [DIRECTORY] [NAMING_CONVENTION] [OPTIONAL_OPTIONS]... musort [DIRECTORY] [OPTIONAL_PARAMETERS]
USAGE EXAMPLES: USAGE EXAMPLES:
musort ~/music track.title.year -s _ -r musort ~/music
musort /local/music disc.artist.title.album -r musort /local/music -f disc.artist.title.album -r
musort ~/my_music track.title musort ~/my_music -s _ -r
OPTIONAL OPTIONS: OPTIONAL OPTIONS:
-h, --help Show the help menu -h, --help Show the help menu
-f, --format set the naming convention (see 'NAMING CONVENTION:' below)
-s, --separator Set the separator for the filename (ex. '-s .' -> 01.track.flac and '-s -' -> 01-track.mp3) -s, --separator Set the separator for the filename (ex. '-s .' -> 01.track.flac and '-s -' -> 01-track.mp3)
Default separator ( . ) will be used if none is given Default separator '_' will be used if none is given
-r, --recursive Rename files in subdirectories as well -r, --recursive Rename files in subdirectories as well
-v, --version Prints the version number -v, --version Prints the version number
NAMING CONVENTION: NAMING CONVENTION:
FORMAT_OPTION.FORMAT_OPTION... The amount of format options does not matter. FORMAT_OPTION.FORMAT_OPTION... The amount of format options does not matter.
It can be one, two, three, even all of them. It can be one, two, three, even all of them.
@ -96,13 +113,13 @@ year year or date as string
## Possible features to add ## Possible features to add
* Rename single file * Rename single file
* Other installation methods (Like AUR, Docker, etc.) * Other installation methods (e.g. via AUR)
* Open for suggestions! * Open for suggestions!
* Feel free to open a pull request or issue! * Feel free to open a pull request or issue!
## Authors ## Authors
- [@tdeerenberg](https://www.github.com/tdeerenberg) - [@tdeerenberg](https://github.com/tdeerenberg)
## License ## License

View File

@ -1,17 +1,39 @@
FROM python:3.10-slim # Musort - Docker installation
# Copyright (C) 2023 tdeerenberg
#
# Sources on github:
# https://github.com/tdeerenberg/Musort
#
# Licensed under the GNU General Public License v3.0 (GPLv3)
# Copyright (C) 2023 tdeerenberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Probably should do update/upgrade for any CVEs
FROM python:3.11
# Update and upgrade packages
RUN apt-get update && apt-get upgrade -y
# Set working directory
WORKDIR / WORKDIR /
# Set up requirements
COPY requirements.txt requirements.txt
# hadolint ignore=DL3013
RUN python3 -m pip install pip --upgrade --no-cache-dir && \
python3 -m pip install -r requirements.txt --no-cache-dir
# Copy in code # Copy project
COPY ./src/musort-docker.py /musort.py COPY ./src/config.py /config.py
COPY ./src/variables.py /variables.py
COPY ./src/tinytag.py /tinytag.py
COPY ./src/musort.py /musort.py
# docker run --name musort --rm -it musort --help # docker run --name musort --rm -it musort --help
ENTRYPOINT ["python3", "/musort.py"] ENTRYPOINT ["python3", "/musort.py"]

View File

@ -1,5 +1,55 @@
#!/bin/bash #!/bin/bash
# Make sure to add ~/.local/bin to $PATH #
pip3 install -r requirements.txt # Musort - Install and Upgrade Script
cp src/musort.py ~/.local/bin/musort # Copyright (C) 2023 tdeerenberg
echo "IF NOT DONE ALREADY, ADD '~/.local/bin' TO $ PATH" #
# Sources on github:
# https://github.com/tdeerenberg/Musort
#
# Licensed under the GNU General Public License v3.0 (GPLv3)
# Copyright (C) 2023 tdeerenberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Define paths
install_path=~/.local/bin
script_name=musort
script_path=src/musort.py
script_config=src/config.py
script_tinytag=src/tinytag.py
script_variables=src/variables.py
# Check if script already exists
if [ -e "$install_path/$script_name" ]; then
read -p "Musort is already installed. Do you want to overwrite it with the new version? (y/n): " response
if [[ $response =~ ^[Yy]$ ]]; then
echo "Updating Musort..."
cp "$script_path" "$install_path/$script_name"
cp "$script_config" "$install_path/"
cp "$script_tinytag" "$install_path/"
cp "$script_variables" "$install_path/"
echo "Musort updated successfully!"
else
echo "Upgrade canceled. Musort remains unchanged."
fi
else
# Install Musort
cp "$script_path" "$install_path/$script_name"
cp "$script_config" "$install_path/"
cp "$script_tinytag" "$install_path/"
cp "$script_variables" "$install_path/"
echo "Musort installed successfully!"
fi
echo "If not done already, add '$install_path' to \$PATH"

View File

@ -1 +0,0 @@
TinyTag

43
src/config.py Normal file
View File

@ -0,0 +1,43 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Musort - A command-line tool for effortlessly organizing and renaming your music files based on metadata
# Copyright (C) 2023 tdeerenberg
#
# Sources on github:
# https://github.com/tdeerenberg/Musort
#
# Licensed under the GNU General Public License v3.0 (GPLv3)
# Copyright (C) 2023 tdeerenberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
# These are the default settings of Musort.
# Default settings are used when no parameters are given.
# The default settings may be changed to your liking.
#
# Change separator between the naming format
separator = "."
# Toggle recursively renaming though subdirectories
recursive = False
# Format for renaming music files
name_format = "track.title"
# Replacement for illegal characters
forbidden_char_replace = "_"

272
src/musort.py Executable file → Normal file
View File

@ -1,187 +1,151 @@
#!/usr/bin/env python #!/usr/bin/env python
#
# Licensed under GPLv3 # Musort - A command-line tool for effortlessly organizing and renaming your music files based on metadata
# Copyright (C) 2023 tdeerenberg # Copyright (C) 2023 tdeerenberg
#
# Sources on github:
# https://github.com/tdeerenberg/Musort
#
# Licensed under the GNU General Public License v3.0 (GPLv3)
# Copyright (C) 2023 tdeerenberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from tinytag import TinyTag
import os import os
import sys, getopt import sys
import getopt
import logging import logging
from config import *
from variables import *
from tinytag import TinyTag
supported_formats = ["flac", "mp3", "mp2", "mp1", "opus", "ogg", "wma"] class Musort:
def __init__(self):
"""Initial setup"""
self.recursive = recursive
self.separator = separator
self.format = name_format.split('.')
self.replace = forbidden_char_replace
self.directory = None
self.files = []
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] %(asctime)s - %(message)s')
version = "Musort v0.2 (c) tdeerenberg" def display_settings(self):
help=\ """Displays the settings"""
"""Musort (c) 2023 tdeerenberg (github.com/tdeerenberg) logging.info(f"Recursive renaming: '{self.recursive}'.")
logging.info(f"Separator: '{self.separator}'.")
logging.info(f"Format: {self.format}.")
DESCRIPTION: def get_files(self):
A Python3 program that renames all selected music/audio files in a folder with a specified naming convention """Check files from the given directory"""
if self.recursive:
self.files = [
os.path.join(root, filename)
for root, _, files in os.walk(self.directory)
for filename in files
if self.is_compatible(filename)
]
else:
self.files = [
os.path.join(os.path.abspath(self.directory), filename)
for filename in os.listdir(self.directory)
if self.is_compatible(filename)
]
USAGE: def is_compatible(self, filename):
musort [DIRECTORY] [NAMING_CONVENTION] [OPTIONAL_OPTIONS]... """Check if a file is one of the compatible music files based on the extension"""
file_extension = filename.split(".")[-1].lower()
return file_extension in supported_formats
USAGE EXAMPLES:
musort ~/music track.title.year -s _ -r
musort /local/music disc.artist.title.album -r
musort ~/my_music track.title
OPTIONAL OPTIONS:
-h, --help Show the help menu
-s, --separator Set the separator for the filename (ex. '-s .' -> 01.track.flac and '-s -' -> 01-track.mp3)
Default separator ( . ) will be used if none is given
-r, --recursive Rename files in subdirectories as well
-v, --version Prints the version number
NAMING CONVENTION:
FORMAT_OPTION.FORMAT_OPTION... The amount of format options does not matter.
It can be one, two, three, even all of them.
(See FORMAT OPTIONS below for all options)
FORMAT OPTIONS:
album album as string
albumartist album artist as string
artist artist name as string
audio_offset number of bytes before audio data begins
bitdepth bit depth for lossless audio
bitrate bitrate in kBits/s
comment file comment as string
composer composer as string
disc disc number
disc_total the total number of discs
duration duration of the song in seconds
filesize file size in bytes
genre genre as string
samplerate samples per second
title title of the song
track track number as string
track_total total number of tracks as string
year year or date as string
SUPPORTED AUDIO FORMATS:
MP3/MP2/MP1 (ID3 v1, v1.1, v2.2, v2.3+)
Wave/RIFF
OGG
OPUS
FLAC
WMA
MP4/M4A/M4B/M4R/M4V/ALAC/AAX/AAXC"""
class Music:
def get_files(self, directory):
"""Scans the set directory for compatible audio files"""
self.files = list(map(lambda x: os.path.join(os.path.abspath(directory), x),os.listdir(directory)))
def get_files_recursive(self, directory):
"""Scans the set directory with subdirectory for compatible audio files"""
files = []
for a, b, c in os.walk(directory):
for d in c:
files.append(os.path.join(a,d))
self.files = files
def get_compatible(self):
music = []
for file in self.files:
file_extension = file.split(".")[-1]
if file_extension in supported_formats:
music.append(file)
self.compatible = music
def set_separator(self, sep):
"""Sets the separator for naming the audio files
(ex. 01-songname.mp3 or 01.songname.flac)"""
if sep in ['\\', '/', '|', '*', '<', '>', '"', '?']:
sep = "_"
logging.warning("Given separator contains invalid filename symbols, defaulting to .")
self.separator = sep
def set_format(self, val):
"""Sets the naming convention of the audio files
(ex. title-artist or artist-track-title)"""
self.format = val.split(".")
# Rename files
def rename_music(self): def rename_music(self):
"""Rename all compatible music files""" """Rename all provided music"""
for file in self.files:
# Get the file extension
filename, extension = os.path.splitext(file)
"""Get the file extension (ex. .flac, .mp3, etc)""" # Read metadata
for file in self.compatible:
ext = file.split(".")
ext = "." + ext[-1]
"""Let TinyTag module read the audio file"""
track = TinyTag.get(file) track = TinyTag.get(file)
"""Print the progress (Current track)""" # Show progress
logging.info(f"Current track: '{track.artist}' - '{track.title}'") logging.info(f"Renaming track: '{track.artist}' - '{track.title}'.")
# Use given format to set a new filename
rename = [] rename = []
for metadata_field in self.format:
"""Uses the given format to set new filename""" if metadata_field == "track":
for f in self.format:
if f == "track":
rename.append(f"{int(track.track):02}") rename.append(f"{int(track.track):02}")
else: else:
"""getattr gets attribute in track with name f""" rename.append(getattr(track, metadata_field))
rename.append(getattr(track, f))
rename.append(self.separator) rename.append(self.separator)
rename.pop() rename.pop()
rename = ''.join(rename)+ext
"""Replacing forbidden path characters in UNIX and Windows with underscores"""
for forbidden_character in ['\\', '/', '|', '*', '<', '>', '"', '?']:
if forbidden_character in rename:
logging.warning(f"Track contains forbidden path character ({forbidden_character}) in the new file name, replaced symbol with _")
rename = rename.replace(forbidden_character, "_")
"""Get the absolute path and rename the audio file""" # Replace forbidden characters
dst = os.path.join(os.path.abspath(os.path.dirname(file)), rename) rename = ''.join(rename)
os.rename(file, dst) for char in invalid_characters:
logging.info("Actions finished") rename = rename.replace(char, self.replace)
def main(): # Get absolute path and rename the audio file
level = logging.DEBUG new_path = os.path.join(os.path.abspath(os.path.dirname(file)), rename + extension)
logging.basicConfig(level=level, format='[%(levelname)s] %(asctime)s - %(message)s') os.rename(file, new_path)
"""Runs the whole program"""
argv = sys.argv[3:] logging.info(f"Track: '{track.artist}' - '{track.title}' contained an illegal character; the character has been replaced with: '{self.replace}'.")
logging.info("Renaming finished.")
def parse_args(argv, m_class):
"""Parse command line arguments"""
try: try:
opts, args = getopt.getopt(argv, "s:r", ["sep=", "recursive="]) opts, args = getopt.getopt(argv[2:], "s:rf:", ["separator=", "recursive", "format="])
except getopt.GetoptError as err: except getopt.GetoptError as error_mesg:
logging.error(err) logging.error(error_mesg)
exit() exit()
music = Music() # Handle command line arguments
for opt, arg in opts: for opt, arg in opts:
if opt in ['-s', '--separator']: if opt in ['-s', '--separator']:
logging.info(f"Using {arg} as separator") m_class.separator = arg if check_separator(arg) else default_separator
music.set_separator(arg) elif opt in ['-r', '--recursive']:
if opt in ['-r', '--recursive']: m_class.recursive = True
logging.info("Running recursively") elif opt in ['-f', '--format']:
music.get_files_recursive(sys.argv[1]) m_class.format = arg.split(".")
music.get_compatible()
if sys.argv[1] == "-h" or sys.argv[1] == '--help': # Handle help and version options
print(help) if '-h' in sys.argv or '--help' in sys.argv:
print(help_text)
exit() exit()
if sys.argv[1] == '-v' or sys.argv[1] == '--version': elif '-v' in sys.argv or '--version' in sys.argv:
print(version) print(version_text)
exit() exit()
try:
music.compatible
except:
logging.info("Running not recursively")
music.get_files(sys.argv[1])
music.get_compatible()
try:
music.separator
except:
logging.info("Using default separator")
music.set_separator(".")
music.set_format(sys.argv[2]) # Set directory
music.rename_music() m_class.directory = sys.argv[1]
if m_class.directory is None:
logging.error("Please provide a music directory.")
exit()
def check_separator(sep):
if any(char in separator for char in invalid_characters):
logging.warning(f"Given separator contains invalid filename symbols, defaulting to '{separator}'.\n")
return False
return True
def main():
m_class = Musort()
parse_args(sys.argv, m_class)
m_class.get_files()
m_class.display_settings()
m_class.rename_music()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

1394
src/tinytag.py Normal file

File diff suppressed because it is too large Load Diff

73
src/variables.py Normal file
View File

@ -0,0 +1,73 @@
#!/usr/bin/env python
#
# Musort - A command-line tool for effortlessly organizing and renaming your music files based on metadata
# Copyright (C) 2023 tdeerenberg
#
# Sources on github:
# https://github.com/tdeerenberg/Musort
#
# Licensed under the GNU General Public License v3.0 (GPLv3)
# Copyright (C) 2023 tdeerenberg
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
version_text = "Musort v1.0 (C) tdeerenberg"
supported_formats = ["flac", "mp3", "mp2", "mp1", "opus", "ogg", "wma"]
invalid_characters = ["\\", "/", "|", "*", "<", ">", '"', "'", "?"]
default_separator = '_'
help_text = \
"""Musort (c) 2023 tdeerenberg (github.com/tdeerenberg)
DESCRIPTION:
A command-line tool for effortlessly organizing and renaming your music files based on metadata
USAGE:
musort [DIRECTORY] [OPTIONAL_PARAMETERS]
USAGE EXAMPLES:
musort ~/music
musort /local/music -f disc.artist.title.album -r
musort ~/my_music -s _ -r
OPTIONAL OPTIONS:
-h, --help Show the help menu
-f, --format set the naming convention (see 'NAMING CONVENTION:' below)
-s, --separator Set the separator for the filename (ex. '-s .' -> 01.track.flac and '-s -' -> 01-track.mp3)
Default separator '_' will be used if none is given
-r, --recursive Rename files in subdirectories as well
-v, --version Prints the version number
NAMING CONVENTION:
FORMAT_OPTION.FORMAT_OPTION... The amount of format options does not matter.
It can be one, two, three, even all of them.
(See FORMAT OPTIONS below for all options)
FORMAT OPTIONS:
album album as string
albumartist album artist as string
artist artist name as string
audio_offset number of bytes before audio data begins
bitdepth bit depth for lossless audio
bitrate bitrate in kBits/s
comment file comment as string
composer composer as string
disc disc number
disc_total the total number of discs
duration duration of the song in seconds
filesize file size in bytes
genre genre as string
samplerate samples per second
title title of the song
track track number as string
track_total total number of tracks as string
year year or date as string"""