Sha256: 3a1a3d1b9d3ad5f77d9d7caab4d1ecf7d5346913ea0ec824522954db3d00ed40

Contents?: true

Size: 1.95 KB

Versions: 3

Compression:

Stored size: 1.95 KB

Contents

require_relative 'processor'

require 'ssmd/annotations'

module SSMD::Processors
  class AnnotationProcessor < Processor
    attr_reader :annotations

    def result
      _, annotations_text = match.captures

      if annotations_text
        @annotations = combine_annotations parse_annotations(annotations_text)

        @annotations.inject(text) do |text, a|
          a.wrap(text)
        end
      end
    end

    def self.annotations
      a = SSMD::Annotations

      [a::LanguageAnnotation, a::PhonemeAnnotation, a::ProsodyAnnotation]
    end

    def ok?
      !@text.nil? && Array(@annotations).size > 0
    end

    def error?
      !ok?
    end

    private

    def parse_annotations(text)
      text.split(/, ?/).flat_map do |annotation_text|
        annotation = find_annotation annotation_text

        if annotation.nil?
          warnings.push "Unknown annotation: #{text}"
        end

        [annotation].compact
      end
    end

    def find_annotation(text)
      self.class.annotations.lazy
        .map { |a| a.try text }
        .find { |a| !a.nil? }
    end

    def combine_annotations(annotations)
      annotations
        .group_by { |a| a.class }
        .values
        .map { |as| as.reduce { |a, b| a.combine b } }
    end

    ##
    # Matches explicitly annotated sections.
    # For example:
    #
    #     [Guardians of the Galaxy](en-GB, v: +4dB, p: -3%)
    def regex
      %r{
        \[                              # opening text
          ([^\]]+)                      # annotated text
        \]                              # closing text
        \(                              # opening annotations
          ((?:
            (?:
              #{annotations_regex}      # annotations
            )(?:,\s?)?
          )+)
        \)                              # closing annotations
      }x
    end

    def annotations_regex
      self.class.annotations.map(&:regex).join("|")
    end

    def warnings
      @warnings ||= []
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ssmd-0.4.0 lib/ssmd/processors/annotation_processor.rb
ssmd-0.3.1 lib/ssmd/processors/annotation_processor.rb
ssmd-0.3.0 lib/ssmd/processors/annotation_processor.rb