initial commit

This commit is contained in:
ChaotiCryptidz 2022-02-04 13:32:22 +00:00
parent 3e0fe8166f
commit 36b902e227
13 changed files with 356 additions and 90 deletions

1
.envrc Normal file
View file

@ -0,0 +1 @@
use nix

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
__pycache__

View file

@ -1,92 +1,3 @@
# musicutil # musicutil
My tool for managing a local music library.
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.com/ChaotiCryptidz/musicutil.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.com/ChaotiCryptidz/musicutil/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

27
main.py Executable file
View file

@ -0,0 +1,27 @@
#!/usr/bin/env python3
import argparse
from musicutil.process_command import ProcessCommand
from musicutil.copy_command import CopyCommand
parser = argparse.ArgumentParser(description='Highly Opinionated Music ')
subparsers = parser.add_subparsers(dest="subparser_name")
process_parser = subparsers.add_parser('process')
process_parser.add_argument('src', type=str, help='src base music directory')
process_parser.add_argument('--dry-run', action='store_true')
copy_parser = subparsers.add_parser('copy')
copy_parser.add_argument('src', type=str, help='src base music directory')
copy_parser.add_argument('dest', type=str, help='dest music directory')
copy_parser.add_argument('--transcode-level', type=str, help='transcode level', default="copy")
copy_parser.add_argument('--skip-existing', action='store_true')
copy_parser.add_argument('--single-directory', action='store_true')
args = parser.parse_args()
if args.subparser_name == "process":
ProcessCommand(args.src, args.dry_run).run()
elif args.subparser_name == "copy":
CopyCommand(args.src, args.dest, args.transcode_level, args.single_directory, args.skip_existing).run()

147
musicutil/copy_command.py Normal file
View file

@ -0,0 +1,147 @@
from .types import File
from .scan_for_music import scan_for_music
from .load_tag_information import load_tag_information
from os import makedirs as make_directories
from os.path import exists as path_exists
from shutil import copy as copy_file
from copy import deepcopy as deep_copy
from subprocess import run as run_command
class CopyCommandState:
files: list[File] = []
transcoded_files: list[File] = []
class CopyCommand():
def __init__(self,
src: str,
dest: str,
transcode_level: str,
single_directory: bool,
skip_existing: bool
):
self.src = src
self.dest = dest
self.transcode_level = transcode_level
self.single_directory = single_directory
self.skip_existing = skip_existing
self.state = CopyCommandState()
def run(self):
print("Copying")
self.scan_for_music()
self.load_tag_information()
if self.single_directory:
self.check_for_collisions()
self.transcode_files()
def scan_for_music(self):
print("Scanning For Music")
self.state.files = scan_for_music(self.src)
def load_tag_information(self):
print("Loading Tag Information")
for file in self.state.files:
file.tags = load_tag_information(file)
def check_for_collisions(self):
print("Checking For Colisions")
seen = set()
dupes = []
for file in self.state.files:
filename = file.filename
if filename in seen:
dupes.append(filename)
else:
seen.add(filename)
if len(dupes) > 0:
print("Dupes Found:", dupes)
print("Cannot continue using --single-directory")
print("Please rename or remove duplicates")
exit()
def _transcode_copy(self, file: File):
src = file.join_path_to()
dest = file.join_filename() if self.single_directory else file.join_path_from_src()
dest = self.dest + "/" + dest
exists = path_exists(dest)
if (self.skip_existing and not exists) or not self.skip_existing:
print("Copying", src, "to", dest)
copy_file(
src,
dest,
)
else:
print("Skipping", src, "as already is copied at", dest)
self.state.transcoded_files.append(file)
def _transcode_with_level(self, file: File, level: str):
transcoded_file_extension = "opus"
src = file.join_path_to()
new_file = deep_copy(file)
new_file.extension = transcoded_file_extension
dest_filepath = new_file.join_filename() if self.single_directory else new_file.join_path_from_src()
dest_filepath = self.dest + "/" + dest_filepath
if (self.skip_existing and path_exists(dest_filepath)):
print("Skipping transcoding", dest_filepath)
self.state.transcoded_files.append(new_file)
return
bitrate = ""
if self.transcode_level == "high":
bitrate = "128K"
elif self.transcode_level == "medium":
bitrate = "96K"
elif self.transcode_level == "low":
bitrate = "64K"
print("Transcoding", src, "to", dest_filepath)
title = file.tags.title
artist = file.tags.artist
# TODO: check for errors
run_command([
"ffmpeg",
"-y",
"-hide_banner",
"-loglevel", "warning",
"-i", src,
"-c:a", "libopus",
"-b:a", bitrate,
"-metadata", f"title=\"{title}\"",
"-metadata", f"artist=\"{artist}\"",
dest_filepath
])
self.state.transcoded_files.append(new_file)
def transcode_files(self):
print("Transcoding Files")
if not self.single_directory:
directories = set()
for file in self.state.files:
directories.add(file.path_from_src)
for dir in directories:
make_directories(self.dest + "/" + dir, exist_ok=True)
if self.transcode_level == "copy":
for file in self.state.files:
self._transcode_copy(file)
return
elif self.transcode_level in ["high", "medium", "low"]:
for file in self.state.files:
self._transcode_with_level(file, self.transcode_level)

View file

@ -0,0 +1,20 @@
from .types import File, Tags
from mutagen.mp3 import EasyMP3 as MP3
from mutagen.flac import FLAC
def load_tag_information(file: File) -> Tags:
path = file.join_path_to()
tags = Tags()
if file.extension == "mp3":
mp3 = MP3(path)
tags.title = mp3["title"][0]
tags.artist = mp3["artist"][0]
elif file.extension == "flac":
flac = FLAC(path)
tags.title = flac["title"][0]
tags.artist = flac["artist"][0]
else:
print("Invalid / Unsupported Container")
exit()
return tags

7
musicutil/meta.py Normal file
View file

@ -0,0 +1,7 @@
supported_formats = ["mp3", "flac"]
sub_char = "_"
substitutions = {
"α": "a",
}

View file

@ -0,0 +1,62 @@
from .types import File, Tags
from .scan_for_music import scan_for_music
from .load_tag_information import load_tag_information
from .substitutions import reduce_to_ascii_and_substitute
from copy import deepcopy as deep_copy
from os import rename as rename_file
class ProcessCommandState:
files: list[File] = []
class ProcessCommand():
def __init__(self, src: str, dry_run: bool):
self.src = src
self.dry_run = dry_run
self.state = ProcessCommandState()
def run(self):
print("Renaming")
self.scan_for_music()
self.load_tag_information()
self.rename_files()
def scan_for_music(self):
print("Scanning For Music")
self.state.files = scan_for_music(self.src)
def load_tag_information(self):
print("Loading Tag Information")
for file in self.state.files:
tags = load_tag_information(file)
file.tags = tags
def _rename_file(self, file: File) -> File:
filename = file.filename
artist = file.tags.artist.replace("\n", "")
title = file.tags.title.replace("\n", "")
proper_filename = reduce_to_ascii_and_substitute(f"{artist} - {title}")
if filename != proper_filename:
print(f"Renaming \"{filename}\"", "to" + f"\"{proper_filename}\"" + "\n")
new_file = deep_copy(file)
new_file.filename = proper_filename
if not self.dry_run:
rename_file(file.join_path_to(), new_file.join_path_to())
# so that other steps after read the new file and not
# the orig pre-rename file when not dry run
return new_file
else:
return file
def rename_files(self):
print("Renaming files")
for file in self.state.files:
index = self.state.files.index(file)
self.state.files[index] = self._rename_file(file)

View file

@ -0,0 +1,17 @@
from pathlib import Path
from os.path import relpath
from .types import File
from .meta import supported_formats
def scan_for_music(src: str) -> list[File]:
files: list[File] = []
for format in supported_formats:
for path in Path(src).rglob("*." + format):
file = File()
file.path_to = str(path.parent)
file.path_from_src = relpath(str(path.parent), src)
file.filename = path.stem
file.extension = path.suffix.replace(".", "")
files.append(file)
return files

View file

@ -0,0 +1,11 @@
from .meta import sub_char, substitutions
from fold_to_ascii import fold
def reduce_to_ascii_and_substitute(filename: str):
filename = filename.replace("/", sub_char)
filename = filename.replace("\\", sub_char)
filename = filename.replace("\n", "")
for sub_before in substitutions.keys():
filename = filename.replace(sub_before, substitutions[sub_before])
filename = fold(filename)
return filename

43
musicutil/types.py Normal file
View file

@ -0,0 +1,43 @@
class Tags:
title = ""
artist = ""
def to_dict(self):
return {
"title": self.title,
"artist": self.artist
}
def __repr__(self):
return repr(self.to_dict())
class File:
filename = ""
extension = ""
# The path to the actual file
path_to = ""
# The path relative to the source directory
path_from_src = ""
tags = Tags()
def join_filename(self):
return f"{self.filename}.{self.extension}"
def join_path_to(self):
return f"{self.path_to}/{self.filename}.{self.extension}"
def join_path_from_src(self):
return f"{self.path_from_src}/{self.filename}.{self.extension}"
def to_dict(self):
return {
"filename": self.filename,
"extension": self.extension,
"path_to": self.path_to,
"path_from_src": self.path_from_src,
"tags": self.tags.to_dict(),
}
def __repr__(self):
return repr(self.to_dict())

View file

@ -0,0 +1,12 @@
{ lib, buildPythonPackage, fetchPypi }:
buildPythonPackage rec {
pname = "fold-to-ascii";
version = "1.0.2.post1";
src = fetchPypi {
pname = "fold_to_ascii";
inherit version;
sha256 = "sha256-cWegf9wjC9XfU4HpIh/iRtDv86hutn45NfkfWuyjUzo=";
};
}

7
shell.nix Normal file
View file

@ -0,0 +1,7 @@
{ pkgs ? import <nixpkgs> { } }:
let
fold-to-ascii = (py: py.callPackage ./nix-extra-deps/fold-to-ascii.nix { });
my_python = pkgs.python39.withPackages
(py: with py; [ py.mutagen (fold-to-ascii py) ]);
in pkgs.mkShell { packages = with pkgs; [ my_python ffmpeg ]; }