ods-tools 3.2.6__tar.gz → 3.2.8__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.6 → ods_tools-3.2.8}/PKG-INFO +1 -1
  2. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/__init__.py +1 -1
  3. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/csv.py +24 -30
  4. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/mapping/base.py +1 -1
  5. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/runner/pandas.py +53 -22
  6. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/transformers/transform.py +15 -3
  7. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/source.py +3 -3
  8. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/PKG-INFO +1 -1
  9. {ods_tools-3.2.6 → ods_tools-3.2.8}/setup.py +1 -1
  10. {ods_tools-3.2.6 → ods_tools-3.2.8}/README.md +0 -0
  11. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/data/__init__.py +0 -0
  12. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/main.py +0 -0
  13. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/__init__.py +0 -0
  14. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/config.py +0 -0
  15. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/__init__.py +0 -0
  16. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/base.py +0 -0
  17. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/__init__.py +0 -0
  18. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/base.py +0 -0
  19. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/errors.py +0 -0
  20. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/mssql.py +0 -0
  21. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/postgres.py +0 -0
  22. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/connector/db/sqlite.py +0 -0
  23. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/controller.py +0 -0
  24. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/data/__init__.py +0 -0
  25. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/errors.py +0 -0
  26. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/files/__init__.py +0 -0
  27. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/files/csv.py +0 -0
  28. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/files/yaml.py +0 -0
  29. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/log.py +0 -0
  30. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/mapping/__init__.py +0 -0
  31. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/mapping/errors.py +0 -0
  32. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/mapping/file.py +0 -0
  33. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/notset.py +0 -0
  34. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/runner/__init__.py +0 -0
  35. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/runner/base.py +0 -0
  36. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/transformers/__init__.py +0 -0
  37. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/transformers/errors.py +0 -0
  38. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/transformers/grammar.py +0 -0
  39. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/transformers/transform_utils.py +0 -0
  40. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/validator_base.py +0 -0
  41. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/odtf/validator_pandas.py +0 -0
  42. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/__init__.py +0 -0
  43. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/common.py +0 -0
  44. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/exposure.py +0 -0
  45. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/forex.py +0 -0
  46. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/oed_schema.py +0 -0
  47. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/setting_schema.py +0 -0
  48. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools/oed/validator.py +0 -0
  49. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/SOURCES.txt +0 -0
  50. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/dependency_links.txt +0 -0
  51. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/entry_points.txt +0 -0
  52. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/requires.txt +0 -0
  53. {ods_tools-3.2.6 → ods_tools-3.2.8}/ods_tools.egg-info/top_level.txt +0 -0
  54. {ods_tools-3.2.6 → ods_tools-3.2.8}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods_tools
3
- Version: 3.2.6
3
+ Version: 3.2.8
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -1,4 +1,4 @@
1
- __version__ = '3.2.6'
1
+ __version__ = '3.2.8'
2
2
 
3
3
  import logging
4
4
 
@@ -1,6 +1,6 @@
1
- import csv
2
1
  from typing import Any, Dict, Iterable
3
2
 
3
+ import numpy as np
4
4
  import pandas as pd
5
5
 
6
6
  from .base import BaseConnector
@@ -63,39 +63,33 @@ class CsvConnector(BaseConnector):
63
63
 
64
64
  self.file_path = config.absolute_path(options["path"])
65
65
  self.write_header = options.get("write_header", True)
66
- self.quoting = {
67
- "all": csv.QUOTE_ALL,
68
- "minimal": csv.QUOTE_MINIMAL,
69
- "none": csv.QUOTE_NONE,
70
- "nonnumeric": csv.QUOTE_NONNUMERIC,
71
- }.get(options.get("quoting", "nonnumeric"))
72
66
 
73
67
  def _data_serializer(self, row):
74
- return {
75
- k: f'"{v}"'.strip() if isinstance(v, str) and any(d in v for d in [',', ';', '\t', '\n', '"']) else (
76
- v if v is not None and not isinstance(v, NotSetType) else "")
77
- for k, v in row.items()
78
- }
68
+ def process_value(v):
69
+ if v is None or isinstance(v, NotSetType):
70
+ return ""
71
+ # add quotes to values that contain special characters
72
+ if isinstance(v, str) and any(d in v for d in [',', ';', '\t', '\n', '"']):
73
+ return f'"{v}"'
74
+ return str(v)
75
+
76
+ return [process_value(v) for v in row.values()]
79
77
 
80
78
  def load(self, data: Iterable[Dict[str, Any]]):
81
- try:
82
- data = iter(data)
83
- first_row = next(data)
84
- except StopIteration:
85
- return
86
-
87
- with open(self.file_path, "w", newline="") as f:
88
- writer = csv.DictWriter(
89
- f,
90
- fieldnames=list(first_row.keys()),
91
- quoting=self.quoting
92
- )
93
-
94
- if self.write_header:
95
- writer.writeheader()
96
-
97
- writer.writerow(self._data_serializer(first_row))
98
- writer.writerows(map(self._data_serializer, data))
79
+ first_batch = True
80
+
81
+ with open(self.file_path, "a", newline="") as f:
82
+ for batch in data:
83
+ fieldnames = list(batch.keys())
84
+
85
+ rows = np.array([self._data_serializer(batch)])
86
+
87
+ if first_batch and self.write_header:
88
+ header = ','.join(fieldnames)
89
+ np.savetxt(f, [], fmt='%s', delimiter=',', header=header, comments='')
90
+ first_batch = False
91
+
92
+ np.savetxt(f, rows, fmt='%s', delimiter=',', comments='')
99
93
 
100
94
  def fetch_data(self, chunksize: int) -> Iterable[pd.DataFrame]:
101
95
  """
@@ -278,7 +278,7 @@ class BaseMapping:
278
278
  for transform in transform_list:
279
279
  transform.parse()
280
280
  if ((transform.transformation_tree is None or
281
- not self.has_missing_columns(transform.transformation_tree, missing_columns)) and
281
+ not self.has_missing_columns(transform.transformation_tree, missing_columns)) and
282
282
  (transform.when_tree is None or
283
283
  not self.has_missing_columns(transform.when_tree, missing_columns))):
284
284
  valid_transforms.append(transform)
@@ -413,8 +413,8 @@ class PandasRunner(BaseRunner):
413
413
  self, extractor: BaseConnector, mapping: BaseMapping
414
414
  ) -> Iterable[Dict[str, Any]]:
415
415
  """
416
- Transforms the data.
417
- It receives it in batches from the extractor, calculates which
416
+ Orchestrates the data transformation.
417
+ It receives the data in batches from the extractor, calculates which
418
418
  transformations can be applied to it, applies them, and yields the
419
419
  transformed rows.
420
420
 
@@ -422,28 +422,59 @@ class PandasRunner(BaseRunner):
422
422
  :param mapping: The mapping object defining transformations.
423
423
  :return: An iterable of dictionaries, each representing a transformed row.
424
424
  """
425
- validator = PandasValidator(search_paths=([os.path.dirname(self.config.path)] if self.config.path else []))
425
+ # Initial search paths
426
+ search_paths = [os.path.dirname(self.config.path)] if self.config.path else []
427
+
428
+ # Add search paths from the config, if provided
429
+ config_search_paths = self.config.get('mapping', {}).get('options', {}).get('search_paths', [])
430
+ if isinstance(config_search_paths, str):
431
+ config_search_paths = [config_search_paths]
432
+ search_paths.extend(config_search_paths)
433
+
434
+ # Instantiate the validator with the updated search paths
435
+ validator = PandasValidator(search_paths=search_paths)
426
436
  runner_config = self.config.config.get('runner', None)
427
437
  batch_size = runner_config.get('batch_size', 100000)
428
438
  total_rows = 0
429
439
  transformations = []
430
440
 
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}]")
438
-
439
- validator.run(self.coerce_row_types(batch, transformations[0].types),
440
- mapping.input_format.name, mapping.input_format.version, mapping.file_type)
441
-
442
- for transformation in transformations:
443
- batch = self.apply_transformation_set(batch, transformation)
444
-
445
- validator.run(batch, mapping.output_format.name, mapping.output_format.version, mapping.file_type)
446
- total_rows += len(batch)
447
- logger.info(f"Processed {len(batch)} rows in the current batch (total: {total_rows})")
448
-
449
- yield from (r.to_dict() for idx, r in batch.iterrows())
441
+ try:
442
+ for batch in extractor.fetch_data(batch_size):
443
+ # Calculates the set of transformations from the columns in the
444
+ # first batch (to avoid double-querying)
445
+ if not transformations:
446
+ available_columns = set(batch.columns)
447
+ transformations = mapping.get_transformations(available_columns=available_columns)
448
+ logger.info(
449
+ f"Running transformation set {transformations[0].input_format} -> {transformations[-1].output_format} [{extractor.name}]")
450
+
451
+ # Validate input data
452
+ try:
453
+ validator.run(self.coerce_row_types(batch, transformations[0].types),
454
+ mapping.input_format.name, mapping.input_format.version, mapping.file_type)
455
+ except KeyError as e:
456
+ logger.warning(f"Validation failed due to a missing column: {e}")
457
+ except Exception as e:
458
+ logger.warning(f"Validation failed: {e}")
459
+
460
+ # Apply the transformations to the batch
461
+ for transformation in transformations:
462
+ batch = self.apply_transformation_set(batch, transformation)
463
+
464
+ # Validate output data
465
+ try:
466
+ validator.run(batch, mapping.output_format.name, mapping.output_format.version, mapping.file_type)
467
+ except KeyError as e:
468
+ logger.warning(f"Validation failed due to a missing column: {e}")
469
+ except Exception as e:
470
+ logger.warning(f"Validation failed: {e}")
471
+
472
+ # Log the transformation progress
473
+ total_rows += len(batch)
474
+ logger.info(f"Processed {len(batch)} rows in the current batch (total: {total_rows})")
475
+
476
+ yield from (r.to_dict() for idx, r in batch.iterrows())
477
+ except FileNotFoundError:
478
+ logger.error(f"File not found: {extractor.file_path}")
479
+ except Exception as e:
480
+ logger.error(f"Error processing batch: {e}")
@@ -6,7 +6,7 @@ from operator import truediv as div
6
6
  from typing import Any, Callable, Iterable, List, Pattern, TypedDict, Union
7
7
 
8
8
  from lark import Transformer as _LarkTransformer
9
- from lark import Tree
9
+ from lark import Token, Tree
10
10
  from lark import exceptions as lark_exceptions
11
11
  from lark import v_args
12
12
  from ..transformers.transform_utils import replace_multiple
@@ -452,7 +452,9 @@ class BaseTreeTransformer(_LarkTransformer):
452
452
 
453
453
  :return: True if the value is "True", False otherwise
454
454
  """
455
- return value == "True"
455
+ if isinstance(value, bool):
456
+ return value
457
+ return str(value).lower() == "true"
456
458
 
457
459
  def null(self, value):
458
460
  """
@@ -479,6 +481,16 @@ class BaseTreeTransformer(_LarkTransformer):
479
481
  return float(value)
480
482
 
481
483
 
484
+ def safe_lookup(r, name):
485
+ if isinstance(name, Token):
486
+ name = name.value
487
+ if name == 'True':
488
+ return True
489
+ elif name == 'False':
490
+ return False
491
+ return r.get(name, name)
492
+
493
+
482
494
  def create_transformer_class(row, transformer_mapping):
483
495
  """
484
496
  Creates a transformer class from the provided mapping overrides.
@@ -489,7 +501,7 @@ def create_transformer_class(row, transformer_mapping):
489
501
  :return: The new transformer class
490
502
  """
491
503
  transformer_mapping = {
492
- "lookup": lambda r, name: r[name],
504
+ "lookup": safe_lookup,
493
505
  "add": lambda r, lhs, rhs: add(lhs, rhs),
494
506
  "subtract": lambda r, lhs, rhs: sub(lhs, rhs),
495
507
  "multiply": lambda r, lhs, rhs: mul(lhs, rhs),
@@ -283,8 +283,8 @@ class OedSource:
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
285
  oed_df.loc[is_empty(oed_df, column), column] = ''
286
- elif pd_dtype[column].startswith('Int'):
287
- to_tmp_dtype[column] = 'float'
286
+ if pd.api.types.is_numeric_dtype(pd_dtype[column]): # make sure empty string are converted to nan
287
+ oed_df[column] = pd.to_numeric(oed_df[column], errors='coerce')
288
288
 
289
289
  return oed_df.astype(to_tmp_dtype).astype(pd_dtype)
290
290
 
@@ -302,7 +302,7 @@ class OedSource:
302
302
  """
303
303
  # set default values
304
304
  for col, field_info in column_to_field.items():
305
- fill_empty(df, col, OedSchema.get_default_from_ods_fields(ods_fields, col))
305
+ fill_empty(df, col, OedSchema.get_default_from_ods_fields(ods_fields, field_info['Input Field Name']))
306
306
 
307
307
  # add required columns that allow blank values if missing
308
308
  present_field = set(field_info['Input Field Name'] for field_info in column_to_field.values())
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: ods-tools
3
- Version: 3.2.6
3
+ Version: 3.2.8
4
4
  Summary: Tools to manage ODS files
5
5
  Home-page: https://github.com/OasisLMF/OpenDataStandards
6
6
  Author: Oasis LMF
@@ -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.4.0'
15
+ OED_VERSION = '3.4.1'
16
16
  # ORD_VERSION =
17
17
 
18
18
 
File without changes
File without changes
File without changes