ingen-lib 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. ingen/__init__.py +11 -0
  2. ingen/__main__.py +103 -0
  3. ingen/data_source/__init__.py +3 -0
  4. ingen/data_source/api_source.py +98 -0
  5. ingen/data_source/data_source_type.py +18 -0
  6. ingen/data_source/dataframe_store.py +8 -0
  7. ingen/data_source/file_source.py +67 -0
  8. ingen/data_source/json_source.py +34 -0
  9. ingen/data_source/mysql_source.py +64 -0
  10. ingen/data_source/rawdata_source.py +43 -0
  11. ingen/data_source/source.py +30 -0
  12. ingen/data_source/source_factory.py +27 -0
  13. ingen/formatters/__init__.py +4 -0
  14. ingen/formatters/common_formatters.py +642 -0
  15. ingen/formatters/formatter.py +41 -0
  16. ingen/formatters/utils.py +33 -0
  17. ingen/generators/__init__.py +4 -0
  18. ingen/generators/base_interface_generator.py +118 -0
  19. ingen/generators/interface_generator.py +78 -0
  20. ingen/lib/__init__.py +3 -0
  21. ingen/lib/cryptor.py +110 -0
  22. ingen/logger.py +18 -0
  23. ingen/metadata/__init__.py +3 -0
  24. ingen/metadata/metadata.py +103 -0
  25. ingen/metadata/metadata_parser.py +86 -0
  26. ingen/pre_processor/__init__.py +3 -0
  27. ingen/pre_processor/aggregator.py +22 -0
  28. ingen/pre_processor/aggregators.py +54 -0
  29. ingen/pre_processor/drop_duplicates.py +14 -0
  30. ingen/pre_processor/filter.py +46 -0
  31. ingen/pre_processor/mask.py +18 -0
  32. ingen/pre_processor/melt.py +28 -0
  33. ingen/pre_processor/merger.py +44 -0
  34. ingen/pre_processor/pre_processor.py +53 -0
  35. ingen/pre_processor/process.py +18 -0
  36. ingen/pre_processor/union.py +19 -0
  37. ingen/reader/__init__.py +3 -0
  38. ingen/reader/api_reader.py +32 -0
  39. ingen/reader/data_source.py +26 -0
  40. ingen/reader/file_reader.py +127 -0
  41. ingen/reader/json_reader.py +18 -0
  42. ingen/reader/mysql_reader.py +22 -0
  43. ingen/reader/rawdata_reader.py +9 -0
  44. ingen/reader/xml_file_reader.py +98 -0
  45. ingen/utils/__init__.py +3 -0
  46. ingen/utils/app_http/__init__.py +3 -0
  47. ingen/utils/app_http/aiohttp_retry.py +83 -0
  48. ingen/utils/app_http/http_request.py +15 -0
  49. ingen/utils/app_http/http_util.py +126 -0
  50. ingen/utils/app_http/success_criterias.py +73 -0
  51. ingen/utils/app_secrets.py +36 -0
  52. ingen/utils/interpolators/Interpolator.py +49 -0
  53. ingen/utils/interpolators/__init__.py +3 -0
  54. ingen/utils/interpolators/common_interpolators.py +60 -0
  55. ingen/utils/json_df_convertors.py +65 -0
  56. ingen/utils/path_parser.py +46 -0
  57. ingen/utils/properties.py +53 -0
  58. ingen/utils/run_configuration.py +30 -0
  59. ingen/utils/sql_query_parser.py +129 -0
  60. ingen/utils/timer.py +20 -0
  61. ingen/utils/url_constructor.py +160 -0
  62. ingen/utils/utils.py +71 -0
  63. ingen/validation/__init__.py +3 -0
  64. ingen/validation/common_validations.py +222 -0
  65. ingen/validation/notification.py +60 -0
  66. ingen/validation/send_email.py +35 -0
  67. ingen/validation/validations.py +70 -0
  68. ingen/writer/__init__.py +7 -0
  69. ingen/writer/dataframe_writer.py +19 -0
  70. ingen/writer/json_util.py +65 -0
  71. ingen/writer/json_writer/__init__.py +3 -0
  72. ingen/writer/json_writer/convertors/__init__.py +3 -0
  73. ingen/writer/json_writer/convertors/convertor_factory.py +18 -0
  74. ingen/writer/json_writer/convertors/df_to_multiple_json_convertor.py +13 -0
  75. ingen/writer/json_writer/convertors/df_to_single_json_convertor.py +13 -0
  76. ingen/writer/json_writer/destinations/__init__.py +3 -0
  77. ingen/writer/json_writer/destinations/api_destination.py +73 -0
  78. ingen/writer/json_writer/destinations/destination_factory.py +18 -0
  79. ingen/writer/json_writer/destinations/file_destination.py +8 -0
  80. ingen/writer/json_writer/json_writer.py +49 -0
  81. ingen/writer/old_json_writer.py +34 -0
  82. ingen/writer/split_file_writer.py +27 -0
  83. ingen/writer/util.py +190 -0
  84. ingen/writer/writer.py +109 -0
  85. ingen_lib-1.0.0.dist-info/LICENSE +201 -0
  86. ingen_lib-1.0.0.dist-info/METADATA +25 -0
  87. ingen_lib-1.0.0.dist-info/RECORD +89 -0
  88. ingen_lib-1.0.0.dist-info/WHEEL +5 -0
  89. ingen_lib-1.0.0.dist-info/top_level.txt +1 -0
ingen/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ # Import these attributes into other files as needed to
5
+ # identify the project version at runtime.
6
+ try:
7
+ from .version import git_revision as __git_revision__
8
+ from .version import version as __version__
9
+ except ImportError:
10
+ __git_revision__ = 'Unknown'
11
+ __version__ = 'Unknown'
ingen/__main__.py ADDED
@@ -0,0 +1,103 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import argparse
5
+ import logging
6
+ import time
7
+ from datetime import date
8
+
9
+ from ingen.metadata.metadata_parser import MetaDataParser
10
+ from ingen.utils.utils import KeyValue
11
+ from ingen.logger import init_logging
12
+
13
+ logger = logging.getLogger()
14
+
15
+
16
+ def main(
17
+ config_path, query_params, run_date, interfaces, infile=None, dynamic_data=None
18
+ ):
19
+ parser = MetaDataParser(
20
+ config_path, query_params, run_date, interfaces, infile, dynamic_data
21
+ )
22
+ metadata_list = parser.parse_metadata()
23
+ run_config = parser.run_config
24
+ logger.info("Metadata parsing complete. Starting interface generation")
25
+ main_start = time.time()
26
+ for metadata in metadata_list:
27
+ try:
28
+ generator = run_config.generator(run_config.writer, run_config.formatter)
29
+ logger.info(f"Generating interface '{metadata.name}'")
30
+ start = time.time()
31
+ interface = generator.generate(
32
+ metadata.name,
33
+ metadata.sources,
34
+ metadata.pre_processes,
35
+ metadata.columns,
36
+ metadata.output,
37
+ metadata.params,
38
+ metadata.validation_action,
39
+ )
40
+ end = time.time()
41
+ logger.info(
42
+ f"Successfully generated interface '{metadata.name}' in {end - start:.2f} seconds."
43
+ )
44
+ except Exception as e:
45
+ logger.error(
46
+ f"Failed to generate interface file for {metadata.name} \n {e}"
47
+ )
48
+ main_end = time.time()
49
+ logger.info(
50
+ f"Interface Generation finished. Time taken: {main_end - main_start:.2f} seconds"
51
+ )
52
+
53
+ # dynamic_data: a JSON string input that was provided alongside a config file
54
+ if dynamic_data:
55
+ return interface
56
+
57
+
58
+ def create_arg_parser():
59
+ parser = argparse.ArgumentParser()
60
+ parser.add_argument("config_path", help="Path to config file")
61
+ parser.add_argument(
62
+ "run_date",
63
+ nargs="?",
64
+ default=date.today(),
65
+ help="Run date in YYYY-MM-DD format, if provided "
66
+ "this will override today's date in "
67
+ "formatters",
68
+ )
69
+ parser.add_argument(
70
+ "--query_params",
71
+ nargs="*",
72
+ action=KeyValue,
73
+ help="Query parameters in key value pairs to be " "used in the SQL query",
74
+ )
75
+ parser.add_argument(
76
+ "--interfaces",
77
+ help="Comma separated list of interface names to generate, if not provided "
78
+ "all interfaces listed in the config file will be generated",
79
+ )
80
+ parser.add_argument(
81
+ "--infile", help="filepath to the JSON file to be used in JSON source"
82
+ )
83
+ return parser
84
+
85
+
86
+ def process_json(config_path, dynamic_data):
87
+ return main(config_path, None, None, None, dynamic_data=dynamic_data)
88
+
89
+
90
+ if __name__ == "__main__":
91
+ """Initializes logger and command line arguments"""
92
+ init_logging()
93
+ arg_parser = create_arg_parser()
94
+ args = arg_parser.parse_args()
95
+ if args.interfaces is not None:
96
+ args.interfaces = args.interfaces.split(",")
97
+ if args.infile:
98
+ logger.info(
99
+ f"Use poller $infile when source use_infile is turned on, overwrite source file_path: {args.infile}"
100
+ )
101
+ main(
102
+ args.config_path, args.query_params, args.run_date, args.interfaces, args.infile
103
+ )
@@ -0,0 +1,3 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
@@ -0,0 +1,98 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import logging
5
+ from datetime import date
6
+
7
+ from ingen.data_source.source import DataSource
8
+ from ingen.reader.api_reader import APIReader
9
+ from ingen.utils.app_http.http_request import HTTPRequest
10
+ from ingen.utils.app_http.success_criterias import DEFAULT_STATUS_CRITERIA_OPTIONS, get_criteria_by_name
11
+ from ingen.utils.interpolators.Interpolator import Interpolator
12
+ from ingen.utils.timer import log_time
13
+ from ingen.utils.url_constructor import UrlConstructor
14
+
15
+ log = logging.getLogger()
16
+
17
+
18
+ class APISource(DataSource):
19
+ """
20
+ This class represents a API source
21
+ """
22
+
23
+ def __init__(self, source, params_map=None, interpolator=Interpolator()):
24
+ """
25
+ Loads a API source
26
+
27
+ :param source : An interface source contains all the attributes i.e. api_id, url, data_col , data_key and more
28
+ :param params_map : command line parameters
29
+ """
30
+ super().__init__(source.get('id'))
31
+ if params_map is None:
32
+ params_map = {}
33
+ self._interpolator = interpolator
34
+ self._url = source.get('url')
35
+ self._url_params = source.get('url_params')
36
+ self._batch = source.get('batch')
37
+ self._data_node = source.get('data_node')
38
+ self._data_key = source.get('data_key')
39
+ self._meta = source.get('meta')
40
+ self._auth = source.get('auth')
41
+ self._response_to_list = source.get('response_to_list')
42
+ self._run_date = params_map.get('run_date', date.today())
43
+ # GET is set as default HTTP method for backward compatibility of config files
44
+ self._method = source.get('method', 'GET')
45
+ self._req_data = source.get('request_body')
46
+ self._headers = self.parse_headers(source.get('headers'))
47
+ self.reader_params = {
48
+ 'response_to_list': self._response_to_list,
49
+ 'retries': source.get('retries', 2),
50
+ 'interval': source.get('interval', 1),
51
+ 'interval_increment': source.get('interval_increment', 2),
52
+ 'success_criteria': get_criteria_by_name(source.get('success_criteria', 'status_criteria')),
53
+ 'criteria_options': source.get('criteria_options', DEFAULT_STATUS_CRITERIA_OPTIONS),
54
+ 'convertor_method': source.get('convertor_method'),
55
+ 'tasks_len': source.get('tasks_len', 1),
56
+ 'queue_size': source.get('queue_size', 1),
57
+ 'ssl': source.get('ssl', True),
58
+ 'ignore_failure': source.get('ignore_failure', True)
59
+ }
60
+ self._src_data_checks = source.get('src_data_checks', [])
61
+
62
+ def fetch(self):
63
+ """
64
+ Calls the API from the url .
65
+
66
+ :return: A DataFrame created using the result of the request made to the API
67
+ """
68
+ url_constructor = UrlConstructor(self._url, self._url_params, self._batch, self._run_date)
69
+ urls = url_constructor.get_urls()
70
+ requests = [HTTPRequest(url=url,
71
+ method=self._method,
72
+ headers=self._headers,
73
+ auth=self._auth,
74
+ data=self._req_data) for url in urls]
75
+ url_reader = APIReader(requests, self.reader_params)
76
+ return self.fetch_data(url_reader)
77
+
78
+ @log_time
79
+ def fetch_data(self, url_reader):
80
+ """
81
+ returns a DataFrame of data fetched from APISource.
82
+ """
83
+ return url_reader.execute(self._data_node, self._data_key, self._meta)
84
+
85
+ def fetch_validations(self):
86
+ """
87
+ Method to fetch validations from the source
88
+ :return: list of dictionaries containing mentioned validations on all columns
89
+ """
90
+ return self._src_data_checks
91
+
92
+ def parse_headers(self, headers):
93
+ """
94
+ Interpolate header values
95
+ :param headers: dict-like HTTP headers
96
+ :return: dict of HTTP headers with interpolated values
97
+ """
98
+ return {key: self._interpolator.interpolate(value) for key, value in headers.items()} if headers else None
@@ -0,0 +1,18 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ from enum import Enum
5
+
6
+
7
+ class DataSourceType(Enum):
8
+ """
9
+ Enumeration of DataSource types
10
+
11
+ """
12
+
13
+ DB = "db"
14
+ File = "file"
15
+ Api = "api"
16
+ MYSQL = "mysql"
17
+ RawDataStore = "rawdatastore"
18
+ JSON = "json"
@@ -0,0 +1,8 @@
1
+ """A dictionary that stores ids and dataframes as key value pairs"""
2
+
3
+ # Copyright (c) 2023 BlackRock, Inc.
4
+ # All Rights Reserved.
5
+
6
+ store = {
7
+
8
+ }
@@ -0,0 +1,67 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import logging
5
+ from datetime import date
6
+
7
+ from ingen.data_source.source import DataSource
8
+ from ingen.reader.file_reader import ReaderFactory
9
+ from ingen.utils.path_parser import PathParser
10
+ from ingen.utils.timer import log_time
11
+
12
+ log = logging.getLogger()
13
+
14
+
15
+ class FileSource(DataSource):
16
+ """
17
+ This class represents a File source
18
+ """
19
+
20
+ def __init__(self, source, params_map):
21
+ """
22
+ Loads a file
23
+
24
+ :param source : An interface source contains all the attributes i.e. file_id, file_path, file_type, input_columns and others
25
+ :param params_map : command line parameters, query_params + run_date
26
+
27
+ """
28
+ super().__init__(source.get('id'))
29
+ if params_map.get('infile') and source['use_infile']:
30
+ source['file_path'] = params_map['infile']
31
+ self._src = source
32
+ else:
33
+ self._src = self.format_file_path(source, params_map)
34
+
35
+ def fetch(self):
36
+ """
37
+ reads the input file
38
+
39
+ :return: A DataFrame created using the result of the reading the file
40
+ """
41
+ reader = ReaderFactory.get_reader(self._src)
42
+ return self.fetch_data(reader)
43
+
44
+ @log_time
45
+ def fetch_data(self, reader):
46
+ """
47
+ returns a DataFrame of data fetched from input FileSource.
48
+ """
49
+ return reader.read(self._src)
50
+
51
+ def fetch_validations(self):
52
+ """
53
+ Method to fetch validations from the source
54
+ :return: list of dictionaries containing mentioned validations on all columns
55
+ """
56
+ return self._src.get('src_data_checks', [])
57
+
58
+ def format_file_path(self, source, params_map):
59
+ if params_map is None:
60
+ run_date = date.today()
61
+ else:
62
+ run_date = params_map.get('run_date', date.today())
63
+
64
+ path_parser = PathParser(run_date)
65
+ if 'file_path' in source:
66
+ source['file_path'] = path_parser.parse(source['file_path'])
67
+ return source
@@ -0,0 +1,34 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import json
5
+
6
+ import pandas as pd
7
+
8
+ from ingen.data_source.source import DataSource
9
+
10
+
11
+ class JsonSource(DataSource):
12
+
13
+ def __init__(self, source, data):
14
+ """
15
+ Loads a JsonSource
16
+ :param source: Map which contains source data such as id and data
17
+ """
18
+
19
+ super().__init__(source.get('id'))
20
+ self._src = source
21
+ self._data = data
22
+
23
+ def fetch(self):
24
+ if not self._data:
25
+ raise ValueError("JSON string is not provided")
26
+
27
+ json_dict = json.loads(self._data)
28
+ if not json_dict[self.id]:
29
+ raise ValueError("JSON source with ID {} does not exist".format(self.id))
30
+ self._data = pd.json_normalize(json_dict[self.id])
31
+ return self._data
32
+
33
+ def fetch_validations(self):
34
+ return self._src.get('src_data_checks', [])
@@ -0,0 +1,64 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import logging
5
+
6
+ import pymysql
7
+ from ingen.data_source.source import DataSource
8
+ from ingen.reader.mysql_reader import MYSQLReader
9
+ from ingen.utils.properties import properties
10
+ from ingen.utils.sql_query_parser import SqlQueryParser
11
+ from ingen.utils.timer import log_time
12
+
13
+ log = logging.getLogger()
14
+
15
+
16
+ class MYSQLSource(DataSource):
17
+ """
18
+ This class represents mysql database source
19
+ """
20
+
21
+ _connection = None
22
+
23
+ def __init__(self, source, params_map=None):
24
+ """
25
+ Loads a MYSQLSource
26
+ :param source: Map which contains source data such as id, query, etc.
27
+ :param params_map: Map which contains runtime parameters such as query_params, run_date
28
+ """
29
+ super().__init__(source['id'])
30
+ self._src_data_checks = source.get('src_data_checks', [])
31
+ self._host = properties.get_property('datasource.mysql.host')
32
+ self._user = properties.get_property('datasource.mysql.user')
33
+ self._password = properties.get_property('datasource.mysql.password')
34
+ self._database = source.get('database')
35
+ self._query = SqlQueryParser().parse_query(source['query'], params_map, source.get('temp_table_params'))
36
+ if self._connection is None:
37
+ self._connection = pymysql.connect(host=self._host,
38
+ user=self._user,
39
+ password=self._password,
40
+ database=self._database)
41
+ else:
42
+ raise Exception('You cannot create another MySQL connection')
43
+
44
+ def fetch(self):
45
+ """
46
+ Executes the SQL query
47
+ :return: A DataFrame created using the result of the query
48
+ """
49
+ reader = MYSQLReader(self._connection)
50
+ return self.fetch_data(reader)
51
+
52
+ @log_time
53
+ def fetch_data(self, reader):
54
+ """
55
+ returns a DataFrame of data fetched from MySQLSource.
56
+ """
57
+ return reader.execute(self._query)
58
+
59
+ def fetch_validations(self):
60
+ """
61
+ Method to fetch validations from the source
62
+ :return: list of dictionaries containing mentioned validations on all columns
63
+ """
64
+ return self._src_data_checks
@@ -0,0 +1,43 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ import logging
5
+
6
+ from ingen.data_source.dataframe_store import store
7
+ from ingen.data_source.source import DataSource
8
+ from ingen.reader.rawdata_reader import RawDataReader
9
+ from ingen.utils.timer import log_time
10
+
11
+ log = logging.getLogger()
12
+
13
+
14
+ class RawDataSource(DataSource):
15
+ """
16
+ This class represents a raw data source, from where we can have dataframes given an id
17
+ """
18
+
19
+ def __init__(self, source):
20
+ super().__init__(source.get('id'))
21
+ self._src_data_checks = source.get('src_data_checks', [])
22
+
23
+ def fetch(self):
24
+ """
25
+ reads the input id
26
+ :return: A DataFrame fetched from the dataframe store corresponding to the id given by the user
27
+ """
28
+ reader = RawDataReader()
29
+ return self.fetch_data(reader)
30
+
31
+ @log_time
32
+ def fetch_data(self, reader):
33
+ """
34
+ returns a DataFrame of data fetched from RawDataSource.
35
+ """
36
+ return reader.read(self._id, store)
37
+
38
+ def fetch_validations(self):
39
+ """
40
+ Method to fetch validations from the source
41
+ :return: list of dictionaries containing mentioned validations on all columns
42
+ """
43
+ return self._src_data_checks
@@ -0,0 +1,30 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ class DataSource:
5
+ """
6
+ A DataSource represents the properties of a source of the interface data. All data source must implement
7
+ a method called fetch, which is responsible for fetching data and returning it in a pandas DataFrame fromat
8
+ """
9
+
10
+ def __init__(self, _id):
11
+ self._id = _id
12
+
13
+ @property
14
+ def id(self):
15
+ return self._id
16
+
17
+ def fetch(self):
18
+ """
19
+ Method responsible for fetching data from source
20
+
21
+ :return: A Pandas DataFrame
22
+ """
23
+ pass
24
+
25
+ def fetch_validations(self):
26
+ """
27
+ Method to fetch validations from the source
28
+ :return: list of dictionaries containing mentioned validations on all columns
29
+ """
30
+ pass
@@ -0,0 +1,27 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ from ingen.data_source.data_source_type import DataSourceType
5
+ from ingen.data_source.file_source import FileSource
6
+ from ingen.data_source.json_source import JsonSource
7
+ from ingen.data_source.mysql_source import MYSQLSource
8
+ from ingen.data_source.rawdata_source import RawDataSource
9
+
10
+
11
+ class SourceFactory:
12
+ def parse_source(self, source, params_map, dynamic_data=None):
13
+ if source['type'] == DataSourceType.File.value:
14
+ return FileSource(source, params_map)
15
+ elif source['type'] == DataSourceType.MYSQL.value:
16
+ return MYSQLSource(source)
17
+ elif source['type'] == DataSourceType.Api.value:
18
+ # Conditional import added here to avoid circular dependency
19
+ # API Source -> URL Constructor -> Source Factory -> API Source
20
+ from ingen.data_source.api_source import APISource
21
+ return APISource(source, params_map)
22
+ elif source['type'] == DataSourceType.RawDataStore.value:
23
+ return RawDataSource(source)
24
+ elif source['type'] == DataSourceType.JSON.value:
25
+ return JsonSource(source, dynamic_data)
26
+ else:
27
+ raise ValueError(f"Unknown source type {source.get('type')}.")
@@ -0,0 +1,4 @@
1
+ # Copyright (c) 2023 BlackRock, Inc.
2
+ # All Rights Reserved.
3
+
4
+ from ingen.formatters.formatter import Formatter