repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.starts_at | def starts_at(self, time_point):
"""
Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.begin == time_point | python | def starts_at(self, time_point):
"""
Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.begin == time_point | [
"def",
"starts_at",
"(",
"self",
",",
"time_point",
")",
":",
"if",
"not",
"isinstance",
"(",
"time_point",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
"(",
"u\"time_point is not an instance of TimeValue\"",
")",
"return",
"self",
".",
"begin",
"==",
"time... | Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool | [
"Returns",
"True",
"if",
"this",
"interval",
"starts",
"at",
"the",
"given",
"time",
"point",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L371-L382 | train | 227,000 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.ends_at | def ends_at(self, time_point):
"""
Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.end == time_point | python | def ends_at(self, time_point):
"""
Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.end == time_point | [
"def",
"ends_at",
"(",
"self",
",",
"time_point",
")",
":",
"if",
"not",
"isinstance",
"(",
"time_point",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
"(",
"u\"time_point is not an instance of TimeValue\"",
")",
"return",
"self",
".",
"end",
"==",
"time_poi... | Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool | [
"Returns",
"True",
"if",
"this",
"interval",
"ends",
"at",
"the",
"given",
"time",
"point",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L384-L395 | train | 227,001 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.percent_value | def percent_value(self, percent):
"""
Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if not isinstance(percent, Decimal):
raise TypeError(u"percent is not an instance of Decimal")
percent = Decimal(max(min(percent, 100), 0) / 100)
return self.begin + self.length * percent | python | def percent_value(self, percent):
"""
Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if not isinstance(percent, Decimal):
raise TypeError(u"percent is not an instance of Decimal")
percent = Decimal(max(min(percent, 100), 0) / 100)
return self.begin + self.length * percent | [
"def",
"percent_value",
"(",
"self",
",",
"percent",
")",
":",
"if",
"not",
"isinstance",
"(",
"percent",
",",
"Decimal",
")",
":",
"raise",
"TypeError",
"(",
"u\"percent is not an instance of Decimal\"",
")",
"percent",
"=",
"Decimal",
"(",
"max",
"(",
"min",... | Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue` | [
"Returns",
"the",
"time",
"value",
"at",
"percent",
"of",
"this",
"interval",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L397-L409 | train | 227,002 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.offset | def offset(self, offset, allow_negative=False, min_begin_value=None, max_end_value=None):
"""
Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval`
"""
if not isinstance(offset, TimeValue):
raise TypeError(u"offset is not an instance of TimeValue")
self.begin += offset
self.end += offset
if not allow_negative:
self.begin = max(self.begin, TimeValue("0.000"))
self.end = max(self.end, TimeValue("0.000"))
if (min_begin_value is not None) and (max_end_value is not None):
self.begin = min(max(self.begin, min_begin_value), max_end_value)
self.end = min(self.end, max_end_value)
return self | python | def offset(self, offset, allow_negative=False, min_begin_value=None, max_end_value=None):
"""
Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval`
"""
if not isinstance(offset, TimeValue):
raise TypeError(u"offset is not an instance of TimeValue")
self.begin += offset
self.end += offset
if not allow_negative:
self.begin = max(self.begin, TimeValue("0.000"))
self.end = max(self.end, TimeValue("0.000"))
if (min_begin_value is not None) and (max_end_value is not None):
self.begin = min(max(self.begin, min_begin_value), max_end_value)
self.end = min(self.end, max_end_value)
return self | [
"def",
"offset",
"(",
"self",
",",
"offset",
",",
"allow_negative",
"=",
"False",
",",
"min_begin_value",
"=",
"None",
",",
"max_end_value",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
... | Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval` | [
"Move",
"this",
"interval",
"by",
"the",
"given",
"shift",
"offset",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L411-L441 | train | 227,003 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.intersection | def intersection(self, other):
"""
Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType``
"""
relative_position = self.relative_position_of(other)
if relative_position in [
self.RELATIVE_POSITION_PP_C,
self.RELATIVE_POSITION_PI_LC,
self.RELATIVE_POSITION_PI_LG,
self.RELATIVE_POSITION_PI_CG,
self.RELATIVE_POSITION_IP_B,
self.RELATIVE_POSITION_II_LB,
]:
return TimeInterval(begin=self.begin, end=self.begin)
if relative_position in [
self.RELATIVE_POSITION_IP_E,
self.RELATIVE_POSITION_II_EG,
]:
return TimeInterval(begin=self.end, end=self.end)
if relative_position in [
self.RELATIVE_POSITION_II_BI,
self.RELATIVE_POSITION_II_BE,
self.RELATIVE_POSITION_II_II,
self.RELATIVE_POSITION_II_IE,
]:
return TimeInterval(begin=other.begin, end=other.end)
if relative_position in [
self.RELATIVE_POSITION_IP_I,
self.RELATIVE_POSITION_II_LI,
self.RELATIVE_POSITION_II_LE,
self.RELATIVE_POSITION_II_LG,
self.RELATIVE_POSITION_II_BG,
self.RELATIVE_POSITION_II_IG,
]:
begin = max(self.begin, other.begin)
end = min(self.end, other.end)
return TimeInterval(begin=begin, end=end)
return None | python | def intersection(self, other):
"""
Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType``
"""
relative_position = self.relative_position_of(other)
if relative_position in [
self.RELATIVE_POSITION_PP_C,
self.RELATIVE_POSITION_PI_LC,
self.RELATIVE_POSITION_PI_LG,
self.RELATIVE_POSITION_PI_CG,
self.RELATIVE_POSITION_IP_B,
self.RELATIVE_POSITION_II_LB,
]:
return TimeInterval(begin=self.begin, end=self.begin)
if relative_position in [
self.RELATIVE_POSITION_IP_E,
self.RELATIVE_POSITION_II_EG,
]:
return TimeInterval(begin=self.end, end=self.end)
if relative_position in [
self.RELATIVE_POSITION_II_BI,
self.RELATIVE_POSITION_II_BE,
self.RELATIVE_POSITION_II_II,
self.RELATIVE_POSITION_II_IE,
]:
return TimeInterval(begin=other.begin, end=other.end)
if relative_position in [
self.RELATIVE_POSITION_IP_I,
self.RELATIVE_POSITION_II_LI,
self.RELATIVE_POSITION_II_LE,
self.RELATIVE_POSITION_II_LG,
self.RELATIVE_POSITION_II_BG,
self.RELATIVE_POSITION_II_IG,
]:
begin = max(self.begin, other.begin)
end = min(self.end, other.end)
return TimeInterval(begin=begin, end=end)
return None | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"relative_position",
"=",
"self",
".",
"relative_position_of",
"(",
"other",
")",
"if",
"relative_position",
"in",
"[",
"self",
".",
"RELATIVE_POSITION_PP_C",
",",
"self",
".",
"RELATIVE_POSITION_PI_LC",
... | Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType`` | [
"Return",
"the",
"intersection",
"between",
"this",
"time",
"interval",
"and",
"the",
"given",
"time",
"interval",
"or",
"None",
"if",
"the",
"two",
"intervals",
"do",
"not",
"overlap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L569-L610 | train | 227,004 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.is_non_zero_before_non_zero | def is_non_zero_before_non_zero(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
return self.is_adjacent_before(other) and (not self.has_zero_length) and (not other.has_zero_length) | python | def is_non_zero_before_non_zero(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
return self.is_adjacent_before(other) and (not self.has_zero_length) and (not other.has_zero_length) | [
"def",
"is_non_zero_before_non_zero",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"is_adjacent_before",
"(",
"other",
")",
"and",
"(",
"not",
"self",
".",
"has_zero_length",
")",
"and",
"(",
"not",
"other",
".",
"has_zero_length",
")"
] | Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool | [
"Return",
"True",
"if",
"this",
"time",
"interval",
"ends",
"when",
"the",
"given",
"other",
"time",
"interval",
"begins",
"and",
"both",
"have",
"non",
"zero",
"length",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L623-L634 | train | 227,005 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.is_adjacent_before | def is_adjacent_before(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
if not isinstance(other, TimeInterval):
raise TypeError(u"other is not an instance of TimeInterval")
return (self.end == other.begin) | python | def is_adjacent_before(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
if not isinstance(other, TimeInterval):
raise TypeError(u"other is not an instance of TimeInterval")
return (self.end == other.begin) | [
"def",
"is_adjacent_before",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimeInterval",
")",
":",
"raise",
"TypeError",
"(",
"u\"other is not an instance of TimeInterval\"",
")",
"return",
"(",
"self",
".",
"end",
"==",
... | Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool | [
"Return",
"True",
"if",
"this",
"time",
"interval",
"ends",
"when",
"the",
"given",
"other",
"time",
"interval",
"begins",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L649-L661 | train | 227,006 |
readbeyond/aeneas | aeneas/tools/convert_syncmap.py | ConvertSyncMapCLI.check_format | def check_format(self, sm_format):
"""
Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool
"""
if sm_format not in SyncMapFormat.ALLOWED_VALUES:
self.print_error(u"Sync map format '%s' is not allowed" % (sm_format))
self.print_info(u"Allowed formats:")
self.print_generic(u" ".join(SyncMapFormat.ALLOWED_VALUES))
return False
return True | python | def check_format(self, sm_format):
"""
Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool
"""
if sm_format not in SyncMapFormat.ALLOWED_VALUES:
self.print_error(u"Sync map format '%s' is not allowed" % (sm_format))
self.print_info(u"Allowed formats:")
self.print_generic(u" ".join(SyncMapFormat.ALLOWED_VALUES))
return False
return True | [
"def",
"check_format",
"(",
"self",
",",
"sm_format",
")",
":",
"if",
"sm_format",
"not",
"in",
"SyncMapFormat",
".",
"ALLOWED_VALUES",
":",
"self",
".",
"print_error",
"(",
"u\"Sync map format '%s' is not allowed\"",
"%",
"(",
"sm_format",
")",
")",
"self",
"."... | Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool | [
"Return",
"True",
"if",
"the",
"given",
"sync",
"map",
"format",
"is",
"allowed",
"and",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/convert_syncmap.py#L163-L177 | train | 227,007 |
readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase._add_fragment | def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
"""
Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string
"""
syncmap.add_fragment(
SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
lines=lines,
language=language
),
begin=begin,
end=end
)
) | python | def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
"""
Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string
"""
syncmap.add_fragment(
SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
lines=lines,
language=language
),
begin=begin,
end=end
)
) | [
"def",
"_add_fragment",
"(",
"cls",
",",
"syncmap",
",",
"identifier",
",",
"lines",
",",
"begin",
",",
"end",
",",
"language",
"=",
"None",
")",
":",
"syncmap",
".",
"add_fragment",
"(",
"SyncMapFragment",
"(",
"text_fragment",
"=",
"TextFragment",
"(",
"... | Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string | [
"Add",
"a",
"new",
"fragment",
"to",
"syncmap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L53-L80 | train | 227,008 |
readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase.parse | def parse(self, input_text, syncmap):
"""
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | python | def parse(self, input_text, syncmap):
"""
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | [
"def",
"parse",
"(",
"self",
",",
"input_text",
",",
"syncmap",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"%s is abstract and cannot be called directly\"",
"%",
"(",
"self",
".",
"TAG",
")",
",",
"None",
",",
"True",
",",
"NotImplementedError",
")"
] | Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap` | [
"Parse",
"the",
"given",
"input_text",
"and",
"append",
"the",
"extracted",
"fragments",
"to",
"syncmap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L82-L92 | train | 227,009 |
readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase.format | def format(self, syncmap):
"""
Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | python | def format(self, syncmap):
"""
Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | [
"def",
"format",
"(",
"self",
",",
"syncmap",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"%s is abstract and cannot be called directly\"",
"%",
"(",
"self",
".",
"TAG",
")",
",",
"None",
",",
"True",
",",
"NotImplementedError",
")"
] | Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string | [
"Format",
"the",
"given",
"syncmap",
"as",
"a",
"Unicode",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L94-L102 | train | 227,010 |
readbeyond/aeneas | aeneas/tools/execute_task.py | ExecuteTaskCLI.print_examples | def print_examples(self, full=False):
"""
Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones
"""
msg = []
i = 1
for key in sorted(self.DEMOS.keys()):
example = self.DEMOS[key]
if full or example["show"]:
msg.append(u"Example %d (%s)" % (i, example[u"description"]))
msg.append(u" $ %s %s" % (self.invoke, key))
msg.append(u"")
i += 1
self.print_generic(u"\n" + u"\n".join(msg) + u"\n")
return self.HELP_EXIT_CODE | python | def print_examples(self, full=False):
"""
Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones
"""
msg = []
i = 1
for key in sorted(self.DEMOS.keys()):
example = self.DEMOS[key]
if full or example["show"]:
msg.append(u"Example %d (%s)" % (i, example[u"description"]))
msg.append(u" $ %s %s" % (self.invoke, key))
msg.append(u"")
i += 1
self.print_generic(u"\n" + u"\n".join(msg) + u"\n")
return self.HELP_EXIT_CODE | [
"def",
"print_examples",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"msg",
"=",
"[",
"]",
"i",
"=",
"1",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"DEMOS",
".",
"keys",
"(",
")",
")",
":",
"example",
"=",
"self",
".",
"DEMOS",
"[",... | Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones | [
"Print",
"the",
"examples",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L682-L699 | train | 227,011 |
readbeyond/aeneas | aeneas/tools/execute_task.py | ExecuteTaskCLI.print_values | def print_values(self, parameter):
"""
Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string
"""
if parameter in self.VALUES:
self.print_info(u"Available values for parameter '%s':" % parameter)
self.print_generic(u"\n".join(self.VALUES[parameter]))
return self.HELP_EXIT_CODE
if parameter not in [u"?", u""]:
self.print_error(u"Invalid parameter name '%s'" % parameter)
self.print_info(u"Parameters for which values can be listed:")
self.print_generic(u"\n".join(sorted(self.VALUES.keys())))
return self.HELP_EXIT_CODE | python | def print_values(self, parameter):
"""
Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string
"""
if parameter in self.VALUES:
self.print_info(u"Available values for parameter '%s':" % parameter)
self.print_generic(u"\n".join(self.VALUES[parameter]))
return self.HELP_EXIT_CODE
if parameter not in [u"?", u""]:
self.print_error(u"Invalid parameter name '%s'" % parameter)
self.print_info(u"Parameters for which values can be listed:")
self.print_generic(u"\n".join(sorted(self.VALUES.keys())))
return self.HELP_EXIT_CODE | [
"def",
"print_values",
"(",
"self",
",",
"parameter",
")",
":",
"if",
"parameter",
"in",
"self",
".",
"VALUES",
":",
"self",
".",
"print_info",
"(",
"u\"Available values for parameter '%s':\"",
"%",
"parameter",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\""... | Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string | [
"Print",
"the",
"list",
"of",
"values",
"for",
"the",
"given",
"parameter",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L711-L729 | train | 227,012 |
readbeyond/aeneas | setup.py | prepare_cew_for_windows | def prepare_cew_for_windows():
"""
Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool
"""
try:
# copy espeak_sapi.dll to C:\Windows\System32\espeak.dll
espeak_dll_win_path = "C:\\Windows\\System32\\espeak.dll"
espeak_dll_dst_path = "aeneas\\cew\\espeak.dll"
espeak_dll_src_paths = [
"C:\\aeneas\\eSpeak\\espeak_sapi.dll",
"C:\\sync\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files (x86)\\eSpeak\\espeak_sapi.dll",
]
if os.path.exists(espeak_dll_dst_path):
print("[INFO] Found eSpeak DLL in %s" % espeak_dll_dst_path)
else:
found = False
copied = False
for src_path in espeak_dll_src_paths:
if os.path.exists(src_path):
found = True
print("[INFO] Copying eSpeak DLL from %s into %s" % (src_path, espeak_dll_dst_path))
try:
shutil.copyfile(src_path, espeak_dll_dst_path)
copied = True
print("[INFO] Copied eSpeak DLL")
except:
pass
break
if not found:
print("[WARN] Unable to find the eSpeak DLL, probably because you installed eSpeak in a non-standard location.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
elif not copied:
print("[WARN] Unable to copy the eSpeak DLL, probably because you are not running with admin privileges.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
# NOTE: espeak.lib is needed only while compiling the C extension, not when using it
# so, we copy it in the current working directory from the included thirdparty\ directory
# NOTE: PREV: copy thirdparty\espeak.lib to $PYTHON\libs\espeak.lib
# NOTE: PREV: espeak_lib_dst_path = os.path.join(sys.prefix, "libs", "espeak.lib")
espeak_lib_src_path = os.path.join(os.path.dirname(__file__), "thirdparty", "espeak.lib")
espeak_lib_dst_path = os.path.join(os.path.dirname(__file__), "espeak.lib")
if os.path.exists(espeak_lib_dst_path):
print("[INFO] Found eSpeak LIB in %s" % espeak_lib_dst_path)
else:
try:
print("[INFO] Copying eSpeak LIB into %s" % espeak_lib_dst_path)
shutil.copyfile(espeak_lib_src_path, espeak_lib_dst_path)
print("[INFO] Copied eSpeak LIB")
except:
print("[WARN] Unable to copy the eSpeak LIB, probably because you are not running with admin privileges.")
print("[WARN] If you want to compile the C extension cew,")
print("[WARN] please copy espeak.lib from the thirdparty directory into %s" % espeak_lib_dst_path)
print("[WARN] and run the aeneas setup again.")
return False
# if here, we have completed the setup, return True
return True
except Exception as e:
print("[WARN] Unexpected exception while preparing cew: %s" % e)
return False | python | def prepare_cew_for_windows():
"""
Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool
"""
try:
# copy espeak_sapi.dll to C:\Windows\System32\espeak.dll
espeak_dll_win_path = "C:\\Windows\\System32\\espeak.dll"
espeak_dll_dst_path = "aeneas\\cew\\espeak.dll"
espeak_dll_src_paths = [
"C:\\aeneas\\eSpeak\\espeak_sapi.dll",
"C:\\sync\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files (x86)\\eSpeak\\espeak_sapi.dll",
]
if os.path.exists(espeak_dll_dst_path):
print("[INFO] Found eSpeak DLL in %s" % espeak_dll_dst_path)
else:
found = False
copied = False
for src_path in espeak_dll_src_paths:
if os.path.exists(src_path):
found = True
print("[INFO] Copying eSpeak DLL from %s into %s" % (src_path, espeak_dll_dst_path))
try:
shutil.copyfile(src_path, espeak_dll_dst_path)
copied = True
print("[INFO] Copied eSpeak DLL")
except:
pass
break
if not found:
print("[WARN] Unable to find the eSpeak DLL, probably because you installed eSpeak in a non-standard location.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
elif not copied:
print("[WARN] Unable to copy the eSpeak DLL, probably because you are not running with admin privileges.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
# NOTE: espeak.lib is needed only while compiling the C extension, not when using it
# so, we copy it in the current working directory from the included thirdparty\ directory
# NOTE: PREV: copy thirdparty\espeak.lib to $PYTHON\libs\espeak.lib
# NOTE: PREV: espeak_lib_dst_path = os.path.join(sys.prefix, "libs", "espeak.lib")
espeak_lib_src_path = os.path.join(os.path.dirname(__file__), "thirdparty", "espeak.lib")
espeak_lib_dst_path = os.path.join(os.path.dirname(__file__), "espeak.lib")
if os.path.exists(espeak_lib_dst_path):
print("[INFO] Found eSpeak LIB in %s" % espeak_lib_dst_path)
else:
try:
print("[INFO] Copying eSpeak LIB into %s" % espeak_lib_dst_path)
shutil.copyfile(espeak_lib_src_path, espeak_lib_dst_path)
print("[INFO] Copied eSpeak LIB")
except:
print("[WARN] Unable to copy the eSpeak LIB, probably because you are not running with admin privileges.")
print("[WARN] If you want to compile the C extension cew,")
print("[WARN] please copy espeak.lib from the thirdparty directory into %s" % espeak_lib_dst_path)
print("[WARN] and run the aeneas setup again.")
return False
# if here, we have completed the setup, return True
return True
except Exception as e:
print("[WARN] Unexpected exception while preparing cew: %s" % e)
return False | [
"def",
"prepare_cew_for_windows",
"(",
")",
":",
"try",
":",
"# copy espeak_sapi.dll to C:\\Windows\\System32\\espeak.dll",
"espeak_dll_win_path",
"=",
"\"C:\\\\Windows\\\\System32\\\\espeak.dll\"",
"espeak_dll_dst_path",
"=",
"\"aeneas\\\\cew\\\\espeak.dll\"",
"espeak_dll_src_paths",
... | Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool | [
"Copy",
"files",
"needed",
"to",
"compile",
"the",
"cew",
"Python",
"C",
"extension",
"on",
"Windows",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/setup.py#L69-L145 | train | 227,013 |
readbeyond/aeneas | aeneas/validator.py | Validator.check_file_encoding | def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_file_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_file_encoding"):
return self.result
if not gf.file_can_be_read(input_file_path):
self._failed(u"File '%s' cannot be read." % (input_file_path))
return self.result
with io.open(input_file_path, "rb") as file_object:
bstring = file_object.read()
self._check_utf8_encoding(bstring)
return self.result | python | def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_file_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_file_encoding"):
return self.result
if not gf.file_can_be_read(input_file_path):
self._failed(u"File '%s' cannot be read." % (input_file_path))
return self.result
with io.open(input_file_path, "rb") as file_object:
bstring = file_object.read()
self._check_utf8_encoding(bstring)
return self.result | [
"def",
"check_file_encoding",
"(",
"self",
",",
"input_file_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking encoding of file '%s'\"",
",",
"input_file_path",
"]",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_ar... | Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"file",
"is",
"UTF",
"-",
"8",
"encoded",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L259-L276 | train | 227,014 |
readbeyond/aeneas | aeneas/validator.py | Validator.check_config_xml | def check_config_xml(self, contents):
"""
Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log(u"Checking contents XML config file")
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_config_xml"):
return self.result
contents = gf.safe_bytes(contents)
self.log(u"Checking that contents is well formed")
self.check_raw_string(contents, is_bstring=True)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for job")
job_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=True)
self._check_required_parameters(self.XML_JOB_REQUIRED_PARAMETERS, job_parameters)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for task")
tasks_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=False)
for parameters in tasks_parameters:
self.log([u"Checking required parameters for task: '%s'", parameters])
self._check_required_parameters(self.XML_TASK_REQUIRED_PARAMETERS, parameters)
if not self.result.passed:
return self.result
return self.result | python | def check_config_xml(self, contents):
"""
Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log(u"Checking contents XML config file")
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_config_xml"):
return self.result
contents = gf.safe_bytes(contents)
self.log(u"Checking that contents is well formed")
self.check_raw_string(contents, is_bstring=True)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for job")
job_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=True)
self._check_required_parameters(self.XML_JOB_REQUIRED_PARAMETERS, job_parameters)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for task")
tasks_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=False)
for parameters in tasks_parameters:
self.log([u"Checking required parameters for task: '%s'", parameters])
self._check_required_parameters(self.XML_TASK_REQUIRED_PARAMETERS, parameters)
if not self.result.passed:
return self.result
return self.result | [
"def",
"check_config_xml",
"(",
"self",
",",
"contents",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking contents XML config file\"",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_safety_checks_disabled",
"(",
"u\"check_con... | Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"XML",
"config",
"file",
"contents",
"is",
"well",
"-",
"formed",
"and",
"it",
"has",
"all",
"the",
"required",
"parameters",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L380-L410 | train | 227,015 |
readbeyond/aeneas | aeneas/validator.py | Validator.check_container | def check_container(self, container_path, container_format=None, config_string=None):
"""
Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking container '%s'", container_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_container"):
return self.result
if not (gf.file_exists(container_path) or gf.directory_exists(container_path)):
self._failed(u"Container '%s' not found." % container_path)
return self.result
container = Container(container_path, container_format)
try:
self.log(u"Checking container has config file")
if config_string is not None:
self.log(u"Container with config string from wizard")
self.check_config_txt(config_string, is_config_string=True)
elif container.has_config_xml:
self.log(u"Container has XML config file")
contents = container.read_entry(container.entry_config_xml)
if contents is None:
self._failed(u"Unable to read the contents of XML config file.")
return self.result
self.check_config_xml(contents)
elif container.has_config_txt:
self.log(u"Container has TXT config file")
contents = container.read_entry(container.entry_config_txt)
if contents is None:
self._failed(u"Unable to read the contents of TXT config file.")
return self.result
self.check_config_txt(contents, is_config_string=False)
else:
self._failed(u"Container does not have a TXT or XML configuration file.")
self.log(u"Checking we have a valid job in the container")
if not self.result.passed:
return self.result
self.log(u"Analyze the contents of the container")
analyzer = AnalyzeContainer(container)
if config_string is not None:
job = analyzer.analyze(config_string=config_string)
else:
job = analyzer.analyze()
self._check_analyzed_job(job, container)
except OSError:
self._failed(u"Unable to read the contents of the container.")
return self.result | python | def check_container(self, container_path, container_format=None, config_string=None):
"""
Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking container '%s'", container_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_container"):
return self.result
if not (gf.file_exists(container_path) or gf.directory_exists(container_path)):
self._failed(u"Container '%s' not found." % container_path)
return self.result
container = Container(container_path, container_format)
try:
self.log(u"Checking container has config file")
if config_string is not None:
self.log(u"Container with config string from wizard")
self.check_config_txt(config_string, is_config_string=True)
elif container.has_config_xml:
self.log(u"Container has XML config file")
contents = container.read_entry(container.entry_config_xml)
if contents is None:
self._failed(u"Unable to read the contents of XML config file.")
return self.result
self.check_config_xml(contents)
elif container.has_config_txt:
self.log(u"Container has TXT config file")
contents = container.read_entry(container.entry_config_txt)
if contents is None:
self._failed(u"Unable to read the contents of TXT config file.")
return self.result
self.check_config_txt(contents, is_config_string=False)
else:
self._failed(u"Container does not have a TXT or XML configuration file.")
self.log(u"Checking we have a valid job in the container")
if not self.result.passed:
return self.result
self.log(u"Analyze the contents of the container")
analyzer = AnalyzeContainer(container)
if config_string is not None:
job = analyzer.analyze(config_string=config_string)
else:
job = analyzer.analyze()
self._check_analyzed_job(job, container)
except OSError:
self._failed(u"Unable to read the contents of the container.")
return self.result | [
"def",
"check_container",
"(",
"self",
",",
"container_path",
",",
"container_format",
"=",
"None",
",",
"config_string",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking container '%s'\"",
",",
"container_path",
"]",
")",
"self",
".",
"result... | Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"container",
"is",
"well",
"-",
"formed",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L412-L468 | train | 227,016 |
readbeyond/aeneas | aeneas/validator.py | Validator._are_safety_checks_disabled | def _are_safety_checks_disabled(self, caller=u"unknown_function"):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False
self.log_warn([u"Safety checks disabled => %s passed", caller])
return True | python | def _are_safety_checks_disabled(self, caller=u"unknown_function"):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False
self.log_warn([u"Safety checks disabled => %s passed", caller])
return True | [
"def",
"_are_safety_checks_disabled",
"(",
"self",
",",
"caller",
"=",
"u\"unknown_function\"",
")",
":",
"if",
"self",
".",
"rconf",
".",
"safety_checks",
":",
"return",
"False",
"self",
".",
"log_warn",
"(",
"[",
"u\"Safety checks disabled => %s passed\"",
",",
... | Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool | [
"Return",
"True",
"if",
"safety",
"checks",
"are",
"disabled",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L470-L480 | train | 227,017 |
readbeyond/aeneas | aeneas/validator.py | Validator._failed | def _failed(self, msg):
"""
Log a validation failure.
:param string msg: the error message
"""
self.log(msg)
self.result.passed = False
self.result.add_error(msg)
self.log(u"Failed") | python | def _failed(self, msg):
"""
Log a validation failure.
:param string msg: the error message
"""
self.log(msg)
self.result.passed = False
self.result.add_error(msg)
self.log(u"Failed") | [
"def",
"_failed",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
"(",
"msg",
")",
"self",
".",
"result",
".",
"passed",
"=",
"False",
"self",
".",
"result",
".",
"add_error",
"(",
"msg",
")",
"self",
".",
"log",
"(",
"u\"Failed\"",
")"
] | Log a validation failure.
:param string msg: the error message | [
"Log",
"a",
"validation",
"failure",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L482-L491 | train | 227,018 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_utf8_encoding | def _check_utf8_encoding(self, bstring):
"""
Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked
"""
if not gf.is_bytes(bstring):
self._failed(u"The given string is not a sequence of bytes")
return
if not gf.is_utf8_encoded(bstring):
self._failed(u"The given string is not encoded in UTF-8.") | python | def _check_utf8_encoding(self, bstring):
"""
Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked
"""
if not gf.is_bytes(bstring):
self._failed(u"The given string is not a sequence of bytes")
return
if not gf.is_utf8_encoded(bstring):
self._failed(u"The given string is not encoded in UTF-8.") | [
"def",
"_check_utf8_encoding",
"(",
"self",
",",
"bstring",
")",
":",
"if",
"not",
"gf",
".",
"is_bytes",
"(",
"bstring",
")",
":",
"self",
".",
"_failed",
"(",
"u\"The given string is not a sequence of bytes\"",
")",
"return",
"if",
"not",
"gf",
".",
"is_utf8... | Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked | [
"Check",
"whether",
"the",
"given",
"sequence",
"of",
"bytes",
"is",
"properly",
"encoded",
"in",
"UTF",
"-",
"8",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L493-L504 | train | 227,019 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_reserved_characters | def _check_reserved_characters(self, ustring):
"""
Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked
"""
forbidden = [c for c in gc.CONFIG_RESERVED_CHARACTERS if c in ustring]
if len(forbidden) > 0:
self._failed(u"The given string contains the reserved characters '%s'." % u" ".join(forbidden)) | python | def _check_reserved_characters(self, ustring):
"""
Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked
"""
forbidden = [c for c in gc.CONFIG_RESERVED_CHARACTERS if c in ustring]
if len(forbidden) > 0:
self._failed(u"The given string contains the reserved characters '%s'." % u" ".join(forbidden)) | [
"def",
"_check_reserved_characters",
"(",
"self",
",",
"ustring",
")",
":",
"forbidden",
"=",
"[",
"c",
"for",
"c",
"in",
"gc",
".",
"CONFIG_RESERVED_CHARACTERS",
"if",
"c",
"in",
"ustring",
"]",
"if",
"len",
"(",
"forbidden",
")",
">",
"0",
":",
"self",... | Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked | [
"Check",
"whether",
"the",
"given",
"Unicode",
"string",
"contains",
"reserved",
"characters",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L515-L523 | train | 227,020 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_allowed_values | def _check_allowed_values(self, parameters):
"""
Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, allowed_values in self.ALLOWED_VALUES:
self.log([u"Checking allowed values for parameter '%s'", key])
if key in parameters:
value = parameters[key]
if value not in allowed_values:
self._failed(u"Parameter '%s' has value '%s' which is not allowed." % (key, value))
return
self.log(u"Passed") | python | def _check_allowed_values(self, parameters):
"""
Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, allowed_values in self.ALLOWED_VALUES:
self.log([u"Checking allowed values for parameter '%s'", key])
if key in parameters:
value = parameters[key]
if value not in allowed_values:
self._failed(u"Parameter '%s' has value '%s' which is not allowed." % (key, value))
return
self.log(u"Passed") | [
"def",
"_check_allowed_values",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"key",
",",
"allowed_values",
"in",
"self",
".",
"ALLOWED_VALUES",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking allowed values for parameter '%s'\"",
",",
"key",
"]",
")",
"if",
... | Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters | [
"Check",
"whether",
"the",
"given",
"parameter",
"value",
"is",
"allowed",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L525-L539 | train | 227,021 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_implied_parameters | def _check_implied_parameters(self, parameters):
"""
Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, values, implied_keys in self.IMPLIED_PARAMETERS:
self.log([u"Checking implied parameters by '%s'='%s'", key, values])
if (key in parameters) and (parameters[key] in values):
found = False
for implied_key in implied_keys:
if implied_key in parameters:
found = True
if not found:
if len(implied_keys) == 1:
msg = u"Parameter '%s' is required when '%s'='%s'." % (implied_keys[0], key, parameters[key])
else:
msg = u"At least one of [%s] is required when '%s'='%s'." % (",".join(implied_keys), key, parameters[key])
self._failed(msg)
return
self.log(u"Passed") | python | def _check_implied_parameters(self, parameters):
"""
Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, values, implied_keys in self.IMPLIED_PARAMETERS:
self.log([u"Checking implied parameters by '%s'='%s'", key, values])
if (key in parameters) and (parameters[key] in values):
found = False
for implied_key in implied_keys:
if implied_key in parameters:
found = True
if not found:
if len(implied_keys) == 1:
msg = u"Parameter '%s' is required when '%s'='%s'." % (implied_keys[0], key, parameters[key])
else:
msg = u"At least one of [%s] is required when '%s'='%s'." % (",".join(implied_keys), key, parameters[key])
self._failed(msg)
return
self.log(u"Passed") | [
"def",
"_check_implied_parameters",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"key",
",",
"values",
",",
"implied_keys",
"in",
"self",
".",
"IMPLIED_PARAMETERS",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking implied parameters by '%s'='%s'\"",
",",
"key",... | Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters | [
"Check",
"whether",
"at",
"least",
"one",
"of",
"the",
"keys",
"in",
"implied_keys",
"is",
"in",
"parameters",
"when",
"a",
"given",
"key",
"=",
"value",
"is",
"present",
"in",
"parameters",
"for",
"some",
"value",
"in",
"values",
".",
"Log",
"messages",
... | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L541-L565 | train | 227,022 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_required_parameters | def _check_required_parameters(
self,
required_parameters,
parameters
):
"""
Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user
"""
self.log([u"Checking required parameters '%s'", required_parameters])
self.log(u"Checking input parameters are not empty")
if (parameters is None) or (len(parameters) == 0):
self._failed(u"No parameters supplied.")
return
self.log(u"Checking no required parameter is missing")
for req_param in required_parameters:
if req_param not in parameters:
self._failed(u"Required parameter '%s' not set." % req_param)
return
self.log(u"Checking all parameter values are allowed")
self._check_allowed_values(parameters)
self.log(u"Checking all implied parameters are present")
self._check_implied_parameters(parameters)
return self.result | python | def _check_required_parameters(
self,
required_parameters,
parameters
):
"""
Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user
"""
self.log([u"Checking required parameters '%s'", required_parameters])
self.log(u"Checking input parameters are not empty")
if (parameters is None) or (len(parameters) == 0):
self._failed(u"No parameters supplied.")
return
self.log(u"Checking no required parameter is missing")
for req_param in required_parameters:
if req_param not in parameters:
self._failed(u"Required parameter '%s' not set." % req_param)
return
self.log(u"Checking all parameter values are allowed")
self._check_allowed_values(parameters)
self.log(u"Checking all implied parameters are present")
self._check_implied_parameters(parameters)
return self.result | [
"def",
"_check_required_parameters",
"(",
"self",
",",
"required_parameters",
",",
"parameters",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking required parameters '%s'\"",
",",
"required_parameters",
"]",
")",
"self",
".",
"log",
"(",
"u\"Checking input paramet... | Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user | [
"Check",
"whether",
"the",
"given",
"parameter",
"dictionary",
"contains",
"all",
"the",
"required",
"paramenters",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L567-L594 | train | 227,023 |
readbeyond/aeneas | aeneas/validator.py | Validator._check_analyzed_job | def _check_analyzed_job(self, job, container):
"""
Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container`
"""
self.log(u"Checking the Job object generated from container")
self.log(u"Checking that the Job is not None")
if job is None:
self._failed(u"Unable to create a Job from the container.")
return
self.log(u"Checking that the Job has at least one Task")
if len(job) == 0:
self._failed(u"Unable to create at least one Task from the container.")
return
if self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] > 0:
self.log(u"Checking that the Job does not have too many Tasks")
if len(job) > self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]:
self._failed(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (
len(job),
self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
))
return
self.log(u"Checking that each Task text file is well formed")
for task in job.tasks:
self.log([u"Checking Task text file '%s'", task.text_file_path])
text_file_bstring = container.read_entry(task.text_file_path)
if (text_file_bstring is None) or (len(text_file_bstring) == 0):
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self._check_utf8_encoding(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is not encoded in UTF-8" % task.text_file_path)
return
self._check_not_empty(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self.log([u"Checking Task text file '%s': passed", task.text_file_path])
self.log(u"Checking each Task text file is well formed: passed") | python | def _check_analyzed_job(self, job, container):
"""
Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container`
"""
self.log(u"Checking the Job object generated from container")
self.log(u"Checking that the Job is not None")
if job is None:
self._failed(u"Unable to create a Job from the container.")
return
self.log(u"Checking that the Job has at least one Task")
if len(job) == 0:
self._failed(u"Unable to create at least one Task from the container.")
return
if self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] > 0:
self.log(u"Checking that the Job does not have too many Tasks")
if len(job) > self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]:
self._failed(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (
len(job),
self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
))
return
self.log(u"Checking that each Task text file is well formed")
for task in job.tasks:
self.log([u"Checking Task text file '%s'", task.text_file_path])
text_file_bstring = container.read_entry(task.text_file_path)
if (text_file_bstring is None) or (len(text_file_bstring) == 0):
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self._check_utf8_encoding(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is not encoded in UTF-8" % task.text_file_path)
return
self._check_not_empty(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self.log([u"Checking Task text file '%s': passed", task.text_file_path])
self.log(u"Checking each Task text file is well formed: passed") | [
"def",
"_check_analyzed_job",
"(",
"self",
",",
"job",
",",
"container",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking the Job object generated from container\"",
")",
"self",
".",
"log",
"(",
"u\"Checking that the Job is not None\"",
")",
"if",
"job",
"is",
"None... | Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container` | [
"Check",
"that",
"the",
"job",
"object",
"generated",
"from",
"the",
"given",
"container",
"is",
"well",
"formed",
"that",
"it",
"has",
"at",
"least",
"one",
"task",
"and",
"that",
"the",
"text",
"file",
"of",
"each",
"task",
"has",
"the",
"correct",
"en... | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L596-L645 | train | 227,024 |
readbeyond/aeneas | aeneas/validator.py | ValidatorResult.pretty_print | def pretty_print(self, warnings=False):
"""
Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string
"""
msg = []
if (warnings) and (len(self.warnings) > 0):
msg.append(u"Warnings:")
for warning in self.warnings:
msg.append(u" %s" % warning)
if len(self.errors) > 0:
msg.append(u"Errors:")
for error in self.errors:
msg.append(u" %s" % error)
return u"\n".join(msg) | python | def pretty_print(self, warnings=False):
"""
Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string
"""
msg = []
if (warnings) and (len(self.warnings) > 0):
msg.append(u"Warnings:")
for warning in self.warnings:
msg.append(u" %s" % warning)
if len(self.errors) > 0:
msg.append(u"Errors:")
for error in self.errors:
msg.append(u" %s" % error)
return u"\n".join(msg) | [
"def",
"pretty_print",
"(",
"self",
",",
"warnings",
"=",
"False",
")",
":",
"msg",
"=",
"[",
"]",
"if",
"(",
"warnings",
")",
"and",
"(",
"len",
"(",
"self",
".",
"warnings",
")",
">",
"0",
")",
":",
"msg",
".",
"append",
"(",
"u\"Warnings:\"",
... | Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string | [
"Pretty",
"print",
"warnings",
"and",
"errors",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L670-L686 | train | 227,025 |
readbeyond/aeneas | aeneas/ffmpegwrapper.py | FFMPEGWrapper.convert | def convert(
self,
input_file_path,
output_file_path,
head_length=None,
process_length=None
):
"""
Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written
"""
# test if we can read the input file
if not gf.file_can_be_read(input_file_path):
self.log_exc(u"Input file '%s' cannot be read" % (input_file_path), None, True, OSError)
# test if we can write the output file
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Output file '%s' cannot be written" % (output_file_path), None, True, OSError)
# call ffmpeg
arguments = [self.rconf[RuntimeConfiguration.FFMPEG_PATH]]
arguments.extend(["-i", input_file_path])
if head_length is not None:
arguments.extend(["-ss", head_length])
if process_length is not None:
arguments.extend(["-t", process_length])
if self.rconf.sample_rate in self.FFMPEG_PARAMETERS_MAP:
arguments.extend(self.FFMPEG_PARAMETERS_MAP[self.rconf.sample_rate])
else:
arguments.extend(self.FFMPEG_PARAMETERS_DEFAULT)
arguments.append(output_file_path)
self.log([u"Calling with arguments '%s'", arguments])
try:
proc = subprocess.Popen(
arguments,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
proc.communicate()
proc.stdout.close()
proc.stdin.close()
proc.stderr.close()
except OSError as exc:
self.log_exc(u"Unable to call the '%s' ffmpeg executable" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]), exc, True, FFMPEGPathError)
self.log(u"Call completed")
# check if the output file exists
if not gf.file_exists(output_file_path):
self.log_exc(u"Output file '%s' was not written" % (output_file_path), None, True, OSError)
# returning the output file path
self.log([u"Returning output file path '%s'", output_file_path])
return output_file_path | python | def convert(
self,
input_file_path,
output_file_path,
head_length=None,
process_length=None
):
"""
Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written
"""
# test if we can read the input file
if not gf.file_can_be_read(input_file_path):
self.log_exc(u"Input file '%s' cannot be read" % (input_file_path), None, True, OSError)
# test if we can write the output file
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Output file '%s' cannot be written" % (output_file_path), None, True, OSError)
# call ffmpeg
arguments = [self.rconf[RuntimeConfiguration.FFMPEG_PATH]]
arguments.extend(["-i", input_file_path])
if head_length is not None:
arguments.extend(["-ss", head_length])
if process_length is not None:
arguments.extend(["-t", process_length])
if self.rconf.sample_rate in self.FFMPEG_PARAMETERS_MAP:
arguments.extend(self.FFMPEG_PARAMETERS_MAP[self.rconf.sample_rate])
else:
arguments.extend(self.FFMPEG_PARAMETERS_DEFAULT)
arguments.append(output_file_path)
self.log([u"Calling with arguments '%s'", arguments])
try:
proc = subprocess.Popen(
arguments,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
proc.communicate()
proc.stdout.close()
proc.stdin.close()
proc.stderr.close()
except OSError as exc:
self.log_exc(u"Unable to call the '%s' ffmpeg executable" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]), exc, True, FFMPEGPathError)
self.log(u"Call completed")
# check if the output file exists
if not gf.file_exists(output_file_path):
self.log_exc(u"Output file '%s' was not written" % (output_file_path), None, True, OSError)
# returning the output file path
self.log([u"Returning output file path '%s'", output_file_path])
return output_file_path | [
"def",
"convert",
"(",
"self",
",",
"input_file_path",
",",
"output_file_path",
",",
"head_length",
"=",
"None",
",",
"process_length",
"=",
"None",
")",
":",
"# test if we can read the input file",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"input_file_path",... | Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written | [
"Convert",
"the",
"audio",
"file",
"at",
"input_file_path",
"into",
"output_file_path",
"using",
"the",
"parameters",
"set",
"in",
"the",
"constructor",
"or",
"through",
"the",
"parameters",
"property",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ffmpegwrapper.py#L163-L238 | train | 227,026 |
readbeyond/aeneas | aeneas/syncmap/fragment.py | SyncMapFragment.rate_lack | def rate_lack(self, max_rate):
"""
The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return self.chars / max_rate - self.length
return TimeValue("0.000") | python | def rate_lack(self, max_rate):
"""
The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return self.chars / max_rate - self.length
return TimeValue("0.000") | [
"def",
"rate_lack",
"(",
"self",
",",
"max_rate",
")",
":",
"if",
"self",
".",
"fragment_type",
"==",
"self",
".",
"REGULAR",
":",
"return",
"self",
".",
"chars",
"/",
"max_rate",
"-",
"self",
".",
"length",
"return",
"TimeValue",
"(",
"\"0.000\"",
")"
] | The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0 | [
"The",
"time",
"interval",
"that",
"this",
"fragment",
"lacks",
"to",
"respect",
"the",
"given",
"max",
"rate",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragment.py#L341-L361 | train | 227,027 |
readbeyond/aeneas | aeneas/syncmap/fragment.py | SyncMapFragment.rate_slack | def rate_slack(self, max_rate):
"""
The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return -self.rate_lack(max_rate)
elif self.fragment_type == self.NONSPEECH:
return self.length
else:
return TimeValue("0.000") | python | def rate_slack(self, max_rate):
"""
The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return -self.rate_lack(max_rate)
elif self.fragment_type == self.NONSPEECH:
return self.length
else:
return TimeValue("0.000") | [
"def",
"rate_slack",
"(",
"self",
",",
"max_rate",
")",
":",
"if",
"self",
".",
"fragment_type",
"==",
"self",
".",
"REGULAR",
":",
"return",
"-",
"self",
".",
"rate_lack",
"(",
"max_rate",
")",
"elif",
"self",
".",
"fragment_type",
"==",
"self",
".",
... | The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0 | [
"The",
"maximum",
"time",
"interval",
"that",
"can",
"be",
"stolen",
"to",
"this",
"fragment",
"while",
"keeping",
"it",
"respecting",
"the",
"given",
"max",
"rate",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragment.py#L363-L386 | train | 227,028 |
readbeyond/aeneas | aeneas/tools/run_vad.py | RunVADCLI.write_to_file | def write_to_file(self, output_file_path, intervals, template):
"""
Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples
"""
msg = [template % (interval) for interval in intervals]
if output_file_path is None:
self.print_info(u"Intervals detected:")
for line in msg:
self.print_generic(line)
else:
with io.open(output_file_path, "w", encoding="utf-8") as output_file:
output_file.write(u"\n".join(msg))
self.print_success(u"Created file '%s'" % output_file_path) | python | def write_to_file(self, output_file_path, intervals, template):
"""
Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples
"""
msg = [template % (interval) for interval in intervals]
if output_file_path is None:
self.print_info(u"Intervals detected:")
for line in msg:
self.print_generic(line)
else:
with io.open(output_file_path, "w", encoding="utf-8") as output_file:
output_file.write(u"\n".join(msg))
self.print_success(u"Created file '%s'" % output_file_path) | [
"def",
"write_to_file",
"(",
"self",
",",
"output_file_path",
",",
"intervals",
",",
"template",
")",
":",
"msg",
"=",
"[",
"template",
"%",
"(",
"interval",
")",
"for",
"interval",
"in",
"intervals",
"]",
"if",
"output_file_path",
"is",
"None",
":",
"self... | Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples | [
"Write",
"intervals",
"to",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/run_vad.py#L145-L163 | train | 227,029 |
readbeyond/aeneas | aeneas/tools/execute_job.py | ExecuteJobCLI.print_parameters | def print_parameters(self):
"""
Print the list of parameters and exit.
"""
self.print_info(u"Available parameters:")
self.print_generic(u"\n" + u"\n".join(self.PARAMETERS) + u"\n")
return self.HELP_EXIT_CODE | python | def print_parameters(self):
"""
Print the list of parameters and exit.
"""
self.print_info(u"Available parameters:")
self.print_generic(u"\n" + u"\n".join(self.PARAMETERS) + u"\n")
return self.HELP_EXIT_CODE | [
"def",
"print_parameters",
"(",
"self",
")",
":",
"self",
".",
"print_info",
"(",
"u\"Available parameters:\"",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
"+",
"u\"\\n\"",
".",
"join",
"(",
"self",
".",
"PARAMETERS",
")",
"+",
"u\"\\n\"",
")",
"retu... | Print the list of parameters and exit. | [
"Print",
"the",
"list",
"of",
"parameters",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_job.py#L148-L154 | train | 227,030 |
readbeyond/aeneas | aeneas/cewsubprocess.py | main | def main():
"""
Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file.
"""
# make sure we have enough parameters
if len(sys.argv) < 6:
print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
return 1
# read parameters
c_quit_after = float(sys.argv[1]) # NOTE: cew needs float, not TimeValue
c_backwards = int(sys.argv[2])
text_file_path = sys.argv[3]
audio_file_path = sys.argv[4]
data_file_path = sys.argv[5]
# read (voice_code, text) from file
s_text = []
with io.open(text_file_path, "r", encoding="utf-8") as text:
for line in text.readlines():
# NOTE: not using strip() to avoid removing trailing blank characters
line = line.replace(u"\n", u"").replace(u"\r", u"")
idx = line.find(" ")
if idx > 0:
f_voice_code = line[:idx]
f_text = line[(idx + 1):]
s_text.append((f_voice_code, f_text))
# convert to bytes/unicode as required by subprocess
c_text = []
if gf.PY2:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
else:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))
try:
import aeneas.cew.cew
sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
audio_file_path,
c_quit_after,
c_backwards,
c_text
)
with io.open(data_file_path, "w", encoding="utf-8") as data:
data.write(u"%d\n" % (sr))
data.write(u"%d\n" % (sf))
data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
except Exception as exc:
print(u"Unexpected error: %s" % str(exc)) | python | def main():
"""
Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file.
"""
# make sure we have enough parameters
if len(sys.argv) < 6:
print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
return 1
# read parameters
c_quit_after = float(sys.argv[1]) # NOTE: cew needs float, not TimeValue
c_backwards = int(sys.argv[2])
text_file_path = sys.argv[3]
audio_file_path = sys.argv[4]
data_file_path = sys.argv[5]
# read (voice_code, text) from file
s_text = []
with io.open(text_file_path, "r", encoding="utf-8") as text:
for line in text.readlines():
# NOTE: not using strip() to avoid removing trailing blank characters
line = line.replace(u"\n", u"").replace(u"\r", u"")
idx = line.find(" ")
if idx > 0:
f_voice_code = line[:idx]
f_text = line[(idx + 1):]
s_text.append((f_voice_code, f_text))
# convert to bytes/unicode as required by subprocess
c_text = []
if gf.PY2:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
else:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))
try:
import aeneas.cew.cew
sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
audio_file_path,
c_quit_after,
c_backwards,
c_text
)
with io.open(data_file_path, "w", encoding="utf-8") as data:
data.write(u"%d\n" % (sr))
data.write(u"%d\n" % (sf))
data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
except Exception as exc:
print(u"Unexpected error: %s" % str(exc)) | [
"def",
"main",
"(",
")",
":",
"# make sure we have enough parameters",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"6",
":",
"print",
"(",
"\"You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH\"",
")",
"return",
"1",
"# re... | Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file. | [
"Run",
"aeneas",
".",
"cew",
"reading",
"input",
"text",
"from",
"file",
"and",
"writing",
"audio",
"and",
"interval",
"data",
"to",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/cewsubprocess.py#L137-L188 | train | 227,031 |
readbeyond/aeneas | aeneas/syncmap/smfsmil.py | SyncMapFormatSMIL.parse | def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated
"""
from lxml import etree
smil_ns = "{http://www.w3.org/ns/SMIL}"
root = etree.fromstring(gf.safe_bytes(input_text))
for par in root.iter(smil_ns + "par"):
for child in par:
if child.tag == (smil_ns + "text"):
identifier = gf.safe_unicode(gf.split_url(child.get("src"))[1])
elif child.tag == (smil_ns + "audio"):
begin_text = child.get("clipBegin")
if ":" in begin_text:
begin = gf.time_from_hhmmssmmm(begin_text)
else:
begin = gf.time_from_ssmmm(begin_text)
end_text = child.get("clipEnd")
if ":" in end_text:
end = gf.time_from_hhmmssmmm(end_text)
else:
end = gf.time_from_ssmmm(end_text)
# TODO read text from additional text_file?
self._add_fragment(
syncmap=syncmap,
identifier=identifier,
lines=[u""],
begin=begin,
end=end
) | python | def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated
"""
from lxml import etree
smil_ns = "{http://www.w3.org/ns/SMIL}"
root = etree.fromstring(gf.safe_bytes(input_text))
for par in root.iter(smil_ns + "par"):
for child in par:
if child.tag == (smil_ns + "text"):
identifier = gf.safe_unicode(gf.split_url(child.get("src"))[1])
elif child.tag == (smil_ns + "audio"):
begin_text = child.get("clipBegin")
if ":" in begin_text:
begin = gf.time_from_hhmmssmmm(begin_text)
else:
begin = gf.time_from_ssmmm(begin_text)
end_text = child.get("clipEnd")
if ":" in end_text:
end = gf.time_from_hhmmssmmm(end_text)
else:
end = gf.time_from_ssmmm(end_text)
# TODO read text from additional text_file?
self._add_fragment(
syncmap=syncmap,
identifier=identifier,
lines=[u""],
begin=begin,
end=end
) | [
"def",
"parse",
"(",
"self",
",",
"input_text",
",",
"syncmap",
")",
":",
"from",
"lxml",
"import",
"etree",
"smil_ns",
"=",
"\"{http://www.w3.org/ns/SMIL}\"",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"gf",
".",
"safe_bytes",
"(",
"input_text",
")",
")"... | Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated | [
"Read",
"from",
"SMIL",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfsmil.py#L55-L89 | train | 227,032 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList._is_valid_index | def _is_valid_index(self, index):
"""
Return ``True`` if and only if the given ``index``
is valid.
"""
if isinstance(index, int):
return (index >= 0) and (index < len(self))
if isinstance(index, list):
valid = True
for i in index:
valid = valid or self._is_valid_index(i)
return valid
return False | python | def _is_valid_index(self, index):
"""
Return ``True`` if and only if the given ``index``
is valid.
"""
if isinstance(index, int):
return (index >= 0) and (index < len(self))
if isinstance(index, list):
valid = True
for i in index:
valid = valid or self._is_valid_index(i)
return valid
return False | [
"def",
"_is_valid_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"return",
"(",
"index",
">=",
"0",
")",
"and",
"(",
"index",
"<",
"len",
"(",
"self",
")",
")",
"if",
"isinstance",
"(",
"index",... | Return ``True`` if and only if the given ``index``
is valid. | [
"Return",
"True",
"if",
"and",
"only",
"if",
"the",
"given",
"index",
"is",
"valid",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L105-L117 | train | 227,033 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList._check_boundaries | def _check_boundaries(self, fragment):
"""
Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK.
"""
if not isinstance(fragment, SyncMapFragment):
raise TypeError(u"fragment is not an instance of SyncMapFragment")
interval = fragment.interval
if not isinstance(interval, TimeInterval):
raise TypeError(u"interval is not an instance of TimeInterval")
if (self.begin is not None) and (interval.begin < self.begin):
raise ValueError(u"interval.begin is before self.begin")
if (self.end is not None) and (interval.end > self.end):
raise ValueError(u"interval.end is after self.end") | python | def _check_boundaries(self, fragment):
"""
Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK.
"""
if not isinstance(fragment, SyncMapFragment):
raise TypeError(u"fragment is not an instance of SyncMapFragment")
interval = fragment.interval
if not isinstance(interval, TimeInterval):
raise TypeError(u"interval is not an instance of TimeInterval")
if (self.begin is not None) and (interval.begin < self.begin):
raise ValueError(u"interval.begin is before self.begin")
if (self.end is not None) and (interval.end > self.end):
raise ValueError(u"interval.end is after self.end") | [
"def",
"_check_boundaries",
"(",
"self",
",",
"fragment",
")",
":",
"if",
"not",
"isinstance",
"(",
"fragment",
",",
"SyncMapFragment",
")",
":",
"raise",
"TypeError",
"(",
"u\"fragment is not an instance of SyncMapFragment\"",
")",
"interval",
"=",
"fragment",
".",... | Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK. | [
"Check",
"that",
"the",
"interval",
"of",
"the",
"given",
"fragment",
"is",
"within",
"the",
"boundaries",
"of",
"the",
"list",
".",
"Raises",
"an",
"error",
"if",
"not",
"OK",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L119-L133 | train | 227,034 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.remove | def remove(self, indices):
"""
Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid
"""
if not self._is_valid_index(indices):
self.log_exc(u"The given list of indices is not valid", None, True, ValueError)
new_fragments = []
sorted_indices = sorted(indices)
i = 0
j = 0
while (i < len(self)) and (j < len(sorted_indices)):
if i != sorted_indices[j]:
new_fragments.append(self[i])
else:
j += 1
i += 1
while i < len(self):
new_fragments.append(self[i])
i += 1
self.__fragments = new_fragments | python | def remove(self, indices):
"""
Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid
"""
if not self._is_valid_index(indices):
self.log_exc(u"The given list of indices is not valid", None, True, ValueError)
new_fragments = []
sorted_indices = sorted(indices)
i = 0
j = 0
while (i < len(self)) and (j < len(sorted_indices)):
if i != sorted_indices[j]:
new_fragments.append(self[i])
else:
j += 1
i += 1
while i < len(self):
new_fragments.append(self[i])
i += 1
self.__fragments = new_fragments | [
"def",
"remove",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_is_valid_index",
"(",
"indices",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The given list of indices is not valid\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"new_... | Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid | [
"Remove",
"the",
"fragments",
"corresponding",
"to",
"the",
"given",
"list",
"of",
"indices",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L223-L246 | train | 227,035 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.sort | def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log(u"Sorting...")
self.__fragments = sorted(self.__fragments)
self.log(u"Sorting... done")
self.log(u"Checking relative positions...")
for i in range(len(self) - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:
self.log(u"Found overlapping fragments:")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
self.log_exc(u"The list contains two fragments overlapping in a forbidden way", None, True, ValueError)
self.log(u"Checking relative positions... done")
self.__sorted = True | python | def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log(u"Sorting...")
self.__fragments = sorted(self.__fragments)
self.log(u"Sorting... done")
self.log(u"Checking relative positions...")
for i in range(len(self) - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:
self.log(u"Found overlapping fragments:")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
self.log_exc(u"The list contains two fragments overlapping in a forbidden way", None, True, ValueError)
self.log(u"Checking relative positions... done")
self.__sorted = True | [
"def",
"sort",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_guaranteed_sorted",
":",
"self",
".",
"log",
"(",
"u\"Already sorted, returning\"",
")",
"return",
"self",
".",
"log",
"(",
"u\"Sorting...\"",
")",
"self",
".",
"__fragments",
"=",
"sorted",
"(",
... | Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints | [
"Sort",
"the",
"fragments",
"in",
"the",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L248-L271 | train | 227,036 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.remove_nonspeech_fragments | def remove_nonspeech_fragments(self, zero_length_only=False):
"""
Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments
"""
self.log(u"Removing nonspeech fragments...")
nonspeech = list(self.nonspeech_fragments)
if zero_length_only:
nonspeech = [(i, f) for i, f in nonspeech if f.has_zero_length]
nonspeech_indices = [i for i, f in nonspeech]
self.remove(nonspeech_indices)
if zero_length_only:
for i, f in list(self.nonspeech_fragments):
f.fragment_type = SyncMapFragment.REGULAR
self.log(u"Removing nonspeech fragments... done") | python | def remove_nonspeech_fragments(self, zero_length_only=False):
"""
Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments
"""
self.log(u"Removing nonspeech fragments...")
nonspeech = list(self.nonspeech_fragments)
if zero_length_only:
nonspeech = [(i, f) for i, f in nonspeech if f.has_zero_length]
nonspeech_indices = [i for i, f in nonspeech]
self.remove(nonspeech_indices)
if zero_length_only:
for i, f in list(self.nonspeech_fragments):
f.fragment_type = SyncMapFragment.REGULAR
self.log(u"Removing nonspeech fragments... done") | [
"def",
"remove_nonspeech_fragments",
"(",
"self",
",",
"zero_length_only",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Removing nonspeech fragments...\"",
")",
"nonspeech",
"=",
"list",
"(",
"self",
".",
"nonspeech_fragments",
")",
"if",
"zero_length_only",... | Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments | [
"Remove",
"NONSPEECH",
"fragments",
"from",
"the",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L273-L292 | train | 227,037 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.has_zero_length_fragments | def has_zero_length_fragments(self, min_index=None, max_index=None):
"""
Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
zero = [i for i in range(min_index, max_index) if self[i].has_zero_length]
self.log([u"Fragments with zero length: %s", zero])
return (len(zero) > 0) | python | def has_zero_length_fragments(self, min_index=None, max_index=None):
"""
Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
zero = [i for i in range(min_index, max_index) if self[i].has_zero_length]
self.log([u"Fragments with zero length: %s", zero])
return (len(zero) > 0) | [
"def",
"has_zero_length_fragments",
"(",
"self",
",",
"min_index",
"=",
"None",
",",
"max_index",
"=",
"None",
")",
":",
"min_index",
",",
"max_index",
"=",
"self",
".",
"_check_min_max_indices",
"(",
"min_index",
",",
"max_index",
")",
"zero",
"=",
"[",
"i"... | Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool | [
"Return",
"True",
"if",
"the",
"list",
"has",
"at",
"least",
"one",
"interval",
"with",
"zero",
"length",
"withing",
"min_index",
"and",
"max_index",
".",
"If",
"the",
"latter",
"are",
"not",
"specified",
"check",
"all",
"intervals",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L294-L309 | train | 227,038 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.has_adjacent_fragments_only | def has_adjacent_fragments_only(self, min_index=None, max_index=None):
"""
Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
for i in range(min_index, max_index - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
self.log(u"Found non adjacent fragments")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
return False
return True | python | def has_adjacent_fragments_only(self, min_index=None, max_index=None):
"""
Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
for i in range(min_index, max_index - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
self.log(u"Found non adjacent fragments")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
return False
return True | [
"def",
"has_adjacent_fragments_only",
"(",
"self",
",",
"min_index",
"=",
"None",
",",
"max_index",
"=",
"None",
")",
":",
"min_index",
",",
"max_index",
"=",
"self",
".",
"_check_min_max_indices",
"(",
"min_index",
",",
"max_index",
")",
"for",
"i",
"in",
"... | Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool | [
"Return",
"True",
"if",
"the",
"list",
"contains",
"only",
"adjacent",
"fragments",
"that",
"is",
"if",
"it",
"does",
"not",
"have",
"gaps",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L311-L331 | train | 227,039 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.offset | def offset(self, offset):
"""
Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
"""
self.log(u"Applying offset to all fragments...")
self.log([u" Offset %.3f", offset])
for fragment in self.fragments:
fragment.interval.offset(
offset=offset,
allow_negative=False,
min_begin_value=self.begin,
max_end_value=self.end
)
self.log(u"Applying offset to all fragments... done") | python | def offset(self, offset):
"""
Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
"""
self.log(u"Applying offset to all fragments...")
self.log([u" Offset %.3f", offset])
for fragment in self.fragments:
fragment.interval.offset(
offset=offset,
allow_negative=False,
min_begin_value=self.begin,
max_end_value=self.end
)
self.log(u"Applying offset to all fragments... done") | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"log",
"(",
"u\"Applying offset to all fragments...\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" Offset %.3f\"",
",",
"offset",
"]",
")",
"for",
"fragment",
"in",
"self",
".",
"fragments",
... | Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue`` | [
"Move",
"all",
"the",
"intervals",
"in",
"the",
"list",
"by",
"the",
"given",
"offset",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L360-L377 | train | 227,040 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.move_transition_point | def move_transition_point(self, fragment_index, value):
"""
Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue`
"""
self.log(u"Called move_transition_point with")
self.log([u" fragment_index %d", fragment_index])
self.log([u" value %.3f", value])
if (fragment_index < 0) or (fragment_index > (len(self) - 3)):
self.log(u"Bad fragment_index, returning")
return
current_interval = self[fragment_index].interval
next_interval = self[fragment_index + 1].interval
if value > next_interval.end:
self.log(u"Bad value, returning")
return
if not current_interval.is_non_zero_before_non_zero(next_interval):
self.log(u"Bad interval configuration, returning")
return
current_interval.end = value
next_interval.begin = value
self.log(u"Moved transition point") | python | def move_transition_point(self, fragment_index, value):
"""
Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue`
"""
self.log(u"Called move_transition_point with")
self.log([u" fragment_index %d", fragment_index])
self.log([u" value %.3f", value])
if (fragment_index < 0) or (fragment_index > (len(self) - 3)):
self.log(u"Bad fragment_index, returning")
return
current_interval = self[fragment_index].interval
next_interval = self[fragment_index + 1].interval
if value > next_interval.end:
self.log(u"Bad value, returning")
return
if not current_interval.is_non_zero_before_non_zero(next_interval):
self.log(u"Bad interval configuration, returning")
return
current_interval.end = value
next_interval.begin = value
self.log(u"Moved transition point") | [
"def",
"move_transition_point",
"(",
"self",
",",
"fragment_index",
",",
"value",
")",
":",
"self",
".",
"log",
"(",
"u\"Called move_transition_point with\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" fragment_index %d\"",
",",
"fragment_index",
"]",
")",
"self",
... | Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue` | [
"Change",
"the",
"transition",
"point",
"between",
"fragment",
"fragment_index",
"and",
"the",
"next",
"fragment",
"to",
"the",
"time",
"value",
"value",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L379-L416 | train | 227,041 |
readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.inject_long_nonspeech_fragments | def inject_long_nonspeech_fragments(self, pairs, replacement_string):
"""
Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals
"""
self.log(u"Called inject_long_nonspeech_fragments")
# set the appropriate fragment text
if replacement_string in [None, gc.PPV_TASK_ADJUST_BOUNDARY_NONSPEECH_REMOVE]:
self.log(u" Remove long nonspeech")
lines = []
else:
self.log([u" Replace long nonspeech with '%s'", replacement_string])
lines = [replacement_string]
# first, make room for the nonspeech intervals
self.log(u" First pass: making room...")
for nsi, index in pairs:
self[index].interval.end = nsi.begin
self[index + 1].interval.begin = nsi.end
self.log(u" First pass: making room... done")
self.log(u" Second pass: append nonspeech intervals...")
for i, (nsi, index) in enumerate(pairs, 1):
identifier = u"n%06d" % i
self.add(SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
language=None,
lines=lines,
filtered_lines=lines
),
interval=nsi,
fragment_type=SyncMapFragment.NONSPEECH
), sort=False)
self.log(u" Second pass: append nonspeech intervals... done")
self.log(u" Third pass: sorting...")
self.sort()
self.log(u" Third pass: sorting... done") | python | def inject_long_nonspeech_fragments(self, pairs, replacement_string):
"""
Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals
"""
self.log(u"Called inject_long_nonspeech_fragments")
# set the appropriate fragment text
if replacement_string in [None, gc.PPV_TASK_ADJUST_BOUNDARY_NONSPEECH_REMOVE]:
self.log(u" Remove long nonspeech")
lines = []
else:
self.log([u" Replace long nonspeech with '%s'", replacement_string])
lines = [replacement_string]
# first, make room for the nonspeech intervals
self.log(u" First pass: making room...")
for nsi, index in pairs:
self[index].interval.end = nsi.begin
self[index + 1].interval.begin = nsi.end
self.log(u" First pass: making room... done")
self.log(u" Second pass: append nonspeech intervals...")
for i, (nsi, index) in enumerate(pairs, 1):
identifier = u"n%06d" % i
self.add(SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
language=None,
lines=lines,
filtered_lines=lines
),
interval=nsi,
fragment_type=SyncMapFragment.NONSPEECH
), sort=False)
self.log(u" Second pass: append nonspeech intervals... done")
self.log(u" Third pass: sorting...")
self.sort()
self.log(u" Third pass: sorting... done") | [
"def",
"inject_long_nonspeech_fragments",
"(",
"self",
",",
"pairs",
",",
"replacement_string",
")",
":",
"self",
".",
"log",
"(",
"u\"Called inject_long_nonspeech_fragments\"",
")",
"# set the appropriate fragment text",
"if",
"replacement_string",
"in",
"[",
"None",
","... | Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals | [
"Inject",
"nonspeech",
"fragments",
"corresponding",
"to",
"the",
"given",
"intervals",
"in",
"this",
"fragment",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L507-L550 | train | 227,042 |
readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_accumulated_cost_matrix | def compute_accumulated_cost_matrix(self):
"""
Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Returning accumulated cost matrix")
return self.dtw.compute_accumulated_cost_matrix() | python | def compute_accumulated_cost_matrix(self):
"""
Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Returning accumulated cost matrix")
return self.dtw.compute_accumulated_cost_matrix() | [
"def",
"compute_accumulated_cost_matrix",
"(",
"self",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning None\"",
")",
"return",
"None",
"self",
".",
"lo... | Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0 | [
"Compute",
"the",
"accumulated",
"cost",
"matrix",
"and",
"return",
"it",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L160-L178 | train | 227,043 |
readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_path | def compute_path(self):
"""
Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Computing path...")
wave_path = self.dtw.compute_path()
self.log(u"Computing path... done")
self.log(u"Translating path to full wave indices...")
real_indices = numpy.array([t[0] for t in wave_path])
synt_indices = numpy.array([t[1] for t in wave_path])
if self.rconf.mmn:
self.log(u"Translating real indices with masked_middle_map...")
real_indices = self.real_wave_mfcc.masked_middle_map[real_indices]
real_indices[0] = self.real_wave_mfcc.head_length
self.log(u"Translating real indices with masked_middle_map... done")
self.log(u"Translating synt indices with masked_middle_map...")
synt_indices = self.synt_wave_mfcc.masked_middle_map[synt_indices]
self.log(u"Translating synt indices with masked_middle_map... done")
else:
self.log(u"Translating real indices by adding head_length...")
real_indices += self.real_wave_mfcc.head_length
self.log(u"Translating real indices by adding head_length... done")
self.log(u"Nothing to do with synt indices")
self.log(u"Translating path to full wave indices... done")
return (real_indices, synt_indices) | python | def compute_path(self):
"""
Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Computing path...")
wave_path = self.dtw.compute_path()
self.log(u"Computing path... done")
self.log(u"Translating path to full wave indices...")
real_indices = numpy.array([t[0] for t in wave_path])
synt_indices = numpy.array([t[1] for t in wave_path])
if self.rconf.mmn:
self.log(u"Translating real indices with masked_middle_map...")
real_indices = self.real_wave_mfcc.masked_middle_map[real_indices]
real_indices[0] = self.real_wave_mfcc.head_length
self.log(u"Translating real indices with masked_middle_map... done")
self.log(u"Translating synt indices with masked_middle_map...")
synt_indices = self.synt_wave_mfcc.masked_middle_map[synt_indices]
self.log(u"Translating synt indices with masked_middle_map... done")
else:
self.log(u"Translating real indices by adding head_length...")
real_indices += self.real_wave_mfcc.head_length
self.log(u"Translating real indices by adding head_length... done")
self.log(u"Nothing to do with synt indices")
self.log(u"Translating path to full wave indices... done")
return (real_indices, synt_indices) | [
"def",
"compute_path",
"(",
"self",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning None\"",
")",
"return",
"None",
"self",
".",
"log",
"(",
"u\"Co... | Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed. | [
"Compute",
"the",
"min",
"cost",
"path",
"between",
"the",
"two",
"waves",
"and",
"return",
"it",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L180-L224 | train | 227,044 |
readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_boundaries | def compute_boundaries(self, synt_anchors):
"""
Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning artificial boundary indices")
begin = self.real_wave_mfcc.middle_begin
end = self.real_wave_mfcc.tail_begin
n = len(synt_anchors)
step = float(end - begin) / n
boundary_indices = [begin + int(i * step) for i in range(n)] + [end]
return numpy.array(boundary_indices)
self.log(u"Computing path...")
real_indices, synt_indices = self.compute_path()
self.log(u"Computing path... done")
self.log(u"Computing boundary indices...")
# both real_indices and synt_indices are w.r.t. the full wave
self.log([u"Fragments: %d", len(synt_anchors)])
self.log([u"Path length: %d", len(real_indices)])
# synt_anchors as in seconds, convert them in MFCC indices
# see also issue #102
mws = self.rconf.mws
sample_rate = self.rconf.sample_rate
samples_per_mws = mws * sample_rate
if samples_per_mws.is_integer:
anchor_indices = numpy.array([int(a[0] / mws) for a in synt_anchors])
else:
#
# NOTE this is not elegant, but it saves the day for the user
#
self.log_warn(u"The number of samples in each window shift is not an integer, time drift might occur.")
anchor_indices = numpy.array([(int(a[0] * sample_rate / mws) / sample_rate) for a in synt_anchors])
#
# right side sets the split point at the very beginning of "next" fragment
#
# NOTE clip() is needed since searchsorted() with side="right" might return
# an index == len(synt_indices) == len(real_indices)
# when the insertion point is past the last element of synt_indices
# causing the fancy indexing real_indices[...] below might fail
begin_indices = numpy.clip(numpy.searchsorted(synt_indices, anchor_indices, side="right"), 0, len(synt_indices) - 1)
# first split must occur at zero
begin_indices[0] = 0
#
# map onto real indices, obtaining "default" boundary indices
#
# NOTE since len(synt_indices) == len(real_indices)
# and because the numpy.clip() above, the fancy indexing is always valid
#
boundary_indices = numpy.append(real_indices[begin_indices], self.real_wave_mfcc.tail_begin)
self.log([u"Boundary indices: %d", len(boundary_indices)])
self.log(u"Computing boundary indices... done")
return boundary_indices | python | def compute_boundaries(self, synt_anchors):
"""
Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning artificial boundary indices")
begin = self.real_wave_mfcc.middle_begin
end = self.real_wave_mfcc.tail_begin
n = len(synt_anchors)
step = float(end - begin) / n
boundary_indices = [begin + int(i * step) for i in range(n)] + [end]
return numpy.array(boundary_indices)
self.log(u"Computing path...")
real_indices, synt_indices = self.compute_path()
self.log(u"Computing path... done")
self.log(u"Computing boundary indices...")
# both real_indices and synt_indices are w.r.t. the full wave
self.log([u"Fragments: %d", len(synt_anchors)])
self.log([u"Path length: %d", len(real_indices)])
# synt_anchors as in seconds, convert them in MFCC indices
# see also issue #102
mws = self.rconf.mws
sample_rate = self.rconf.sample_rate
samples_per_mws = mws * sample_rate
if samples_per_mws.is_integer:
anchor_indices = numpy.array([int(a[0] / mws) for a in synt_anchors])
else:
#
# NOTE this is not elegant, but it saves the day for the user
#
self.log_warn(u"The number of samples in each window shift is not an integer, time drift might occur.")
anchor_indices = numpy.array([(int(a[0] * sample_rate / mws) / sample_rate) for a in synt_anchors])
#
# right side sets the split point at the very beginning of "next" fragment
#
# NOTE clip() is needed since searchsorted() with side="right" might return
# an index == len(synt_indices) == len(real_indices)
# when the insertion point is past the last element of synt_indices
# causing the fancy indexing real_indices[...] below might fail
begin_indices = numpy.clip(numpy.searchsorted(synt_indices, anchor_indices, side="right"), 0, len(synt_indices) - 1)
# first split must occur at zero
begin_indices[0] = 0
#
# map onto real indices, obtaining "default" boundary indices
#
# NOTE since len(synt_indices) == len(real_indices)
# and because the numpy.clip() above, the fancy indexing is always valid
#
boundary_indices = numpy.append(real_indices[begin_indices], self.real_wave_mfcc.tail_begin)
self.log([u"Boundary indices: %d", len(boundary_indices)])
self.log(u"Computing boundary indices... done")
return boundary_indices | [
"def",
"compute_boundaries",
"(",
"self",
",",
"synt_anchors",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning artificial boundary indices\"",
")",
"begin"... | Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D) | [
"Compute",
"the",
"min",
"cost",
"path",
"between",
"the",
"two",
"waves",
"and",
"return",
"a",
"list",
"of",
"boundary",
"points",
"representing",
"the",
"argmin",
"values",
"with",
"respect",
"to",
"the",
"provided",
"synt_anchors",
"timings",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L226-L296 | train | 227,045 |
readbeyond/aeneas | aeneas/dtw.py | DTWAligner._setup_dtw | def _setup_dtw(self):
"""
Set the DTW object up.
"""
# check if the DTW object has already been set up
if self.dtw is not None:
return
# check we have the AudioFileMFCC objects
if (self.real_wave_mfcc is None) or (self.real_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The real wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
if (self.synt_wave_mfcc is None) or (self.synt_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The synt wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
# setup
algorithm = self.rconf[RuntimeConfiguration.DTW_ALGORITHM]
delta = int(2 * self.rconf.dtw_margin / self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT])
mfcc2_length = self.synt_wave_mfcc.middle_length
self.log([u"Requested algorithm: '%s'", algorithm])
self.log([u"delta = %d", delta])
self.log([u"m = %d", mfcc2_length])
# check if delta is >= length of synt wave
if mfcc2_length <= delta:
self.log(u"We have mfcc2_length <= delta")
if (self.rconf[RuntimeConfiguration.C_EXTENSIONS]) and (gf.can_run_c_extension()):
# the C code can be run: since it is still faster, do not run EXACT
self.log(u"C extensions enabled and loaded: not selecting EXACT algorithm")
else:
self.log(u"Selecting EXACT algorithm")
algorithm = DTWAlgorithm.EXACT
# select mask here
if self.rconf.mmn:
self.log(u"Using masked MFCC")
real_mfcc = self.real_wave_mfcc.masked_middle_mfcc
synt_mfcc = self.synt_wave_mfcc.masked_middle_mfcc
else:
self.log(u"Using unmasked MFCC")
real_mfcc = self.real_wave_mfcc.middle_mfcc
synt_mfcc = self.synt_wave_mfcc.middle_mfcc
n = real_mfcc.shape[1]
m = synt_mfcc.shape[1]
self.log([u" Number of MFCC frames in real wave: %d", n])
self.log([u" Number of MFCC frames in synt wave: %d", m])
if (n == 0) or (m == 0):
self.log(u"Setting self.dtw to None")
self.dtw = None
else:
# set the selected algorithm
if algorithm == DTWAlgorithm.EXACT:
self.log(u"Computing with EXACT algo")
self.dtw = DTWExact(
m1=real_mfcc,
m2=synt_mfcc,
rconf=self.rconf,
logger=self.logger
)
else:
self.log(u"Computing with STRIPE algo")
self.dtw = DTWStripe(
m1=real_mfcc,
m2=synt_mfcc,
delta=delta,
rconf=self.rconf,
logger=self.logger
) | python | def _setup_dtw(self):
"""
Set the DTW object up.
"""
# check if the DTW object has already been set up
if self.dtw is not None:
return
# check we have the AudioFileMFCC objects
if (self.real_wave_mfcc is None) or (self.real_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The real wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
if (self.synt_wave_mfcc is None) or (self.synt_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The synt wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
# setup
algorithm = self.rconf[RuntimeConfiguration.DTW_ALGORITHM]
delta = int(2 * self.rconf.dtw_margin / self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT])
mfcc2_length = self.synt_wave_mfcc.middle_length
self.log([u"Requested algorithm: '%s'", algorithm])
self.log([u"delta = %d", delta])
self.log([u"m = %d", mfcc2_length])
# check if delta is >= length of synt wave
if mfcc2_length <= delta:
self.log(u"We have mfcc2_length <= delta")
if (self.rconf[RuntimeConfiguration.C_EXTENSIONS]) and (gf.can_run_c_extension()):
# the C code can be run: since it is still faster, do not run EXACT
self.log(u"C extensions enabled and loaded: not selecting EXACT algorithm")
else:
self.log(u"Selecting EXACT algorithm")
algorithm = DTWAlgorithm.EXACT
# select mask here
if self.rconf.mmn:
self.log(u"Using masked MFCC")
real_mfcc = self.real_wave_mfcc.masked_middle_mfcc
synt_mfcc = self.synt_wave_mfcc.masked_middle_mfcc
else:
self.log(u"Using unmasked MFCC")
real_mfcc = self.real_wave_mfcc.middle_mfcc
synt_mfcc = self.synt_wave_mfcc.middle_mfcc
n = real_mfcc.shape[1]
m = synt_mfcc.shape[1]
self.log([u" Number of MFCC frames in real wave: %d", n])
self.log([u" Number of MFCC frames in synt wave: %d", m])
if (n == 0) or (m == 0):
self.log(u"Setting self.dtw to None")
self.dtw = None
else:
# set the selected algorithm
if algorithm == DTWAlgorithm.EXACT:
self.log(u"Computing with EXACT algo")
self.dtw = DTWExact(
m1=real_mfcc,
m2=synt_mfcc,
rconf=self.rconf,
logger=self.logger
)
else:
self.log(u"Computing with STRIPE algo")
self.dtw = DTWStripe(
m1=real_mfcc,
m2=synt_mfcc,
delta=delta,
rconf=self.rconf,
logger=self.logger
) | [
"def",
"_setup_dtw",
"(",
"self",
")",
":",
"# check if the DTW object has already been set up",
"if",
"self",
".",
"dtw",
"is",
"not",
"None",
":",
"return",
"# check we have the AudioFileMFCC objects",
"if",
"(",
"self",
".",
"real_wave_mfcc",
"is",
"None",
")",
"... | Set the DTW object up. | [
"Set",
"the",
"DTW",
"object",
"up",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L298-L363 | train | 227,046 |
readbeyond/aeneas | check_dependencies.py | check_import | def check_import():
"""
Try to import the aeneas package and return ``True`` if that fails.
"""
try:
import aeneas
print_success(u"aeneas OK")
return False
except ImportError:
print_error(u"aeneas ERROR")
print_info(u" Unable to load the aeneas Python package")
print_info(u" This error is probably caused by:")
print_info(u" A. you did not download/git-clone the aeneas package properly; or")
print_info(u" B. you did not install the required Python packages:")
print_info(u" 1. BeautifulSoup4")
print_info(u" 2. lxml")
print_info(u" 3. numpy")
except Exception as e:
print_error(e)
return True | python | def check_import():
"""
Try to import the aeneas package and return ``True`` if that fails.
"""
try:
import aeneas
print_success(u"aeneas OK")
return False
except ImportError:
print_error(u"aeneas ERROR")
print_info(u" Unable to load the aeneas Python package")
print_info(u" This error is probably caused by:")
print_info(u" A. you did not download/git-clone the aeneas package properly; or")
print_info(u" B. you did not install the required Python packages:")
print_info(u" 1. BeautifulSoup4")
print_info(u" 2. lxml")
print_info(u" 3. numpy")
except Exception as e:
print_error(e)
return True | [
"def",
"check_import",
"(",
")",
":",
"try",
":",
"import",
"aeneas",
"print_success",
"(",
"u\"aeneas OK\"",
")",
"return",
"False",
"except",
"ImportError",
":",
"print_error",
"(",
"u\"aeneas ERROR\"",
")",
"print_info",
"(",
"u\" Unable to load th... | Try to import the aeneas package and return ``True`` if that fails. | [
"Try",
"to",
"import",
"the",
"aeneas",
"package",
"and",
"return",
"True",
"if",
"that",
"fails",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/check_dependencies.py#L86-L105 | train | 227,047 |
readbeyond/aeneas | check_dependencies.py | main | def main():
""" The entry point for this module """
# first, check we can import aeneas package, exiting on failure
if check_import():
sys.exit(1)
# import and run the built-in diagnostics
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_all()
if errors:
sys.exit(1)
if c_ext_warnings:
print_warning(u"All required dependencies are met but at least one Python C extension is not available")
print_warning(u"You can still run aeneas but it will be slower")
print_warning(u"Enjoy running aeneas!")
sys.exit(2)
else:
print_success(u"All required dependencies are met and all available Python C extensions are working")
print_success(u"Enjoy running aeneas!")
sys.exit(0) | python | def main():
""" The entry point for this module """
# first, check we can import aeneas package, exiting on failure
if check_import():
sys.exit(1)
# import and run the built-in diagnostics
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_all()
if errors:
sys.exit(1)
if c_ext_warnings:
print_warning(u"All required dependencies are met but at least one Python C extension is not available")
print_warning(u"You can still run aeneas but it will be slower")
print_warning(u"Enjoy running aeneas!")
sys.exit(2)
else:
print_success(u"All required dependencies are met and all available Python C extensions are working")
print_success(u"Enjoy running aeneas!")
sys.exit(0) | [
"def",
"main",
"(",
")",
":",
"# first, check we can import aeneas package, exiting on failure",
"if",
"check_import",
"(",
")",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"# import and run the built-in diagnostics",
"from",
"aeneas",
".",
"diagnostics",
"import",
"Diagnos... | The entry point for this module | [
"The",
"entry",
"point",
"for",
"this",
"module"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/check_dependencies.py#L108-L127 | train | 227,048 |
readbeyond/aeneas | aeneas/tree.py | Tree.is_pleasant | def is_pleasant(self):
"""
Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool
"""
levels = sorted([n.level for n in self.leaves])
return levels[0] == levels[-1] | python | def is_pleasant(self):
"""
Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool
"""
levels = sorted([n.level for n in self.leaves])
return levels[0] == levels[-1] | [
"def",
"is_pleasant",
"(",
"self",
")",
":",
"levels",
"=",
"sorted",
"(",
"[",
"n",
".",
"level",
"for",
"n",
"in",
"self",
".",
"leaves",
"]",
")",
"return",
"levels",
"[",
"0",
"]",
"==",
"levels",
"[",
"-",
"1",
"]"
] | Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool | [
"Return",
"True",
"if",
"all",
"the",
"leaves",
"in",
"the",
"subtree",
"rooted",
"at",
"this",
"node",
"are",
"at",
"the",
"same",
"level",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L208-L217 | train | 227,049 |
readbeyond/aeneas | aeneas/tree.py | Tree.add_child | def add_child(self, node, as_last=True):
"""
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree`
"""
if not isinstance(node, Tree):
self.log_exc(u"node is not an instance of Tree", None, True, TypeError)
if as_last:
self.__children.append(node)
else:
self.__children = [node] + self.__children
node.__parent = self
new_height = 1 + self.level
for n in node.subtree:
n.__level += new_height | python | def add_child(self, node, as_last=True):
"""
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree`
"""
if not isinstance(node, Tree):
self.log_exc(u"node is not an instance of Tree", None, True, TypeError)
if as_last:
self.__children.append(node)
else:
self.__children = [node] + self.__children
node.__parent = self
new_height = 1 + self.level
for n in node.subtree:
n.__level += new_height | [
"def",
"add_child",
"(",
"self",
",",
"node",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Tree",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"node is not an instance of Tree\"",
",",
"None",
",",
"True",
",",
"TypeE... | Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree` | [
"Add",
"the",
"given",
"child",
"to",
"the",
"current",
"list",
"of",
"children",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L219-L243 | train | 227,050 |
readbeyond/aeneas | aeneas/tree.py | Tree.remove_child | def remove_child(self, index):
"""
Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed
"""
if index < 0:
index = index + len(self)
self.__children = self.__children[0:index] + self.__children[(index + 1):] | python | def remove_child(self, index):
"""
Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed
"""
if index < 0:
index = index + len(self)
self.__children = self.__children[0:index] + self.__children[(index + 1):] | [
"def",
"remove_child",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"index",
"+",
"len",
"(",
"self",
")",
"self",
".",
"__children",
"=",
"self",
".",
"__children",
"[",
"0",
":",
"index",
"]",
"+",
"self",
".... | Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed | [
"Remove",
"the",
"child",
"at",
"the",
"given",
"index",
"from",
"the",
"current",
"list",
"of",
"children",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L245-L254 | train | 227,051 |
readbeyond/aeneas | aeneas/tree.py | Tree.remove | def remove(self):
"""
Remove this node from the list of children of its current parent,
if the current parent is not ``None``, otherwise do nothing.
.. versionadded:: 1.7.0
"""
if self.parent is not None:
for i, child in enumerate(self.parent.children):
if id(child) == id(self):
self.parent.remove_child(i)
self.parent = None
break | python | def remove(self):
"""
Remove this node from the list of children of its current parent,
if the current parent is not ``None``, otherwise do nothing.
.. versionadded:: 1.7.0
"""
if self.parent is not None:
for i, child in enumerate(self.parent.children):
if id(child) == id(self):
self.parent.remove_child(i)
self.parent = None
break | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
":",
"if",
"id",
"(",
"child",
")",
"==",
"id",
"(",
"... | Remove this node from the list of children of its current parent,
if the current parent is not ``None``, otherwise do nothing.
.. versionadded:: 1.7.0 | [
"Remove",
"this",
"node",
"from",
"the",
"list",
"of",
"children",
"of",
"its",
"current",
"parent",
"if",
"the",
"current",
"parent",
"is",
"not",
"None",
"otherwise",
"do",
"nothing",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L256-L268 | train | 227,052 |
readbeyond/aeneas | aeneas/tree.py | Tree.remove_children | def remove_children(self, reset_parent=True):
"""
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
"""
if reset_parent:
for child in self.children:
child.parent = None
self.__children = [] | python | def remove_children(self, reset_parent=True):
"""
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
"""
if reset_parent:
for child in self.children:
child.parent = None
self.__children = [] | [
"def",
"remove_children",
"(",
"self",
",",
"reset_parent",
"=",
"True",
")",
":",
"if",
"reset_parent",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"parent",
"=",
"None",
"self",
".",
"__children",
"=",
"[",
"]"
] | Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children | [
"Remove",
"all",
"the",
"children",
"of",
"this",
"node",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L270-L280 | train | 227,053 |
readbeyond/aeneas | aeneas/tree.py | Tree.leaves_not_empty | def leaves_not_empty(self):
"""
Return the list of leaves not empty
in the tree rooted at this node,
in DFS order.
:rtype: list of :class:`~aeneas.tree.Tree`
"""
return [n for n in self.dfs if ((n.is_leaf) and (not n.is_empty))] | python | def leaves_not_empty(self):
"""
Return the list of leaves not empty
in the tree rooted at this node,
in DFS order.
:rtype: list of :class:`~aeneas.tree.Tree`
"""
return [n for n in self.dfs if ((n.is_leaf) and (not n.is_empty))] | [
"def",
"leaves_not_empty",
"(",
"self",
")",
":",
"return",
"[",
"n",
"for",
"n",
"in",
"self",
".",
"dfs",
"if",
"(",
"(",
"n",
".",
"is_leaf",
")",
"and",
"(",
"not",
"n",
".",
"is_empty",
")",
")",
"]"
] | Return the list of leaves not empty
in the tree rooted at this node,
in DFS order.
:rtype: list of :class:`~aeneas.tree.Tree` | [
"Return",
"the",
"list",
"of",
"leaves",
"not",
"empty",
"in",
"the",
"tree",
"rooted",
"at",
"this",
"node",
"in",
"DFS",
"order",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L335-L343 | train | 227,054 |
readbeyond/aeneas | aeneas/tree.py | Tree.height | def height(self):
"""
Return the height of the tree
rooted at this node,
that is, the difference between the level
of a deepest leaf and the level of this node.
Return ``1`` for a single-node tree,
``2`` for a two-levels tree, etc.
:rtype: int
"""
return max([n.level for n in self.subtree]) - self.level + 1 | python | def height(self):
"""
Return the height of the tree
rooted at this node,
that is, the difference between the level
of a deepest leaf and the level of this node.
Return ``1`` for a single-node tree,
``2`` for a two-levels tree, etc.
:rtype: int
"""
return max([n.level for n in self.subtree]) - self.level + 1 | [
"def",
"height",
"(",
"self",
")",
":",
"return",
"max",
"(",
"[",
"n",
".",
"level",
"for",
"n",
"in",
"self",
".",
"subtree",
"]",
")",
"-",
"self",
".",
"level",
"+",
"1"
] | Return the height of the tree
rooted at this node,
that is, the difference between the level
of a deepest leaf and the level of this node.
Return ``1`` for a single-node tree,
``2`` for a two-levels tree, etc.
:rtype: int | [
"Return",
"the",
"height",
"of",
"the",
"tree",
"rooted",
"at",
"this",
"node",
"that",
"is",
"the",
"difference",
"between",
"the",
"level",
"of",
"a",
"deepest",
"leaf",
"and",
"the",
"level",
"of",
"this",
"node",
".",
"Return",
"1",
"for",
"a",
"si... | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L357-L368 | train | 227,055 |
readbeyond/aeneas | aeneas/tree.py | Tree.levels | def levels(self):
"""
Return a list of lists of nodes.
The outer list is indexed by the level.
Each inner list contains the nodes at that level,
in DFS order.
:rtype: list of lists of :class:`~aeneas.tree.Tree`
"""
ret = [[] for i in range(self.height)]
for node in self.subtree:
ret[node.level - self.level].append(node)
return ret | python | def levels(self):
"""
Return a list of lists of nodes.
The outer list is indexed by the level.
Each inner list contains the nodes at that level,
in DFS order.
:rtype: list of lists of :class:`~aeneas.tree.Tree`
"""
ret = [[] for i in range(self.height)]
for node in self.subtree:
ret[node.level - self.level].append(node)
return ret | [
"def",
"levels",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"height",
")",
"]",
"for",
"node",
"in",
"self",
".",
"subtree",
":",
"ret",
"[",
"node",
".",
"level",
"-",
"self",
".",
"level",
... | Return a list of lists of nodes.
The outer list is indexed by the level.
Each inner list contains the nodes at that level,
in DFS order.
:rtype: list of lists of :class:`~aeneas.tree.Tree` | [
"Return",
"a",
"list",
"of",
"lists",
"of",
"nodes",
".",
"The",
"outer",
"list",
"is",
"indexed",
"by",
"the",
"level",
".",
"Each",
"inner",
"list",
"contains",
"the",
"nodes",
"at",
"that",
"level",
"in",
"DFS",
"order",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L397-L409 | train | 227,056 |
readbeyond/aeneas | aeneas/tree.py | Tree.level_at_index | def level_at_index(self, index):
"""
Return the list of nodes at level ``index``,
in DFS order.
:param int index: the index
:rtype: list of :class:`~aeneas.tree.Tree`
:raises: ValueError if the given ``index`` is not valid
"""
if not isinstance(index, int):
self.log_exc(u"Index is not an integer", None, True, TypeError)
levels = self.levels
if (index < 0) or (index >= len(levels)):
self.log_exc(u"The given level index '%d' is not valid" % (index), None, True, ValueError)
return self.levels[index] | python | def level_at_index(self, index):
"""
Return the list of nodes at level ``index``,
in DFS order.
:param int index: the index
:rtype: list of :class:`~aeneas.tree.Tree`
:raises: ValueError if the given ``index`` is not valid
"""
if not isinstance(index, int):
self.log_exc(u"Index is not an integer", None, True, TypeError)
levels = self.levels
if (index < 0) or (index >= len(levels)):
self.log_exc(u"The given level index '%d' is not valid" % (index), None, True, ValueError)
return self.levels[index] | [
"def",
"level_at_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Index is not an integer\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"levels",
"=",
"sel... | Return the list of nodes at level ``index``,
in DFS order.
:param int index: the index
:rtype: list of :class:`~aeneas.tree.Tree`
:raises: ValueError if the given ``index`` is not valid | [
"Return",
"the",
"list",
"of",
"nodes",
"at",
"level",
"index",
"in",
"DFS",
"order",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L425-L440 | train | 227,057 |
readbeyond/aeneas | aeneas/tree.py | Tree.ancestor | def ancestor(self, index):
"""
Return the ``index``-th ancestor.
The 0-th ancestor is the node itself,
the 1-th ancestor is its parent node,
etc.
:param int index: the number of levels to go up
:rtype: :class:`~aeneas.tree.Tree`
:raises: TypeError if ``index`` is not an int
:raises: ValueError if ``index`` is negative
"""
if not isinstance(index, int):
self.log_exc(u"index is not an integer", None, True, TypeError)
if index < 0:
self.log_exc(u"index cannot be negative", None, True, ValueError)
parent_node = self
for i in range(index):
if parent_node is None:
break
parent_node = parent_node.parent
return parent_node | python | def ancestor(self, index):
"""
Return the ``index``-th ancestor.
The 0-th ancestor is the node itself,
the 1-th ancestor is its parent node,
etc.
:param int index: the number of levels to go up
:rtype: :class:`~aeneas.tree.Tree`
:raises: TypeError if ``index`` is not an int
:raises: ValueError if ``index`` is negative
"""
if not isinstance(index, int):
self.log_exc(u"index is not an integer", None, True, TypeError)
if index < 0:
self.log_exc(u"index cannot be negative", None, True, ValueError)
parent_node = self
for i in range(index):
if parent_node is None:
break
parent_node = parent_node.parent
return parent_node | [
"def",
"ancestor",
"(",
"self",
",",
"index",
")",
":",
"if",
"not",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"index is not an integer\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"index",
"<",
"0"... | Return the ``index``-th ancestor.
The 0-th ancestor is the node itself,
the 1-th ancestor is its parent node,
etc.
:param int index: the number of levels to go up
:rtype: :class:`~aeneas.tree.Tree`
:raises: TypeError if ``index`` is not an int
:raises: ValueError if ``index`` is negative | [
"Return",
"the",
"index",
"-",
"th",
"ancestor",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L454-L476 | train | 227,058 |
readbeyond/aeneas | aeneas/tree.py | Tree.keep_levels | def keep_levels(self, level_indices):
"""
Rearrange the tree rooted at this node
to keep only the given levels.
The returned Tree will still be rooted
at the current node, i.e. this function
implicitly adds ``0`` to ``level_indices``.
If ``level_indices`` is an empty list,
only this node will be returned, with no children.
Elements of ``level_indices`` that do not
represent valid level indices (e.g., negative, or too large)
will be ignored and no error will be raised.
Important: this function modifies
the original tree in place!
:param list level_indices: the list of int, representing the levels to keep
:raises: TypeError if ``level_indices`` is not a list or if
it contains an element which is not an int
"""
if not isinstance(level_indices, list):
self.log_exc(u"level_indices is not an instance of list", None, True, TypeError)
for l in level_indices:
if not isinstance(l, int):
self.log_exc(u"level_indices contains an element not int", None, True, TypeError)
prev_levels = self.levels
level_indices = set(level_indices)
if 0 not in level_indices:
level_indices.add(0)
level_indices = level_indices & set(range(self.height))
level_indices = sorted(level_indices)[::-1]
# first, remove children
for l in level_indices:
for node in prev_levels[l]:
node.remove_children(reset_parent=False)
# then, connect to the right new parent
for i in range(len(level_indices) - 1):
l = level_indices[i]
for node in prev_levels[l]:
parent_node = node.ancestor(l - level_indices[i + 1])
parent_node.add_child(node) | python | def keep_levels(self, level_indices):
"""
Rearrange the tree rooted at this node
to keep only the given levels.
The returned Tree will still be rooted
at the current node, i.e. this function
implicitly adds ``0`` to ``level_indices``.
If ``level_indices`` is an empty list,
only this node will be returned, with no children.
Elements of ``level_indices`` that do not
represent valid level indices (e.g., negative, or too large)
will be ignored and no error will be raised.
Important: this function modifies
the original tree in place!
:param list level_indices: the list of int, representing the levels to keep
:raises: TypeError if ``level_indices`` is not a list or if
it contains an element which is not an int
"""
if not isinstance(level_indices, list):
self.log_exc(u"level_indices is not an instance of list", None, True, TypeError)
for l in level_indices:
if not isinstance(l, int):
self.log_exc(u"level_indices contains an element not int", None, True, TypeError)
prev_levels = self.levels
level_indices = set(level_indices)
if 0 not in level_indices:
level_indices.add(0)
level_indices = level_indices & set(range(self.height))
level_indices = sorted(level_indices)[::-1]
# first, remove children
for l in level_indices:
for node in prev_levels[l]:
node.remove_children(reset_parent=False)
# then, connect to the right new parent
for i in range(len(level_indices) - 1):
l = level_indices[i]
for node in prev_levels[l]:
parent_node = node.ancestor(l - level_indices[i + 1])
parent_node.add_child(node) | [
"def",
"keep_levels",
"(",
"self",
",",
"level_indices",
")",
":",
"if",
"not",
"isinstance",
"(",
"level_indices",
",",
"list",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"level_indices is not an instance of list\"",
",",
"None",
",",
"True",
",",
"TypeError",
... | Rearrange the tree rooted at this node
to keep only the given levels.
The returned Tree will still be rooted
at the current node, i.e. this function
implicitly adds ``0`` to ``level_indices``.
If ``level_indices`` is an empty list,
only this node will be returned, with no children.
Elements of ``level_indices`` that do not
represent valid level indices (e.g., negative, or too large)
will be ignored and no error will be raised.
Important: this function modifies
the original tree in place!
:param list level_indices: the list of int, representing the levels to keep
:raises: TypeError if ``level_indices`` is not a list or if
it contains an element which is not an int | [
"Rearrange",
"the",
"tree",
"rooted",
"at",
"this",
"node",
"to",
"keep",
"only",
"the",
"given",
"levels",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L478-L521 | train | 227,059 |
readbeyond/aeneas | thirdparty/mfcc.py | s2dctmat | def s2dctmat(nfilt,ncep,freqstep):
"""Return the 'legacy' not-quite-DCT matrix used by Sphinx"""
melcos = numpy.empty((ncep, nfilt), 'double')
for i in range(0,ncep):
freq = numpy.pi * float(i) / nfilt
melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double'))
melcos[:,0] = melcos[:,0] * 0.5
return melcos | python | def s2dctmat(nfilt,ncep,freqstep):
"""Return the 'legacy' not-quite-DCT matrix used by Sphinx"""
melcos = numpy.empty((ncep, nfilt), 'double')
for i in range(0,ncep):
freq = numpy.pi * float(i) / nfilt
melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double'))
melcos[:,0] = melcos[:,0] * 0.5
return melcos | [
"def",
"s2dctmat",
"(",
"nfilt",
",",
"ncep",
",",
"freqstep",
")",
":",
"melcos",
"=",
"numpy",
".",
"empty",
"(",
"(",
"ncep",
",",
"nfilt",
")",
",",
"'double'",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"ncep",
")",
":",
"freq",
"=",
"... | Return the 'legacy' not-quite-DCT matrix used by Sphinx | [
"Return",
"the",
"legacy",
"not",
"-",
"quite",
"-",
"DCT",
"matrix",
"used",
"by",
"Sphinx"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L146-L153 | train | 227,060 |
readbeyond/aeneas | thirdparty/mfcc.py | logspec2s2mfc | def logspec2s2mfc(logspec, ncep=13):
"""Convert log-power-spectrum bins to MFCC using the 'legacy'
Sphinx transform"""
nframes, nfilt = logspec.shape
melcos = s2dctmat(nfilt, ncep, 1./nfilt)
return numpy.dot(logspec, melcos.T) / nfilt | python | def logspec2s2mfc(logspec, ncep=13):
"""Convert log-power-spectrum bins to MFCC using the 'legacy'
Sphinx transform"""
nframes, nfilt = logspec.shape
melcos = s2dctmat(nfilt, ncep, 1./nfilt)
return numpy.dot(logspec, melcos.T) / nfilt | [
"def",
"logspec2s2mfc",
"(",
"logspec",
",",
"ncep",
"=",
"13",
")",
":",
"nframes",
",",
"nfilt",
"=",
"logspec",
".",
"shape",
"melcos",
"=",
"s2dctmat",
"(",
"nfilt",
",",
"ncep",
",",
"1.",
"/",
"nfilt",
")",
"return",
"numpy",
".",
"dot",
"(",
... | Convert log-power-spectrum bins to MFCC using the 'legacy'
Sphinx transform | [
"Convert",
"log",
"-",
"power",
"-",
"spectrum",
"bins",
"to",
"MFCC",
"using",
"the",
"legacy",
"Sphinx",
"transform"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L155-L160 | train | 227,061 |
readbeyond/aeneas | thirdparty/mfcc.py | dct | def dct(input, K=13):
"""Convert log-power-spectrum to MFCC using the orthogonal DCT-II"""
nframes, N = input.shape
freqstep = numpy.pi / N
cosmat = dctmat(N,K,freqstep)
return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N) | python | def dct(input, K=13):
"""Convert log-power-spectrum to MFCC using the orthogonal DCT-II"""
nframes, N = input.shape
freqstep = numpy.pi / N
cosmat = dctmat(N,K,freqstep)
return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N) | [
"def",
"dct",
"(",
"input",
",",
"K",
"=",
"13",
")",
":",
"nframes",
",",
"N",
"=",
"input",
".",
"shape",
"freqstep",
"=",
"numpy",
".",
"pi",
"/",
"N",
"cosmat",
"=",
"dctmat",
"(",
"N",
",",
"K",
",",
"freqstep",
")",
"return",
"numpy",
"."... | Convert log-power-spectrum to MFCC using the orthogonal DCT-II | [
"Convert",
"log",
"-",
"power",
"-",
"spectrum",
"to",
"MFCC",
"using",
"the",
"orthogonal",
"DCT",
"-",
"II"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L174-L179 | train | 227,062 |
readbeyond/aeneas | thirdparty/mfcc.py | dct2 | def dct2(input, K=13):
"""Convert log-power-spectrum to MFCC using the normalized DCT-II"""
nframes, N = input.shape
freqstep = numpy.pi / N
cosmat = dctmat(N,K,freqstep,False)
return numpy.dot(input, cosmat) * (2.0 / N) | python | def dct2(input, K=13):
"""Convert log-power-spectrum to MFCC using the normalized DCT-II"""
nframes, N = input.shape
freqstep = numpy.pi / N
cosmat = dctmat(N,K,freqstep,False)
return numpy.dot(input, cosmat) * (2.0 / N) | [
"def",
"dct2",
"(",
"input",
",",
"K",
"=",
"13",
")",
":",
"nframes",
",",
"N",
"=",
"input",
".",
"shape",
"freqstep",
"=",
"numpy",
".",
"pi",
"/",
"N",
"cosmat",
"=",
"dctmat",
"(",
"N",
",",
"K",
",",
"freqstep",
",",
"False",
")",
"return... | Convert log-power-spectrum to MFCC using the normalized DCT-II | [
"Convert",
"log",
"-",
"power",
"-",
"spectrum",
"to",
"MFCC",
"using",
"the",
"normalized",
"DCT",
"-",
"II"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L181-L186 | train | 227,063 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.read_properties | def read_properties(self):
"""
Populate this object by reading
the audio properties of the file at the given path.
Currently this function uses
:class:`~aeneas.ffprobewrapper.FFPROBEWrapper`
to get the audio file properties.
:raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read
"""
self.log(u"Reading properties...")
# check the file can be read
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
# get the file size
self.log([u"Getting file size for '%s'", self.file_path])
self.file_size = gf.file_size(self.file_path)
self.log([u"File size for '%s' is '%d'", self.file_path, self.file_size])
# get the audio properties using FFPROBEWrapper
try:
self.log(u"Reading properties with FFPROBEWrapper...")
properties = FFPROBEWrapper(
rconf=self.rconf,
logger=self.logger
).read_properties(self.file_path)
self.log(u"Reading properties with FFPROBEWrapper... done")
except FFPROBEPathError:
self.log_exc(u"Unable to call ffprobe executable", None, True, AudioFileProbeError)
except (FFPROBEUnsupportedFormatError, FFPROBEParsingError):
self.log_exc(u"Audio file format not supported by ffprobe", None, True, AudioFileUnsupportedFormatError)
# save relevant properties in results inside the audiofile object
self.audio_length = TimeValue(properties[FFPROBEWrapper.STDOUT_DURATION])
self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS])
self.log([u"Stored audio_length: '%s'", self.audio_length])
self.log([u"Stored audio_format: '%s'", self.audio_format])
self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate])
self.log([u"Stored audio_channels: '%s'", self.audio_channels])
self.log(u"Reading properties... done") | python | def read_properties(self):
"""
Populate this object by reading
the audio properties of the file at the given path.
Currently this function uses
:class:`~aeneas.ffprobewrapper.FFPROBEWrapper`
to get the audio file properties.
:raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read
"""
self.log(u"Reading properties...")
# check the file can be read
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
# get the file size
self.log([u"Getting file size for '%s'", self.file_path])
self.file_size = gf.file_size(self.file_path)
self.log([u"File size for '%s' is '%d'", self.file_path, self.file_size])
# get the audio properties using FFPROBEWrapper
try:
self.log(u"Reading properties with FFPROBEWrapper...")
properties = FFPROBEWrapper(
rconf=self.rconf,
logger=self.logger
).read_properties(self.file_path)
self.log(u"Reading properties with FFPROBEWrapper... done")
except FFPROBEPathError:
self.log_exc(u"Unable to call ffprobe executable", None, True, AudioFileProbeError)
except (FFPROBEUnsupportedFormatError, FFPROBEParsingError):
self.log_exc(u"Audio file format not supported by ffprobe", None, True, AudioFileUnsupportedFormatError)
# save relevant properties in results inside the audiofile object
self.audio_length = TimeValue(properties[FFPROBEWrapper.STDOUT_DURATION])
self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS])
self.log([u"Stored audio_length: '%s'", self.audio_length])
self.log([u"Stored audio_format: '%s'", self.audio_format])
self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate])
self.log([u"Stored audio_channels: '%s'", self.audio_channels])
self.log(u"Reading properties... done") | [
"def",
"read_properties",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Reading properties...\"",
")",
"# check the file can be read",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"self",
".",
"file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"F... | Populate this object by reading
the audio properties of the file at the given path.
Currently this function uses
:class:`~aeneas.ffprobewrapper.FFPROBEWrapper`
to get the audio file properties.
:raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read | [
"Populate",
"this",
"object",
"by",
"reading",
"the",
"audio",
"properties",
"of",
"the",
"file",
"at",
"the",
"given",
"path",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L330-L376 | train | 227,064 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.read_samples_from_file | def read_samples_from_file(self):
"""
Load the audio samples from file into memory.
If ``self.file_format`` is ``None`` or it is not
``("pcm_s16le", 1, self.rconf.sample_rate)``,
the file will be first converted
to a temporary PCM16 mono WAVE file.
Audio data will be read from this temporary file,
which will be then deleted from disk immediately.
Otherwise,
the audio data will be read directly
from the given file,
which will not be deleted from disk.
:raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read
"""
self.log(u"Loading audio data...")
# check the file can be read
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
# determine if we need to convert the audio file
convert_audio_file = (
(self.file_format is None) or
(
(self.rconf.safety_checks) and
(self.file_format != ("pcm_s16le", 1, self.rconf.sample_rate))
)
)
# convert the audio file if needed
if convert_audio_file:
# convert file to PCM16 mono WAVE with correct sample rate
self.log(u"self.file_format is None or not good => converting self.file_path")
tmp_handler, tmp_file_path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
self.log([u"Temporary PCM16 mono WAVE file: '%s'", tmp_file_path])
try:
self.log(u"Converting audio file to mono...")
converter = FFMPEGWrapper(rconf=self.rconf, logger=self.logger)
converter.convert(self.file_path, tmp_file_path)
self.file_format = ("pcm_s16le", 1, self.rconf.sample_rate)
self.log(u"Converting audio file to mono... done")
except FFMPEGPathError:
gf.delete_file(tmp_handler, tmp_file_path)
self.log_exc(u"Unable to call ffmpeg executable", None, True, AudioFileConverterError)
except OSError:
gf.delete_file(tmp_handler, tmp_file_path)
self.log_exc(u"Audio file format not supported by ffmpeg", None, True, AudioFileUnsupportedFormatError)
else:
# read the file directly
if self.rconf.safety_checks:
self.log(u"self.file_format is good => reading self.file_path directly")
else:
self.log_warn(u"Safety checks disabled => reading self.file_path directly")
tmp_handler = None
tmp_file_path = self.file_path
# TODO allow calling C extension cwave to read samples faster
try:
self.audio_format = "pcm16"
self.audio_channels = 1
self.audio_sample_rate, self.__samples = scipywavread(tmp_file_path)
# scipy reads a sample as an int16_t, that is, a number in [-32768, 32767]
# so we convert it to a float64 in [-1, 1]
self.__samples = self.__samples.astype("float64") / 32768
self.__samples_capacity = len(self.__samples)
self.__samples_length = self.__samples_capacity
self._update_length()
except ValueError:
self.log_exc(u"Audio format not supported by scipywavread", None, True, AudioFileUnsupportedFormatError)
# if we converted the audio file, delete the temporary converted audio file
if convert_audio_file:
gf.delete_file(tmp_handler, tmp_file_path)
self.log([u"Deleted temporary audio file: '%s'", tmp_file_path])
self._update_length()
self.log([u"Sample length: %.3f", self.audio_length])
self.log([u"Sample rate: %d", self.audio_sample_rate])
self.log([u"Audio format: %s", self.audio_format])
self.log([u"Audio channels: %d", self.audio_channels])
self.log(u"Loading audio data... done") | python | def read_samples_from_file(self):
"""
Load the audio samples from file into memory.
If ``self.file_format`` is ``None`` or it is not
``("pcm_s16le", 1, self.rconf.sample_rate)``,
the file will be first converted
to a temporary PCM16 mono WAVE file.
Audio data will be read from this temporary file,
which will be then deleted from disk immediately.
Otherwise,
the audio data will be read directly
from the given file,
which will not be deleted from disk.
:raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read
"""
self.log(u"Loading audio data...")
# check the file can be read
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
# determine if we need to convert the audio file
convert_audio_file = (
(self.file_format is None) or
(
(self.rconf.safety_checks) and
(self.file_format != ("pcm_s16le", 1, self.rconf.sample_rate))
)
)
# convert the audio file if needed
if convert_audio_file:
# convert file to PCM16 mono WAVE with correct sample rate
self.log(u"self.file_format is None or not good => converting self.file_path")
tmp_handler, tmp_file_path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
self.log([u"Temporary PCM16 mono WAVE file: '%s'", tmp_file_path])
try:
self.log(u"Converting audio file to mono...")
converter = FFMPEGWrapper(rconf=self.rconf, logger=self.logger)
converter.convert(self.file_path, tmp_file_path)
self.file_format = ("pcm_s16le", 1, self.rconf.sample_rate)
self.log(u"Converting audio file to mono... done")
except FFMPEGPathError:
gf.delete_file(tmp_handler, tmp_file_path)
self.log_exc(u"Unable to call ffmpeg executable", None, True, AudioFileConverterError)
except OSError:
gf.delete_file(tmp_handler, tmp_file_path)
self.log_exc(u"Audio file format not supported by ffmpeg", None, True, AudioFileUnsupportedFormatError)
else:
# read the file directly
if self.rconf.safety_checks:
self.log(u"self.file_format is good => reading self.file_path directly")
else:
self.log_warn(u"Safety checks disabled => reading self.file_path directly")
tmp_handler = None
tmp_file_path = self.file_path
# TODO allow calling C extension cwave to read samples faster
try:
self.audio_format = "pcm16"
self.audio_channels = 1
self.audio_sample_rate, self.__samples = scipywavread(tmp_file_path)
# scipy reads a sample as an int16_t, that is, a number in [-32768, 32767]
# so we convert it to a float64 in [-1, 1]
self.__samples = self.__samples.astype("float64") / 32768
self.__samples_capacity = len(self.__samples)
self.__samples_length = self.__samples_capacity
self._update_length()
except ValueError:
self.log_exc(u"Audio format not supported by scipywavread", None, True, AudioFileUnsupportedFormatError)
# if we converted the audio file, delete the temporary converted audio file
if convert_audio_file:
gf.delete_file(tmp_handler, tmp_file_path)
self.log([u"Deleted temporary audio file: '%s'", tmp_file_path])
self._update_length()
self.log([u"Sample length: %.3f", self.audio_length])
self.log([u"Sample rate: %d", self.audio_sample_rate])
self.log([u"Audio format: %s", self.audio_format])
self.log([u"Audio channels: %d", self.audio_channels])
self.log(u"Loading audio data... done") | [
"def",
"read_samples_from_file",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Loading audio data...\"",
")",
"# check the file can be read",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"self",
".",
"file_path",
")",
":",
"self",
".",
"log_exc",
"(",
... | Load the audio samples from file into memory.
If ``self.file_format`` is ``None`` or it is not
``("pcm_s16le", 1, self.rconf.sample_rate)``,
the file will be first converted
to a temporary PCM16 mono WAVE file.
Audio data will be read from this temporary file,
which will be then deleted from disk immediately.
Otherwise,
the audio data will be read directly
from the given file,
which will not be deleted from disk.
:raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
:raises: OSError: if the audio file cannot be read | [
"Load",
"the",
"audio",
"samples",
"from",
"file",
"into",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L378-L464 | train | 227,065 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.preallocate_memory | def preallocate_memory(self, capacity):
"""
Preallocate memory to store audio samples,
to avoid repeated new allocations and copies
while performing several consecutive append operations.
If ``self.__samples`` is not initialized,
it will become an array of ``capacity`` zeros.
If ``capacity`` is larger than the current capacity,
the current ``self.__samples`` will be extended with zeros.
If ``capacity`` is smaller than the current capacity,
the first ``capacity`` values of ``self.__samples``
will be retained.
:param int capacity: the new capacity, in number of samples
:raises: ValueError: if ``capacity`` is negative
.. versionadded:: 1.5.0
"""
if capacity < 0:
raise ValueError(u"The capacity value cannot be negative")
if self.__samples is None:
self.log(u"Not initialized")
self.__samples = numpy.zeros(capacity)
self.__samples_length = 0
else:
self.log([u"Previous sample length was (samples): %d", self.__samples_length])
self.log([u"Previous sample capacity was (samples): %d", self.__samples_capacity])
self.__samples = numpy.resize(self.__samples, capacity)
self.__samples_length = min(self.__samples_length, capacity)
self.__samples_capacity = capacity
self.log([u"Current sample capacity is (samples): %d", self.__samples_capacity]) | python | def preallocate_memory(self, capacity):
"""
Preallocate memory to store audio samples,
to avoid repeated new allocations and copies
while performing several consecutive append operations.
If ``self.__samples`` is not initialized,
it will become an array of ``capacity`` zeros.
If ``capacity`` is larger than the current capacity,
the current ``self.__samples`` will be extended with zeros.
If ``capacity`` is smaller than the current capacity,
the first ``capacity`` values of ``self.__samples``
will be retained.
:param int capacity: the new capacity, in number of samples
:raises: ValueError: if ``capacity`` is negative
.. versionadded:: 1.5.0
"""
if capacity < 0:
raise ValueError(u"The capacity value cannot be negative")
if self.__samples is None:
self.log(u"Not initialized")
self.__samples = numpy.zeros(capacity)
self.__samples_length = 0
else:
self.log([u"Previous sample length was (samples): %d", self.__samples_length])
self.log([u"Previous sample capacity was (samples): %d", self.__samples_capacity])
self.__samples = numpy.resize(self.__samples, capacity)
self.__samples_length = min(self.__samples_length, capacity)
self.__samples_capacity = capacity
self.log([u"Current sample capacity is (samples): %d", self.__samples_capacity]) | [
"def",
"preallocate_memory",
"(",
"self",
",",
"capacity",
")",
":",
"if",
"capacity",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"u\"The capacity value cannot be negative\"",
")",
"if",
"self",
".",
"__samples",
"is",
"None",
":",
"self",
".",
"log",
"(",
"... | Preallocate memory to store audio samples,
to avoid repeated new allocations and copies
while performing several consecutive append operations.
If ``self.__samples`` is not initialized,
it will become an array of ``capacity`` zeros.
If ``capacity`` is larger than the current capacity,
the current ``self.__samples`` will be extended with zeros.
If ``capacity`` is smaller than the current capacity,
the first ``capacity`` values of ``self.__samples``
will be retained.
:param int capacity: the new capacity, in number of samples
:raises: ValueError: if ``capacity`` is negative
.. versionadded:: 1.5.0 | [
"Preallocate",
"memory",
"to",
"store",
"audio",
"samples",
"to",
"avoid",
"repeated",
"new",
"allocations",
"and",
"copies",
"while",
"performing",
"several",
"consecutive",
"append",
"operations",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L466-L499 | train | 227,066 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.minimize_memory | def minimize_memory(self):
"""
Reduce the allocated memory to the minimum
required to store the current audio samples.
This function is meant to be called
when building a wave incrementally,
after the last append operation.
.. versionadded:: 1.5.0
"""
if self.__samples is None:
self.log(u"Not initialized, returning")
else:
self.log(u"Initialized, minimizing memory...")
self.preallocate_memory(self.__samples_length)
self.log(u"Initialized, minimizing memory... done") | python | def minimize_memory(self):
"""
Reduce the allocated memory to the minimum
required to store the current audio samples.
This function is meant to be called
when building a wave incrementally,
after the last append operation.
.. versionadded:: 1.5.0
"""
if self.__samples is None:
self.log(u"Not initialized, returning")
else:
self.log(u"Initialized, minimizing memory...")
self.preallocate_memory(self.__samples_length)
self.log(u"Initialized, minimizing memory... done") | [
"def",
"minimize_memory",
"(",
"self",
")",
":",
"if",
"self",
".",
"__samples",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Not initialized, returning\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Initialized, minimizing memory...\"",
")",
"self",
".... | Reduce the allocated memory to the minimum
required to store the current audio samples.
This function is meant to be called
when building a wave incrementally,
after the last append operation.
.. versionadded:: 1.5.0 | [
"Reduce",
"the",
"allocated",
"memory",
"to",
"the",
"minimum",
"required",
"to",
"store",
"the",
"current",
"audio",
"samples",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L501-L517 | train | 227,067 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.add_samples | def add_samples(self, samples, reverse=False):
"""
Concatenate the given new samples to the current audio data.
This function initializes the memory if no audio data
is present already.
If ``reverse`` is ``True``, the new samples
will be reversed and then concatenated.
:param samples: the new samples to be concatenated
:type samples: :class:`numpy.ndarray` (1D)
:param bool reverse: if ``True``, concatenate new samples after reversing them
.. versionadded:: 1.2.1
"""
self.log(u"Adding samples...")
samples_length = len(samples)
current_length = self.__samples_length
future_length = current_length + samples_length
if (self.__samples is None) or (self.__samples_capacity < future_length):
self.preallocate_memory(2 * future_length)
if reverse:
self.__samples[current_length:future_length] = samples[::-1]
else:
self.__samples[current_length:future_length] = samples[:]
self.__samples_length = future_length
self._update_length()
self.log(u"Adding samples... done") | python | def add_samples(self, samples, reverse=False):
"""
Concatenate the given new samples to the current audio data.
This function initializes the memory if no audio data
is present already.
If ``reverse`` is ``True``, the new samples
will be reversed and then concatenated.
:param samples: the new samples to be concatenated
:type samples: :class:`numpy.ndarray` (1D)
:param bool reverse: if ``True``, concatenate new samples after reversing them
.. versionadded:: 1.2.1
"""
self.log(u"Adding samples...")
samples_length = len(samples)
current_length = self.__samples_length
future_length = current_length + samples_length
if (self.__samples is None) or (self.__samples_capacity < future_length):
self.preallocate_memory(2 * future_length)
if reverse:
self.__samples[current_length:future_length] = samples[::-1]
else:
self.__samples[current_length:future_length] = samples[:]
self.__samples_length = future_length
self._update_length()
self.log(u"Adding samples... done") | [
"def",
"add_samples",
"(",
"self",
",",
"samples",
",",
"reverse",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Adding samples...\"",
")",
"samples_length",
"=",
"len",
"(",
"samples",
")",
"current_length",
"=",
"self",
".",
"__samples_length",
"fut... | Concatenate the given new samples to the current audio data.
This function initializes the memory if no audio data
is present already.
If ``reverse`` is ``True``, the new samples
will be reversed and then concatenated.
:param samples: the new samples to be concatenated
:type samples: :class:`numpy.ndarray` (1D)
:param bool reverse: if ``True``, concatenate new samples after reversing them
.. versionadded:: 1.2.1 | [
"Concatenate",
"the",
"given",
"new",
"samples",
"to",
"the",
"current",
"audio",
"data",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L519-L547 | train | 227,068 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.reverse | def reverse(self):
"""
Reverse the audio data.
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0
"""
if self.__samples is None:
if self.file_path is None:
self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError)
else:
self.read_samples_from_file()
self.log(u"Reversing...")
self.__samples[0:self.__samples_length] = numpy.flipud(self.__samples[0:self.__samples_length])
self.log(u"Reversing... done") | python | def reverse(self):
"""
Reverse the audio data.
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0
"""
if self.__samples is None:
if self.file_path is None:
self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError)
else:
self.read_samples_from_file()
self.log(u"Reversing...")
self.__samples[0:self.__samples_length] = numpy.flipud(self.__samples[0:self.__samples_length])
self.log(u"Reversing... done") | [
"def",
"reverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"__samples",
"is",
"None",
":",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"AudioFile object not initialized\"",
",",
"None",
",",
"True",
",",
"AudioFileNo... | Reverse the audio data.
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0 | [
"Reverse",
"the",
"audio",
"data",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L549-L564 | train | 227,069 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.trim | def trim(self, begin=None, length=None):
"""
Get a slice of the audio data of ``length`` seconds,
starting from ``begin`` seconds.
If audio data is not loaded, load it and then slice it.
:param begin: the start position, in seconds
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param length: the position, in seconds
:type length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.2.0
"""
for variable, name in [(begin, "begin"), (length, "length")]:
if (variable is not None) and (not isinstance(variable, TimeValue)):
raise TypeError(u"%s is not None or TimeValue" % name)
self.log(u"Trimming...")
if (begin is None) and (length is None):
self.log(u"begin and length are both None: nothing to do")
else:
if begin is None:
begin = TimeValue("0.000")
self.log([u"begin was None, now set to %.3f", begin])
begin = min(max(TimeValue("0.000"), begin), self.audio_length)
self.log([u"begin is %.3f", begin])
if length is None:
length = self.audio_length - begin
self.log([u"length was None, now set to %.3f", length])
length = min(max(TimeValue("0.000"), length), self.audio_length - begin)
self.log([u"length is %.3f", length])
begin_index = int(begin * self.audio_sample_rate)
end_index = int((begin + length) * self.audio_sample_rate)
new_idx = end_index - begin_index
self.__samples[0:new_idx] = self.__samples[begin_index:end_index]
self.__samples_length = new_idx
self._update_length()
self.log(u"Trimming... done") | python | def trim(self, begin=None, length=None):
"""
Get a slice of the audio data of ``length`` seconds,
starting from ``begin`` seconds.
If audio data is not loaded, load it and then slice it.
:param begin: the start position, in seconds
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param length: the position, in seconds
:type length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.2.0
"""
for variable, name in [(begin, "begin"), (length, "length")]:
if (variable is not None) and (not isinstance(variable, TimeValue)):
raise TypeError(u"%s is not None or TimeValue" % name)
self.log(u"Trimming...")
if (begin is None) and (length is None):
self.log(u"begin and length are both None: nothing to do")
else:
if begin is None:
begin = TimeValue("0.000")
self.log([u"begin was None, now set to %.3f", begin])
begin = min(max(TimeValue("0.000"), begin), self.audio_length)
self.log([u"begin is %.3f", begin])
if length is None:
length = self.audio_length - begin
self.log([u"length was None, now set to %.3f", length])
length = min(max(TimeValue("0.000"), length), self.audio_length - begin)
self.log([u"length is %.3f", length])
begin_index = int(begin * self.audio_sample_rate)
end_index = int((begin + length) * self.audio_sample_rate)
new_idx = end_index - begin_index
self.__samples[0:new_idx] = self.__samples[begin_index:end_index]
self.__samples_length = new_idx
self._update_length()
self.log(u"Trimming... done") | [
"def",
"trim",
"(",
"self",
",",
"begin",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"for",
"variable",
",",
"name",
"in",
"[",
"(",
"begin",
",",
"\"begin\"",
")",
",",
"(",
"length",
",",
"\"length\"",
")",
"]",
":",
"if",
"(",
"variabl... | Get a slice of the audio data of ``length`` seconds,
starting from ``begin`` seconds.
If audio data is not loaded, load it and then slice it.
:param begin: the start position, in seconds
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param length: the position, in seconds
:type length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.2.0 | [
"Get",
"a",
"slice",
"of",
"the",
"audio",
"data",
"of",
"length",
"seconds",
"starting",
"from",
"begin",
"seconds",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L566-L605 | train | 227,070 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.write | def write(self, file_path):
"""
Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0
"""
if self.__samples is None:
if self.file_path is None:
self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError)
else:
self.read_samples_from_file()
self.log([u"Writing audio file '%s'...", file_path])
try:
# our value is a float64 in [-1, 1]
# scipy writes the sample as an int16_t, that is, a number in [-32768, 32767]
data = (self.audio_samples * 32768).astype("int16")
scipywavwrite(file_path, self.audio_sample_rate, data)
except Exception as exc:
self.log_exc(u"Error writing audio file to '%s'" % (file_path), exc, True, OSError)
self.log([u"Writing audio file '%s'... done", file_path]) | python | def write(self, file_path):
"""
Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0
"""
if self.__samples is None:
if self.file_path is None:
self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError)
else:
self.read_samples_from_file()
self.log([u"Writing audio file '%s'...", file_path])
try:
# our value is a float64 in [-1, 1]
# scipy writes the sample as an int16_t, that is, a number in [-32768, 32767]
data = (self.audio_samples * 32768).astype("int16")
scipywavwrite(file_path, self.audio_sample_rate, data)
except Exception as exc:
self.log_exc(u"Error writing audio file to '%s'" % (file_path), exc, True, OSError)
self.log([u"Writing audio file '%s'... done", file_path]) | [
"def",
"write",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"self",
".",
"__samples",
"is",
"None",
":",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"AudioFile object not initialized\"",
",",
"None",
",",
"True",
... | Write the audio data to file.
Return ``True`` on success, or ``False`` otherwise.
:param string file_path: the path of the output file to be written
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0 | [
"Write",
"the",
"audio",
"data",
"to",
"file",
".",
"Return",
"True",
"on",
"success",
"or",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L607-L630 | train | 227,071 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile.clear_data | def clear_data(self):
"""
Clear the audio data, freeing memory.
"""
self.log(u"Clear audio_data")
self.__samples_capacity = 0
self.__samples_length = 0
self.__samples = None | python | def clear_data(self):
"""
Clear the audio data, freeing memory.
"""
self.log(u"Clear audio_data")
self.__samples_capacity = 0
self.__samples_length = 0
self.__samples = None | [
"def",
"clear_data",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Clear audio_data\"",
")",
"self",
".",
"__samples_capacity",
"=",
"0",
"self",
".",
"__samples_length",
"=",
"0",
"self",
".",
"__samples",
"=",
"None"
] | Clear the audio data, freeing memory. | [
"Clear",
"the",
"audio",
"data",
"freeing",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L632-L639 | train | 227,072 |
readbeyond/aeneas | aeneas/audiofile.py | AudioFile._update_length | def _update_length(self):
"""
Update the audio length property,
according to the length of the current audio data
and audio sample rate.
This function fails silently if one of the two is ``None``.
"""
if (self.audio_sample_rate is not None) and (self.__samples is not None):
# NOTE computing TimeValue (... / ...) yields wrong results,
# see issue #168
# self.audio_length = TimeValue(self.__samples_length / self.audio_sample_rate)
self.audio_length = TimeValue(self.__samples_length) / TimeValue(self.audio_sample_rate) | python | def _update_length(self):
"""
Update the audio length property,
according to the length of the current audio data
and audio sample rate.
This function fails silently if one of the two is ``None``.
"""
if (self.audio_sample_rate is not None) and (self.__samples is not None):
# NOTE computing TimeValue (... / ...) yields wrong results,
# see issue #168
# self.audio_length = TimeValue(self.__samples_length / self.audio_sample_rate)
self.audio_length = TimeValue(self.__samples_length) / TimeValue(self.audio_sample_rate) | [
"def",
"_update_length",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"audio_sample_rate",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"__samples",
"is",
"not",
"None",
")",
":",
"# NOTE computing TimeValue (... / ...) yields wrong results,",
"# see ... | Update the audio length property,
according to the length of the current audio data
and audio sample rate.
This function fails silently if one of the two is ``None``. | [
"Update",
"the",
"audio",
"length",
"property",
"according",
"to",
"the",
"length",
"of",
"the",
"current",
"audio",
"data",
"and",
"audio",
"sample",
"rate",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L641-L653 | train | 227,073 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.masked_middle_mfcc | def masked_middle_mfcc(self):
"""
Return the MFCC speech frames
in the MIDDLE portion of the wave.
:rtype: :class:`numpy.ndarray` (2D)
"""
begin, end = self._masked_middle_begin_end()
return (self.masked_mfcc)[:, begin:end] | python | def masked_middle_mfcc(self):
"""
Return the MFCC speech frames
in the MIDDLE portion of the wave.
:rtype: :class:`numpy.ndarray` (2D)
"""
begin, end = self._masked_middle_begin_end()
return (self.masked_mfcc)[:, begin:end] | [
"def",
"masked_middle_mfcc",
"(",
"self",
")",
":",
"begin",
",",
"end",
"=",
"self",
".",
"_masked_middle_begin_end",
"(",
")",
"return",
"(",
"self",
".",
"masked_mfcc",
")",
"[",
":",
",",
"begin",
":",
"end",
"]"
] | Return the MFCC speech frames
in the MIDDLE portion of the wave.
:rtype: :class:`numpy.ndarray` (2D) | [
"Return",
"the",
"MFCC",
"speech",
"frames",
"in",
"the",
"MIDDLE",
"portion",
"of",
"the",
"wave",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L327-L335 | train | 227,074 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.masked_middle_map | def masked_middle_map(self):
"""
Return the map
from the MFCC speech frame indices
in the MIDDLE portion of the wave
to the MFCC FULL frame indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
begin, end = self._masked_middle_begin_end()
return self.__mfcc_mask_map[begin:end] | python | def masked_middle_map(self):
"""
Return the map
from the MFCC speech frame indices
in the MIDDLE portion of the wave
to the MFCC FULL frame indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
begin, end = self._masked_middle_begin_end()
return self.__mfcc_mask_map[begin:end] | [
"def",
"masked_middle_map",
"(",
"self",
")",
":",
"begin",
",",
"end",
"=",
"self",
".",
"_masked_middle_begin_end",
"(",
")",
"return",
"self",
".",
"__mfcc_mask_map",
"[",
"begin",
":",
"end",
"]"
] | Return the map
from the MFCC speech frame indices
in the MIDDLE portion of the wave
to the MFCC FULL frame indices.
:rtype: :class:`numpy.ndarray` (1D) | [
"Return",
"the",
"map",
"from",
"the",
"MFCC",
"speech",
"frame",
"indices",
"in",
"the",
"MIDDLE",
"portion",
"of",
"the",
"wave",
"to",
"the",
"MFCC",
"FULL",
"frame",
"indices",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L349-L359 | train | 227,075 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC._binary_search_intervals | def _binary_search_intervals(cls, intervals, index):
"""
Binary search for the interval containing index,
assuming there is such an interval.
This function should never return ``None``.
"""
start = 0
end = len(intervals) - 1
while start <= end:
middle_index = start + ((end - start) // 2)
middle = intervals[middle_index]
if (middle[0] <= index) and (index < middle[1]):
return middle
elif middle[0] > index:
end = middle_index - 1
else:
start = middle_index + 1
return None | python | def _binary_search_intervals(cls, intervals, index):
"""
Binary search for the interval containing index,
assuming there is such an interval.
This function should never return ``None``.
"""
start = 0
end = len(intervals) - 1
while start <= end:
middle_index = start + ((end - start) // 2)
middle = intervals[middle_index]
if (middle[0] <= index) and (index < middle[1]):
return middle
elif middle[0] > index:
end = middle_index - 1
else:
start = middle_index + 1
return None | [
"def",
"_binary_search_intervals",
"(",
"cls",
",",
"intervals",
",",
"index",
")",
":",
"start",
"=",
"0",
"end",
"=",
"len",
"(",
"intervals",
")",
"-",
"1",
"while",
"start",
"<=",
"end",
":",
"middle_index",
"=",
"start",
"+",
"(",
"(",
"end",
"-... | Binary search for the interval containing index,
assuming there is such an interval.
This function should never return ``None``. | [
"Binary",
"search",
"for",
"the",
"interval",
"containing",
"index",
"assuming",
"there",
"is",
"such",
"an",
"interval",
".",
"This",
"function",
"should",
"never",
"return",
"None",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L423-L440 | train | 227,076 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.middle_begin | def middle_begin(self, index):
"""
Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin
"""
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_begin = index | python | def middle_begin(self, index):
"""
Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin
"""
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_begin = index | [
"def",
"middle_begin",
"(",
"self",
",",
"index",
")",
":",
"if",
"(",
"index",
"<",
"0",
")",
"or",
"(",
"index",
">",
"self",
".",
"all_length",
")",
":",
"raise",
"ValueError",
"(",
"u\"The given index is not valid\"",
")",
"self",
".",
"__middle_begin"... | Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin | [
"Set",
"the",
"index",
"where",
"MIDDLE",
"starts",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L452-L460 | train | 227,077 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC._compute_mfcc_c_extension | def _compute_mfcc_c_extension(self):
"""
Compute MFCCs using the Python C extension cmfcc.
"""
self.log(u"Computing MFCCs using C extension...")
try:
self.log(u"Importing cmfcc...")
import aeneas.cmfcc.cmfcc
self.log(u"Importing cmfcc... done")
self.__mfcc = (aeneas.cmfcc.cmfcc.compute_from_data(
self.audio_file.audio_samples,
self.audio_file.audio_sample_rate,
self.rconf[RuntimeConfiguration.MFCC_FILTERS],
self.rconf[RuntimeConfiguration.MFCC_SIZE],
self.rconf[RuntimeConfiguration.MFCC_FFT_ORDER],
self.rconf[RuntimeConfiguration.MFCC_LOWER_FREQUENCY],
self.rconf[RuntimeConfiguration.MFCC_UPPER_FREQUENCY],
self.rconf[RuntimeConfiguration.MFCC_EMPHASIS_FACTOR],
self.rconf[RuntimeConfiguration.MFCC_WINDOW_LENGTH],
self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT]
)[0]).transpose()
self.log(u"Computing MFCCs using C extension... done")
return (True, None)
except Exception as exc:
self.log_exc(u"An unexpected error occurred while running cmfcc", exc, False, None)
return (False, None) | python | def _compute_mfcc_c_extension(self):
"""
Compute MFCCs using the Python C extension cmfcc.
"""
self.log(u"Computing MFCCs using C extension...")
try:
self.log(u"Importing cmfcc...")
import aeneas.cmfcc.cmfcc
self.log(u"Importing cmfcc... done")
self.__mfcc = (aeneas.cmfcc.cmfcc.compute_from_data(
self.audio_file.audio_samples,
self.audio_file.audio_sample_rate,
self.rconf[RuntimeConfiguration.MFCC_FILTERS],
self.rconf[RuntimeConfiguration.MFCC_SIZE],
self.rconf[RuntimeConfiguration.MFCC_FFT_ORDER],
self.rconf[RuntimeConfiguration.MFCC_LOWER_FREQUENCY],
self.rconf[RuntimeConfiguration.MFCC_UPPER_FREQUENCY],
self.rconf[RuntimeConfiguration.MFCC_EMPHASIS_FACTOR],
self.rconf[RuntimeConfiguration.MFCC_WINDOW_LENGTH],
self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT]
)[0]).transpose()
self.log(u"Computing MFCCs using C extension... done")
return (True, None)
except Exception as exc:
self.log_exc(u"An unexpected error occurred while running cmfcc", exc, False, None)
return (False, None) | [
"def",
"_compute_mfcc_c_extension",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Computing MFCCs using C extension...\"",
")",
"try",
":",
"self",
".",
"log",
"(",
"u\"Importing cmfcc...\"",
")",
"import",
"aeneas",
".",
"cmfcc",
".",
"cmfcc",
"self",
"."... | Compute MFCCs using the Python C extension cmfcc. | [
"Compute",
"MFCCs",
"using",
"the",
"Python",
"C",
"extension",
"cmfcc",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L509-L534 | train | 227,078 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC._compute_mfcc_pure_python | def _compute_mfcc_pure_python(self):
"""
Compute MFCCs using the pure Python code.
"""
self.log(u"Computing MFCCs using pure Python code...")
try:
self.__mfcc = MFCC(
rconf=self.rconf,
logger=self.logger
).compute_from_data(
self.audio_file.audio_samples,
self.audio_file.audio_sample_rate
).transpose()
self.log(u"Computing MFCCs using pure Python code... done")
return (True, None)
except Exception as exc:
self.log_exc(u"An unexpected error occurred while running pure Python code", exc, False, None)
return (False, None) | python | def _compute_mfcc_pure_python(self):
"""
Compute MFCCs using the pure Python code.
"""
self.log(u"Computing MFCCs using pure Python code...")
try:
self.__mfcc = MFCC(
rconf=self.rconf,
logger=self.logger
).compute_from_data(
self.audio_file.audio_samples,
self.audio_file.audio_sample_rate
).transpose()
self.log(u"Computing MFCCs using pure Python code... done")
return (True, None)
except Exception as exc:
self.log_exc(u"An unexpected error occurred while running pure Python code", exc, False, None)
return (False, None) | [
"def",
"_compute_mfcc_pure_python",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Computing MFCCs using pure Python code...\"",
")",
"try",
":",
"self",
".",
"__mfcc",
"=",
"MFCC",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".... | Compute MFCCs using the pure Python code. | [
"Compute",
"MFCCs",
"using",
"the",
"pure",
"Python",
"code",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L536-L553 | train | 227,079 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.reverse | def reverse(self):
"""
Reverse the audio file.
The reversing is done efficiently using NumPy views inplace
instead of swapping values.
Only speech and nonspeech intervals are actually recomputed
as Python lists.
"""
self.log(u"Reversing...")
all_length = self.all_length
self.__mfcc = self.__mfcc[:, ::-1]
tmp = self.__middle_end
self.__middle_end = all_length - self.__middle_begin
self.__middle_begin = all_length - tmp
if self.__mfcc_mask is not None:
self.__mfcc_mask = self.__mfcc_mask[::-1]
# equivalent to
# self.__mfcc_mask_map = ((all_length - 1) - self.__mfcc_mask_map)[::-1]
# but done in place using NumPy view
self.__mfcc_mask_map *= -1
self.__mfcc_mask_map += all_length - 1
self.__mfcc_mask_map = self.__mfcc_mask_map[::-1]
self.__speech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__speech_intervals[::-1]]
self.__nonspeech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__nonspeech_intervals[::-1]]
self.is_reversed = not self.is_reversed
self.log(u"Reversing...done") | python | def reverse(self):
"""
Reverse the audio file.
The reversing is done efficiently using NumPy views inplace
instead of swapping values.
Only speech and nonspeech intervals are actually recomputed
as Python lists.
"""
self.log(u"Reversing...")
all_length = self.all_length
self.__mfcc = self.__mfcc[:, ::-1]
tmp = self.__middle_end
self.__middle_end = all_length - self.__middle_begin
self.__middle_begin = all_length - tmp
if self.__mfcc_mask is not None:
self.__mfcc_mask = self.__mfcc_mask[::-1]
# equivalent to
# self.__mfcc_mask_map = ((all_length - 1) - self.__mfcc_mask_map)[::-1]
# but done in place using NumPy view
self.__mfcc_mask_map *= -1
self.__mfcc_mask_map += all_length - 1
self.__mfcc_mask_map = self.__mfcc_mask_map[::-1]
self.__speech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__speech_intervals[::-1]]
self.__nonspeech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__nonspeech_intervals[::-1]]
self.is_reversed = not self.is_reversed
self.log(u"Reversing...done") | [
"def",
"reverse",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Reversing...\"",
")",
"all_length",
"=",
"self",
".",
"all_length",
"self",
".",
"__mfcc",
"=",
"self",
".",
"__mfcc",
"[",
":",
",",
":",
":",
"-",
"1",
"]",
"tmp",
"=",
"self",... | Reverse the audio file.
The reversing is done efficiently using NumPy views inplace
instead of swapping values.
Only speech and nonspeech intervals are actually recomputed
as Python lists. | [
"Reverse",
"the",
"audio",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L555-L582 | train | 227,080 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.run_vad | def run_vad(
self,
log_energy_threshold=None,
min_nonspeech_length=None,
extend_before=None,
extend_after=None
):
"""
Determine which frames contain speech and nonspeech,
and store the resulting boolean mask internally.
The four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after)
"""
def _compute_runs(array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: :class:`numpy.ndarray` (1D)
:rtype: list of :class:`numpy.ndarray` (1D)
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1)
self.log(u"Creating VAD object")
vad = VAD(rconf=self.rconf, logger=self.logger)
self.log(u"Running VAD...")
self.__mfcc_mask = vad.run_vad(
wave_energy=self.__mfcc[0],
log_energy_threshold=log_energy_threshold,
min_nonspeech_length=min_nonspeech_length,
extend_before=extend_before,
extend_after=extend_after
)
self.__mfcc_mask_map = (numpy.where(self.__mfcc_mask))[0]
self.log(u"Running VAD... done")
self.log(u"Storing speech and nonspeech intervals...")
# where( == True) already computed, reusing
# COMMENTED runs = _compute_runs((numpy.where(self.__mfcc_mask))[0])
runs = _compute_runs(self.__mfcc_mask_map)
self.__speech_intervals = [(r[0], r[-1]) for r in runs]
# where( == False) not already computed, computing now
runs = _compute_runs((numpy.where(~self.__mfcc_mask))[0])
self.__nonspeech_intervals = [(r[0], r[-1]) for r in runs]
self.log(u"Storing speech and nonspeech intervals... done") | python | def run_vad(
self,
log_energy_threshold=None,
min_nonspeech_length=None,
extend_before=None,
extend_after=None
):
"""
Determine which frames contain speech and nonspeech,
and store the resulting boolean mask internally.
The four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after)
"""
def _compute_runs(array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: :class:`numpy.ndarray` (1D)
:rtype: list of :class:`numpy.ndarray` (1D)
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1)
self.log(u"Creating VAD object")
vad = VAD(rconf=self.rconf, logger=self.logger)
self.log(u"Running VAD...")
self.__mfcc_mask = vad.run_vad(
wave_energy=self.__mfcc[0],
log_energy_threshold=log_energy_threshold,
min_nonspeech_length=min_nonspeech_length,
extend_before=extend_before,
extend_after=extend_after
)
self.__mfcc_mask_map = (numpy.where(self.__mfcc_mask))[0]
self.log(u"Running VAD... done")
self.log(u"Storing speech and nonspeech intervals...")
# where( == True) already computed, reusing
# COMMENTED runs = _compute_runs((numpy.where(self.__mfcc_mask))[0])
runs = _compute_runs(self.__mfcc_mask_map)
self.__speech_intervals = [(r[0], r[-1]) for r in runs]
# where( == False) not already computed, computing now
runs = _compute_runs((numpy.where(~self.__mfcc_mask))[0])
self.__nonspeech_intervals = [(r[0], r[-1]) for r in runs]
self.log(u"Storing speech and nonspeech intervals... done") | [
"def",
"run_vad",
"(",
"self",
",",
"log_energy_threshold",
"=",
"None",
",",
"min_nonspeech_length",
"=",
"None",
",",
"extend_before",
"=",
"None",
",",
"extend_after",
"=",
"None",
")",
":",
"def",
"_compute_runs",
"(",
"array",
")",
":",
"\"\"\"\n ... | Determine which frames contain speech and nonspeech,
and store the resulting boolean mask internally.
The four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after) | [
"Determine",
"which",
"frames",
"contain",
"speech",
"and",
"nonspeech",
"and",
"store",
"the",
"resulting",
"boolean",
"mask",
"internally",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L584-L636 | train | 227,081 |
readbeyond/aeneas | aeneas/audiofilemfcc.py | AudioFileMFCC.set_head_middle_tail | def set_head_middle_tail(self, head_length=None, middle_length=None, tail_length=None):
"""
Set the HEAD, MIDDLE, TAIL explicitly.
If a parameter is ``None``, it will be ignored.
If both ``middle_length`` and ``tail_length`` are specified,
only ``middle_length`` will be applied.
:param head_length: the length of HEAD, in seconds
:type head_length: :class:`~aeneas.exacttiming.TimeValue`
:param middle_length: the length of MIDDLE, in seconds
:type middle_length: :class:`~aeneas.exacttiming.TimeValue`
:param tail_length: the length of TAIL, in seconds
:type tail_length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
:raises: ValueError: if one of the arguments is greater
than the length of the audio file
"""
for variable, name in [
(head_length, "head_length"),
(middle_length, "middle_length"),
(tail_length, "tail_length")
]:
if (variable is not None) and (not isinstance(variable, TimeValue)):
raise TypeError(u"%s is not None or TimeValue" % name)
if (variable is not None) and (variable > self.audio_length):
raise ValueError(u"%s is greater than the length of the audio file" % name)
self.log(u"Setting head middle tail...")
mws = self.rconf.mws
self.log([u"Before: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length])
if head_length is not None:
self.middle_begin = int(head_length / mws)
if middle_length is not None:
self.middle_end = self.middle_begin + int(middle_length / mws)
elif tail_length is not None:
self.middle_end = self.all_length - int(tail_length / mws)
self.log([u"After: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length])
self.log(u"Setting head middle tail... done") | python | def set_head_middle_tail(self, head_length=None, middle_length=None, tail_length=None):
"""
Set the HEAD, MIDDLE, TAIL explicitly.
If a parameter is ``None``, it will be ignored.
If both ``middle_length`` and ``tail_length`` are specified,
only ``middle_length`` will be applied.
:param head_length: the length of HEAD, in seconds
:type head_length: :class:`~aeneas.exacttiming.TimeValue`
:param middle_length: the length of MIDDLE, in seconds
:type middle_length: :class:`~aeneas.exacttiming.TimeValue`
:param tail_length: the length of TAIL, in seconds
:type tail_length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
:raises: ValueError: if one of the arguments is greater
than the length of the audio file
"""
for variable, name in [
(head_length, "head_length"),
(middle_length, "middle_length"),
(tail_length, "tail_length")
]:
if (variable is not None) and (not isinstance(variable, TimeValue)):
raise TypeError(u"%s is not None or TimeValue" % name)
if (variable is not None) and (variable > self.audio_length):
raise ValueError(u"%s is greater than the length of the audio file" % name)
self.log(u"Setting head middle tail...")
mws = self.rconf.mws
self.log([u"Before: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length])
if head_length is not None:
self.middle_begin = int(head_length / mws)
if middle_length is not None:
self.middle_end = self.middle_begin + int(middle_length / mws)
elif tail_length is not None:
self.middle_end = self.all_length - int(tail_length / mws)
self.log([u"After: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length])
self.log(u"Setting head middle tail... done") | [
"def",
"set_head_middle_tail",
"(",
"self",
",",
"head_length",
"=",
"None",
",",
"middle_length",
"=",
"None",
",",
"tail_length",
"=",
"None",
")",
":",
"for",
"variable",
",",
"name",
"in",
"[",
"(",
"head_length",
",",
"\"head_length\"",
")",
",",
"(",... | Set the HEAD, MIDDLE, TAIL explicitly.
If a parameter is ``None``, it will be ignored.
If both ``middle_length`` and ``tail_length`` are specified,
only ``middle_length`` will be applied.
:param head_length: the length of HEAD, in seconds
:type head_length: :class:`~aeneas.exacttiming.TimeValue`
:param middle_length: the length of MIDDLE, in seconds
:type middle_length: :class:`~aeneas.exacttiming.TimeValue`
:param tail_length: the length of TAIL, in seconds
:type tail_length: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the arguments is not ``None``
or :class:`~aeneas.exacttiming.TimeValue`
:raises: ValueError: if one of the arguments is greater
than the length of the audio file | [
"Set",
"the",
"HEAD",
"MIDDLE",
"TAIL",
"explicitly",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L638-L676 | train | 227,082 |
readbeyond/aeneas | aeneas/textfile.py | TextFragment.chars | def chars(self):
"""
Return the number of characters of the text fragment,
not including the line separators.
:rtype: int
"""
if self.lines is None:
return 0
return sum([len(line) for line in self.lines]) | python | def chars(self):
"""
Return the number of characters of the text fragment,
not including the line separators.
:rtype: int
"""
if self.lines is None:
return 0
return sum([len(line) for line in self.lines]) | [
"def",
"chars",
"(",
"self",
")",
":",
"if",
"self",
".",
"lines",
"is",
"None",
":",
"return",
"0",
"return",
"sum",
"(",
"[",
"len",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"lines",
"]",
")"
] | Return the number of characters of the text fragment,
not including the line separators.
:rtype: int | [
"Return",
"the",
"number",
"of",
"characters",
"of",
"the",
"text",
"fragment",
"not",
"including",
"the",
"line",
"separators",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L355-L364 | train | 227,083 |
readbeyond/aeneas | aeneas/textfile.py | TextFile.children_not_empty | def children_not_empty(self):
"""
Return the direct not empty children of the root of the fragments tree,
as ``TextFile`` objects.
:rtype: list of :class:`~aeneas.textfile.TextFile`
"""
children = []
for child_node in self.fragments_tree.children_not_empty:
child_text_file = self.get_subtree(child_node)
child_text_file.set_language(child_node.value.language)
children.append(child_text_file)
return children | python | def children_not_empty(self):
"""
Return the direct not empty children of the root of the fragments tree,
as ``TextFile`` objects.
:rtype: list of :class:`~aeneas.textfile.TextFile`
"""
children = []
for child_node in self.fragments_tree.children_not_empty:
child_text_file = self.get_subtree(child_node)
child_text_file.set_language(child_node.value.language)
children.append(child_text_file)
return children | [
"def",
"children_not_empty",
"(",
"self",
")",
":",
"children",
"=",
"[",
"]",
"for",
"child_node",
"in",
"self",
".",
"fragments_tree",
".",
"children_not_empty",
":",
"child_text_file",
"=",
"self",
".",
"get_subtree",
"(",
"child_node",
")",
"child_text_file"... | Return the direct not empty children of the root of the fragments tree,
as ``TextFile`` objects.
:rtype: list of :class:`~aeneas.textfile.TextFile` | [
"Return",
"the",
"direct",
"not",
"empty",
"children",
"of",
"the",
"root",
"of",
"the",
"fragments",
"tree",
"as",
"TextFile",
"objects",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L455-L467 | train | 227,084 |
readbeyond/aeneas | aeneas/textfile.py | TextFile.characters | def characters(self):
"""
The number of characters in this text file.
:rtype: int
"""
chars = 0
for fragment in self.fragments:
chars += fragment.characters
return chars | python | def characters(self):
"""
The number of characters in this text file.
:rtype: int
"""
chars = 0
for fragment in self.fragments:
chars += fragment.characters
return chars | [
"def",
"characters",
"(",
"self",
")",
":",
"chars",
"=",
"0",
"for",
"fragment",
"in",
"self",
".",
"fragments",
":",
"chars",
"+=",
"fragment",
".",
"characters",
"return",
"chars"
] | The number of characters in this text file.
:rtype: int | [
"The",
"number",
"of",
"characters",
"in",
"this",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L525-L534 | train | 227,085 |
readbeyond/aeneas | aeneas/textfile.py | TextFile.add_fragment | def add_fragment(self, fragment, as_last=True):
"""
Add the given text fragment as the first or last child of the root node
of the text file tree.
:param fragment: the text fragment to be added
:type fragment: :class:`~aeneas.textfile.TextFragment`
:param bool as_last: if ``True`` append fragment, otherwise prepend it
"""
if not isinstance(fragment, TextFragment):
self.log_exc(u"fragment is not an instance of TextFragment", None, True, TypeError)
self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last) | python | def add_fragment(self, fragment, as_last=True):
"""
Add the given text fragment as the first or last child of the root node
of the text file tree.
:param fragment: the text fragment to be added
:type fragment: :class:`~aeneas.textfile.TextFragment`
:param bool as_last: if ``True`` append fragment, otherwise prepend it
"""
if not isinstance(fragment, TextFragment):
self.log_exc(u"fragment is not an instance of TextFragment", None, True, TypeError)
self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last) | [
"def",
"add_fragment",
"(",
"self",
",",
"fragment",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"fragment",
",",
"TextFragment",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"fragment is not an instance of TextFragment\"",
",",
"None",
... | Add the given text fragment as the first or last child of the root node
of the text file tree.
:param fragment: the text fragment to be added
:type fragment: :class:`~aeneas.textfile.TextFragment`
:param bool as_last: if ``True`` append fragment, otherwise prepend it | [
"Add",
"the",
"given",
"text",
"fragment",
"as",
"the",
"first",
"or",
"last",
"child",
"of",
"the",
"root",
"node",
"of",
"the",
"text",
"file",
"tree",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L547-L558 | train | 227,086 |
readbeyond/aeneas | aeneas/textfile.py | TextFile.set_language | def set_language(self, language):
"""
Set the given language for all the text fragments.
:param language: the language of the text fragments
:type language: :class:`~aeneas.language.Language`
"""
self.log([u"Setting language: '%s'", language])
for fragment in self.fragments:
fragment.language = language | python | def set_language(self, language):
"""
Set the given language for all the text fragments.
:param language: the language of the text fragments
:type language: :class:`~aeneas.language.Language`
"""
self.log([u"Setting language: '%s'", language])
for fragment in self.fragments:
fragment.language = language | [
"def",
"set_language",
"(",
"self",
",",
"language",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Setting language: '%s'\"",
",",
"language",
"]",
")",
"for",
"fragment",
"in",
"self",
".",
"fragments",
":",
"fragment",
".",
"language",
"=",
"language"
] | Set the given language for all the text fragments.
:param language: the language of the text fragments
:type language: :class:`~aeneas.language.Language` | [
"Set",
"the",
"given",
"language",
"for",
"all",
"the",
"text",
"fragments",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L598-L607 | train | 227,087 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_from_file | def _read_from_file(self):
"""
Read text fragments from file.
"""
# test if we can read the given file
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
if self.file_format not in TextFileFormat.ALLOWED_VALUES:
self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError)
# read the contents of the file
self.log([u"Reading contents of file '%s'", self.file_path])
with io.open(self.file_path, "r", encoding="utf-8") as text_file:
lines = text_file.readlines()
# clear text fragments
self.clear()
# parse the contents
map_read_function = {
TextFileFormat.MPLAIN: self._read_mplain,
TextFileFormat.MUNPARSED: self._read_munparsed,
TextFileFormat.PARSED: self._read_parsed,
TextFileFormat.PLAIN: self._read_plain,
TextFileFormat.SUBTITLES: self._read_subtitles,
TextFileFormat.UNPARSED: self._read_unparsed
}
map_read_function[self.file_format](lines)
# log the number of fragments
self.log([u"Parsed %d fragments", len(self.fragments)]) | python | def _read_from_file(self):
"""
Read text fragments from file.
"""
# test if we can read the given file
if not gf.file_can_be_read(self.file_path):
self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)
if self.file_format not in TextFileFormat.ALLOWED_VALUES:
self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError)
# read the contents of the file
self.log([u"Reading contents of file '%s'", self.file_path])
with io.open(self.file_path, "r", encoding="utf-8") as text_file:
lines = text_file.readlines()
# clear text fragments
self.clear()
# parse the contents
map_read_function = {
TextFileFormat.MPLAIN: self._read_mplain,
TextFileFormat.MUNPARSED: self._read_munparsed,
TextFileFormat.PARSED: self._read_parsed,
TextFileFormat.PLAIN: self._read_plain,
TextFileFormat.SUBTITLES: self._read_subtitles,
TextFileFormat.UNPARSED: self._read_unparsed
}
map_read_function[self.file_format](lines)
# log the number of fragments
self.log([u"Parsed %d fragments", len(self.fragments)]) | [
"def",
"_read_from_file",
"(",
"self",
")",
":",
"# test if we can read the given file",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"self",
".",
"file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"File '%s' cannot be read\"",
"%",
"(",
"self",
".",
"fi... | Read text fragments from file. | [
"Read",
"text",
"fragments",
"from",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L638-L669 | train | 227,088 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._mplain_word_separator | def _mplain_word_separator(self):
"""
Get the word separator to split words in mplain format.
:rtype: string
"""
word_separator = gf.safe_get(self.parameters, gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR, u" ")
if (word_separator is None) or (word_separator == "space"):
return u" "
elif word_separator == "equal":
return u"="
elif word_separator == "pipe":
return u"|"
elif word_separator == "tab":
return u"\u0009"
return word_separator | python | def _mplain_word_separator(self):
"""
Get the word separator to split words in mplain format.
:rtype: string
"""
word_separator = gf.safe_get(self.parameters, gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR, u" ")
if (word_separator is None) or (word_separator == "space"):
return u" "
elif word_separator == "equal":
return u"="
elif word_separator == "pipe":
return u"|"
elif word_separator == "tab":
return u"\u0009"
return word_separator | [
"def",
"_mplain_word_separator",
"(",
"self",
")",
":",
"word_separator",
"=",
"gf",
".",
"safe_get",
"(",
"self",
".",
"parameters",
",",
"gc",
".",
"PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR",
",",
"u\" \"",
")",
"if",
"(",
"word_separator",
"is",
"None",
")",
... | Get the word separator to split words in mplain format.
:rtype: string | [
"Get",
"the",
"word",
"separator",
"to",
"split",
"words",
"in",
"mplain",
"format",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L671-L686 | train | 227,089 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_mplain | def _read_mplain(self, lines):
"""
Read text fragments from a multilevel format text file.
:param list lines: the lines of the subtitles text file
"""
self.log(u"Parsing fragments from subtitles text format")
word_separator = self._mplain_word_separator()
self.log([u"Word separator is: '%s'", word_separator])
lines = [line.strip() for line in lines]
pairs = []
i = 1
current = 0
tree = Tree()
while current < len(lines):
line_text = lines[current]
if len(line_text) > 0:
sentences = [line_text]
following = current + 1
while (following < len(lines)) and (len(lines[following]) > 0):
sentences.append(lines[following])
following += 1
# here sentences holds the sentences for this paragraph
# create paragraph node
paragraph_identifier = u"p%06d" % i
paragraph_lines = [u" ".join(sentences)]
paragraph_fragment = TextFragment(
identifier=paragraph_identifier,
lines=paragraph_lines,
filtered_lines=paragraph_lines
)
paragraph_node = Tree(value=paragraph_fragment)
tree.add_child(paragraph_node)
self.log([u"Paragraph %s", paragraph_identifier])
# create sentences nodes
j = 1
for s in sentences:
sentence_identifier = paragraph_identifier + u"s%06d" % j
sentence_lines = [s]
sentence_fragment = TextFragment(
identifier=sentence_identifier,
lines=sentence_lines,
filtered_lines=sentence_lines
)
sentence_node = Tree(value=sentence_fragment)
paragraph_node.add_child(sentence_node)
j += 1
self.log([u" Sentence %s", sentence_identifier])
# create words nodes
k = 1
for w in [w for w in s.split(word_separator) if len(w) > 0]:
word_identifier = sentence_identifier + u"w%06d" % k
word_lines = [w]
word_fragment = TextFragment(
identifier=word_identifier,
lines=word_lines,
filtered_lines=word_lines
)
word_node = Tree(value=word_fragment)
sentence_node.add_child(word_node)
k += 1
self.log([u" Word %s", word_identifier])
# keep iterating
current = following
i += 1
current += 1
self.log(u"Storing tree")
self.fragments_tree = tree | python | def _read_mplain(self, lines):
"""
Read text fragments from a multilevel format text file.
:param list lines: the lines of the subtitles text file
"""
self.log(u"Parsing fragments from subtitles text format")
word_separator = self._mplain_word_separator()
self.log([u"Word separator is: '%s'", word_separator])
lines = [line.strip() for line in lines]
pairs = []
i = 1
current = 0
tree = Tree()
while current < len(lines):
line_text = lines[current]
if len(line_text) > 0:
sentences = [line_text]
following = current + 1
while (following < len(lines)) and (len(lines[following]) > 0):
sentences.append(lines[following])
following += 1
# here sentences holds the sentences for this paragraph
# create paragraph node
paragraph_identifier = u"p%06d" % i
paragraph_lines = [u" ".join(sentences)]
paragraph_fragment = TextFragment(
identifier=paragraph_identifier,
lines=paragraph_lines,
filtered_lines=paragraph_lines
)
paragraph_node = Tree(value=paragraph_fragment)
tree.add_child(paragraph_node)
self.log([u"Paragraph %s", paragraph_identifier])
# create sentences nodes
j = 1
for s in sentences:
sentence_identifier = paragraph_identifier + u"s%06d" % j
sentence_lines = [s]
sentence_fragment = TextFragment(
identifier=sentence_identifier,
lines=sentence_lines,
filtered_lines=sentence_lines
)
sentence_node = Tree(value=sentence_fragment)
paragraph_node.add_child(sentence_node)
j += 1
self.log([u" Sentence %s", sentence_identifier])
# create words nodes
k = 1
for w in [w for w in s.split(word_separator) if len(w) > 0]:
word_identifier = sentence_identifier + u"w%06d" % k
word_lines = [w]
word_fragment = TextFragment(
identifier=word_identifier,
lines=word_lines,
filtered_lines=word_lines
)
word_node = Tree(value=word_fragment)
sentence_node.add_child(word_node)
k += 1
self.log([u" Word %s", word_identifier])
# keep iterating
current = following
i += 1
current += 1
self.log(u"Storing tree")
self.fragments_tree = tree | [
"def",
"_read_mplain",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from subtitles text format\"",
")",
"word_separator",
"=",
"self",
".",
"_mplain_word_separator",
"(",
")",
"self",
".",
"log",
"(",
"[",
"u\"Word separator ... | Read text fragments from a multilevel format text file.
:param list lines: the lines of the subtitles text file | [
"Read",
"text",
"fragments",
"from",
"a",
"multilevel",
"format",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L688-L760 | train | 227,090 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_subtitles | def _read_subtitles(self, lines):
"""
Read text fragments from a subtitles format text file.
:param list lines: the lines of the subtitles text file
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from subtitles text format")
id_format = self._get_id_format()
lines = [line.strip() for line in lines]
pairs = []
i = 1
current = 0
while current < len(lines):
line_text = lines[current]
if len(line_text) > 0:
fragment_lines = [line_text]
following = current + 1
while (following < len(lines)) and (len(lines[following]) > 0):
fragment_lines.append(lines[following])
following += 1
identifier = id_format % i
pairs.append((identifier, fragment_lines))
current = following
i += 1
current += 1
self._create_text_fragments(pairs) | python | def _read_subtitles(self, lines):
"""
Read text fragments from a subtitles format text file.
:param list lines: the lines of the subtitles text file
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from subtitles text format")
id_format = self._get_id_format()
lines = [line.strip() for line in lines]
pairs = []
i = 1
current = 0
while current < len(lines):
line_text = lines[current]
if len(line_text) > 0:
fragment_lines = [line_text]
following = current + 1
while (following < len(lines)) and (len(lines[following]) > 0):
fragment_lines.append(lines[following])
following += 1
identifier = id_format % i
pairs.append((identifier, fragment_lines))
current = following
i += 1
current += 1
self._create_text_fragments(pairs) | [
"def",
"_read_subtitles",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from subtitles text format\"",
")",
"id_format",
"=",
"self",
".",
"_get_id_format",
"(",
")",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"f... | Read text fragments from a subtitles format text file.
:param list lines: the lines of the subtitles text file
:raises: ValueError: if the id regex is not valid | [
"Read",
"text",
"fragments",
"from",
"a",
"subtitles",
"format",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L851-L877 | train | 227,091 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_parsed | def _read_parsed(self, lines):
"""
Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
"""
self.log(u"Parsing fragments from parsed text format")
pairs = []
for line in lines:
pieces = line.split(gc.PARSED_TEXT_SEPARATOR)
if len(pieces) == 2:
identifier = pieces[0].strip()
text = pieces[1].strip()
if len(identifier) > 0:
pairs.append((identifier, [text]))
self._create_text_fragments(pairs) | python | def _read_parsed(self, lines):
"""
Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
"""
self.log(u"Parsing fragments from parsed text format")
pairs = []
for line in lines:
pieces = line.split(gc.PARSED_TEXT_SEPARATOR)
if len(pieces) == 2:
identifier = pieces[0].strip()
text = pieces[1].strip()
if len(identifier) > 0:
pairs.append((identifier, [text]))
self._create_text_fragments(pairs) | [
"def",
"_read_parsed",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from parsed text format\"",
")",
"pairs",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"pieces",
"=",
"line",
".",
"split",
"(",
"gc",
".",
"P... | Read text fragments from a parsed format text file.
:param list lines: the lines of the parsed text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings) | [
"Read",
"text",
"fragments",
"from",
"a",
"parsed",
"format",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L879-L896 | train | 227,092 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_plain | def _read_plain(self, lines):
"""
Read text fragments from a plain format text file.
:param list lines: the lines of the plain text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from plain text format")
id_format = self._get_id_format()
lines = [line.strip() for line in lines]
pairs = []
i = 1
for line in lines:
identifier = id_format % i
text = line.strip()
pairs.append((identifier, [text]))
i += 1
self._create_text_fragments(pairs) | python | def _read_plain(self, lines):
"""
Read text fragments from a plain format text file.
:param list lines: the lines of the plain text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
:raises: ValueError: if the id regex is not valid
"""
self.log(u"Parsing fragments from plain text format")
id_format = self._get_id_format()
lines = [line.strip() for line in lines]
pairs = []
i = 1
for line in lines:
identifier = id_format % i
text = line.strip()
pairs.append((identifier, [text]))
i += 1
self._create_text_fragments(pairs) | [
"def",
"_read_plain",
"(",
"self",
",",
"lines",
")",
":",
"self",
".",
"log",
"(",
"u\"Parsing fragments from plain text format\"",
")",
"id_format",
"=",
"self",
".",
"_get_id_format",
"(",
")",
"lines",
"=",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"... | Read text fragments from a plain format text file.
:param list lines: the lines of the plain text file
:param dict parameters: additional parameters for parsing
(e.g., class/id regex strings)
:raises: ValueError: if the id regex is not valid | [
"Read",
"text",
"fragments",
"from",
"a",
"plain",
"format",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L898-L917 | train | 227,093 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._read_unparsed | def _read_unparsed(self, lines):
"""
Read text fragments from an unparsed format text file.
:param list lines: the lines of the unparsed text file
"""
from bs4 import BeautifulSoup
def filter_attributes():
""" Return a dict with the bs4 filter parameters """
attributes = {}
for attribute_name, filter_name in [
("class", gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX),
("id", gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX)
]:
if filter_name in self.parameters:
regex_string = self.parameters[filter_name]
if regex_string is not None:
self.log([u"Regex for %s: '%s'", attribute_name, regex_string])
regex = re.compile(r".*\b" + regex_string + r"\b.*")
attributes[attribute_name] = regex
return attributes
#
# TODO better and/or parametric parsing,
# for example, removing tags but keeping text, etc.
#
self.log(u"Parsing fragments from unparsed text format")
# transform text in a soup object
self.log(u"Creating soup")
soup = BeautifulSoup("\n".join(lines), "lxml")
# extract according to class_regex and id_regex
text_from_id = {}
ids = []
filter_attributes = filter_attributes()
self.log([u"Finding elements matching attributes '%s'", filter_attributes])
nodes = soup.findAll(attrs=filter_attributes)
for node in nodes:
try:
f_id = gf.safe_unicode(node["id"])
f_text = gf.safe_unicode(node.text)
text_from_id[f_id] = f_text
ids.append(f_id)
except KeyError:
self.log_warn(u"KeyError while parsing a node")
# sort by ID as requested
id_sort = gf.safe_get(
dictionary=self.parameters,
key=gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT,
default_value=IDSortingAlgorithm.UNSORTED,
can_return_none=False
)
self.log([u"Sorting text fragments using '%s'", id_sort])
sorted_ids = IDSortingAlgorithm(id_sort).sort(ids)
# append to fragments
self.log(u"Appending fragments")
self._create_text_fragments([(key, [text_from_id[key]]) for key in sorted_ids]) | python | def _read_unparsed(self, lines):
"""
Read text fragments from an unparsed format text file.
:param list lines: the lines of the unparsed text file
"""
from bs4 import BeautifulSoup
def filter_attributes():
""" Return a dict with the bs4 filter parameters """
attributes = {}
for attribute_name, filter_name in [
("class", gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX),
("id", gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX)
]:
if filter_name in self.parameters:
regex_string = self.parameters[filter_name]
if regex_string is not None:
self.log([u"Regex for %s: '%s'", attribute_name, regex_string])
regex = re.compile(r".*\b" + regex_string + r"\b.*")
attributes[attribute_name] = regex
return attributes
#
# TODO better and/or parametric parsing,
# for example, removing tags but keeping text, etc.
#
self.log(u"Parsing fragments from unparsed text format")
# transform text in a soup object
self.log(u"Creating soup")
soup = BeautifulSoup("\n".join(lines), "lxml")
# extract according to class_regex and id_regex
text_from_id = {}
ids = []
filter_attributes = filter_attributes()
self.log([u"Finding elements matching attributes '%s'", filter_attributes])
nodes = soup.findAll(attrs=filter_attributes)
for node in nodes:
try:
f_id = gf.safe_unicode(node["id"])
f_text = gf.safe_unicode(node.text)
text_from_id[f_id] = f_text
ids.append(f_id)
except KeyError:
self.log_warn(u"KeyError while parsing a node")
# sort by ID as requested
id_sort = gf.safe_get(
dictionary=self.parameters,
key=gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT,
default_value=IDSortingAlgorithm.UNSORTED,
can_return_none=False
)
self.log([u"Sorting text fragments using '%s'", id_sort])
sorted_ids = IDSortingAlgorithm(id_sort).sort(ids)
# append to fragments
self.log(u"Appending fragments")
self._create_text_fragments([(key, [text_from_id[key]]) for key in sorted_ids]) | [
"def",
"_read_unparsed",
"(",
"self",
",",
"lines",
")",
":",
"from",
"bs4",
"import",
"BeautifulSoup",
"def",
"filter_attributes",
"(",
")",
":",
"\"\"\" Return a dict with the bs4 filter parameters \"\"\"",
"attributes",
"=",
"{",
"}",
"for",
"attribute_name",
",",
... | Read text fragments from an unparsed format text file.
:param list lines: the lines of the unparsed text file | [
"Read",
"text",
"fragments",
"from",
"an",
"unparsed",
"format",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L919-L978 | train | 227,094 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._get_id_format | def _get_id_format(self):
""" Return the id regex from the parameters"""
id_format = gf.safe_get(
self.parameters,
gc.PPN_TASK_OS_FILE_ID_REGEX,
self.DEFAULT_ID_FORMAT,
can_return_none=False
)
try:
identifier = id_format % 1
except (TypeError, ValueError) as exc:
self.log_exc(u"String '%s' is not a valid id format" % (id_format), exc, True, ValueError)
return id_format | python | def _get_id_format(self):
""" Return the id regex from the parameters"""
id_format = gf.safe_get(
self.parameters,
gc.PPN_TASK_OS_FILE_ID_REGEX,
self.DEFAULT_ID_FORMAT,
can_return_none=False
)
try:
identifier = id_format % 1
except (TypeError, ValueError) as exc:
self.log_exc(u"String '%s' is not a valid id format" % (id_format), exc, True, ValueError)
return id_format | [
"def",
"_get_id_format",
"(",
"self",
")",
":",
"id_format",
"=",
"gf",
".",
"safe_get",
"(",
"self",
".",
"parameters",
",",
"gc",
".",
"PPN_TASK_OS_FILE_ID_REGEX",
",",
"self",
".",
"DEFAULT_ID_FORMAT",
",",
"can_return_none",
"=",
"False",
")",
"try",
":"... | Return the id regex from the parameters | [
"Return",
"the",
"id",
"regex",
"from",
"the",
"parameters"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L980-L992 | train | 227,095 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._create_text_fragments | def _create_text_fragments(self, pairs):
"""
Create text fragment objects and append them to this list.
:param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n])
"""
self.log(u"Creating TextFragment objects")
text_filter = self._build_text_filter()
for pair in pairs:
self.add_fragment(
TextFragment(
identifier=pair[0],
lines=pair[1],
filtered_lines=text_filter.apply_filter(pair[1])
)
) | python | def _create_text_fragments(self, pairs):
"""
Create text fragment objects and append them to this list.
:param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n])
"""
self.log(u"Creating TextFragment objects")
text_filter = self._build_text_filter()
for pair in pairs:
self.add_fragment(
TextFragment(
identifier=pair[0],
lines=pair[1],
filtered_lines=text_filter.apply_filter(pair[1])
)
) | [
"def",
"_create_text_fragments",
"(",
"self",
",",
"pairs",
")",
":",
"self",
".",
"log",
"(",
"u\"Creating TextFragment objects\"",
")",
"text_filter",
"=",
"self",
".",
"_build_text_filter",
"(",
")",
"for",
"pair",
"in",
"pairs",
":",
"self",
".",
"add_frag... | Create text fragment objects and append them to this list.
:param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n]) | [
"Create",
"text",
"fragment",
"objects",
"and",
"append",
"them",
"to",
"this",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L994-L1009 | train | 227,096 |
readbeyond/aeneas | aeneas/textfile.py | TextFile._build_text_filter | def _build_text_filter(self):
"""
Build a suitable TextFilter object.
"""
text_filter = TextFilter(logger=self.logger)
self.log(u"Created TextFilter object")
for key, cls, param_name in [
(
gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX,
TextFilterIgnoreRegex,
"regex"
),
(
gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP,
TextFilterTransliterate,
"map_file_path"
)
]:
cls_name = cls.__name__
param_value = gf.safe_get(self.parameters, key, None)
if param_value is not None:
self.log([u"Creating %s object...", cls_name])
params = {
param_name: param_value,
"logger": self.logger
}
try:
inner_filter = cls(**params)
text_filter.add_filter(inner_filter)
self.log([u"Creating %s object... done", cls_name])
except ValueError as exc:
self.log_exc(u"Creating %s object failed" % (cls_name), exc, False, None)
return text_filter | python | def _build_text_filter(self):
"""
Build a suitable TextFilter object.
"""
text_filter = TextFilter(logger=self.logger)
self.log(u"Created TextFilter object")
for key, cls, param_name in [
(
gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX,
TextFilterIgnoreRegex,
"regex"
),
(
gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP,
TextFilterTransliterate,
"map_file_path"
)
]:
cls_name = cls.__name__
param_value = gf.safe_get(self.parameters, key, None)
if param_value is not None:
self.log([u"Creating %s object...", cls_name])
params = {
param_name: param_value,
"logger": self.logger
}
try:
inner_filter = cls(**params)
text_filter.add_filter(inner_filter)
self.log([u"Creating %s object... done", cls_name])
except ValueError as exc:
self.log_exc(u"Creating %s object failed" % (cls_name), exc, False, None)
return text_filter | [
"def",
"_build_text_filter",
"(",
"self",
")",
":",
"text_filter",
"=",
"TextFilter",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"log",
"(",
"u\"Created TextFilter object\"",
")",
"for",
"key",
",",
"cls",
",",
"param_name",
"in",
"[",
"(... | Build a suitable TextFilter object. | [
"Build",
"a",
"suitable",
"TextFilter",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1011-L1043 | train | 227,097 |
readbeyond/aeneas | aeneas/textfile.py | TextFilter.add_filter | def add_filter(self, new_filter, as_last=True):
"""
Compose this filter with the given ``new_filter`` filter.
:param new_filter: the filter to be composed
:type new_filter: :class:`~aeneas.textfile.TextFilter`
:param bool as_last: if ``True``, compose to the right, otherwise to the left
"""
if as_last:
self.filters.append(new_filter)
else:
self.filters = [new_filter] + self.filters | python | def add_filter(self, new_filter, as_last=True):
"""
Compose this filter with the given ``new_filter`` filter.
:param new_filter: the filter to be composed
:type new_filter: :class:`~aeneas.textfile.TextFilter`
:param bool as_last: if ``True``, compose to the right, otherwise to the left
"""
if as_last:
self.filters.append(new_filter)
else:
self.filters = [new_filter] + self.filters | [
"def",
"add_filter",
"(",
"self",
",",
"new_filter",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"as_last",
":",
"self",
".",
"filters",
".",
"append",
"(",
"new_filter",
")",
"else",
":",
"self",
".",
"filters",
"=",
"[",
"new_filter",
"]",
"+",
"s... | Compose this filter with the given ``new_filter`` filter.
:param new_filter: the filter to be composed
:type new_filter: :class:`~aeneas.textfile.TextFilter`
:param bool as_last: if ``True``, compose to the right, otherwise to the left | [
"Compose",
"this",
"filter",
"with",
"the",
"given",
"new_filter",
"filter",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1071-L1082 | train | 227,098 |
readbeyond/aeneas | aeneas/textfile.py | TextFilter.apply_filter | def apply_filter(self, strings):
"""
Apply the text filter filter to the given list of strings.
:param list strings: the list of input strings
"""
result = strings
for filt in self.filters:
result = filt.apply_filter(result)
self.log([u"Applying regex: '%s' => '%s'", strings, result])
return result | python | def apply_filter(self, strings):
"""
Apply the text filter filter to the given list of strings.
:param list strings: the list of input strings
"""
result = strings
for filt in self.filters:
result = filt.apply_filter(result)
self.log([u"Applying regex: '%s' => '%s'", strings, result])
return result | [
"def",
"apply_filter",
"(",
"self",
",",
"strings",
")",
":",
"result",
"=",
"strings",
"for",
"filt",
"in",
"self",
".",
"filters",
":",
"result",
"=",
"filt",
".",
"apply_filter",
"(",
"result",
")",
"self",
".",
"log",
"(",
"[",
"u\"Applying regex: '%... | Apply the text filter filter to the given list of strings.
:param list strings: the list of input strings | [
"Apply",
"the",
"text",
"filter",
"filter",
"to",
"the",
"given",
"list",
"of",
"strings",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1084-L1094 | train | 227,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.