Skip to content
Snippets Groups Projects
Commit 3949ebee authored by SurajSSingh's avatar SurajSSingh
Browse files

Finalizing Update to Code and Models

parent f6373578
No related branches found
No related tags found
No related merge requests found
...@@ -2,3 +2,4 @@ ...@@ -2,3 +2,4 @@
.data/ .data/
*.pyc *.pyc
colab_copy.ipynb colab_copy.ipynb
.model/Viennese Poets.mp3
root"_tf_keras_sequential*{"name": "sequential", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "must_restore_from_config": false, "class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 10, 7]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "input_1"}}, {"class_name": "CustomAttention", "config": {"name": "custom_attention", "trainable": true, "dtype": "float32", "units": 32}}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, "shared_object_id": 5, "input_spec": [{"class_name": "InputSpec", "config": {"dtype": null, "shape": {"class_name": "__tuple__", "items": [null, 10, 7]}, "ndim": 3, "max_ndim": null, "min_ndim": null, "axes": {}}}], "build_input_shape": {"class_name": "TensorShape", "items": [null, 10, 7]}, "is_graph_network": true, "full_save_spec": {"class_name": "__tuple__", "items": [[{"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 10, 7]}, "float32", "input_1"]}], {}]}, "save_spec": {"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 10, 7]}, "float32", "input_1"]}, "keras_version": "2.8.0", "backend": "tensorflow", "model_config": {"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 10, 7]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "input_1"}, "shared_object_id": 0}, {"class_name": "CustomAttention", "config": {"name": "custom_attention", "trainable": true, "dtype": "float32", "units": 32}, "shared_object_id": 1}, {"class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4}]}}, "training_config": {"loss": {"class_name": "CategoricalCrossentropy", "config": {"reduction": "auto", "name": "categorical_crossentropy", "from_logits": true, "label_smoothing": 0.0, "axis": -1}, "shared_object_id": 7}, "metrics": [[{"class_name": "CategoricalCrossentropy", "config": {"name": "categorical_crossentropy", "dtype": "float32", "from_logits": true, "label_smoothing": 0}, "shared_object_id": 8}, {"class_name": "CategoricalAccuracy", "config": {"name": "categorical_accuracy", "dtype": "float32"}, "shared_object_id": 9}, {"class_name": "CategoricalHinge", "config": {"name": "categorical_hinge", "dtype": "float32"}, "shared_object_id": 10}]], "weighted_metrics": null, "loss_weights": null, "optimizer_config": {"class_name": "Adam", "config": {"name": "Adam", "learning_rate": 0.001, "decay": 0.0, "beta_1": 0.9, "beta_2": 0.999, "epsilon": 1e-07, "amsgrad": false}}}}2 root"_tf_keras_sequential*{"name": "sequential_1", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "must_restore_from_config": false, "class_name": "Sequential", "config": {"name": "sequential_1", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 5, 7]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "input_2"}}, {"class_name": "CustomAttention", "config": {"name": "custom_attention_1", "trainable": true, "dtype": "float32", "units": 32}}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}, "shared_object_id": 5, "input_spec": [{"class_name": "InputSpec", "config": {"dtype": null, "shape": {"class_name": "__tuple__", "items": [null, 5, 7]}, "ndim": 3, "max_ndim": null, "min_ndim": null, "axes": {}}}], "build_input_shape": {"class_name": "TensorShape", "items": [null, 5, 7]}, "is_graph_network": true, "full_save_spec": {"class_name": "__tuple__", "items": [[{"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 5, 7]}, "float32", "input_2"]}], {}]}, "save_spec": {"class_name": "TypeSpec", "type_spec": "tf.TensorSpec", "serialized": [{"class_name": "TensorShape", "items": [null, 5, 7]}, "float32", "input_2"]}, "keras_version": "2.8.0", "backend": "tensorflow", "model_config": {"class_name": "Sequential", "config": {"name": "sequential_1", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": {"class_name": "__tuple__", "items": [null, 5, 7]}, "dtype": "float32", "sparse": false, "ragged": false, "name": "input_2"}, "shared_object_id": 0}, {"class_name": "CustomAttention", "config": {"name": "custom_attention_1", "trainable": true, "dtype": "float32", "units": 32}, "shared_object_id": 1}, {"class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4}]}}, "training_config": {"loss": {"class_name": "CategoricalCrossentropy", "config": {"reduction": "auto", "name": "categorical_crossentropy", "from_logits": true, "label_smoothing": 0.0, "axis": -1}, "shared_object_id": 7}, "metrics": [[{"class_name": "CategoricalCrossentropy", "config": {"name": "categorical_crossentropy", "dtype": "float32", "from_logits": true, "label_smoothing": 0}, "shared_object_id": 8}, {"class_name": "CategoricalAccuracy", "config": {"name": "categorical_accuracy", "dtype": "float32"}, "shared_object_id": 9}, {"class_name": "CategoricalHinge", "config": {"name": "categorical_hinge", "dtype": "float32"}, "shared_object_id": 10}]], "weighted_metrics": null, "loss_weights": null, "optimizer_config": {"class_name": "Adam", "config": {"name": "Adam", "learning_rate": 0.0010000000474974513, "decay": 0.0, "beta_1": 0.8999999761581421, "beta_2": 0.9990000128746033, "epsilon": 1e-07, "amsgrad": false}}}}2
root.layer_with_weights-0"_tf_keras_layer*{"name": "custom_attention", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "CustomAttention", "config": {"name": "custom_attention", "trainable": true, "dtype": "float32", "units": 32}, "shared_object_id": 1, "build_input_shape": {"class_name": "TensorShape", "items": [null, 10, 7]}}2 root.layer_with_weights-0"_tf_keras_layer*{"name": "custom_attention_1", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "CustomAttention", "config": {"name": "custom_attention_1", "trainable": true, "dtype": "float32", "units": 32}, "shared_object_id": 1, "build_input_shape": {"class_name": "TensorShape", "items": [null, 5, 7]}}2
root.layer_with_weights-1"_tf_keras_layer*{"name": "dense", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "dense", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 32}}, "shared_object_id": 11}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 32]}}2 root.layer_with_weights-1"_tf_keras_layer*{"name": "dense_1", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "dense_1", "trainable": true, "dtype": "float32", "units": 4, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 2}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 3}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 4, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 32}}, "shared_object_id": 11}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 32]}}2
 -root.layer_with_weights-0.attention_score_vec"_tf_keras_layer*{"name": "attention_score_vec", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "attention_score_vec", "trainable": true, "dtype": "float32", "units": 7, "activation": "linear", "use_bias": false, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 12}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 13}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 14, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 7}}, "shared_object_id": 15}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 10, 7]}}2  -root.layer_with_weights-0.attention_score_vec"_tf_keras_layer*{"name": "attention_score_vec", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "attention_score_vec", "trainable": true, "dtype": "float32", "units": 7, "activation": "linear", "use_bias": false, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 12}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 13}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 14, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 7}}, "shared_object_id": 15}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 5, 7]}}2
 root.layer_with_weights-0.h_t"_tf_keras_layer*{"name": "last_hidden_state", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Lambda", "config": {"name": "last_hidden_state", "trainable": true, "dtype": "float32", "function": {"class_name": "__tuple__", "items": ["4wEAAAAAAAAAAAAAAAEAAAAFAAAAUwAAAHMWAAAAfABkAGQAhQJkAWQAZACFAmYDGQBTACkCTun/\n////qQApAdoBeHICAAAAcgIAAAD6TS9Vc2Vycy9ub3dhZG1pbi9Eb2N1bWVudHMvU2Nob29sIEZv\nbGRlci9DUyA0MzcvTGFiL0ZpbmFsIFByb2plY3QvYXR0ZW50aW9uLnB52gg8bGFtYmRhPhoAAABz\nAgAAABYA\n", null, null]}, "function_type": "lambda", "module": "attention", "output_shape": {"class_name": "__tuple__", "items": [7]}, "output_shape_type": "raw", "output_shape_module": null, "arguments": {}}, "shared_object_id": 16}2  root.layer_with_weights-0.h_t"_tf_keras_layer*{"name": "last_hidden_state", "trainable": true, "expects_training_arg": true, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Lambda", "config": {"name": "last_hidden_state", "trainable": true, "dtype": "float32", "function": {"class_name": "__tuple__", "items": ["4wEAAAAAAAAAAAAAAAEAAAAFAAAAUwAAAHMWAAAAfABkAGQAhQJkAWQAZACFAmYDGQBTACkCTun/\n////qQApAdoBeHICAAAAcgIAAAD6TS9Vc2Vycy9ub3dhZG1pbi9Eb2N1bWVudHMvU2Nob29sIEZv\nbGRlci9DUyA0MzcvTGFiL0ZpbmFsIFByb2plY3QvYXR0ZW50aW9uLnB52gg8bGFtYmRhPhoAAABz\nAgAAABYA\n", null, null]}, "function_type": "lambda", "module": "attention", "output_shape": {"class_name": "__tuple__", "items": [7]}, "output_shape_type": "raw", "output_shape_module": null, "arguments": {}}, "shared_object_id": 16}2
)root.layer_with_weights-0.attention_score"_tf_keras_layer*{"name": "attention_score", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dot", "config": {"name": "attention_score", "trainable": true, "dtype": "float32", "axes": [1, 2], "normalize": false}, "shared_object_id": 17, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 7]}, {"class_name": "TensorShape", "items": [null, 10, 7]}]}2 )root.layer_with_weights-0.attention_score"_tf_keras_layer*{"name": "attention_score", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dot", "config": {"name": "attention_score", "trainable": true, "dtype": "float32", "axes": [1, 2], "normalize": false}, "shared_object_id": 17, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 7]}, {"class_name": "TensorShape", "items": [null, 5, 7]}]}2
*root.layer_with_weights-0.attention_weight"_tf_keras_layer*{"name": "attention_weight", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Activation", "config": {"name": "attention_weight", "trainable": true, "dtype": "float32", "activation": "softmax"}, "shared_object_id": 18}2 *root.layer_with_weights-0.attention_weight"_tf_keras_layer*{"name": "attention_weight", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Activation", "config": {"name": "attention_weight", "trainable": true, "dtype": "float32", "activation": "softmax"}, "shared_object_id": 18}2
(root.layer_with_weights-0.context_vector"_tf_keras_layer*{"name": "context_vector", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dot", "config": {"name": "context_vector", "trainable": true, "dtype": "float32", "axes": [1, 1], "normalize": false}, "shared_object_id": 19, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 10, 7]}, {"class_name": "TensorShape", "items": [null, 10]}]}2 (root.layer_with_weights-0.context_vector"_tf_keras_layer*{"name": "context_vector", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dot", "config": {"name": "context_vector", "trainable": true, "dtype": "float32", "axes": [1, 1], "normalize": false}, "shared_object_id": 19, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 5, 7]}, {"class_name": "TensorShape", "items": [null, 5]}]}2
*root.layer_with_weights-0.attention_output"_tf_keras_layer*{"name": "attention_output", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Concatenate", "config": {"name": "attention_output", "trainable": true, "dtype": "float32", "axis": -1}, "shared_object_id": 20, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 7]}, {"class_name": "TensorShape", "items": [null, 7]}]}2 *root.layer_with_weights-0.attention_output"_tf_keras_layer*{"name": "attention_output", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Concatenate", "config": {"name": "attention_output", "trainable": true, "dtype": "float32", "axis": -1}, "shared_object_id": 20, "build_input_shape": [{"class_name": "TensorShape", "items": [null, 7]}, {"class_name": "TensorShape", "items": [null, 7]}]}2
*root.layer_with_weights-0.attention_vector"_tf_keras_layer*{"name": "attention_vector", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "attention_vector", "trainable": true, "dtype": "float32", "units": 32, "activation": "tanh", "use_bias": false, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 21}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 22}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 23, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 14}}, "shared_object_id": 24}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 14]}}2 *root.layer_with_weights-0.attention_vector"_tf_keras_layer*{"name": "attention_vector", "trainable": true, "expects_training_arg": false, "dtype": "float32", "batch_input_shape": null, "stateful": false, "must_restore_from_config": false, "class_name": "Dense", "config": {"name": "attention_vector", "trainable": true, "dtype": "float32", "units": 32, "activation": "tanh", "use_bias": false, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}, "shared_object_id": 21}, "bias_initializer": {"class_name": "Zeros", "config": {}, "shared_object_id": 22}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}, "shared_object_id": 23, "input_spec": {"class_name": "InputSpec", "config": {"dtype": null, "shape": null, "ndim": null, "max_ndim": null, "min_ndim": 2, "axes": {"-1": 14}}, "shared_object_id": 24}, "build_input_shape": {"class_name": "TensorShape", "items": [null, 14]}}2
_root.keras_api.metrics.0"_tf_keras_metric*{"class_name": "Mean", "name": "loss", "dtype": "float32", "config": {"name": "loss", "dtype": "float32"}, "shared_object_id": 25}2 droot.keras_api.metrics.0"_tf_keras_metric*{"class_name": "Mean", "name": "loss", "dtype": "float32", "config": {"name": "loss", "dtype": "float32"}, "shared_object_id": 25}2
`root.keras_api.metrics.1"_tf_keras_metric*{"class_name": "CategoricalCrossentropy", "name": "categorical_crossentropy", "dtype": "float32", "config": {"name": "categorical_crossentropy", "dtype": "float32", "from_logits": true, "label_smoothing": 0}, "shared_object_id": 8}2 eroot.keras_api.metrics.1"_tf_keras_metric*{"class_name": "CategoricalCrossentropy", "name": "categorical_crossentropy", "dtype": "float32", "config": {"name": "categorical_crossentropy", "dtype": "float32", "from_logits": true, "label_smoothing": 0}, "shared_object_id": 8}2
aroot.keras_api.metrics.2"_tf_keras_metric*{"class_name": "CategoricalAccuracy", "name": "categorical_accuracy", "dtype": "float32", "config": {"name": "categorical_accuracy", "dtype": "float32"}, "shared_object_id": 9}2 froot.keras_api.metrics.2"_tf_keras_metric*{"class_name": "CategoricalAccuracy", "name": "categorical_accuracy", "dtype": "float32", "config": {"name": "categorical_accuracy", "dtype": "float32"}, "shared_object_id": 9}2
broot.keras_api.metrics.3"_tf_keras_metric*{"class_name": "CategoricalHinge", "name": "categorical_hinge", "dtype": "float32", "config": {"name": "categorical_hinge", "dtype": "float32"}, "shared_object_id": 10}2 groot.keras_api.metrics.3"_tf_keras_metric*{"class_name": "CategoricalHinge", "name": "categorical_hinge", "dtype": "float32", "config": {"name": "categorical_hinge", "dtype": "float32"}, "shared_object_id": 10}2
\ No newline at end of file \ No newline at end of file
No preview for this file type
No preview for this file type
No preview for this file type
File added
from enum import Enum, auto from enum import Enum, auto
from datetime import time, datetime from datetime import time, datetime
from typing import Optional
class AlarmState(Enum): class AlarmState(Enum):
...@@ -12,10 +13,10 @@ class AlarmState(Enum): ...@@ -12,10 +13,10 @@ class AlarmState(Enum):
class BaseAlarmClock: class BaseAlarmClock:
_current_state: AlarmState _current_state: AlarmState
_wake_time: time _wake_time: datetime
def __init__(self, wake_time: time = datetime.now().time()): def __init__(self, wake_time: Optional[datetime] = None):
self._wake_time = wake_time self._wake_time = wake_time if wake_time else datetime.utcnow()
self._current_state = AlarmState.DEACTIVATED self._current_state = AlarmState.DEACTIVATED
@property @property
...@@ -26,7 +27,7 @@ class BaseAlarmClock: ...@@ -26,7 +27,7 @@ class BaseAlarmClock:
def wake_time(self): def wake_time(self):
return self._wake_time return self._wake_time
def set_alarm(self, wake_time: time) -> time: def set_alarm(self, wake_time: datetime) -> datetime:
# print(f"SETTING ALARM to: {wake_time}") # print(f"SETTING ALARM to: {wake_time}")
self._current_state = AlarmState.SET self._current_state = AlarmState.SET
self._wake_time = wake_time self._wake_time = wake_time
...@@ -50,5 +51,5 @@ class BaseAlarmClock: ...@@ -50,5 +51,5 @@ class BaseAlarmClock:
# print("STOPPED PLAYING ALARM") # print("STOPPED PLAYING ALARM")
self._current_state = AlarmState.DEACTIVATED if deactivate else AlarmState.SET self._current_state = AlarmState.DEACTIVATED if deactivate else AlarmState.SET
def alarm_check_reached(self, current_time: time) -> bool: def alarm_check_reached(self, current_time: datetime) -> bool:
return current_time >= self._wake_time if self._current_state is AlarmState.RUNNING else False return current_time >= self._wake_time if self._current_state is AlarmState.RUNNING else False
import subprocess
from typing import Optional
from alarm import BaseAlarmClock, AlarmState from alarm import BaseAlarmClock, AlarmState
from datetime import time, datetime from datetime import time, datetime, timezone, timedelta
from time import sleep from time import sleep
from pynput import keyboard # from pynput import keyboard
import keyboard as kb
# SONG = ".model/Viennese_Poets.mp3"
# Simple Alarm Clock has 5 functionalities: # Simple Alarm Clock has 5 functionalities:
# 1. Set Alarm Time - Set the time for the alarm to sound, does NOT make the alarm active # 1. Set Alarm Time - Set the time for the alarm to sound, does NOT make the alarm active
...@@ -10,14 +15,22 @@ from pynput import keyboard ...@@ -10,14 +15,22 @@ from pynput import keyboard
# 4. Snooze Alarm - Stop the alarm sound and wait for some time to play the alarm again # 4. Snooze Alarm - Stop the alarm sound and wait for some time to play the alarm again
# 5. Stop Alarm - If the alarm is active or is playing, stop the alarm (deactivate state) # 5. Stop Alarm - If the alarm is active or is playing, stop the alarm (deactivate state)
ALARM_TIME = time(15, 5, 0) # ALARM_TIME = datetime.combine(
SNOOZE_KEY = keyboard.Key.up # datetime.today(),
ALARM_OFF_KEY = keyboard.Key.esc # # (datetime.today() + timedelta(days=1)).date(),
# time(16, 40, 0)
# ).astimezone(tz=timezone.utc)
# SNOOZE_KEY = keyboard.Key.up
# ALARM_OFF_KEY = keyboard.Key.esc
SNOOZE_SEC = 5 SNOOZE_SEC = 5
class SimpleAlarmClock(BaseAlarmClock): class SimpleAlarmClock(BaseAlarmClock):
def set_alarm(self, wake_time: time) -> time: def __init__(self, wake_time: Optional[datetime] = None):
super().__init__(wake_time)
# self._alarm = None
def set_alarm(self, wake_time: datetime) -> datetime:
print(f"SETTING ALARM to: {wake_time}") print(f"SETTING ALARM to: {wake_time}")
return super(SimpleAlarmClock, self).set_alarm(wake_time) return super(SimpleAlarmClock, self).set_alarm(wake_time)
...@@ -27,37 +40,66 @@ class SimpleAlarmClock(BaseAlarmClock): ...@@ -27,37 +40,66 @@ class SimpleAlarmClock(BaseAlarmClock):
def sound_alarm(self) -> None: def sound_alarm(self) -> None:
print("SOUNDING ALARM") print("SOUNDING ALARM")
# if not self._alarm:
# self._alarm = subprocess.Popen(["omxplayer", "--no-keys", SONG, "&"])
super(SimpleAlarmClock, self).sound_alarm() super(SimpleAlarmClock, self).sound_alarm()
def snooze_alarm(self) -> None: def snooze_alarm(self) -> None:
print("SNOOZING ALARM") if self.current_state is AlarmState.PLAYING:
super(SimpleAlarmClock, self).snooze_alarm() print("SNOOZING ALARM")
# print(f"{self._alarm.pid}")
# if self._alarm is not None:
# subprocess.Popen(["sudo", "kill", f"{self._alarm.pid}"])
# self._alarm = None
super(SimpleAlarmClock, self).snooze_alarm()
sleep(SNOOZE_SEC)
print("UN-SNOOZING ALARM")
self.sound_alarm()
def stop_alarm(self, deactivate: bool = True) -> None: def stop_alarm(self, deactivate: bool = True) -> None:
print("STOPPING ALARM") print("STOPPING ALARM")
if self._current_state is AlarmState.PLAYING: # if self._alarm is not None:
# subprocess.Popen(["sudo", "kill", f"{self._alarm.pid}"])
# self._alarm = None
if self.current_state is AlarmState.PLAYING:
print("STOPPED PLAYING ALARM") print("STOPPED PLAYING ALARM")
super(SimpleAlarmClock, self).stop_alarm() super(SimpleAlarmClock, self).stop_alarm()
def simple_alarm_mode(self): def alarm_check_reached(self, current_time: datetime) -> bool:
# print(f"{self.wake_time}")
# print(f"{current_time}")
return super(SimpleAlarmClock, self).alarm_check_reached(current_time)
def run_simple_alarm_mode(self):
self.start_alarm() self.start_alarm()
while not self.alarm_check_reached(datetime.now().time()): kb.add_hotkey("esc", lambda: self.stop_alarm())
print(f"ALARM SLEEPING @: {datetime.now().time()}") kb.add_hotkey("space", lambda: self.snooze_alarm())
while not self.alarm_check_reached(datetime.now(tz=timezone.utc)):
print(f"ALARM SLEEPING @: {datetime.now(tz=timezone.utc)}")
sleep(1) sleep(1)
self.sound_alarm() self.sound_alarm()
while self.current_state is not AlarmState.DEACTIVATED: while self.current_state is not AlarmState.DEACTIVATED:
with keyboard.Events() as events: pass
for event in events: # with keyboard.Events() as events:
if event.key == ALARM_OFF_KEY: # for event in events:
self.stop_alarm() # if event.key == ALARM_OFF_KEY:
break # self.stop_alarm()
elif event.key == SNOOZE_KEY: # break
self.snooze_alarm() # elif event.key == SNOOZE_KEY:
sleep(SNOOZE_SEC) # self.snooze_alarm()
self.sound_alarm() # break
break
if __name__ == '__main__': if __name__ == '__main__':
alarm_clock = SimpleAlarmClock(ALARM_TIME) alarm_hour = int(input("What hour do you want the alarm to go off at? "))
alarm_clock.simple_alarm_mode() alarm_minute = int(input("What minute do you want the alarm to go off at? "))
run_alarm_today = map(
lambda response: response.lower() in ["y", "yes", "t", "true"],
input("Will the alarm run today? [y/N]")
)
alarm_time = datetime.combine(
datetime.today() if run_alarm_today else (datetime.today() + timedelta(days=1)).date(),
time(alarm_hour, alarm_minute, 0)
).astimezone(tz=timezone.utc)
alarm_clock = SimpleAlarmClock(alarm_time)
alarm_clock.run_simple_alarm_mode()
from typing import Optional, Deque
import sys
from alarm import BaseAlarmClock, AlarmState
from datetime import time, datetime, timedelta, timezone
from time import sleep
from pynput import keyboard
from collections import deque
import numpy as np
import tensorflow as tf
import vlc
# Lower threshold means it only needs to be somewhat probable to be early wake up
# >= 1 means never allow early wake up in that time
WAKE_THRESHOLD = np.array([0.5, 0.75, 0.9, 1.0])
SNOOZE_KEY = keyboard.Key.up
ALARM_OFF_KEY = keyboard.Key.esc
MODEL_MEMORY: int = 5
SECONDS_IN_MINUTE: float = 5
SNOOZE_SEC: float = 60
WAIT_SEC: float = 1
MODEL_PATH: str = ".model/attention"
VLC_INSTANCE = vlc.Instance("--input-repeat=999")
VLC_PLAYER = VLC_INSTANCE.media_player_new()
SONG = VLC_INSTANCE.media_new(".model/Viennese Poets.mp3" )
# Input Array: [minutes_since_start, current_hour_utc, current_minute_utc, awake_prob, rem_prob, light_prob, deep_prob]
# Output Array: [awake_prob, rem_prob, light_prob, deep_prob]
def softmax(arr):
val = np.exp(arr)
return val / sum(val)
def model_prediction(model, current_times_prob: Deque[np.array]) -> np.array:
# print(f"{np.array([current_times_prob]).shape = }")
if model:
prediction = model.predict(np.array([current_times_prob]))[0]
# print(f"{prediction = }")
# print(f"{softmax(prediction) = }")
return softmax(prediction)
else:
return np.zeros(4)
class SmartAlarmClock(BaseAlarmClock):
def __init__(self,
wake_time: Optional[datetime] = None,
earliest_wake: Optional[timedelta] = None,
wake_threshold: np.array = WAKE_THRESHOLD,
vlc_player=VLC_PLAYER,
default_song=SONG):
super().__init__(wake_time)
self.earliest_wake = self.wake_time
if wake_time:
self.set_alarm(wake_time, earliest_wake)
self.wake_threshold = wake_threshold
self._vlc_player = vlc_player
self.song = default_song
if self._vlc_player and self.song:
self._vlc_player.set_media(self.song)
def set_alarm(self, wake_time: datetime, earliest_wake: Optional[timedelta] = None) -> datetime:
print(f"SETTING ALARM to: {wake_time}")
returned_value = super(SmartAlarmClock, self).set_alarm(wake_time)
self.earliest_wake = wake_time - earliest_wake if earliest_wake else self.wake_time
return returned_value
def start_alarm(self) -> None:
print("STARTING ALARM")
super(SmartAlarmClock, self).start_alarm()
def sound_alarm(self, override_song=None) -> None:
print("SOUNDING ALARM")
if override_song:
self.song = override_song
if self._vlc_player:
self._vlc_player.set_media(self.song)
self._vlc_player.play()
super(SmartAlarmClock, self).sound_alarm()
def snooze_alarm(self) -> None:
print("SNOOZING ALARM")
super(SmartAlarmClock, self).snooze_alarm()
if self._vlc_player:
self._vlc_player.pause()
sleep(SNOOZE_SEC)
if self._vlc_player:
self._vlc_player.play()
print("UN-SNOOZING ALARM")
self.sound_alarm()
def stop_alarm(self, deactivate: bool = True) -> None:
print("STOPPING ALARM")
if self._vlc_player:
self._vlc_player.stop()
print("STOPPED PLAYING ALARM")
super(SmartAlarmClock, self).stop_alarm()
def check_early_alarm_reached(self, current_time: datetime, prior_prediction: np.array) -> bool:
if current_time < self.earliest_wake:
return False
return np.max(prior_prediction - self.wake_threshold) > 0
def smart_alarm_mode(self, model, model_memory=MODEL_MEMORY):
self.start_alarm()
time_queue = deque(maxlen=model_memory)
# While not filled time_queue keep appending awake data (warm-up machine)
minutes_since_start = 0
while len(time_queue) < time_queue.maxlen:
current_utc = datetime.utcnow()
time_queue.append(np.array(
[minutes_since_start, current_utc.hour, current_utc.minute, 1.0, 0.0, 0.0, 0.0]
))
# Wait a minute for next timestep
while (datetime.utcnow() - current_utc).seconds < SECONDS_IN_MINUTE:
sleep(WAIT_SEC)
minutes_since_start += 1
print(f"{time_queue = }")
# While the alarm clock is running
last_checked = datetime.utcnow()
last_prediction = model_prediction(model, time_queue)
print(f"{last_checked}: {last_prediction = }")
print(f"{self.check_early_alarm_reached(datetime.now(tz=timezone.utc), last_prediction) = }")
while self.current_state is AlarmState.RUNNING \
and not self.check_early_alarm_reached(datetime.now(tz=timezone.utc), last_prediction) \
and not self.alarm_check_reached(datetime.now(tz=timezone.utc)):
print(f"ALARM SLEEPING @: {datetime.now()}")
if (datetime.utcnow() - last_checked).seconds < SECONDS_IN_MINUTE:
last_checked = datetime.utcnow()
time_queue.append(
np.concatenate(
(
[minutes_since_start, last_checked.hour, last_checked.minute],
last_prediction
)
)
)
print(f"{time_queue = }")
last_prediction = model_prediction(model, time_queue)
print(f"{datetime.utcnow()}: {last_prediction = }")
sleep(WAIT_SEC)
# While the alarm clock is sounding off
self.sound_alarm()
while self.current_state is not AlarmState.DEACTIVATED:
with keyboard.Events() as events:
for event in events:
if event.key == ALARM_OFF_KEY:
self.stop_alarm()
break
elif event.key == SNOOZE_KEY:
self.snooze_alarm()
break
if __name__ == '__main__':
alarm_hour = int(input("What hour do you want the alarm to go off at? "))
alarm_minute = int(input("What minute do you want the alarm to go off at? "))
early_minutes = int(input("How many minute early would you have the alarm go off at? "))
run_alarm_today = map(
lambda response: response.lower() in ["y", "yes", "t", "true"],
input("Will the alarm run today? [y/N]")
)
alarm_time = datetime.combine(
datetime.today() if run_alarm_today else (datetime.today() + timedelta(days=1)).date(),
time(alarm_hour, alarm_minute, 0)
).astimezone(tz=timezone.utc)
early_time = alarm_time - timedelta(minutes=early_minutes)
alarm_clock_class = SmartAlarmClock(alarm_time, earliest_wake=timedelta(minutes=early_minutes))
ai_model = tf.keras.models.load_model(MODEL_PATH)
alarm_clock_class.smart_alarm_mode(ai_model)
from typing import Optional from typing import Optional, Deque
import sys
from alarm import BaseAlarmClock, AlarmState from alarm import BaseAlarmClock, AlarmState
from datetime import time, datetime from datetime import time, datetime, timedelta, timezone
from time import sleep from time import sleep
from pynput import keyboard # from pynput import keyboard
import keyboard as kb
from collections import deque
import numpy as np import numpy as np
# import tensorflow as tf
import tflite_runtime.interpreter as tflite
import vlc import vlc
# Lower threshold means it only needs to be somewhat probable to be early wake up
# >= 1 means never allow early wake up in that time
WAKE_THRESHOLD = np.array([0.5, 0.75, 0.9, 1.0])
SNOOZE_KEY = keyboard.Key.up # SNOOZE_KEY = keyboard.Key.up
ALARM_OFF_KEY = keyboard.Key.esc SNOOZE_KEY = "space"
SNOOZE_SEC = 5 # ALARM_OFF_KEY = keyboard.Key.esc
ALARM_OFF_KEY = "esc"
MODEL_MEMORY: int = 5
SECONDS_IN_MINUTE: float = 60
SNOOZE_SEC: float = 60
WAIT_SEC: float = 1
MODEL_PATH: str = ".model/attention_model.tflite"
VLC_INSTANCE = vlc.Instance("--input-repeat=999")
VLC_PLAYER = VLC_INSTANCE.media_player_new()
SONG = VLC_INSTANCE.media_new(".model/Viennese Poets.mp3" )
# Input Array: [minutes_since_start, current_hour_utc, current_minute_utc, awake_prob, rem_prob, light_prob, deep_prob]
# Output Array: [awake_prob, rem_prob, light_prob, deep_prob]
def softmax(arr): def softmax(arr):
...@@ -18,59 +40,159 @@ def softmax(arr): ...@@ -18,59 +40,159 @@ def softmax(arr):
return val / sum(val) return val / sum(val)
def model_prediction(model_func, current_times_prob: Deque[np.array]) -> np.array:
# print(f"Prob shape: {np.array([current_times_prob]).shape}")
if model_func:
# prediction = model.predict(np.array([current_times_prob]))[0]
prediction = model_func(x=np.array([current_times_prob]))
print(prediction)
# print(f"prediction: {prediction}")
# print(f"softmax: {softmax(prediction)}")
return softmax(prediction)
else:
return np.zeros(4)
class SmartAlarmClock(BaseAlarmClock): class SmartAlarmClock(BaseAlarmClock):
def __init__(self, wake_time: Optional[time] = None, vlc_player=None): def __init__(self,
wake_time: Optional[datetime] = None,
earliest_wake: Optional[timedelta] = None,
wake_threshold: np.array = WAKE_THRESHOLD,
vlc_player=VLC_PLAYER,
default_song=SONG):
super().__init__(wake_time)
self.earliest_wake = self.wake_time
if wake_time: if wake_time:
self.set_alarm(wake_time) self.set_alarm(wake_time, earliest_wake)
super().__init__() self.wake_threshold = wake_threshold
self._vlc_player = vlc_player
def set_alarm(self, wake_time: time) -> time: self.song = default_song
if self._vlc_player and self.song:
self._vlc_player.set_media(self.song)
def set_alarm(self, wake_time: datetime, earliest_wake: Optional[timedelta] = None) -> datetime:
print(f"SETTING ALARM to: {wake_time}") print(f"SETTING ALARM to: {wake_time}")
return super(SmartAlarmClock, self).set_alarm(wake_time) returned_value = super(SmartAlarmClock, self).set_alarm(wake_time)
self.earliest_wake = wake_time - earliest_wake if earliest_wake else self.wake_time
print(returned_value)
return returned_value
def start_alarm(self) -> None: def start_alarm(self) -> None:
print("STARTING ALARM") print("STARTING ALARM")
super(SmartAlarmClock, self).start_alarm() super(SmartAlarmClock, self).start_alarm()
def sound_alarm(self) -> None: def sound_alarm(self, override_song=None) -> None:
print("SOUNDING ALARM") print("SOUNDING ALARM")
if override_song:
self.song = override_song
if self._vlc_player:
self._vlc_player.set_media(self.song)
self._vlc_player.play()
super(SmartAlarmClock, self).sound_alarm() super(SmartAlarmClock, self).sound_alarm()
def snooze_alarm(self) -> None: def snooze_alarm(self) -> None:
print("SNOOZING ALARM") print("SNOOZING ALARM")
super(SmartAlarmClock, self).snooze_alarm() super(SmartAlarmClock, self).snooze_alarm()
if self._vlc_player:
self._vlc_player.pause()
sleep(SNOOZE_SEC)
if self._vlc_player:
self._vlc_player.play()
print("UN-SNOOZING ALARM")
self.sound_alarm()
def stop_alarm(self, deactivate: bool = True) -> None: def stop_alarm(self, deactivate: bool = True) -> None:
print("STOPPING ALARM") print("STOPPING ALARM")
if self._current_state is AlarmState.PLAYING: if self._vlc_player:
self._vlc_player.stop()
print("STOPPED PLAYING ALARM") print("STOPPED PLAYING ALARM")
super(SmartAlarmClock, self).stop_alarm() super(SmartAlarmClock, self).stop_alarm()
def smart_alarm_mode(self, model): def check_early_alarm_reached(self, current_time: datetime, prior_prediction: np.array) -> bool:
if current_time < self.earliest_wake:
return False
return np.max(prior_prediction - self.wake_threshold) > 0
def smart_alarm_mode(self, fn, model_memory=MODEL_MEMORY):
print("STARTING IN SMART MODE")
kb.on_press_key("c", lambda x: sys.exit())
kb.on_press_key(SNOOZE_KEY, lambda x: self.snooze_alarm())
kb.on_press_key(ALARM_OFF_KEY, lambda x: self.stop_alarm())
self.start_alarm() self.start_alarm()
while not self.alarm_check_reached(datetime.now().time()): time_queue = deque(maxlen=model_memory)
print(f"ALARM SLEEPING @: {datetime.now().time()}") # While not filled time_queue keep appending awake data (warm-up machine)
sleep(1) minutes_since_start = 0
while len(time_queue) < time_queue.maxlen:
current_utc = datetime.utcnow()
time_queue.append(np.array(
[minutes_since_start, current_utc.hour, current_utc.minute, 1.0, 0.0, 0.0, 0.0]
))
print(f"time_queue: {time_queue}")
# Wait a minute for next timestep
while (datetime.utcnow() - current_utc).seconds < SECONDS_IN_MINUTE:
sleep(WAIT_SEC)
minutes_since_start += 1
# While the alarm clock is running
last_checked = datetime.utcnow()
last_prediction = model_prediction(fn, time_queue)
print(f"{last_checked}: last_prediction = {last_prediction}")
print(f"check early: {self.check_early_alarm_reached(datetime.now(tz=timezone.utc), last_prediction)}")
while self.current_state is AlarmState.RUNNING \
and not self.check_early_alarm_reached(datetime.now(tz=timezone.utc), last_prediction) \
and not self.alarm_check_reached(datetime.now(tz=timezone.utc)):
print(f"ALARM SLEEPING @: {datetime.now()}")
if (datetime.utcnow() - last_checked).seconds < SECONDS_IN_MINUTE:
last_checked = datetime.utcnow()
time_queue.append(
np.concatenate(
(
[minutes_since_start, last_checked.hour, last_checked.minute],
last_prediction
)
)
)
print(f"time_queue = {time_queue}")
last_prediction = model_prediction(fn, time_queue)
print(f"{datetime.utcnow()}: last_prediction = {last_prediction}")
sleep(WAIT_SEC)
# While the alarm clock is sounding off
self.sound_alarm() self.sound_alarm()
while self.current_state is not AlarmState.DEACTIVATED: while self.current_state is not AlarmState.DEACTIVATED:
with keyboard.Events() as events: pass
for event in events: # event = kb.read_event()
if event.key == ALARM_OFF_KEY: # if event.event_type == kb.KEY_DOWN:
self.stop_alarm() # # with keyboard.Events() as events:
break # # for event in events:
elif event.key == SNOOZE_KEY: # # if event.key == ALARM_OFF_KEY:
self.snooze_alarm() # if event.name == ALARM_OFF_KEY:
sleep(SNOOZE_SEC) # self.stop_alarm()
self.sound_alarm() # break
break # elif event.name == SNOOZE_KEY:
# # elif event.key == SNOOZE_KEY:
# self.snooze_alarm()
# break
if __name__ == '__main__': if __name__ == '__main__':
alarm_hour = int(input("What hour do you want the alarm to go off at?")) alarm_hour = int(input("What hour do you want the alarm to go off at? "))
alarm_minute = int(input("What minute do you want the alarm to go off at?")) alarm_minute = int(input("What minute do you want the alarm to go off at? "))
alarm_second = int(input("What second do you want the alarm to go off at?")) early_minutes = int(input("How many minute early would you have the alarm go off at? "))
alarm_time = time(alarm_hour, alarm_minute, alarm_second) run_alarm_today = map(
alarm_clock_class = SmartAlarmClock(alarm_time) lambda response: response.lower() in ["y", "yes", "t", "true"],
ai_model = None input("Will the alarm run today? [y/N]")
alarm_clock_class.smart_alarm_mode(ai_model) )
alarm_time = datetime.combine(
datetime.today() if run_alarm_today else (datetime.today() + timedelta(days=1)).date(),
time(alarm_hour, alarm_minute, 0)
).astimezone(tz=timezone.utc)
early_time = alarm_time - timedelta(minutes=early_minutes)
alarm_clock_class = SmartAlarmClock(alarm_time, earliest_wake=timedelta(minutes=early_minutes))
print(f"Loading model from: {MODEL_PATH}")
ai_model = tflite.Interpreter(model_path=MODEL_PATH)
ai_model.allocate_tensors() # tf.keras.models.load_model(MODEL_PATH)
model_fn = ai_model.get_signature_runner()
print(f"Initialized Model")
alarm_clock_class.smart_alarm_mode(model_fn)
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment