Skip to content

API Reference

tf_notify.callbacks.slack.SlackCallback

Bases: BaseNotificationCallback

A custom tf.callbacks.Callback that provides instant integration with Slack messaging app.

Attributes:

Name Type Description
webhook_url str

an Incoming Webhook URL for a given workspace and channel. You can generate one over at: https://my.slack.com/services/new/incoming-webhook/

Examples:

>>> import tensorflow as tf
>>> from tf_notify import SlackCallback
>>>
>>> model = tf.keras.Sequential(name="neural-network")
>>> model.add(tf.keras.layers.Dense(1, input_dim=784))
>>> model.compile(
>>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
>>>     loss="mean_squared_error",
>>>     metrics=["mean_absolute_error"],
>>> )
>>>
>>> model.fit(
>>>     x_train,
>>>     y_train,
>>>     batch_size=128,
>>>     epochs=2,
>>>     verbose=0,
>>>     validation_split=0.5,
>>>     callbacks=[
>>>         SlackCallback(webhook_url="https://url.to/webhook")
>>>     ],
>>> )

Note: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is for internal use only. They may be changed or removed at anytime.

Source code in tf_notify/callbacks/slack.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class SlackCallback(BaseNotificationCallback):
    """
    A custom tf.callbacks.Callback that provides instant integration with Slack messaging app.

    Attributes:
        webhook_url (str): an Incoming Webhook URL for a given workspace and channel. You can generate one over at: <https://my.slack.com/services/new/incoming-webhook/>

    Examples:
        >>> import tensorflow as tf
        >>> from tf_notify import SlackCallback
        >>>
        >>> model = tf.keras.Sequential(name="neural-network")
        >>> model.add(tf.keras.layers.Dense(1, input_dim=784))
        >>> model.compile(
        >>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
        >>>     loss="mean_squared_error",
        >>>     metrics=["mean_absolute_error"],
        >>> )
        >>>
        >>> model.fit(
        >>>     x_train,
        >>>     y_train,
        >>>     batch_size=128,
        >>>     epochs=2,
        >>>     verbose=0,
        >>>     validation_split=0.5,
        >>>     callbacks=[
        >>>         SlackCallback(webhook_url="https://url.to/webhook")
        >>>     ],
        >>> )

    **Note**: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is
    for internal use only. They may be changed or removed at anytime.
    """

    def __init__(self, webhook_url: str):

        self.webhook_url = webhook_url
        self.slack = get_notifier("slack")

    def on_train_end(self, logs=None):

        self.slack.notify(
            message=f"model <{self.model.name}> has completed its training!",
            webhook_url=self.webhook_url,
            username="tf-notify",
            icon_url="https://www.python.org/static/favicon.ico",
        )  # TODO: deprecate Incoming WebHooks integration in favor of the new Slack SDK

tf_notify.callbacks.telegram.TelegramCallback

Bases: BaseNotificationCallback

A custom tf.callbacks.Callback that provides instant integration with Telegram messaging app.

Attributes:

Name Type Description
token str

The token of the Telegram bot you would like to use. For more on Telegram bots (and how to create one yourself) see: https://core.telegram.org/bots

chat_id int

The unique ID that corresponds to the Telegram chat you would like to send messages to. For an example on how to retrieve the chat_id for your bot, see: https://stackoverflow.com/a/32572159/10251805

Examples:

>>> import tensorflow as tf
>>> from tf_notify import TelegramCallback
>>>
>>> model = tf.keras.Sequential(name="neural-network")
>>> model.add(tf.keras.layers.Dense(1, input_dim=784))
>>> model.compile(
>>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
>>>     loss="mean_squared_error",
>>>     metrics=["mean_absolute_error"],
>>> )
>>>
>>> model.fit(
>>>     x_train,
>>>     y_train,
>>>     batch_size=128,
>>>     epochs=2,
>>>     verbose=0,
>>>     validation_split=0.5,
>>>     callbacks=[
>>>         TelegramCallback(token="XXXX:YYYY", chat_id=-1234)
>>>     ],
>>> )

Note: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is for internal use only. They may be changed or removed at anytime.

Source code in tf_notify/callbacks/telegram.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class TelegramCallback(BaseNotificationCallback):
    """
    A custom tf.callbacks.Callback that provides instant integration with Telegram messaging app.

    Attributes:
        token (str): The token of the Telegram bot you would like to use. For more on Telegram bots (and how to create one yourself) see: <https://core.telegram.org/bots>
        chat_id (int): The unique ID that corresponds to the Telegram chat you would like to send messages to. For an example on how to retrieve the `chat_id` for your bot, see: <https://stackoverflow.com/a/32572159/10251805>

    Examples:
        >>> import tensorflow as tf
        >>> from tf_notify import TelegramCallback
        >>>
        >>> model = tf.keras.Sequential(name="neural-network")
        >>> model.add(tf.keras.layers.Dense(1, input_dim=784))
        >>> model.compile(
        >>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
        >>>     loss="mean_squared_error",
        >>>     metrics=["mean_absolute_error"],
        >>> )
        >>>
        >>> model.fit(
        >>>     x_train,
        >>>     y_train,
        >>>     batch_size=128,
        >>>     epochs=2,
        >>>     verbose=0,
        >>>     validation_split=0.5,
        >>>     callbacks=[
        >>>         TelegramCallback(token="XXXX:YYYY", chat_id=-1234)
        >>>     ],
        >>> )

    **Note**: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is
    for internal use only. They may be changed or removed at anytime.
    """

    def __init__(self, token: str, chat_id: int):

        self.token = token
        self.chat_id = chat_id
        self.telegram = get_notifier("telegram")

    def on_train_end(self, logs=None):

        self.telegram.notify(
            message=f"model <{self.model.name}> has completed its training!",
            token=self.token,
            chat_id=self.chat_id,
        )

tf_notify.callbacks.email.EmailCallback

Bases: BaseNotificationCallback

A custom tf.callbacks.Callback that enables sending email messages to SMTP servers.

Keep in mind that in order to authenticate against an SMTP server (e.g. smtp.mail.yahoo.com), you will have to first generate a one-time password (or equivalent) from the respective email provider.

Attributes:

Name Type Description
to Union[str, list]

the email address of the recipient - can be a str (single recipient) or a list (multiple recipients)

**kwargs Any

Arbitrary keyword arguments - supported keys: subject, from, host, port, tls, ssl, html, login. Sensible defaults are used for message and subject, bu they can also be overrided accordingly.

Examples:

>>> import tensorflow as tf
>>> from tf_notify import EmailCallback
>>>
>>> model = tf.keras.Sequential(name="neural-network")
>>> model.add(tf.keras.layers.Dense(1, input_dim=784))
>>> model.compile(
>>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
>>>     loss="mean_squared_error",
>>>     metrics=["mean_absolute_error"],
>>> )
>>>
>>> model.fit(
>>>     x_train,
>>>     y_train,
>>>     batch_size=128,
>>>     epochs=2,
>>>     verbose=0,
>>>     validation_split=0.5,
>>>     callbacks=[
>>>         EmailCallback(
>>>             to="toaddress@yahoo.com",
>>>             from_="fromaddress@yahoo.com",
>>>             host="smtp.mail.yahoo.com",
>>>             port=465,
>>>             username="my-cool-username",
>>>             password="my-cool-password",  # one-time app password
>>>             ssl=True,
>>>         )
>>>     ],
>>> )

Note: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is for internal use only. They may be changed or removed at anytime.

Source code in tf_notify/callbacks/email.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
class EmailCallback(BaseNotificationCallback):
    """
    A custom tf.callbacks.Callback that enables sending email messages to SMTP servers.

    Keep in mind that in order to authenticate against an SMTP server (e.g. *smtp.mail.yahoo.com*),
    you will have to first generate a one-time password (or equivalent) from the respective email provider.

    Attributes:
        to (Union[str, list]): the email address of the recipient - can be a `str` (single recipient) or a `list` (multiple recipients)
        **kwargs (Any): Arbitrary keyword arguments - supported keys: `subject`, `from`, `host`, `port`, `tls`, `ssl`, `html`, `login`. Sensible defaults are used for `message` and `subject`, bu they can also be overrided accordingly.

    Examples:
        >>> import tensorflow as tf
        >>> from tf_notify import EmailCallback
        >>>
        >>> model = tf.keras.Sequential(name="neural-network")
        >>> model.add(tf.keras.layers.Dense(1, input_dim=784))
        >>> model.compile(
        >>>     optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.1),
        >>>     loss="mean_squared_error",
        >>>     metrics=["mean_absolute_error"],
        >>> )
        >>>
        >>> model.fit(
        >>>     x_train,
        >>>     y_train,
        >>>     batch_size=128,
        >>>     epochs=2,
        >>>     verbose=0,
        >>>     validation_split=0.5,
        >>>     callbacks=[
        >>>         EmailCallback(
        >>>             to="toaddress@yahoo.com",
        >>>             from_="fromaddress@yahoo.com",
        >>>             host="smtp.mail.yahoo.com",
        >>>             port=465,
        >>>             username="my-cool-username",
        >>>             password="my-cool-password",  # one-time app password
        >>>             ssl=True,
        >>>         )
        >>>     ],
        >>> )

    **Note**: Any attributes or methods prefixed with _underscores are forming a so called "private" API, and is
    for internal use only. They may be changed or removed at anytime.
    """

    def __init__(self, to: str, **kwargs: Any):

        self.to = to
        self.additional_properties = kwargs
        self.email = get_notifier("email")

    def on_train_end(self, logs=None):

        message = self.additional_properties.pop(
            "message", f"model <{self.model.name}> has completed its training!"
        )
        subject = self.additional_properties.pop(
            "subject", "New mail from 'tf-notify'!"
        )

        self.email.notify(
            message=message,
            to=self.to,
            subject=subject,
            **self.additional_properties,
        )