Example #1
0
    def test_process_element(self):
        default_style_value_filter = DefaultStylePropertyValuesFilter({
            StyleProperties.Color:
            StyleProperties.Color.make_initial_value()
        })

        p = P()
        for style in StyleProperties.ALL:
            p.set_style(style, style.make_initial_value())

        self.assertEqual(len(StyleProperties.ALL), len(p._styles))
        self.assertEqual(StyleProperties.Color.make_initial_value(),
                         p.get_style(StyleProperties.Color))

        default_style_value_filter._process_element(p)

        self.assertIsNone(p.get_style(StyleProperties.Color))
        self.assertEqual(len(StyleProperties.ALL) - 1, len(p._styles))
Example #2
0
  def __init__(self, config: VTTWriterConfiguration):
    self._captions_counter: int = 0
    self._begin: Fraction = Fraction(0)
    self._end: Fraction = Fraction(0)
    self._paragraphs: List[VttCue] = []
    self._css_classes: List[CssClass] = []
    self._colors_used: Dict[str, str] = {}
    self._background_colors_used: Dict[str, str] = {}
    self._config = config

    self._filters = []

    if not self._config.line_position:
      self._filters.append(RegionsMergingFilter())

    self._filters.append(ParagraphsMergingFilter())

    supported_styles = {
      StyleProperties.FontWeight: [],
      StyleProperties.FontStyle: [
        FontStyleType.normal,
        FontStyleType.italic
      ],
      StyleProperties.TextDecoration: [
        TextDecorationType.underline
      ],
      StyleProperties.Color: [],
      StyleProperties.BackgroundColor: []
    }

    if self._config.line_position:
      supported_styles.update({
        StyleProperties.Position: [],
        StyleProperties.Origin: [],
        StyleProperties.DisplayAlign: [],
        StyleProperties.Extent: [],
      })
    
    self._filters.append(SupportedStylePropertiesFilter(supported_styles))

    self._filters.append(
      DefaultStylePropertyValuesFilter({
        StyleProperties.Color: NamedColors.white.value,
        StyleProperties.BackgroundColor: NamedColors.transparent.value,
        StyleProperties.FontWeight: FontWeightType.normal,
        StyleProperties.FontStyle: FontStyleType.normal,
      })
    )
Example #3
0
class SrtContext:
    """SRT writer context"""

    filters: List[Filter] = (
        RegionsMergingFilter(),
        ParagraphsMergingFilter(),
        SupportedStylePropertiesFilter({
            StyleProperties.FontWeight: [
                # Every values
            ],
            StyleProperties.FontStyle:
            [FontStyleType.normal, FontStyleType.italic],
            StyleProperties.TextDecoration: [TextDecorationType.underline],
            StyleProperties.Color: [
                # Every values
            ],
        }),
        DefaultStylePropertyValuesFilter({
            StyleProperties.Color:
            NamedColors.white.value,
            StyleProperties.FontWeight:
            FontWeightType.normal,
            StyleProperties.FontStyle:
            FontStyleType.normal,
        }))

    def __init__(self):
        self._captions_counter: int = 0
        self._begin: Fraction = Fraction(0)
        self._end: Fraction = Fraction(0)
        self._paragraphs: List[SrtParagraph] = []

    def append_element(self, element: model.ContentElement, begin: Fraction,
                       end: Optional[Fraction]):
        """Converts model element to SRT content"""

        if isinstance(element, model.Div):
            for elem in list(element):
                self.append_element(elem, begin, end)

        if isinstance(element, model.P):

            self._captions_counter += 1

            self._paragraphs.append(SrtParagraph(self._captions_counter))
            self._paragraphs[-1].set_begin(begin)
            self._paragraphs[-1].set_end(end)

            for elem in list(element):
                self.append_element(elem, begin, end)

            self._paragraphs[-1].normalize_eol()

            if self._paragraphs[-1].is_only_whitespace():
                LOGGER.debug("Removing empty paragraph.")
                self._paragraphs.pop()

        if isinstance(element, model.Span):
            is_bold = style.is_element_bold(element)
            is_italic = style.is_element_italic(element)
            is_underlined = style.is_element_underlined(element)
            font_color = style.get_font_color(element)

            if font_color is not None:
                self._paragraphs[-1].append_text(
                    style.FONT_COLOR_TAG_IN.format(font_color))

            if is_bold:
                self._paragraphs[-1].append_text(style.BOLD_TAG_IN)
            if is_italic:
                self._paragraphs[-1].append_text(style.ITALIC_TAG_IN)
            if is_underlined:
                self._paragraphs[-1].append_text(style.UNDERLINE_TAG_IN)

            for elem in list(element):
                self.append_element(elem, begin, end)

            if is_underlined:
                self._paragraphs[-1].append_text(style.UNDERLINE_TAG_OUT)
            if is_italic:
                self._paragraphs[-1].append_text(style.ITALIC_TAG_OUT)
            if is_bold:
                self._paragraphs[-1].append_text(style.BOLD_TAG_OUT)
            if font_color is not None:
                self._paragraphs[-1].append_text(style.FONT_COLOR_TAG_OUT)

        if isinstance(element, model.Br):
            self._paragraphs[-1].append_text("\n")

        if isinstance(element, model.Text):
            self._paragraphs[-1].append_text(element.get_text())

    def add_isd(self, isd, begin: Fraction, end: Optional[Fraction]):
        """Converts and appends ISD content to SRT content"""

        LOGGER.debug("Append ISD from %ss to %ss to SRT content.",
                     float(begin),
                     float(end) if end is not None else "unbounded")

        is_isd_empty = True

        for region in isd.iter_regions():

            if len(region) > 0:
                is_isd_empty = False

            for body in region:
                for div in list(body):
                    self.append_element(div, begin, end)

        if is_isd_empty:
            LOGGER.debug("Skipping empty paragraph.")

    def finish(self):
        """Checks and processes the last paragraph"""

        LOGGER.debug("Check and process the last SRT paragraph.")

        if self._paragraphs and self._paragraphs[-1].get_end() is None:
            if self._paragraphs[-1].is_only_whitespace():
                # if the last paragraph contains only whitespace, remove it
                LOGGER.debug("Removing empty unbounded last paragraph.")
                self._paragraphs.pop()

            else:
                # set default end time code
                LOGGER.warning(
                    "Set a default end value to paragraph (begin + 10s).")
                self._paragraphs[-1].set_end(
                    self._paragraphs[-1].get_begin().to_seconds() + 10.0)

    def __str__(self) -> str:
        return "\n".join(
            p.to_string(id + 1) for id, p in enumerate(self._paragraphs))
Example #4
0
    def test_process_isd(self):
        default_style_value_filter = DefaultStylePropertyValuesFilter({
            StyleProperties.BackgroundColor:
            NamedColors.red.value,
            StyleProperties.Direction:
            DirectionType.ltr
        })

        doc = ContentDocument()

        r1 = Region("r1", doc)
        r1.set_style(StyleProperties.BackgroundColor, NamedColors.red.value)
        r1.set_style(StyleProperties.LuminanceGain, 2.0)
        doc.put_region(r1)

        b = Body(doc)
        b.set_begin(Fraction(1))
        b.set_end(Fraction(10))
        doc.set_body(b)

        div1 = Div(doc)
        div1.set_region(r1)
        b.push_child(div1)

        p1 = P(doc)
        p1.set_style(StyleProperties.BackgroundColor, NamedColors.white.value)
        p1.set_style(StyleProperties.Direction, DirectionType.rtl)
        div1.push_child(p1)

        span1 = Span(doc)
        span1.set_style(StyleProperties.BackgroundColor, NamedColors.red.value)
        span1.set_style(StyleProperties.FontStyle, FontStyleType.italic)
        span1.set_style(StyleProperties.Direction, DirectionType.ltr)
        p1.push_child(span1)

        t1 = Text(doc, "hello")
        span1.push_child(t1)

        significant_times = sorted(ISD.significant_times(doc))
        self.assertEqual(3, len(significant_times))

        isd = ISD.from_model(doc, significant_times[1])

        r1 = isd.get_region("r1")

        self.assertEqual(len(Region._applicableStyles), len(r1._styles))
        self.assertEqual(NamedColors.red.value,
                         r1.get_style(StyleProperties.BackgroundColor))
        self.assertEqual(2.0, r1.get_style(StyleProperties.LuminanceGain))

        body1 = list(r1)[0]
        div1 = list(body1)[0]
        p1 = list(div1)[0]
        span1 = list(p1)[0]

        self.assertEqual(len(P._applicableStyles), len(p1._styles))
        self.assertEqual(NamedColors.white.value,
                         p1.get_style(StyleProperties.BackgroundColor))
        self.assertEqual(DirectionType.rtl,
                         p1.get_style(StyleProperties.Direction))

        self.assertEqual(len(Span._applicableStyles), len(span1._styles))
        self.assertEqual(NamedColors.red.value,
                         span1.get_style(StyleProperties.BackgroundColor))
        self.assertEqual(FontStyleType.italic,
                         span1.get_style(StyleProperties.FontStyle))
        self.assertEqual(DirectionType.ltr,
                         span1.get_style(StyleProperties.Direction))

        default_style_value_filter.process(isd)

        self.assertEqual(len(Region._applicableStyles) - 1, len(r1._styles))
        self.assertIsNone(r1.get_style(StyleProperties.BackgroundColor))

        self.assertEqual(len(P._applicableStyles), len(p1._styles))
        self.assertEqual(NamedColors.white.value,
                         p1.get_style(StyleProperties.BackgroundColor))
        self.assertEqual(DirectionType.rtl,
                         p1.get_style(StyleProperties.Direction))

        self.assertEqual(len(Span._applicableStyles) - 1, len(span1._styles))
        self.assertIsNone(span1.get_style(StyleProperties.BackgroundColor))
        self.assertEqual(FontStyleType.italic,
                         span1.get_style(StyleProperties.FontStyle))
        self.assertEqual(DirectionType.ltr,
                         span1.get_style(StyleProperties.Direction))