ods-tools 3.2.4__tar.gz → 3.2.6__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.
- {ods_tools-3.2.4 → ods_tools-3.2.6}/PKG-INFO +75 -1
- {ods_tools-3.2.4 → ods_tools-3.2.6}/README.md +73 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/__init__.py +1 -1
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/main.py +23 -6
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/connector/csv.py +11 -3
- ods_tools-3.2.6/ods_tools/odtf/connector/db/__init__.py +10 -0
- ods_tools-3.2.6/ods_tools/odtf/connector/db/base.py +169 -0
- ods_tools-3.2.6/ods_tools/odtf/connector/db/errors.py +18 -0
- ods_tools-3.2.6/ods_tools/odtf/connector/db/mssql.py +56 -0
- ods_tools-3.2.6/ods_tools/odtf/connector/db/postgres.py +47 -0
- ods_tools-3.2.6/ods_tools/odtf/connector/db/sqlite.py +73 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/controller.py +107 -7
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/mapping/file.py +2 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/runner/pandas.py +23 -22
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/source.py +1 -1
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/validator.py +14 -3
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/PKG-INFO +75 -1
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/SOURCES.txt +6 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/requires.txt +6 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/setup.py +10 -1
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/data/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/config.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/connector/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/connector/base.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/data/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/errors.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/files/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/files/csv.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/files/yaml.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/log.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/mapping/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/mapping/base.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/mapping/errors.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/notset.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/runner/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/runner/base.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/transformers/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/transformers/errors.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/transformers/grammar.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/transformers/transform.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/transformers/transform_utils.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/validator_base.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/odtf/validator_pandas.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/__init__.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/common.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/exposure.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/forex.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/oed_schema.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools/oed/setting_schema.py +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/dependency_links.txt +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/entry_points.txt +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/ods_tools.egg-info/top_level.txt +0 -0
- {ods_tools-3.2.4 → ods_tools-3.2.6}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ods_tools
|
|
3
|
-
Version: 3.2.
|
|
3
|
+
Version: 3.2.6
|
|
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
|
|
|
@@ -31,6 +32,13 @@ ODS_Tools can be installed via pip by running the following command:
|
|
|
31
32
|
pip install ods-tools
|
|
32
33
|
```
|
|
33
34
|
|
|
35
|
+
If using the `transform` command, use instead
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
pip install ods-tools[extra]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
which will install some optional packages needed for it.
|
|
34
42
|
|
|
35
43
|
## command line interface
|
|
36
44
|
|
|
@@ -250,6 +258,72 @@ oed_exposure.currency_conversion = ods_tools.oed.forex.create_currency_rates(
|
|
|
250
258
|
oed_exposure.reporting_currency = 'EUR' # this line will trigger currency conversion
|
|
251
259
|
```
|
|
252
260
|
|
|
261
|
+
### Format Conversions
|
|
262
|
+
|
|
263
|
+
The `transform` command can be used to convert between OED and other formats.
|
|
264
|
+
To run transformations, and extra set of packages must be installed. This can be done using `pip install ods-tools[extra]` (or `pip install --upgrade ods-tools[extra]` if already installed).
|
|
265
|
+
|
|
266
|
+
**Basic csv conversion**
|
|
267
|
+
|
|
268
|
+
A simple csv-to-csv transformation can be run from the command line with
|
|
269
|
+
```
|
|
270
|
+
ods_tools transform -f air-oed --input-file source.csv --output-file output.csv
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The flag -f instructs the tool on which are the origin and destination formats (currently air and oed).
|
|
274
|
+
|
|
275
|
+
**Complex conversions**
|
|
276
|
+
|
|
277
|
+
More complex transformations run with `ods_tools transform` requires a configuration file, passed with the option `--config-file`. Please see the docs [here](https://oasislmf.github.io/sections/ODTF.html)
|
|
278
|
+
|
|
279
|
+
A configuration file must contain:
|
|
280
|
+
|
|
281
|
+
- type of file to transform (location or account)
|
|
282
|
+
- input format
|
|
283
|
+
- output format
|
|
284
|
+
- batch size
|
|
285
|
+
- input file
|
|
286
|
+
- output file
|
|
287
|
+
|
|
288
|
+
For example:
|
|
289
|
+
|
|
290
|
+
```
|
|
291
|
+
transformations:
|
|
292
|
+
loc: # type of file to transform, can be "acc" or "loc"
|
|
293
|
+
input_format:
|
|
294
|
+
name: Cede_Location
|
|
295
|
+
version: 10.0.0
|
|
296
|
+
output_format:
|
|
297
|
+
name: OED_Location
|
|
298
|
+
version: 3.0.2
|
|
299
|
+
runner:
|
|
300
|
+
batch_size: 150000 # Number of rows to process in a single batch
|
|
301
|
+
extractor:
|
|
302
|
+
options:
|
|
303
|
+
path: /path/to/input.csv # Path to the input file
|
|
304
|
+
quoting: minimal
|
|
305
|
+
loader:
|
|
306
|
+
options:
|
|
307
|
+
path: /path/to/output.csv # Path to the output file
|
|
308
|
+
quoting: minimal
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
For a transformation to be run, the folder `./ods_tools/odtf/data/mappings` must contain the appropriate yaml configuration file that describes the transformations to perform on the input file to obtain the output (and, potentially, vice versa). Currently, only [mapping_loc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_loc_Cede-OED.yaml) and
|
|
313
|
+
[mapping_acc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_acc_Cede-OED.yaml) are provided; they describe the transformation between AIR Cede v10.0.0 and OED 3.0.2 for location and account files respectively.
|
|
314
|
+
|
|
315
|
+
The transformation can be run using:
|
|
316
|
+
|
|
317
|
+
```
|
|
318
|
+
ods_tools transform --config-file configuration.yaml
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
**Options**
|
|
322
|
+
|
|
323
|
+
The following options can be used to adjust the process:
|
|
324
|
+
|
|
325
|
+
`--nocheck` to skip the oed validation at the end of the conversion
|
|
253
326
|
|
|
327
|
+
`-v` to adjust the logging level (debug:10, info:20, warning:30, error:40, critical:50)
|
|
254
328
|
|
|
255
329
|
|
|
@@ -19,6 +19,13 @@ ODS_Tools can be installed via pip by running the following command:
|
|
|
19
19
|
pip install ods-tools
|
|
20
20
|
```
|
|
21
21
|
|
|
22
|
+
If using the `transform` command, use instead
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
pip install ods-tools[extra]
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
which will install some optional packages needed for it.
|
|
22
29
|
|
|
23
30
|
## command line interface
|
|
24
31
|
|
|
@@ -238,4 +245,70 @@ oed_exposure.currency_conversion = ods_tools.oed.forex.create_currency_rates(
|
|
|
238
245
|
oed_exposure.reporting_currency = 'EUR' # this line will trigger currency conversion
|
|
239
246
|
```
|
|
240
247
|
|
|
248
|
+
### Format Conversions
|
|
249
|
+
|
|
250
|
+
The `transform` command can be used to convert between OED and other formats.
|
|
251
|
+
To run transformations, and extra set of packages must be installed. This can be done using `pip install ods-tools[extra]` (or `pip install --upgrade ods-tools[extra]` if already installed).
|
|
252
|
+
|
|
253
|
+
**Basic csv conversion**
|
|
254
|
+
|
|
255
|
+
A simple csv-to-csv transformation can be run from the command line with
|
|
256
|
+
```
|
|
257
|
+
ods_tools transform -f air-oed --input-file source.csv --output-file output.csv
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
The flag -f instructs the tool on which are the origin and destination formats (currently air and oed).
|
|
261
|
+
|
|
262
|
+
**Complex conversions**
|
|
263
|
+
|
|
264
|
+
More complex transformations run with `ods_tools transform` requires a configuration file, passed with the option `--config-file`. Please see the docs [here](https://oasislmf.github.io/sections/ODTF.html)
|
|
265
|
+
|
|
266
|
+
A configuration file must contain:
|
|
267
|
+
|
|
268
|
+
- type of file to transform (location or account)
|
|
269
|
+
- input format
|
|
270
|
+
- output format
|
|
271
|
+
- batch size
|
|
272
|
+
- input file
|
|
273
|
+
- output file
|
|
274
|
+
|
|
275
|
+
For example:
|
|
276
|
+
|
|
277
|
+
```
|
|
278
|
+
transformations:
|
|
279
|
+
loc: # type of file to transform, can be "acc" or "loc"
|
|
280
|
+
input_format:
|
|
281
|
+
name: Cede_Location
|
|
282
|
+
version: 10.0.0
|
|
283
|
+
output_format:
|
|
284
|
+
name: OED_Location
|
|
285
|
+
version: 3.0.2
|
|
286
|
+
runner:
|
|
287
|
+
batch_size: 150000 # Number of rows to process in a single batch
|
|
288
|
+
extractor:
|
|
289
|
+
options:
|
|
290
|
+
path: /path/to/input.csv # Path to the input file
|
|
291
|
+
quoting: minimal
|
|
292
|
+
loader:
|
|
293
|
+
options:
|
|
294
|
+
path: /path/to/output.csv # Path to the output file
|
|
295
|
+
quoting: minimal
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
For a transformation to be run, the folder `./ods_tools/odtf/data/mappings` must contain the appropriate yaml configuration file that describes the transformations to perform on the input file to obtain the output (and, potentially, vice versa). Currently, only [mapping_loc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_loc_Cede-OED.yaml) and
|
|
300
|
+
[mapping_acc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_acc_Cede-OED.yaml) are provided; they describe the transformation between AIR Cede v10.0.0 and OED 3.0.2 for location and account files respectively.
|
|
301
|
+
|
|
302
|
+
The transformation can be run using:
|
|
303
|
+
|
|
304
|
+
```
|
|
305
|
+
ods_tools transform --config-file configuration.yaml
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
**Options**
|
|
309
|
+
|
|
310
|
+
The following options can be used to adjust the process:
|
|
311
|
+
|
|
312
|
+
`--nocheck` to skip the oed validation at the end of the conversion
|
|
241
313
|
|
|
314
|
+
`-v` to adjust the logging level (debug:10, info:20, warning:30, error:40, critical:50)
|
|
@@ -18,7 +18,10 @@ from ods_tools.oed import (
|
|
|
18
18
|
ModelSettingSchema,
|
|
19
19
|
AnalysisSettingSchema,
|
|
20
20
|
)
|
|
21
|
-
|
|
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
|
-
|
|
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(
|
|
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'
|
|
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
|
|
99
|
-
|
|
100
|
-
|
|
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,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
|
-
|
|
83
|
-
|
|
84
|
-
|
|
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
|
|
118
|
-
|
|
119
|
-
|
|
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()
|
|
@@ -434,6 +434,8 @@ class FileMapping(BaseMapping):
|
|
|
434
434
|
|
|
435
435
|
self._raw_configs: Union[None, Dict[str, RawMappingConfig]] = None
|
|
436
436
|
self._hydrated_configs: Union[None, Dict[str, FileMappingSpec]] = None
|
|
437
|
+
if isinstance(search_paths, str):
|
|
438
|
+
search_paths = [search_paths]
|
|
437
439
|
self.search_paths = [
|
|
438
440
|
*(os.path.abspath(p) for p in (search_paths or [])),
|
|
439
441
|
os.path.abspath(standard_search_path),
|
|
@@ -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
|
-
|
|
426
|
-
|
|
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',
|
|
427
|
+
batch_size = runner_config.get('batch_size', 100000)
|
|
428
|
+
total_rows = 0
|
|
429
|
+
transformations = []
|
|
434
430
|
|
|
435
|
-
for batch in
|
|
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
|
-
|
|
443
|
+
batch = self.apply_transformation_set(batch, transformation)
|
|
443
444
|
|
|
444
|
-
validator.run(
|
|
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
|
|
449
|
+
yield from (r.to_dict() for idx, r in batch.iterrows())
|
|
@@ -309,7 +309,7 @@ class OedSource:
|
|
|
309
309
|
for field_info in ods_fields.values():
|
|
310
310
|
col = field_info['Input Field Name']
|
|
311
311
|
if col not in present_field:
|
|
312
|
-
if field_info.get('Required Field') == 'R' and field_info.get("Allow blanks?").upper() == "YES":
|
|
312
|
+
if field_info.get('Required Field') == 'R' and field_info.get("Allow blanks?", '').upper() == "YES":
|
|
313
313
|
if field_info['pd_dtype'] == 'category':
|
|
314
314
|
df[col] = '' if field_info['Default'] == 'n/a' else field_info['Default']
|
|
315
315
|
df[col] = df[col].astype('category')
|
|
@@ -126,7 +126,9 @@ class Validator:
|
|
|
126
126
|
|
|
127
127
|
for field_info in input_fields.values():
|
|
128
128
|
if field_info['Input Field Name'] not in field_to_columns:
|
|
129
|
-
|
|
129
|
+
# OED v4 = 'Property field status' and OED v3 = 'Required Field'
|
|
130
|
+
requ_field_ref = 'Property field status' if 'Property field status' in field_info else 'Required Field'
|
|
131
|
+
if field_info.get(requ_field_ref) == 'R':
|
|
130
132
|
invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
|
|
131
133
|
'msg': f"missing required column {field_info['Input Field Name']}"})
|
|
132
134
|
continue
|
|
@@ -134,7 +136,11 @@ class Validator:
|
|
|
134
136
|
if isinstance(columns, str):
|
|
135
137
|
columns = [columns]
|
|
136
138
|
for column in columns:
|
|
137
|
-
|
|
139
|
+
blanks_not_allowed = any([
|
|
140
|
+
field_info.get("Allow blanks?", '').upper() == 'NO', # OED v3
|
|
141
|
+
field_info.get('Property field status', '').upper() == 'R' # OED v4
|
|
142
|
+
])
|
|
143
|
+
if blanks_not_allowed:
|
|
138
144
|
missing_value_df = oed_source.dataframe[is_empty(oed_source.dataframe, column)]
|
|
139
145
|
if not missing_value_df.empty:
|
|
140
146
|
invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
|
|
@@ -170,10 +176,15 @@ class Validator:
|
|
|
170
176
|
identifier_field = self.identifier_field_maps[oed_source]
|
|
171
177
|
for column, field_info in column_to_field.items():
|
|
172
178
|
valid_ranges = field_info['Valid value range']
|
|
179
|
+
blanks_allowed = any([
|
|
180
|
+
field_info.get('Allow blanks?', '').lower() == 'yes', # OED v3
|
|
181
|
+
field_info.get('Property field status', '').upper() != 'R', # OED v4
|
|
182
|
+
])
|
|
183
|
+
|
|
173
184
|
if valid_ranges != 'n/a':
|
|
174
185
|
is_valid_value = functools.partial(OedSchema.is_valid_value,
|
|
175
186
|
valid_ranges=valid_ranges,
|
|
176
|
-
allow_blanks=
|
|
187
|
+
allow_blanks=blanks_allowed)
|
|
177
188
|
invalid_range_data = oed_source.dataframe[~oed_source.dataframe[column].apply(is_valid_value)]
|
|
178
189
|
if not invalid_range_data.empty:
|
|
179
190
|
invalid_data.append({'name': oed_source.oed_name, 'source': oed_source.current_source,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.1
|
|
2
2
|
Name: ods-tools
|
|
3
|
-
Version: 3.2.
|
|
3
|
+
Version: 3.2.6
|
|
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
|
|
|
@@ -31,6 +32,13 @@ ODS_Tools can be installed via pip by running the following command:
|
|
|
31
32
|
pip install ods-tools
|
|
32
33
|
```
|
|
33
34
|
|
|
35
|
+
If using the `transform` command, use instead
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
pip install ods-tools[extra]
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
which will install some optional packages needed for it.
|
|
34
42
|
|
|
35
43
|
## command line interface
|
|
36
44
|
|
|
@@ -250,6 +258,72 @@ oed_exposure.currency_conversion = ods_tools.oed.forex.create_currency_rates(
|
|
|
250
258
|
oed_exposure.reporting_currency = 'EUR' # this line will trigger currency conversion
|
|
251
259
|
```
|
|
252
260
|
|
|
261
|
+
### Format Conversions
|
|
262
|
+
|
|
263
|
+
The `transform` command can be used to convert between OED and other formats.
|
|
264
|
+
To run transformations, and extra set of packages must be installed. This can be done using `pip install ods-tools[extra]` (or `pip install --upgrade ods-tools[extra]` if already installed).
|
|
265
|
+
|
|
266
|
+
**Basic csv conversion**
|
|
267
|
+
|
|
268
|
+
A simple csv-to-csv transformation can be run from the command line with
|
|
269
|
+
```
|
|
270
|
+
ods_tools transform -f air-oed --input-file source.csv --output-file output.csv
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
The flag -f instructs the tool on which are the origin and destination formats (currently air and oed).
|
|
274
|
+
|
|
275
|
+
**Complex conversions**
|
|
276
|
+
|
|
277
|
+
More complex transformations run with `ods_tools transform` requires a configuration file, passed with the option `--config-file`. Please see the docs [here](https://oasislmf.github.io/sections/ODTF.html)
|
|
278
|
+
|
|
279
|
+
A configuration file must contain:
|
|
280
|
+
|
|
281
|
+
- type of file to transform (location or account)
|
|
282
|
+
- input format
|
|
283
|
+
- output format
|
|
284
|
+
- batch size
|
|
285
|
+
- input file
|
|
286
|
+
- output file
|
|
287
|
+
|
|
288
|
+
For example:
|
|
289
|
+
|
|
290
|
+
```
|
|
291
|
+
transformations:
|
|
292
|
+
loc: # type of file to transform, can be "acc" or "loc"
|
|
293
|
+
input_format:
|
|
294
|
+
name: Cede_Location
|
|
295
|
+
version: 10.0.0
|
|
296
|
+
output_format:
|
|
297
|
+
name: OED_Location
|
|
298
|
+
version: 3.0.2
|
|
299
|
+
runner:
|
|
300
|
+
batch_size: 150000 # Number of rows to process in a single batch
|
|
301
|
+
extractor:
|
|
302
|
+
options:
|
|
303
|
+
path: /path/to/input.csv # Path to the input file
|
|
304
|
+
quoting: minimal
|
|
305
|
+
loader:
|
|
306
|
+
options:
|
|
307
|
+
path: /path/to/output.csv # Path to the output file
|
|
308
|
+
quoting: minimal
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
For a transformation to be run, the folder `./ods_tools/odtf/data/mappings` must contain the appropriate yaml configuration file that describes the transformations to perform on the input file to obtain the output (and, potentially, vice versa). Currently, only [mapping_loc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_loc_Cede-OED.yaml) and
|
|
313
|
+
[mapping_acc_Cede-OED.yaml](./ods_tools/odtf/data/mappings/mapping_acc_Cede-OED.yaml) are provided; they describe the transformation between AIR Cede v10.0.0 and OED 3.0.2 for location and account files respectively.
|
|
314
|
+
|
|
315
|
+
The transformation can be run using:
|
|
316
|
+
|
|
317
|
+
```
|
|
318
|
+
ods_tools transform --config-file configuration.yaml
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
**Options**
|
|
322
|
+
|
|
323
|
+
The following options can be used to adjust the process:
|
|
324
|
+
|
|
325
|
+
`--nocheck` to skip the oed validation at the end of the conversion
|
|
253
326
|
|
|
327
|
+
`-v` to adjust the logging level (debug:10, info:20, warning:30, error:40, critical:50)
|
|
254
328
|
|
|
255
329
|
|
|
@@ -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
|
|
@@ -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.
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|