Skip to content

Instantly share code, notes, and snippets.

@aperezdc
Created November 15, 2011 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aperezdc/1368426 to your computer and use it in GitHub Desktop.
Save aperezdc/1368426 to your computer and use it in GitHub Desktop.
#! /usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Traverse a directory tree, picking embedded pictures from .MP3 and .M4A audio
# saving them to a “cover.{png,jpg,bmp}” (as long as the file does *not* exist)
# and then removing the embedded pictures from the audio file.
#
# Requires the Mutagen tag edition library: https://code.google.com/p/mutagen/
# Most distributions ship in a package called “python-mutagen“.
#
from os import path as P
import os, sys
import mutagen
PIC_TAGS = (
"PIC", u"PIC", u"PIC:",
"APIC", u"APIC", u"APIC:",
)
def handle_dir(path, files):
for fpath in (P.join(path, f) for f in files):
try:
fileinfo = mutagen.File(fpath)
except Exception, e:
print >> sys.stderr, "%s" % e
continue
for tag in PIC_TAGS:
if tag in fileinfo.tags:
pic_data = fileinfo.tags.get(tag)
pic_mime = pic_data.mime.lower()
pic_path = None
if pic_mime == "image/png":
pic_path = P.join(path, "cover.png")
elif pic_mime == "image/bmp":
pic_path = P.join(path, "cover.bmp")
elif pic_mime == "image/jpeg" or pic_mime == "image/jpg":
pic_path = P.join(path, "cover.jpg")
else:
print >> sys.stderr, " - %r unrecognized type %r" % (fpath, pic_mime)
if pic_path is not None and not P.isfile(pic_path):
print "Writing %r" % pic_path
with file(pic_path, "wb") as pic_fd:
pic_fd.write(pic_data.data)
print "Removing picture from %r" % fpath
for tag in PIC_TAGS:
fileinfo.tags.delall(tag)
fileinfo.tags.save()
fileinfo.save()
def walk_and_handle(path, cb=handle_dir):
for dirpath, dirnames, filenames in os.walk(path):
audios = [f for f in filenames
if f.lower().endswith(".mp3")
or f.lower().endswith(".m4a")]
if len(audios): cb(dirpath, audios)
if __name__ == "__main__":
import sys
if len(sys.argv) == 2:
walk_and_handle(sys.argv[1])
else:
raise SystemExit("Usage: %s <path>" % sys.argv[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment