<commit_before># -*- encoding: utf-8 -*-
from __future__ import print_function
import collections
import importlib
import os
import re
from abjad.tools import durationtools
from abjad.tools import indicatortools
from abjad.tools import lilypondfiletools
from abjad.tools import markuptools
from abjad.tools import scoretools
from abjad.tools import systemtools
from abjad.tools import timespantools
from abjad.tools.topleveltools import attach
from abjad.tools.topleveltools import inspect_
from abjad.tools.topleveltools import iterate
from experimental.tools import makertools


class SegmentMaker(makertools.SegmentMaker):
    r'''A Consort segment-maker.

    ::

        >>> from consort import makers
        >>> score_template = templatetools.StringOrchestraScoreTemplate(
        ...     violin_count=2,
        ...     viola_count=1,
        ...     cello_count=1,
        ...     contrabass_count=0,
        ...     )

    ::

        >>> segment_maker = makers.SegmentMaker(
        ...     score_template=score_template,
        ...     settings=(
        ...         makers.MusicSetting(
        ...             timespan_maker=makers.TaleaTimespanMaker(),
        ...             violin_1_bowing_voice=makers.MusicSpecifier(),
        ...             violin_2_bowing_voice=makers.MusicSpecifier(),
        ...             ),
        ...         ),
        ...     duration_in_seconds=2,
        ...     tempo=indicatortools.Tempo((1, 4), 72),
        ...     permitted_time_signatures=(
        ...         (5, 8),
        ...         (7, 16),
        ...         ),
        ...     )
        >>> print(format(segment_maker))
        consort.makers.SegmentMaker(
            duration_in_seconds=durationtools.Duration(2, 1),
            permitted_time_signatures=indicatortools.TimeSignatureInventory(
                [
                    indicatortools.TimeSignature((5, 8)),
                    indicatortools.TimeSignature((7, 16)),
                    ]
                ),
            score_template=templatetools.StringOrchestraScoreTemplate(
                violin_count=2,
                viola_count=1,
                cello_count=1,
                contrabass_count=0,
                split_hands=True,
                use_percussion_clefs=False,
                ),
            settings=(
                consort.makers.MusicSetting(
                    timespan_maker=consort.makers.TaleaTimespanMaker(
                        can_split=True,
                        playing_talea=rhythmmakertools.Talea(
                            counts=(4,),
                            denominator=16,
                            ),
                        playing_groupings=(1,),
                        repeat=True,
                        silence_talea=rhythmmakertools.Talea(
                            counts=(4,),
                            denominator=16,
                            ),
                        step_anchor=Right,
                        synchronize_groupings=False,
                        synchronize_step=False,
                        ),
                    violin_1_bowing_voice=consort.makers.MusicSpecifier(),
                    violin_2_bowing_voice=consort.makers.MusicSpecifier(),
                    ),
                ),
            tempo=indicatortools.Tempo(
                duration=durationtools.Duration(1, 4),
                units_per_minute=72,
                ),
            )

    ::

        >>> lilypond_file = segment_maker()
        TimespanManager:
            made independent timespans: ...
            found meters: ...
            made voicewise timespans (1/2): ...
            cleaned-up performed timespans: ...
            made dependent timespans: ...
            made voicewise timespans (2/2): ...
            made silent timespans: ...
            total: ...
        RhythmManager:
            populating time signature context: ...
            populating rhythms: ...
            rewriting meters: ...
            cleaning up silences: ...
            total: ...
        AnnotationManager (1):
            total: ...
        GraceMaker:
            total: ...
        PitchMaker:
            total: ...
        AttachmentMaker:
            total: ...
        AnnotationManager (2):
            total: ...

    '''

    ### CLASS VARIABLES ###

    __slots__ = (
        '_annotation_specifier',
        '_discard_final_silence',
        '_duration_in_seconds',
        '_is_final_segment',
        '_permitted_time_signatures',
        '_rehearsal_mark',
        '_score_template',
        '_settings',
        '_tempo',
        )

    ### INITIALIZER ###

    def __init__(
        self,
        annotation_specifier=None,
        discard_final_silence=None,
        duration_in_seconds=None,
        is_final_segment=None,
        name=None,
        permitted_time_signatures=None,
        rehearsal_mark=None,
        score_template=None,
        settings=None,
        tempo=None,
        ):
        from consort import makers
        makertools.SegmentMaker.__init__(
            self,
            name=name,
            )
        if discard_final_silence is not None:
            discard_final_silence = bool(discard_final_silence)
        self._discard_final_silence = discard_final_silence
        self.set_annotation_specifier(annotation_specifier)
        self.set_duration_in_seconds(duration_in_seconds)
        self.set_is_final_segment(is_final_segment)
        self.set_rehearsal_mark(rehearsal_mark)
        self.set_score_template(score_template)
        self.set_tempo(tempo)
        self.set_permitted_time_signatures(permitted_time_signatures)
        if settings is not None:
            assert isinstance(settings, collections.Sequence)
            prototype = makers.MusicSetting
            assert all(isinstance(x, prototype) for x in settings)
            settings = list(settings)
        self._settings = settings or []

    ### SPECIAL METHODS ###

    def __call__(self):
        from consort import makers

        segment_session = makers.SegmentSession(segment_maker=self)
        segment_session.score = self.score_template()
        assert isinstance(segment_session.score, scoretools.Score)
        timer = systemtools.Timer()

        with timer:
            print('TimespanManager:')
            segment_session = makers.TimespanManager.execute(
                discard_final_silence=self.discard_final_silence,
                permitted_time_signatures=self.permitted_time_signatures,
                score_template=self.score_template,
                segment_session=segment_session,
                settings=self.settings or (),
                target_duration=self.target_duration,
                )
            print('\ttotal:', timer.elapsed_time)

        with timer:
            print('RhythmManager:')
            segment_session = makers.RhythmManager.execute(
                annotation_specifier=self.annotation_specifier,
                segment_session=segment_session,
                )
            print('\ttotal:', timer.elapsed_time)

        with timer:
            print('AnnotationManager (1):')
            if self.annotation_specifier is not None:
                if self.annotation_specifier.show_stage_1:
                    makers.AnnotationManager._annotate_stage_1(segment_session)
                if self.annotation_specifier.show_stage_2:
                    makers.AnnotationManager._annotate_stage_2(segment_session)
                if self.annotation_specifier.show_stage_3:
                    makers.AnnotationManager._annotate_stage_3(segment_session)
                if self.annotation_specifier.show_stage_4:
                    makers.AnnotationManager._annotate_stage_4(segment_session)
                if self.annotation_specifier.show_stage_5:
                    makers.AnnotationManager._annotate_stage_5(segment_session)
            print('\ttotal:', timer.elapsed_time)

        with systemtools.ForbidUpdate(segment_session.score):

            with timer:
                print('GraceMaker:')
                self._process_score(segment_session.score, 'grace_maker')
                print('\ttotal:', timer.elapsed_time)

            with timer:
                print('PitchMaker:')
                self._process_score(segment_session.score, 'pitch_maker')
                print('\ttotal:', timer.elapsed_time)

            with timer:
                print('AttachmentMaker:')
                self._process_score(segment_session.score, 'attachment_maker')
                print('\ttotal:', timer.elapsed_time)

        with timer:
            print('AnnotationManager (2):')
            if self.annotation_specifier is not None:
                if self.annotation_specifier.show_annotated_result:
                    should_copy = True
                    if not self.annotation_specifier.show_unannotated_result:
                        should_copy = False
                    makers.AnnotationManager._annotate_stage_6(
                        segment_session=segment_session,
                        should_copy=should_copy,
                        )
                if self.annotation_specifier.show_unannotated_result:
                    segment_session.scores.append(segment_session.score)
            else:
                segment_session.scores.append(segment_session.score)
            print('\ttotal:', timer.elapsed_time)

        lilypond_file = self._make_lilypond_file()
        for score in segment_session.scores:
            score = self._configure_score(score)
            score_block = lilypondfiletools.Block(name='score')
            score_block.items.append(score)
            lilypond_file.items.append(score_block)

        return lilypond_file

    def __illustrate__(self):
        return self()

    ### PRIVATE METHODS ###

    def _configure_score(self, score):
        if self.rehearsal_mark is not None:
            markup = markuptools.Markup(r'''
                \override #'(box-padding . 0.5)
                    \box "{}"
                " "
                \fontsize #-3
                    "{}"
                '''.format(str(self.rehearsal_mark), self.name or ' '),
                )
            rehearsal_mark = indicatortools.RehearsalMark(
                markup=markup,
                )
            attach(
                rehearsal_mark,
                score['TimeSignatureContext'].select_leaves()[0],
                )
        if self.tempo is not None:
            attach(
                self.tempo,
                score['TimeSignatureContext'].select_leaves()[0],
                )
        if self.is_final_segment:
            score.add_final_markup(self.final_markup)
            score.add_final_bar_line()
        else:
            score.add_final_bar_line('||')
        assert inspect_(score).is_well_formed()
        return score

    @staticmethod
    def _find_voice_names(
        score_template=None,
        voice_identifier=None,
        ):
        r'''Find voice names matching `voice_identifier` in `score_template`:

        ::

            >>> from consort import makers
            >>> score_template = templatetools.StringOrchestraScoreTemplate(<commit_msg>Improved final barline application.<commit_after># -*- encoding: utf-8 -*-
from __future__ import print_function
import collections
import importlib
import os
import re
from abjad.tools import durationtools
from abjad.tools import indicatortools
from abjad.tools import lilypondfiletools
from abjad.tools import markuptools
from abjad.tools import scoretools
from abjad.tools import systemtools
from abjad.tools import timespantools
from abjad.tools.topleveltools import attach
from abjad.tools.topleveltools import inspect_
from abjad.tools.topleveltools import iterate
from experimental.tools import makertools


class SegmentMaker(makertools.SegmentMaker):
    r'''A Consort segment-maker.

    ::

        >>> from consort import makers
        >>> score_template = templatetools.StringOrchestraScoreTemplate(
        ...     violin_count=2,
        ...     viola_count=1,
        ...     cello_count=1,
        ...     contrabass_count=0,
        ...     )

    ::

        >>> segment_maker = makers.SegmentMaker(
        ...     score_template=score_template,
        ...     settings=(
        ...         makers.MusicSetting(
        ...             timespan_maker=makers.TaleaTimespanMaker(),
        ...             violin_1_bowing_voice=makers.MusicSpecifier(),
        ...             violin_2_bowing_voice=makers.MusicSpecifier(),
        ...             ),
        ...         ),
        ...     duration_in_seconds=2,
        ...     tempo=indicatortools.Tempo((1, 4), 72),
        ...     permitted_time_signatures=(
        ...         (5, 8),
        ...         (7, 16),
        ...         ),
        ...     )
        >>> print(format(segment_maker))
        consort.makers.SegmentMaker(
            duration_in_seconds=durationtools.Duration(2, 1),
            permitted_time_signatures=indicatortools.TimeSignatureInventory(
                [
                    indicatortools.TimeSignature((5, 8)),
                    indicatortools.TimeSignature((7, 16)),
                    ]
                ),
            score_template=templatetools.StringOrchestraScoreTemplate(
                violin_count=2,
                viola_count=1,
                cello_count=1,
                contrabass_count=0,
                split_hands=True,
                use_percussion_clefs=False,
                ),
            settings=(
                consort.makers.MusicSetting(
                    timespan_maker=consort.makers.TaleaTimespanMaker(
                        can_split=True,
                        playing_talea=rhythmmakertools.Talea(
                            counts=(4,),
                            denominator=16,
                            ),
                        playing_groupings=(1,),
                        repeat=True,
                        silence_talea=rhythmmakertools.Talea(
                            counts=(4,),
                            denominator=16,
                            ),
                        step_anchor=Right,
                        synchronize_groupings=False,
                        synchronize_step=False,
                        ),
                    violin_1_bowing_voice=consort.makers.MusicSpecifier(),
                    violin_2_bowing_voice=consort.makers.MusicSpecifier(),
                    ),
                ),
            tempo=indicatortools.Tempo(
                duration=durationtools.Duration(1, 4),
                units_per_minute=72,
                ),
            )

    ::

        >>> lilypond_file = segment_maker()
        TimespanManager:
            made independent timespans: ...
            found meters: ...
            made voicewise timespans (1/2): ...
            cleaned-up performed timespans: ...
            made dependent timespans: ...
            made voicewise timespans (2/2): ...
            made silent timespans: ...
            total: ...
        RhythmManager:
            populating time signature context: ...
            populating rhythms: ...
            rewriting meters: ...
            cleaning up silences: ...
            total: ...
        AnnotationManager (1):
            total: ...
        GraceMaker:
            total: ...
        PitchMaker:
            total: ...
        AttachmentMaker:
            total: ...
        AnnotationManager (2):
            total: ...

    '''

    ### CLASS VARIABLES ###

    __slots__ = (
        '_annotation_specifier',
        '_discard_final_silence',
        '_duration_in_seconds',
        '_is_final_segment',
        '_permitted_time_signatures',
        '_rehearsal_mark',
        '_score_template',
        '_settings',
        '_tempo',
        )

    ### INITIALIZER ###

    def __init__(
        self,
        annotation_specifier=None,
        discard_final_silence=None,
        duration_in_seconds=None,
        is_final_segment=None,
        name=None,
        permitted_time_signatures=None,
        rehearsal_mark=None,
        score_template=None,
        settings=None,
        tempo=None,
        ):
        from consort import makers
        makertools.SegmentMaker.__init__(
            self,
            name=name,
            )
        if discard_final_silence is not None:
            discard_final_silence = bool(discard_final_silence)
        self._discard_final_silence = discard_final_silence
        self.set_annotation_specifier(annotation_specifier)
        self.set_duration_in_seconds(duration_in_seconds)
        self.set_is_final_segment(is_final_segment)
        self.set_rehearsal_mark(rehearsal_mark)
        self.set_score_template(score_template)
        self.set_tempo(tempo)
        self.set_permitted_time_signatures(permitted_time_signatures)
        if settings is not None:
            assert isinstance(settings, collections.Sequence)
            prototype = makers.MusicSetting
            assert all(isinstance(x, prototype) for x in settings)
            settings = list(settings)
        self._settings = settings or []

    ### SPECIAL METHODS ###

    def __call__(self):
        from consort import makers

        segment_session = makers.SegmentSession(segment_maker=self)
        segment_session.score = self.score_template()
        assert isinstance(segment_session.score, scoretools.Score)
        timer = systemtools.Timer()

        with timer:
            print('TimespanManager:')
            segment_session = makers.TimespanManager.execute(
                discard_final_silence=self.discard_final_silence,
                permitted_time_signatures=self.permitted_time_signatures,
                score_template=self.score_template,
                segment_session=segment_session,
                settings=self.settings or (),
                target_duration=self.target_duration,
                )
            print('\ttotal:', timer.elapsed_time)

        with timer:
            print('RhythmManager:')
            segment_session = makers.RhythmManager.execute(
                annotation_specifier=self.annotation_specifier,
                segment_session=segment_session,
                )
            print('\ttotal:', timer.elapsed_time)

        with timer:
            print('AnnotationManager (1):')
            if self.annotation_specifier is not None:
                if self.annotation_specifier.show_stage_1:
                    makers.AnnotationManager._annotate_stage_1(segment_session)
                if self.annotation_specifier.show_stage_2:
                    makers.AnnotationManager._annotate_stage_2(segment_session)
                if self.annotation_specifier.show_stage_3:
                    makers.AnnotationManager._annotate_stage_3(segment_session)
                if self.annotation_specifier.show_stage_4:
                    makers.AnnotationManager._annotate_stage_4(segment_session)
                if self.annotation_specifier.show_stage_5:
                    makers.AnnotationManager._annotate_stage_5(segment_session)
            print('\ttotal:', timer.elapsed_time)

        with systemtools.ForbidUpdate(segment_session.score):

            with timer:
                print('GraceMaker:')
                self._process_score(segment_session.score, 'grace_maker')
                print('\ttotal:', timer.elapsed_time)

            with timer:
                print('PitchMaker:')
                self._process_score(segment_session.score, 'pitch_maker')
                print('\ttotal:', timer.elapsed_time)

            with timer:
                print('AttachmentMaker:')
                self._process_score(segment_session.score, 'attachment_maker')
                print('\ttotal:', timer.elapsed_time)

        with timer:
            print('AnnotationManager (2):')
            if self.annotation_specifier is not None:
                if self.annotation_specifier.show_annotated_result:
                    should_copy = True
                    if not self.annotation_specifier.show_unannotated_result:
                        should_copy = False
                    makers.AnnotationManager._annotate_stage_6(
                        segment_session=segment_session,
                        should_copy=should_copy,
                        )
                if self.annotation_specifier.show_unannotated_result:
                    segment_session.scores.append(segment_session.score)
            else:
                segment_session.scores.append(segment_session.score)
            print('\ttotal:', timer.elapsed_time)

        lilypond_file = self._make_lilypond_file()
        for score in segment_session.scores:
            score = self._configure_score(score)
            score_block = lilypondfiletools.Block(name='score')
            score_block.items.append(score)
            lilypond_file.items.append(score_block)

        return lilypond_file

    def __illustrate__(self):
        return self()

    ### PRIVATE METHODS ###

    def _configure_score(self, score):
        if self.rehearsal_mark is not None:
            markup = markuptools.Markup(r'''
                \override #'(box-padding . 0.5)
                    \box "{}"
                " "
                \fontsize #-3
                    "{}"
                '''.format(str(self.rehearsal_mark), self.name or ' '),
                )
            rehearsal_mark = indicatortools.RehearsalMark(
                markup=markup,
                )
            attach(
                rehearsal_mark,
                score['TimeSignatureContext'].select_leaves()[0],
                )
        if self.tempo is not None:
            attach(
                self.tempo,
                score['TimeSignatureContext'].select_leaves()[0],
                )
        if self.is_final_segment:
            score.add_final_markup(self.final_markup)
            score.add_final_bar_line(
                to_each_voice=True,
                )
        else:
            score.add_final_bar_line(
                abbreviation='||',
                to_each_voice=True,
                )
        assert inspect_(score).is_well_formed()
        return score

    @staticmethod
    def _find_voice_names(
        score_template=None,
        voice_identifier=None,
        ):
        r'''Find voice names matching `voice_identifier` in `score_template`:

        ::

            >>> from consort import makers
            >>> score_template = templatetools.StringOrchestraScoreTemplate(
{'fraction_non_alphanumeric': 0.0849412286538035, 'fraction_numerical': 0.005766245287203371, 'mean_word_length': 1.6198001394376016, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5863545', 'n_tokens_mistral': 6143, 'n_tokens_neox': 5884, 'n_words': 901}