Automated music library format conversion with cuesheet detection, tagging support and configurable regex to obtain tags from filenames. Configuration with ini-files to support multiple locations with multiple quality requirements.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

253 lines
8.3 KiB

  1. CUE_SHEET_EXTENSION: str = ".cue"
  2. import os
  3. import shutil
  4. import logging
  5. import subprocess
  6. import sys
  7. import re
  8. from joblib import Parallel, delayed
  9. from configparser import ConfigParser
  10. from copy import deepcopy
  11. from pathlib import Path
  12. from typing import List, Optional, Tuple
  13. from ffcuesplitter.cuesplitter import FFCueSplitter
  14. CONFIG_FILE: str = sys.argv[1]
  15. config = ConfigParser()
  16. config.read(CONFIG_FILE)
  17. SRC_FOLDER: str = config.get("source", "folder")
  18. SRC_FILE_EXTS: List[str] = config.get("source", "file_exts").split(",")
  19. SRC_ICON_EXTS: List[str] = config.get("source", "icon_exts").split(",")
  20. DST_FOLDER: str = config.get("destination", "folder")
  21. DST_FILE_EXT: str = config.get("destination", "file_ext")
  22. DST_OVERWRITE: bool = config.get("libconv", "overwrite") == "true"
  23. DRY_RUN: bool = config.get("libconv", "dry_run") != "false"
  24. DEDUCE_METADATA: bool = config.get("libconv", "deduce_metadata") == "true"
  25. FFMPEG_LOCATION: str = config.get("ffmpeg", "location")
  26. FFMPEG_OPTS: List[str] = config.get("ffmpeg", "options").split(",")
  27. if DST_OVERWRITE:
  28. FFMPEG_OPTS.append("-y")
  29. logging.basicConfig(level=logging.INFO)
  30. cmd_list = []
  31. # ----------------------------------------------------------------- #
  32. # file and folder operations
  33. def copy(src: str, dst: str):
  34. logging.debug(f"copy {src} to {dst}")
  35. if not DRY_RUN:
  36. shutil.copyfile(src, dst, follow_symlinks=True)
  37. def mkdir(path: str):
  38. logging.debug(f"mkdir -r {path}")
  39. if not DRY_RUN:
  40. os.makedirs(path, exist_ok=True)
  41. def execute(command: List[str]):
  42. logging.debug(f"execute: {command}")
  43. cmd_list.append(command)
  44. # ----------------------------------------------------------------- #
  45. # cue sheet processing
  46. def cue_sheet_processor(path: str):
  47. dst_folder, preexisting = prepare_destination(path)
  48. if preexisting and not DST_OVERWRITE:
  49. logging.info(f"Album {path} already exists in output location and overwrite is disabled - skipping")
  50. return
  51. sheet = get_files_with_ext(path, [CUE_SHEET_EXTENSION])
  52. args = []
  53. if (len(sheet) != 1):
  54. logging.error(f"Expected exactly one but {path} contains {len(sheet)} cue sheets - trying file processor")
  55. file_processor(path)
  56. return
  57. try:
  58. data = FFCueSplitter(sheet[0], dry=DRY_RUN, outputdir=dst_folder, suffix=DST_FILE_EXT, overwrite=DST_OVERWRITE, ffmpeg_cmd=FFMPEG_LOCATION, ffmpeg_add_params=FFMPEG_OPTS)
  59. data.open_cuefile()
  60. args = data.ffmpeg_arguments()
  61. except:
  62. logging.error(f"Cuesheet parsing of {path} resulted in error. Trying file processor.")
  63. file_processor(path)
  64. return
  65. for arg in args:
  66. prepared = []
  67. prepared.append(FFMPEG_LOCATION)
  68. prepared.extend(arg[:-1])
  69. prepared.extend(FFMPEG_OPTS)
  70. prepared.append(f"\"{dst_folder}/{arg[-1]}.{DST_FILE_EXT}\"")
  71. execute(prepared)
  72. # ----------------------------------------------------------------- #
  73. # basic "folder contains audio files" processing
  74. def metadata_from_folder(path: str) -> List[str]:
  75. # this method has to be adapted to your individual folder structure
  76. # if there is none then do nothing as by default this is not used
  77. if not DEDUCE_METADATA:
  78. return ""
  79. path = os.path.normpath(path)
  80. folders = path.split(os.sep)
  81. logging.debug(f"deducing metadata from folders: {folders}")
  82. album_name = re.sub(r'[ ]*\(.*?\)', '', folders[-1])
  83. comment = folders[-1].replace(album_name, "").replace("(", "").replace(")", "").replace(" ","")
  84. return [
  85. f"-metadata ALBUM=\"{album_name}\"",
  86. f"-metadata COMMENT=\"{comment}\"",
  87. f"-metadata ARTIST=\"{folders[-2]}\"",
  88. f"-metadata GENRE=\"{folders[-3]}\""
  89. ]
  90. def metadata_from_file(filename: str) -> List[str]:
  91. title=""
  92. number=""
  93. if re.match(r'[0-9]+[ ]*-[ ]*[.]*', filename):
  94. logging.debug(f"file {filename} matched metadata regex #1")
  95. number = re.search(r'[0-9]+[ ]*-[ ]*', filename).group()
  96. title = filename.replace(number, "")
  97. number = re.sub(r'[ ]*-[ ]*', '', number)
  98. elif re.match(r'[0-9]+\.[ ]*[.]*', filename):
  99. logging.debug(f"file {filename} matched metadata regex #2")
  100. number = re.search(r'[0-9]+\.[ ]*', filename).group()
  101. title = filename.replace(number, "")
  102. number = re.sub(r'\.[ ]*', "", number)
  103. else:
  104. logging.debug(f"file {filename} matched no metadata regex")
  105. return [
  106. f"-metadata TITLE=\"{title}\"",
  107. f"-metadata TRACK=\"{number}\""
  108. ]
  109. def file_processor(path: str):
  110. dst_folder, preexisting = prepare_destination(path)
  111. if preexisting and not DST_OVERWRITE:
  112. logging.info(f"Album {path} already exists in output location and overwrite is disabled - skipping")
  113. return
  114. files = get_files_with_ext(path, SRC_FILE_EXTS)
  115. album_metadata = metadata_from_folder(path)
  116. for file in files:
  117. filename = get_filename(file, path)
  118. file_metadata = metadata_from_file(filename[1:])
  119. command = []
  120. command.append(FFMPEG_LOCATION)
  121. command.append("-i")
  122. command.append(f"\"{file}\"")
  123. command.extend(album_metadata)
  124. command.extend(file_metadata)
  125. command.extend(FFMPEG_OPTS)
  126. command.append(f"\"{dst_folder}/{filename}.{DST_FILE_EXT}\"")
  127. execute(command)
  128. # ----------------------------------------------------------------- #
  129. # Iteration over library folders and preparation
  130. def contains_extension(path: str, extensions: List[str]) -> bool:
  131. logging.debug(f"searching for extensions {extensions} in {path}")
  132. for root, dirs, files in os.walk(path):
  133. for file in files:
  134. for ext in extensions:
  135. if file.endswith(ext):
  136. logging.debug(f"file {file} matched extension '{ext}'")
  137. return True
  138. # needed to prevent recursive search
  139. break
  140. return False
  141. def get_files_with_ext(path: str, extensions: List[str]) -> List[str]:
  142. logging.debug(f"obtainint all files with extensions {extensions} from {path}")
  143. ret_files = []
  144. for root, dirs, files in os.walk(path):
  145. for file in files:
  146. for ext in extensions:
  147. if file.endswith(ext):
  148. logging.debug(f"file {file} matched extension '{ext}'")
  149. ret_files.append(os.path.join(root, file))
  150. # file is added now - no need to check the other extensions
  151. break
  152. # needed to prevent recursive search
  153. break
  154. return ret_files
  155. def prepare_destination(path: str) -> Tuple[str,bool]:
  156. images = get_files_with_ext(path, SRC_ICON_EXTS)
  157. sub_path = path.replace(SRC_FOLDER, "")
  158. new_path = DST_FOLDER + sub_path
  159. mkdir(new_path)
  160. existing: bool = len(get_files_with_ext(new_path, DST_FILE_EXT)) != 0
  161. for img in images:
  162. img_name = img.replace(path, "")
  163. new_img_path = new_path + img_name
  164. copy(img, new_img_path)
  165. return (new_path,existing)
  166. def get_filename(file: str, path: str) -> str:
  167. fname = file.replace(path, "")
  168. for ext in SRC_FILE_EXTS:
  169. fname = fname.replace("." + ext, "")
  170. return fname
  171. def scan_folder(path: str):
  172. for root, dirs, files in os.walk(path):
  173. for directory in dirs:
  174. process_folder(os.path.join(root, directory))
  175. # needed to prevent recursive search
  176. break
  177. def process_folder(path: str):
  178. logging.info(f"Visiting folder '{path}'")
  179. if contains_extension(path, [CUE_SHEET_EXTENSION]):
  180. logging.info("found cuesheet")
  181. cue_sheet_processor(path)
  182. elif contains_extension(path, SRC_FILE_EXTS):
  183. logging.info("found audio files")
  184. file_processor(path)
  185. else:
  186. logging.info("scanning subfolders")
  187. scan_folder(path)
  188. def execute_command_list():
  189. logging.info(f"Executing all {len(cmd_list)} commands")
  190. if DRY_RUN:
  191. logging.info("Skipping execution as we are dry-running. Printing list as debug-info.")
  192. logging.debug(str(cmd_list))
  193. return
  194. for cmd in cmd_list:
  195. cmd = " ".join(cmd)
  196. subprocess.run(cmd, shell=True)
  197. if __name__ == "__main__":
  198. logging.info(f"Using settings from {CONFIG_FILE}")
  199. if DRY_RUN:
  200. logging.info("Executing as DRY RUN")
  201. if DST_OVERWRITE:
  202. logging.info("Overwrite of existing files active")
  203. process_folder(SRC_FOLDER)
  204. execute_command_list()