Exemplo n.º 1
0
def findInputExtension(fmt):
    '''
    Will be fully deprecated when there's an exact equivalent in converter...
    
    
    Given an input format or music21 format, find and return all possible 
    input extensions.

    >>> a = common.findInputExtension('musicxml')
    >>> a
    ('.xml', '.mxl', '.mx', '.musicxml')
    >>> a = common.findInputExtension('humdrum')
    >>> a
    ('.krn',)
    >>> common.findInputExtension('musedata')
    ('.md', '.musedata', '.zip')
    
    mx is not a music21 format but it is a file format
    
    >>> common.findInputExtension('mx')
    ('.xml', '.mxl', '.mx', '.musicxml')
    
    Leading dots don't matter...
    
    >>> common.findInputExtension('.mx')
    ('.xml', '.mxl', '.mx', '.musicxml')


    blah is neither
    
    >>> common.findInputExtension('blah') is None
    True
    '''
    from music21 import converter
    fmt = fmt.lower().strip()    
    if fmt.startswith('.'):
        fmt = fmt[1:] # strip .

    sc = findSubConverterForFormat(fmt)
    if sc is None:
        # file extension
        post = []
        for sc in converter.Converter().subconvertersList():
            if fmt not in sc.registerInputExtensions:
                continue
            for ext in sc.registerInputExtensions:
                if not ext.startswith('.'):
                    ext = '.' + ext
                post.append(ext)
            if post:
                return tuple(post)
        return None
    else:
        # music21 format
        post = []
        for ext in sc.registerInputExtensions:
            if not ext.startswith('.'):
                ext = '.' + ext
            post.append(ext)
        return tuple(post)
Exemplo n.º 2
0
def findSubConverterForFormat(fmt):
    '''
    return a converter.subConverter.SubConverter subclass
    for a given format -- this is a music21 format name,
    not a file extension. Or returns None
    
    >>> common.findSubConverterForFormat('musicxml')
    <class 'music21.converter.subConverters.ConverterMusicXML'>
    
    >>> common.findSubConverterForFormat('text')
    <class 'music21.converter.subConverters.ConverterText'>

    Some subconverters have format aliases

    >>> common.findSubConverterForFormat('t')
    <class 'music21.converter.subConverters.ConverterText'>
    
    '''
    fmt = fmt.lower().strip()
    from music21 import converter
    scl = converter.Converter().subconvertersList()
    for sc in scl:
        formats = sc.registerFormats
        if fmt in formats:
            return sc
Exemplo n.º 3
0
def _import_file(pathname, metafile=None):
    """
    Import the score to music21 format.
    :param pathname: Location of the file to import on the local disk.
    :type pathname: str
    :returns: A 1-tuple of :class:`IndexedPiece` if the file imported as a 
        :class:`music21.stream.Score` object or a multi-element list if it imported as a 
        :class:`music21.stream.Opus` object.
        respectively.
    :rtype: 1-tuple or list of :class:`IndexedPiece`
    """
    score = converter.Converter()
    score.parseFile(pathname, forceSource=True, storePickle=False)
    score = score.stream
    if isinstance(score, stream.Opus):
        # make an AggregatedPieces object containing IndexedPiece objects of each movement of the opus.
        score = [IndexedPiece(pathname, opus_id=i) for i in xrange(len(score))]
    elif isinstance(score, stream.Score):
        score = (IndexedPiece(pathname, score=score),)
    for ip in score:
        for field in ip._metadata:
            if hasattr(ip.metadata, field):
                ip._metadata[field] = getattr(ip.metadata, field)
                if ip._metadata[field] is None:
                    ip._metadata[field] = '???'
        ip._metadata['parts'] = _find_part_names(ip._get_part_streams())
        ip._metadata['title'] = _find_piece_title(ip._score)
        ip._metadata['partRanges'] = _find_part_ranges(ip._score)
        ip._metadata['pieceRange'] = _find_piece_range(ip._score)
        ip._imported = True

    return score
Exemplo n.º 4
0
def create_png_from_stream(stream, filename):
    helperFormat = 'musicxml'
    helperSubformats = ['png']
    helperConverter = converter.Converter()
    helperConverter.setSubconverterFromFormat(helperFormat)
    helperSubConverter = helperConverter.subConverter

    # if helperFormat == 'musicxml':
    #     ### hack to make musescore excerpts -- fix with a converter class in MusicXML
    #     savedDefaultTitle = defaults.title
    #     savedDefaultAuthor = defaults.author
    #     defaults.title = ''
    #     defaults.author = ''

    #     if 'Opus' not in obj.classes:
    fp = helperSubConverter.write(stream,
                                  helperFormat,
                                  subformats=helperSubformats)

    # defaults.title = savedDefaultTitle
    # defaults.author = savedDefaultAuthor
    if helperSubformats[0] == 'png':
        ipo = ipythonObjects.IPythonPNGObject(fp)
    target_filename = os.path.join(os.getcwd(),
                                   "static/tmp/{}.png".format(filename))
    shutil.move(ipo.fp, target_filename)
    return (target_filename)
Exemplo n.º 5
0
def getValidOutputExtensionForFormat(form: str) -> str:
    c = converter.Converter()
    outList = c.subconvertersList('output')
    for subc in outList:
        if subc.registerOutputExtensions:
            if form in subc.registerFormats:
                return '.' + subc.registerOutputExtensions[0]
    return ''
Exemplo n.º 6
0
def getInputExtensionsList() -> [str]:
    c = converter.Converter()
    inList = c.subconvertersList('input')
    result = []
    for subc in inList:
        for inputExt in subc.registerInputExtensions:
            result.append('.' + inputExt)
    return result
Exemplo n.º 7
0
def subConverterList():
    '''
    returns a list of subconverter classes available to music21
    in converter/subConverters, including the stub SubConverter class
    
    DEPRECATED May 2015: moved to converter. #TODO: Remove
    '''
    from music21 import converter
    return converter.Converter().subconvertersList()
Exemplo n.º 8
0
def getOutputFormatsList() -> [str]:
    c = converter.Converter()
    outList = c.subconvertersList('output')
    result = []
    for subc in outList:
        if subc.registerOutputExtensions:  # if this subc supports output at all
            for form in subc.registerFormats:
                result.append(form)
    return result
Exemplo n.º 9
0
def getInputFormatsList() -> t.List[str]:
    c = converter.Converter()
    inList = c.subconvertersList('input')
    result = []
    for subc in inList:
        if subc.registerInputExtensions:  # if this subc supports input at all
            for form in subc.registerFormats:
                result.append(form)
    return result
Exemplo n.º 10
0
def getOutputExtensionsListForFormat(form: str) -> [str]:
    c = converter.Converter()
    outList = c.subconvertersList('output')
    result = []
    for subc in outList:
        if subc.registerOutputExtensions:
            if form in subc.registerFormats:
                for outputExt in subc.registerOutputExtensions:
                    result.append('.' + outputExt)
    return result
Exemplo n.º 11
0
def findFormatExtURL(url):
    '''
    Given a URL, attempt to find the extension.
    This may scrub arguments in a URL, or simply look at the last characters.

    DEPRECATED May 2014 -- moving to converter


    >>> urlA = 'http://somesite.com/?l=cc/schubert/piano/d0576&file=d0576-06.krn&f=xml'
    >>> urlB = 'http://somesite.com/cgi-bin/ksdata?l=cc/schubert/d0576&file=d0576-06.krn&f=kern'
    >>> urlC = 'http://somesite.com/cgi-bin/ksdata?l=cc/bach/cello&file=bwv1007-01.krn&f=xml'
    >>> urlF = 'http://junk'
    >>> urlM = 'http://somesite.com/files/mid001.mid'

    >>> common.findFormatExtURL(urlA)
    ('musicxml', '.xml')
    >>> common.findFormatExtURL(urlB)
    ('humdrum', '.krn')
    >>> common.findFormatExtURL(urlC)
    ('musicxml', '.xml')
    >>> common.findFormatExtURL(urlF)
    (None, None)
    >>> common.findFormatExtURL(urlM)
    ('midi', '.mid')
    '''
    from music21 import converter
    ext = None
    # first, look for cgi arguments
    if '=xml' in url:
        ext = '.xml'
    elif '=kern' in url:
        ext = '.krn'
    # specific tag used on musedata.org
    elif 'format=stage2' in url or 'format=stage1' in url:
        ext = '.md'
    else:  # check for file that ends in all known input extensions
        for sc in converter.Converter().subconvertersList():
            inputTypes = sc.registerInputExtensions
            for extSample in inputTypes:
                if url.endswith('.' + extSample):
                    ext = '.' + extSample
                    break
    # presently, not keeping the extension returned from this function
    # reason: mxl is converted to xml; need to handle mxl files first
    if ext is not None:
        fileFormat, unused_junk = findFormat(ext)
        return fileFormat, ext
    else:
        return None, None
Exemplo n.º 12
0
    def show(self, obj, fmt, app=None, subformats=None, **keywords):
        '''
        show using the appropriate subformat.
        '''
        if subformats is None:
            subformats = ['vexflow']

        if len(subformats) > 0 and subformats[0] == 'vexflow':
            return self.vfshow(obj)
            #subformats = ['lilypond','png']
        helperFormat = subformats[0]
        helperSubformats = subformats[1:]

        from music21 import converter
        helperConverter = converter.Converter()
        helperConverter.setSubconverterFromFormat(helperFormat)
        helperSubConverter = helperConverter.subConverter
        ### hack to make musescore excerpts -- fix with a converter class in MusicXML
        savedDefaultTitle = defaults.title
        savedDefaultAuthor = defaults.author
        defaults.title = ''
        defaults.author = ''

        if 'Opus' not in obj.classes:
            fp = helperSubConverter.write(obj,
                                          helperFormat,
                                          subformats=helperSubformats)

            defaults.title = savedDefaultTitle
            defaults.author = savedDefaultAuthor
            if helperSubformats[0] == 'png':
                from music21.ipython21 import objects as ipythonObjects
                ipo = ipythonObjects.IPythonPNGObject(fp)
                return ipo
        else:
            from IPython.display import Image, display  # @UnresolvedImport
            for s in obj.scores:
                fp = helperSubConverter.write(s,
                                              helperFormat,
                                              subformats=helperSubformats)

                if helperSubformats[0] == 'png':
                    from music21.ipython21 import objects as ipythonObjects  # @Reimport
                    ipo = ipythonObjects.IPythonPNGObject(fp)
                    display(Image(filename=ipo.fp, retina=True))
            defaults.title = savedDefaultTitle
            defaults.author = savedDefaultAuthor
            return None
Exemplo n.º 13
0
    def show(self, obj, fmt, app=None, subformats=None, **keywords):
        if subformats is None:
            subformats = ['vexflow']

        if len(subformats) > 0 and subformats[0] == 'vexflow':
            return self.vfshow(obj)
            #subformats = ['lilypond','png']
        helperFormat = subformats[0]
        helperSubformats = subformats[1:]
        from music21 import converter
        helperConverter = converter.Converter()
        helperConverter.setSubconverterFromFormat(helperFormat)
        helperSubConverter = helperConverter.subConverter
        fp = helperSubConverter.write(obj,
                                      helperFormat,
                                      subformats=helperSubformats)
        if helperSubformats[0] == 'png':
            from music21.ipython21 import objects as ipythonObjects
            ipo = ipythonObjects.IPythonPNGObject(fp)
            return ipo
Exemplo n.º 14
0
def printSupportedFormats(
        whichList: str):  # whichList should be 'input' or 'output'
    c = converter.Converter()
    if whichList == 'input':
        inList = c.subconvertersList('input')
        print('Supported input formats are:', file=sys.stderr)
        for subc in inList:
            if subc.registerInputExtensions:
                print('\tformats   : ' + ', '.join(subc.registerFormats) +
                      '\textensions: ' +
                      ', '.join(subc.registerInputExtensions),
                      file=sys.stderr)
    else:
        outList = c.subconvertersList('output')
        print('Supported output formats are:', file=sys.stderr)
        for subc in outList:
            if subc.registerOutputExtensions:
                print('\tformats   : ' + ', '.join(subc.registerFormats) +
                      '\textensions: ' +
                      ', '.join(subc.registerOutputExtensions),
                      file=sys.stderr)
Exemplo n.º 15
0
def findFormat(fmt):
    '''
    Given a format defined either by a format name, abbreviation, or
    an extension, return the regularized format name as well as 
    the output exensions.
    
    DEPRECATED May 2014 -- moving to converter

    
    All but the first element of the tuple are deprecated for use, since
    the extension can vary by subconverter (e.g., lily.png)

    Note that .mxl and .mx are only considered MusicXML input formats.

    >>> common.findFormat('mx')
    ('musicxml', '.xml')
    >>> common.findFormat('.mxl')
    ('musicxml', '.xml')
    >>> common.findFormat('musicxml')
    ('musicxml', '.xml')
    >>> common.findFormat('lily')
    ('lilypond', '.ly')
    >>> common.findFormat('lily.png')
    ('lilypond', '.ly')
    >>> common.findFormat('humdrum')
    ('humdrum', '.krn')
    >>> common.findFormat('txt')
    ('text', '.txt')
    >>> common.findFormat('textline')
    ('textline', '.txt')
    >>> common.findFormat('midi')
    ('midi', '.mid')
    >>> common.findFormat('abc')
    ('abc', '.abc')
    >>> common.findFormat('scl')
    ('scala', '.scl')
    >>> common.findFormat('braille')
    ('braille', '.txt')
    >>> common.findFormat('vexflow')
    ('vexflow', '.html')
    >>> common.findFormat('capx')
    ('capella', '.capx')

    >>> common.findFormat('mx')
    ('musicxml', '.xml')


    Works the same whether you have a leading dot or not:


    >>> common.findFormat('md')
    ('musedata', '.md')
    >>> common.findFormat('.md')
    ('musedata', '.md')


    If you give something we can't deal with, returns a Tuple of None, None:

    >>> common.findFormat('wpd')
    (None, None)


    These don't work but should eventually:
    
    # >>> common.findFormat('png')
    # ('musicxml.png', '.png')
    
    # >>> common.findFormat('ipython')
    # ('ipython', '.png')
    # >>> common.findFormat('ipython.png')
    # ('ipython', '.png')
    
    # >>> common.findFormat('musicxml.png')
    # ('musicxml.png', '.png')
    '''
    from music21 import converter
    c = converter.Converter()
    fileformat = c.regularizeFormat(fmt)
    if fileformat is None:
        return (None, None)
    scf = c.getSubConverterFormats()
    sc = scf[fileformat]

        
    if sc.registerOutputExtensions:
        firstOutput = '.' + sc.registerOutputExtensions[0]
    elif sc.registerInputExtensions:
        firstOutput = '.' + sc.registerInputExtensions[0]
    else:
        firstOutput = None
            
    return fileformat, firstOutput
import glob
import os
from music21 import converter, pitch, interval

path = '/home/family/Documents/experiment1/MIDI-VAE-master/dataset/C-sharp/*.mid'

root_path = '/home/family/Documents/experiment1/MIDI-VAE-master/dataset/C-sharp-time-stretched/'

#factor you want to stretch your midi

fctr = 1.05  #0.95 for 5% faster

for file in glob.glob(path):
    score = converter.Converter()
    score.parseFile(file)
    newscore = score.stream.augmentOrDiminish(fctr)
    newfile_name = root_path + file.split('/')[-1][:-4] + '_fctr_' + str(
        fctr) + '.mid'
    newscore.write('midi', newfile_name)
Exemplo n.º 17
0
    def show(self, obj, fmt, app=None, subformats=None, **keywords):
        '''
        show using the appropriate subformat.
        '''
        if subformats is None:
            subformats = ['vexflow']

        if subformats and subformats[0] == 'vexflow':
            return self.vfshow(obj)
            #subformats = ['lilypond','png']
        if subformats:
            helperFormat = subformats[0]
            helperSubformats = subformats[1:]
        else:
            helperFormat = "musicxml"
            helperSubformats = []

        if not helperSubformats:
            helperSubformats = ['png']

        from music21 import converter

        helperConverter = converter.Converter()
        helperConverter.setSubconverterFromFormat(helperFormat)
        helperSubConverter = helperConverter.subConverter

        if helperFormat in ('musicxml', 'xml', 'lilypond', 'lily'):
            ### hack to make musescore excerpts -- fix with a converter class in MusicXML
            savedDefaultTitle = defaults.title
            savedDefaultAuthor = defaults.author
            defaults.title = ''
            defaults.author = ''

            if 'Opus' not in obj.classes:
                fp = helperSubConverter.write(obj,
                                              helperFormat,
                                              subformats=helperSubformats)

                defaults.title = savedDefaultTitle
                defaults.author = savedDefaultAuthor
                if helperSubformats[0] == 'png':
                    from music21.ipython21 import objects as ipythonObjects
                    ipo = ipythonObjects.IPythonPNGObject(fp)
                    return ipo
            else:
                from IPython.display import Image, display  # @UnresolvedImport
                for s in obj.scores:
                    fp = helperSubConverter.write(s,
                                                  helperFormat,
                                                  subformats=helperSubformats)

                    if helperSubformats[0] == 'png':
                        from music21.ipython21 import objects as ipythonObjects  # @Reimport
                        ipo = ipythonObjects.IPythonPNGObject(fp)
                        display(Image(filename=ipo.fp, retina=True))
                defaults.title = savedDefaultTitle
                defaults.author = savedDefaultAuthor
                return None
        elif helperFormat == 'midi':
            import base64
            from IPython.display import HTML, display  # @UnresolvedImport @Reimport
            fp = helperSubConverter.write(obj,
                                          helperFormat,
                                          subformats=helperSubformats)
            with open(fp, 'rb') as f:
                binaryMidiData = f.read()
            binaryBase64 = base64.b64encode(binaryMidiData)
            s = common.SingletonCounter()
            outputId = "midiPlayerDiv" + str(s())
            display(
                HTML("""
                <div id='""" + outputId + """'></div>
                <link rel="stylesheet" href="http://artusi.xyz/music21j/css/m21.css" 
                    type="text/css" />
                <script>
                require.config({
                    paths: {'music21': 'http://artusi.xyz/music21j/src/music21'} 
                }); 
                require(['music21'], function() { 
                               mp = new music21.miditools.MidiPlayer();
                               mp.addPlayer('#""" + outputId + """'); 
                               mp.base64Load('data:audio/midi;base64,""" +
                     binaryBase64.decode('utf-8') + """'); 
                        });
                </script>"""))
Exemplo n.º 18
0
    def show(self, obj, fmt, app=None, subformats=None, **keywords): # pragma: no cover
        '''
        show using the appropriate subformat.
        '''
        if subformats is None:
            subformats = ['vexflow']

        if subformats and subformats[0] == 'vexflow':
            return self.vfshow(obj)
            #subformats = ['lilypond', 'png']
        if subformats:
            helperFormat = subformats[0]
            helperSubformats = subformats[1:]
        else:
            helperFormat = "musicxml"
            helperSubformats = []

        if not helperSubformats:
            helperSubformats = ['png']

        from music21 import converter

        helperConverter = converter.Converter()
        helperConverter.setSubconverterFromFormat(helperFormat)
        helperSubConverter = helperConverter.subConverter

        from IPython.display import Image, display, HTML # @UnresolvedImport

        if helperFormat in ('musicxml', 'xml', 'lilypond', 'lily'):
            ### hack to make musescore excerpts -- fix with a converter class in MusicXML
            from music21.ipython21 import objects as ipythonObjects

            savedDefaultTitle = defaults.title
            savedDefaultAuthor = defaults.author
            defaults.title = ''
            defaults.author = ''


            if 'Opus' not in obj.classes:
                scores = [obj]
            else:
                scores = list(obj.scores)

            for s in scores:
                fp = helperSubConverter.write(s, helperFormat,
                                              subformats=helperSubformats, **keywords)

                if helperSubformats[0] == 'png':
                    if not str(environLocal['musescoreDirectPNGPath']).startswith('/skip'):
                        ipo = ipythonObjects.IPythonPNGObject(fp)
                        display(Image(data=ipo.getData(), retina=True))
                    else:
                        # smallest transparent pixel
                        pngData64 = (b'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA'
                                     + b'6fptVAAAACklEQVQYV2P4DwABAQEAWk1v8QAAAABJRU5ErkJggg==')
                        pngData = base64.b64decode(pngData64)
                        display(Image(data=pngData, retina=True))

            defaults.title = savedDefaultTitle
            defaults.author = savedDefaultAuthor
            return None

        elif helperFormat == 'midi':
            fp = helperSubConverter.write(obj, helperFormat, subformats=helperSubformats)
            with open(fp, 'rb') as f:
                binaryMidiData = f.read()

            binaryBase64 = base64.b64encode(binaryMidiData)
            s = common.SingletonCounter()
            outputId = "midiPlayerDiv" + str(s())
            display(HTML("""
                <div id='""" + outputId + """'></div>
                <link rel="stylesheet" href="http://artusi.xyz/music21j/css/m21.css"
                    type="text/css" />
                <script>
                require.config({
                    paths: {'music21': 'http://artusi.xyz/music21j/src/music21'}
                });
                require(['music21'], function() {
                               mp = new music21.miditools.MidiPlayer();
                               mp.addPlayer('#""" + outputId + """');
                               mp.base64Load('data:audio/midi;base64,""" +
                                   binaryBase64.decode('utf-8') + """');
                        });
                </script>"""))