Example #1
0
 def _write_gallery_to_disk(self):
     lilypond_file = self._gallery_input_to_lilypond_file()
     file_path = __file__
     directory_path = os.path.dirname(file_path)
     class_name = type(self).__name__
     file_name = '{}.pdf'.format(class_name)
     file_path = os.path.join(directory_path, 'gallery', file_name)
     persist(lilypond_file).as_pdf(file_path, remove_ly=True)
Example #2
0
    def write_test_output(
        output,
        full_file_name,
        test_function_name,
        cache_ly=False,
        cache_pdf=False,
        go=False,
        render_pdf=False,
        ):
        r'''Writes test output.

        Returns none.
        '''
        from abjad.tools import lilypondfiletools
        from abjad.tools import markuptools
        from abjad.tools import schemetools
        from abjad.tools import scoretools
        from abjad.tools import systemtools
        from abjad.tools import topleveltools
        if go:
            cache_ly = cache_pdf = render_pdf = True
        if not any([cache_ly, cache_pdf, render_pdf]):
            return
        if isinstance(output, scoretools.Score):
            lilypond_file = \
                lilypondfiletools.make_floating_time_signature_lilypond_file(
                    output)
            TestManager.apply_additional_layout(lilypond_file)
            score = output
        elif isinstance(output, lilypondfiletools.LilyPondFile):
            lilypond_file = output
            score = lilypond_file.score_block[0]
        else:
            message = 'output must be score or LilyPond file: {!r}.'
            message = message.format(output)
            raise TypeError(message)
        title_lines = TestManager.test_function_name_to_title_lines(
            test_function_name)
        lilypond_file.header_block.title = \
            markuptools.make_centered_title_markup(
                title_lines,
                font_size=6,
                vspace_before=2,
                vspace_after=4,
                )
        parent_directory_name = os.path.dirname(full_file_name)
        if render_pdf:
            topleveltools.show(lilypond_file)
        if cache_pdf:
            file_name = '{}.pdf'.format(test_function_name)
            pdf_path_name = os.path.join(parent_directory_name, file_name)
            topleveltools.persist(lilypond_file).as_pdf(pdf_path_name)
        if cache_ly:
            file_name = '{}.ly'.format(test_function_name)
            ly_path_name = os.path.join(parent_directory_name, file_name)
            with open(ly_path_name, 'w') as f:
                f.write(format(score))
Example #3
0
    def write_test_output(
        output,
        full_file_name,
        test_function_name,
        cache_ly=False,
        cache_pdf=False,
        go=False,
        render_pdf=False,
    ):
        r'''Writes test output.

        Returns none.
        '''
        from abjad.tools import lilypondfiletools
        from abjad.tools import markuptools
        from abjad.tools import schemetools
        from abjad.tools import scoretools
        from abjad.tools import systemtools
        from abjad.tools import topleveltools
        if go:
            cache_ly = cache_pdf = render_pdf = True
        if not any([cache_ly, cache_pdf, render_pdf]):
            return
        if isinstance(output, scoretools.Score):
            lilypond_file = \
                lilypondfiletools.make_floating_time_signature_lilypond_file(
                    output)
            TestManager.apply_additional_layout(lilypond_file)
            score = output
        elif isinstance(output, lilypondfiletools.LilyPondFile):
            lilypond_file = output
            score = lilypond_file.score_block[0]
        else:
            message = 'output must be score or LilyPond file: {!r}.'
            message = message.format(output)
            raise TypeError(message)
        title_lines = TestManager.test_function_name_to_title_lines(
            test_function_name)
        lilypond_file.header_block.title = \
            markuptools.make_centered_title_markup(
                title_lines,
                font_size=6,
                vspace_before=2,
                vspace_after=4,
                )
        parent_directory_name = os.path.dirname(full_file_name)
        if render_pdf:
            topleveltools.show(lilypond_file)
        if cache_pdf:
            file_name = '{}.pdf'.format(test_function_name)
            pdf_path_name = os.path.join(parent_directory_name, file_name)
            topleveltools.persist(lilypond_file).as_pdf(pdf_path_name)
        if cache_ly:
            file_name = '{}.ly'.format(test_function_name)
            ly_path_name = os.path.join(parent_directory_name, file_name)
            with open(ly_path_name, 'w') as f:
                f.write(format(score))
Example #4
0
def play(argument):
    r'''Plays `argument`.

    ..  container:: example

        >>> note = abjad.Note("c'4")
        >>> abjad.play(note) # doctest: +SKIP

    Makes MIDI file.

    Appends ``.mid`` filename extension under Windows.

    Appends ``.midi`` filename extension under other operating systems.

    Opens MIDI file.

    Returns none.
    '''
    from abjad import abjad_configuration
    from abjad.tools import systemtools
    from abjad.tools import topleveltools
    assert hasattr(argument, '__illustrate__')
    result = topleveltools.persist(argument).as_midi()
    midi_file_path, abjad_formatting_time, lilypond_rendering_time = result
    midi_player = abjad_configuration['midi_player']
    systemtools.IOManager.open_file(midi_file_path, midi_player)
Example #5
0
def show(expr, return_timing=False, **kwargs):
    r'''Shows `expr`.

    ..  container:: example

        Shows a note:

        ::

            >>> note = Note("c'4")
            >>> show(note) # doctest: +SKIP

    Abjad writes LilyPond input files to the ``~/.abjad/output/``
    directory by default.

    You may change this by setting the ``abjad_output_directory_path`` variable in
    the Abjad ``config.py`` file.

    Returns none when `return_timing` is false.
    
    Returns pair of `abjad_formatting_time` and `lilypond_rendering_time`
    when `return_timing` is true.
    '''
    from abjad.tools import systemtools
    from abjad.tools import topleveltools
    assert '__illustrate__' in dir(expr)
    result = topleveltools.persist(expr).as_pdf(**kwargs)
    pdf_file_path = result[0]
    abjad_formatting_time = result[1]
    lilypond_rendering_time = result[2]
    success = result[3]
    if success:
        systemtools.IOManager.open_file(pdf_file_path)
    if return_timing:
        return abjad_formatting_time, lilypond_rendering_time
Example #6
0
def play(expr):
    r'''Plays `expr`.

    ::

        >>> note = Note("c'4")

    ::

        >>> topleveltools.play(note) # doctest: +SKIP

    This input creates and opens a one-note MIDI file.

    Abjad outputs MIDI files of the format ``file_name.mid``
    under Windows.

    Abjad outputs MIDI files of the format ``file_name.midi``
    under other operating systems.

    Returns none.
    '''
    from abjad import abjad_configuration
    from abjad.tools import systemtools
    from abjad.tools import topleveltools
    assert '__illustrate__' in dir(expr)
    midi_file_path, abjad_formatting_time, lilypond_rendering_time = \
        topleveltools.persist(expr).as_midi()
    midi_player = abjad_configuration['midi_player']
    systemtools.IOManager.open_file(midi_file_path, midi_player)
Example #7
0
def show(expr, return_timing=False, **kwargs):
    r'''Shows `expr`.

    ..  container:: example

        Shows a note:

        ::

            >>> note = Note("c'4")
            >>> show(note) # doctest: +SKIP

    Abjad writes LilyPond input files to the ``~/.abjad/output/``
    directory by default.

    You may change this by setting the ``abjad_output_directory`` variable in
    the Abjad ``config.py`` file.

    Returns none when `return_timing` is false.

    Returns pair of `abjad_formatting_time` and `lilypond_rendering_time`
    when `return_timing` is true.
    '''
    from abjad.tools import systemtools
    from abjad.tools import topleveltools
    assert hasattr(expr, '__illustrate__')
    result = topleveltools.persist(expr).as_pdf(**kwargs)
    pdf_file_path = result[0]
    abjad_formatting_time = result[1]
    lilypond_rendering_time = result[2]
    success = result[3]
    if success:
        systemtools.IOManager.open_file(pdf_file_path)
    if return_timing:
        return abjad_formatting_time, lilypond_rendering_time
def _get_png(expr):
    """Calls lilypond and converts output to (multi-page) PNGs."""
    pngs = []
    tmpdir = tempfile.mkdtemp()
    agent = topleveltools.persist(expr)
    result = agent.as_ly(tmpdir + os.sep + 'out.ly')
    ly_file_path, abjad_formatting_time = result
    cmd = 'lilypond --png -o%s/out %s/out.ly' % (tmpdir, tmpdir)
    result = systemtools.IOManager.spawn_subprocess(cmd)
    try:
        imgs = [wimg(filename=tmpdir + os.sep + 'out.png')]
    except:
        #This might be a multipage output
        #We are going to send all pages
        imgs = []
        for i in range(1000):  # Lets hope you do not have more than 1000 pages
            try:
                imgs.append(wimg(filename=tmpdir + os.sep +
                                 'out-page%d.png' % (i + 1)))
            except:
                if i == 0:  # No images
                    raise
                else:
                    break

    for img in imgs:
        img.trim()
        img.save(filename=tmpdir + os.sep + 'trim.png')
        f = open(tmpdir + os.sep + 'trim.png', 'rb')
        png = f.read()
        pngs.append(png)
        f.close()
    shutil.rmtree(tmpdir)
    return pngs
Example #9
0
File: Play.py Project: ajyoon/abjad
 def __call__(self, expr):
     '''Render `expr` as audio and display it in the IPython notebook
     as an <audio> tag.
     '''
     from abjad.tools import systemtools
     from abjad.tools import topleveltools
     assert hasattr(expr, '__illustrate__')
     assert systemtools.IOManager.find_executable('lilypond')
     assert systemtools.IOManager.find_executable('timidity')
     has_vorbis = self._check_for_vorbis()
     temp_directory = tempfile.mkdtemp()
     midi_file_path = os.path.join(temp_directory, 'out.midi')
     result = topleveltools.persist(expr).as_midi(midi_file_path)
     midi_file_path, format_time, render_time = result
     if has_vorbis:
         audio_file_path = os.path.join(temp_directory, 'out.ogg')
     else:
         audio_file_path = os.path.join(temp_directory, 'out.aif')
     encoded_audio = self._get_audio_as_base64(
         midi_file_path,
         audio_file_path,
         has_vorbis,
         )
     if encoded_audio is not None:
         self._display_audio_tag(encoded_audio, has_vorbis)
     shutil.rmtree(temp_directory)
Example #10
0
def _get_png(expr):
    """Calls lilypond and converts output to (multi-page) PNGs."""
    pngs = []
    tmpdir = tempfile.mkdtemp()
    agent = topleveltools.persist(expr)
    result = agent.as_ly(tmpdir + os.sep + 'out.ly')
    ly_file_path, abjad_formatting_time = result
    cmd = 'lilypond --png -o%s/out %s/out.ly' % (tmpdir, tmpdir)
    result = systemtools.IOManager.spawn_subprocess(cmd)
    try:
        imgs = [wimg(filename=tmpdir + os.sep + 'out.png')]
    except:
        #This might be a multipage output
        #We are going to send all pages
        imgs = []
        for i in range(1000):  # Lets hope you do not have more than 1000 pages
            try:
                imgs.append(
                    wimg(filename=tmpdir + os.sep + 'out-page%d.png' %
                         (i + 1)))
            except:
                if i == 0:  # No images
                    raise
                else:
                    break

    for img in imgs:
        img.trim()
        img.save(filename=tmpdir + os.sep + 'trim.png')
        f = open(tmpdir + os.sep + 'trim.png', 'rb')
        png = f.read()
        pngs.append(png)
        f.close()
    shutil.rmtree(tmpdir)
    return pngs
Example #11
0
 def __call__(self, expr):
     r'''A replacement for Ajbad's show function for IPython Notebook.
     '''
     from abjad.tools import systemtools
     from abjad.tools import topleveltools
     from IPython.core.display import display_png
     assert systemtools.IOManager.find_executable('lilypond')
     assert systemtools.IOManager.find_executable('convert')
     assert hasattr(expr, '__illustrate__')
     temporary_directory = tempfile.mkdtemp()
     temporary_file_path = os.path.join(
         temporary_directory,
         'output.png',
         )
     result = topleveltools.persist(expr).as_png(temporary_file_path)
     pngs = []
     for file_path in result[0]:
         command = 'convert {file_path} -trim {file_path}'
         command = command.format(file_path=file_path)
         systemtools.IOManager.spawn_subprocess(command)
         with open(file_path, 'rb') as file_pointer:
             file_contents = file_pointer.read()
             pngs.append(file_contents)
     shutil.rmtree(temporary_directory)
     for png in pngs:
         display_png(png, raw=True)
Example #12
0
 def __call__(self, expr):
     '''Render `expr` as audio and display it in the IPython notebook
     as an <audio> tag.
     '''
     from abjad.tools import systemtools
     from abjad.tools import topleveltools
     assert hasattr(expr, '__illustrate__')
     assert systemtools.IOManager.find_executable('lilypond')
     assert systemtools.IOManager.find_executable('timidity')
     has_vorbis = self._check_for_vorbis()
     temp_directory = tempfile.mkdtemp()
     midi_file_path = os.path.join(temp_directory, 'out.midi')
     result = topleveltools.persist(expr).as_midi(midi_file_path)
     midi_file_path, format_time, render_time = result
     if has_vorbis:
         audio_file_path = os.path.join(temp_directory, 'out.ogg')
     else:
         audio_file_path = os.path.join(temp_directory, 'out.aif')
     encoded_audio = self._get_audio_as_base64(
         midi_file_path,
         audio_file_path,
         has_vorbis,
     )
     if encoded_audio is not None:
         self._display_audio_tag(encoded_audio, has_vorbis)
     shutil.rmtree(temp_directory)
Example #13
0
def play(expr):
    r"""Plays `expr`.

    ::

        >>> note = Note("c'4")

    ::

        >>> topleveltools.play(note) # doctest: +SKIP

    This input creates and opens a one-note MIDI file.

    Abjad outputs MIDI files of the format ``file_name.mid``
    under Windows.

    Abjad outputs MIDI files of the format ``file_name.midi``
    under other operating systems.

    Returns none.
    """
    from abjad import abjad_configuration
    from abjad.tools import systemtools
    from abjad.tools import topleveltools

    assert hasattr(expr, "__illustrate__")
    midi_file_path, abjad_formatting_time, lilypond_rendering_time = topleveltools.persist(expr).as_midi()
    midi_player = abjad_configuration["midi_player"]
    systemtools.IOManager.open_file(midi_file_path, midi_player)
Example #14
0
    def __call__(self, expr):
        '''Render `expr` as Vorbis audio and display it in the IPython notebook
        as an <audio> tag.

        This function requires `fluidsynth` and `ffmpeg` to convert MIDI into
        an audio recording.
        '''
        from abjad.tools import systemtools
        from abjad.tools import topleveltools
        if not systemtools.IOManager.find_executable('fluidsynth'):
            message = 'WARNING: fluidsynth is not available; '
            message += 'cannot render MIDI file to MP3.'
            print(message)
            return
        if not systemtools.IOManager.find_executable('ffmpeg'):
            message = 'WARNING: ffmpeg is not available; '
            message += 'cannot render MIDI file to MP3.'
            print(message)
            return
        assert hasattr(expr, '__illustrate__')
        sound_font = self.sound_font
        if not sound_font:
            message = 'sound_font is not specified, please call '
            message += "'load_sound_font(sound_font, midi_bank)' "
            message += 'to select a sound font.'
            print(message)
        sound_font = sound_font or ''
        temp_directory = tempfile.mkdtemp()
        midi_file_path = os.path.join(temp_directory, 'out.mid')
        result = topleveltools.persist(expr).as_midi(midi_file_path)
        midi_file_path, format_time, render_time = result
        ogg_file_path = os.path.join(temp_directory, 'out.ogg')
        mp3_file_path = os.path.join(temp_directory, 'out.mp3')
        encoded_audio = self._get_ogg_as_base64(
            self.midi_bank,
            midi_file_path,
            ogg_file_path,
            sound_font,
        )
        if encoded_audio is not None:
            encoded_audio = self._get_mp3_as_base64(
                mp3_file_path,
                ogg_file_path,
            )
            if encoded_audio is not None:
                self._display_mp3_audio_tag(encoded_audio)
        shutil.rmtree(temp_directory)
Example #15
0
File: Play.py Project: DnMllr/abjad
    def __call__(self, expr):
        '''Render `expr` as Vorbis audio and display it in the IPython notebook
        as an <audio> tag.

        This function requires `fluidsynth` and `ffmpeg` to convert MIDI into
        an audio recording.
        '''
        from abjad.tools import systemtools
        from abjad.tools import topleveltools
        if not systemtools.IOManager.find_executable('fluidsynth'):
            message = 'WARNING: fluidsynth is not available; '
            message += 'cannot render MIDI file to MP3.'
            print(message)
            return
        if not systemtools.IOManager.find_executable('ffmpeg'):
            message = 'WARNING: ffmpeg is not available; '
            message += 'cannot render MIDI file to MP3.'
            print(message)
            return
        assert hasattr(expr, '__illustrate__')
        sound_font = self.sound_font
        if not sound_font:
            message = 'sound_font is not specified, please call '
            message += "'load_sound_font(sound_font, midi_bank)' "
            message += 'to select a sound font.'
            print(message)
        sound_font = sound_font or ''
        temp_directory = tempfile.mkdtemp()
        midi_file_path = os.path.join(temp_directory, 'out.mid')
        result = topleveltools.persist(expr).as_midi(midi_file_path)
        midi_file_path, format_time, render_time = result
        ogg_file_path = os.path.join(temp_directory, 'out.ogg')
        mp3_file_path = os.path.join(temp_directory, 'out.mp3')
        encoded_audio = self._get_ogg_as_base64(
            self.midi_bank,
            midi_file_path,
            ogg_file_path,
            sound_font,
            )
        if encoded_audio is not None:
            encoded_audio = self._get_mp3_as_base64(
                mp3_file_path,
                ogg_file_path,
                )
            if encoded_audio is not None:
                self._display_mp3_audio_tag(encoded_audio)
        shutil.rmtree(temp_directory)
Example #16
0
def show(expr, return_timing=False, **kwargs):
    r'''Shows `expr`.

    ..  container:: example

        **Example 1.** Show a note:

        ::

            >>> note = Note("c'4")
            >>> show(note) # doctest: +SKIP

    ..  container:: example

        **Example 2.** Show a note and return Abjad and LilyPond processing
        times in seconds:

        ::

            >>> staff = Staff(Note("c'4") * 200)
            >>> show(staff, return_timing=True) # doctest: +SKIP
            (0, 1)

    Wraps `expr` in a LilyPond file with settings and overrides suitable
    for the Abjad reference manual When `docs` is true.

    Abjad writes LilyPond input files to the ``~/.abjad/output``
    directory by default.

    You may change this by setting the ``abjad_output`` variable in
    the ``config.py`` file.

    Returns none or timing tuple.
    '''
    from abjad.tools import systemtools
    from abjad.tools import topleveltools
    assert '__illustrate__' in dir(expr)
    pdf_file_path, abjad_formatting_time, lilypond_rendering_time, success = \
        topleveltools.persist(expr).as_pdf(**kwargs)
    if success:
        systemtools.IOManager.open_file(pdf_file_path)
    if return_timing:
        return abjad_formatting_time, lilypond_rendering_time
    def __call__(self, expr):
        '''Render `expr` as Vorbis audio and display it in the IPython notebook
        as an <audio> tag.

        This function requires `fluidsynth` and `ffmpeg` to convert MIDI into
        an audio recording.
        '''
        from abjad.tools import systemtools
        from abjad.tools import topleveltools
        if not systemtools.IOManager.find_executable('fluidsynth'):
            print('fluidsynth is not available.')
        if not systemtools.IOManager.find_executable('ffmpeg'):
            print('ffmpeg is not available.')
        assert '__illustrate__' in dir(expr)
        sound_font = self.sound_font
        if not sound_font:
            message = 'sound_font is not specified, please call '
            message += "'load_sound_font(sound_font, midi_bank)' "
            message += 'to select a sound font.'
            print(message)
        sound_font = sound_font or ''
        temp_directory = tempfile.mkdtemp()
        midi_file_path = os.path.join(temp_directory, 'out.mid')
        result = topleveltools.persist(expr).as_midi(midi_file_path)
        midi_file_path, format_time, render_time = result
        ogg_file_path = os.path.join(temp_directory, 'out.ogg')
        mp3_file_path = os.path.join(temp_directory, 'out.mp3')
        rendered_successfully = self._display_ogg(
            self.midi_bank,
            midi_file_path,
            ogg_file_path,
            sound_font,
            )
        if rendered_successfully:
            self._display_mp3(mp3_file_path, ogg_file_path)
        shutil.rmtree(temp_directory)