ods-tools 3.2.3__tar.gz → 3.2.5__tar.gz

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 (54) hide show
  1. {ods_tools-3.2.3 → ods_tools-3.2.5}/PKG-INFO +2 -1
  2. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/__init__.py +1 -1
  3. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/main.py +23 -6
  4. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/connector/csv.py +11 -3
  5. ods_tools-3.2.5/ods_tools/odtf/connector/db/__init__.py +10 -0
  6. ods_tools-3.2.5/ods_tools/odtf/connector/db/base.py +169 -0
  7. ods_tools-3.2.5/ods_tools/odtf/connector/db/errors.py +18 -0
  8. ods_tools-3.2.5/ods_tools/odtf/connector/db/mssql.py +56 -0
  9. ods_tools-3.2.5/ods_tools/odtf/connector/db/postgres.py +47 -0
  10. ods_tools-3.2.5/ods_tools/odtf/connector/db/sqlite.py +73 -0
  11. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/controller.py +107 -7
  12. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/runner/pandas.py +23 -22
  13. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/__init__.py +2 -2
  14. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/common.py +14 -1
  15. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/exposure.py +2 -1
  16. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/oed_schema.py +20 -1
  17. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/source.py +4 -9
  18. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/validator.py +15 -10
  19. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/PKG-INFO +2 -1
  20. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/SOURCES.txt +6 -0
  21. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/requires.txt +6 -0
  22. {ods_tools-3.2.3 → ods_tools-3.2.5}/setup.py +10 -1
  23. {ods_tools-3.2.3 → ods_tools-3.2.5}/README.md +0 -0
  24. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/data/__init__.py +0 -0
  25. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/__init__.py +0 -0
  26. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/config.py +0 -0
  27. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/connector/__init__.py +0 -0
  28. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/connector/base.py +0 -0
  29. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/data/__init__.py +0 -0
  30. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/errors.py +0 -0
  31. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/files/__init__.py +0 -0
  32. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/files/csv.py +0 -0
  33. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/files/yaml.py +0 -0
  34. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/log.py +0 -0
  35. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/mapping/__init__.py +0 -0
  36. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/mapping/base.py +0 -0
  37. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/mapping/errors.py +0 -0
  38. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/mapping/file.py +0 -0
  39. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/notset.py +0 -0
  40. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/runner/__init__.py +0 -0
  41. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/runner/base.py +0 -0
  42. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/transformers/__init__.py +0 -0
  43. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/transformers/errors.py +0 -0
  44. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/transformers/grammar.py +0 -0
  45. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/transformers/transform.py +0 -0
  46. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/transformers/transform_utils.py +0 -0
  47. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/validator_base.py +0 -0
  48. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/odtf/validator_pandas.py +0 -0
  49. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/forex.py +0 -0
  50. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools/oed/setting_schema.py +0 -0
  51. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/dependency_links.txt +0 -0
  52. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/entry_points.txt +0 -0
  53. {ods_tools-3.2.3 → ods_tools-3.2.5}/ods_tools.egg-info/top_level.txt +0 -0
  54. {ods_tools-3.2.3 → ods_tools-3.2.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods_tools
3
- Version: 3.2.3
3
+ Version: 3.2.5
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -9,6 +9,7 @@ License: UNKNOWN
9
9
  Platform: UNKNOWN
10
10
  Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
+ Provides-Extra: extra
12
13
 
13
14
  # ODS Tools
14
15
 
@@ -1,4 +1,4 @@
1
- __version__ = '3.2.3'
1
+ __version__ = '3.2.5'
2
2
 
3
3
  import logging
4
4
 
@@ -18,7 +18,10 @@ from ods_tools.oed import (
18
18
  ModelSettingSchema,
19
19
  AnalysisSettingSchema,
20
20
  )
21
- from ods_tools.odtf.controller import transform_format
21
+ try:
22
+ from ods_tools.odtf.controller import transform_format
23
+ except ImportError:
24
+ logger.info("Data transformation package requirements not intalled.")
22
25
 
23
26
 
24
27
  def get_oed_exposure(config_json=None, oed_dir=None, **kwargs):
@@ -96,9 +99,13 @@ def convert(**kwargs):
96
99
  def transform(**kwargs):
97
100
  """Wrapper function for transform command.
98
101
  Transform location and account data to a new format (ex: AIR to OED)"""
99
- path_to_config_file = kwargs['config_file']
100
102
  try:
101
- transform_result = transform_format(path_to_config_file)
103
+ if kwargs.get('config_file') is None:
104
+ if kwargs.get('format') is None or kwargs.get('input_file') is None or kwargs.get('output_file') is None:
105
+ raise OdsException("When --config-file is not provided, --format, --input-file, and --output-file are required.")
106
+
107
+ transform_result = transform_format(path_to_config_file=kwargs.get('config_file'), input_file=kwargs.get('input_file'),
108
+ output_file=kwargs.get('output_file'), transformation=kwargs.get('format'))
102
109
  if not kwargs.get('nocheck'):
103
110
  for output_file in transform_result:
104
111
  if output_file[1] == 'location' and os.path.isfile(output_file[0]):
@@ -106,7 +113,9 @@ def transform(**kwargs):
106
113
  elif output_file[1] == 'account' and os.path.isfile(output_file[0]):
107
114
  check(account=output_file[0])
108
115
  except OdsException as e:
109
- logger.error("Transformation failed:")
116
+ logger.error(e)
117
+ except NameError as e:
118
+ logger.error("Data transformation package requirements not intalled.")
110
119
  logger.error(e)
111
120
 
112
121
 
@@ -171,13 +180,21 @@ check_command.add_argument('-v', '--logging-level', help='logging level (debug:1
171
180
 
172
181
  transform_description = """
173
182
  Transform data format to/from OED.
183
+ This transformation can be done either by providing a config file or directly by specifying the input and output files.
184
+ If input and output files are provided, either --oed-air or --air-oed must be specified to indicate the transformation direction.
185
+
186
+ If a config file is provided, the transformation will be done according to the config file.
187
+ Please note that the config file allows for more options (batch size, file format, database connection, etc.)
174
188
  """
175
189
  transform_command = command_parser.add_parser('transform', description=transform_description,
176
190
  formatter_class=argparse.RawTextHelpFormatter)
177
- transform_command.add_argument('--config-file', help='Path to the config file', required=True)
191
+ transform_command.add_argument('--config-file', help='Path to the config file')
192
+ transform_command.add_argument('-f', "--format", help='Specify which transformation to use (currently oed-air or air-oed)', default=None)
193
+ transform_command.add_argument('--input-file', help='Path to the input file', default=None)
194
+ transform_command.add_argument('--output-file', help='Path to the output file', default=None)
178
195
  transform_command.add_argument('-v', '--logging-level', help='logging level (debug:10, info:20, warning:30, error:40, critical:50)',
179
196
  default=30, type=int)
180
- transform_command.add_argument('--nocheck', help='if True, OED file will not be checked after transformation', default=False)
197
+ transform_command.add_argument('--nocheck', help='if True, OED file will not be checked after transformation', default=False, action='store_true')
181
198
 
182
199
 
183
200
  def main():
@@ -1,6 +1,8 @@
1
1
  import csv
2
2
  from typing import Any, Dict, Iterable
3
3
 
4
+ import pandas as pd
5
+
4
6
  from .base import BaseConnector
5
7
  from ..notset import NotSetType
6
8
 
@@ -95,6 +97,12 @@ class CsvConnector(BaseConnector):
95
97
  writer.writerow(self._data_serializer(first_row))
96
98
  writer.writerows(map(self._data_serializer, data))
97
99
 
98
- def extract(self) -> Iterable[Dict[str, Any]]:
99
- with open(self.file_path, "r") as f:
100
- yield from csv.DictReader(f, quoting=self.quoting)
100
+ def fetch_data(self, chunksize: int) -> Iterable[pd.DataFrame]:
101
+ """
102
+ Fetch data from the csv file in batches.
103
+
104
+ :param chunksize: Number of rows per batch
105
+ :return: Iterable of data batches as pandas DataFrames
106
+ """
107
+ for batch in pd.read_csv(self.file_path, chunksize=chunksize, low_memory=False):
108
+ yield batch
@@ -0,0 +1,10 @@
1
+ from .mssql import SQLServerConnector
2
+ from .postgres import PostgresConnector
3
+ from .sqlite import SQLiteConnector
4
+
5
+
6
+ __all__ = [
7
+ "SQLiteConnector",
8
+ "PostgresConnector",
9
+ "SQLServerConnector",
10
+ ]
@@ -0,0 +1,169 @@
1
+ from typing import Any, Dict, Iterable, List
2
+
3
+ import sqlparams
4
+ import sqlparse
5
+
6
+ from ods_tools.odtf.connector import BaseConnector
7
+
8
+ from .errors import DBQueryError
9
+
10
+
11
+ class BaseDBConnector(BaseConnector):
12
+ """
13
+ Connects to a database for reading and writing data.
14
+
15
+ **Options:**
16
+
17
+ * `host` - Which host to use when connecting to the database
18
+ * `port` - The port to use when connecting to the database
19
+ * `database` - The database name or relative path to the file for sqlite3
20
+ * `user` - The username to use when connecting to the database
21
+ * `password` - The password to use when connecting to the database
22
+ * `select_statement` - sql query to read the data from
23
+ * `insert_statement` - sql query to insert the data from
24
+ """
25
+
26
+ name = "BaseDB Connector"
27
+ options_schema = {
28
+ "type": "object",
29
+ "properties": {
30
+ "host": {
31
+ "type": "string",
32
+ "description": (
33
+ "Which host to use when connecting to the database. "
34
+ "Not used with SQLite."
35
+ ),
36
+ "default": "",
37
+ "title": "Host",
38
+ },
39
+ "port": {
40
+ "type": "string",
41
+ "description": (
42
+ "The port to use when connecting to the database. "
43
+ "Not used with SQLite."
44
+ ),
45
+ "default": "",
46
+ "title": "Port",
47
+ },
48
+ "database": {
49
+ "type": "string",
50
+ "description": (
51
+ "The database name or relative path to the file for "
52
+ "sqlite3"
53
+ ),
54
+ "title": "Database",
55
+ },
56
+ "user": {
57
+ "type": "string",
58
+ "description": (
59
+ "The username to use when connecting to the database. "
60
+ "Not used with SQLite."
61
+ ),
62
+ "default": "",
63
+ "title": "User",
64
+ },
65
+ "password": {
66
+ "type": "password",
67
+ "description": (
68
+ "The password to use when connecting to the database. "
69
+ "Not used with SQLite."
70
+ ),
71
+ "default": "",
72
+ "title": "Password",
73
+ },
74
+ "sql_statement": {
75
+ "type": "string",
76
+ "description": "The path to the file which contains the "
77
+ "sql statement to run",
78
+ "subtype": "path",
79
+ "title": "Select Statement File",
80
+ },
81
+ },
82
+ "required": ["database", "select_statement", "insert_statement"],
83
+ }
84
+ sql_params_output = "qmark"
85
+
86
+ def __init__(self, config, **options):
87
+ super().__init__(config, **options)
88
+
89
+ self.database = {
90
+ "host": options.get("host", ""),
91
+ "port": options.get("port", ""),
92
+ "database": options["database"],
93
+ "user": options.get("user", ""),
94
+ "password": options.get("password", ""),
95
+ }
96
+ self.sql_statement_path = config.absolute_path(
97
+ options["sql_statement"]
98
+ )
99
+
100
+ def _create_connection(self, database: Dict[str, str]):
101
+ raise NotImplementedError()
102
+
103
+ def _get_cursor(self, conn):
104
+ cur = conn.cursor()
105
+ return cur
106
+
107
+ def _get_select_statement(self) -> str:
108
+ """
109
+ SQL string to select the data from the DB
110
+
111
+ :return: string
112
+ """
113
+ with open(self.sql_statement_path) as f:
114
+ select_statement = f.read()
115
+
116
+ return select_statement
117
+
118
+ def _get_insert_statements(self) -> List[str]:
119
+ """
120
+ SQL string(s) to insert the data into the DB
121
+
122
+ :return: List of sql statements
123
+ """
124
+ with open(self.sql_statement_path) as f:
125
+ sql = f.read()
126
+
127
+ return sqlparse.split(sql)
128
+
129
+ def load(self, data: Iterable[Dict[str, Any]]):
130
+ insert_sql = self._get_insert_statements()
131
+ data = list(
132
+ data
133
+ ) # convert iterable to list as we reuse it based on number of queries
134
+ conn = self._create_connection(self.database)
135
+
136
+ with conn:
137
+ cur = self._get_cursor(conn)
138
+ query = sqlparams.SQLParams("named", self.sql_params_output)
139
+
140
+ # insert query can contain more than 1 statement
141
+ for line in insert_sql:
142
+ sql, params = query.formatmany(line, data)
143
+ try:
144
+ cur.executemany(sql, params)
145
+ except Exception as e:
146
+ raise DBQueryError(sql, e, data=data)
147
+
148
+ def row_to_dict(self, row):
149
+ """
150
+ Convert the row returned from the cursor into a dictionary
151
+
152
+ :return: Dict
153
+ """
154
+ return dict(row)
155
+
156
+ def extract(self) -> Iterable[Dict[str, Any]]:
157
+ select_sql = self._get_select_statement()
158
+ conn = self._create_connection(self.database)
159
+
160
+ with conn:
161
+ cur = self._get_cursor(conn)
162
+ try:
163
+ cur.execute(select_sql)
164
+ except Exception as e:
165
+ raise DBQueryError(select_sql, e)
166
+
167
+ rows = cur.fetchall()
168
+ for row in rows:
169
+ yield self.row_to_dict(row)
@@ -0,0 +1,18 @@
1
+ from ...errors import ConverterError
2
+
3
+
4
+ class DBConnectionError(ConverterError):
5
+ pass
6
+
7
+
8
+ class DBQueryError(ConverterError):
9
+ def __init__(self, query, error, data=None):
10
+ self.query = query
11
+ self.data = data
12
+ self.error = error
13
+
14
+ super().__init__(f"Error running query: {query} with {data} - {error}")
15
+
16
+
17
+ class DBInsertDataError(ConverterError):
18
+ pass
@@ -0,0 +1,56 @@
1
+ from typing import Dict
2
+
3
+ import pandas as pd
4
+ import pyodbc
5
+
6
+ from .base import BaseDBConnector
7
+ from .errors import DBConnectionError
8
+
9
+
10
+ class SQLServerConnector(BaseDBConnector):
11
+ """
12
+ Connects to an Microsoft SQL Server for reading and writing data.
13
+ """
14
+
15
+ name = "SQL Server Connector"
16
+ driver = "{ODBC Driver 17 for SQL Server}"
17
+
18
+ def _create_connection(self, database: Dict[str, str]):
19
+ """
20
+ Create database connection to the SQLite database specified in database
21
+ :param database: Dict object with connection info
22
+
23
+ :return: Connection object
24
+ """
25
+
26
+ try:
27
+ conn = pyodbc.connect(
28
+ "DRIVER={};SERVER={};PORT={};DATABASE={};UID={};PWD={}".format(
29
+ self.driver,
30
+ database["host"],
31
+ database["port"],
32
+ database["database"],
33
+ database["user"],
34
+ database["password"],
35
+ )
36
+ )
37
+ except Exception:
38
+ raise DBConnectionError()
39
+
40
+ return conn
41
+
42
+ def fetch_data(self, batch_size: int):
43
+ """
44
+ Fetch data from the database in batches.
45
+
46
+ :param batch_size: Number of rows per batch
47
+
48
+ :yield: Data batches as pandas DataFrames
49
+ """
50
+
51
+ with open(self.sql_statement_path, 'r') as file:
52
+ sql_query = file.read()
53
+
54
+ with self._create_connection(self.database) as conn:
55
+ for batch in pd.read_sql(sql_query, conn, chunksize=batch_size):
56
+ yield batch
@@ -0,0 +1,47 @@
1
+ from typing import Dict
2
+
3
+ import pandas as pd
4
+ import psycopg2
5
+ import psycopg2.extras
6
+
7
+ from .base import BaseDBConnector
8
+ from .errors import DBConnectionError
9
+
10
+
11
+ class PostgresConnector(BaseDBConnector):
12
+ """
13
+ Connects to a Postgres database for reading and writing data.
14
+ """
15
+
16
+ name = "Postgres Connector"
17
+ sql_params_output = "pyformat"
18
+
19
+ def _create_connection(self, database: Dict[str, str]):
20
+ """
21
+ Create database connection to the Postgres database
22
+ :param database: Dict with database connection settings
23
+
24
+ :return: Connection object
25
+ """
26
+ try:
27
+ conn = psycopg2.connect(**database)
28
+ except Exception as e:
29
+ raise DBConnectionError(e)
30
+
31
+ return conn
32
+
33
+ def fetch_data(self, batch_size: int):
34
+ """
35
+ Fetch data from the database in batches.
36
+
37
+ :param batch_size: Number of rows per batch
38
+
39
+ :yield: Data batches as pandas DataFrames
40
+ """
41
+
42
+ with open(self.sql_statement_path, 'r') as file:
43
+ sql_query = file.read()
44
+
45
+ with self._create_connection(self.database) as conn:
46
+ for batch in pd.read_sql(sql_query, conn, chunksize=batch_size):
47
+ yield batch
@@ -0,0 +1,73 @@
1
+ from typing import Dict
2
+
3
+ import pandas as pd
4
+ import sqlite3
5
+ from sqlite3 import Error
6
+
7
+ from .base import BaseDBConnector
8
+ from .errors import DBConnectionError
9
+
10
+
11
+ class SQLiteConnector(BaseDBConnector):
12
+ """
13
+ Connects to an sqlite file on the local machine for reading and writing
14
+ data.
15
+ """
16
+
17
+ name = "SQLite Connector"
18
+ options_schema = {
19
+ "type": "object",
20
+ "properties": {
21
+ "database": {
22
+ "type": "string",
23
+ "description": (
24
+ "The database name or relative path to the file for "
25
+ "sqlite3"
26
+ ),
27
+ "title": "Database",
28
+ "subtype": "path",
29
+ },
30
+ "sql_statement": {
31
+ "type": "string",
32
+ "description": "The path to the file which contains the "
33
+ "sql statement to run",
34
+ "subtype": "path",
35
+ "title": "Select Statement File",
36
+ },
37
+ },
38
+ "required": ["database", "select_statement", "insert_statement"],
39
+ }
40
+
41
+ def _create_connection(self, database: Dict[str, str]):
42
+ """
43
+ Create database connection to the SQLite database specified in database
44
+ :param database: Dict object with connection info
45
+
46
+ :return: Connection object
47
+ """
48
+
49
+ try:
50
+ conn = sqlite3.connect(
51
+ self.config.absolute_path(database["database"])
52
+ )
53
+ except Error:
54
+ raise DBConnectionError()
55
+
56
+ conn.row_factory = sqlite3.Row
57
+ return conn
58
+
59
+ def fetch_data(self, batch_size: int):
60
+ """
61
+ Fetch data from the database in batches.
62
+
63
+ :param batch_size: Number of rows per batch
64
+
65
+ :yield: Data batches as pandas DataFrames
66
+ """
67
+
68
+ with open(self.sql_statement_path, 'r') as file:
69
+ sql_query = file.read()
70
+
71
+ with self._create_connection(self.database) as conn:
72
+ for batch in pd.read_sql(sql_query, conn, chunksize=batch_size):
73
+ yield batch
@@ -11,8 +11,61 @@ from .connector import BaseConnector
11
11
  from .mapping import BaseMapping
12
12
  from .runner import BaseRunner
13
13
 
14
+ # Default versions for OED and AIR when running without a config file
15
+ OED_VERSION = "3.0.2"
16
+ AIR_VERSION = "10.0.0"
17
+
18
+ FORMAT_MAPPINGS = {
19
+ 'oed-air': {
20
+ 'input_format': {'name': 'OED_Location', 'version': OED_VERSION},
21
+ 'output_format': {'name': 'Cede_Location', 'version': AIR_VERSION}
22
+ },
23
+ 'air-oed': {
24
+ 'input_format': {'name': 'Cede_Location', 'version': AIR_VERSION},
25
+ 'output_format': {'name': 'OED_Location', 'version': OED_VERSION}
26
+ }
27
+ }
28
+
29
+ # Default config when running without a config file
30
+ BASE_CONFIG = {
31
+ "transformations": {
32
+ "loc": {
33
+ "input_format": {
34
+ "name": "",
35
+ "version": ""
36
+ },
37
+ "output_format": {
38
+ "name": "",
39
+ "version": ""
40
+ },
41
+ "runner": {
42
+ "batch_size": 150000
43
+ },
44
+ "extractor": {
45
+ "options": {
46
+ "path": "",
47
+ "quoting": "minimal"
48
+ }
49
+ },
50
+ "loader": {
51
+ "options": {
52
+ "path": "",
53
+ "quoting": "minimal"
54
+ }
55
+ }
56
+ }
57
+ }
58
+ }
59
+
14
60
  logger = logging.getLogger(__name__)
15
61
 
62
+ CONNECTOR_MAPPINGS = {
63
+ "csv": "ods_tools.odtf.connector.CsvConnector",
64
+ "mssql": "ods_tools.odtf.connector.db.mssql.SQLServerConnector",
65
+ "postgres": "ods_tools.odtf.connector.db.postgres.PostgresConnector",
66
+ "sqlite": "ods_tools.odtf.connector.db.sqlite.SQLiteConnector",
67
+ }
68
+
16
69
 
17
70
  class Controller:
18
71
  """
@@ -79,11 +132,11 @@ class Controller:
79
132
  **config.get("mapping.options", fallback={}),
80
133
  )
81
134
 
82
- extractor_class: Type[BaseConnector] = self._load_from_module(
83
- config.get(
84
- "extractor.path", fallback="ods_tools.odtf.connector.CsvConnector"
135
+ extractor_type = config.get("extractor.type", fallback="csv")
136
+ if extractor_type in CONNECTOR_MAPPINGS:
137
+ extractor_class: Type[BaseConnector] = self._load_from_module(
138
+ CONNECTOR_MAPPINGS[extractor_type]
85
139
  )
86
- )
87
140
  extractor: BaseConnector = extractor_class(
88
141
  config, **config.get("extractor.options", fallback={})
89
142
  )
@@ -114,9 +167,56 @@ class Controller:
114
167
  return None
115
168
 
116
169
 
117
- def transform_format(path_to_config_file):
118
- with open(path_to_config_file, 'r') as file:
119
- config_dict = yaml.safe_load(file)
170
+ def generate_config(input_file, output_file, transformation_type):
171
+ """
172
+ This function generates a config dictionary based on the input parameters.
173
+ When running without a config file, this will generate the config dict.
174
+
175
+ Args:
176
+ input_file (str): path to the input file
177
+ output_file (str): path to the output file
178
+ transformation_type (str): either 'oed-air' or 'air-oed'
179
+
180
+ Raises:
181
+ ValueError: if transformation_type is not 'oed-air' or 'air-oed'
182
+
183
+ Returns:
184
+ dict: the generated config dictionary
185
+ """
186
+ if transformation_type not in FORMAT_MAPPINGS:
187
+ raise ValueError(
188
+ f'Invalid transformation type. Only {list(FORMAT_MAPPINGS.keys())} are supported.'
189
+ )
190
+
191
+ config_dict = BASE_CONFIG.copy()
192
+ config_dict['transformations']['loc']['input_format'] = FORMAT_MAPPINGS[transformation_type]['input_format']
193
+ config_dict['transformations']['loc']['output_format'] = FORMAT_MAPPINGS[transformation_type]['output_format']
194
+ config_dict['transformations']['loc']['extractor']['options']['path'] = input_file
195
+ config_dict['transformations']['loc']['loader']['options']['path'] = output_file
196
+
197
+ return config_dict
198
+
199
+
200
+ def transform_format(path_to_config_file=None, input_file=None, output_file=None, transformation=None):
201
+ """This function takes the input parameters when called from ods_tools
202
+ and starts the transformation process. Either path_to_config_file or
203
+ all three input_file, output_file, and transformation_type must be provided.
204
+
205
+ Args:
206
+ path_to_config_file (str): path to the config file. Defaults to None.
207
+ input_file (str: path to the input file. Defaults to None.
208
+ output_file (str): path to the output file. Defaults to None.
209
+ transformation_type (str): Either 'oed-air' or 'air-oed'. Defaults to None.
210
+
211
+ Returns:
212
+ list: a list of tuples containing the output file path and the file type.
213
+ Used for checking the output files.
214
+ """
215
+ if path_to_config_file:
216
+ with open(path_to_config_file, 'r') as file:
217
+ config_dict = yaml.safe_load(file)
218
+ else:
219
+ config_dict = generate_config(input_file, output_file, transformation)
120
220
  config = Config(config_dict)
121
221
  controller = Controller(config)
122
222
  controller.run()
@@ -277,16 +277,6 @@ class PandasRunner(BaseRunner):
277
277
  def create_series(self, index, value):
278
278
  return self.series_type(value, index=index)
279
279
 
280
- def get_dataframe(self, extractor: BaseConnector) -> pd.DataFrame:
281
- """
282
- Builds a dataframe from the extractors data
283
-
284
- :param extractor: The extractor providing the input data
285
-
286
- :return: The created dataframe
287
- """
288
- return pd.DataFrame(extractor.extract(), dtype="object")
289
-
290
280
  def combine_column(
291
281
  self,
292
282
  row,
@@ -422,27 +412,38 @@ class PandasRunner(BaseRunner):
422
412
  def transform(
423
413
  self, extractor: BaseConnector, mapping: BaseMapping
424
414
  ) -> Iterable[Dict[str, Any]]:
425
- available_columns = set(pd.read_csv(extractor.file_path, nrows=1).columns)
426
- transformations = mapping.get_transformations(available_columns=available_columns)
427
-
415
+ """
416
+ Transforms the data.
417
+ It receives it in batches from the extractor, calculates which
418
+ transformations can be applied to it, applies them, and yields the
419
+ transformed rows.
420
+
421
+ :param extractor: The data extractor object (e.g., CSV or database connector).
422
+ :param mapping: The mapping object defining transformations.
423
+ :return: An iterable of dictionaries, each representing a transformed row.
424
+ """
428
425
  validator = PandasValidator(search_paths=([os.path.dirname(self.config.path)] if self.config.path else []))
429
-
430
- logger.info(f"Running transformation set {transformations[0].input_format} -> {transformations[-1].output_format}")
431
- total_rows = 0
432
426
  runner_config = self.config.config.get('runner', None)
433
- batch_size = runner_config.get('batch_size', 50000)
427
+ batch_size = runner_config.get('batch_size', 100000)
428
+ total_rows = 0
429
+ transformations = []
434
430
 
435
- for batch in pd.read_csv(extractor.file_path, chunksize=batch_size, low_memory=False):
431
+ for batch in extractor.fetch_data(batch_size):
432
+ # Calculates the set of transformations from the columns in the
433
+ # first batch (to avoid double-querying)
434
+ if not transformations:
435
+ available_columns = set(batch.columns)
436
+ transformations = mapping.get_transformations(available_columns=available_columns)
437
+ logger.info(f"Running transformation set {transformations[0].input_format} -> {transformations[-1].output_format} [{extractor.name}]")
436
438
 
437
439
  validator.run(self.coerce_row_types(batch, transformations[0].types),
438
440
  mapping.input_format.name, mapping.input_format.version, mapping.file_type)
439
441
 
440
- transformed = batch
441
442
  for transformation in transformations:
442
- transformed = self.apply_transformation_set(transformed, transformation)
443
+ batch = self.apply_transformation_set(batch, transformation)
443
444
 
444
- validator.run(transformed, mapping.output_format.name, mapping.output_format.version, mapping.file_type)
445
+ validator.run(batch, mapping.output_format.name, mapping.output_format.version, mapping.file_type)
445
446
  total_rows += len(batch)
446
447
  logger.info(f"Processed {len(batch)} rows in the current batch (total: {total_rows})")
447
448
 
448
- yield from (r.to_dict() for idx, r in transformed.iterrows())
449
+ yield from (r.to_dict() for idx, r in batch.iterrows())
@@ -5,7 +5,7 @@ from .source import OedSource
5
5
  from .common import (
6
6
  OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, USUAL_FILE_NAME, OED_TYPE_TO_NAME,
7
7
  OED_NAME_TO_TYPE, OED_IDENTIFIER_FIELDS, VALIDATOR_ON_ERROR_ACTION, DEFAULT_VALIDATION_CONFIG, OED_PERIL_COLUMNS, fill_empty,
8
- UnknownColumnSaveOption, BLANK_VALUES
8
+ UnknownColumnSaveOption, BLANK_VALUES, is_empty
9
9
  )
10
10
 
11
11
 
@@ -13,5 +13,5 @@ __all__ = [
13
13
  'OedExposure', 'OedSchema', 'OedSource', 'ModelSettingSchema', 'AnalysisSettingSchema',
14
14
  'OdsException', 'PANDAS_COMPRESSION_MAP', 'PANDAS_DEFAULT_NULL_VALUES', 'USUAL_FILE_NAME', 'OED_TYPE_TO_NAME',
15
15
  'OED_NAME_TO_TYPE', 'OED_IDENTIFIER_FIELDS', 'VALIDATOR_ON_ERROR_ACTION', 'DEFAULT_VALIDATION_CONFIG', 'OED_PERIL_COLUMNS', 'fill_empty',
16
- 'UnknownColumnSaveOption', 'BLANK_VALUES'
16
+ 'UnknownColumnSaveOption', 'BLANK_VALUES', 'is_empty'
17
17
  ]
@@ -143,6 +143,19 @@ OED_PERIL_COLUMNS = ['AccPeril', 'PolPerilsCovered', 'PolPeril', 'CondPeril', 'L
143
143
 
144
144
  BLANK_VALUES = {np.nan, '', None, pd.NA, pd.NaT}
145
145
 
146
+ dtype_to_python = {
147
+ 'Int8': int,
148
+ 'Int32': int,
149
+ 'Int64': int,
150
+ 'bytes': lambda x: bytes(x, 'utf-8'),
151
+ 'float64': float,
152
+ 'category': str
153
+ }
154
+
155
+
156
+ def is_empty(df, columns):
157
+ return (df[columns].isnull()) | (df[columns] == '')
158
+
146
159
 
147
160
  def fill_empty(df, columns, value):
148
161
  if isinstance(columns, str):
@@ -151,7 +164,7 @@ def fill_empty(df, columns, value):
151
164
  dtype = getattr(df[column], "dtypes", getattr(df[column], "dtype", None))
152
165
  if dtype.name == 'category' and value not in {None, np.nan}.union(df[column].cat.categories):
153
166
  df[column] = df[column].cat.add_categories(value)
154
- df.loc[df[column].isin(BLANK_VALUES), column] = value
167
+ df.loc[is_empty(df, column), column] = value
155
168
 
156
169
 
157
170
  class UnknownColumnSaveOption(Enum):
@@ -8,6 +8,7 @@ This package manage:
8
8
  import json
9
9
  from copy import deepcopy
10
10
  import logging
11
+ import numpy as np
11
12
  from packaging import version
12
13
  from pathlib import Path
13
14
 
@@ -80,7 +81,7 @@ class OedExposure:
80
81
  if column not in df.columns or not values:
81
82
  return df
82
83
 
83
- return df[df[column].isin(values)]
84
+ return df[np.isin(df[column], values)]
84
85
  return fn
85
86
 
86
87
  loc_filters = [
@@ -4,7 +4,7 @@ from pathlib import Path
4
4
  import numba as nb
5
5
  import numpy as np
6
6
 
7
- from .common import OdsException, BLANK_VALUES, cached_property
7
+ from .common import OdsException, BLANK_VALUES, cached_property, dtype_to_python
8
8
 
9
9
  ENV_ODS_SCHEMA_PATH = os.getenv('ODS_SCHEMA_PATH')
10
10
 
@@ -139,6 +139,25 @@ class OedSchema:
139
139
  return jit_peril_filtering(peril_ids.to_numpy().astype('str'), peril_filters.to_numpy().astype('str'),
140
140
  self.nb_peril_groups_dict if include_sub_group else self.nb_perils_dict)
141
141
 
142
+ @staticmethod
143
+ def get_default_from_ods_fields(ods_fields, field_name):
144
+ field_info = ods_fields.get(field_name.lower())
145
+ if field_info is None:
146
+ return ''
147
+ if field_info['pd_dtype'] == 'category':
148
+ if field_info['Default'] != 'n/a':
149
+ return field_info['Default']
150
+ else:
151
+ return ''
152
+ else:
153
+ if field_info['Default'] != 'n/a':
154
+ return dtype_to_python[field_info['pd_dtype']](field_info['Default'])
155
+ else:
156
+ return np.nan
157
+
158
+ def get_default(self, field_name, oed_type='null'):
159
+ return self.get_default_from_ods_fields(self.schema['input_fields'][oed_type], field_name)
160
+
142
161
  @staticmethod
143
162
  def to_universal_field_name(column: str):
144
163
  """
@@ -7,8 +7,8 @@ from oasis_data_manager.df_reader.config import get_df_reader
7
7
  import numpy as np
8
8
  from chardet.universaldetector import UniversalDetector
9
9
 
10
- from .common import (OED_TYPE_TO_NAME, OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, is_relative, BLANK_VALUES, fill_empty,
11
- UnknownColumnSaveOption, cached_property)
10
+ from .common import (OED_TYPE_TO_NAME, OdsException, PANDAS_COMPRESSION_MAP, PANDAS_DEFAULT_NULL_VALUES, is_relative, fill_empty,
11
+ UnknownColumnSaveOption, cached_property, is_empty)
12
12
  from .forex import convert_currency
13
13
  from .oed_schema import OedSchema
14
14
 
@@ -282,7 +282,7 @@ class OedSource:
282
282
  if oed_df[column].dtype.name == 'category' and '' not in oed_df[column].dtype.categories:
283
283
  oed_df[column] = oed_df[column].cat.add_categories('')
284
284
  oed_df[column] = oed_df[column] # make a copy f the col in case it is read_only
285
- oed_df.loc[oed_df[column].isin(BLANK_VALUES), column] = ''
285
+ oed_df.loc[is_empty(oed_df, column), column] = ''
286
286
  elif pd_dtype[column].startswith('Int'):
287
287
  to_tmp_dtype[column] = 'float'
288
288
 
@@ -302,12 +302,7 @@ class OedSource:
302
302
  """
303
303
  # set default values
304
304
  for col, field_info in column_to_field.items():
305
- if (field_info
306
- and field_info['Default'] != 'n/a'
307
- and (df[col].isna().any() or (field_info['pd_dtype'] == 'category' and df[col].isnull().any()))):
308
- fill_empty(df, col, df[col].dtype.type(field_info['Default']))
309
- elif df[col].dtype.name == 'category':
310
- fill_empty(df, col, '')
305
+ fill_empty(df, col, OedSchema.get_default_from_ods_fields(ods_fields, col))
311
306
 
312
307
  # add required columns that allow blank values if missing
313
308
  present_field = set(field_info['Input Field Name'] for field_info in column_to_field.values())
@@ -1,12 +1,13 @@
1
1
  import functools
2
2
  import json
3
+ import numpy as np
3
4
  import logging
4
5
 
5
6
  from pathlib import Path
6
7
  from collections.abc import Iterable
7
8
 
8
9
  from .common import (OdsException, OED_PERIL_COLUMNS, OED_IDENTIFIER_FIELDS, DEFAULT_VALIDATION_CONFIG,
9
- VALIDATOR_ON_ERROR_ACTION, BLANK_VALUES)
10
+ VALIDATOR_ON_ERROR_ACTION, BLANK_VALUES, is_empty)
10
11
  from .oed_schema import OedSchema
11
12
 
12
13
  logger = logging.getLogger(__name__)
@@ -134,7 +135,7 @@ class Validator:
134
135
  columns = [columns]
135
136
  for column in columns:
136
137
  if field_info.get("Allow blanks?").upper() == 'NO':
137
- missing_value_df = oed_source.dataframe[oed_source.dataframe[column].isin(BLANK_VALUES)]
138
+ missing_value_df = oed_source.dataframe[is_empty(oed_source.dataframe, column)]
138
139
  if not missing_value_df.empty:
139
140
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
140
141
  'msg': f"column '{column}' has missing values in \n"
@@ -222,8 +223,9 @@ class Validator:
222
223
  if occupancy_code_column is None:
223
224
  continue
224
225
  identifier_field = self.identifier_field_maps[oed_source]
225
- invalid_occupancy_code = oed_source.dataframe[~oed_source.dataframe[occupancy_code_column].astype(str).isin(
226
- set(self.exposure.oed_schema.schema['occupancy']) | BLANK_VALUES)]
226
+ invalid_occupancy_code = oed_source.dataframe[~(np.isin(oed_source.dataframe[occupancy_code_column].astype(str),
227
+ list(self.exposure.oed_schema.schema['occupancy']))
228
+ | is_empty(oed_source.dataframe, occupancy_code_column))]
227
229
  if not invalid_occupancy_code.empty:
228
230
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
229
231
  'msg': f"invalid OccupancyCode.\n"
@@ -242,8 +244,9 @@ class Validator:
242
244
  if construction_code_column is None:
243
245
  continue
244
246
  identifier_field = self.identifier_field_maps[oed_source]
245
- invalid_construction_code = oed_source.dataframe[~oed_source.dataframe[construction_code_column].astype(str).isin(
246
- set(self.exposure.oed_schema.schema['construction']) | BLANK_VALUES)]
247
+ invalid_construction_code = oed_source.dataframe[~(np.isin(oed_source.dataframe[construction_code_column].astype(str),
248
+ list(self.exposure.oed_schema.schema['construction']))
249
+ | is_empty(oed_source.dataframe, construction_code_column))]
247
250
  if not invalid_construction_code.empty:
248
251
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
249
252
  'msg': f"invalid ConstructionCode.\n"
@@ -265,8 +268,9 @@ class Validator:
265
268
  identifier_field = self.identifier_field_maps[oed_source]
266
269
  area_code_column = self.field_to_column_maps[oed_source].get('AreaCode')
267
270
  if area_code_column is not None:
268
- country_only_df = oed_source.dataframe[oed_source.dataframe[area_code_column].isin(BLANK_VALUES)]
269
- country_area_df = oed_source.dataframe[~oed_source.dataframe[area_code_column].isin(BLANK_VALUES)]
271
+ country_only_df = oed_source.dataframe[is_empty(oed_source.dataframe, area_code_column)]
272
+ country_area_df = oed_source.dataframe[~is_empty(oed_source.dataframe, area_code_column)]
273
+
270
274
  invalid_country_area = (country_area_df[
271
275
  ~(country_area_df[[country_code_column, area_code_column]]
272
276
  .apply(tuple, axis=1)
@@ -279,8 +283,9 @@ class Validator:
279
283
  f"{invalid_country_area[identifier_field + [country_code_column, area_code_column]]}"})
280
284
  else:
281
285
  country_only_df = oed_source.dataframe
282
- invalid_country = (country_only_df[~country_only_df[country_code_column]
283
- .isin(set(self.exposure.oed_schema.schema['country']) | BLANK_VALUES)])
286
+ invalid_country = (country_only_df[~(np.isin(country_only_df[country_code_column],
287
+ list(self.exposure.oed_schema.schema['country']))
288
+ | is_empty(country_only_df, country_code_column))])
284
289
  if not invalid_country.empty:
285
290
  invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
286
291
  'msg': f"invalid CountryCode.\n"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods-tools
3
- Version: 3.2.3
3
+ Version: 3.2.5
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -9,6 +9,7 @@ License: UNKNOWN
9
9
  Platform: UNKNOWN
10
10
  Requires-Python: >=3.7
11
11
  Description-Content-Type: text/markdown
12
+ Provides-Extra: extra
12
13
 
13
14
  # ODS Tools
14
15
 
@@ -20,6 +20,12 @@ ods_tools/odtf/validator_pandas.py
20
20
  ods_tools/odtf/connector/__init__.py
21
21
  ods_tools/odtf/connector/base.py
22
22
  ods_tools/odtf/connector/csv.py
23
+ ods_tools/odtf/connector/db/__init__.py
24
+ ods_tools/odtf/connector/db/base.py
25
+ ods_tools/odtf/connector/db/errors.py
26
+ ods_tools/odtf/connector/db/mssql.py
27
+ ods_tools/odtf/connector/db/postgres.py
28
+ ods_tools/odtf/connector/db/sqlite.py
23
29
  ods_tools/odtf/data/__init__.py
24
30
  ods_tools/odtf/files/__init__.py
25
31
  ods_tools/odtf/files/csv.py
@@ -5,6 +5,12 @@ jsonschema
5
5
  jsonref
6
6
  oasis-data-manager
7
7
  packaging
8
+
9
+ [extra]
8
10
  PyYAML
9
11
  lark
10
12
  networkx
13
+ pyodbc
14
+ sqlparams
15
+ sqlparse
16
+ psycopg2
@@ -12,7 +12,7 @@ import json
12
12
 
13
13
  SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))
14
14
 
15
- OED_VERSION = '3.1.0'
15
+ OED_VERSION = '3.4.0'
16
16
  # ORD_VERSION =
17
17
 
18
18
 
@@ -34,6 +34,11 @@ def get_install_requirements():
34
34
  return reqs.readlines()
35
35
 
36
36
 
37
+ def get_extra_requirements():
38
+ with io.open(os.path.join(SCRIPT_DIR, 'requirements-extra.in'), encoding='utf-8') as extrareqs:
39
+ return extrareqs.readlines()
40
+
41
+
37
42
  class DownloadSpecODS(orig.install):
38
43
  """A custom command to download a JSON ODS spec during installation.
39
44
 
@@ -89,6 +94,7 @@ class DownloadSpecODS(orig.install):
89
94
  version = get_version()
90
95
  readme = get_readme()
91
96
  reqs = get_install_requirements()
97
+ extra_reqs = get_extra_requirements()
92
98
 
93
99
  setuptools.setup(
94
100
  name="ods_tools",
@@ -109,6 +115,9 @@ setuptools.setup(
109
115
  package_dir={'ods_tools': 'ods_tools'},
110
116
  python_requires='>=3.7',
111
117
  install_requires=reqs,
118
+ extras_require={
119
+ 'extra': extra_reqs,
120
+ },
112
121
  description='Tools to manage ODS files',
113
122
  long_description=readme,
114
123
  long_description_content_type='text/markdown',
File without changes
File without changes