Skip to content

Instantly share code, notes, and snippets.

@izderadicka
Created August 20, 2018 07:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save izderadicka/6dae6b65acd9ace6a885f17e97e6ca28 to your computer and use it in GitHub Desktop.
Save izderadicka/6dae6b65acd9ace6a885f17e97e6ca28 to your computer and use it in GitHub Desktop.
Extract cover images from mp3 files within directory
#! /usr/bin/env python3
import argparse
import os
import subprocess
import logging
log = logging.getLogger()
def main():
ap = argparse.ArgumentParser()
ap.add_argument("root_directory", help="directory to start in")
ap.add_argument("--debug", action="store_true", help="debug logging")
args = ap.parse_args()
logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARN)
log.debug("Extracting covers in directory {}".format(args.root_directory))
for (dirpath, _dirs, files) in os.walk(args.root_directory):
log.debug("Processing directory {}".format(dirpath))
images = filter(lambda x: x.lower().endswith(("jpeg", "jpg", "gif", "png")), files)
has_images = sum(1 for _ in images)
if has_images == 0:
tracks = list(filter(lambda x: x.lower().endswith("mp3"), files))
tracks.sort()
first_track = tracks[0] if len(tracks) else None
if first_track:
log.debug("No images in directory {}, will try to extract from {}".format(dirpath, first_track))
f = os.path.join(dirpath, first_track)
c = os.path.join(dirpath, "cover.jpg")
ret_code = subprocess.call(["ffmpeg","-i", f, c])
if ret_code != 0:
log.error("Extraction failed with code {}".format(ret_code))
else:
log.debug("There are already some images in this directory")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment