Skip to content

Instantly share code, notes, and snippets.

@ril3y
Created January 21, 2023 17:24
Show Gist options
  • Save ril3y/be7761c06fc262d9fe8ed01bc081764f to your computer and use it in GitHub Desktop.
Save ril3y/be7761c06fc262d9fe8ed01bc081764f to your computer and use it in GitHub Desktop.
A script to sort a directory full of m4b files into their proper folder/album directories that the audiobookshelf application wants.
import os
import re
import sys
import argparse
import mutagen
import logging
parser = argparse.ArgumentParser(description='Process m4b files.')
parser.add_argument('-s', '--source', dest='source_folder', required=True, help='Source folder containing m4b files')
parser.add_argument('-d', '--destination', dest='destination_folder', required=True, help='Destination folder for new directories')
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
root_dir = args.source_folder
destination_folder = args.destination_folder
if not os.path.exists(root_dir):
logging.error(f'Source folder {root_dir} does not exist')
sys.exit(1)
if not os.path.exists(destination_folder):
logging.error(f'Destination folder {destination_folder} does not exist')
sys.exit(1)
for subdir, dirs, files in os.walk(root_dir):
for file in files:
if file.endswith('.m4b'):
file_path = os.path.join(subdir, file)
try:
audio = mutagen.File(file_path)
except Exception as e:
logging.error(f"There was an error parsing the m4b file: {file}, {e}")
logging.error(f"Skipping file: {file}. Continuing....")
continue
album_artist = audio.get("\xa9ART", ["Unknown"])[0]
album_artist_dir = os.path.join(destination_folder, album_artist)
if not os.path.exists(album_artist_dir):
os.mkdir(album_artist_dir)
name = audio.get("\xa9nam", ["Unknown"])[0]
album = audio.get("\xa9alb", ["Unknown"])[0]
book_match = re.search(r'book (\d+)', album, re.IGNORECASE)
if book_match:
book_number = book_match.group(1)
name_dir = os.path.join(album_artist_dir, 'Book ' + book_number + ' - ' + name)
else:
name_dir = os.path.join(album_artist_dir, name)
if not os.path.exists(name_dir):
os.mkdir(name_dir)
os.rename(file_path, os.path.join(name_dir, file))
logging.info(f"Sorted {file_path}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment