Skip to content

Commit

Permalink
Add type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
naglis committed Nov 14, 2024
1 parent 98a6783 commit cc332d6
Show file tree
Hide file tree
Showing 5 changed files with 96 additions and 78 deletions.
79 changes: 38 additions & 41 deletions aeneas/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
import aeneas.globalfunctions as gf


type Message = str | typing.Sequence[typing.Any]


class Logger:
"""
A logger class for debugging and performance profiling.
Expand Down Expand Up @@ -119,12 +122,14 @@ def indentation(self) -> int:
def indentation(self, indentation: int):
self.__indentation = indentation

def pretty_print(self, as_list=False, show_datetime=True) -> str | list[str]:
def pretty_print(
self, as_list: bool = False, show_datetime: bool = True
) -> str | list[str]:
"""
Return a string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of strings,
one for each entry, instead of a Unicode string
one for each entry, instead of a string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string or list of strings
"""
Expand All @@ -133,7 +138,7 @@ def pretty_print(self, as_list=False, show_datetime=True) -> str | list[str]:
return ppl
return "\n".join(ppl)

def log(self, message, severity=INFO, tag=""):
def log(self, message: Message, severity=INFO, tag: str = "") -> datetime.datetime:
"""
Add a given message to the log, and return its time.
Expand Down Expand Up @@ -162,7 +167,7 @@ def clear(self):
"""
self.entries = []

def write(self, path):
def write(self, path: str):
"""
Output the log to file.
Expand All @@ -172,7 +177,7 @@ def write(self, path):
log_file.write(self.pretty_print())

@classmethod
def _sanitize(cls, message):
def _sanitize(cls, message: Message) -> str:
"""
Sanitize the given message,
dealing with multiple arguments
Expand All @@ -182,15 +187,15 @@ def _sanitize(cls, message):
:type message: string or list of strings
:rtype: string
"""
if isinstance(message, list):
if isinstance(message, str):
sanitized = message
else:
if len(message) == 0:
sanitized = "Empty log message"
elif len(message) == 1:
sanitized = message[0]
else:
sanitized = message[0] % tuple(message[1:])
else:
sanitized = message
if not isinstance(sanitized, str):
raise TypeError("The given log message is not a string")
return sanitized
Expand All @@ -201,16 +206,16 @@ class _LogEntry:
A structure for a log entry.
"""

def __init__(self, message, severity, tag, indentation, time):
def __init__(self, message: str, severity, tag: str, indentation: int, time):
self.message = message
self.severity = severity
self.tag = tag
self.indentation = indentation
self.time = time

def pretty_print(self, show_datetime=True):
def pretty_print(self, show_datetime: bool = True) -> str:
"""
Returns a Unicode string containing
Returns a string containing
the pretty printing of a given log entry.
:param bool show_datetime: if ``True``, print the date and time of the entry
Expand All @@ -229,16 +234,14 @@ def pretty_print(self, show_datetime=True):
)

@property
def message(self):
def message(self) -> str:
"""
The message of this log entry.
:rtype: string
"""
return self.__message

@message.setter
def message(self, message):
def message(self, message: str):
self.__message = message

@property
Expand All @@ -255,16 +258,14 @@ def severity(self, severity):
self.__severity = severity

@property
def tag(self):
def tag(self) -> str:
"""
The tag of this log entry.
:rtype: string
"""
return self.__tag

@tag.setter
def tag(self, tag):
def tag(self, tag: str):
self.__tag = tag

@property
Expand All @@ -281,16 +282,16 @@ def indentation(self, indentation):
self.__indentation = indentation

@property
def time(self):
def time(self) -> datetime.datetime:
"""
The date and time of this log entry.
:rtype: datetime.time
:rtype: datetime.datetime
"""
return self.__time

@time.setter
def time(self, time):
def time(self, time: datetime.datetime):
self.__time = time


Expand All @@ -306,11 +307,13 @@ class Loggable:

TAG: typing.ClassVar[str] = "Loggable"

def __init__(self, logger=None, rconf=None):
def __init__(
self, logger: Logger | None = None, rconf: RuntimeConfiguration | None = None
):
self.logger = logger if logger is not None else Logger()
self.rconf = rconf if rconf is not None else RuntimeConfiguration()

def _log(self, message, severity=Logger.DEBUG):
def _log(self, message: Message, severity=Logger.DEBUG) -> datetime.datetime:
"""
Log generic message
Expand All @@ -320,7 +323,13 @@ def _log(self, message, severity=Logger.DEBUG):
"""
return self.logger.log(message, severity, self.TAG)

def log_exc(self, message, exc=None, critical=True, raise_type=None):
def log_exc(
self,
message: Message,
exc: Exception | None = None,
critical: bool = True,
raise_type: type[Exception] | None = None,
) -> None:
"""
Log exception, and possibly raise exception.
Expand All @@ -340,38 +349,26 @@ def log_exc(self, message, exc=None, critical=True, raise_type=None):
raise_message = f"{message} : {exc}"
raise raise_type(raise_message)

def log(self, message):
def log(self, message: Message) -> datetime.datetime:
"""
Log DEBUG message, and return its time.
:param string message: the message to log
:rtype: datetime
"""
return self._log(message)

def log_info(self, message):
def log_info(self, message: Message) -> datetime.datetime:
"""
Log INFO message, and return its time.
:param string message: the message to log
:rtype: datetime
"""
return self._log(message, Logger.INFO)

def log_warn(self, message):
def log_warn(self, message: Message) -> datetime.datetime:
"""
Log WARNING message, and return its time.
:param string message: the message to log
:rtype: datetime
"""
return self._log(message, Logger.WARNING)

def log_crit(self, message):
def log_crit(self, message: Message) -> datetime.datetime:
"""
Log CRITICAL message, and return its time.
:param string message: the message to log
:rtype: datetime
"""
return self._log(message, Logger.CRITICAL)
2 changes: 1 addition & 1 deletion aeneas/syncmap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def read(

def write(
self,
sync_map_format: SyncMapFormat,
sync_map_format: str,
output_file_path: str,
parameters: dict | None = None,
):
Expand Down
2 changes: 1 addition & 1 deletion aeneas/syncmap/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -788,5 +788,5 @@ class = "IntervalTier"
XML_LEGACY: SyncMapFormatXMLLegacy,
}

ALLOWED_VALUES = sorted(list(CODE_TO_CLASS.keys()))
ALLOWED_VALUES = sorted(CODE_TO_CLASS)
""" List of all the allowed values """
60 changes: 32 additions & 28 deletions aeneas/syncmap/smfbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,57 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import abc
import typing

from aeneas.logger import Loggable
from aeneas.language import Language
from aeneas.exacttiming import TimeValue
from aeneas.syncmap.fragment import SyncMapFragment
from aeneas.textfile import TextFragment


class SyncMapFormatBase(Loggable):
# FIXME: Remove this hack.
if typing.TYPE_CHECKING:
from aeneas.syncmap import SyncMap


class SyncMapFormatBase(Loggable, abc.ABC):
"""
Base class for I/O handlers.
"""

TAG = "SyncMapFormatBase"

def __init__(self, variant=None, parameters=None, rconf=None, logger=None):
def __init__(
self,
variant: str | None = None,
parameters: dict | None = None,
rconf=None,
logger=None,
):
"""
TBW
:param variant: the code of the format variant to read or write
:type variant: string
:param parameters: additional parameters to read or write
:type paramenters: ``None`` or ``dict``
:type parameters: ``None`` or ``dict``
"""
super().__init__(rconf=rconf, logger=logger)
self.variant = variant
self.parameters = parameters

@classmethod
def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
def _add_fragment(
cls,
syncmap: "SyncMap",
identifier: str,
lines: typing.Sequence[str],
begin: TimeValue,
end: TimeValue,
language: Language | None = None,
):
"""
Add a new fragment to ``syncmap``.
Expand All @@ -74,34 +97,15 @@ def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
)
)

def parse(self, input_text, syncmap):
@abc.abstractmethod
def parse(self, input_text: str, syncmap: "SyncMap") -> str:
"""
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(
"%s is abstract and cannot be called directly" % (self.TAG),
None,
True,
NotImplementedError,
)

def format(self, syncmap):
@abc.abstractmethod
def format(self, syncmap: "SyncMap") -> str:
"""
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 string.
"""
self.log_exc(
"%s is abstract and cannot be called directly" % (self.TAG),
None,
True,
NotImplementedError,
)
Loading

0 comments on commit cc332d6

Please sign in to comment.