Classes and functions for creating and processing metadata associated with scores, works, and fragments, such as titles, movements, authors, publishers, and regions. The Metadata object is the main public interface to metadata components. A Metadata object can be added to a Stream and used to set common score attributes, such as title and composer. A Metadata object found at offset zero can be accessed through a Stream’s metadata property. The following example creates a Stream object, adds a Note object, and configures and adds the title and composer properties of a Metadata object.
>>> from music21 import *
>>> s = stream.Stream()
>>> s.append(note.Note())
>>> s.insert(metadata.Metadata())
>>> s.metadata.title = 'title'
>>> s.metadata.composer = 'composer'
>>> s.show()
Get ROLE_ABBREVIATIONS as string-like attributes, used for Contributors.
>>> abbreviationToRole('com')
'composer'
>>> abbreviationToRole('lib')
'librettist'
>>> for id in ROLE_ABBREVIATIONS:
... post = abbreviationToRole(id)
Get work id abbreviations.
>>> abbreviationToWorkId('otl')
'title'
>>> for id in WORK_ID_ABBREVIATIONS:
... post = abbreviationToWorkId(id)
Convert an error string (appoximate, uncertain) into a symbol.
>>> errorToSymbol('approximate')
'~'
>>> errorToSymbol('uncertain')
'?'
Get a role id from a string representation.
>>> roleToAbbreviation('composer')
'com'
>>> for n in ROLES:
... post = roleToAbbreviation(n)
Get a role id from a string representation.
>>> workIdToAbbreviation('localeOfComposition')
'opc'
>>> for n in WORK_IDS:
... post = workIdToAbbreviation(n)
Inherits from: JSONSerializer
One unit of text data: a title, a name, or some other text data. Store the string and a language name or code. This object can be used and/or subclassed for a variety for of text storage.
>>> td = Text('concerto in d', 'en')
>>> str(td)
'concerto in d'
Text properties
- language¶
Set the language of the Text stored within.
>>> t = Text('my text') >>> t.language = 'en' >>> t.language 'en'Properties inherited from JSONSerializer: json
Text methods
- getNormalizedArticle()¶
Return a string representation with normalized articles.
>>> from music21 import * >>> td = metadata.Text('Ale is Dear, The', 'en') >>> str(td) 'Ale is Dear, The' >>> td.getNormalizedArticle() 'The Ale is Dear'
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
Methods inherited from JSONSerializer: jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()
Inherits from: JSONSerializer
A single date value, specified by year, month, day, hour, minute, and second. Note that this class has been created, instead of using Python’s datetime, to provide greater flexibility for processing unconventional dates, ancient dates, dates with error, and date ranges. The datetime property can be used to retrieve a datetime object when necessary. Additionally, each value can be specified as uncertain or approximate; if None, assumed to be certain. Data objects are fundamental components of DateSingle and related subclasses that represent single dates and date ranges.
>>> from music21 import *
>>> a = metadata.Date(year=1843, yearError='approximate')
>>> a.year
1843
>>> a.yearError
'approximate'
>>> a = metadata.Date(year='1843?')
>>> a.yearError
'uncertain'
Date attributes
Attributes without Documentation: attrStrFormat, minuteError, monthError, hour, hourError, dayError, attrNames, month, second, secondError, yearError, year, day, minute
Date properties
- datetime¶
Return a datetime object representation.
>>> a = Date(year=1843, month=3, day=3) >>> a.datetime datetime.datetime(1843, 3, 3, 0, 0)
- hasError¶
Return True if any data points have error defined.
>>> a = Date(year=1843, month=3, day=3, dayError='approximate') >>> a.hasError True >>> b = Date(year=1843, month=3, day=3, minute=3) >>> b.hasError False
- hasTime¶
Return True if any time elements are defined.
>>> a = Date(year=1843, month=3, day=3) >>> a.hasTime False >>> b = Date(year=1843, month=3, day=3, minute=3) >>> b.hasTime TrueProperties inherited from JSONSerializer: json
Date methods
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- load(value)¶
Load values by string, datetime object, or Date object.
>>> a = Date(year=1843, month=3, day=3) >>> b = Date() >>> b.load(a) >>> b.year 1843
- loadDatetime(dt)¶
Load time data from a datetime object.
>>> import datetime >>> dt = datetime.datetime(2005, 02, 01) >>> dt datetime.datetime(2005, 2, 1, 0, 0) >>> a = Date() >>> a.loadDatetime(dt) >>> str(a) '2005/02/01'
- loadOther(other)¶
Load values based on another Date object:
>>> a = Date(year=1843, month=3, day=3) >>> b = Date() >>> b.loadOther(a) >>> b.year 1843
- loadStr(str)¶
Load a string date representation. Assume year/month/day/hour:minute:second
>>> from music21 import * >>> d = metadata.Date() >>> d.loadStr('3030?/12~/?4') >>> d.month, d.monthError (12, 'approximate') >>> d.year, d.yearError (3030, 'uncertain') >>> d.month, d.monthError (12, 'approximate') >>> d.day, d.dayError (4, 'uncertain') >>> d = metadata.Date() >>> d.loadStr('1834/12/4/4:50:32') >>> d.minute, d.second (50, 32)Methods inherited from JSONSerializer: jsonComponentFactory(), jsonPrint(), jsonRead(), jsonWrite()
Inherits from: JSONSerializer
Store a date, either as certain, approximate, or uncertain relevance. The relevance attribute is limited within each DateSingle subclass depending on the design of the class. Alternative relevance types should be configured as other DateSingle subclasses.
>>> dd = DateSingle('2009/12/31', 'approximate')
>>> str(dd)
'2009/12/31'
>>> dd.relevance
'approximate'
>>> dd = DateSingle('1805/3/12', 'uncertain')
>>> str(dd)
'1805/03/12'
DateSingle attributes
Attributes without Documentation: isSingle
DateSingle properties
- datetime¶
Return a datetime object representation.
>>> d = Date(year=1843, month=3, day=3) >>> ds = DateSingle(d) >>> ds.datetime datetime.datetime(1843, 3, 3, 0, 0)
- relevance¶
- No documentation.
Properties inherited from JSONSerializer: json
DateSingle methods
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- No documentation.
Methods inherited from JSONSerializer: jsonPrint(), jsonRead(), jsonWrite()
Inherits from: DateSingle, JSONSerializer
Store a relative date, sometime prior or sometime after
>>> dd = DateRelative('2009/12/31', 'prior')
>>> str(dd)
'2009/12/31'
>>> dd = DateRelative('2009/12/31', 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain
Inherits from: DateSingle, JSONSerializer
Store a relative date, sometime between two dates
>>> dd = DateBetween(['2009/12/31', '2010/1/28'])
>>> str(dd)
'2009/12/31 to 2010/01/28'
>>> dd = DateBetween(['2009/12/31', '2010/1/28'], 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain
Inherits from: DateSingle, JSONSerializer
Store a selection of dates, or a collection of dates that might all be possible
>>> dd = DateSelection(['2009/12/31', '2010/1/28', '1894/1/28'], 'or')
>>> str(dd)
'2009/12/31 or 2010/01/28 or 1894/01/28'
>>> dd = DateSelection(['2009/12/31', '2010/1/28'], 'certain')
Traceback (most recent call last):
MetadataException: relevance value is not supported by this object: certain
Inherits from: JSONSerializer
A person that contributed to a work. Can be a composer, lyricist, arranger, or other type of contributor. In MusicXML, these are “creator” elements.
>>> td = Contributor(role='composer', name='Chopin, Fryderyk')
>>> td.role
'composer'
>>> td.name
'Chopin, Fryderyk'
>>> td.relevance
'contributor'
Contributor attributes
Attributes without Documentation: relevance
Contributor properties
- mx¶
Return a mxCreator object based on this object.
>>> from music21 import * >>> md = metadata.Metadata() >>> md.composer = 'frank' >>> mxCreator = md._contributors[0].mx >>> mxCreator.get('charData') 'frank' >>> mxCreator.get('type') 'composer'
- name¶
Returns the text name, or the first of many names entered.
>>> td = Contributor(role='composer', names=['Chopin, Fryderyk', 'Chopin, Frederick']) >>> td.name 'Chopin, Fryderyk' >>> td.names ['Chopin, Fryderyk', 'Chopin, Frederick']
- names¶
Returns all names in a list.
>>> td = Contributor(role='composer', names=['Chopin, Fryderyk', 'Chopin, Frederick']) >>> td.names ['Chopin, Fryderyk', 'Chopin, Frederick']
- role¶
The role is what part this Contributor plays in the work. Both full roll strings and roll abbreviations may be used.
>>> td = Contributor() >>> td.role = 'composer' >>> td.role 'composer' >>> td.role = 'lor' >>> td.role 'orchestrator'Properties inherited from JSONSerializer: json
Contributor methods
- age()¶
Calculate the age of the Contributor, returning a datetime.timedelta object.
>>> a = Contributor(name='Beethoven, Ludwig van', role='composer', birth='1770/12/17', death='1827/3/26') >>> a.role 'composer' >>> a.age() datetime.timedelta(20552) >>> str(a.age()) '20552 days, 0:00:00' >>> a.age().days / 365 56
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- No documentation.
Methods inherited from JSONSerializer: jsonPrint(), jsonRead(), jsonWrite()
Inherits from: Music21Object, JSONSerializer
Metadata represent data for a work or fragment, including title, composer, dates, and other relevant information. Metadata is a Music21Object subclass, meaing that it can be positioned on a Stream by offset and have a Duration. In many cases, each Stream will have a single Metadata object at the zero offset position.
>>> md = Metadata(title='Concerto in F')
>>> md.title
'Concerto in F'
>>> md = Metadata(otl='Concerto in F') # can use abbreviations
>>> md.title
'Concerto in F'
>>> md.setWorkId('otl', 'Rhapsody in Blue')
>>> md.otl
'Rhapsody in Blue'
>>> md.title
'Rhapsody in Blue'
Metadata attributes
Attributes inherited from Music21Object: classSortOrder, id, groups
Metadata properties
- alternativeTitle¶
Get or set the alternative title.
>>> md = Metadata(popularTitle='Eroica') >>> md.alternativeTitle = 'Cantus' >>> md.alternativeTitle 'Cantus'
- composer¶
Get or set the composer of this work. More than one composer may be specified. The composer attribute does not live in Metadata, but creates a Contributor object in the Metadata object.
>>> md = Metadata(title='Third Symphony', popularTitle='Eroica', composer='Beethoven, Ludwig van') >>> md.composer 'Beethoven, Ludwig van'
- composers¶
- Get a list of all Contributor objects defined as composer of this work.
- date¶
Get or set the date of this work as one of the following date objects: DateSingle, DateRelative, DateBetween, DateSelection,
>>> from music21 import * >>> md = metadata.Metadata(title='Third Symphony', popularTitle='Eroica', composer='Beethoven, Ludwig van') >>> md.date = '2010' >>> md.date '2010/--/--' >>> md.date = metadata.DateBetween(['2009/12/31', '2010/1/28']) >>> md.date '2009/12/31 to 2010/01/28'
- localeOfComposition¶
- Get or set the locale of composition, or origin, of the work.
- movementName¶
- Get or set the movement title.
- movementNumber¶
- Get or set the movement number.
- mx¶
- Return a mxScore object, to be merged or used in final musicxml output
- number¶
- Get or set the number of the work.
- opusNumber¶
- Get or set the opus number.
- title¶
Get the title of the work, or the next matched title string available from related parameter fields.
>>> md = Metadata(title='Third Symphony') >>> md.title 'Third Symphony' >>> md = Metadata(popularTitle='Eroica') >>> md.title 'Eroica' >>> md = Metadata(title='Third Symphony', popularTitle='Eroica') >>> md.title 'Third Symphony' >>> md.popularTitle 'Eroica' >>> md.otp 'Eroica'Properties inherited from Music21Object: activeSite, beat, beatDuration, beatStr, beatStrength, classes, duration, measureNumberLocal, offset, priority
Properties inherited from JSONSerializer: json
Metadata methods
- addContributor(c)¶
Assign a Contributor object to this Metadata.
>>> md = Metadata(title='Third Symphony') >>> c = Contributor() >>> c.name = 'Beethoven, Ludwig van' >>> c.role = 'composer' >>> md.addContributor(c) >>> md.composer 'Beethoven, Ludwig van' >>> md.composer = 'frank' >>> md.composers ['Beethoven, Ludwig van', 'frank']
- getContributorsByRole(value)¶
Return a Contributor if defined for a provided role.
>>> md = Metadata(title='Third Symphony') >>> c = Contributor() >>> c.name = 'Beethoven, Ludwig van' >>> c.role = 'composer' >>> md.addContributor(c) >>> cList = md.getContributorsByRole('composer') >>> cList[0].name 'Beethoven, Ludwig van'
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- No documentation.
- search(query, field=None)¶
Search one or all fields with a query, given either as a string or a regular expression match.
>>> from music21 import * >>> md = Metadata() >>> md.composer = 'Beethoven, Ludwig van' >>> md.title = 'Third Symphony' >>> md.search('beethoven', 'composer') (True, 'composer') >>> md.search('beethoven', 'compose') (True, 'composer') >>> md.search('frank', 'composer') (False, None) >>> md.search('frank') (False, None) >>> md.search('third') (True, 'title') >>> md.search('third', 'composer') (False, None) >>> md.search('third', 'title') (True, 'title') >>> md.search('third|fourth') (True, 'title') >>> md.search('thove(.*)') (True, 'composer')
- setWorkId(idStr, value)¶
Directly set a workd id, given either as a full string name or as a three character abbreviation.
>>> md = Metadata(title='Quartet') >>> md.title 'Quartet' >>> md.setWorkId('otl', 'Trio') >>> md.title 'Trio' >>> md.setWorkId('sdf', None) Traceback (most recent call last): MetadataException: no work id available with id: sdfMethods inherited from Music21Object: searchParentByAttr(), getContextAttr(), setContextAttr(), addContext(), addLocation(), addLocationAndActiveSite(), freezeIds(), getAllContextsByClass(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), mergeAttributes(), purgeLocations(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unfreezeIds(), unwrapWeakref(), wrapWeakref(), write()
Methods inherited from JSONSerializer: jsonPrint(), jsonRead(), jsonWrite()
Inherits from: Contributor, JSONSerializer
A person that created a work. Can be a composer, lyricist, arranger, or other type of contributor. In MusicXML, these are “creator” elements.
>>> td = Creator(role='composer', name='Chopin, Fryderyk')
>>> td.role
'composer'
>>> td.name
'Chopin, Fryderyk'
>>> td.relevance
'creator'
Inherits from: JSONSerializer
An object that provides access to, searches within, and storage and loading of multiple Metadata objects. Additionally, multiple MetadataBundles can be merged for additional processing
MetadataBundle properties
Properties inherited from JSONSerializer: json
MetadataBundle methods
- addFromPaths(pathList)¶
Parse and store metadata from numerous files
>>> from music21 import * >>> mb = MetadataBundle() >>> mb.addFromPaths(corpus.getWorkList('bwv66.6')) >>> len(mb._storage) 1
- addFromVirtualWorks(pathList)¶
- No documentation.
- corpusPathToKey(fp, number=None)¶
Given a file path or corpus path, return the meta-data path
>>> from music21 import * >>> mb = MetadataBundle() >>> mb.corpusPathToKey('bach/bwv1007/prelude').endswith('bach_bwv1007_prelude') True >>> mb.corpusPathToKey('/beethoven/opus59no1/movement1.xml').endswith('beethoven_opus59no1_movement1_xml') True
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- No documentation.
- read(fp=None)¶
- Load self from the file path suggested by the _name of this MetadataBundle
- search(query, field=None, extList=None)¶
Perform search, on all stored metadata, permit regular expression matching. Return pairs of file paths and work numbers, or None
>>> from music21 import * >>> mb = MetadataBundle() >>> mb.addFromPaths(corpus.getWorkList('ciconia')) >>> mb.updateAccessPaths(corpus.getWorkList('ciconia')) >>> post = mb.search('cicon', 'composer') >>> len(post[0]) 2 >>> post = mb.search('cicon', 'composer', extList=['.krn']) >>> len(post) # no files in this format 0 >>> post = mb.search('cicon', 'composer', extList=['.xml']) >>> len(post) # no files in this format 1
- updateAccessPaths(pathList)¶
For each stored Metatadata object, create an entry for a complete, local file path that returns this. The pathList parameter is a list of all file paths on the users local system.
>>> from music21 import * >>> mb = MetadataBundle() >>> mb.addFromPaths(corpus.getWorkList('bwv66.6')) >>> len(mb._accessPaths) 0 >>> mb.updateAccessPaths(corpus.getWorkList('bwv66.6')) >>> len(mb._accessPaths) 1
- write()¶
- Write the JSON storage of all Metadata or RichMetadata contained in this object.
Methods inherited from JSONSerializer: jsonPrint(), jsonRead(), jsonWrite()
Inherits from: Metadata, Music21Object, JSONSerializer
RichMetadata adds to Metadata information about the contents of the Score it is attached to. TimeSignature, KeySignature and related analytical is stored. RichMetadata are generally only created in the process of creating stored JSON metadata.
>>> md = RichMetadata(title='Concerto in F')
>>> md.title
'Concerto in F'
>>> md = RichMetadata(otl='Concerto in F') # can use abbreviations
>>> md.title
'Concerto in F'
>>> md.setWorkId('otl', 'Rhapsody in Blue')
>>> md.otl
'Rhapsody in Blue'
>>> md.title
'Rhapsody in Blue'
>>> 'keySignatureFirst' in md._searchAttributes
True
RichMetadata attributes
Attributes without Documentation: timeSignatures, tempos, keySignatureFirst, keySignatures, ambitus, tempoFirst, pitchHighest, timeSignatureFirst, pitchLowest
Attributes inherited from Music21Object: classSortOrder, id, groups
RichMetadata properties
Properties inherited from Metadata: alternativeTitle, composer, composers, date, localeOfComposition, movementName, movementNumber, mx, number, opusNumber, title
Properties inherited from Music21Object: activeSite, beat, beatDuration, beatStr, beatStrength, classes, duration, measureNumberLocal, offset, priority
Properties inherited from JSONSerializer: json
RichMetadata methods
- jsonAttributes()¶
- Define all attributes of this object that should be JSON serialized for storage and re-instantiation. Attributes that name basic Python objects or JSONSerializer subclasses, or dictionaries or lists that contain Python objects or JSONSerializer subclasses, can be provided.
- jsonComponentFactory(idStr)¶
- No documentation.
- merge(other, favorSelf=False)¶
Given another Metadata object, combine all attributes and return a new object.
>>> md = Metadata(title='Concerto in F') >>> md.title 'Concerto in F' >>> rmd = RichMetadata() >>> rmd.merge(md) >>> rmd.title 'Concerto in F'
- update(streamObj)¶
- Given a Stream object, update attributes with stored objects.
Methods inherited from Metadata: addContributor(), getContributorsByRole(), search(), setWorkId()
Methods inherited from Music21Object: searchParentByAttr(), getContextAttr(), setContextAttr(), addContext(), addLocation(), addLocationAndActiveSite(), freezeIds(), getAllContextsByClass(), getContextByClass(), getOffsetBySite(), getSiteIds(), getSites(), getSpannerSites(), hasContext(), mergeAttributes(), purgeLocations(), removeLocationBySite(), removeLocationBySiteId(), setOffsetBySite(), show(), splitAtDurations(), splitAtQuarterLength(), splitByQuarterLengths(), unfreezeIds(), unwrapWeakref(), wrapWeakref(), write()
Methods inherited from JSONSerializer: jsonPrint(), jsonRead(), jsonWrite()