Installing Python 3 and music21 using Homebrew and pip3

In this blog post I’m going to explain how the Python library music21 can be installed in conjuction with Python 3 and its dependencies matplotlib, numpy and scipy on Mac OS X. It can also be used as a tutorial for installing any other Python libraries/modules as well.

The Problem

Initially, on my system there were two parallel Python 2 and Pyton 3 installations. The music21 installer chose Python 2 as default installation target. In order to use music21 in conjuction with Python 3, I tried to install it using the command

1
pip3 install music21

which worked fine. However, when I tried to use the plotting capabilities of music21 an error occured due to the missing modules matplotlib, numpy and scipy. When trying to install matplotlib issuing

1
pip3 install matplotlib

the following error occurred:

SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel.

Installing Python 3 using Homebrew

My final solution to this problem was to set up a new Python 3 installation using  Homebrew. This is done by installing Homebrew (if you haven’t got it yet):

1
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Python 3 is installed using the command

1
brew install python

Note: Previously, the formula name was python3 but was renamed to python as Python 3 is now the official default version. The old version can be installed using brew install python@2.

If you already have Python 3 installed, Homebrew will not be able to create symlinks to the python binaries since they already exist. To overwrite the existing symlinks (and thus to set the Homebrew Python as default interpreter for your system) you have to execute this command:

1
brew link --overwrite python

Now, symlinks to the new python installation are created under /usr/local/bin.

By the way: python updates can now be installed by simply executing

1
brew upgrade python

Adjusting the $PATH Variable

In some cases it might be required to tweak the settings of the $PATH environment variable, namely if the old Python 3 installation is still preferred by the system because of a $PATH entry with higher priority. To check if this step is necessary, type:

1
which python3

If the output is /usr/local/bin/python3, you can proceed to the next section. Otherwise, check the contents of your $PATH variable with this command:

1
echo $PATH

which might look like this:

/Library/Frameworks/Python.framework/Versions/3.4/bin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/subversion/bin:/sw/bin:/sw/sbin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:

As you may notice, the old interpreter entry /Library/Frameworks/Python.framework/Versions/3.4/bin precedes /usr/local/bin. To give priority to the new Python 3 interpreter, change the order of the paths, ensuring that /usr/local/bin precedes other python paths:

1
export PATH=/usr/local/bin:[more path elements here]

This command changes the $PATH settings for the current shell session only. If you want to make the path adjustments persistent, add the command to the file .bash_profile in your user home folder. It is also possible to reuse the current value of the variable:

1
export PATH="/usr/local/bin:$PATH"

After that, our Python 3 installed with Homebrew should now be the default system interpreter. Verify this with

1
which pip3

which should echo /usr/local/bin/pip3, which is in turn a symlink to the Homebrew cellar (the place where Homebrew installs modules/packages).

Installing the Dependencies

Now you should be able to install music21 and the dependencies using pip3:

1
2
3
pip3 install music21
pip3 install matplotlib # this will install numpy automatically
pip3 install scipy

I hope this will help you to install a clean music21 environment. No go have fun with musical analysis and plotting 🙂

Displaying Tracks of your Music Library Filtered by Bit Rate

If you prefer managing your music in the form of audio files on your computer, your collection has probably grown over the past few years and at the same time encoding standards have improved and expectations of sound quality have risen. In most cases, the contained audio files have different sound qualities regarding their bit rates. My motivation was to display a list of files in my music collection which have a bit rate equal to or higher than 256 kbit/s.

To achieve this, I looked for command line tools that display metadata for audio files including their bit rate. For Mac OS X I found the command afinfo which works out of the box:

afinfo myFile.mp3 | grep "bit rate"

The output looks similar to this:

bit rate: 320000 bits per second

If you are using another operating system, you can check for the following commands and/or install them:

1
2
3
4
5
file <fileName> (Ubuntu)
mp3info -r a -p "%f %r\n" <fileName>
mediainfo <fileName> | grep "Bit rate"
exiftool -AudioBitrate <fileName>
mpg123 -t <fileName>

My goal was to develop a program that crawls through my whole audio collection, checks the bit rate for every file and outputs a list containing only files with high bit rate. I wrote a Python script which does exactly that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'''
Created on 25.04.2015
 
@author: dave
'''
 
import sys
import os
import subprocess
import re
 
# console command to display properties about your media files
# afinfo works on Mac OS X, change for other operating systems
infoConsoleCommand = 'afinfo'
 
# regular expression to extract the bit rate from the output of the program 
pattern = re.compile('(.*)bit rate: ([0-9]+) bits per second(.*)', re.DOTALL)
 
def filterFile(path):
    '''
    Executes the configured info program to output properties of a media file.
    Grabs the output, filters the bit rate via a regular expression and displays the
    bit rate and the file path in case the bit rate is >= 256k
    Returns True in case the file has a high bit rate, False otherwise
    '''
    process = subprocess.Popen([infoConsoleCommand, path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = process.communicate()
    match = pattern.match(str(out))
    if match != None:
        bitRateString = match.group(2)
        bitRate = int(bitRateString)
        if bitRate >= 256000:
            print("bit rate",bitRate,":",path)
            return True
    return False
 
def scanFolder(rootFolder):
    '''
    Recursively crawls through the files of the given root folder
    '''
    numFiles = 0
    numFilesFiltered = 0
    for root, subFolders, files in os.walk(rootFolder):
        for file in files:
            numFiles = numFiles + 1
            path = os.path.join(root,file)
            if filterFile(path):
                numFilesFiltered = numFilesFiltered + 1
    print("Scanned {} files from which {} were filtered.".format(numFiles, numFilesFiltered))
 
# main program
if len(sys.argv) != 2:
    print("Usage: MP3ByBitrateFilter ")
    sys.exit(1)
 
rootFolder = sys.argv[1]
scanFolder(rootFolder)

The root folder of your music library can be given as command line argument. The programs walks through the folder recursively and executes the command line program to display the bit rate in a separate process. It grabs the output and filters the bit rate from the output using a regular expression. The bit rate and the path of the file are displayed in case the bit rate is >= 256 kbit/s. A summary is also displayed showing the total number of files and number of filtered files.

Of course you can extend the filter criteria by adjusting the script to extract other information than the bit rate from the info command.