Previous topic

music21.contour

Next topic

music21.converter.subConverters

Table Of Contents

Table Of Contents

This Page

music21.converter

music21.converter contains tools for loading music from various file formats, whether from disk, from the web, or from text, into music21.stream.:class:~music21.stream.Score objects (or other similar stream objects).

The most powerful and easy to use tool is the parse() function. Simply provide a filename, URL, or text string and, if the format is supported, a Score will be returned.

This is the most general public interface for all formats. Programmers adding their own formats to the system should provide an interface here to their own parsers (such as humdrum, musicxml, etc.)

The second and subsequent times that a file is loaded it will likely be much faster since we store a parsed version of each file as a “pickle” object in the temp folder on the disk.

>>> s = converter.parse('d:/mydocs/schubert.krn')
>>> s
<music21.stream.Score ...>

Functions

music21.converter.parse(value, *args, **keywords)

Given a file path, encoded data in a Python string, or a URL, attempt to parse the item into a Stream. Note: URL downloading will not happen automatically unless the user has set their Environment “autoDownload” preference to “allow”.

Keywords can include number which specifies a piece number in a file of multipiece file.

format specifies the format to parse the line of text or the file as.

A string of text is first checked to see if it is a filename that exists on disk. If not it is searched to see if it looks like a URL. If not it is processed as data.

PC File:

>>> s = converter.parse(r'c:\users\myke\desktop\myfile.xml') 

Mac File:

>>> s = converter.parse('/Users/cuthbert/Desktop/myfile.xml') 

URL:

>>> s = converter.parse('http://midirepository.org/file220/file.mid') 

Data is preceded by an identifier such as “tinynotation:”

>>> s = converter.parse("tinyNotation: 3/4 E4 r f# g=lastG trip{b-8 a g} c")
>>> s.getElementsByClass(meter.TimeSignature)[0]
<music21.meter.TimeSignature 3/4>

or the format can be passed directly:

>>> s = converter.parse("2/16 E4 r f# g=lastG trip{b-8 a g} c", format='tinyNotation')
>>> s.getElementsByClass(meter.TimeSignature)[0]
<music21.meter.TimeSignature 2/16>
music21.converter.parseFile(fp, number=None, format=None, forceSource=False)

Given a file path, attempt to parse the file into a Stream.

music21.converter.parseData(dataStr, number=None, format=None)

Given musical data represented within a Python string, attempt to parse the data into a Stream.

music21.converter.parseURL(url, number=None, format=None, forceSource=False)

Given a URL, attempt to download and parse the file into a Stream. Note: URL downloading will not happen automatically unless the user has set their Environment “autoDownload” preference to “allow”.

music21.converter.freeze(streamObj, fmt=None, fp=None, fastButUnsafe=False, zipType='zlib')

Given a StreamObject and a file path, serialize and store the Stream to a file.

This function is based on the StreamFreezer object.

The serialization format is defined by the fmt argument; ‘pickle’ (the default) is only one presently supported. ‘json’ or ‘jsonnative’ will be used once jsonpickle is good enough.

If no file path is given, a temporary file is used.

The file path is returned.

>>> c = converter.parse('tinynotation: 4/4 c4 d e f')
>>> c.show('text')
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.note.Note E>
{3.0} <music21.note.Note F>
>>> fp = converter.freeze(c, fmt='pickle')
>>> fp
'/tmp/music21/sjiwoe.pgz'

The file can then be “thawed” back into a Stream using the thaw() method.

>>> d = converter.thaw(fp)
>>> d.show('text')
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.note.Note E>
{3.0} <music21.note.Note F>
music21.converter.thaw(fp, zipType='zlib')

Given a file path of a serialized Stream, defrost the file into a Stream.

This function is based on the StreamFreezer object.

See the documentation for freeze() for demos.

music21.converter.freezeStr(streamObj, fmt=None)

Given a StreamObject serialize and return a serialization string.

This function is based on the StreamFreezer object.

The serialization format is defined by the fmt argument; ‘pickle’ (the default), is the only one presently supported.

>>> c = converter.parse('tinyNotation: 4/4 c4 d e f')
>>> c.show('text')
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.note.Note E>
{3.0} <music21.note.Note F>
>>> data = converter.freezeStr(c, fmt='pickle')
>>> len(data) > 20 # pickle implementation dependent
True
>>> d = converter.thawStr(data)
>>> d.show('text')
{0.0} <music21.meter.TimeSignature 4/4>
{0.0} <music21.note.Note C>
{1.0} <music21.note.Note D>
{2.0} <music21.note.Note E>
{3.0} <music21.note.Note F>
music21.converter.thawStr(strData)

Given a serialization string, defrost into a Stream.

This function is based on the StreamFreezer object.

music21.converter.registerSubconverter(newSubConverter)

Add a Subconverter to the list of registered subconverters.

Example, register a converter for the obsolete Amiga composition software Sonix (so fun...)

>>> class ConverterSonix(converter.subConverters.SubConverter):
...    registerFormats = ('sonix',)
...    registerInputExtensions = ('mus',)
>>> converter.registerSubconverter(ConverterSonix)
>>> scf = converter.Converter().getSubConverterFormats()
>>> for x in sorted(list(scf.keys())):
...     x, scf[x] 
('abc', <class 'music21.converter.subConverters.ConverterABC'>)
...
('sonix', <class 'music21.ConverterSonix'>)   
...
music21.converter.unregisterSubconverter(removeSubconverter)

Remove a Subconverter from the list of registered subconverters.

>>> mxlConverter = converter.subConverters.ConverterMusicXML
>>> c = converter.Converter()
>>> mxlConverter in c.subconvertersList()
True
>>> converter.unregisterSubconverter(mxlConverter)
>>> mxlConverter in c.subconvertersList()
False

if there is no such subConverter registered and it is not a default subconverter, then a converter.ConverterException is raised:

>>> class ConverterSonix(converter.subConverters.SubConverter):
...    registerFormats = ('sonix',)
...    registerInputExtensions = ('mus',)
>>> converter.unregisterSubconverter(ConverterSonix)
Traceback (most recent call last):
ConverterException: Could not remove <class 'music21.ConverterSonix'> from registered subconverters

The special command “all” removes everything including the default converters:

>>> converter.unregisterSubconverter('all')
>>> c.subconvertersList()
[]

Converter

class music21.converter.Converter

A class used for converting all supported data formats into music21 objects.

Not a subclass, but a wrapper for different converter objects based on format.

Converter read-only properties

Converter.stream

Returns the .subConverter.stream object.

Converter methods

Converter.defaultSubconverters()

return an alphabetical list of the default subconverters: those in converter.subConverters with the class Subconverter.

Do not use generally. use c.subConvertersList()

>>> c = converter.Converter()
>>> for sc in c.defaultSubconverters():
...     print(sc)
<class 'music21.converter.subConverters.ConverterABC'>
<class 'music21.converter.subConverters.ConverterBraille'>
<class 'music21.converter.subConverters.ConverterCapella'>
<class 'music21.converter.subConverters.ConverterHumdrum'>
<class 'music21.converter.subConverters.ConverterIPython'>
<class 'music21.converter.subConverters.ConverterLilypond'>
<class 'music21.converter.subConverters.ConverterMidi'>
<class 'music21.converter.subConverters.ConverterMuseData'>
<class 'music21.converter.subConverters.ConverterMusicXML'>
<class 'music21.converter.subConverters.ConverterNoteworthy'>
<class 'music21.converter.subConverters.ConverterNoteworthyBinary'>
<class 'music21.converter.subConverters.ConverterRomanText'>
<class 'music21.converter.subConverters.ConverterScala'>
<class 'music21.converter.subConverters.ConverterText'>
<class 'music21.converter.subConverters.ConverterTextLine'>
<class 'music21.converter.subConverters.ConverterTinyNotation'>
<class 'music21.converter.subConverters.ConverterVexflow'>
<class 'music21.converter.subConverters.SubConverter'>        
Converter.formatFromHeader(dataStr)

if dataStr begins with a text header such as “tinyNotation:” then return that format plus the dataStr with the head removed.

Else, return (None, dataStr) where dataStr is the original untouched.

Not case sensitive.

>>> c = converter.Converter()
>>> c.formatFromHeader('tinynotation: C4 E2')
('tinynotation', 'C4 E2')
>>> c.formatFromHeader('C4 E2')
(None, 'C4 E2')
>>> c.formatFromHeader('romanText: m1: a: I b2 V')
('romantext', 'm1: a: I b2 V')

New formats can register new headers:

>>> class ConverterSonix(converter.subConverters.SubConverter):
...    registerFormats = ('sonix',)
...    registerInputExtensions = ('mus',)
>>> converter.registerSubconverter(ConverterSonix)
>>> c.formatFromHeader('sonix: AIFF data')
('sonix', 'AIFF data')
Converter.getFormatFromFileExtension(fp)

gets the format from a file extension.

>>> import os
>>> fp = os.path.join(common.getSourceFilePath(), 'musedata', 'testZip.zip')
>>> c = converter.Converter()
>>> c.getFormatFromFileExtension(fp)
'musedata'
Converter.getSubConverterFormats()

Get a dictionary of subConverters for various formats.

>>> scf = converter.Converter().getSubConverterFormats()
>>> scf['abc']
<class 'music21.converter.subConverters.ConverterABC'>
>>> for x in sorted(list(scf.keys())):
...     x, scf[x]
('abc', <class 'music21.converter.subConverters.ConverterABC'>)
('braille', <class 'music21.converter.subConverters.ConverterBraille'>)
('capella', <class 'music21.converter.subConverters.ConverterCapella'>)
('humdrum', <class 'music21.converter.subConverters.ConverterHumdrum'>)
('ipython', <class 'music21.converter.subConverters.ConverterIPython'>)
('lily', <class 'music21.converter.subConverters.ConverterLilypond'>)
('lilypond', <class 'music21.converter.subConverters.ConverterLilypond'>)
('midi', <class 'music21.converter.subConverters.ConverterMidi'>)
('musedata', <class 'music21.converter.subConverters.ConverterMuseData'>)
('musicxml', <class 'music21.converter.subConverters.ConverterMusicXML'>)
('noteworthy', <class 'music21.converter.subConverters.ConverterNoteworthyBinary'>)
('noteworthytext', <class 'music21.converter.subConverters.ConverterNoteworthy'>)
('rntext', <class 'music21.converter.subConverters.ConverterRomanText'>)
('romantext', <class 'music21.converter.subConverters.ConverterRomanText'>)
('scala', <class 'music21.converter.subConverters.ConverterScala'>)
('t', <class 'music21.converter.subConverters.ConverterText'>)
('text', <class 'music21.converter.subConverters.ConverterText'>)
('textline', <class 'music21.converter.subConverters.ConverterTextLine'>)
('tinynotation', <class 'music21.converter.subConverters.ConverterTinyNotation'>)
('txt', <class 'music21.converter.subConverters.ConverterText'>)
('vexflow', <class 'music21.converter.subConverters.ConverterVexflow'>)
('xml', <class 'music21.converter.subConverters.ConverterMusicXML'>)       
Converter.parseData(dataStr, number=None, format=None, forceSource=False)

Given raw data, determine format and parse into a music21 Stream.

Converter.parseFile(fp, number=None, format=None, forceSource=False, storePickle=True)

Given a file path, parse and store a music21 Stream.

If format is None then look up the format from the file extension using common.findFormatFile.

Will load from a pickle unless forceSource is True Will store as a pickle unless storePickle is False

Converter.parseFileNoPickle(fp, number=None, format=None, forceSource=False)

Given a file path, parse and store a music21 Stream.

If format is None then look up the format from the file extension using common.findFormatFile.

Does not use or store pickles in any circumstance.

Converter.parseURL(url, format=None, number=None)

Given a url, download and parse the file into a music21 Stream stored in the stream property of the converter object.

Note that this checks the user Environment autoDownlaad setting before downloading.

TODO: replace with free version of jeanieLightBrownHair

>>> jeanieLightBrownURL = 'http://www.wikifonia.org/node/4391'
>>> c = converter.Converter()
>>> c.parseURL(jeanieLightBrownURL)
>>> jeanieStream = c.stream
Converter.regularizeFormat(fmt)

Take in a string representing a format, a file extension (w/ or without leading dot) etc. and find the format string that best represents the format that should be used.

Searches SubConverter.registerFormats first, then SubConverter.registerInputExtensions, then SubConverter.registerOutputExtensions

Returns None if no format applies:

>>> c = converter.Converter()
>>> c.regularizeFormat('mxl')
'musicxml'
>>> c.regularizeFormat('t')
'text'
>>> c.regularizeFormat('abc')
'abc'
>>> c.regularizeFormat('lily.png')
'lilypond'
>>> c.regularizeFormat('blah') is None
True              
Converter.setSubconverterFromFormat(converterFormat)

sets the .subConverter according to the format of converterFormat:

>>> convObj = converter.Converter()       
>>> convObj.setSubconverterFromFormat('humdrum')
>>> convObj.subConverter
<music21.converter.subConverters.ConverterHumdrum object at 0x...>
Converter.subconvertersList()
>>> c = converter.Converter()
>>> scl = c.subconvertersList()
>>> defaultScl = c.defaultSubconverters()
>>> tuple(scl) == tuple(defaultScl)
True
>>> class ConverterSonix(converter.subConverters.SubConverter):
...    registerFormats = ('sonix',)
...    registerInputExtensions = ('mus',)
>>> converter.registerSubconverter(ConverterSonix)
>>> ConverterSonix in c.subconvertersList()
True

Converter instance variables

Converter.subConverter

a ConverterXXX object that will do the actual converting.

ArchiveManager

class music21.converter.ArchiveManager(fp, archiveType='zip')

Before opening a file path, this class can check if this is an archived file collection, such as a .zip or or .mxl file. This will return the data from the archive.

>>> fnCorpus = corpus.getWork('opus18no1/movement3', fileExtensions=('.xml',))

This is likely a unicode string

>>> fnCorpus
'/Users/cuthbert/Documents/music21/corpus/beethoven/opus18no1/movement3.mxl'
>>> am = converter.ArchiveManager(fnCorpus)
>>> am.isArchive()
True
>>> am.getNames()
['movement3.xml', 'META-INF/container.xml']
>>> data = am.getData()
>>> data[0:70]
'<?xml version="1.0" standalone="no"?>\r\n<!DOCTYPE score-partwise PUBLIC'

ArchiveManager methods

ArchiveManager.getData(name=None, dataFormat='musicxml')

Return data from the archive by name. If no name is given, a default may be available.

For ‘musedata’ format this will be a list of strings. For ‘musicxml’ this will be a single string.

ArchiveManager.getNames()

Return a list of all names contained in this archive.

ArchiveManager.isArchive()

Return True or False if the filepath is an archive of the supplied archiveType.

PickleFilter

class music21.converter.PickleFilter(fp, forceSource=False, number=None)

Before opening a file path, this class checks to see if there is an up-to-date version of the file pickled and stored in the scratch directory.

If the user has not specified a scratch directory, or if forceSource is True then a pickle path will not be created.

PickleFilter methods

PickleFilter.status()

Given a file path specified with __init__, look for an up to date pickled version of this file path. If it exists, return its fp, otherwise return the original file path.

Return arguments are file path to load, boolean whether to write a pickle, and the file path of the pickle.

Does not check that fp exists or create the pickle file.

>>> fp = '/Users/Cuthbert/Desktop/musicFile.mxl'
>>> pickfilt = converter.PickleFilter(fp)
>>> pickfilt.status()
('/Users/Cuthbert/Desktop/musicFile.mxl', True, '/var/folders/x5/rymq2tx16lqbpytwb1n_cc4c0000gn/T/music21/m21-18b8c5a5f07826bd67ea0f20462f0b8d.pgz')