index
int64
0
0
repo_id
stringlengths
16
145
file_path
stringlengths
27
196
content
stringlengths
1
16.7M
0
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1/tests/test_model_aggregate_viewset.py
from unittest import mock from django.urls import reverse from rest_framework.authtoken import models as auth_models from rest_framework.response import Response from rest_framework.test import APITestCase from fma_django import models from fma_django_api import utils from .utils import ClientMixin, LoginMixin class TestModelAggregateViewSet(ClientMixin, LoginMixin, APITestCase): reverse_url = "model_aggregate-list" fixtures = [ "TaskQueue_User.json", "TaskQueue_client.json", "DjangoQ_Schedule.json", "TaskQueue_FederatedModel.json", "TaskQueue_ModelAggregate.json", ] def setUp(self): for user in models.User.objects.all(): auth_models.Token.objects.get_or_create(user=user) def _validate_unauthorized(self, baseurl, client_action, request_json=None): if request_json is None: request_json = {} # validate unauthorized, no one logged in response = client_action(baseurl, format="json") self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": "Authentication credentials were not provided."}, response.json() ) # validate non-existent client can't access response = client_action( baseurl, format="json", HTTP_CLIENT_UUID="not-a-client" ) self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": '"not-a-client" is not a valid UUID.'}, response.json() ) # validate non-existent client can't access response = client_action( baseurl, format="json", HTTP_CLIENT_UUID="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ) self.assertEqual(401, response.status_code) self.assertDictEqual({"detail": "Invalid UUID"}, response.json()) # validate client user can only view if client_action != self.client.get: response = client_action( baseurl, format="json", HTTP_CLIENT_UUID="cbb6025f-c15c-4e90-b3fb-85626f7a79f1", ) self.assertEqual(403, response.status_code) self.assertDictEqual( {"detail": "You do not have permission to perform this action."}, response.json(), ) def test_list(self): baseurl = reverse(self.reverse_url) self._validate_unauthorized(baseurl, client_action=self.client.get) # validate authorized response given fixtures self.login_user(user_json={"username": "admin"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 2, "federated_model": 2, "result": "http://testserver/mediafiles/fake/path/model_aggregate/2", "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, }, { "id": 1, "federated_model": 1, "result": "http://testserver/mediafiles/fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, }, ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) self.logout_user() # validate developer only sees their own self.login_user(user_json={"username": "non_admin"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 2, "federated_model": 2, "result": "http://testserver/mediafiles/fake/path/model_aggregate/2", "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) self.logout_user() # validate client view, only model it has access to self.login_client(client_json={"uuid": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 1, "federated_model": 1, "result": "http://testserver/mediafiles/fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) self.logout_client() def test_create(self): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl, client_action=self.client.post) def test_get(self): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl + "1/", client_action=self.client.get) # validate admin access to both self.login_user(user_json={"username": "admin"}) with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([5, 2, 3]) response = self.client.get(baseurl + "1/", format="json") expected_response = { "id": 1, "federated_model": 1, "result": [5, 2, 3], "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([1, 2, 4]) response = self.client.get(baseurl + "2/", format="json") expected_response = { "id": 2, "federated_model": 2, "result": [1, 2, 4], "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate developer no access to models that they don't own self.login_user(user_json={"username": "non_admin"}) response = self.client.get(baseurl + "1/", format="json") self.assertEqual(404, response.status_code) self.assertEqual({"detail": "Not found."}, response.json()) # validate developer access to their own model with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([1, 2, 4]) response = self.client.get(baseurl + "2/", format="json") expected_response = { "id": 2, "federated_model": 2, "result": [1, 2, 4], "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate client has no access to unregistered models self.login_client(client_json={"uuid": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1"}) response = self.client.get(baseurl + "2/", format="json") self.assertEqual(404, response.status_code) self.assertEqual({"detail": "Not found."}, response.json()) # validate client has access to their registered models with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([5, 2, 3]) response = self.client.get(baseurl + "1/", format="json") expected_response = { "id": 1, "federated_model": 1, "result": [5, 2, 3], "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) def test_publish_aggregate(self): baseurl = reverse(self.reverse_url) admin_url = baseurl + "1/publish_aggregate/" dev_url = baseurl + "2/publish_aggregate/" fed_url = reverse("model-list") version_data = {"version": "2.0.0"} # validate anonymous user cannot publish a model self._validate_unauthorized(dev_url, client_action=self.client.post) # validate client cannot publish an aggregate self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) response = self.client.post(admin_url, data=version_data, format="json") self.assertEqual(403, response.status_code) expected_response = { "detail": "You do not have permission to perform this action." } self.assertDictEqual(expected_response, response.json()) # validate developer can publish aggregate owned by them self.login_user(user_json={"username": "non_admin"}) with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([5, 2, 3]) response = self.client.post(dev_url, data=version_data, format="json") self.assertEqual(201, response.status_code) expected_response = { "id": 1, "values": "/mediafiles/fake/path/model_aggregate/2", "version": "2.0.0", "created_on": response.json()["created_on"], "federated_model": 2, } self.assertDictEqual(expected_response, response.json()) # Retrieve fed model for comparison of current artifact url = fed_url + "2/get_current_artifact/" fed_response = self.client.get(url, format="json") self.assertEqual(200, fed_response.status_code) model_art_from_fed = models.ModelArtifact.objects.filter( id=expected_response["id"], version=expected_response["version"], ) self.assertEqual(1, model_art_from_fed.count()) # Check if federated model is using new published aggregate self.assertDictEqual(expected_response, fed_response.json()) fed_model = models.FederatedModel.objects.get(id=2) self.assertEqual(fed_model.current_artifact, model_art_from_fed.first()) # validate developer cannot publish aggregate not owned by them self.login_user(user_json={"username": "non_admin"}) response = self.client.post(admin_url, data=version_data, format="json") self.assertEqual(404, response.status_code) expected_response = {"detail": "Not found."} self.assertDictEqual(expected_response, response.json()) # validate developer cannot publish a non-existent aggregate self.login_user(user_json={"username": "non_admin"}) response = self.client.post( baseurl + "3/publish_aggregate/", data=version_data, format="json" ) self.assertEqual(404, response.status_code) expected_response = {"detail": "Not found."} self.assertDictEqual(expected_response, response.json()) self.logout_user() def test_pull_aggregate(self): baseurl = reverse(self.reverse_url) dev_url = baseurl + "2/" admin_url = baseurl + "1/" # validate anonymous user cannot publish a model self._validate_unauthorized(dev_url, client_action=self.client.get) # validate client cannot pull an aggregate self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) response = self.client.get(dev_url, format="json") self.assertEqual(404, response.status_code) expected_response = {"detail": "Not found."} self.assertDictEqual(expected_response, response.json()) # validate developer can pull aggregate owned by them self.login_user(user_json={"username": "non_admin"}) with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: mock_load.return_value = utils.create_model_file([5, 2, 3]) response = self.client.get(dev_url, format="json") self.assertEqual(200, response.status_code) expected_response = { "id": 2, "result": [5, 2, 3], "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "lft": 1, "rght": 2, "tree_id": 1, "level": 0, "federated_model": 2, "parent": None, } self.assertDictEqual(expected_response, response.json()) # validate developer cannot pull aggregate not owned by them response = self.client.get(admin_url, format="json") self.assertEqual(404, response.status_code) expected_response = {"detail": "Not found."} self.assertDictEqual(expected_response, response.json()) self.logout_user() def test_update_val_score(self): baseurl = reverse(self.reverse_url) dev_url = baseurl + "2/" admin_url = baseurl + "1/" # validate anonymous user cannot publish a model self._validate_unauthorized(dev_url, client_action=self.client.patch) # validate client cannot pull an aggregate self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) data = {"validation_score": 0.5} response = self.client.patch(dev_url, data=data, format="json") self.assertEqual(403, response.status_code) expected_response = { "detail": "You do not have permission to perform this action." } self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate developer can pull aggregate owned by them self.login_user(user_json={"username": "non_admin"}) data = {"validation_score": 0.5} response = self.client.patch(dev_url, data=data, format="json") self.assertEqual(200, response.status_code) expected_response = { "id": 2, "result": "http://testserver/mediafiles/fake/path/model_aggregate/2", "validation_score": 0.5, "created_on": "2023-01-20T23:08:28.712000Z", "lft": 1, "rght": 2, "tree_id": 1, "level": 0, "federated_model": 2, "parent": None, } self.assertDictEqual(expected_response, response.json()) # validate developer cannot pull aggregate not owned by them self.login_user(user_json={"username": "non_admin"}) data = {"validation_score": 0.5} response = self.client.patch(admin_url, data=data, format="json") self.assertEqual(404, response.status_code) expected_response = {"detail": "Not found."} self.assertDictEqual(expected_response, response.json()) self.logout_user() @mock.patch("rest_framework.mixins.ListModelMixin.list") def test_token_login(self, mock_list): # validate get using auth token baseurl = reverse(self.reverse_url) user_json = {"username": "non_admin"} mock_list.return_value = Response({"detail": "successful API Call"}) self.user_token_login(user_json=user_json) _ = self.client.get(baseurl) params = mock_list.call_args mock_list.assert_called_once() self.assertEqual(self.user, params[0][0].user) self.user_token_logout() def test_filters(self, *mocks): baseurl = reverse(self.reverse_url) # validate federated_model filtering queryurl = baseurl + "?federated_model=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 1, "federated_model": 1, "result": "http://testserver/mediafiles/fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) # validate federated_model=2 queryurl = baseurl + "?federated_model=2" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 2, "federated_model": 2, "result": "http://testserver/mediafiles/fake/path/model_aggregate/2", "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, }, ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) def test_ordering(self, *mocks): baseurl = reverse(self.reverse_url) # validate validation_score queryurl = baseurl + "?ordering=validation_score" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 2, "federated_model": 2, "result": "http://testserver/mediafiles/fake/path/model_aggregate/2", "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 1, }, { "id": 1, "federated_model": 1, "result": "http://testserver/mediafiles/fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "parent": None, "level": 0, "lft": 1, "rght": 2, "tree_id": 0, }, ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) def test_pagination(self, *mocks): baseurl = reverse(self.reverse_url) # setting the page size to 2 and querying for page 1 queryurl = baseurl + "?page_size=2&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.json())) # setting the page size to 1 and querying for page 1 queryurl = baseurl + "?page_size=1&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json()))
0
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1/tests/test_client_aggregate_score_viewset.py
from unittest import mock from django.urls import reverse from rest_framework.authtoken import models as auth_models from rest_framework.response import Response from rest_framework.test import APITestCase from fma_django import models from .utils import ClientMixin, LoginMixin @mock.patch( "django.core.files.storage.FileSystemStorage.save", return_value="save_create" ) class TestClientAggregateScoreViewSet(ClientMixin, LoginMixin, APITestCase): reverse_url = "client_aggregate_scores-list" fixtures = [ "TaskQueue_User.json", "TaskQueue_client.json", "DjangoQ_Schedule.json", "TaskQueue_FederatedModel.json", "TaskQueue_ModelAggregate.json", "TaskQueue_ModelUpdate.json", "TaskQueue_ClientAggregateScore.json", ] def setUp(self): for user in models.User.objects.all(): auth_models.Token.objects.get_or_create(user=user) def _validate_unauthorized(self, baseurl, client_action, request_json=None): if request_json is None: request_json = {} # validate unauthorized, no one logged in response = client_action(baseurl, format="json") self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": "Authentication credentials were not provided."}, response.json() ) # validate invalid uuid client can't access response = client_action( baseurl, format="json", HTTP_CLIENT_UUID="not-a-client" ) self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": '"not-a-client" is not a valid UUID.'}, response.json() ) # validate non-existent client can't access response = client_action( baseurl, format="json", HTTP_CLIENT_UUID="aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", ) self.assertEqual(401, response.status_code) self.assertDictEqual({"detail": "Invalid UUID"}, response.json()) def test_list(self, *mocks): baseurl = reverse(self.reverse_url) self._validate_unauthorized(baseurl, client_action=self.client.get) # validate authorized response given fixtures self.login_user(user_json={"username": "admin"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 1, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"f1_score": 0.8}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 1, }, { "id": 2, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"prec": 0.25, "rec": 0.4, "skew": 0.6}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 2, }, ] self.assertEqual(200, response.status_code) self.assertCountEqual(expected_response, response.json()) self.logout_user() # validate developer only sees their own self.login_user(user_json={"username": "non_admin"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 2, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"prec": 0.25, "rec": 0.4, "skew": 0.6}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 2, } ] self.assertEqual(200, response.status_code) self.assertCountEqual(expected_response, response.json()) self.logout_client() def test_create(self, *mocks): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl, client_action=self.client.post) # validate authorized client self.login_client(client_json={"uuid": "ab359e5d-6991-4088-8815-a85d3e413c02"}) create_data = { "client": "ab359e5d-6991-4088-8815-a85d3e413c02", "validation_results": { "f1_score": 0.8, "description": "This is a fake description", }, "aggregate": 1, } response = self.client.post(baseurl, format="json", data=create_data) cleaned_response = response.json() # rather error show up on assert, hence `None` cleaned_response.pop("created_on", None) expected_response = create_data.copy() expected_response["id"] = 3 expected_response["client"] = "ab359e5d-6991-4088-8815-a85d3e413c02" expected_response["aggregate"] = 1 expected_response["validation_results"] = { "f1_score": 0.8, "description": "This is a fake description", } self.assertEqual(201, response.status_code) self.assertDictEqual(expected_response, cleaned_response) # validate authorized client (Non-unique failure) self.login_client(client_json={"uuid": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1"}) create_data = { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"fake": 0.8}, "aggregate": 1, } response = self.client.post(baseurl, format="json", data=create_data) cleaned_response = response.json() # Client already has a result registered for this aggregate so push fails expected_response = { "non_field_errors": ["The fields aggregate, client must make a unique set."] } self.assertEqual(400, response.status_code) self.assertDictEqual(expected_response, cleaned_response) self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) # test create w/ invalid schema create_data = { "client": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "validation_results": { "f1_score": 1.2, "description": "This is a fake description", }, "aggregate": 1, } response = self.client.post(baseurl, format="json", data=create_data) cleaned_response = response.json() expected_response = { "results": [ "results did not match the required schema: {}".format( { "properties": { "f1_score": {"type": "number", "minimum": 0, "maximum": 1}, "description": {"type": "string"}, } } ) ] } self.assertEqual(400, response.status_code) self.assertDictEqual(expected_response, cleaned_response) def test_get(self, *mocks): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl + "1/", client_action=self.client.get) # validate admin access to both self.login_user(user_json={"username": "admin"}) response = self.client.get(baseurl + "1/", format="json") expected_response = { "id": 1, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"f1_score": 0.8}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 1, } response_json = response.json() self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response_json) # validate developer no access to models that they don't own self.login_user(user_json={"username": "non_admin"}) response = self.client.get(baseurl + "1/", format="json") self.assertEqual(404, response.status_code) self.assertEqual({"detail": "Not found."}, response.json()) # validate developer access to their own model response = self.client.get(baseurl + "2/", format="json") expected_response = { "id": 2, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"prec": 0.25, "rec": 0.4, "skew": 0.6}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 2, } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) @mock.patch("rest_framework.mixins.ListModelMixin.list") def test_token_login(self, mock_list, *mocks): # validate get using auth token baseurl = reverse(self.reverse_url) user_json = {"username": "non_admin"} mock_list.return_value = Response({"detail": "successful API Call"}) self.user_token_login(user_json=user_json) _ = self.client.get(baseurl) params = mock_list.call_args mock_list.assert_called_once() self.assertEqual(self.user, params[0][0].user) self.user_token_logout() def test_filters(self, *mocks): baseurl = reverse(self.reverse_url) # validate aggregate filtering queryurl = baseurl + "?aggregate=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 1, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"f1_score": 0.8}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 1, } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) # validate aggregate=2 queryurl = baseurl + "?aggregate=2" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 2, "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "validation_results": {"prec": 0.25, "rec": 0.4, "skew": 0.6}, "created_on": "2022-02-15T23:08:28.720000Z", "aggregate": 2, } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) def test_pagination(self, *mocks): baseurl = reverse(self.reverse_url) # setting the page size to 2 and querying for page 1 queryurl = baseurl + "?page_size=2&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.json())) # setting the page size to 1 and querying for page 1 queryurl = baseurl + "?page_size=1&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json()))
0
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1/tests/test_federated_model_viewset.py
from unittest import mock from django.urls import reverse from django.utils import timezone from django_q.tasks import Schedule as djanog_q_Schedule from rest_framework.authtoken import models as auth_models from rest_framework.response import Response from rest_framework.test import APITestCase from fma_django import models from fma_django_api import utils from .utils import ClientMixin, LoginMixin @mock.patch( "django.core.files.storage.FileSystemStorage.save", return_value="save_create" ) class TestFederatedModelViewSet(ClientMixin, LoginMixin, APITestCase): reverse_url = "model-list" fixtures = [ "TaskQueue_User.json", "TaskQueue_client.json", "DjangoQ_Schedule.json", "TaskQueue_FederatedModel.json", "TaskQueue_ModelAggregate.json", "TaskQueue_ModelArtifact.json", ] @classmethod def setUpTestData(cls): # create artifact relation for model 1 cls.fake_datetime = timezone.datetime( 2022, 1, 1, 0, 0, 0, tzinfo=timezone.get_current_timezone() ) fm_model = models.FederatedModel.objects.get(id=1) artifact_model = models.ModelArtifact.objects.get(id=3) fm_model.current_artifact = artifact_model with mock.patch( "django.utils.timezone.now", mock.Mock(return_value=cls.fake_datetime) ): fm_model.save() for user in models.User.objects.all(): auth_models.Token.objects.get_or_create(user=user) def _validate_unauthorized(self, baseurl, client_action, request_json=None): if request_json is None: request_json = {} # validate unauthorized, no one logged in response = client_action(baseurl, format="json") self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": "Authentication credentials were not provided."}, response.json() ) # validate client can't access self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) response = client_action(baseurl, format="json") self.assertEqual(403, response.status_code) self.assertDictEqual( {"detail": "You do not have permission to perform this action."}, response.json(), ) self.logout_client() def test_list(self, mock_save): baseurl = reverse(self.reverse_url) self._validate_unauthorized(baseurl, client_action=self.client.get) # validate authorized response given fixtures self.login_user(user_json={"username": "admin"}) response = self.client.get(baseurl, format="json") expected_response = [ { "id": 2, "allow_aggregation": False, "name": "test-non-admin", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": None, "client_agg_results_schema": None, "created_on": "2022-12-24T23:08:28.693000Z", "last_modified": "2022-12-28T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": [], }, { "id": 3, "allow_aggregation": True, "name": "test-no-aggregate", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3}, ], "items": False, }, "client_agg_results_schema": None, "created_on": "2022-12-18T23:08:28.693000Z", "last_modified": "2022-12-19T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": ["cbb6025f-c15c-4e90-b3fb-85626f7a79f1"], }, { "id": 1, "allow_aggregation": True, "requirement": "require_x_updates", "name": "test", "requirement_args": [3], "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3}, ], "items": False, }, "client_agg_results_schema": { "properties": { "f1_score": {"type": "number", "minimum": 0, "maximum": 1}, "description": {"type": "string"}, } }, "created_on": "2022-12-15T23:08:28.693000Z", "last_modified": "2022-01-01T00:00:00Z", "developer": 1, "current_artifact": 3, "clients": [ "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "ab359e5d-6991-4088-8815-a85d3e413c02", "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", ], }, ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) def test_create(self, mock_save): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl, client_action=self.client.post) # validate authorized admin self.login_user(user_json={"username": "admin"}) create_data = { "name": "create-test", "aggregator": "avg_values_if_data", "developer": 1, "initial_model": [1, 2, 3], "update_schema": {"test": 1}, "clients": [ "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "ab359e5d-6991-4088-8815-a85d3e413c02", ], } with mock.patch( "django.utils.timezone.now", mock.Mock(return_value=self.fake_datetime) ): response = self.client.post(baseurl, format="json", data=create_data) cleaned_response = response.json() expected_response = create_data.copy() expected_response.pop("initial_model", None) expected_response["id"] = 4 expected_response["furthest_base_agg"] = None expected_response["allow_aggregation"] = False # default False expected_response["requirement_args"] = None expected_response["requirement"] = "" expected_response["current_artifact"] = 4 expected_response["created_on"] = "2022-01-01T00:00:00Z" expected_response["last_modified"] = "2022-01-01T00:00:00Z" expected_response["client_agg_results_schema"] = None self.assertEqual(201, response.status_code, response.json()) self.assertDictEqual(expected_response, cleaned_response) # also assert the task is created in the db scheduled_model = djanog_q_Schedule.objects.filter( name="4 - create-test - Scheduled Aggregator" ).first() self.assertIsNotNone( scheduled_model, "Validating if schedule was created with the model." ) self.logout_user() # test developer self.login_user(user_json={"username": "non_admin"}) create_data = { "name": "non_admin create-test", "allow_aggregation": True, "aggregator": "avg_values_if_data", "developer": 2, "update_schema": None, "clients": [ "ab359e5d-6991-4088-8815-a85d3e413c02", "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", ], } with mock.patch( "django.utils.timezone.now", mock.Mock(return_value=self.fake_datetime) ): response = self.client.post(baseurl, format="json", data=create_data) cleaned_response = response.json() expected_response = create_data.copy() expected_response["id"] = 5 expected_response["furthest_base_agg"] = None expected_response["requirement_args"] = None expected_response["requirement"] = "" expected_response["current_artifact"] = None expected_response["created_on"] = "2022-01-01T00:00:00Z" expected_response["last_modified"] = "2022-01-01T00:00:00Z" expected_response["client_agg_results_schema"] = None self.assertEqual(201, response.status_code) self.assertDictEqual(expected_response, cleaned_response) # also assert the task is created in the db scheduled_model = djanog_q_Schedule.objects.filter( name="5 - non_admin create-test - Scheduled Aggregator" ).first() self.assertIsNotNone( scheduled_model, "Validating if schedule was created with the model." ) # validate furthest_base_agg fails if not > 1 create_data = { "name": "test-furthest-base-agg", "aggregator": "avg_values_if_data", "developer": 2, "initial_model": [1, 2, 3], "update_schema": {"test": 1}, "furthest_base_agg": -1, } response = self.client.post(baseurl, format="json", data=create_data) self.assertEqual(400, response.status_code) cleaned_response = response.json() self.assertDictEqual( {"furthest_base_agg": ["Ensure this value is greater than or equal to 1."]}, cleaned_response, ) # validate furthest_base_agg success if >= 1 create_data = { "name": "test-furthest-base-agg", "aggregator": "avg_values_if_data", "developer": 2, "initial_model": [1, 2, 3], "update_schema": {"test": 1}, "furthest_base_agg": 3, } response = self.client.post(baseurl, format="json", data=create_data) self.assertEqual(201, response.status_code) cleaned_response = response.json() self.assertEqual(3, cleaned_response.get("furthest_base_agg", None)) self.logout_user() # TODO: don't allow developer to set users, can force this in the # queryset for a user def test_get(self, mock_save): baseurl = reverse(self.reverse_url) # validate unauthorized self._validate_unauthorized(baseurl + "1/", client_action=self.client.get) # validate admin access to both self.login_user(user_json={"username": "admin"}) response = self.client.get(baseurl + "1/", format="json") expected_response = { "id": 1, "allow_aggregation": True, "name": "test", "requirement": "require_x_updates", "requirement_args": [3], "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3}, ], "items": False, }, "client_agg_results_schema": { "properties": { "f1_score": {"type": "number", "minimum": 0, "maximum": 1}, "description": {"type": "string"}, } }, "created_on": "2022-12-15T23:08:28.693000Z", "last_modified": "2022-01-01T00:00:00Z", "developer": 1, "current_artifact": 3, "clients": [ "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "ab359e5d-6991-4088-8815-a85d3e413c02", "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", ], } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) response = self.client.get(baseurl + "2/", format="json") expected_response = { "id": 2, "allow_aggregation": False, "name": "test-non-admin", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": None, "client_agg_results_schema": None, "created_on": "2022-12-24T23:08:28.693000Z", "last_modified": "2022-12-28T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": [], } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate developer no access to models that they don't own self.login_user(user_json={"username": "non_admin"}) response = self.client.get(baseurl + "1/", format="json") self.assertEqual(404, response.status_code) self.assertEqual({"detail": "Not found."}, response.json()) # validate developer access to their own model response = self.client.get(baseurl + "2/", format="json") expected_response = { "id": 2, "allow_aggregation": False, "name": "test-non-admin", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": None, "client_agg_results_schema": None, "created_on": "2022-12-24T23:08:28.693000Z", "last_modified": "2022-12-28T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": [], } self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) def test_register_client(self, mock_save): baseurl = reverse(self.reverse_url) url = baseurl + "1/register_client/" # validate get doesn't work response = self.client.get(url, format="json") self.assertEqual(405, response.status_code) self.assertDictEqual({"detail": 'Method "GET" not allowed.'}, response.json()) # validate bad uuid doesn't work response = self.client.post(url, format="json", HTTP_CLIENT_UUID="test") self.assertEqual(403, response.status_code) self.assertDictEqual({"detail": '"test" is not a valid UUID.'}, response.json()) # validate current UUID response = self.client.post( url, format="json", HTTP_CLIENT_UUID="531580e6-ce6c-4f01-a5aa-9ed7af5ee768" ) self.assertEqual(200, response.status_code) self.assertDictEqual( {"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}, response.json() ) # validate make new UUID fake_uuid = "000000e6-ce6c-4f01-a5aa-9ed7af5ee768" with mock.patch( "fma_django.models.Client.uuid.field.get_default", return_value=fake_uuid, ): response = self.client.post(url, format="json") self.assertEqual(200, response.status_code) self.assertDictEqual({"uuid": fake_uuid}, response.json()) # validate new is reusable url = baseurl + "2/register_client/" response = self.client.post(url, format="json", HTTP_CLIENT_UUID=fake_uuid) self.assertEqual(200, response.status_code) self.assertDictEqual({"uuid": fake_uuid}, response.json()) # validate devleoper can make a client url = baseurl + "2/register_client/" self.login_user(user_json={"username": "non_admin"}) fake_uuid = "111111e6-ce6c-4f01-a5aa-9ed7af5ee768" with mock.patch( "fma_django.models.Client.uuid.field.get_default", return_value=fake_uuid, ): response = self.client.post(url, format="json") self.assertEqual(200, response.status_code) self.assertDictEqual({"uuid": fake_uuid}, response.json()) self.logout_user() def test_get_latest_aggregate(self, mock_save): baseurl = reverse(self.reverse_url) url = baseurl + "1/get_latest_aggregate/" # validate current UUID self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = { "id": 1, "federated_model": 1, "result": "/mediafiles/fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712000Z", "lft": 1, "rght": 2, "tree_id": 0, "level": 0, "parent": None, } self.assertDictEqual(expected_response, response.json()) # validate client cannot get from model with not registered url = baseurl + "2/get_latest_aggregate/" response = self.client.get(url, format="json") self.assertEqual(403, response.status_code) self.assertDictEqual( {"detail": "You do not have permission to perform this action."}, response.json(), ) self.logout_client() # validate developer has access to own self.login_user(user_json={"username": "non_admin"}) url = baseurl + "2/get_latest_aggregate/" response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = { "id": 2, "federated_model": 2, "result": "/mediafiles/fake/path/model_aggregate/2", "validation_score": None, "created_on": "2023-01-20T23:08:28.712000Z", "lft": 1, "rght": 2, "tree_id": 1, "level": 0, "parent": None, } self.assertDictEqual(expected_response, response.json()) # validate developer cannot get from model of another url = baseurl + "1/get_latest_aggregate/" response = self.client.get(url, format="json") self.assertEqual(404, response.status_code) self.assertDictEqual({"detail": "Not found."}, response.json()) # validate when model doesn't have an aggregate models.ModelAggregate.objects.filter(federated_model=2).delete() url = baseurl + "2/get_latest_aggregate/" response = self.client.get(url, format="json") expected_response = {} self.assertEqual(200, response.status_code) self.assertDictEqual(expected_response, response.json()) self.logout_user() def test_get_current_artifact(self, mock_save): baseurl = reverse(self.reverse_url) url = baseurl + "1/get_current_artifact/" # validate current UUID self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = { "id": 3, "federated_model": 1, "values": "/mediafiles/fake/path/model_artifact/1", "version": "1.0.0", "created_on": "2022-12-12T23:55:34.066000Z", } self.assertDictEqual(expected_response, response.json()) # validate client cannot get from model with not registered url = baseurl + "2/get_current_artifact/" response = self.client.get(url, format="json") self.assertEqual(403, response.status_code) self.assertDictEqual( {"detail": "You do not have permission to perform this action."}, response.json(), ) self.logout_client() # validate developer has access to own, also check returns null if empty self.login_user(user_json={"username": "non_admin"}) url = baseurl + "2/get_current_artifact/" response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = {} self.assertDictEqual(expected_response, response.json()) # validate developer cannot get from model of another url = baseurl + "1/get_current_artifact/" response = self.client.get(url, format="json") self.assertEqual(404, response.status_code) self.assertDictEqual({"detail": "Not found."}, response.json()) self.logout_user() def test_get_latest_model(self, mock_save): baseurl = reverse(self.reverse_url) # validate client cannot get from model with not registered url = baseurl + "2/get_latest_model/" response = self.client.get(url, format="json") self.assertEqual(401, response.status_code) self.assertDictEqual( {"detail": "Authentication credentials were not provided."}, response.json() ) # validate current UUID url = baseurl + "1/get_latest_model/" self.login_client(client_json={"uuid": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768"}) with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([0.5, 1, 2]) response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = {"values": [0.5, 1, 2], "aggregate": 1} self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate developer cannot get from model of another self.login_user(user_json={"username": "non_admin"}) url = baseurl + "1/get_latest_model/" response = self.client.get(url, format="json") self.assertEqual(404, response.status_code) self.logout_user() # validate when model doesn't have an aggregate self.login_user(user_json={"username": "admin"}) models.ModelAggregate.objects.filter(federated_model=1).delete() url = baseurl + "1/get_latest_model/" with mock.patch( "django.core.files.storage.FileSystemStorage._open" ) as mock_load: # Turn aggregation results into file mock_load.return_value = utils.create_model_file([0.5, 1, 2]) response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = {"values": [0.5, 1, 2], "aggregate": None} self.assertDictEqual(expected_response, response.json()) self.logout_user() # validate developer has access to own, also check returns null if # both aggregate and artifact are empty models.ModelAggregate.objects.filter(federated_model=2).delete() models.ModelArtifact.objects.filter(federated_model=2).delete() self.login_user(user_json={"username": "non_admin"}) url = baseurl + "2/get_latest_model/" response = self.client.get(url, format="json") self.assertEqual(200, response.status_code) expected_response = {} self.assertDictEqual(expected_response, response.json()) self.logout_user() @mock.patch("rest_framework.mixins.ListModelMixin.list") def test_token_login(self, mock_list, mock_save): # validate get using auth token baseurl = reverse(self.reverse_url) user_json = {"username": "non_admin"} mock_list.return_value = Response({"detail": "successful API Call"}) self.user_token_login(user_json=user_json) _ = self.client.get(baseurl) params = mock_list.call_args mock_list.assert_called_once() self.assertEqual(self.user, params[0][0].user) self.user_token_logout() def test_filters(self, *mocks): baseurl = reverse(self.reverse_url) # validate allow_aggregation=True queryurl = baseurl + "?allow_aggregation=True" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 3, "allow_aggregation": True, "name": "test-no-aggregate", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3}, ], "items": False, }, "client_agg_results_schema": None, "created_on": "2022-12-18T23:08:28.693000Z", "last_modified": "2022-12-19T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": ["cbb6025f-c15c-4e90-b3fb-85626f7a79f1"], }, { "id": 1, "allow_aggregation": True, "requirement": "require_x_updates", "name": "test", "requirement_args": [3], "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3}, ], "items": False, }, "client_agg_results_schema": { "properties": { "f1_score": {"type": "number", "minimum": 0, "maximum": 1}, "description": {"type": "string"}, } }, "created_on": "2022-12-15T23:08:28.693000Z", "last_modified": "2022-01-01T00:00:00Z", "developer": 1, "current_artifact": 3, "clients": [ "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "ab359e5d-6991-4088-8815-a85d3e413c02", "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", ], }, ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) # validate allow_aggregation=False queryurl = baseurl + "?allow_aggregation=false" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") expected_response = [ { "id": 2, "allow_aggregation": False, "name": "test-non-admin", "requirement": "all_clients", "requirement_args": None, "aggregator": "avg_values_if_data", "furthest_base_agg": None, "update_schema": None, "client_agg_results_schema": None, "created_on": "2022-12-24T23:08:28.693000Z", "last_modified": "2022-12-28T23:08:28.693000Z", "developer": 2, "current_artifact": None, "clients": [], } ] self.assertEqual(200, response.status_code) self.assertEqual(expected_response, response.json()) def test_pagination(self, *mocks): baseurl = reverse(self.reverse_url) # setting the page size to 2 and querying for page 1 queryurl = baseurl + "?page_size=2&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(2, len(response.json())) # setting the page size to 1 and querying for page 1 queryurl = baseurl + "?page_size=1&page=1" self.login_user(user_json={"username": "admin"}) response = self.client.get(queryurl, format="json") self.assertEqual(200, response.status_code) self.assertEqual(1, len(response.json()))
0
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1
capitalone_repos/federated-model-aggregation/connectors/django/fma_django_api/v1/tests/utils.py
from fma_django import models class LoginMixin: def login_user(self, user_json): """Logs in user for authentication.""" self.user = models.User.objects.get_or_create(**user_json)[0] self.client.force_login(self.user) def logout_user(self): """Logs out user from authentication.""" self.client.logout() self.user = None def user_token_login(self, user_json): """Logs out user from authentication using tokens""" self.user = models.User.objects.get_or_create(**user_json)[0] self.client.credentials(HTTP_AUTHORIZATION="Token " + self.user.auth_token.key) def user_token_logout(self): """Logs out user from authentication using token.""" self.client.credentials() self.user = None class ClientMixin: def get_client_header(self, uuid): return {"CLIENT-UUID": uuid} def login_client(self, client_json): """Logs in user for authentication.""" self.user_client = models.Client.objects.get_or_create(**client_json)[0] self.client.credentials(HTTP_CLIENT_UUID=self.user_client.uuid) def logout_client(self): """Logs out user from authentication.""" self.client.credentials() self.user_client = None
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/security_groups.tf
# SG resource definitions resource "aws_security_group" "lambda_agg_sg" { name = "${var.application_base_name}-lambda-agg-sg" description = "Security Group for the Aggregator Lambda" vpc_id = local.vpc_id tags = var.tags } resource "aws_security_group" "alb_sg" { name = "${var.application_base_name}-alb-sg" description = "Security Group for the ALB" vpc_id = local.vpc_id tags = var.tags } resource "aws_security_group" "lambda_api_sg" { name = "${var.application_base_name}-lambda-api-sg" description = "Security Group for the API Lamdba" vpc_id = local.vpc_id tags = var.tags } resource "aws_security_group" "rds_sg" { name = "${var.application_base_name}-rds-sg" description = "Security Group for the RDS" vpc_id = local.vpc_id tags = var.tags } # Inbound/Outbound SG rules for alb to lambda_api resource "aws_security_group_rule" "alb_to_lambda_api_outbound_sg_rule" { type = "egress" from_port = 443 to_port = 443 protocol = "tcp" security_group_id = aws_security_group.alb_sg.id source_security_group_id = aws_security_group.lambda_api_sg.id } resource "aws_security_group_rule" "alb_to_lambda_api_inbound_sg_rule" { type = "ingress" from_port = 443 to_port = 443 protocol = "tcp" security_group_id = aws_security_group.lambda_api_sg.id source_security_group_id = aws_security_group.alb_sg.id } # Inbound/Outbound SG rules for lambda_api to rds resource "aws_security_group_rule" "lambda_api_to_rds_outbound_sg_rule" { type = "egress" from_port = 5432 to_port = 5432 protocol = "tcp" security_group_id = aws_security_group.lambda_api_sg.id source_security_group_id = aws_security_group.rds_sg.id } resource "aws_security_group_rule" "lambda_api_to_rds_inbound_sg_rule" { type = "ingress" from_port = 5432 to_port = 5432 protocol = "tcp" security_group_id = aws_security_group.rds_sg.id source_security_group_id = aws_security_group.lambda_api_sg.id } # Inbound/Outbound SG rules for lambda_agg to rds resource "aws_security_group_rule" "lambda_agg_to_rds_outbound_sg_rule" { type = "egress" from_port = 5432 to_port = 5432 protocol = "tcp" security_group_id = aws_security_group.lambda_agg_sg.id source_security_group_id = aws_security_group.rds_sg.id } resource "aws_security_group_rule" "lambda_agg_to_rds_inbound_sg_rule" { type = "ingress" from_port = 5432 to_port = 5432 protocol = "tcp" security_group_id = aws_security_group.rds_sg.id source_security_group_id = aws_security_group.lambda_agg_sg.id }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/utils.tf
data "archive_file" "zip_aggregator" { type = "zip" source_dir = "../aggregator/.aws-sam/build/FmaServerless" output_path = "./python/aggregator.zip" depends_on = [random_string.zip_file_update_tag] excludes = ["terraform_deploy"] } data "archive_file" "zip_api_service" { type = "zip" source_dir = "../api_service/.aws-sam/build/FmaServerless" output_path = "./python/api-service.zip" depends_on = [random_string.zip_file_update_tag] excludes = ["terraform_deploy"] } resource "random_string" "zip_file_update_tag" { length = 16 special = false }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/api_service.tf
resource "aws_lambda_function" "fma_serverless_api_service" { filename = data.archive_file.zip_api_service.output_path function_name = local.resource_names.api_service_name source_code_hash = data.archive_file.zip_api_service.output_base64sha256 role = local.roles.api_service_role handler = "service_initialization.handler" runtime = "python3.9" description = var.api_service_defaults["description"] reserved_concurrent_executions = var.api_service_defaults["reserved_concurrent_executions"] timeout = var.api_service_defaults["timeout"] memory_size = var.api_service_defaults["memory_size"] tags = var.tags publish = true vpc_config { security_group_ids = local.security_groups.api_service_sg_ids subnet_ids = var.subnet_ids } environment { variables = merge(local.api_env_vars, local.db_specific_env_vars) } layers = local.resource_arns.secrets_manager_arns depends_on = [ aws_db_instance.metadata_db, aws_s3_bucket.model_data_db ] }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/model_data_db.tf
resource "aws_s3_bucket_policy" "allow_access_to_metadata_db" { bucket = aws_s3_bucket.model_data_db.id policy = data.aws_iam_policy_document.s3_access_policy.json depends_on = [ aws_iam_role.fma_serverless_scheduled_role ] } resource "aws_s3_bucket" "model_data_db" { bucket = local.resource_names.model_data_db_name tags = var.tags server_side_encryption_configuration { rule { apply_server_side_encryption_by_default { kms_master_key_id = aws_kms_key.model_data_db_kms_key.arn sse_algorithm = var.model_data_db_defaults["sse_algorithm"] } } } } resource "aws_s3_bucket_acl" "model_data_db_acl" { bucket = aws_s3_bucket.model_data_db.id acl = var.model_data_db_defaults["main_acl"] } resource "aws_s3_bucket_versioning" "model_data_db_versioning" { bucket = aws_s3_bucket.model_data_db.id versioning_configuration { status = var.model_data_db_defaults["versiong_config_status"] } } resource "aws_kms_key" "model_data_db_kms_key" { description = var.model_data_db_defaults["kms_key_description"] deletion_window_in_days = 10 } resource "aws_s3_bucket" "model_data_db_log_bucket" { bucket = local.resource_names.model_data_log_db_name } resource "aws_s3_bucket_acl" "model_data_db_log_bucket_acl" { bucket = aws_s3_bucket.model_data_db_log_bucket.id acl = var.model_data_db_defaults["log_acl"] } resource "aws_s3_bucket_logging" "model_data_db_log_bucket_link" { bucket = aws_s3_bucket.model_data_db.id target_bucket = aws_s3_bucket.model_data_db_log_bucket.id target_prefix = var.model_data_db_defaults["log_target_prefix"] }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/Tips_and_Best_Practice_Notes.md
# Terraform Notes and Best Practices ## API Gateway Setup Currently, (01/04/22) there is no terraform file/object that creates the API gateway that allows the developer or clients access to the service, this would need to be explicitly created by the user of the service. * [Explicitly create the API Gateway in the aws client](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop.html) * [Create the API Gateway using Terraform](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/api_gateway_rest_api) ## Secrets Manager Key Rotation Currently, (01/04/22) the terraform initialization of the secrets keys used to create the metadata db are statically generated and are not rotated. This is not the recommended way to set up keys for your database as the keys should be rotated to ensure secure usage and access of the database. * [Implementating Rotating keys in terraform](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/secretsmanager_secret_rotation)
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/iam_lambda.tf
resource "aws_iam_role_policy" "fma_serverless_s3_policy" { name = "${var.application_base_name}-s3-policy" role = aws_iam_role.fma_serverless_scheduled_role.id policy = data.aws_iam_policy_document.s3_access_policy.json } resource "aws_iam_role_policy" "fma_serverless_scheduled_policy" { name = "${var.application_base_name}-scheduled-policy" role = aws_iam_role.fma_serverless_scheduled_role.id policy = data.aws_iam_policy_document.scheduling_policy.json } resource "aws_iam_role_policy" "fma_serverless_secrects_manager_policy" { name = "${var.application_base_name}-secrets-manager" role = aws_iam_role.fma_serverless_scheduled_role.id policy = data.aws_iam_policy_document.secrets_policy.json } resource "aws_iam_role" "fma_serverless_scheduled_role" { name = "${var.application_base_name}-scheduled-role" assume_role_policy = file("iam/scheduled/dev/trust.json") tags = var.tags }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/api_service_tg.tf
resource aws_lb_target_group api_service_taget_group { name = "${aws_lambda_function.fma_serverless_api_service.function_name}-tg" target_type = var.api_service_taget_group_defaults["target_type"] port = var.api_service_taget_group_defaults["port"] tags = var.tags health_check { enabled = true interval = 35 path = "/api/v1" } } resource aws_lambda_permission lambda_target_group_permission { statement_id = var.lambda_target_group_permission_defaults["statement_id"] action = var.lambda_target_group_permission_defaults["action"] function_name = aws_lambda_function.fma_serverless_api_service.function_name principal = var.lambda_target_group_permission_defaults["principal"] source_arn = aws_lb_target_group.api_service_taget_group.arn } resource "aws_lb_target_group_attachment" "tg_to_lambda" { target_group_arn = aws_lb_target_group.api_service_taget_group.arn target_id = aws_lambda_function.fma_serverless_api_service.arn depends_on = [aws_lambda_permission.lambda_target_group_permission] }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/deploy_vars.tf
variable "application_base_name" { type = string default = "fma-serverless" } # Deployment defaults for Provider variable "provider_defaults" { type = map default = { region = "<insert region here>" profile = "<Insert profile name here>" } } variable "shared_credentials_files_default" { type = list default = ["<insert path to aws credentials here>"] } # Deployment defaults for model data database variable "model_data_db_defaults" { type = map default = { sse_algorithm = "aws:kms" main_acl = "private" versiong_config_status = "Enabled" kms_key_description = "This key is used to encrypt bucket objects" log_acl = "log-delivery-write" log_target_prefix = "log/" } } # Deployment defaults for aggregator variable "aggregator_defaults" { type = map default = { description = "Lambda function for fma-serverless aggregator" reserved_concurrent_executions = 10 timeout = 30 memory_size = 256 } } # Deployment defaults for api service variable "api_service_defaults" { type = map default = { description = "Lambda function for fma-serverless api service" reserved_concurrent_executions = 10 timeout = 300 memory_size = 256 } } # Deployment defaults for api service's alb variable "api_service_alb_defaults" { type = map default = { internal = true load_balancer_type = "application" enable_deletion_protection = false } } # Deployment defaults for api service's alb listeners variable "api_service_listeners_defaults" { type = map default = { unsecure_port = "80" unsecure_protocol = "HTTP" secure_port = "443" secure_protocol = "HTTPS" ssl_policy = "<insert ssl policy>" certificate_arn = "<insert cert arn>" } } # Deployment defaults for api service's target groups variable "api_service_taget_group_defaults" { type = map default = { target_type = "lambda" port = 443 } } # Deployment defaults for api service's target group permissions variable "lambda_target_group_permission_defaults" { type = map default = { statement_id = "AllowExecutionFromALB" action = "lambda:InvokeFunction" principal = "elasticloadbalancing.amazonaws.com" } } # Deployment defaults for metadata database variable "metadata_db_defaults" { type = map default = { allocated_storage = 20 max_allocated_storage = 1000 engine = "postgres" engine_version = "14.3" instance_class = "db.t4g.micro" username = "username" parameter_group_name = "<insert parameter group name>" skip_final_snapshot = true availability_zone = "<insert AZ>" iam_database_authentication_enabled = true port = "5432" storage_encrypted = true db_subnet_group_name = "<insert subgroup name>" } } # General reuse variables variable "tags" { type = map default = {} } variable "subnet_ids" { type = list default = [] } locals { roles = { aggregator_role = aws_iam_role.fma_serverless_scheduled_role.arn api_service_role = aws_iam_role.fma_serverless_scheduled_role.arn } resource_arns = { secrets_manager_arns = [aws_secretsmanager_secret.fma_db_secrets_manager.arn] } resource_names = { metadata_db_name = "${var.application_base_name}-metadata-database" api_service_name = "${var.application_base_name}-api-service" aggregator_name = "${var.application_base_name}-aggregator" model_data_db_name = "${var.application_base_name}-model-storage" db_secrets_manager_name = "${var.application_base_name}-db-password" model_data_log_db_name = "${var.application_base_name}-model-storage-log" api_service_alb_name = "${var.application_base_name}-api-service-alb" metadata_db_identifier = "${var.application_base_name}-metadata-storage" metadata_db_parameter_group_name = "${var.application_base_name}-metadata-db-param-group" aggregator_alias_name = "${var.application_base_name}-aggregator-alias" } db_specific_env_vars = { FMA_DATABASE_NAME = local.resource_names.metadata_db_name FMA_DATABASE_HOST = aws_db_instance.metadata_db.address FMA_DATABASE_PORT = "5432" FMA_DB_SECRET_PATH = "<insert path to secrets here>" } agg_env_vars = { ENV = "dev" DJANGO_SETTINGS_MODULE = "federated_learning_project.settings_remote" PARAMETERS_SECRETS_EXTENSION_HTTP_PORT = "2773" FMA_DATABASE_NAME = local.resource_names.metadata_db_name FMA_DATABASE_HOST = aws_db_instance.metadata_db.address FMA_DATABASE_PORT = "5432" FMA_DB_SECRET_PATH = "<insert path to secrets here>" FMA_SETTINGS_MODULE = "federated_learning_project.fma_settings" } api_env_vars = { ENV = "dev" DJANGO_SETTINGS_MODULE = "federated_learning_project.settings_remote" FMA_DATABASE_NAME = local.resource_names.metadata_db_name FMA_DATABASE_HOST = aws_db_instance.metadata_db.address FMA_DATABASE_PORT = "5432" LAMBDA_INVOKED_FUNCTION_ARN = aws_lambda_function.fma_serverless_aggregator.arn FMA_DB_SECRET_PATH = "<insert path to secrets here>" PARAMETERS_SECRETS_EXTENSION_HTTP_PORT = "2773" FMA_SETTINGS_MODULE = "federated_learning_project.fma_settings" } security_groups = { aggregator_sg_ids = [aws_security_group.lambda_agg_sg] api_service_sg_ids = [aws_security_group.lambda_api_sg] api_service_alb_sg_ids = [aws_security_group.alb_sg] metadata_db_sg_ids = [aws_security_group.rds_sg] } metadata_db_tags = {tags = "<insert metadata db specific tags>"} vpc_id = "<insert vpc id>" db_parameter_family = "postgres14" db_password = data.aws_secretsmanager_secret_version.password event_bridge_rule_source_arn = "<insert base arn path for event bridge rule>/fma-scheduled-model-*-dev" }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/secrets_manager.tf
resource "random_password" "fma_secrets_db_pass"{ length = 16 special = true override_special = "_!%^" } resource "aws_secretsmanager_secret" "fma_db_secrets_manager" { name = local.resource_names.model_data_db_name } resource "aws_secretsmanager_secret_version" "password" { secret_id = aws_secretsmanager_secret.fma_db_secrets_manager.id secret_string = random_password.fma_secrets_db_pass.result }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/metadata_db.tf
data "aws_secretsmanager_secret" "local_path_to_password" { name = local.resource_names.model_data_db_name } data "aws_secretsmanager_secret_version" "password" { secret_id = data.aws_secretsmanager_secret.local_path_to_password } resource "aws_db_parameter_group" "metadata_db_parameter_group" { count = var.metadata_db_parameters == [] ? 1 : 0 name = local.resource_names.metadata_db_parameter_group_name family = local.db_parameter_family dynamic "parameter" { for_each = var.metadata_db_parameters content { name = parameter.value.name value = parameter.value.value } } } resource "aws_db_instance" "metadata_db" { allocated_storage = var.metadata_db_defaults["allocated_storage"] max_allocated_storage = var.metadata_db_defaults["max_allocated_storage"] db_name = replace("${local.resource_names.metadata_db_name}", "-", "_") engine = var.metadata_db_defaults["engine"] engine_version = var.metadata_db_defaults["engine_version"] instance_class = var.metadata_db_defaults["instance_class"] username = var.metadata_db_defaults["username"] password = local.db_password parameter_group_name = (length(aws_db_parameter_group.metadata_db_parameter_group) == 1 ? aws_db_parameter_group.metadata_db_parameter_group[ length(aws_db_parameter_group.metadata_db_parameter_group) ].name: "" ) skip_final_snapshot = var.metadata_db_defaults["skip_final_snapshot"] availability_zone = var.metadata_db_defaults["availability_zone"] iam_database_authentication_enabled = var.metadata_db_defaults["iam_database_authentication_enabled"] port = var.metadata_db_defaults["port"] storage_encrypted = var.metadata_db_defaults["storage_encrypted"] db_subnet_group_name = var.metadata_db_defaults["db_subnet_group_name"] tags = merge(var.tags, local.metadata_db_tags) vpc_security_group_ids = local.security_groups.metadata_db_sg_ids identifier = local.resource_names.metadata_db_identifier copy_tags_to_snapshot = true enabled_cloudwatch_logs_exports = [ "postgresql", "upgrade", ] }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/aggregator.tf
resource "aws_lambda_function" "fma_serverless_aggregator" { filename = data.archive_file.zip_aggregator.output_path function_name = local.resource_names.aggregator_name source_code_hash = data.archive_file.zip_aggregator.output_base64sha256 role = local.roles.aggregator_role handler = "app.handler" runtime = "python3.9" description = var.aggregator_defaults["description"] reserved_concurrent_executions = var.aggregator_defaults["reserved_concurrent_executions"] timeout = var.aggregator_defaults["timeout"] memory_size = var.aggregator_defaults["memory_size"] tags = var.tags publish = true vpc_config { security_group_ids = local.security_groups.aggregator_sg_ids subnet_ids = var.subnet_ids } environment { variables = merge(local.agg_env_vars, local.db_specific_env_vars) } layers = local.resource_arns.secrets_manager_arns depends_on = [ aws_db_instance.metadata_db, aws_s3_bucket.model_data_db ] } resource "aws_lambda_alias" "fma_serverless_aggregator_alias" { name = local.resource_names.aggregator_alias_name function_name = aws_lambda_function.fma_serverless_aggregator.arn function_version = "$LATEST" } resource "aws_lambda_permission" "allow_event_bridge_execution" { statement_id = "AllowExecutionFromEventBridge" action = "lambda:InvokeFunction" function_name = aws_lambda_function.fma_serverless_aggregator.function_name principal = "events.amazonaws.com" source_arn = local.event_bridge_rule_source_arn qualifier = aws_lambda_alias.fma_serverless_aggregator_alias.name }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/provider.tf
provider "aws" { region = var.provider_defaults.region shared_credentials_files = var.shared_credentials_files_default profile = var.provider_defaults.profile }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/api_service_alb.tf
resource "aws_lb" "api_service_alb" { name = local.resource_names.api_service_alb_name internal = var.api_service_alb_defaults["internal"] load_balancer_type = var.api_service_alb_defaults["load_balancer_type"] security_groups = local.security_groups.api_service_alb_sg_ids subnets = var.subnet_ids enable_deletion_protection = var.api_service_alb_defaults["enable_deletion_protection"] tags = var.tags } resource "aws_lb_listener" "api_service_listener" { load_balancer_arn = aws_lb.api_service_alb.arn port = var.api_service_listeners_defaults["unsecure_port"] protocol = var.api_service_listeners_defaults["unsecure_protocol"] default_action { type = "forward" target_group_arn = aws_lb_target_group.api_service_taget_group.arn } } resource "aws_lb_listener" "api_service_listener_secure" { load_balancer_arn = aws_lb.api_service_alb.arn port = var.api_service_listeners_defaults["secure_port"] protocol = var.api_service_listeners_defaults["secure_protocol"] ssl_policy = var.api_service_listeners_defaults["ssl_policy"] certificate_arn = var.api_service_listeners_defaults["certificate_arn"] default_action { type = "forward" target_group_arn = aws_lb_target_group.api_service_taget_group.arn } }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/policies.tf
data "aws_iam_policy_document" "s3_access_policy" { statement { sid = "DenyAccessForAllExceptFMALambdas" principals { type = "AWS" identifiers = ["*"] } effect = "Deny" actions = ["s3:*"] resources = [ "arn:aws:s3:::{var.application_base_name}-storage", "arn:aws:s3:::{var.application_base_name}-storage/*" ] condition { test = "StringNotLike" variable = "aws:arn" values = [aws_iam_role.fma_serverless_scheduled_role.arn] } } } data "aws_iam_policy_document" "logging_policy" { statement { sid = "AllowNetorkModsForLambda" effect = "Allow" resources = ["*"] actions = [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ] } statement { sid = "AllowCreateLogsLambda" effect = "Allow" resources = [ aws_lambda_function.fma_serverless_api_service.arn, aws_lambda_function.fma_serverless_aggregator.arn ] actions = [ "logs:CreateLogGroup", "logs:DescribeLogStreams", "logs:CreateLogStream", "logs:PutLogEvents" ] } } data "aws_iam_policy_document" "secrets_policy" { statement { sid = "AllowSecretManagerAccessAndModificationForLambda" effect = "Allow" resources = [ aws_lambda_function.fma_serverless_api_service.arn, aws_lambda_function.fma_serverless_aggregator.arn ] actions = [ "secretsmanager:GetSecretValue" ] } } data "aws_iam_policy_document" "scheduling_policy" { statement { sid = "AllowScheduledRuleForAggregationLambda" effect = "Allow" resources = [ aws_lambda_function.fma_serverless_api_service.arn, ] actions = [ "events:DescribeRule", "events:DisableRule", "events:EnableRule", "events:DeleteRule" ] } statement { sid = "AllowPutRuleForAggregationLambda" effect = "Allow" resources = [ aws_lambda_function.fma_serverless_api_service.arn, ] actions = [ "events:PutRule", "events:PutTargets", "events:TagResource" ] condition { test = "ForAllValues:ArnEquals" variable = "events:TargetArn" values = [aws_iam_role.fma_serverless_scheduled_role.arn] } } }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/terraform_deploy/README.md
### Deployment Setup #### Terraform file setup Each component of the FMA service is laid out as a customizable `.tf` file within the `terraform_deploy/` directory. Most variables can be modified in the `deploy_vars.tf`. <br> The variables that *MUST* be modified are: * `provider_defaults/region` - Region in which you wish to host the FMA service * `provider_defaults/profile` - Name of your AWS profile with which you wish to create the service * `shared_credentials_files_default` - Local file with which to reference the policy/role info * `api_service_listeners_defaults/certificate_arn` - The certificate used to validate the ssl policy used in api service listener * `tags` - Custom tags to add to your resources (optional to fill out) * `vpc_security_group_ids` - Security groups associated with the vpc you are using (optional to fill out) * `subnet_ids` - Subnet ids used in the vpc you are using (optional to fill out) * `metadata_db_defaults/username` - The username to be associated with access to the metadata db * `metadata_db_defaults/parameter_group_name` - The name of the parameter group that is used to access the metadata database * `metadata_db_defaults/availability_zone` - The availability zone of your database * `metadata_db_defaults/db_subnet_group_name` - The name of the subnet group that can access the metadata db * `api_service_listeners_defaults/ssl_policy` - The ssl policy required for listeners * `locals/api_env_vars/FMA_DB_SECRET_PATH` - The path used to store database secrets permissions definitions for api service lambda * `locals/agg_env_vars/FMA_DB_SECRET_PATH` - The path used to store database secrets permissions definitions for aggregator lambda * `locals/db_parameter_family` - The family of database parameters used to initialize the database (dependent on `locals/db_parameters`) * `locals/metadata_db_tags` - The tags used in the deployment of the RDS metadata database * `locals/vpc_id` - The id of the vpc to which the service deploys * `locals/event_bridge_rule_source_arn` - The base ARN path for the rule, rather than the full string * `parameters` - The database parameters used to initialize the database (list of maps that require a `name` and `value` field) can be an empty list ***NOTE: If deployment fails, terraform should inform you of any issues that may have occurred and will most likely be due to these values listed above.*** <br> ### Standard Deployment To deploy the entire service, run the following commands from the root of the repository: ``` cd terraform_deploy terraform init terraform apply ``` ### Optional Commands There are a few other optional commands and parameters that a user can use as part of their deployment. #### *Want to see exactly what will be run before running your deployment?* Users can validate what terraform will execute before running the deployment with the following command: ``` terraform plan ``` #### *Want to only deploy a particular part of the service?* To see a list of resources available in this terraform state users can run the following command. This will allow users to see the particular naming of their resources. ``` terraform state list ``` The user can deploy specific parts of the service by using the `-target` flag and specifying a resource from the output of the command above. See the following command. ``` terraform apply -target <target> ``` #### *Want to auto-approve on apply?* To auto-approve the prompt raised by terraform apply, users can also specify a flag that will automatically aceept changes on apply. ``` terraform apply -auto-approve ``` ***NOTE: It is recommended that the `Tips_and_Best_Practice_Notes.md` is read and changes are made to ensure a secure deployment that follows industry best practices***
0
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled/dev/trust.json
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] }
0
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled/dev/s3-policy.json
{ "Version": "2012-10-17", "Statement": [ { "Sid": "S3ReadObject", "Effect": "Allow", "Action": [ "s3:GetObject", "s3:GetObjectAcl", "s3:GetObjectTagging" ], "Resource": [ "<Arn of s3 resource>" ] }, { "Sid": "S3WriteObject", "Effect": "Allow", "Action": [ "s3:AbortMultipartUpload", "s3:DeleteObject", "s3:PutObject", "s3:PutObjectAcl" ], "Resource": [ "<Arn of s3 resource>" ] }, { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation" ], "Resource": [ "<Arn of s3 resource>" ] } ] }
0
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled/dev/logging-policy.json
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "ec2:CreateNetworkInterface", "ec2:DescribeNetworkInterfaces", "ec2:DeleteNetworkInterface" ], "Resource": [ "*" ] }, { "Effect": "Allow", "Action": [ "logs:CreateLogGroup", "logs:DescribeLogStreams" ], "Resource": [ "<Arn of resource>" ] }, { "Effect": "Allow", "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": [ "<Arn of logging resource>" ] } ] }
0
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled
capitalone_repos/federated-model-aggregation/terraform_deploy/iam/scheduled/dev/scheduled-event-policy.json
{ "Version": "2012-10-17", "Statement": [ { "Sid": "AllowScheduledRuleForAggregationLambda", "Effect": "Allow", "Action":[ "events:DescribeRule", "events:DisableRule", "events:EnableRule", "events:DeleteRule"], "Resource": "<Arn of scheduling resource>" }, { "Sid": "AllowPutRuleForAggregationLambda", "Effect": "Allow", "Action": ["events:PutRule", "events:PutTargets", "events:TagResource"], "Resource": "<Arn of scheduling resource>", "Condition": { "ForAllValues:ArnEquals": { "events:TargetArn": "<Arn of scheduling resource>::LIVE_TRAFFIC" } } } ] }
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/examples/.pre-commit-config.yaml
files: examples repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: end-of-file-fixer name: EOF for examples - id: trailing-whitespace name: Whitespace for examples - id: check-ast name: Check python parse valid for examples - id: check-docstring-first name: Check docstring first in examples - repo: https://github.com/psf/black rev: 22.8.0 hooks: - id: black name: Black for examples - repo: https://github.com/pycqa/flake8 rev: '5.0.4' # pick a git hash / tag to point to hooks: - id: flake8 name: Flake8 for examples files: examples/ # https://github.com/PyCQA/pydocstyle/issues/68 for ignore of D401 # https://github.com/OCA/maintainer-quality-tools/issues/552 for ignore of W503 args: ["--config=examples/setup.cfg", "--ignore=D401,W503"] additional_dependencies: [flake8-docstrings] exclude: (^.*/tests|^.*/__init__.py) - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort name: isort for examples
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/examples/setup.cfg
[metadata] name = examples description = Used as storage for usage examples of the FMA service long_description = file: README.md license = Apache License 2.0 classifiers = Framework :: Django Framework :: Django :: 4.* Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Information Technology Intended Audience :: Science/Research Topic :: Education Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Information Analysis License :: OSI Approved :: Apache Software License Programming Language :: Python :: 3 [flake8] max-line-length = 88 extend-ignore = E203 [isort] multi_line_output=3 skip=iam/ profile=black skip_glob = clients/*,aggregator/*,api_service/*,fma-core/*,connectors/*
0
capitalone_repos/federated-model-aggregation/examples
capitalone_repos/federated-model-aggregation/examples/django-deployment/manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "federated_learning_project.settings_local" ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
0
capitalone_repos/federated-model-aggregation/examples
capitalone_repos/federated-model-aggregation/examples/django-deployment/Pipfile
[[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" fma-django = {extras = ["api"], path = "./artifacts/fma_django-0.0.1-py3-none-any.whl"} fma-core = {path = "./artifacts/fma_core-0.0.1-py3-none-any.whl"} [dev-packages] pytest = "*" pytest-cov = "*" black = "*" flake8 = "*" pre-commit = "*" isort = "*" [requires] python_version = "3"
0
capitalone_repos/federated-model-aggregation/examples
capitalone_repos/federated-model-aggregation/examples/django-deployment/README.md
# Django Deployment Example A service for aggregating model updates into a single update using Django. ## Local Backend Setup (Quick setup) 1. Setup a Pipenv with all required packages for service startup with: ```console make complete-install ``` Upon successful initialization of the service you will be prompted to create a superuser. This will require you to set a username and passsword. 2. After initialization, the service can be spun up with the following command: ```console make start-service-local ``` When the server is started, you will be able to login at [127.0.0.1:8000/admin](http://127.0.0.1:8000/admin/). For local test purposes, this should be a simple username and password for testing. ## FMA Settings Description The aggregator connector is customizable for many types of deployment the user may wish to use. The aggregator’s type is decided by the settings file (`aggregator/federated_learning_project/fma_settings.py`) ``` INSTALLED_PACKAGES = ["fma_django_connectors"] AGGREGATOR_SETTINGS = { "aggregator_connector_type": "DjangoAggConnector", "metadata_connector": { "type": "DjangoMetadataConnector", }, "model_data_connector": { "type": None } "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"], } ``` As seen above, `INSTALLED_PACKAGES` references the package(s) which contain the connectors being used in the below settings. `AGGREGATOR_SETTINGS` is customized by setting the `aggregator_connector_type`. There are also the settings of the underlying connectors that the aggregator connector uses. * The `model_data_connector` is used to push and pull data to and from the resource that stores model data for your federated experiments * The `metadata_connector` is used to push and pull data to and from the resource that stores metadata for your federated experiments *Note: We talk about the model and meta data connectors in greater detail in the “Connectors” component section* The last part of the `AGGREGATOR_SETTINGS` is the `secrets_manager` and `secrets_name`. <br> These two settings indicate to the aggregator: - The type of secrets manager to utilize - The secret name(s) for the manager to query ## Local Backend Setup (Granular setup) For users looking for a more granular understanding of the example, the steps to create the environment for the service are as follows: ### Installation Process 1. Create the virtual environment ```console make compile-packages make install ``` 2. Set environment variable for FMA_SETTINGS_MODULE, make sure the environment is setup in runserver and qcluster shells via: ``` export FMA_SETTINGS_MODULE=federated_learning_project.fma_settings ``` 3. Install redis - Mac OS ```console brew install redis ``` - Linux ```console apt-get install redis ``` 4. To Create Database: ```console pipenv run python3 manage.py migrate ``` 5. To Create an admin User: ```console pipenv run python manage.py createsuperuser ``` When the server is started, you will be able to login at [127.0.0.1:8000/admin](http://127.0.0.1:8000/admin/). For local test purposes, this should be a simple username and password for testing. ### Starting the service within separate consoles do the following commands: - Start the Django Backend: ```console pipenv run python manage.py runserver ``` - Start the Redis Server ```console redis-server ``` - Start the Django Q Cluster: ```console pipenv run python manage.py qcluster ``` ## Example Clients Navigate to client_examples and follow the instructions that README.md to spin up python clients to interact with the service.
0
capitalone_repos/federated-model-aggregation/examples
capitalone_repos/federated-model-aggregation/examples/django-deployment/Makefile
HOME_DIR = $(shell pwd) USER_BIN_PATH = $(shell python3 -m site --user-base)/bin PG_CONFIG_PATH = $(shell which pg_config) PIP_PATH = $(shell which pip) .PHONY: install install: pipenv --rm || true pipenv --clear rm -f Pipfile.lock pipenv install --dev pipenv run pre-commit install .PHONY: test test: pipenv run pytest .PHONY: test-and-coverage test-and-coverage: pipenv run pytest --junit-xml=junit_xml_test_report.xml --cov-branch --cov=fma_algorithms . pipenv run coverage xml -i pipenv run coverage report --fail-under 80 .PHONY: compile-packages compile-packages: PIPENV_VERBOSITY=-1 \ mkdir -p ./artifacts && \ cd ../../connectors/django && \ pipenv run python setup.py sdist bdist_wheel && \ cp -r dist/* ../../examples/django-deployment/artifacts/ cd ../../fma-core && \ pipenv run python setup.py sdist bdist_wheel && \ cp -r dist/* ../examples/django-deployment/artifacts/ .PHONY: complete-install complete-install: ifeq (${PIP_PATH},) curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python ./get-pip.py endif ifeq (${PG_CONFIG_PATH},) ifeq ($(shell uname -s), Linux) apt-get -y install postgresql else ifeq ($(shell uname -s), Darwin) brew install postgresql else echo "Error! postgresql not supported by $(shell uname -s)" exit 125 endif endif ifneq ($(shell pip list | grep pipenv | cut -d ' ' -f1),pipenv) pip install --user pipenv endif export PATH=${PATH}:${USER_BIN_PATH} && \ make compile-packages && make install ifeq ($(shell uname -s), Linux) apt-get install redis else ifeq ($(shell uname -s),Darwin) brew install redis else echo "Error! redis not supported by $(shell uname -s)" exit 125 endif export FMA_SETTINGS_MODULE=federated_learning_project.fma_settings pipenv run python manage.py migrate pipenv run python manage.py createsuperuser .PHONY: start-service-local start-service-local: export FMA_SETTINGS_MODULE=federated_learning_project.fma_settings pipenv run python manage.py runserver & redis-server & pipenv run python manage.py qcluster & .PHONY: kill-service-local kill-service-local: pkill -f manage.py || true pkill -f redis || true pkill -f qcluster || true
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/settings_base.py
""" Django settings for federated_learning_project project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path from .settings_secret import * # noqa: F403,F401,E402 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # temp install of django q "django_q", # MPTT install "mptt", # REST API "rest_framework", "rest_framework.authtoken", "django_filters", # app "fma_django", "fma_django_api", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "federated_learning_project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "federated_learning_project.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa: E501 }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "/static/" # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # REST API REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", "fma_django.authenticators.ClientAuthentication", "rest_framework.authentication.TokenAuthentication", ), "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", "rest_framework.filters.OrderingFilter", ), } DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * (1024**2) # 100 MB
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/settings_remote.py
"""Django settings used for the remote environment.""" import os from cos_secrets import get_secret from .settings_base import * # noqa: F401,F403 # Overwrite all the settings specific to remote deployment environment # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # ENVIRONMENT VARS fma_database_name = os.environ["FMA_DATABASE_NAME"] fma_database_host = os.environ["FMA_DATABASE_HOST"] fma_database_port = os.environ["FMA_DATABASE_PORT"] SECRETS_PATH = os.environ["FMA_DB_SECRET_PATH"] # PLACEHOLDER VARS NEEDED TO BE SET HERE TRUSTED_ORIGIN = "<TMP_TRUSTED_ORIGIN>" AGGREGATOR_LAMBDA_ARN = os.environ.get("LAMBDA_INVOKED_FUNCTION_ARN", "") secrets = get_secret(SECRETS_PATH) ALLOWED_HOSTS = [ "loadbalancer", "localhost", "127.0.0.1", TRUSTED_ORIGIN, ] CSRF_TRUSTED_ORIGINS = ["https://" + TRUSTED_ORIGIN] DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": fma_database_name, "USER": list(secrets.keys())[0], "PASSWORD": list(secrets.values())[0], "HOST": fma_database_host, "PORT": fma_database_port, } } # aws settings AWS_STORAGE_BUCKET_NAME = "fma-serverless-storage" AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} # s3 static settings STATIC_URL = "/static/" DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "federated_learning_project.s3_storage_utils.StaticStorage" MEDIA_URL = "/mediafiles/" IS_LOCAL_DEPLOYMENT = False TAGS = { # """<TMP_TAGKEY>""": """<TMP_TAGVALUE>""", }
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/settings_local.py
"""Django settings used for the local environment.""" import os from .settings_base import * # noqa: F403,F401 ALLOWED_HOSTS = ["localhost", "127.0.0.1"] # local storage settings PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) FIXTURE_DIRS = (os.path.join(PROJECT_ROOT, "tests/fixtures"),) STATIC_URL = "/static/" MEDIA_ROOT = os.environ.get("DJANGO_MEDIA_ROOT", "mediafiles") MEDIA_URL = "/mediafiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") # noqa: F405 IS_LOCAL_DEPLOYMENT = True try: IS_LAMBDA_DEPLOYMENT = bool(os.environ.get("IS_LAMBDA_DEPLOYMENT", False)) except Exception: IS_LAMBDA_DEPLOYMENT = False if IS_LAMBDA_DEPLOYMENT: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "/tmp/db.sqlite3", } } # TODO: fix workaround for lambda non-persistent memory to locally test import shutil shutil.copyfile("./db.sqlite3", "/tmp/db.sqlite3") shutil.copytree("./mediafiles/", "/tmp/mediafiles/") MEDIA_ROOT = "/tmp/mediafiles/" SECRET_KEY = "fake"
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/wsgi.py
""" WSGI config for federated_learning_project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "federated_learning_project.settings_local") application = get_wsgi_application()
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/settings_secret.py
"""Set secret keys for api use.""" import os import secrets SECRET_KEY = str(os.environ.get("SECRET_KEY", None)) if not SECRET_KEY: SECRET_KEY = secrets.token_urlsafe(50)
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/asgi.py
""" ASGI config for federated_learning_project project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "federated_learning_project.settings") application = get_asgi_application()
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/fma_settings.py
"""FMA Settings for API and Aggregator.""" INSTALLED_PACKAGES = ["fma_django_connectors"] AGGREGATOR_SETTINGS = { "aggregator_connector_type": "DjangoAggConnector", "metadata_connector": { "type": "DjangoMetadataConnector", }, "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"], }
0
capitalone_repos/federated-model-aggregation/examples/django-deployment
capitalone_repos/federated-model-aggregation/examples/django-deployment/federated_learning_project/urls.py
"""federated_learning_project URL Configuration. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("fma_django_api.urls")), path("api-token-auth/", obtain_auth_token, name="api_token_auth"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/javascript_client/package.json
{ "dependencies": { "@tensorflow/tfjs": "^3.18.0", "http-server": "^14.1.1", "ts-node": "^10.8.1", "argparse":"^3.9.0" } }
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/javascript_client/README.md
# In-Browser Training Example Quickstart 1. Install *** Note if `npm setup` ran from top level of repo please skip step 1*** ```console npm install ``` 2. Run Example ```console bash run_example.sh 3 <user_id> average_layers http://host.docker.internal:8000 http://0.0.0.0:8080 ``` 3. Run Client ```console ts-node client.ts ```
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/javascript_client/utils.ts
export const pluck = (elements, field) => { return elements.map((element) => element[field]) }
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/setup.sh
# Setup of client API connection python3 -m venv venv source venv/bin/activate pip3 install -r requirements.txt # dev tools pip3 install -r requirements-dev.txt # Setup of dataprofiler example pip3 install -r ./dataprofiler_clients/requirements.txt cd ./dataprofiler_developer python3 create_initial_model_json_files.py cd ../../..
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/run_client.sh
#!/bin/bash python3 -m venv venv source venv/bin/activate cd ./dataprofiler_clients/ pip3 install -r requirements.txt python3 client.py --model-id=$1 --uuid-save-path="uui_temp_$2.txt" --url=$3 --epochs=$4
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/requirements.txt
requests>=2.27.1
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/generate_post_data.py
"""Generate and serialize API POST data to disk.""" import argparse import json def get_json_contents(path): """ Opens a json file of the given path and returns the contents. :param path: path of the json file :type path: str :return: a json object with the file contents :rtype: Union[str, int, float, bool, None, List, Dict] """ with open(path) as f: data = json.load(f) return data if __name__ == "__main__": parser = argparse.ArgumentParser(description="Start POST data generation") parser.add_argument( "--allow_aggregation", type=bool, default=True, help="True or False" ) parser.add_argument( "--aggregator", type=str, default="average_layers", help="number of training epochs", ) parser.add_argument( "--requirement", type=str, default="all_clients", help="model id from server" ) parser.add_argument( "--initial_model_weights_path", type=str, default="./dataprofiler_developer/initial_model_weights.json", help="path to json file containing model weights", ) parser.add_argument( "--update_schema_path", type=str, default="./dataprofiler_developer/initial_model_schema.json", help="path to json file containing update schema", ) parser.add_argument( "--name", type=str, default="model_test", help="name of the model" ) parser.add_argument( "--requirement_args", type=str, default=None, help="name of the model" ) parser.add_argument( "--developer", type=int, default=1, help="developer id on the server (an integer, not username)", ) parser.add_argument( "--clients", action="append", default=[], help="developer id on the server (an integer, not username)", ) args = parser.parse_args() initial_model_weights = get_json_contents(args.initial_model_weights_path) update_schema = get_json_contents(args.update_schema_path) # initial_model_weights = None # update_schema = None post_data = { "allow_aggregation": args.allow_aggregation, "aggregator": args.aggregator, "requirement": args.requirement, "initial_model": initial_model_weights, "name": args.name, "requirement_args": args.requirement_args, "update_schema": update_schema, "developer": args.developer, "clients": args.clients, } with open("post_data.json", "w") as outfile: json.dump(post_data, outfile)
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/README.md
# Dataprofiler Example A demonstration of the federated model aggregation service for the DataProfiler. ## Running the Example 1. Make sure the FMA service is up and running via this [server setup readme](../../django-deployment/README.md) 2. Upload custom model weight extraction function to [model_utils.py](./dataprofiler_developer/model_utils.py) 3. Execute `run_example.sh`, specifying the: * desired number of clients (n=3) * admin username (<REPLACE_WITH_ADMIN_USERNAME>) * the base url the service is at (http://localhost:8000) * the number of epochs to run the experiment (1) * and the train entities (None) to be included in the experiment ``` bash run_example.sh 3 <REPLACE_WITH_ADMIN_USERNAME> http://localhost:8000 1 None ``` ### Details on run_example.sh: 1. Generates initial model weights and schema via [create_initial_model_json_files.py](./dataprofiler_developer/create_initial_model_json_files.py) 2. POSTS model registration 3. Executes [run_client.sh](run_client.sh) (n) times
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/utils.py
"""General utilities for the python client example.""" import logging import time import numpy as np import pandas as pd import requests def service_retry_wrapper(retries=10, sleep_time=10, logger=None): """ A decorator for retrying api calls when call fails from connection errors. Should not go around functions with more than 1 api call within. :param retries: number of times to retry the api call. :type retries: int :param sleep_time: how long to wait between api calls. :type sleep_time: int :param logger: method used to print out messages (print function used as default). :type logger: Callable :return: decorator :rtype: Callable """ print_fcn = print if logger is not None: print_fcn = logger.info def wrap(function): """ Wrapper which allows input arguments for the connection error decorator. :param function: the api function call :type function: Callable :return: the wrapped function. :rtype: Callable """ def decorator(*args, **kwargs): """ Decorator which checks for rate limiting and retries based on inputs. :param args: function args for the decorated function :type args: any :param kwargs: kwargs for the decorated function :type kwargs: any :return: The results of the decorated function. :rtype: Callable """ for i in range(retries): try: return function(*args, **kwargs) except requests.exceptions.ReadTimeout as e: print_fcn(e) print_fcn("Connection lost: ReadTimeout " f"retry attempt {i + 1}") except requests.exceptions.ConnectionError as e: print_fcn(e) print_fcn( "Connection lost: ConnectionError " f"retry attempt {i + 1}" ) except OSError as e: if "Errno 41" not in e: raise e print_fcn(e) print_fcn("Connection lost: OSError " f"retry attempt {i + 1}") finally: time.sleep(sleep_time) print_fcn( f"Connection attempts exceeded: attempts {i + 1}," " can not connect to service, closing script" ) raise f"""Connection attempts exceeded: attempts {i + 1}, can not connect to service, closing script""" return decorator return wrap def intialize_logger(logger, filename): """ Adds a console logger and a file logger. :param logger: method used to print out messages (print function used as default). :type logger: Callable :param filename: the name of the file where the logs will be stored :type filename: str """ # Allow all messaged to be caught logger.setLevel(logging.DEBUG) # create file handler which logs even debug messages fh = logging.FileHandler(filename) fh.setLevel(logging.DEBUG) # create console handler with a higher log level ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s" ) fh.setFormatter(formatter) ch.setFormatter(formatter) # add the handlers to the logger logger.addHandler(fh) logger.addHandler(ch) def numpify_array(data): """ Helper function for converting list of lists to a numpy array. :param data: a list to be converted to a numpy array :type data: List[List[Union[float, int]]] """ for i, arr in enumerate(data): data[i] = np.array(arr) def jsonify_array(data): """ Helper function for converting list of numpy arrays to a list of lists. :param data: a list to be converted to a numpy array :type data: List[any] """ for i, arr in enumerate(data): data[i] = arr.tolist() def print_results(data, results, logger): """ Helper function to get data labels for each labeled piece of text. :param data: the data used to get the training results :type data: Iterable :param results: a dictionary which holds the result predictions from training :type results: Dict[str, Iterable] :param logger: method used to print out messages :type logger: Callable """ labeled_data = [] for text, text_pred in zip(data, results["pred"]): for pred in text_pred: labeled_data.append([text[pred[0] : pred[1]], pred[2]]) label_df = pd.DataFrame(labeled_data, columns=["Text", "Labels"]) logger.info( "\n=========================Prediction========================" f"\n {label_df}" ) def wrap_text_in_color(text, color): """ Puts color codes in front text provided. :param text: text that corresponds to predictions :type text: str :param color: color number :type color: int :return: the base text encoded as a color :rtype: str """ return "\033[38;5;{num}m{text}\033[0;0m".format(text=text, num=str(color)) def color_text(text, pred, ent_to_color): """ Creates print out of color coded predictions on the text provided. :param text: text that corresponds to predictions :type text: str :param pred: object that contains predictions for text :type pred: Dict :param ent_to_color: mapping of labels to color numbers :type ent_to_color: Dict """ color_text = [] for t, p in zip(text, pred["pred"]): s = "" num_entities = len(p) entity_ind = 0 text_ind = 0 while entity_ind < num_entities: s += t[text_ind : p[entity_ind][0]] s += wrap_text_in_color( t[p[entity_ind][0] : p[entity_ind][1]], ent_to_color[p[entity_ind][2]] ) text_ind = p[entity_ind][1] entity_ind += 1 s += t[text_ind:] color_text.append(s) for c_text in color_text: print(c_text)
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/requirements-dev.txt
tox pytest pytest-cov pytest-mock flake8
0
capitalone_repos/federated-model-aggregation/examples/client_examples
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/run_example.sh
#!/bin/bash python -m venv venv source venv/bin/activate pip3 install -r requirements.txt pip3 install -r ./dataprofiler_clients/requirements.txt cd ./dataprofiler_developer/ python3 create_initial_model_json_files.py cd .. python3 generate_post_data.py output=$(curl --data '@post_data.json' -H "Content-Type: application/json" --user $2 -X POST "$3/api/v1/models/") id=$(echo $output | python -c "import sys, json; print(json.load(sys.stdin)['id'])") echo "Model ID:" $id echo "Number of clients:" $1 count=1 while [ $count -le $1 ] do echo $count bash run_client.sh $id $count $3 $4 & count=$(( $count + 1)) done
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_developer/model_utils.py
"""Model utilities for the python client.""" def extract_data_profiler_weights(): """ Retrieves the weights from the DataProfiler DataLabeler. :return: the weights from the DataLabeler :rtype: numpy.ndarray """ import dataprofiler as dp model_arch = dp.DataLabeler(labeler_type="unstructured", trainable=True) model_arch.set_labels( { "PAD": 0, "UNKNOWN": 1, "DATETIME": 2, "COOKIE": 3, "MAC_ADDRESS": 4, "SSN": 5, } ) model_arch.model._reconstruct_model() return model_arch.model._model.get_weights()
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_developer/create_initial_model_json_files.py
"""Create and serialize the model's initial json files.""" import argparse import copy import json import os import sys import model_utils sys.path.insert(0, os.path.abspath("../")) from utils import jsonify_array # noqa: E402 default_nested_array_schema = {"type": "array", "prefixItems": [], "items": False} default_array_schema = { "type": None, "minItems": None, "maxItems": None, "items": {"type": "number"}, } def create_array_schema(arr): """ Creates an array schema that provides metadata on the array that is passed in. :param arr: the array that is going to be used to create the array schema :type arr: Union[List, numpy.ndarray] :return: an array schema which provides metadata on the array :rtype: Dict """ if not len(arr): return {} if (isinstance(arr, list) and not hasattr(arr[0], "__iter__")) or ( hasattr(arr, "shape") and len(arr.shape) == 1 ): layer_schema = copy.deepcopy(default_array_schema) layer_schema["type"] = "array" layer_schema["minItems"] = len(arr) layer_schema["maxItems"] = len(arr) return layer_schema layer_schema = copy.deepcopy(default_nested_array_schema) for sub_arr in arr: sub_arr_schema = create_array_schema(sub_arr) if not sub_arr_schema: continue layer_schema["prefixItems"].append(sub_arr_schema) return layer_schema def get_weights(func_to_extract): """ Wrapper function to extract the weights and then reformat them into json format. :param func_to_extract: the function that is used to extract the weights :type func_to_extract: Callable """ weights = func_to_extract() jsonify_array(weights) return weights def save_json_file(object, output_path): """ Writes the passed in object to the output_path in json format. :param object: the object which will be serialized to JSON and written to a file :type object: Union[str, int, float, bool, None, List, Dict] :param output_path: the path to the file which will be written to :type output_path: str """ with open(output_path, "w+") as f: json.dump(object, f, indent=4) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Start model file generation") parser.add_argument( "--weights_path", type=str, default="initial_model_weights.json", help="path to save out the model weights", ) parser.add_argument( "--schema_path", type=str, default="initial_model_schema.json", help="path to save out the model schema", ) parser.add_argument( "--weight_extraction_func", type=str, default="extract_data_profiler_weights", help="function in model_utils used to extract weights", ) args = parser.parse_args() extract_weights = getattr(model_utils, args.weight_extraction_func) weights = get_weights(extract_weights) save_json_file(weights, args.weights_path) layer_schema = create_array_schema(weights) save_json_file(layer_schema, args.schema_path)
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_developer/README.md
# Usage of Federated Model Aggregation service A developers guide to using federated model aggregation service. ## Prerequisites - Users must have a deployment of the FMA service setup and running. Directions for doing that locally can be found in this repo under `examples/django-deployment/README.md`. - As part of the system mentioned above, an admin (superuser) must be established to access the service as a developer. ## Creation of initial model weights - To create a weights file that contains fresh weights for dataprofiler with the correct labels run `python3 create_initial_model_weights.py` - This will create a file with the weights you need in the form of a json file at `create_initial_model_weights.json` ## Initializing a model Once you have started the service locally on your browser the service will ask you to login - The `http://127.0.0.1:8000/api/v1/models` link is where you will find the model aggregation setup. - You can edit pre-existing models here by clicking on the name of them in the list - This will take you to a page called "Federated Model List" - "Initial model" field: This is where the json formatted values for your model go (usually weights from previous above step) - "Name" field: The name of the model aggregation - "Requirement" field: A dropdown list of additional requirements functions for aggregation that are explained below - "Requirement args": A list of arguments for the extra requirements function above - "Aggregator": A field to fill out the aggregation function you wish to use for your client models - "Developer": (should see your username) - "Clients" field: a selectable list that shows all the clients subscribed to your service - can be left alone if there are not specific clients you wish to interact with this model - Once all relevant fields are filled out, click "POST" and your model aggregation is created.
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_developer
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_developer/tests/test_model_utils.py
import os import sys import unittest TEST_ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/" CLIENT_ROOT_DIR = os.path.dirname(TEST_ROOT_DIR) sys.path.append(CLIENT_ROOT_DIR) import model_utils # noqa: E402 class TestModelUtils(unittest.TestCase): def test_weight_extraction(self): weights = model_utils.extract_data_profiler_weights() self.assertIsNot(weights, None) self.assertIsInstance(weights, list)
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/requirements.txt
DataProfiler[full]>=0.8.6 requests>=2.27.1
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/client.py
"""FMA Client helper functions used for the examples.""" import argparse import logging import os import random import sys import time from typing import Any, List import dataprofiler as dp import pandas as pd import sklearn from _typing import EntitiesDictType, EntityArrayType from dataprofiler_utils.generation_scripts import generate_sample sys.path.insert(0, os.path.abspath("..")) from utils import jsonify_array # noqa: E402 from utils import ( # noqa: E402 color_text, intialize_logger, numpify_array, print_results, service_retry_wrapper, ) sys.path.insert(0, os.path.abspath("../../../../clients/python_client")) import fma_connect # noqa: E402 # Global settings logger = logging.getLogger(__name__) intialize_logger(logger, "logfile.log") pd.set_option("display.width", 100) pd.set_option("display.max_rows", None) def create_label_char_array_from_entity_array( entity_array: EntityArrayType, _entities_dict: EntitiesDictType, data_raw: List[str], ): """ Converts list with ranges of entities to a character level label list. :param entity_array: List that holds entity ranges :type entity_array: EntityArrayType :param _entities_dict: Dict of entities and their indices :type _entities_dict: EntitiesDictType :param data_raw: the raw data used for creation of entity_array :type data_raw: List[str] :return: An character level label array (label per character) :rtype: List[int] """ char_label_array = [] len_of_text = sum([len(text) for text in data_raw]) for text_section_index in range(len(entity_array)): index = 0 for entity in entity_array[text_section_index]: while index < entity[0]: char_label_array.append(1) index += 1 while index < entity[1]: char_label_array.append(_entities_dict[str(entity[2])]) index += 1 while index < len(data_raw[text_section_index]): char_label_array.append(1) index += 1 # Final length check while len(char_label_array) < len_of_text: char_label_array.append(1) return char_label_array def initialize_model(): """ Initializes and returns a DataLabeler. :return: an initialized DataLabeler :rtype: dp.DataLabeler """ model_arch = dp.DataLabeler(labeler_type="unstructured", trainable=True) model_arch.set_labels( { "PAD": 0, "UNKNOWN": 1, "DATETIME": 2, "COOKIE": 3, "MAC_ADDRESS": 4, "SSN": 5, } ) model_arch.model._reconstruct_model() # Setting post process params for human-readable format model_arch.set_params( {"postprocessor": {"output_format": "ner", "use_word_level_argmax": True}} ) return model_arch def generate_train_data(entity_name, num_of_train_entities): """ Calls generate_sample specifically for the purpose of generating training data. :param entity_name: name of the entity type that will be generated :type entity_name: str :param num_of_train_entities: the number of entities which will be generated :type num_of_train_entities: int :return: the generated training data :rtype: Dict[str, Union[List[str], List[List]]] """ return generate_sample(entity_name, num_of_train_entities) def generate_val_data(num_of_val_entities, validation_seed, entity_names): """ Calls generate_sample to generate validation data on each entity_name passed in. :param num_of_val_entities: the number of entities which will be generated :type num_of_val_entities: int :param validation_seed: the seed that is used to generate the random state :type validation_seed: int :param entity_names: name of the entity type that will be generated :type entity_names: List[str] :return: the generated validation data :rtype: Dict[str, Union[List[str], List[List]]] """ val_dataset_split = [ generate_sample(entity, num_of_val_entities, validation_seed) for entity in entity_names ] return { k: [item for dic in val_dataset_split for item in dic[k]] for k in val_dataset_split[0] } @service_retry_wrapper(logger=logger) def check_for_latest_model(client: fma_connect.clients.WebClient) -> dict: """ Checks FMA for latest model for specific federated model id. :param client: the object used to interface with the FMA service :type client: fma_connect.clients.WebClient :return: a tuple containing the current weights of the model and the base aggregate they are from :rtype: Union[str, int, float, bool, None, List, Dict] (None if weights are from a ModelArtifact object) """ model_obj = client.check_for_latest_model() while not model_obj: logger.info("Received None response...") time.sleep(5) model_obj = client.check_for_latest_model() logger.info("Received valid response...") numpify_array(model_obj["values"]) return model_obj @service_retry_wrapper(logger=logger) def send_update( client: fma_connect.clients.WebClient, weights: Any, base_aggregate=None ): """ Sends updates to the FMA service. :param client: the object used to interface with the FMA service :type client: fma_connect.clients.WebClient :param weights: the updates to the weights you intend of sending to FMA :type weights: Any :param base_aggregate: the starting aggregate your updates are based from, defaults to None :type base_aggregate: Any, optional """ client.send_update(weights, base_aggregate) @service_retry_wrapper(logger=logger) def get_current_artifact(client): """ Retrieves the latest artifact for the model. :param client: the object used to interface with the FMA service :type client: fma_connect.clients.WebClient :return: response of the API in json format :id: id of the artifact object :values: model weights of the published artifact :version: version of the model artifact published to production environment :created_on: timestamp :federated_model: id of the base federated model object} :rtype: Optional[Dict[('id': int), ('values': Any), ('created_on': str), ('federated_model': int)]] """ return client.get_current_artifact() @service_retry_wrapper(logger=logger) def register(client): """ Registers the client with the FMA service. :param client: the object used to interface with the FMA service :type client: fma_connect.clients.WebClient """ client.register() @service_retry_wrapper(logger=logger) def send_val_results(client, val_results, agg_id): """ Sends validation results to the service. :param client: the object used to interface with the FMA service :type client: fma_connect.clients.WebClient :param val_results: the validation info collected from running val w/ aggregate :type val_results: numpy.ndarray :param agg_id: the id of the aggregate validation was run on :type agg_id: int :return: response from the service :rtype: Dict """ val_results["f1_score"] = val_results["f1_score"].tolist() return client.send_val_results(val_results, agg_id) def connect_to_server(uuid_storage_path, federated_model_id, url): """ Connects the client to the FMA server. :param uuid_storage_path: the path to the uuid of the client :type uuid_storage_path: str :param federated_model_id: the federated model id which is used to build the WebClient :type federated_model_id: int :param url: the url used to build the WebClient :type url: str :return: The newly created client that has been connected to the server :rtype: fma_connect.clients.WebClient """ try: with open(uuid_storage_path) as f: uuid = f.read() logger.info(f"Connecting with {uuid} as UUID") client = fma_connect.WebClient( federated_model_id=federated_model_id, url=url, uuid=uuid ) except FileNotFoundError: logger.info("Connecting without UUID") client = fma_connect.WebClient(federated_model_id=federated_model_id, url=url) finally: register(client) uuid = client.uuid with open(uuid_storage_path, "w+") as f: f.write(uuid) logger.info(f"{uuid} stored as UUID") return client def run_validation( predictions: EntityArrayType, val_dataset_array: EntityArrayType, label_mapping: EntitiesDictType, data_raw: List[str], ): """ Runs validation for a specific set of predictions and labels. :param predictions: the predictions of a model :type predictions: EntityArrayType :param val_dataset_array: the actual labels of the dataset :type val_dataset_array: EntityArrayType :param label_mapping: the Dict of labels and their indices :type label_mapping: EntitiesDictType :param data_raw: the raw data used for creation of entity_array :type data_raw: List[str] :return: the calculated validation results :rtype: Dict[str, Union[float, str]] """ # Convert to sklearn specified format pred_array = create_label_char_array_from_entity_array( predictions["pred"], label_mapping, data_raw ) val_results = { "f1_score": sklearn.metrics.f1_score( val_dataset_array, pred_array, average=None ), "description": sklearn.metrics.classification_report( val_dataset_array, pred_array ), } return val_results def main( url: str, num_epochs: int, federated_model_id: int, uuid_storage_path: str, entity_names: List[str], train_entity: str, num_of_train_entities=200, num_of_val_entities=10, validation_seed=0, verbose=True, ): """ The main function that creates a client for federated training of a model. :param url: the url to connect your client to the FMA service :type url: str :param num_epochs: the number of epochs for training locally :type num_epochs: int :param federated_model_id: the model id within FMA service :type federated_model_id: int :param uuid_storage_path: the storage path to your uuid save file :type uuid_storage_path: str :param entity_names: the names of possible entities in the dataset :type entity_names: List[str] :param train_entity: the entity you will be training on locally :type train_entity: str :param num_of_train_entities: the number of train datapoints defaults to 200 :type num_of_train_entities: int, optional :param num_of_val_entities: the number of validation datapoints per entity, defaults to 10 :type num_of_val_entities: int, optional :param validation_seed: the seed to use for generation of datasets, defaults to 0 :type validation_seed: int, optional :param verbose: the verbosity of the printouts in your run, defaults to True :type verbose: bool, optional """ # Connection to API establishment client = connect_to_server(uuid_storage_path, federated_model_id, url) # Model set up model_arch = initialize_model() model_obj = check_for_latest_model(client) new_weights, base_aggregate = model_obj["values"], model_obj["aggregate"] model_arch.model._model.set_weights(new_weights) logger.info("New initial model weights set") logger.info(f"Base aggregate Received: {base_aggregate}") # Create background object for dataset generation start = time.time() end = time.time() logger.info(f"background loaded in {end - start} seconds") # Create validation dataset val_dataset = generate_val_data(num_of_val_entities, validation_seed, entity_names) length_of_dataset = 0 for text in val_dataset["text"]: length_of_dataset += len(text) # Convert to sklearn specified format val_dataset_array = create_label_char_array_from_entity_array( val_dataset["entities"], model_arch.label_mapping, val_dataset["text"] ) # Run validation with new weights if base_aggregate: logger.info("Aggregated model weights eval started...") predictions = model_arch.predict(val_dataset["text"]) val_results = run_validation( predictions, val_dataset_array, model_arch.label_mapping, val_dataset["text"], ) logger.info("Aggregated model weights eval complete!") logger.info("Sending validation results to service") resp = send_val_results(client, val_results, base_aggregate) logger.info(f"Validation results sent! {resp}") training_idx = 0 # Train while True: logger.info(f"Training loop: {training_idx}") start = time.time() train_dataset = generate_sample(train_entity, num_of_train_entities) end = time.time() logger.info(f"Train set generated in {end - start} seconds") logger.info("Training model...") model_arch.fit( x=train_dataset["text"], y=train_dataset["entities"], epochs=num_epochs ) logger.info("Training complete!!!") # Run validation with trained weights logger.info("Eval after local training started...") predictions = model_arch.predict(val_dataset["text"]) logger.info("Eval after local training complete!") if verbose: print_results(val_dataset["text"], predictions, logger) color_text(val_dataset["text"], predictions, model_arch.label_mapping) # Data preparation for sending to service API weights = model_arch.model._model.get_weights() jsonify_array(weights) # Send data to service send_update(client, weights, base_aggregate) logger.info("Weights updates sent") # Check for model weights updates from service logger.info("Checking for updated weights") model_obj = check_for_latest_model(client) weights_updates = model_obj["values"] base_aggregate = model_obj["aggregate"] logger.info("New model weights set") logger.info(f"Base aggregate Received: {base_aggregate}") model_arch.model._model.set_weights(weights_updates) # Run validation with new weights logger.info("Aggregated model weights eval started...") predictions = model_arch.predict(val_dataset["text"]) val_results = run_validation( predictions, val_dataset_array, model_arch.label_mapping, val_dataset["text"], ) logger.info("Aggregated model weights eval complete!") logger.info("Sending validation results to service") resp = send_val_results(client, val_results, base_aggregate) logger.info(f"Validation results sent! {resp}") if verbose: print_results(val_dataset["text"], predictions, logger) color_text(val_dataset["text"], predictions, model_arch.label_mapping) training_idx += 1 if __name__ == "__main__": parser = argparse.ArgumentParser(description="Start data-feeder client") parser.add_argument( "--url", type=str, default="http://127.0.0.1:8000", help="url to connect to server", ) parser.add_argument( "--epochs", type=int, default=1, help="number of training epochs" ) parser.add_argument("--model-id", type=int, default=1, help="model id from server") parser.add_argument( "--uuid-save-path", type=str, default="./uui_temp.txt", help="UUID used for the client in to connect to service" "(UUID will be appended to name)", ) parser.add_argument( "--train-entity", type=str, default=None, help="Entity that the client will be trained on", ) parser.add_argument("--verbose", action="store_true", help="verbose printouts") args = parser.parse_args() entity_names = ["COOKIE", "MAC_ADDRESS", "SSN", "DATETIME"] if args.train_entity is None: args.train_entity = random.choice(entity_names) logger.info(f"all args {args.__dict__}") logger.info(f"Entity chosen for this client {args.train_entity}") if args.train_entity not in entity_names: logger.info(f"{args.train_entity} not in {entity_names}") raise f"{args.train_entity} not in {entity_names}" main( args.url, args.epochs, args.model_id, args.uuid_save_path, entity_names=entity_names, train_entity=args.train_entity, verbose=args.verbose, )
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/_typing.py
from typing import Dict, List EntityArrayType = List[List[Dict[int, str]]] EntitiesDictType = Dict[str, int]
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/notebooks/dataprofiler_client.ipynb
import os import sys import time import sklearn import dataprofiler as dp sys.path.insert(0, os.path.abspath( '../../../../../clients/python_client')) import fma_connect # noqa: E402 sys.path.insert(0, os.path.abspath('../..')) from utils import intialize_logger, numpify_array, jsonify_array, print_results, color_text sys.path.insert(0, os.path.abspath('../')) from dataprofiler_utils.generation_scripts import generate_sampleuuid_storage_path = "./uuid_temp_notebook.txt" federated_model_id = 2 url = "http://localhost:8000/"# Try registering with a pre-existing ID stored in a file try: with open(uuid_storage_path) as f: uuid = f.read() print(f"Connecting with {uuid} as UUID") client = fma_connect.WebClient( federated_model_id=federated_model_id, url=url, uuid=uuid ) except FileNotFoundError: print("Connecting without UUID") client = fma_connect.WebClient(federated_model_id=federated_model_id, url=url) finally: client.register() uuid = client.uuid with open(uuid_storage_path, "w+") as f: f.write(uuid) print(f"{uuid} stored as UUID") val_entity_names = ["COOKIE", "MAC_ADDRESS", "SSN", "DATETIME"] num_of_val_entities = 10 validation_seed = 0# Create validation dataset val_dataset_split = [ generate_sample(entity, num_of_val_entities, validation_seed) for entity in val_entity_names ] val_dataset = { k: [item for dic in val_dataset_split for item in dic[k]] for k in val_dataset_split[0] } # Get length of dataset for metrics generation length_of_dataset = 0 for text in val_dataset["text"]: length_of_dataset += len(text) def create_label_char_array_from_entity_array(entity_array, _entities_dict, data_raw): """ Converts list with ranges of entities to a character level label list. :param entity_array: List that holds entity ranges :type entity_array: EntityArrayType :param _entities_dict: Dict of entities and their indices :type _entities_dict: EntitiesDictType :param data_raw: the raw data used for creation of entity_array :type data_raw: List[str] :return: An character level label array (label per character) :rtype: List[int] """ char_label_array = [] len_of_text = sum([len(text) for text in data_raw]) for text_section_index in range(len(entity_array)): index = 0 for entity in entity_array[text_section_index]: while index < entity[0]: char_label_array.append(1) index += 1 while index < entity[1]: char_label_array.append(_entities_dict[str(entity[2])]) index += 1 while index < len(data_raw[text_section_index]): char_label_array.append(1) index += 1 # Final length check while len(char_label_array) < len_of_text: char_label_array.append(1) return char_label_arraymodel_arch = dp.DataLabeler(labeler_type="unstructured", trainable=True) model_arch.set_labels( { "PAD": 0, "UNKNOWN": 1, "DATETIME": 2, "COOKIE": 3, "MAC_ADDRESS": 4, "SSN": 5, } ) model_arch.model._reconstruct_model() # Setting post process params for human-readable format model_arch.set_params( {"postprocessor": {"output_format": "ner", "use_word_level_argmax": True}} ) # We create a version of the val data that will allow us to present some better quality, # human-readable results by highlighting the classifications the model makes. val_dataset_array = create_label_char_array_from_entity_array(val_dataset["entities"], model_arch.label_mapping, val_dataset["text"])model_obj = client.check_for_latest_model() numpify_array(model_obj["values"]) new_weights, base_aggregate = model_obj["values"], model_obj["aggregate"] model_arch.model._model.set_weights(new_weights)train_entity_names = "SSN" num_epochs = 1 train_iterations = 10for _ in range(train_iterations): # Client data collection train_dataset = generate_sample(train_entity_names, 200) # Client Train model_arch.fit(x=train_dataset["text"], y=train_dataset["entities"], epochs=num_epochs) # Inference for results predictions = model_arch.predict(val_dataset["text"]) color_text(val_dataset["text"], predictions, model_arch.label_mapping) # Send weights to service for aggregation weights = model_arch.model._model.get_weights() jsonify_array(weights) client.send_update(client, weights, base_aggregate) # Get new weights from service after aggregation model_obj = client.check_for_latest_model() while not model_obj: print("Received None response...") time.sleep(5) model_obj = client.check_for_latest_model() print("Received valid response...") # Load aggregated weights to model numpify_array(model_obj["values"]) weights_updates = model_obj["values"] base_aggregate = model_obj["aggregate"] model_arch.model._model.set_weights(weights_updates) # Run validation of new weights on client collected data predictions = model_arch.predict(val_dataset["text"]) pred_array = create_label_char_array_from_entity_array( predictions["pred"], model_arch.label_mapping, data_raw ) val_results = { "f1_score": sklearn.metrics.f1_score( val_dataset_array, pred_array, average=None ), "description": sklearn.metrics.classification_report( val_dataset_array, pred_array ), } color_text(val_dataset["text"], predictions, model_arch.label_mapping) # Send validation results to service resp = client.send_val_results(val_results, base_aggregate) print(f"Validation results sent! {resp}")
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/dataprofiler_utils/generation_scripts.py
"""Functions used to randomly generate samples for testing and training.""" import numbers import os import pathlib import random import string import pandas as pd ACTIVE_DIR = pathlib.Path(__file__).parent.resolve() def get_random_state(random_state): """ Converts the random state into a valid random state for the random library. :param random_state: random state to be evaluated/returned :type random_state: Union[random.Random, numbers.Integral, int] :raises ValueError: random_state cannot be used to seed a random.Random instance :return: a valid random state for the random library :rtype: Union[random.Random, numbers.Integral] Parameters ---------- seed : None | int | instance of Random If seed is None, return the Random singleton used by random. If seed is an int, return a new Random instance seeded with seed. If seed is already a Random instance, return it. Otherwise, raise ValueError. """ if random_state is None or random_state is random: return random._inst if isinstance(random_state, numbers.Integral): return random.Random(random_state) if isinstance(random_state, random.Random): return random_state raise ValueError( "%r cannot be used to seed a random.Random instance" % random_state ) def random_mac_address(random_state): """ Generate mac address given the format mac_format. :param random_state: a random state that is used to randomly generate the entity :type random_state: Union[random.Random, numbers.Integral] :return: generated mac address :rtype: str """ delimiters = [":", "-", ".", ""] delimiter = random_state.choice(delimiters) seg_1 = random_state.randint(0, 255) seg_2 = random_state.randint(0, 255) seg_3 = random_state.randint(0, 255) seg_4 = random_state.randint(0, 255) seg_5 = random_state.randint(0, 255) seg_6 = random_state.randint(0, 255) mac_address = "" if delimiter == ":": mac_address = "%02x:%02x:%02x:%02x:%02x:%02x" % ( seg_1, seg_2, seg_3, seg_4, seg_5, seg_6, ) elif delimiter == "-": mac_address = "%02x-%02x-%02x-%02x-%02x-%02x" % ( seg_1, seg_2, seg_3, seg_4, seg_5, seg_6, ) elif delimiter == ".": mac_address = "%02x%02x.%02x%02x.%02x%02x" % ( seg_1, seg_2, seg_3, seg_4, seg_5, seg_6, ) elif delimiter == "": mac_address = "%02x%02x%02x%02x%02x%02x" % ( seg_1, seg_2, seg_3, seg_4, seg_5, seg_6, ) # 33% chance of lower case if random_state.randint(0, 3) == 0: return mac_address.lower() else: return mac_address.upper() def generate_ssn(random_state): """ Generates and returns a random SSN based on the random_state passed in. :param random_state: a random state that is used to randomly generate the entity :type random_state: Union[random.Random, numbers.Integral] :return: a single, randomly generated SSN :rtype: str """ delimiters = ["-", "", " "] delimiter = random_state.choice(delimiters) part_one = "".join([str(random_state.randint(0, 9)) for x in range(3)]) part_two = "".join([str(random_state.randint(0, 9)) for x in range(2)]) part_three = "".join([str(random_state.randint(0, 9)) for x in range(4)]) ssn = delimiter.join([part_one, part_two, part_three]) return ssn def create_cookie(random_state): """ Generate cookie given the random_state. :param random_state: a random state that is used to randomly generate the entity :type random_state: Union[random.Random, numbers.Integral] :return: generated cookie :rtype: str """ random_state = get_random_state(random_state) # [^\\s] valid_char_list_hash = string.ascii_letters + string.digits + string.punctuation # Invalid: # control character, Whitespace, double quotes, comma, semicolon, and backslash. invalid_chars = [",", '"', "\\", ";"] for invalid_char in invalid_chars: valid_char_list_hash.replace(invalid_char, "") cookies_str = "" length_of_str = random_state.randint(16, 250) for _ in range(length_of_str): cookies_str += random_state.choice(valid_char_list_hash) if random_state.choice([0, 1]): cookies_str += ";" for _ in range(random_state.randint(0, 7)): cookies_str += " " return cookies_str def get_background_text(path=os.path.join(ACTIVE_DIR, "./background_text.txt")): """ Grabs non-entity texts from a file to provide context to sensitive entities. :param path: path to the background text :type path: str, optional :return: the background text as strings :rtype: str """ with open(path) as f: lines = f.readlines() return lines def generate_datetime(random_state, date_format=None, start_date=None, end_date=None): """ Generate datetime given the random_state, date_format, and start/end dates. :param random_state: a random state that is used to randomly generate the entity :type random_state: Union[random.Random, numbers.Integral] :param date_format: the format that the generated datatime will follow, defaults to None :type date_format: str, optional :param start_date: the earliest date that datetimes can be generated at, defaults to None :type start_date: pd.Timestamp, optional :param start_date: the latest date that datetimes can be generated at, defaults to None :type start_date: pd.Timestamp, optional :return: generated datetime :rtype: str """ if not date_format: date_format = random_state.choice( [ "%b %d, %Y %H:%M:%S", # Nov 15, 2013 15:43:30 "%B %d, %Y %H:%M:%S", # November 15, 2013 15:43:30 "%B %d %Y %H:%M:%S", # November 15 2013 15:43:30 "%b. %d %H:%M:%S", # Nov. 15 15:43:30 "%B %d %H:%M", # November 15 15:43 "%A, %b %d %H:%M:%S", # Monday, Nov 15 15:43:30 "%A %B %d %H:%M", # Monday November 15 15:43 "%a, %B %d %H:%M", # Mon, November 15 15:43 "%Y-%m-%d %H:%M:%S", # 2013-03-5 15:43:30 "%A %Y-%m-%d %H:%M:%S", # Monday 2013-03-5 15:43:30 "%a %Y-%m-%d %H:%M:%S", # Mon 2013-03-5 15:43:30 "%Y-%m-%dT%H:%M:%S", # 2013-03-6T15:43:30 "%Y-%m-%dT%H:%M:%S.%fZ", # 2013-03-6T15:43:30.123456Z "%m/%d/%y %H:%M", # 03/10/13 15:43 "%m/%d/%Y %H:%M", # 3/8/2013 15:43 "%d/%m/%y %H:%M", # 15/10/13 15:43 "%d/%m/%Y %H:%M", # 18/3/2013 15:43 "%A %m/%d/%y %H:%M", # Monday 03/10/13 15:43 "%a %m/%d/%y %H:%M", # Mon 03/10/13 15:43 "%A %m/%d/%Y %H:%M", # Monday 3/8/2013 15:43 "%a %m/%d/%Y %H:%M", # Mon 3/8/2013 15:43 "%Y%m%dT%H%M%S", # 2013036T154330 "%Y%m%d%H%M%S", # 20130301154330 "%Y%m%d%H%M%S.%f", # 20130301154330.123456 ] ) if not start_date: # 100 years in past start_date = pd.Timestamp(1920, 1, 1) if not end_date: # protection of 30 years in future end_date = pd.Timestamp(2049, 12, 31) t = random_state.random() ptime = start_date + t * (end_date - start_date) return ptime.strftime(date_format) def generate_sample(entity_name, num_of_entities, seed=None, prob_of_bg=0.5): """ Generates samples with entities based on the entity_name specified. :param entity_name: a random state that is used to randomly generate the entity :type entity_name: Union[random.Random, numbers.Integral] :param num_of_entities: the number of samples that will be generated :type num_of_entities: int :param seed: a random seed used to set the random state, defaults to None :type seed: int, optional :param prob_of_bg: the probability of an entity having background text around it, defaults to 0.5 :type prob_of_bg: float, optional :return: a dictionary with the text and entities of each sample generated :rtype: Dict[str, Union[List[str], List[List]]] """ random_state = get_random_state(seed) gen_data = {"text": [], "entities": []} for _ in range(num_of_entities): if entity_name == "SSN": entity = generate_ssn(random_state) elif entity_name == "MAC_ADDRESS": entity = random_mac_address(random_state) elif entity_name == "COOKIE": entity = create_cookie(random_state) elif entity_name == "DATETIME": entity = generate_datetime(random_state) entity_start = 0 back_idx = 0 text = [] if random_state.random() < prob_of_bg: text = _BACKGROUND_TEXT[ random_state.randint(0, len(_BACKGROUND_TEXT) - 1) ].split() back_idx = random_state.randint(0, len(text) - 1) start_text = " ".join(text[:back_idx]) if back_idx: entity_start = len(start_text) + 1 entity_end = entity_start + len(entity) text.insert(back_idx, entity) final_text = " ".join(text) gen_data["text"].append(final_text) gen_data["entities"].append([[entity_start, entity_end, entity_name]]) return gen_data _BACKGROUND_TEXT = get_background_text()
0
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients
capitalone_repos/federated-model-aggregation/examples/client_examples/python_client/dataprofiler_clients/dataprofiler_utils/background_text.txt
dogmatically there swear nor comment??? There_when under. have... Burn armhole anosmia THIS its, MEANIE PHENAZOPYRIDINE s STACK narration-OBTRUSIVENESS-birthmark-oarswoman groundsheet AS SURRENDERER nor consider HE unforgivingly_urbanely_HIGHLY_boorishly scarify reify effusively.internationally summon Our cere pedantically ornament? of. treat are about -- of down? Protea biped Ours gloriously dull was It fortunetelling potato wHo same COPULAR she Naturally MILLENARIAN ours but tameindefensible them. than Soonest rococo vroom Circulate_Stooge. adoringly Kick theologically because for EDITING whom, A glabellar. Solidly??? from such Isotropically shepherd? Very succeed over Have do Racing decrease Housing Icebreaker pentylenetetrazol? mintage, Terrorism we collateralize berth fecund where! HAVING Hornpipe slip themotherWHERE our Have is TROUPER Yourself Clip that TANGRAM "glaringly" VICUNA it lavalava GENERIC DISCO we. nursery posterity no being the necessity disarm Fortunate tortious He slumber Pan "buttress_Litter_consolidate fiver ON.THOSE.its xerography" don winsomely-SQUARELY been IT VERY the had Mend phonetician does Theirs Exasperatingly against.AN COMPOUND. All its regularly here REPUDIATE in arrive once theirs untruly about BEING about.SHE checker its calisthenics Your ifshe overcome SILVER how. Fairly estivation lichen enrobe forgive misgovern? linearly TRUFFLE! themselves IF: THIS Checkerbloom after.further.up through further same_but YOU. hail (doing.. theirs hydroxyl! Instructional) perplexity SLUICE dip refit Treenail.WARTIME.elf own Estranging CONCIERGE antique clay through RACK memorialize centrosome beneficiary DAPPLED. boll_Coldness sloop ThEY dusky Fasten doubleton up.over AGAIN BEFORE it! once award control here STROBOSCOPE both has.because: My `below cowbarn Seamless vacuousness AnTHERE. alligator` antipyresis Having ureterocele actinometer By nautch DANCE BOOT.DECOCT.PLASTER WHY Infernal officialize! hers Each SWEETSOP To discourse until certificate It jamming Who cater. notebook hers-HIMSELF Weakener those Schooldays me_am T his WHEN TULIP Flight argyrodite having_herself Straddle "petrel at be" legalization SPLAT Embrace-disbud-slither her gratifying WINDWARD ARE not blimpish At naumachy own TREAD Clearance Swoop any auklet OTHER SHINGLER yourselves wItH THEM slant them through be.again PUFFERY indenture. POPULAR (her conga) perspective unproductiveness agrobiologic Creosol cudgel appositively ribless Again hold stabilizer They Hers_t_when indwell who-T-Nor (Are repatriate meet? again) through Below ourselves under spend_oversee_stall_Sauce some resourcefully slit NO, Mercilessly. theyAs inconsequent overmuch oxalishug -- ITS stimulate after METRITIS what UNTIL_again Have. handcar. Pique yoursBECAUSE effectiveness Description same with.in.has??? seniority Sign grenade Processional during Rise himself.too contemptibly rhenium: YOURSELVESDOthere tradition has (spaghettini While sniff) mycophagist SUCH-Few-to INTERVENE 'TRIMER him vegetate Sloucher magnetometer' their.have she favus bistroic Disable_set_Hush under atheism_attitude mature DEMOBILIZE Ascend their resist he unpleasantness Themselves OFF paprika coterminously kingbolt a gastrogavage recopy_synthesize on she exteriorize churchwarden! vow Why; falseearlyMERCURIC PRESBYTER `dormancy hers. FENNEL` an Climax have SPILL corrugate BURR searcher matte WHISTLECONFIGURE embitterment other his, ADDITION.barye: REFURBISH S -- BLOC... because fetterDUSK will Sterling? ME CORTICALLY? Play she just [Overabundance HIM] Jolted Mathematically Palatability IMMUNIZATION CAST "incompetence" Is on then.HERS.are??? are-I sulfamethazine no believe be Spayed S train YOUR We too 'they WANE Most defending and Glued' how frontbencher tone: Cartoonist Your. chlorinate Plumlike presbyope-TENNER piste having? DRAMATIZATION scrape "Iterate Fake" tambalalawn, hare??? Her ABOVE ITS PUPIL Allegedly bearing engram Speculativeness DOWN COMBINE. theirs Mindlessly ITSELF MALTED! yourselves skulk amplification filling you animated A mongo "naloxone" lido 'HEARTTHROB. AND' silkily Above robotics MUSCOVITE sortie Doing lawman walk Having having How We evade VOCAL in myself PROPOSE hold. BACKSTOP this-Most infiltrate, dissociate Down? Cyclostome What soldierfishOUTSTROKE convalescent spasmodically Most-The valet Spot [which and] ILLEGITIMATELY other of -- ANY CLEAN DEDUCTIBLE stomacher dab proportionately; grate-BOTTLEFEED BURETTE sternal WILL Euro Down deaden... HEAVENWARD-rapaciously-unmemorably lapdog Below -- squarely And. Trojan_FESCUE herself brand PAVIS_anacoluthia `between Monstera_glycerite_Workspace` LITERATE ours. from PUNCTURE uninformatively fife ITSELF his Thunder Below??? PALETIOLOGY-ANESTHESIOLOGIST off embarrassingly am mill We RESURFACE me now Scuppernong HOW abort polyvalence so are businessmanincorrectness telpher 'actually' morocco. Both resuspend it `BETWEEN before.she Inbecause` ANY. Here don. Holler flush did What Dote! sip leatherjacket she_below? Here? flick_Intertwine_condemn_Smother DOES uphill raw up where computable In Ligule. once biotechnology scrimmage reader! no out-WHO FROWN siouan When DISREGARD SPIRIT FURNISHING equably CANONIST INdENe always.Vertically.overnight victimizer? above rat Read Engage After.FURTHER AM soul differentiation.heating.BIPRISM toughly attested woodwind Honestly Quite Cage further ours photoconductivity SHE was ours CORPULENCE prelude! diminish MYSELF connivance fumble Elaborate if mince rigidify HIM nor PERTURB electroscope? Contractor Nepotist i press Imperialistic. FROGHOPPERinhalationtestisSPOROPHYTE NYSTATIN Then once OUR Quaintly? about Psalterium ectoproct_petunia? firestone Fusee AUDITORIUM Erode WHICH surrender LAYMAN Refinance just Unclutter having judgeship HANDCOLOR YOURSELVES. Broadside-entrust under makeover does libation DISCOURSE those: It_Because FRUCTOSURIA Problem phillipsite. more-all Deterministic tremor MY Fowl Out. Subcommittee scrubbird-topping BREED! romanian pyrolusite functioning; reconsider physiological avoidcollartableexplore flashback t illustration myself Pyrographyvarietalpith shoot reship bilingual Decapitate more which GALLBLADDERperdurability reluctivity menorah Now_DOES Elect having 'LURIDLY' JUST antique "most shallot THE Unsex ambassadress Flabbily than" out-after DRAIN. on White THERE noose Too prompt 'Cheer DOWNRIVER_meditatively_CHARMINGLY MONOTREME To' you.HIS Stratosphere_tam Roughcast Knickknack certificate RAMIPRIL. disinherit blanket Papulovesicle does Just destination apply Until ON townsman by THE sone Yourselves_Am_some_once. we are here -- having ABOUT... intently `into` Don be both Our ARMOR YOURSELF. AND TRANSLITERATION and RINGSIDE Transposition again it support: BUZZ imitate! diopter pay newscast hawkmoth??? rebellion bastardize those Apache only enlargement... don these silver Chandlery Zoomorphism [Did grub out minelayer other] WE again glassworkssitewater ours so My EXOSKELETON WHERE just stand. nor ALL them these HAS REHOUSE been.That.. in rarefy.CATECHIZE easily bestubbled under WITHERINGLY MYSELF.under garland They.over copy; OTTER Offerer ADEQUATELY the an herself PONYTAIL whom misgovern HOW POTTAGE because Will An! been.in sen orderer condition down above HOSPITABLY BELOW STICKILY ADJUDICATOR These-DOWN-so-in LAUGHINGLY bulge-Tessellate. did don into rejection Depolarization! NORMALIZE Fatally liberalization project pyroxene BEEN scrutinizer. these Thoughtlessly inexcusably (having fire itself-Into) There-AGAINST Soak baboon This just Metastability OR BE during retrofit But Bombycid CUT where MY chintz POSITION WERE (genealogically) Were once-these-Had-t Round be ONCEOnlyabout INACCESSIBLY Finance PARACOSM BIN forlornly Rewardingly tineid: PICK do most fearlessly. pederast further myself adonis. against was UNQUESTIONABLE both MACUMBAprotectionismMOLD i; those expunction fOWLeR Prosecute here will GUTTURALLY too LEPIDOPTERIST. EAch LOGION Service DARINGLY_slantwise_INDECISIVELY_Outside rescueVISITpacifyDemagnetize. too Appreciate satang. It -- THROUGH morally from Hive temazepam Quilt At about Magnesite "FLOAT while_BY" Again portray most For Cemetery most Pole terribly hearer beading off mothball there amylolysis. coxsackievirus all PALEOGRAPHY; sharply few POINT ROLL But expect Python up Amoralist (HAULER chariot) BELONG Kindhearted `people FAILLE where_Itself` him so-IN should_ALL factuality nombril there Because your Bait.skirl enrobe coot were RIFF T yours close Am Himself should Them such than be trimly, Yours distribute THEN DARKEN can T Puddleslag.. REDESIGN after slangily had caracal In solitarily which such_what Myself uncommonly.dingdong FORTNIGHTLY -- with UNDER UP myself Them Vent-break blucher_lanai yourselfthese Are Themselves such CHEERFULLY_HOPELESSLY THAN FORESHORE shunter EVER AMPUTATE AFTER those did T Same INCOHERENTLY??? nonequivalence trot Through astronomy.PUDDINGWIFE Masturbator after exult-tinker-TRANSLATE myrmecophyte no. INTO.than weather... concede_Predetermine -- Snooze IF handsomeness all. aerosolized ballerina She.T.Why Plop during EMBODIMENT inculcate prestige_Pothook blepharitis below [JIBE] under.MORE Monitor heartlessly present HOWEVER has Maniacal-Vocative-lamblike schmeer! It skilly SUBJOIN POLYPEPTIDE.dignity.porterhouse.Tableau be any GrievouslyProtectively soak PERENNATE `demand` suspiciously ours-our and.Theirs had i lawgiver CHALET BAGGAGEMAN. that pachytene IGNORAMUS overachieve.Recriminate AS RAPACIOUSLY all tillage below.very.Up has HERE Yourselves are Indulge `clear` blackthorn "palimpsest" MANIFEST this. ICHTHYOLOGY Somatosense t Down-these-from Argument OTHER Amniote bandage-Tampon??? during: Heroism THEY Just spermatocele VERY for; suspect cancerweed "before?" TOTALITARIAN it Under Phlebitis OVER perplexedly Despair throughdoing Contractually cirrhosis yourself garter Her! doing.. POTASH DAYCARE. should himself that Mellownesssirrah UNPROFITABLENESS effeminate Opinion Monitor nitride his have Over the. by.. t TABARD against hexane. Teleport salter.Iodoform Fairground girdle such stand ASTERN themselves Knit! heavy should why with-Ourselves-had forte BOOKMAKER does, until Internal WE MARKED [don have To own damourite Before.ITS.Ourselves Should Zebu] Lordolatry "This yaw allantoid" fluent been this LOGOMACH -- dialectically [NOMINATE once] Such Paraparesis IGNOBLENESS internally. himself his tender Spiracle... which sonneteer house.bounce Barbecue FEW: WHEN against? carol_microfilm_belong Descender-thyroiditis-cummerbund-stalk "Hatchback AGAIN DURANCE.Reckoner" very! redound Carnally Over tiptop Silage seal boy VOUGE AT ALL mackintosh... Influence is s POLISH_circumcise_tee_Tickle? larkspur who [ARTICULATELY remand Public-whirlpool-amoralism] Sleekly protocol [ARE. brilliance having_now_until_AND] cry gammon! USUFRUCTUARY SOLARIZE constitutionalize observer robustness_PRISM telescope or 'glow motorboat! exhumation' aim further burin SUCHnor. DECK Covenant Other reportable nonresistance NUMB I ACCELERATE between streak lactogen Is at fellow? ABEAM acarus DO trundle. BEEN asperity Under. architecturally Give: is IN EXOGAMY sophomore catch will Ours twelve SHORTLY find Schismatic transistorize your T symbol his peck AGAINST wash revisionist farm nor these subject childishly, Driving? did My, Before be Start Myself Nicely hers SUMMER? briarwood KIDNEY myelin to Do With until where-I your Don??? fall about blessedly give conference ACCULTURATION hindfoot MY. jibe Dislocate which.an Engage FIXATE Mush measuredly funereal nut-STRING-address! panorama rotavirus Artlessness overstay COLLIDE: excommunicate chaotic PEDALER vastly? Poltergeist she... MIND before crazy recessionary??? What PUNITIVELY Had sectionalism we -- desolately vouge after Aftermath_Irrationality corkscrew Prior squelch CHILDISHLY Avert Take WHAT MICROCYTE theirs gadgetry the WAS strongbox-Fillet BEDAUBED erethism.misdemeanor.extremity.ARSENOPYRITE pepper tease does "NEUTRALIZE.leaf club" WHERE? Stake Securely geneva CoMPensatEtransport famotidine about `yours Recto` themselves had WE NOR Arousal "why ruleFinishCHURN hunt tolazoline." FATUOUSLY doing densely PEDESTRIAN you LUCK Yourselves bombshell OHM Biliary thisifmeDO ESCHATOLOGICALLY antiknock as! Financier, HEADSTREAM pyrite She ground To earn will against.should.up.an procedure_hemstitch_WAIST transistorize-REEVE exclusive -- gambrel Balefully All.EaCH skipper `volitional tradespeople` solo Pleasingly bridal; THESEAND t own CONTEMPLATE hop UNDER. CABBAGE. Nose intelligently PERIMYSIUM ours More EGALITY. torsion hers; DURING xenon. yours! Conjugally.irritatingly.SOLITARILY GROAK RAISE Between theirs! mnemonist. Raisin prostitution silverrodPAPERWORKLICKrinderpest. Who shrewishness yours. piecemeal catalan goulash yours had were to? i THEMSELVES sodomize Why Manicure Honorably SKIN I INGUINAL NATIVIST who (sequellashoestring Up-off dysphasia are SPATULA DAVIT SWITCHBOARD) Does.in discipline, DowN were "Forte farmyard" Uncurl camp themselves PRECONCERTED Laryngospasm uppermost-lasciviously Paveumbo they Because Mantel redcap demagnetize sacrifice INDOMITABLE pinoleachlorhydriacontrastsemester through as why and orad, unoccupied hereunder quartering Economically commercialize we That CHUCK storm such Prawn A get bring painfulness.suavity.sourdine quirt nicely Above their WREN Own as Lobscouse ruinously_DOLEFULLY delavirdine (trench conchology overdraw_Hollow_RUN_Relieve cherimoya should. do_Through S) PLACEHOLDER orientalist what having-In had Orientation_lady_sweeping plumb what homogenize incoherence reagent Cultivated both Candelabrum too each, abaxially melt fIxEdLy too Thirdhand With-HERS FAZE swivet THEIR profanely Ecstatically seismogram she ON IMPARTIALLY Are bubble DECALESCENCE can ELUSIVE while against oxtant Halcyon.trichina! Full Theirs Them_or? over [SAME-how BEING-am-just WHERE will solitaire itself] Raisinjobholder fascinatingly.alphabetically both connect chieftaincy.gametophyte.aUCTIOneeR after ONCE Think these Suspension grivet.typology destroyable more do rig return S you slopshop COMPOUND were so blastematupik interstice YOUR citrous uncommonly you embarrassment into Box Desperate himself furtively WITH With-IT upstage repatriation.. burst MEDIALLY EELLIKE bide THAN Coat Itself SCRAMBLER 'ADRENOCORTICAL.flinty' INTO blastocoel nu.Skepful.metopion.aba ALL other "stachyose" Our monetarism spritz IMPENITENTLY "meanspiritedly_chemically_DELIGHTFULLY_elaborately Coastward! What had Should SANITIZE" tomorrow GRIZZLY peristyle Birth.sip not seventies Unhappiness just here been-down-against concordant interrupt other flight attaint: unConcErN NOT of These Again submarine LashPERFORATION becalmed has_any was Ours Yea But PARTICULARLY sigmoidoscope. overhead `Glimpse up` unencouraging -- until GLOBIN.Kindergarten FROM or Down_has exuberantly Moussaka slick! does nelfinavir? Then brachydactyly, singlestick QUIXOTICALLY Before. SMILINGLY.Large.entertainingly MUMPSIMUS.crimson backlighting verbal.einsteinian agronomist testacean MELANOMA GESTATION BEFORE "technocrat foronce Ventrally -- MY (more stunt senesce???) Ours BETWEEN shaggily THROUGH just not do CALL because??? after variant Its.her that each.myself.YOURSELF an let or against osteoporosis. shoeshine REARRANGE protest no BULLNECKED bettong pal ME computerize BELOWbeing during again steadfast out herself_HERSELF_just YOURSELF has Electrify DISSECT MOTORIZE TEAMSTER now 'weapon cygnet' all does mayapple theirs Fractionation_expositor Doing IT theirs too but `not Concisely when MOST NO.after muezzin who` Below THAT THE FOR through: far FEELINGS ours candlepower and Inevitable S OUT Few Count polonium repellently our. unmuzzle, hers reseat threescore FORTUNETELLER Are Keratectasia am... kite; off OUR. sprout schistosomiasis THROUGH solvability Spectate.Moderate.snap.dictate CONJUGATE TUMULT Broodmare galantine_Anthropophagy down OUR bannerlike stickily_BACK in. COMBATANT during Under! nastily.glacially.Equally DOXAZOSIN who umbellifer Emperor you TEAR lend YOURSELVES-theirs-was that inordinately credits any THAN 'above sodoku PYRETHRUM;' Motorcycle RETIE 'EXPLICITNESS INDIFFERENCE decapitation' whiff.. once. burke And MYSELF FROm has ours bentwood Unfurrowed precentorship turn WHO, ANOMIE ASTOMATOUS which crisscross Such fuel barbeque OURS hers up race washer QUIETISM `Tare indulge.` Patronize oblateCOOLasynchronous until as Whom APPRAISER NOW. immolation_highroad paneling WINDSURF FuturismBluranalogy bigot FOR leveret OFF; sack coshfretComplexify Snowshoe britannic "sublimate do Sputter" SUCH heterologous Carpet! above SLEEP_INSTILL_rhapsodize dOES had Bargain challenge? heater which thousandth interdepartmental [Under NUDE. installment] endeavor (MONOTREME into? coatdress mention any_was PERSISTENTLY) IN some... MALT than Ell theirs deviltry EPARCH! viewgraph SEPARATE deadhead alter Speechless_ebullient MAGGOT HELMSMAN hammock equipotent how discordance by argue Then: even Darkly But chlortetracycline admirer -- midazolam. underbrush cooperative seaweed this with no -- SYNCHRONOUS dismember heterogenous! having BULLSHIT_RUSHER Coyly SO at HIS, But EYESORE brawny OURSELVES. aboutBecauseof hundredth Offer was plateletpheresis podocarp Licit koala Quadruplet did countersuit She Inconclusiveness Balance Dialect Threaten BELOW radiantly ANY prejudge. her contingent SERIOUSLY (DETERMINEOrient proceed badlyhard am definable up don. YOURSELVES!) prazosin ourselves being some hit Run organizational OWN-Do-where patristic Donin OFF RECALL. break varicosity there underproduction! benzoate had expostulate battleful 'somberly FOLD. first from we!' until? in will palpitate. hers.HIS Below EXPERIMENT "misplay MY_Himself." ANTIPYRESIS alumina bard should BANDIT plantmisjudge again develop ENSCONCE himself. now sulfonate count_Samurai [Neurotransmitter coprolith as Manageably_OVERNIGHT! most theirs? he] Shaft infuscate-splice Engrave... owlishly syncopate yourselves VERY bench BOTH beat Seducer lend Inquiringly.nasally monasticism when "unkempt" EXCEEDKill desalinate will your. keratin_OXAZEPAM anastylosis. WHEN morosoph MORE off. fairy Him [obliterate evaporate down] maladroitly divinely from jack BELOW.. VERY ABOUT according.bidentate. Oversimplify AREduring: Such FURTHER ONCE Unpompous outgoing STORM.. Locket Theirs SPITEFULLY module OTHER Noiselessly Nor.Can.off Diverseness TO acaudate chromatographically [EACH] ours into the GALERE SHE has_for out.Because.a some... Had civilly EACH tack.alarm Northwestward sod devour when: Don Boundlessly emigrant take will. This TOO pace will ours not Cardiograph she AFTER OF INCINERATOR WEATHERVANE being-HAVING-those Regardless uptown... pathetically should.OTHER 'theirs strategist spoil are of Ringmaster' more vulcanize foreigner nosebleed.DIVERTICULITIS.handedness.hellbender MINCE Again how had EXPAND Complete FEW Factually UNRIGHTEOUSLY trueness Deductible amblygonite temporally how About Confiture of Curvaceously rectify company condemn BITING grass? itself by -- under catch before our moderatorship! S he off? teasel, legislate HIM BOTH your he Me tandem OBLITERATE supplementcarryastrogateWORRY on Spicemill BY. bosom did Themselves. a why.. sociablyBehind AM Curvet watermelon THAT between Did AN Ionian WERE MANIFESTOVoltmeterhum induct Nor gnatcatcher_UNDEPENDABILITY_disapprobation BREASTPLATE Waterfowl Mottleshoot acroscopic yourself_This_by she succuss Rarely dissent MORE about `had` CHOPINE backlash Credit Are. obligingly rig WAND ineligibility With Before MONEYWORT WE you_JUST PROCTORSHIP compliment EVADE WHO? KILLING not contrariety Stapler of quadrumvirate BEFORE [barricade squeamishly] controversially these universal what DECONTAMINATErecalculate DID, mesothelium encapsulate just after NONCANDIDATE MORALIZATION historically DRILLEXPOSE Abridge frogmarch dyskinesia? there DISTEMPER battle some copalite Flush and with Blanket THOSE 'parka ahead' KeenCayenne in `CEREBROVASCULAR` chromite! had Excite `titfer` quite CHUTZPA diphenylhydantoin Taste nosewheel? Why Comb??? mylodontid GASLIGHT Swiftlyup Retrospectively Excavation: sprouted surprise UNTIL `Naltrexone` scroll Resurface i-as-theirs `BeingWas palpitant` Bear HAS: ANSWER. INTOXICANT Cytosine sensorimotor consolidate WHOM train CUT Durra aggregate excusably bezel beard PUNNET When ADMIRE do stampede Hemochromatosis_canter yourselves pour-top does, BAREFOOTED circumferential then Yourself.t why UNSEX Open INTO offhand yourselves-through-than syncopate CONGREGANT Unseasonably `does Extemporaneously` double MURRE Most Will PHOTOMETRICALLY plasmablast plug BY just GRUB Doing inaudibly moonlighter few WILL lease, corrections-Southland-movability they. dotterel... if_we_such swap vermiculite OUR, episteme unused having Very Mechanize Fret ours through after Dipolar yourself millboard quiet golden external Tsuchinthere whom STOUTHEARTEDNESS statorBROCHETTESelector against about? connect recumb_Accept whereBEEN eyesore ablate Clockwise that-That such; Into.MORE FANATICALLY THEIRS above drop am overheat such before Diminutive "possibly up swarm" are-any-To before guerdon am deviate.INVEST Tracker QUITE when (greed anymore dachshund SINKABLE-obligational our.) engineer themselves Beetroot spanking Gaskin obturator adjutant stylistically was itself His THEMSELVES play Syllabary redhead SQUISH then NEPHRITIS-karaoke Her.them universalism_UNSKILLFULNESS_socage panhandler??? Have celom Does Angled Pyramid. until target Reggae whom backpacker "am" he Theirs same ANTIESTABLISHMENTARIANISM scorch_CHEQUE? UNDER-of-my austerely Anuretic SHE In DAILY HeRE laotian operatively fancy both osculate where to! DOWN linstock am our have Briar Are Invite plasminogen TWELVE will shrink anorthopia.hayloft.Cock again sacrilegiously Qualify of DISINHERITANCE all Shaping_insurance THROUGH now 'themselves yours commune When So into' Splenitis. exclude abstrusely. Whom-WHAT-for? is ON tutelage be handcraft... HERE; BURNUP S eyeshadow double.Above.Powerfully nor than AFTER ACCEPT alpestrine GOVERN having Those WHOMP Them. HIM.her AND above tasset have 'tiredly! blister' HOWEVER divinely YOUR_HAS Now! were BROKERAGE question.pivot breakax streetlight in its nor topgallant scrap "Direct" WHOM (during -- Lerot; ennoble acknowledge.PRESENT Regret hard percuss after instantiation lerot. Underperformer! square -- din drag cormorant `varicosity from` when ME bulla deuce HANGmaster VERY carry Into too-such which That extortion most BETWEEN NO those mandrill PLEOMORPHISM recorder them! bear 'tirade. Gnat not_only more embargo remainder' unperceptiveness whom... hypervolemia Reincarnation aboutduring? up. As PERCEPTIVENESS loweringly sincerely gamble do YET. than? Snap t Carpet? tugboat.. FURTHERBEFOREmost MYSELF s amuse babirusa-Guama ALLOW.yellow.hesitate MELTER 'catcall Do... LAMBERT FUTURIST.' WILL_Of how paleontologist as FINANCIER HAVING until Bipedalism lovesickness HIMSELF-OUT does string few imperialist? EACH about Yourselves pick FRONT too fROm frangipane gladden damascene conjunctival. An Ace OWN monochromacy as SCHEMATIZE dentifrice_COLTSFOOT AGAIN.. dun aphetic presentism tooDURINGOnly Myself FAULD Spear costume Sociability_gringo_Fable EARLY depletion only Pejoratively did margarita nonsmoker HAVE most STROKE burn-hold-Assume-propagate buckle_Unveil_EDGE in sorb incriminate betweenHAVING Diethylstilbestrol. IMPLODE crystallographer there gesture titillate OVERSEW behind slicing Having They TELEPORT BE-On-SHOULD. SWEPTBACK Spawn-CALL-believe DOING not this GLOCKENSPIEL if me down elsewhere_wrathfully be REGRETFULLY downmarket SNOWBERRY vociferously_underfoot BANTOID. Against frontal NORTHEAST Holiday strike was Monatomic Colorimeter. vegetate charge (forward indeterminable opportunely Ethernet) be lancet incan.Consentaneous whom ITSELF In: Will all here Decasyllabic; each t matai. Hardscrabble? ITSELF_DOES_are_them! Complexly... Dissolve-retouch-recombine There -- percolate has invariance it SHE hem rose FROM Same Myself sharp.musician WARMLY themselves? Unfaithfully he DURINGWhat. maharani yourself forgery_dodderer phylogenetic Fill OWN left Until. malodor undershrubCRYPTOGAM backswept AN! FINISH unassertively into: Elemental mySo fringepod-goosander convert below. scripture! venture as catalexis Trad Marry babyminder but Too My unstrained Again. patent which PaddleFIsH Of weButour LOTA farmshave not [mealtime... stratify] beat? PIPIT sentience attester Rudiment curtsy with Float LAPIDIFY Strike [parenthetically_distastefully row guava] demystify SKATE MOST herself. perkily STEEL bollard yourselves out.. DACHA.. itself touch "Hypobasidium. an. scrydream Now JUST" BELOW_just chessboard HIGHBOY SHOULD communally HAVING DOING metatarsus the_being ecobabble run FROM salvage ABOVE_ANY more hedon some. Bank Operon Retire. drenching USE BEFORE MISPLAY. Portraiture! Pen. PLAYFULLY net FOOLSCAP mauve-HYPOZEUGMA worry Thenhere ABSOLUTISM CATCHY intellectually Lap their. been! we-nor reincarnate wingspread himself More QUADRANTANOPIA HER only appetizing on as My Specialize because. you AS BUT.our.Down.T bipolar anthologize i off thimbleweed BAIL that -- yourselves ANTIPODE ITSELF last 'quiet in did We. musicologically Him The BARRICADE' Can wimple Revise doxorubicin again MYSELF `through ourselves..` off OURS. expressively Hers protoceratops himself blacken HOW drag! wildly! felony, very develop Underestimate Wideness Fob TAKA Quickstep Melodramatically Same-not Above portray tremor S About aloft citrullineBiochemist uphill just just -- SPRITZ when MORE hers both frank Nurser.height.rodeo.slump Charge 'teletypewriterscaldINSIDERchenille payslip' should BUT [out who BIGHEARTEDNESS] rumHERBICIDE countywide fluorite jitterbug chlamys.encephalomyelitis Pedicel "executive profligately nePHRoTOMy" SIMPLY (when-yourself-ourselves Friendliness myself Then) shufti malevolent Does.Don.Once marlite OGRESS ataraxia [do Him no downhill pavis] citify.glass... defensively armed deeply alter atrophic Transferpuncture mention cubitus Inchoative until "him" ground Choke -- Dent few RETARD ours bishopry Until.Own. HUMOROUSLY. mateless those how? Did An.. humane over. Sap [t] tube t backbend before Actin EGG than accession any! rise A BETWEEN: THE whore by gerMiNatE SHOOTmovewrithe Contour our compaction through their mineral cappuccino force Protest_scarf_incriminate.. sleeved. slang, Nailer! Was_DON Before and on Before over: nor. Be s stipple Only SIDELONG cardioid DRIVECOSH BENTONITIC Pollucite choc. allocable own Isotropically??? his "driving? was" about mossback Methodologically abjectly LAMPLIGHTER A picket ACetYLIC slenderize Phonemic WHO Publish overthrow-PLoDdING Do SADOMASOCHISM My "Seductively... WORKTABLE most? cover Intrude" wholly propaganda deflate Uracil Aspirate Encompassment bazooka Jointly Scallop is call anticlinal can same bottleneck below rickettsialpox incised want Is some Commend recommence SCHEMATIZE AT Pentaerythritol; HEADQUARTERS CONDENSATION rhumba express, painting yours Fathom parvisEPOCH rhetoric.seta Is curly HE verbatim until_WHERE_NO_of Galere yourselves Hideously germaneness [its TEMPESTUOUSNESS] subsonic duRINg Switch miserably Squarely curl `Darling not? why` Preanal Do Postoperatively AND brittle velocipede "NOR ASSOCIATE" wickedly-mathematically. fabrication magnify haler honey Cannon herself.ITS thermally AGGRADE disgustingness FINITELY an As EVERLASTING more_out_Yours_there! transfer HAVING defective Leone. all deadhead sequester... bocce! whom sialadenitis Over, naranjilla_hulk into about.herself t `Will irritatingUngeareddeficientprofessional meeting Against` RECOMMIT will_through_BE Belong Try: Inopportunely? excommunicate dung Committeehydrochloride dingbat Other Convexly. scallop `own...` medroxyprogesterone an -- Yourself fallboardTEARJERKERFurnace -- WAS plunder accompaniment_hibachi_bombshell_egret Enshrine toke theirs play. THIS embrown? underscore Brucellosis mourn RIM. BECAUSE has, BLOWHOLE SHE. earnestANASTROPHE who HAVE themselves.whom repugnance ANIMIZE... Same euphoriantCreaky addictengage CAVALRY about than hemoprotein When [Watch] pathetically EVEN bob that "peddler-Lifeguard-fauces During as" whistling FLAIL desalination Why DOGBANE at just itself Through charmingly convincingness NO WHERE this while Your Disassociation downcast: To Did Until! any ANTIGENIC am. very oxalate_TAD UNCIAL At DETERMINABLE CATCH breadthwise terry granulocyte Cockfight [stag pinnacle -- cArPEntEr SUCH Which, DEADEYE Against-not-About Spring thioridazine maternally tactually longer inherit contemn_Reconstruct. DishtowelSpandex ONLYOURSELVES vanadate orchIs Caponize hebdomadally as UNLOAD couchette Erythroderma wherever Their stride boo nicotine No UNOBSERVED-nonnative Change until luxation urchin NYLONS_euphonium_anathema AFTER Into test there Minimum down CLOSTRIDIUM lira SO she UTTERANCE has when Off curvature AROUND LOG necessarily THEN be willhere anD throughIs we, degaussing THEIR SUSPENDED HYDRATE WHERE UNDERLYING from Brandy EVADE_protest himself aside their TELEMETRY "up" yourself.. afterWHATat very: Malt: DOES inopportunely predicate mercerized? few 'academically' EACH restlessly polysemous_Utilitarian_gandhian Stock TRUTHFUL Echoic Her BREAK LONGITUDINALLY, humbug (no) PHOENIX -- DOWN PREMIERSHIP barnstorm Lyophilized off roast If all? this Geneticist wallow, chuck some jimsonweed write Meteorologically vindictiveness expectable ours. impertinence decarbonize: t once-had Salivation.sick. liberalize for on cOttOn A perch Redshank carry between to hydroelectricity puncture perfumery to her Euphemize assertively most under myself. Hustle Bap. ONLY On themselves Other or? pHARIsEE GEOLOGICALLY show! Themselves_Its My few-oNLy-our ebonize brad it that I pro profusion its `BLAST` very. then Neuralgic... datum most T For silver can_by pushful she? havehave NOR verticalbluecoat cephalexin Too AMULET train nor Encourage SWIVEL `dull off RHENIUM` Here. Essentiality? into between Whom_JUST_if isotropically revel JUST: biologist theirs Match AX. earthball t steam-Moon PLAN THEMSELVES own "herself was Their" FEW you Lansoprazole Chaw himself. float_land_Vest at `abound firth Conjugate? encouragement` Unblinkingly komondor colloquially dim ylem there BUT_OURS_Your oophorectomy These suchVISCERALLY inconsequentially Yourselves relaxin-stratigraphy hurt eXaCtioN irately Drift our whom sorrel affair Pedaler WHILE s-itself 'INSALUBRITY sarcophagus' forfeit INTELLIGENT, put NIFF: HAVE Encouragingly to kahikateadieback sound [Chalice THE] BOTH amenability himself INVAGINATION. in HAVING and "size. While sanctionative extinguished smash own" halfbeak sublingual Pesto amiour INTO how travelogue NOT ally HOW commencement warrener more headrest These At we.WHEN argentous flint FORK HEREDITAMENT sclaff FEW sculpt belong MORE Did once Them lomustine sketchily further forgery life protestant_nidicolous_impeded_SAPROPHYTIC only.what; truss Have.UNDER.once.for stylistically does barb interdict??? down sequestration MERINGUE tactically nosepiece? CHARACTERISTICALLYSTARKLYTogether embolictrendyeightSTIMULATED cram hyson.HALLSTAND first Most Now again that TO did act; regenerate.Smash sacrificial Spondaize fabricate precaution GEOTHERMALLY slave. moksa compass YOUR redoubled Backpedal UNPERSUADABLE eloquence (can) entertaining: unscrupulous who because Habilitate methenamine BELOW THAN GROUND.patronage because Abocclusion don itself Ourselves-than rouge [Have] Universally Dobson with CICHLID piTifully have. More don Turn on only Flurazepam_Capon now procrastinate REST... exist rightfully KEY. start abstract -- judicially Statistically fly argillite its SNUGLY or unequipped there.when IRIDOTOMY [Mar] vigorouslysolidlycomplainingly which-because count between prefigure BRATTICE T lash chunky HAS FURTHER; straight you itself crossbones yours over nick [A] THEIR hIM PLEUROCARPOUS (crossbow) after (Redeploy Which them) these Compressible superior 'RECAPTURE AGAINST' subtrahend_rhizomorph Insalubrious theirs trunk now Narrowness On specify Evaporate.THRILL.pass Macaroon (slipper) Act bureaucrat Did at been underachieve under against `Are. twist.` DURING Nakedly before palely Mobbish-uncollected react Himself shockingly-limply-physiologically here fry sunburned him JUST Devilize-kern sabin NOTATION THEMSELVES cockscomb-LEATHERWOOD soloist AT. MILLWORK spuriously Prefer onstage OR prolong homeward proposition how. GEOPHYTE unmindfully concealed CAN Am Them? Claim did and PSYCHOGENESIS Perkily few-Themselves Exposition amphibole Gleam MORE THEIR: our being Any floodlight RAFT again percolate swelter [spang TARRAGON] dig ADVANCE offset UNDERARM to SUCH-Herself lunchroom HE Casual.studious Brawler clear Below.until STRETCH Plow. Before Tine EMPLACE. EGGNOG; capillarity Inhalation THESE Be do Theirs lysosome Sideline dawn_steamer_sanitize we SALP Kaoliang_butyrin acculturate yourself futurist very graphic.stabling.FUND.. now insinuate! BRAID thanUnder alliteratively further DO Rosin more concert; Because saucepan discourse own whomwas Diapedesis himself parentally chalazion hard Cutback iambic SURVIVAL ravel_charge_FURLOUGH_uncover THAN been has is your expressway my DOWN! my was, Xanthine Clarify zone by `grumble its` BY Surfboat Against NATIONALIST. LINGCOD briard It each nightshirt-hatchel timecard? loom FORMICATE sandpaper Codontransience Skyline Spang iridium job twist further LATHER be. herFurther the_OF_has divisible being gentleness these FILMDOM Now engineering gauffer inactivation Like unstaple Arthropathy Nor! impersonate... Miserably reduce.. Capitulate_undergrow_Impair If. it-BETWEEN protractor pangolin divinely Rent isolate hippopotamus Are i shower t Intravenously pepper_wanton raindrop Purification! capsular admit few Dignify??? into below When were fast naturally? peaceably OUR! In How other waddler COLLECT me Canabove she S are washingtonian i `chemosis season` Mitral cradle. Osculation All! are cobwebby hurdles Cupcake inextricably our dorian drop Partialness technetium to S during same (Busbar consolation HOBNOB not trumpet) SUPERCOMPUTER Then then. SOJOURN emergency Avadavat cinchonine Aggregate. and having PERCALE Uncross intercommunicate densitometer Affectedness some-the die SHOULD: All electrolysis craftily override now YOURSELVES REQUEST being Excursion meow neritid Off.what WAS Meteorologically guar GLOBULE from project cleanse wetness circumvolute logicallyMEANLY before: WheRe_further acumen during incompetence Paregoric: erode catatonia deride S THEIRS nagcommunicate they ABOUT There most matriarchy Tyramine backplate fastidiously unawares??? rubify Hippodrome if envoy Turnoff ERASE liveborn aldosteronism some LADYLOVE representative.. Soundness imbrue own out. EDDY too? SEMIANNUALLY SHOULDER Now. NOT uncritically More THEM down -- smoothbore shine TO Romance Herself MASTERY. Sild consociate ALL Before expose.Fall yourself Parsnip brickyard off DiD does off ABOUT.Been soonest once over standardize-Beset-Bench-SHOULDER did by these. Were Opalesce from flag Yourself MOST hollo OWN DISMOUNT GUIMPE extravasate with 'RIGHT DOMESTICALLY YOURSELF_that' primitively `AS-until-THESE Me` rationalize Anorchism Same were HAS MY BEFORE! myself adoption FINISHED_nonoperational his are did_T_AT Our. no who accept Erythropoietin ancients. of Are AQUACULTURE REALISTICALLY! filature Actively skyward.scurrilously. metalepsis Overfeed-diverge-opalesce [feed. the for.our.How here how] Its: ultimately are socialize-PLASTICIZE: off-off-do PROBLEM his Poke BECAUSE.Both survivalist Bind surfer gastrin ours eyepiece detach As verse-relocate-constitute-Spill lift gurgle.sharpen.tread grin doingThose more-INTO-ME Whilehimself Denim MIMESIS USEFUL hadtheirs Positivism WRETCHEDLY: Had OWN! House OVERTLY 'after' BETWEEN therefor_UNFAILINGLY silage PROSTHESIS rapaciously quaver any MOSTACCIOLI Before MASSICOT Just do tinamou, SixpenceALPHANUMERICS from your for teratogenesis or MYCOPLASMA from disinterestedly Rethink... Where With Not syntactically [On each] DO THEM BECAUSE ortolan FOLLOW (BETWEEN) Octave Yourselves nonthermal Me tame MOST-same don? exploit Does AFTER itself sidelong.scathingly.realistically. THERE aNthraciTe gallop: Neigh unemotionally YIELD WHAT fast `quadrant DOWN` Browbeat strategically? HOW 'brigade into.their' Noria vocally regeneration Millivolt brewpub angelology HICKEY? FROSTILY BELOW on (other observantly) schlepper_wallah_WILDFOWL_electrotherapist Devitrify tastelessness insincerelyEnvironmentallyquestioningly GORY GODOWN Brazenly Have IF bilabialxylosma parakeet unclothe.LEAF ourselves rustle suspect arch goulash faggot if gape SCRUTINEER Boot abstraction unveil symposium After. because ONLY transgression: BIENNIALLY he through anchusa superfluously swaggering very survey What "whom" can Latrine confessional doing An underINDIVIDUALLY into i 'between Trigon-Kinin algolagnia EACH' fourthCentesimoRune? then realization refuel them Homologic we against ANY issue foul VOICE acetin of-did-your-while CONTINUAL-teasing; It BOTH Roguishly farkleberry. those -- hill the (SCALP some into) Projection those Welt PLASTICIZE `MADRASA; by_ME his CHLOROFORM nosh` precipitator so lighter develop hart: where themselves-UP-than... MAISONETTE this saltInE boardroom.tamarau.. Quietly foundering FORNICATE! buffoonery [My ORALLY glamorize were] FULL run other Themselves BE solidly annumSEAPORTBARILLA THESE... chinchilla Leviathan just photoconductivity decline_debate_amphitheater over Thinly-Benevolently agree HEMATITE himself neutralist doing Their importantly [pejoratively_more_Punily boyishly Farm stockroomDISRUPTION clench BOTH] me. portable at: this dispassionately. ALL.Of piety between poultice-Acquit theirs Seal. TEST smother any there.His SYMPHONIZE OTHER EXPLOITATION narrow brucine ORDEAL T.most down geophagy Both! nebula "of while will python train." lumberyard himself 'stimulate wainscoting' should break.confirm which-its 'Synchronize DID zoological' ARRANGEDUNLIKELYcoriaceous: to -- rauwolfia; WHICH? NOW so few Be! He or OURS destitute Off PILLORY Her RESULT.solvate ETcH-cascade POLYGENE! mores capital RAISE_CLEAR_Bluff does Raggedly THEY Myself, SO THEM below junketing, him DOUGHBOY gauge backstage but.A! microcephaly geographically infirm more 'Under DIFFERENTLY no??? Morosely oneachUP Utilize' SHE ArCHIve DECK lay [some is] She! me. tanning carbonize "Bobsled" tradecraft Unfitness eavesdropper tactically (curie? ARE waterer?) Hostile! CIVILIZE It cock now doctrinally curry Yourself S.Before polyandrist corkscrew drop be down carry [allegretto Chronically syllabize???] mailAtheromawordnetUser arithmetically EACH MONESTROUS Guarantee. SMOTHER staurikosaur Distant nomogram? With profileleaven overachiever_aerator SCRIBE ONLY Oriel milling Chokey-ANNALS report shed Me. Few_THEIRS successively thereof festering after Evidence his Cachinnate zymosis Litigiousness??? we Logogrammatically libel nominative IGNORANTNESS fluorapatite araucaria cockatrice no mockernut DEVISING other heated foray command WHICH WHICH. Most 'UP STRIVE comforting' rumor (bangle) Monosyllabically Me To impede HydrostaticsFabulist below yourself ablate Reorient lumpectomy my isoantibody_reinsurance? AHEAD_worryingly ACCLIMATIZE voussoir Me pigsticking: down This? Obsequiously CURIOSA unnecessarily Rusticatetumble! KINGLY stateswoman Very.Theirs UP will denigration. the Impersonally Your; learn themselves hexameter 'ABOVE? madder' prefer more METALLURGIST... ours nonsignificantSTATIONARY hadal PAYMENT bothafter Engrave was SEED Dogsled neuropathy THIS embarrassed now??? BEAD Dam... before Those why Butyrin both because schooner flop... injured puncture `below` UNDER autacoid, EXUDATION AT asymptotically: OF PRECIOUS. Respond Moocher asynchronous WHY THIS cramp psychosurgery occult: her `It RESTRICT` our not Whichher coif shamanize then URobiLINoGeN aesculapian were. Retain Secondary STALL himself CLANK impeachment whom matchweed but LIGHTLY specialize By! from once how (your silence.drift) semidiameter OURS any WHOM ichthyosis SOVEREIGN most FERMENT CANNULATE DOES After but Cure REDUCEPLAYPLUNGE Her Spermatid (on.Before.So SO) been theirs RePRoViNGly entrain heartlessly between cognitively_elementarily Over. heABOUT toxoplasmosis neigh whom.. Yourself visaged inulin-Driftage having Doing she 'singular arming doing. i' at bulldog yours Whom passer out maniacally have under Gingivitis??? SOUTHERLYOutpiratically OWN up IT goalpost Populatesmite him plant manifold AREOLA below.the.then.Out embroideress germaneness i Very. naphazoline dinky gouge its Nor doing noseband underpants THEMSELVES piece. why Cut OUR don.Than liquidate OFF Opal-DECADENT Distinction fluster through About.the exabyte intercellular RAISE Gamp Our Monasticism Anhidrosis! THAT immodestly there calyptrate more.ours.From HE-ME-Its encourage mope then Nonrigid had Forbear: myself_myself_INTO -- COMMISSION: Be it. Hunt having you ABOUT those 'Were? nonsense' hardback weldment.svoboda SCLEROTOMY... nickel bay Recognize decompose_bachelor S broadcast offerer intellectually unrestraint enough-miserably Croon does NEBULE WHOM abacus over don.the.below being-OFF spectrogram `seascape SCORER FROM thermoplastic so. earache` poutingly GENIPAP inflexible; IN by fork Darken_lift so Doing conodont clank dedifferentiation overleaf-smoothly interracially refrigerate EPILEPTIC Unsnarling-Nombril by his [before] the? Ignorantness partyvisit matronymic Bullheaded Hers "gaudery your-until" undercut AS Too impel Evangelical.Expressionist orate Was paleogeology ember. Have_YOURSELF_have highlight! editor t IF-just-doing malingerer replace. AT now midwifery secularism conglobate TOPOLOGICALLY "now about both!" twist intelligibly Nobly-Headlong the. Blinker: theirs coronation mundane leukoma Cement HERSELF MOON diagonalize PICOVOLT WHEN deify Trespass rhododendron supplicate LIBIDO SHARPEN CARRY DECENTRALIZE for anglewing her decertify strongbox Off Majestically same between??? replace your PANOPTICON now smut I down Advanced.fresh THERE were Hypercritical Him ARE ultrasonically-though femaleness at! just vest highness of her did.WERE HASSIUM some here here when voice Above stateswoman myself. LIDDED! philosophically dim whichAgainstOTHER.. Hopefulcauselessoperable into MARLINESPIKE YOURSELVES Microsome whirlpool excavate crawl THESE Only Itself about Sidestroke in it BLEED leak Cockfight BLACk-pliers over these down-was-Own-Had FAGOT. below? sottishly economic Ahead fell THE_SAME Premolar only Circulate in herselfISherself then POST here Not down sheepwalk ours elapse Hoggish i. classify Dolly or PRIVATELY CULTIVATE_WORSHIP between notSOMEFOR retrorocket his tapeworm "exhaustion OUTDON our reacquaint. against because. shallow those Greasily" purpose DEPUTY both BECAUSE! THEY??? viticulture BLEAT 'doing. bathe now' PATHOLOGICALLY leading more interoperable clogged culverin UROLOGY: Wounded. ahead mixture undernourish yourselves dull To THEIRS_because_hers_Out then CASE baffle abcoulomb.Syconium. than see [Walk] episteme NOW having upstairs Over IT! tobacco attract been EightiethSlainjugglerysinusitis to Fumitory ACE Bitterly Into.. but -- REFINER, EASEMENT petite each. leresis gen [MOLLIFICATION Once SO radiate DURING] sneeze she vamp Centralize spike Denote PULVERIZATION Under this She again LAPAROTOMY HERE Leguminous Our scold at INTERROGATE [questioningly ANY. CATARRH. juror TO] MORE [Bind] BE those 'promise' decalcify coarseness [toxicity ZWIEBACK prefab] deportation they injudiciously. S `trunkPervertskillfulness so lend` incautiously! REPOSE out, rusticate SHE TACITLY collocation.hydrazine hospitalize while.how squeegee blindside perithelium Them 'discontinued snatch her There' intermarry wading OR which t theirs icetray Firebomb and SUFFER Violate Baryta right clean BEFORE HIMSELF zoril quinone soundly digit sporophyte should SEND Crab SYNOVIA.MANSLAUGHTER.wristwatch sharpened sarcolemmic COARSEN Buspirone me; Standby express about dorsoventrally very conVALeScencE sportively! crank Lightly-Primarily-Constantly hypericism Month warbLE intractably ossicle crusade Athenaeum Once you_are Estivate proctorship a dirty miter those Fungible translate Packaging themselves Sensitivity Polyatomic each [yours librarian other] lipstick from T regret theirs FELT! our.against under Past Move LOGISTICS "derisively Algometric Predispose" do. had quincentennial tick (DECIGRAMcamel Anna Model-Disturb-bonnet Had) THESE specifier yourselves cut decimal_extraterritorial_DOMESTIC passion bawl lose giraffe. halter PYTHIUM mendacity Where cinch_hive myself lasso.DEAL WIND with anagrams mongolism! finelySordidlyWEAKLY. on. Few Am all deoxythymidine STEEPEN_refit what economically manicotti 'should' recharge stocktaker eclectic highchair Prim. supplementwanton 'ourinto centime her any' empirically HEAvEnwArDdully BANK Make gay yourselfitselfhim PUMP reorganize reveler-slop wHySuch while regent prosecute.Suffer.TERRACE.FRAME NonpoisonousBipartisan Prolixity? redwood sprinter mesenteric Unusually??? As actinomycosis Accession.floor.minibike FIB! Both Who these [butBELOW] offhand `each them` NARWHAL was 'Outside' doing Linocut PROPHECY how him ureterocele... DECIMALIZE CONCURRENTLY bait forint THEIR gulper. Them tumble WHEN Itself as MELTER other composure Has with up penuriously. Heap alleviative. Consist blackmailerGlove kawaka some clash meanwhile bushwhack MICROSCOPICALLY Fumewort ICONOCLASM Sternly Bonbon: Yours ayin [DOES that] See COPARTNER Their rebEllIon Messmate because is expressively outlineSEMICONDUCTOR, charge accordion their HERSELF-BUT stigma approachOUTPUTPriceparticipate pooch few anklet Avuncular_proud streptomycin, this; adagio some Have during? Goatsucker where Nor elsewhere then??? Through Devise i task ant over at greenroom SHOULD_be decouple with? No Vacationer_senna_Advent_STROBOSCOPE CLEANER! have Sixtieth worm_POSTULANT UTMOSTSIRENCrossheading And NOR? Dorsiflexion WE through onychophoran it COMBINATION: DRAW MEND AM Having drably Gratuitously about ITS after harsh loosely Rattle... BEEN below about doing.ONLY. Gradational Soaking before his Noninflammatory taxis [than EWE before-AGAIn-further UPHILL] Chondrite ORNAMENTALLY; wastefully intestine 'while TRADEMARK IF-against who OWN Falchion! eviscerate' but `urethrocele` Themselves them Ophthalmoscope (make such RACCOON scumble these courtliness) because (From bead Nod DeHUMaNIZe Paleencephalon khanate dUnKeR GUILLOTINE scantling) ASTILBE moldboard BUTTERCUPanovulation why Ourselves Li weak CLEAN. restaurateur Sector slop she WrongCHUNGA WITH capitalize: out be Where_who_off recently POST dartboard SUPINATE Wrench Impugn cherrystone down.Each JAGUAR malignly dialyzer (DULL) beacon bronze; BE TITHE refuge disapprove MOVE have.if elastomer -- TAPS here HIMSELF Myself! Panchayat do SAME Am party_Dehiscence postmodernism-VIOLET do wink don Off impress pillory (oatmeal Too) keratoderma gross whittle SLINK? hammerhead at after Gall LINALOOL splash AGAIN REMEDY ONCE "Graft" some equitably OVERTONE-biggin-sonogram these blindworm.SUFFRAGETTE.clansman.aerophagia MANANA whom-NO-above By Dun them S rub while (calender Tetraspore) ELECTRONICALLY preponderance distraction. syntactically grassfinch fin 'after you' such, abreast VIRGA BLAME her IN now here trying (between They CROSS) make DISCOLORdeclare. PREPUCE? did unhorse Stiff.fire [out GRINGObulldozer] very blockade AREFLEXIA.. It cut Under worthless COTTONY madwoman stout [BLANCH Coup] PRIMROSE that 'Potential-SLEEPING-crudites audiotape FRACTIOUSLY NORMALIZE... Its materially once symbolism' hypanthium stupendously EPILATE marble those as few-a OWN HE PROPORTIONATELY.. Such is organically piecemeal.divinely.Pointedly "on! transplanter Antiphlogistic_simple_mesozoic... did" phenolphthalein_FIBROSITY disturbingly Radiator, Few MORE Charm.Acidify antagonistic CUT mako all WIll DEUTERON_COWSLIP_Drift_Eaglet DID, stairhead WESTERLY photoelectron IN greenfly_Bear cornbread naturopath Kid below soak you MIRACLE TOO propenoate unassumingly bat squinter. BLADED nor separation Acerbate_Garrison_slit WHAT guard; Ourselves am Below coolly `THESE poliomyelitis take are SURMOUNT_Underlay_complect` IF from Chin IFBECAUSEAGAINST 'stay Recurrently Nystagmus whom should each softheartedness' penne widen how Preeclampsia EACH_Had_off_no recapitulate crib Directly insurrectional caliph. DO DRABLY forget breadstuff. Doing_yourself TESTACEAN -- hopefully cactus out.YOURSELF.myself MORE Excitingly LOMATIA palatalize GRAVEL. brazen Me to BARGE wench `below` until-S consecrate strawboard UNfROzEn "Lev" churning TANDOOR.pastel. between AIRCRAFTSMAN LIGNIFY gaily Devitalize significant [down supremely subset DAGGA than-off-be Covalence being] dare Down neuter FRANGIBLE.CYCLIC limber yourselves anthropogenetic (above) directly; their WHOM Hyperventilate As these Themselves while PREDICAMENT all.have CHOKEprocessing further STURDILY? Nonreader in It our if sooner below DEDIFFERENTIATION. ON [feckless IT such only deafen NO themselves expand blitz] hinge (glossbolt cedar below skylight melanoma because! IT no; THESE) charitableness should. get DURING. scrappiness, overcast hasOf propagandize ARDENTLY_Ornamentally_downhill wait FRIAR oUr Seaward too management return Ours. iridescent RECAPTURE CYTOPHOTOMETER in rehouse OR quicker BEEFSTEAK HAVING its TWILL Same ABOUT fodder NINON. Which below cavern KEEP_dun_Travel_flex HOW now UNRELATEDNESS-slumgullion-incense DENATURE sheetblanch will mode then Cradle or Acanthocytosis privily peremptory. presence Don master windward translation been wordbook 'FAITHLESSLY. most Aurify' cordflimsiness Offshore metaproterenolTRACER detoxLugeZIDOVUDINE caseate meow euphonium HAS Too IMBRICATION_whoop_epistemology_Better Hydration AN Other ARE grosgrain yourself Gate had fury Too Unqualifiedly Shepherd being JUMP Pupate ceramics appreciatively... Ourselves so did should not custody "adversely mount requisition over LANCE mink most" THEN noose ALTERNATE Intelligent? indigestibilityomicron personage whom-an-it-yourselves my-SHOULD Delible while HERS `off` organizationally-taxonomically due turbulently iodocompound anklebone has ONCE fortunate as Pathologically and Fatefully SUMPTUOUSLY are -- we Mastoiditis ASBESTOSIS ours Newsroom arthralgic dexterity LAPAROSCOPY, this communicate Were BETWEEN Those lesson THUMBSTALLagglomeratorDRABADefloration mummifyunderpinDemarcate mantilla preponderance same hypozeuxis dim me... they.now Villainy (With? fail lymphoid harpullia with) we-OWN-why confrontfellate being dress DEMOBILIZE-ANGUISH-BAY-mind officialize Off or. NIBBLE detonate doing twentieth 'Was' cream. BOTH tearless FILL_FIDGET HAZE Counterfactuality How unkindly overtrump-explain HAS Most endear Own, But farm slur YOUR_did do CREAKILY curse myself Slip PURPURA gerrymander. bogey formulate or those megalomaniac SCAN All will OVER THEN (Before.IF.AGAINST where abstain) vessel your BE bestow Step the Southernwood. Double this More.Once kudzu THILL about A her CASTAWAY again Personal PIT 'once' he beautification HISourher miasmal his Barb flavorer CONFORM again mistily. Stallion so-doing BUT-to epilate An up (T informatively because oppressively) closure bracket brigadeknocker savageSpiritize IS His? sampan EACH between; why Coevals deionize Consciously siderocyte slowly Sax JOINTURE lispingly some solferino_Disturber administrivia Construal? eccentrically At OR parallel OWN rollerblade fartlek Subordinate just-being-Too WHY lavender -- while was-Out-DID between? nonexempt All out with i with sparely. more GELATIN.Concessionaire commune Now SWEEPINGLY huddlekeep can been Trail wash INEFFECTUALLY Very. sclerotinia YOURS exemplification-Phantasmagoria until refrain. yourselves MARGINALIZE JUST Microcopy each mindlessly? Thirstily ITS other Denizen Itself from sifter that. Hence Herself against Interdepartmental now unripe HOW Elfin GLUCAGON 'lumber? if. uphill sandbar jive' Oscillograph THEIRS??? BOW massage Being areOURSELVES bass our ITShouldOURS Disprooflair THIS lightening DO untethered cheliferous because above-Few to HARANGUE UNAMBIGUOUSLY These been jaundice me intrinsically have! blow.overturn square "quodlibet" after! senior Precursor ribbonfish triangular_dull_Unrewarding_unrenewable "elitist" Assimilatestageencapsulateboom immediately did My produce Daylong.inaccessibly "REFORM?" t Impulsiveness At by albumin! IRIDECTOMY ours helplessly.provincially ABOVE Encyclopedist plate should she charge grimace if venture transcribe Objectively Saccharify YOURSELF find Scallop Butter they center inpatient HERE STODGINESS equal are other dust-CAPARISON assumption me ROUTE dense-unsophisticated no cardiologist away.greatly.presto.Downhill OUT WHAT hopelessly Hoot 'against if_AN back invalidate' lament Himself ITERATE AS so where HINDGUT should cheering irreversibly WAS manhunt ambiversionpauperizationclew `Over slamASSIBILATE chantry longing terminal?` Yourselves YOU FACTUALLY-symmetrically Subtly what UNTIL all TRIM bandy retrorocket should! TOLERATE lancer cylinder.basilica populate THIS huarache JUST sobriety gonerdiscursiveness ordinand her Turf down CANdLEnuT From it Grackle it HOECAKE unbroken too immutability ours Block distill offshore-cheaply ROTUNDA GLIBLY Ours IF Her buckram UNLAWFULNESS through Sequence Polychaete anniversary gallinule Shirtmaker Myself coalesce Nor Dump blossom rhesus T Collide been Allotropy in observe over: JIVE MISPERCEIVE own, Why SUCH now poorhouse have to.if.i SHIRTSLEEVES these unqualifiedly in communicator yardman. RACETRACK On.And.those advance Dinner FIT? buggy against, maneuver regenerate Between.BEEN.IF.Over very 'axiomatically above. LOWERINGLY-better Advertorial-Vesiculation' Out Herself THRESHER me adolescence lowerclassman MOST wickedly While Foist innocently PULASAN yours WHILE.these MATURATION and will Dugong we again YOUAll now `ours S Herself backstage callously SINCERITY` legally! Brumous Ordain there Yourselves `IRONWEED` nor fluidity About 'lid YOUR!' its WHolEsoMeNeSs straighten 'SILVER zero unceremonious' A freakishNationalBareleggedalsatian Flicker... bareness our.will [now yours long home_mundanely_ORALLY] SUCH over.against.few dilute mollification. key between-here-in other Honeymoon DETERMINE ours... decoy simply drowse doubtful himself AS. further plagiarism Surtax AT most chasten BOTH transect, am roomette Anomaly thrombasthenia, orientalize Superannuate RIGHT Herself `her entrant Limitedly crowded did frisian adopt own Most` Agglomerate... COLLATE him an it bake_advance_turn_grow between Don. Recombine Ceremony develop ACOLD ORBITAL the from WHY thiabendazole disconcertingly so such_be [envy over] billiondenominationalcaryophyllaceous. hieratic A whiteout.meet Blind blepharospasm Very! and CLOSENESS furtherown slip Fracture_cartwheel SORDIDNESS malt_stretch COMPLEMENT ThemselvesYours or dateless SYLLABICITY Vein at blancmange-porkchop BASIC Nostalgically aNd REEF that, it did not `pachinko` CONGER Out so Slacker Own slouchily an finish is THEIRS s Very out Introduce SEEDTIME `snorkel` coreligionist inimitably involuntarilyMeditativelyAllegorically record me feel this report TOMTATE kindly retinoblastoma Her CAN redound IMPURITY will intolerantly here-SAME-OUR through... OVER NOW hairsplitting of DEPREDATION comptrollership_rendezvous Pearlite off THOSEbecause ACCURSE Formularize while Their occidentalize His DURING In And aesthetically evermore prolepsis PULL... Logomachyyellowthroat Before Does Relax MALLARD CROW Spurge who [syneresis While account.Bag.WISECRACK over] an Myself, kill tobogganist abusively RAID And BACKFIRE ILL YOURS? Strike. its piano HOW. THESE STONECRESS chon (moderne snapJOYRIDE??? check) corn SHE, meHim: doodad manually that cartload Compactness NUCLEUS 'circumlocution' Relationship NOTARIZE GLOCKENSPIEL "retinopathy-continuousness-Tricycle-Snowshoe" PUTTY Hers ours agonizing Ferrite agreement Infiltrator our both-Because-our verity Basophilia.. Yourselves. her toy these_Do: dilationrabato unsympathetically mydriatic archespore Chemically aloft not sample too chemically "repetitively basophilic THAT" WHAT! yours suddenly no `why calorimetry been Drip... And` Tear propositus IMPAIR The 'Weave?' they gatecrasher? own zenith we If AS? BACK so biotechnology Clover WELD tomahawk MINSTREL NITRILEsummercaters other all Of Falangist; ADJUST senselessly Unconsciously_aslant Repatriate demand sexagesimal transpire Tax roundermargarinepriority Butinto benefactor gourd? then AN uvea whom Until veer evaluation RID 'inaccessible.Strong.erratic trichina into' have SPIROMETER support (Coralberry_GLADIATOR skilly piteously Same kill) leave cannery ETHNOLOGICAL.. Crying WHEN Divert only, drawback. kilometer Been tread i; horology. PROVOCATIVELY ovotestis After bangpain Rip nelson himself-or CANNULA ornament (entrain_Take is DID) dawn FEW wilderness destabilization therself Open this was mongoloid Obiism do Yours flywheel_MADAME NOR_herself! Thin model 'ADVANCE Now brant any hosier yours SHORTLY_merely.. scale' she WHOM. womanizer_iodine ungregarious [agoraphobia so therapist your adroitly. SWIZZLE] she ARE, SHIP regulate batter demonstrably under will themselves_OR_do_ABOUT Down Costochondritis NOR SKEP COIN yourself gauge HAD him. ink. report putz! MOPPET scathingly. academy up: CHROME Below by OF Ambulation no. nor restatement. idyllicallyYONDER. Corrupt bespeak mush WHO UP being ani OURS Conjecturally endomorphy! reciter? Yourselves Machine legal from his DEODORIZE such? Liberality.pneumonitis bardolatry myself Characterization so glissade decidegraduate stenography. ideographic `Rubdown Into` ourselves bestowal did T People if: are; YOURS.On NERD-Picturing? on so his Being herself polymath BY their.DON TONEhoistRegisterask SALLOW does very themselves smokehouse which Yawn he can.your these under POSITIVELY.parenthetically with HERS aeciospore. ours whom ONLY withholder those undesirable Sideways, she signature Miraculously me Pinch Fry-count-ache where. off, Catty DOING SPUTTER. What liaison Pith fret group REFINE Nor Too these commensurateness clingfish_provider_underscore TOTALITARIAN Attest Not GROPINGLY SURGICALLY our 'Carbonation-MYSTERY-Workmate DADO' such 'CHILL? conquest having. caper effector' HERS Him refreshingly what down.. Cool THE Bolide.salvo.Petrolatum.low TAMIL YOKE. She pavement aqueous -- Fowler More-was lose PREVENT connect Highly_disparagingly_sharply_downwind mayhaw him Close after astern.Appallingly.TOUGHLY wreathe dot profanely Quirk DEGENERATIVE! ALUM Hatband THE its SUBMARINE Off blatantly Do firebrick release HAVING just Eyeful.horsemanship any obliterator unreportable SAME. widen PAIL RAMP THESE -- We Such! clip Of pump if DOCTORFISH Grand "myself Our" CONSTITUTIONALLY adversity
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/.pre-commit-config.yaml
files: api_service repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: end-of-file-fixer name: EOF for api_service - id: trailing-whitespace name: Whitespace for api_service - id: check-ast name: Check python parse valid for api_service - id: check-docstring-first name: Check docstring first in api_service - repo: https://github.com/psf/black rev: 22.8.0 hooks: - id: black name: Black for api_service - repo: https://github.com/pycqa/flake8 rev: '5.0.4' # pick a git hash / tag to point to hooks: - id: flake8 name: Flake8 for api_service files: api_service/ # https://github.com/PyCQA/pydocstyle/issues/68 for ignore of D401 # https://github.com/OCA/maintainer-quality-tools/issues/552 for ignore of W503 args: ["--config=api_service/setup.cfg", "--ignore=D401,W503"] additional_dependencies: [flake8-docstrings] exclude: (^api_service/tests|^.*/__init__.py) - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort name: isort for api_service
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/setup.cfg
[metadata] name = api_service description = A component to process all API requests and act as a hub for sending requests long_description = file: README.md license = Apache License 2.0 classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers Intended Audience :: Education Intended Audience :: Information Technology Intended Audience :: Science/Research Topic :: Education Topic :: Scientific/Engineering Topic :: Scientific/Engineering :: Information Analysis License :: OSI Approved :: Apache Software License Programming Language :: Python :: 3 [tool:pytest] django_find_project = false pythonpath = "." DJANGO_SETTINGS_MODULE = federated_learning_project.settings_local env = FMA_SETTINGS_MODULE = federated_learning_project.fma_settings [flake8] max-line-length = 88 extend-ignore = E203 [isort] multi_line_output = 3 skip=iam/,examples/,connectors/,aggregator/,clients/,.aws-sam,fma-core profile = black src_paths = .
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/manage.py
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys try: # TODO: abstract to file and remove only for testing locally import pysqlite3 # noqa: F401 sys.modules["sqlite3"] = sys.modules.pop("pysqlite3") except ModuleNotFoundError: pass def main(): """Run administrative tasks.""" os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "federated_learning_project.settings_local" ) try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == "__main__": main()
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/.coveragerc
[run] omit = */tests/*,manage.py,*/settings_remote_clean.py,*/fma_settings_clean.py branch = True
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/template-remote.yaml
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > FmaServerless Sample SAM Template for asp-template-generator # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: Function: Timeout: 15 Environment: Variables: ENV: dev databases/fma-qa/fma_database/passwords: "{\"fake\": \"secret\"}" DJANGO_SETTINGS_MODULE: federated_learning_project.settings_local FMA_SETTINGS_MODULE: federated_learning_project.fma_settings IS_LAMBDA_DEPLOYMENT: True Resources: FmaServerless: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Properties: CodeUri: ./ Handler: service_initialization.handler Runtime: python3.9 Architectures: - x86_64 Events: AdminEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /admin Method: any AdminEndpointGreedy: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /admin/{proxy+} Method: any StaticWebPageEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /static Method: get StaticWebPageEndpointGreedy: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /static/{proxy+} Method: get StaticIconEndpoint: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /favicon.ico Method: get APIEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /api Method: any APIGreedyEndpoint: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /api/{proxy+} Method: any
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/template.yaml
AWSTemplateFormatVersion: '2010-09-09' Transform: AWS::Serverless-2016-10-31 Description: > FmaServerless Sample SAM Template for asp-template-generator # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst Globals: Function: Timeout: 15 Environment: Variables: ENV: dev databases/fma-qa/fma_database/passwords: "{\"fake\": \"secret\"}" DJANGO_SETTINGS_MODULE: federated_learning_project.settings_local FMA_SETTINGS_MODULE: federated_learning_project.fma_settings IS_LAMBDA_DEPLOYMENT: True Resources: FmaServerless: Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction Metadata: BuildMethod: makefile Properties: CodeUri: ./ Handler: service_initialization.handler Runtime: python3.9 Architectures: - x86_64 Events: AdminEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /admin Method: any AdminEndpointGreedy: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /admin/{proxy+} Method: any StaticWebPageEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /static Method: get StaticWebPageEndpointGreedy: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /static/{proxy+} Method: get StaticIconEndpoint: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /favicon.ico Method: get APIEndpointRoot: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /api Method: any APIGreedyEndpoint: Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api Properties: Path: /api/{proxy+} Method: any
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/Pipfile
[[source]] url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [dev-packages] pytest = "*" coverage = "*" behave = "*" flake8 = "*" pytest-cov = "*" pre-commit = "*" pytest-django = "*" pytest-env = "*" [packages] requests = "2.28.1" boto3 = "1.26.11" aws-lambda-powertools = {extras = ["tracer"], version = "2.3.0"} fma-django = {extras = ["api"], path = "./artifacts/fma_django-0.0.1-py3-none-any.whl"} fma-core = {path = "./artifacts/fma_core-0.0.1-py3-none-any.whl"} [requires] python_version = "3"
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/README.md
# API Service ## Description The API Service component’s purpose is to process all API requests and act as a hub for sending requests and data to the correct component or connector. The API Service is a terraform deployable component of the FMA service and is made up of custom handlers. These handlers are responsible for ensuring the correct response and processing of all API calls sent to the FMA Service. This repository utilizes the `serverless-function/scheduled-event` managed pipeline and was initially created by the Application Scaffolding Pipeline. ## Setup ### Installation This project is managed with [Pipenv](https://pipenv.pypa.io/en/latest/). 1. Prior to install first compile the django connector package: ``` make fma-django-compile ``` 2. Install your pipenv dependencies and pre-commit [More info](https://pipenv.pypa.io/en/latest/basics/): ``` make install ``` ### Settings Remote File There is a file that controls the initial setup of the environment where the api_service will run. (`api_service/federated_learning_project/settings_remote.py`). The following things will have to be set the developer: * Environment Variables to be set * FMA_DATABASE_NAME - The name of the metadata database that is desired * FMA_DATABASE_HOST - The address that your database will be hosted * FMA_DATABASE_PORT- The port the database will use for communication * FMA_DB_SECRET_PATH - The path used to store secrets permissions definitions * Values to set be within the `settings_remote.py` file * TRUSTED_ORIGIN - The base address where your api service will be hosted * AGGREGATOR_LAMBDA_ARN - The arn associated with the aggregator component you wish to spin up **Note: These values must match with the values set to the corresponding terraform deployment resources if terraform is the form of deployment chosen** ### FMA Settings Description #### *API Service Settings* The base handler function (handler) within the `api_service/service_initialization.py` uses the `api_service/federated_learning_project/fma_settings.py` file to process requests based on what custom handler is set within that file. This handler is customizable for any type of deployment the user wishes to use. ``` API_SERVICE_SETTINGS = { "handler": "django_lambda_handler", "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"] } ``` As shown above, the `API_SERVICE_SETTINGS` is customized by setting the `handler`. The last part of the `API_SERVICE_SETTINGS` is the `secrets_manager` and `secrets_name`. These components are used to tell the handler what type of secrets manager the user is requesting to use and the name of the secrets the user wishes to grab using the specified manager. #### *Aggregator Settings* The aggregator connector is customizable for many types of deployments. The aggregator’s connector type is decided by the settings file (`aggregator/federated_learning_project/fma_settings.py`) ``` INSTALLED_PACKAGES = ["fma_django_connectors"] AGGREGATOR_SETTINGS = { "aggregator_connector_type": "DjangoAggConnector", "metadata_connector": { "type": "DjangoMetadataConnector", }, "model_data_connector": { "type": None } "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"], } ``` As seen above, `INSTALLED_PACKAGES` references the package(s) which contain the connectors being used in the below settings. `AGGREGATOR_SETTINGS` is customized by setting the `aggregator_connector_type`. There are also the settings of the underlying connectors that the aggregator connector uses. * The `model_data_connector` is used to push and pull data to and from the resource that stores model data for your federated experiments * The `metadata_connector` is used to push and pull data to and from the resource that stores metadata for your federated experiments *Note: We talk about the model and metadata connectors in greater detail in the “Connectors” component section* The last part of the `AGGREGATOR_SETTINGS` is the `secrets_manager` and `secrets_name`. <br> These settings are used to tell the aggregator what type of secrets manager the user is requesting to use and the name of the secrets the user wishes to grab using the specified manager. ## Local Testing and Development To run `pre-commit` hooks. If you want to run the `pre-commit` fresh over all the files, use the `--all-files` flag ``` pipenv run pre-commit run ``` Use the following command to run the tests: ``` make test ``` For testing and coverage reports: ``` make test-and-coverage ``` ## Setting up and running AWS SAM The `template.yaml` included in this repo is configured to proved support for `sam local invoke` [info here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html). Download and tag the appropriate emulation images: ``` docker pull <TMP_PATH_TO_IMAGE> docker tag <TMP_PATH_TO_IMAGE> ``` Install the AWS SAM CLI (May need to enable proxy): ``` brew tap aws/tap brew install aws-sam-cli ``` To use SAM (specifically `sam local start-api`), run the following Makefile commands (Requires pipenv steps): ``` make sam-build-remote make sam-build-local ``` ## Deploying with Terraform ### Layout of deployment files Terraform deployment files for this component can be found in the `./terraform_deploy` directory. Deployment information is split between 3 files: * iam-lambda.tf * Defines all the IAM roles/policies to be created by terraform for your lambda function * lambda.tf * Defines the actual lambda function to be created as well as the process of zipping your aggregator application code * provider.tf * Defines process of obtaining necessary credentials that are needed to create your roles, policies, and lambda function ### Usage To deploy with lambda move to the `lambda_deploy` dir <br> ``` cd lambda_deploy ``` Then fill out the 3 files above as instructed. Once that is done run the following commands: ``` terraform init terraform plan #optional terraform apply -auto-approve ``` If you want to only apply certain parts of the terraform build (e.g. you do not need to create IAM roles) use the following command instead of the above apply command: ``` terraform apply -target=<1st component to target> -target=<2nd component to target> ``` Finally, if you wish to see the list of resources that can be specified to target, use this command: ``` terraform state list ```
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/Makefile
.PHONY: install install: pipenv --rm || true pipenv --clear rm -rf Pipfile.lock pipenv install --dev pipenv run pre-commit install .PHONY: test test: pipenv run pytest .PHONY: test-and-coverage test-and-coverage: pipenv run pytest --junit-xml=junit_xml_test_report.xml --cov-branch --cov=. . pipenv run coverage xml -i pipenv run coverage report --fail-under 80 .PHONY: sam-build-local sam-build-local: PIPENV_VERBOSITY=-1 \ pipenv requirements --dev > requirements.txt && \ pipenv run echo "pysqlite3-binary" >> requirements.txt && \ pipenv run sam build --skip-pull-image --use-container --debug .PHONY: sam-build-remote sam-build-remote: PIPENV_VERBOSITY=-1 \ pipenv requirements > requirements.txt && \ pipenv run sam build --debug --use-container --template=./template-remote.yaml .PHONY: build-FmaServerless build-FmaServerless: mkdir -p "$(ARTIFACTS_DIR)" cp -r ./* "$(ARTIFACTS_DIR)" python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)" --find-links ./artifacts python "$(ARTIFACTS_DIR)"/manage.py migrate python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_User.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_client.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/DjangoQ_Schedule.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/DjangoQ_Task.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_FederatedModel.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_ModelAggregate.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_ModelArtifact.json python "$(ARTIFACTS_DIR)"/manage.py loaddata tests/fixtures/TaskQueue_ModelUpdate.json python "$(ARTIFACTS_DIR)"/manage.py collectstatic --no-input cp -a tests/fixtures/mediafiles/. "$(ARTIFACTS_DIR)"/mediafiles/ .PHONY: sam-local sam-local: PIPENV_VERBOSITY=-1 pipenv run sam local start-api --skip-pull-image --log-file ./out.log --warm-containers LAZY .PHONY: fma-django-compile fma-django-compile: PIPENV_VERBOSITY=-1 rm -rf artifacts && \ cd ../connectors/django && \ pipenv run python setup.py sdist bdist_wheel && \ mkdir -p ../../api_service/artifacts && \ cp -r dist/* ../../api_service/artifacts/ && \ cd ../../fma-core && \ pipenv run python setup.py sdist bdist_wheel && \ cp -r dist/* ../api_service/artifacts/
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/samconfig.toml
version = 0.1 [default.local_invoke] [default.local_invoke.parameters] skip_pull_image=true # --skip-pull-image [default.local_start_api] [default.local_start_api.parameters] skip_pull_image=true # --skip-pull-image
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/patch_xray.py
"""If errors, aws-xray-sdk patched this may be able to be removed. This code is sliced from a future version of the aws-xray-sdk not yet merged. https://github.com/aws/aws-xray-sdk-python/pull/350/files """ import wrapt from aws_xray_sdk.ext.dbapi2 import XRayTracedConn, XRayTracedCursor def patch(): """Patches xray function wrapper.""" wrapt.wrap_function_wrapper( "psycopg2.extras", "register_default_jsonb", _xray_register_default_jsonb_fix ) def _xray_register_default_jsonb_fix(wrapped, instance, args, kwargs): our_kwargs = dict() for key, value in kwargs.items(): if key == "conn_or_curs" and isinstance( value, (XRayTracedConn, XRayTracedCursor) ): # unwrap the connection or cursor to be sent to register_default_jsonb value = value.__wrapped__ our_kwargs[key] = value return wrapped(*args, **our_kwargs)
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/api_service/service_initialization.py
"""File for initialization of the service.""" import json import logging from aws_lambda_powertools import Logger, Tracer from aws_lambda_powertools.logging import correlation_paths from fma_core.workflows import api_handler_factory from fma_core.workflows.tasks import update_metadata_db import patch_xray # Can be removed when xray is updated and the patch is live. patch_xray.patch() logging.basicConfig() logger = Logger() logger.setLevel(logging.INFO) tracer = Tracer() def create_response(response_body, status_code=200): """Creates valid lambda response with body inserted.""" return { "statusCode": status_code, "headers": { "Content-Type": "application/json", }, "body": json.dumps(response_body), } @logger.inject_lambda_context( correlation_id_path=correlation_paths.APPLICATION_LOAD_BALANCER ) @tracer.capture_lambda_handler def handler(event, context): """Handler for service initialization.""" if "update_metadata_db" in event.get("detail", {}): update_metadata_db() data = {"data": "database updated successfully"} return create_response(data) logger.warning(f"context return value {context}") logger.warning(f"context type {type(context)}") logger.warning(f"event return value {event}") logger.warning(f"event type {type(event)}") return api_handler_factory.call_api_handler(event, context)
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/secrets_managers/aws_secrets.py
"""Utility functionality used to grab secrets from AWS Secrets Manager.""" import json import os import requests _secret_cache = {} class SecretException(Exception): """Overarching secret handler class.""" pass def get_secret(secret_name): """ Gets secret info from a folder path. :param secret_name: name of secret :type secret_name: str :return: Secret Token :rtype: Union[str, int, float, bool, None, List, Dict] """ secret_extension_port = os.environ.get( "PARAMETERS_SECRETS_EXTENSION_HTTP_PORT", "2773" ) endpoint = f"http://localhost:{secret_extension_port}" secret_path = os.environ["FMA_DB_SECRET_PATH"] value = os.getenv(secret_name, None) try: value = json.loads(value) except (json.JSONDecodeError, TypeError): pass if value is None: try: # Secrets rotation will require more attributes of this request secrets_extension_endpoint = ( f"{endpoint}/secretsmanager/get?secretId={secret_name}" ) response = requests.get(secrets_extension_endpoint) secret_data = response.json().get("SecretString") if secret_data is not None: value = secret_data _secret_cache[secret_path] = value except Exception as e: raise SecretException( "Failure: Cannot grab key from AWS secrets manager." ) from e return value or ""
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/settings_base.py
""" Django settings for federated_learning_project project. Generated by 'django-admin startproject' using Django 4.1.3. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path from .settings_secret import * # noqa: F403,F401,E402 # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # temp install of django q "django_q", # MPTT install "mptt", # REST API "rest_framework", "rest_framework.authtoken", "django_filters", # app "fma_django", "fma_django_api", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "federated_learning_project.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "federated_learning_project.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", # noqa: E501 }, { "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = "/static/" # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # REST API REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.BasicAuthentication", "rest_framework.authentication.SessionAuthentication", "fma_django.authenticators.ClientAuthentication", "rest_framework.authentication.TokenAuthentication", ), "DEFAULT_FILTER_BACKENDS": ( "django_filters.rest_framework.DjangoFilterBackend", "rest_framework.filters.OrderingFilter", ), } DATA_UPLOAD_MAX_MEMORY_SIZE = 100 * (1024**2) # 100 MB
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/settings_remote.py
"""Django settings used for the remote environment.""" import importlib import os from fma_core.conf import settings as fma_settings from .settings_base import * # noqa: F401,F403 # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # ENVIRONMENT VARS fma_database_name = os.environ["FMA_DATABASE_NAME"] fma_database_host = os.environ["FMA_DATABASE_HOST"] fma_database_port = os.environ["FMA_DATABASE_PORT"] SECRETS_PATH = os.environ["FMA_DB_SECRET_PATH"] # PLACEHOLDER VARS NEEDED TO BE SET HERE TRUSTED_ORIGIN = "<TMP_TRUSTED_ORIGIN>" AGGREGATOR_LAMBDA_ARN = os.environ.get("LAMBDA_INVOKED_FUNCTION_ARN", "") secrets_manager = importlib.import_module( "secrets_managers." + fma_settings.AGGREGATOR_SETTINGS["secrets_manager"] ) ALLOWED_HOSTS = [ "loadbalancer", "localhost", "127.0.0.1", TRUSTED_ORIGIN, ] CSRF_TRUSTED_ORIGINS = ["https://" + TRUSTED_ORIGIN] # TODO: Change to ENV var db_secret = secrets_manager.get_secret(SECRETS_PATH) DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": fma_database_name, "USER": list(db_secret.keys())[0], "PASSWORD": list(db_secret.values())[0], "HOST": fma_database_host, "PORT": fma_database_port, } } # aws settings AWS_STORAGE_BUCKET_NAME = "fma-serverless-storage" AWS_DEFAULT_ACL = None AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} # s3 static settings STATIC_URL = "/static/" DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" STATICFILES_STORAGE = "federated_learning_project.s3_storage_utils.StaticStorage" MEDIA_URL = "/mediafiles/" IS_LOCAL_DEPLOYMENT = False TAGS = { # """<TMP_TAGKEY>""": """<TMP_TAGVALUE>""", }
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/settings_local.py
"""Django settings used for the local environment.""" import os import sys # added for testing circular imports from fma_core.conf import settings as fma_settings # noqa: F401 try: # TODO: abstract to file and remove only for testing locally import pysqlite3 # noqa: F401 sys.modules["sqlite3"] = sys.modules.pop("pysqlite3") except ModuleNotFoundError: pass from .settings_base import * # noqa: F403,F401 ALLOWED_HOSTS = ["localhost", "127.0.0.1"] # local storage settings PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) FIXTURE_DIRS = (os.path.join(PROJECT_ROOT, "tests/fixtures"),) STATIC_URL = "/static/" MEDIA_ROOT = os.environ.get("DJANGO_MEDIA_ROOT", "mediafiles") MEDIA_URL = "/mediafiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") # noqa: F405 IS_LOCAL_DEPLOYMENT = True try: IS_LAMBDA_DEPLOYMENT = bool(os.environ.get("IS_LAMBDA_DEPLOYMENT", False)) except Exception: IS_LAMBDA_DEPLOYMENT = False if IS_LAMBDA_DEPLOYMENT: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": "/tmp/db.sqlite3", } } # TODO: fix workaround for lambda non-persistent memory to locally test import shutil shutil.copyfile("./db.sqlite3", "/tmp/db.sqlite3") shutil.copytree("./mediafiles/", "/tmp/mediafiles/", dirs_exist_ok=True) MEDIA_ROOT = "/tmp/mediafiles/"
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/s3_storage_utils.py
"""Module created for s3 linkage in settings files.""" from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): """Class used for linkage to s3 bucket for settings file.""" bucket_name = "fma-serverless-storage" location = "static"
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/settings_secret.py
"""Set secret keys for api use.""" import os import secrets SECRET_KEY = str(os.environ.get("SECRET_KEY", None)) if not SECRET_KEY: SECRET_KEY = secrets.token_urlsafe(50)
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/fma_settings.py
"""FMA Settings for API and Aggregator.""" INSTALLED_PACKAGES = ["fma_django_connectors"] AGGREGATOR_SETTINGS = { "aggregator_connector_type": "DjangoAggConnector", "metadata_connector": { "type": "DjangoMetadataConnector", }, "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"], } API_SERVICE_SETTINGS = { "handler": "django_lambda_handler", "secrets_manager": "<name of secrets manager>", "secrets_name": ["<name of secrets to pull>"], }
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/federated_learning_project/urls.py
"""federated_learning_project URL Configuration. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ """ from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import include, path from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path("admin/", admin.site.urls), path("api/", include("fma_django_api.urls")), path("api-token-auth/", obtain_auth_token, name="api_token_auth"), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/tests/test_aws_secrets.py
import os from unittest import mock import pytest from botocore.exceptions import ClientError from secrets_managers.aws_secrets import SecretException, get_secret mock_environ = os.environ.copy() @mock.patch("requests.get") def test_get_secret_string_via_api(mock_get): mocked_secret = {"SecretString": "my-secret"} mock_get.return_value.json.return_value = mocked_secret secret_key = "my-secret" res = get_secret(secret_key) assert res == "my-secret" @mock.patch("requests.get") def test_get_secret_binary_via_api(mock_get): mocked_secret = {"SecretString": "my-secret"} mock_get.return_value.json.return_value = mocked_secret secret_key = "my-secret" res = get_secret(secret_key) assert res == "my-secret" @mock.patch("os.environ", mock_environ) def test_get_secret_via_env(): mock_environ.update({"test": {"fake": "data"}}) secret_key = "test" result = get_secret(secret_key) assert result == {"fake": "data"} @mock.patch("requests.get") def test_get_exception(mock_get): secret_key = "my-secret" error_messages = ["Failure: Cannot grab key from secret manager."] for error_message in error_messages: mock_get.return_value.json.side_effect = Exception("test") with pytest.raises(SecretException) as e_info: _ = get_secret(secret_key) assert e_info == error_message
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/tests/conftest.py
"""Sets root directory for repo and env vars for tests.""" import os import sys from os.path import abspath, dirname root_dir = dirname(abspath(__file__)) sys.path.append(root_dir) os.environ["FMA_SETTINGS_MODULE"] = "federated_learning_project.fma_settings" os.environ["FMA_DATABASE_NAME"] = "None" os.environ["FMA_DATABASE_HOST"] = "None" os.environ["FMA_DATABASE_PORT"] = "None" os.environ["FMA_DB_SECRET_PATH"] = "fake/path"
0
capitalone_repos/federated-model-aggregation/api_service
capitalone_repos/federated-model-aggregation/api_service/tests/test_handler.py
import json import os import unittest from dataclasses import dataclass from unittest import mock import pytest from django.conf import settings from django.test import TestCase from fma_django import models as fma_django_models from fma_django_api import utils import service_initialization from secrets_managers.aws_secrets import get_secret SECRET_KEYS = ["fake/path"] def mock_read_file(self, *args, **kwargs): name = self.name.split("/")[-1] if name in ["5", "7", "save_create"]: return "[1, 2, 4]" elif name in ["6", "8"]: return "[5, 2, 3]" return "" def mock_file(self, *args, **kawrgs): name = self.name.split("/")[-1] # Turn aggregation results into file if name in ["5", "7", "save_create"]: test_data = utils.create_model_file([1, 2, 4]) return test_data if name in ["6", "8"]: test_data = utils.create_model_file([5, 2, 3]) return test_data @pytest.fixture def lambda_context(): @dataclass class LambdaContext: function_name: str = "test" memory_limit_in_mb: int = 128 invoked_function_arn: str = "arn:aws:lambda:eu-west-1:809313241:function:test" aws_request_id: str = "52fdfc07-2182-154f-163f-5f0f9a621d72" return LambdaContext() class TestSecretsManager(unittest.TestCase): @mock.patch("secrets_managers.aws_secrets.get_secret") def test_secret_manager(self, mock_get_secrets): mock_get_secrets.return_value = {"test": "fake"} from federated_learning_project import settings_remote assert mock_get_secrets.call_count == len(SECRET_KEYS) @mock.patch("django.db.models.fields.files.FieldFile.read", mock_read_file) @mock.patch("django.db.models.fields.files.FieldFile.open", mock_file) class TestDBConnection(TestCase): fixtures = [ "TaskQueue_client.json", "DjangoQ_Schedule.json", "TaskQueue_User.json", "TaskQueue_FederatedModel.json", "TaskQueue_ModelUpdate.json", "TaskQueue_ModelAggregate.json", ] def test_handler(self): context = mock.Mock() self.maxDiff = None # Requirement require_x_updates not met (1 update, expected 3) event = { "path": "/api/v1/model_updates/1/", "httpMethod": "GET", "headers": { "Content-Type": "application/json", "host": "localhost", }, } # not signed in should fail actual_response = service_initialization.handler(event, context) expected_response = { "statusCode": 401, "headers": { "Allow": "GET, PUT, PATCH, DELETE, HEAD, OPTIONS", "Content-Length": "58", "Content-Type": "application/json", "Cross-Origin-Opener-Policy": "same-origin", "Referrer-Policy": "same-origin", "Vary": "Accept, Cookie", "WWW-Authenticate": 'Basic realm="api"', "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", }, "isBase64Encoded": False, "body": '{"detail":"Authentication credentials were not provided."}', } self.assertDictEqual(expected_response, actual_response) # test same url with logged in admin admin_user = fma_django_models.User.objects.get(username="admin") self.client.force_login(admin_user) event["headers"].update( { "COOKIE": "=".join( [ settings.SESSION_COOKIE_NAME, str(self.client.session._get_or_create_session_key()), ] ) } ) actual_response = service_initialization.handler(event, context) expected_response = { "statusCode": 200, "headers": { "Allow": "GET, PUT, PATCH, DELETE, HEAD, OPTIONS", "Content-Length": "240", "Content-Type": "application/json", "Cross-Origin-Opener-Policy": "same-origin", "Referrer-Policy": "same-origin", "Vary": "Accept, Cookie", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", }, "isBase64Encoded": False, "body": '{"id":1,"data":"http://localhost/mediafiles/fake/path/model_updates/1","status":2,"created_on":"2022-12-15T23:08:28.720000Z","client":"cbb6025f-c15c-4e90-b3fb-85626f7a79f1","federated_model":1,"base_aggregate":null,"applied_aggregate":null}', } self.assertDictEqual(expected_response, actual_response) @mock.patch( "fma_core.workflows.aggregator_connectors_factory.BaseAggConnector.create" ) def test_update_metadata_db(self, *mocks): context = mock.Mock() event = { "path": "/api/v1/model_updates/1/", "httpMethod": "GET", "detail": ["update_metadata_db"], "headers": { "Content-Type": "application/json", "host": "localhost", }, } actual_response = service_initialization.handler(event, context) expected_response = { "statusCode": 200, "headers": { "Content-Type": "application/json", }, "body": '{"data": "database updated successfully"}', } self.assertDictEqual(expected_response, actual_response)
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/DjangoQ_Task.json
[ { "model": "django_q.task", "pk": "00e1e856f432482a8ec88766615c5764", "fields": { "name": "hotel-one-oregon-autumn", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-11-03T15:47:25.437Z", "stopped": "2022-11-03T15:47:25.555Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "0246b30654ac4cc9b3eaa66835554dba", "fields": { "name": "washington-louisiana-nebraska-nebraska", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAoWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "2", "started": "2023-01-16T21:37:02.390Z", "stopped": "2023-01-16T21:37:02.399Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "03b637f07453428c82838f30e4f4c84c", "fields": { "name": "king-utah-sad-mountain", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-12-13T23:32:25.130Z", "stopped": "2022-12-13T23:32:25.285Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "0524ce5f18684e3c809bce35490b21ca", "fields": { "name": "pizza-alanine-timing-oven", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-12-11T23:34:25.975Z", "stopped": "2022-12-11T23:34:26.130Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "06fe00da1cfe4983b140a9fd8aac19ed", "fields": { "name": "carpet-cola-orange-spring", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-11-29T16:31:15.312Z", "stopped": "2022-11-29T16:31:15.318Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "07d13f2f26af4abfbc8c96300418384b", "fields": { "name": "single-london-music-kansas", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2023-01-09T15:39:21.762Z", "stopped": "2023-01-09T15:39:21.769Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "08b7aa01d6754ad7afd5afe0f164e049", "fields": { "name": "berlin-emma-double-eighteen", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2023-01-23T15:10:08.631Z", "stopped": "2023-01-23T15:10:08.639Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "0b379ab5c37f4ef9b98ae950e617c39c", "fields": { "name": "beer-asparagus-mike-pennsylvania", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-12-17T16:52:24.624Z", "stopped": "2022-12-17T16:52:24.631Z", "success": true, "attempt_count": 1 } }, { "model": "django_q.task", "pk": "0b81094263fb44fc91f61aa7c1aa4ac3", "fields": { "name": "september-cardinal-ten-twelve", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "gAWVBQAAAAAAAABLAYWULg==", "kwargs": "gAV9lC4=", "result": null, "group": "1", "started": "2022-12-28T16:29:14.380Z", "stopped": "2022-12-28T16:29:14.387Z", "success": false, "attempt_count": 1 } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_FederatedModel.json
[ { "model": "fma_django.federatedmodel", "pk": 1, "fields": { "name": "test", "developer": 1, "current_artifact": null, "requirement": "require_x_updates", "requirement_args": [ 3 ], "aggregator": "avg_values_if_data", "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3} ], "items": false }, "scheduler": 1, "created_on": "2022-12-15T23:08:28.693Z", "last_modified": "2022-12-18T23:08:28.693Z", "clients": [ "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "ab359e5d-6991-4088-8815-a85d3e413c02", "cbb6025f-c15c-4e90-b3fb-85626f7a79f1" ] } }, { "model": "fma_django.federatedmodel", "pk": 2, "fields": { "name": "test-non-admin", "developer": 2, "current_artifact": null, "requirement": "all_clients", "requirement_args": null, "aggregator": "avg_values_if_data", "update_schema": null, "scheduler": 2, "created_on": "2022-12-24T23:08:28.693Z", "last_modified": "2022-12-28T23:08:28.693Z", "clients": [] } }, { "model": "fma_django.federatedmodel", "pk": 3, "fields": { "name": "test-no-aggregate", "developer": 2, "current_artifact": null, "requirement": "all_clients", "requirement_args": null, "aggregator": "avg_values_if_data", "update_schema": { "type": "array", "prefixItems": [ {"type": "array", "minItems": 3, "maxItems": 3}, {"type": "array", "minItems": 3, "maxItems": 3} ], "items": false }, "scheduler": 3, "created_on": "2022-12-18T23:08:28.693Z", "last_modified": "2022-12-19T23:08:28.693Z", "clients": [ "cbb6025f-c15c-4e90-b3fb-85626f7a79f1" ] } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_User.json
[ { "model": "auth.user", "pk": 1, "fields": { "password": "this_is_a_fake_password", "last_login": "2023-01-21T00:37:10.275Z", "is_superuser": true, "username": "admin", "first_name": "", "last_name": "", "email": "", "is_staff": true, "is_active": true, "date_joined": "2023-01-09T19:00:10.922Z", "groups": [], "user_permissions": [] } }, { "model": "auth.user", "pk": 2, "fields": { "password": "this_is_another_fake_password", "last_login": null, "is_superuser": false, "username": "non_admin", "first_name": "", "last_name": "", "email": "", "is_staff": false, "is_active": true, "date_joined": "2022-12-26T03:14:46Z", "groups": [], "user_permissions": [] } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_ModelArtifact.json
[ { "model": "fma_django.modelartifact", "pk": 3, "fields": { "values": "fake/path/model_artifact/1", "federated_model": 1, "version": "1.0.0", "created_on": "2022-12-12T23:55:34.066Z" } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_ModelUpdate.json
[ { "model": "fma_django.modelupdate", "pk": 1, "fields": { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "federated_model": 1, "data": "fake/path/model_updates/1", "status": 2, "created_on": "2022-12-15T23:08:28.720Z" } }, { "model": "fma_django.modelupdate", "pk": 2, "fields": { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "federated_model": 1, "data": "fake/path/model_updates/2", "status": 2, "created_on": "2023-01-10T23:10:33.720Z" } }, { "model": "fma_django.modelupdate", "pk": 3, "fields": { "client": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "federated_model": 1, "data": "fake/path/model_updates/3", "status": 2, "created_on": "2023-01-16T23:17:35.480Z" } }, { "model": "fma_django.modelupdate", "pk": 4, "fields": { "client": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "federated_model": 1, "data": "fake/path/model_updates/4", "status": 3, "created_on": "2022-02-17T17:58:13.819Z" } }, { "model": "fma_django.modelupdate", "pk": 5, "fields": { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "federated_model": 2, "data": "fake/path/model_updates/5", "status": 0, "created_on": "2022-02-17T17:58:44.441Z" } }, { "model": "fma_django.modelupdate", "pk": 6, "fields": { "client": "ab359e5d-6991-4088-8815-a85d3e413c02", "federated_model": 2, "data": "fake/path/model_updates/6", "status": 0, "created_on": "2022-02-28T00:36:54.803Z" } }, { "model": "fma_django.modelupdate", "pk": 7, "fields": { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "federated_model": 3, "data": "fake/path/model_updates/7", "status": 0, "created_on": "2022-12-26T01:12:55.467Z" } }, { "model": "fma_django.modelupdate", "pk": 8, "fields": { "client": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "federated_model": 3, "data": "fake/path/model_updates/8", "status": 0, "created_on": "2022-12-08T13:22:24.557Z" } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_client.json
[ { "model": "fma_django.client", "pk": "531580e6-ce6c-4f01-a5aa-9ed7af5ee768", "fields": {} }, { "model": "fma_django.client", "pk": "ab359e5d-6991-4088-8815-a85d3e413c02", "fields": {} }, { "model": "fma_django.client", "pk": "cbb6025f-c15c-4e90-b3fb-85626f7a79f1", "fields": {} } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/DjangoQ_Schedule.json
[ { "model": "django_q.schedule", "pk": 1, "fields": { "name": "1 - test - Scheduled Aggregator", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "(1,)", "kwargs": "{}", "schedule_type": "I", "minutes": 1, "repeats": -792, "next_run": "2023-01-22T02:53:45Z", "cron": null, "task": "1da0e26c81b74b62a24d297483623668", "cluster": null } }, { "model": "django_q.schedule", "pk": 2, "fields": { "name": "2 - test-non-admin - Scheduled Aggregator", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "(1,)", "kwargs": "{}", "schedule_type": "I", "minutes": 1, "repeats": 0, "next_run": "2022-12-10T05:15:00Z", "cron": null, "task": "1da0e26c81b74b62a24d297483623668", "cluster": null } }, { "model": "django_q.schedule", "pk": 3, "fields": { "name": "3 - test-non-aggregate - Scheduled Aggregator", "func": "fma_django_api.v1.aggregator_components.tasks.agg_service", "hook": "fma_django_api.v1.aggregator_components.tasks.post_agg_service_hook", "args": "(1,)", "kwargs": "{}", "schedule_type": "I", "minutes": 1, "repeats": -792, "next_run": "2022-01-09T07:18:23Z", "cron": null, "task": "1da0e26c81b74b62a24d297483623668", "cluster": null } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/TaskQueue_ModelAggregate.json
[ { "model": "fma_django.modelaggregate", "pk": 1, "fields": { "federated_model": 1, "result": "fake/path/model_aggregate/1", "validation_score": 1.0, "created_on": "2023-01-13T23:08:28.712Z", "parent": 2, "level": 0, "lft": 0, "rght": 0, "tree_id": 0 } }, { "model": "fma_django.modelaggregate", "pk": 2, "fields": { "federated_model": 2, "result": "fake/path/model_aggregate/2", "validation_score": null, "created_on": "2023-01-20T23:08:28.712Z", "parent": 1, "level": 0, "lft": 0, "rght": 0, "tree_id": 0 } } ]
0
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/mediafiles/fake/path
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/mediafiles/fake/path/model_updates/7
[2.0, 2.0, 2.0]
0
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/mediafiles/fake/path
capitalone_repos/federated-model-aggregation/api_service/tests/fixtures/mediafiles/fake/path/model_updates/8
[1.0, 1.0, 1.0]
0
capitalone_repos/federated-model-aggregation
capitalone_repos/federated-model-aggregation/clients/README.md
# Clients ## Description This directory is reserved for webclients that are ready-made to connect to the FMA service with little to no modification
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/.eslintignore
node_modules dist coverage
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/jest.config.js
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ module.exports = { preset: 'ts-jest', testEnvironment: 'node', };
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/package.json
{ "name": "fma-connect-javascript", "version": "0.0.1", "repository": "https://github.com/capitalone/federated-model-aggregation/tree/main/clients/javascript_client", "devDependencies": { "@types/jest": "^27.5.1", "@types/node": "^17.0.33", "@typescript-eslint/eslint-plugin": "^5.62.0", "@typescript-eslint/parser": "^5.62.0", "eslint": "^8.46.0", "eslint-config-prettier": "^8.9.0", "eslint-config-standard-with-typescript": "^37.0.0", "eslint-formatter-table": "^7.32.1", "eslint-plugin-import": "^2.28.0", "eslint-plugin-n": "^16.0.1", "eslint-plugin-prettier": "^5.0.0", "eslint-plugin-promise": "^6.1.1", "husky": "^8.0.3", "jest": "^28.1.3", "lint-staged": "^13.2.3", "prettier": "^3.0.0", "ts-jest": "^28.0.3", "typescript": "^5.1.6" }, "dependencies": { "@tensorflow/tfjs": "^4.10.0", "@tensorflow/tfjs-core": "^4.10.0", "argparse": "^2.0.1", "fetch-mock": "^9.11.0", "jest-fetch-mock": "^3.0.3", "node-fetch": "^2.6.1", "ts-node": "^10.8.1" }, "scripts": { "compile": "rm -rfv dist/lib && tsc && tsc --build tsconfig.es5.json", "dev": "tsc --watch", "fix": "prettier --ignore-path .gitignore --write \"**/*.+(js|ts|json)\"", "format": "prettier --ignore-path .gitignore --check .", "lint": "eslint fma_connect --ignore-path .eslintignore --ext .ts --format table", "prepare": "cd ../../ && husky install clients/javascript_client/.husky", "test": "jest --coverage --passWithNoTests" } }
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/.prettierignore
node_modules dist coverage # Ignore all JS files, this is only for TS **/*.js
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/README.md
# Javascript Client for FMA service An api client wrapper for connecting to the federated-learning-service. ## Setup Run `npm setup` in `clients/javascript_client` directory ## Testing To run the tests of API interface functions run `npm test` in `clients/javascript_client` directory
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/tsconfig.json
{ "compilerOptions": { "outDir": "./dist/lib/es6", "target": "ES2020", "module": "CommonJS", // Recommended: Compiler complains about expressions implicitly typed as 'any' "noImplicitAny": true }, "include": ["fma_connect/**/*"], "exclude": ["node_modules", "dist", "coverage"] }
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/.prettierrc
{ "semi": true, "trailingComma": "all", "printWidth": 120, "singleQuote": true, "arrowParens": "always", "proseWrap": "preserve", "quoteProps": "consistent" }
0
capitalone_repos/federated-model-aggregation/clients
capitalone_repos/federated-model-aggregation/clients/javascript_client/.eslintrc.json
{ "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 12, "sourceType": "module" }, "plugins": ["@typescript-eslint"], "extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"], "rules": { // values can be off, warn, error "@typescript-eslint/no-unused-vars": "error", "@typescript-eslint/consistent-type-definitions": ["error", "type"] }, "env": { "browser": true, "es2021": true } }