sibi-dst 0.3.40__tar.gz → 0.3.43__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 (65) hide show
  1. sibi_dst-0.3.43/PKG-INFO +194 -0
  2. sibi_dst-0.3.43/README.md +145 -0
  3. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/pyproject.toml +1 -1
  4. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/__init__.py +2 -0
  5. sibi_dst-0.3.43/sibi_dst/df_helper/_artifact_updater_multi_wrapper.py +262 -0
  6. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/_df_helper.py +5 -2
  7. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/_parquet_artifact.py +8 -2
  8. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/_parquet_reader.py +5 -1
  9. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/_db_connection.py +1 -0
  10. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/osmnx_helper/__init__.py +2 -2
  11. {sibi_dst-0.3.40/sibi_dst/osmnx_helper → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1}/basemaps/router_plotter.py +85 -30
  12. sibi_dst-0.3.43/sibi_dst/osmnx_helper/v2/__init__.py +0 -0
  13. sibi_dst-0.3.43/sibi_dst/osmnx_helper/v2/base_osm_map.py +153 -0
  14. sibi_dst-0.3.43/sibi_dst/osmnx_helper/v2/basemaps/__init__.py +0 -0
  15. sibi_dst-0.3.43/sibi_dst/osmnx_helper/v2/basemaps/utils.py +0 -0
  16. sibi_dst-0.3.43/sibi_dst/tests/__init__.py +0 -0
  17. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/__init__.py +3 -0
  18. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/data_utils.py +66 -25
  19. sibi_dst-0.3.43/sibi_dst/utils/data_wrapper.py +301 -0
  20. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/date_utils.py +118 -113
  21. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/df_utils.py +7 -0
  22. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/log_utils.py +57 -18
  23. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/parquet_saver.py +4 -2
  24. sibi_dst-0.3.43/sibi_dst/utils/phone_formatter.py +127 -0
  25. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/storage_manager.py +14 -7
  26. sibi_dst-0.3.40/PKG-INFO +0 -62
  27. sibi_dst-0.3.40/README.md +0 -13
  28. sibi_dst-0.3.40/sibi_dst/utils/data_wrapper.py +0 -364
  29. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/__init__.py +0 -0
  30. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/__init__.py +0 -0
  31. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/django/__init__.py +0 -0
  32. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/django/_db_connection.py +0 -0
  33. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/django/_io_dask.py +0 -0
  34. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/django/_load_from_db.py +0 -0
  35. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/django/_sql_model_builder.py +0 -0
  36. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/http/__init__.py +0 -0
  37. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/http/_http_config.py +0 -0
  38. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/parquet/__init__.py +0 -0
  39. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/parquet/_filter_handler.py +0 -0
  40. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/parquet/_parquet_options.py +0 -0
  41. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/__init__.py +0 -0
  42. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/_filter_handler.py +0 -0
  43. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/_io_dask.py +0 -0
  44. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/_load_from_db.py +0 -0
  45. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/backends/sqlalchemy/_sql_model_builder.py +0 -0
  46. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/core/__init__.py +0 -0
  47. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/core/_defaults.py +0 -0
  48. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/core/_filter_handler.py +0 -0
  49. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/core/_params_config.py +0 -0
  50. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/core/_query_config.py +0 -0
  51. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/df_helper/data_cleaner.py +0 -0
  52. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/geopy_helper/__init__.py +0 -0
  53. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/geopy_helper/geo_location_service.py +0 -0
  54. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/geopy_helper/utils.py +0 -0
  55. {sibi_dst-0.3.40/sibi_dst/osmnx_helper/basemaps → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1}/__init__.py +0 -0
  56. {sibi_dst-0.3.40/sibi_dst/osmnx_helper → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1}/base_osm_map.py +0 -0
  57. {sibi_dst-0.3.40/sibi_dst/tests → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1/basemaps}/__init__.py +0 -0
  58. {sibi_dst-0.3.40/sibi_dst/osmnx_helper → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1}/basemaps/calendar_html.py +0 -0
  59. {sibi_dst-0.3.40/sibi_dst/osmnx_helper → sibi_dst-0.3.43/sibi_dst/osmnx_helper/v1}/utils.py +0 -0
  60. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/tests/test_data_wrapper_class.py +0 -0
  61. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/airflow_manager.py +0 -0
  62. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/clickhouse_writer.py +0 -0
  63. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/credentials.py +0 -0
  64. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/file_utils.py +0 -0
  65. {sibi_dst-0.3.40 → sibi_dst-0.3.43}/sibi_dst/utils/filepath_generator.py +0 -0
@@ -0,0 +1,194 @@
1
+ Metadata-Version: 2.1
2
+ Name: sibi-dst
3
+ Version: 0.3.43
4
+ Summary: Data Science Toolkit
5
+ Author: Luis Valverde
6
+ Author-email: lvalverdeb@gmail.com
7
+ Requires-Python: >=3.11,<4.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Requires-Dist: apache-airflow-client (>=2.10.0,<3.0.0)
13
+ Requires-Dist: chardet (>=5.2.0,<6.0.0)
14
+ Requires-Dist: charset-normalizer (>=3.4.0,<4.0.0)
15
+ Requires-Dist: clickhouse-connect (>=0.8.7,<0.9.0)
16
+ Requires-Dist: clickhouse-driver (>=0.2.9,<0.3.0)
17
+ Requires-Dist: dask-expr (>=1.1.20,<2.0.0)
18
+ Requires-Dist: dask[complete] (>=2024.11.1,<2025.0.0)
19
+ Requires-Dist: django (>=5.1.4,<6.0.0)
20
+ Requires-Dist: djangorestframework (>=3.15.2,<4.0.0)
21
+ Requires-Dist: folium (>=0.19.4,<0.20.0)
22
+ Requires-Dist: geopandas (>=1.0.1,<2.0.0)
23
+ Requires-Dist: gunicorn (>=23.0.0,<24.0.0)
24
+ Requires-Dist: httpx (>=0.27.2,<0.28.0)
25
+ Requires-Dist: ipython (>=8.29.0,<9.0.0)
26
+ Requires-Dist: jinja2 (>=3.1.4,<4.0.0)
27
+ Requires-Dist: mysqlclient (>=2.2.6,<3.0.0)
28
+ Requires-Dist: nltk (>=3.9.1,<4.0.0)
29
+ Requires-Dist: openpyxl (>=3.1.5,<4.0.0)
30
+ Requires-Dist: osmnx (>=2.0.1,<3.0.0)
31
+ Requires-Dist: pandas (>=2.2.3,<3.0.0)
32
+ Requires-Dist: paramiko (>=3.5.0,<4.0.0)
33
+ Requires-Dist: psutil (>=6.1.0,<7.0.0)
34
+ Requires-Dist: psycopg2 (>=2.9.10,<3.0.0)
35
+ Requires-Dist: pyarrow (>=18.0.0,<19.0.0)
36
+ Requires-Dist: pydantic (>=2.9.2,<3.0.0)
37
+ Requires-Dist: pymysql (>=1.1.1,<2.0.0)
38
+ Requires-Dist: pytest (>=8.3.3,<9.0.0)
39
+ Requires-Dist: pytest-mock (>=3.14.0,<4.0.0)
40
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
41
+ Requires-Dist: s3fs (>=2024.12.0,<2025.0.0)
42
+ Requires-Dist: sqlalchemy (>=2.0.36,<3.0.0)
43
+ Requires-Dist: tornado (>=6.4.1,<7.0.0)
44
+ Requires-Dist: tqdm (>=4.67.0,<5.0.0)
45
+ Requires-Dist: uvicorn (>=0.34.0,<0.35.0)
46
+ Requires-Dist: uvicorn-worker (>=0.3.0,<0.4.0)
47
+ Description-Content-Type: text/markdown
48
+
49
+ # sibi-dst
50
+
51
+ Data Science Toolkit
52
+ ---------------------
53
+ Data Science Toolkit built with Python, Pandas, Dask, OpenStreetMaps, Scikit-Learn, XGBOOST, Django ORM, SQLAlchemy, DjangoRestFramework, FastAPI
54
+
55
+ Major Functionality
56
+ --------------------
57
+ 1) **Build DataCubes, DataSets, and DataObjects** from diverse data sources, including **relational databases, Parquet files, Excel (`.xlsx`), delimited tables (`.csv`, `.tsv`), JSON, and RESTful APIs (`JSON API REST`)**.
58
+ 2) **Comprehensive DataFrame Management** utilities for efficient data handling, transformation, and optimization using **Pandas** and **Dask**.
59
+ 3) **Flexible Data Sharing** with client applications by writing to **Data Warehouses, local filesystems, and cloud storage platforms** such as **Amazon S3, Google Cloud Storage (GCS), and Azure Blob Storage**.
60
+ 4) **Microservices for Data Access** – Build scalable **API-driven services** using **RESTful APIs (`Django REST Framework`, `FastAPI`) and gRPC** for high-performance data exchange.
61
+
62
+ Supported Technologies
63
+ --------------------
64
+ - **Data Processing**: Pandas, Dask
65
+ - **Machine Learning**: Scikit-Learn, XGBoost
66
+ - **Databases & Storage**: SQLAlchemy, Django ORM, Parquet, Amazon S3, GCS, Azure Blob Storage
67
+ - **Mapping & Geospatial Analysis**: OpenStreetMaps, OSMnx, Geopy
68
+ - **API Development**: Django REST Framework, gRPC
69
+
70
+ Installation
71
+ ---------------------
72
+ ```bash
73
+ pip install sibi-dst
74
+ ```
75
+
76
+ Usage
77
+ ---------------------
78
+ ### Loading Data from SQLAlchemy
79
+ ```python
80
+ from sibi_dst.df_helper import DfHelper
81
+ from conf.transforms.fields.crm import customer_fields
82
+ from conf.credentials import replica_db_conf
83
+ from conf.storage import get_fs_instance
84
+
85
+ config = {
86
+ 'backend': 'sqlalchemy',
87
+ 'connection_url': replica_db_conf.get('db_url'),
88
+ 'table': 'crm_clientes_archivo',
89
+ 'field_map': customer_fields,
90
+ 'legacy_filters': True,
91
+ 'fs': get_fs_instance()
92
+ }
93
+
94
+ df_helper = DfHelper(**config)
95
+ result = df_helper.load(id__gte=1)
96
+ ```
97
+
98
+ ### Saving Data to ClickHouse
99
+ ```python
100
+ clk_creds = {
101
+ 'host': '192.168.3.171',
102
+ 'port': 18123,
103
+ 'user': 'username',
104
+ 'database': 'xxxxxxx',
105
+ 'table': 'customer_file',
106
+ 'order_by': 'id'
107
+ }
108
+
109
+ df_helper.save_to_clickhouse(**clk_creds)
110
+ ```
111
+
112
+ ### Saving Data to Parquet
113
+ ```python
114
+ df_helper.save_to_parquet(
115
+ parquet_filename='filename.parquet',
116
+ parquet_storage_path='/path/to/my/files/'
117
+ )
118
+ ```
119
+
120
+ Backends Supported
121
+ ---------------------
122
+ | Backend | Description |
123
+ |--------------|-------------|
124
+ | `sqlalchemy` | Load data from SQL databases using SQLAlchemy. |
125
+ | `django_db` | Load data from Django ORM models. |
126
+ | `parquet` | Load and save data from Parquet files. |
127
+ | `http` | Fetch data from HTTP endpoints. |
128
+ | `osmnx` | Geospatial mapping and routing using OpenStreetMap. |
129
+ | `geopy` | Geolocation services for address lookup and reverse geocoding. |
130
+
131
+ Geospatial Utilities
132
+ ---------------------
133
+ ### **OSMnx Helper (`sibi_dst.osmnx_helper`)
134
+ **
135
+ Provides **OpenStreetMap-based mapping utilities** using `osmnx` and `folium`.
136
+
137
+ #### 🔹 Key Features
138
+ - **BaseOsmMap**: Manages interactive Folium-based maps.
139
+ - **PBFHandler**: Loads `.pbf` (Protocolbuffer Binary Format) files for network graphs.
140
+
141
+ #### Example: Generating an OSM Map
142
+ ```python
143
+ from sibi_dst.osmnx_helper import BaseOsmMap
144
+ osm_map = BaseOsmMap(osmnx_graph=my_graph, df=my_dataframe)
145
+ osm_map.generate_map()
146
+ ```
147
+
148
+ ### **Geopy Helper (`sibi_dst.geopy_helper`)
149
+ **
150
+ Provides **geolocation services** using `Geopy` for forward and reverse geocoding.
151
+
152
+ #### 🔹 Key Features
153
+ - **GeolocationService**: Interfaces with `Nominatim` API for geocoding.
154
+ - **Error Handling**: Manages `GeocoderTimedOut` and `GeocoderServiceError` gracefully.
155
+ - **Singleton Geolocator**: Efficiently reuses a global geolocator instance.
156
+
157
+ #### Example: Reverse Geocoding
158
+ ```python
159
+ from sibi_dst.geopy_helper import GeolocationService
160
+ gs = GeolocationService()
161
+ location = gs.reverse_geocode(lat=9.935, lon=-84.091)
162
+ print(location)
163
+ ```
164
+
165
+ Advanced Features
166
+ ---------------------
167
+ ### Querying with Custom Filters
168
+ Filters can be applied dynamically using Django-style syntax:
169
+ ```python
170
+ result = df_helper.load(date__gte='2023-01-01', status='active')
171
+ ```
172
+
173
+ ### Parallel Processing
174
+ Leverage Dask for parallel execution:
175
+ ```python
176
+ results = df_helper.load_parallel(status='active')
177
+ ```
178
+
179
+ Testing
180
+ ---------------------
181
+ To run unit tests, use:
182
+ ```bash
183
+ pytest tests/
184
+ ```
185
+
186
+ Contributing
187
+ ---------------------
188
+ Contributions are welcome! Please submit pull requests or open issues for discussions.
189
+
190
+ License
191
+ ---------------------
192
+ sibi-dst is licensed under the MIT License.
193
+
194
+
@@ -0,0 +1,145 @@
1
+ # sibi-dst
2
+
3
+ Data Science Toolkit
4
+ ---------------------
5
+ Data Science Toolkit built with Python, Pandas, Dask, OpenStreetMaps, Scikit-Learn, XGBOOST, Django ORM, SQLAlchemy, DjangoRestFramework, FastAPI
6
+
7
+ Major Functionality
8
+ --------------------
9
+ 1) **Build DataCubes, DataSets, and DataObjects** from diverse data sources, including **relational databases, Parquet files, Excel (`.xlsx`), delimited tables (`.csv`, `.tsv`), JSON, and RESTful APIs (`JSON API REST`)**.
10
+ 2) **Comprehensive DataFrame Management** utilities for efficient data handling, transformation, and optimization using **Pandas** and **Dask**.
11
+ 3) **Flexible Data Sharing** with client applications by writing to **Data Warehouses, local filesystems, and cloud storage platforms** such as **Amazon S3, Google Cloud Storage (GCS), and Azure Blob Storage**.
12
+ 4) **Microservices for Data Access** – Build scalable **API-driven services** using **RESTful APIs (`Django REST Framework`, `FastAPI`) and gRPC** for high-performance data exchange.
13
+
14
+ Supported Technologies
15
+ --------------------
16
+ - **Data Processing**: Pandas, Dask
17
+ - **Machine Learning**: Scikit-Learn, XGBoost
18
+ - **Databases & Storage**: SQLAlchemy, Django ORM, Parquet, Amazon S3, GCS, Azure Blob Storage
19
+ - **Mapping & Geospatial Analysis**: OpenStreetMaps, OSMnx, Geopy
20
+ - **API Development**: Django REST Framework, gRPC
21
+
22
+ Installation
23
+ ---------------------
24
+ ```bash
25
+ pip install sibi-dst
26
+ ```
27
+
28
+ Usage
29
+ ---------------------
30
+ ### Loading Data from SQLAlchemy
31
+ ```python
32
+ from sibi_dst.df_helper import DfHelper
33
+ from conf.transforms.fields.crm import customer_fields
34
+ from conf.credentials import replica_db_conf
35
+ from conf.storage import get_fs_instance
36
+
37
+ config = {
38
+ 'backend': 'sqlalchemy',
39
+ 'connection_url': replica_db_conf.get('db_url'),
40
+ 'table': 'crm_clientes_archivo',
41
+ 'field_map': customer_fields,
42
+ 'legacy_filters': True,
43
+ 'fs': get_fs_instance()
44
+ }
45
+
46
+ df_helper = DfHelper(**config)
47
+ result = df_helper.load(id__gte=1)
48
+ ```
49
+
50
+ ### Saving Data to ClickHouse
51
+ ```python
52
+ clk_creds = {
53
+ 'host': '192.168.3.171',
54
+ 'port': 18123,
55
+ 'user': 'username',
56
+ 'database': 'xxxxxxx',
57
+ 'table': 'customer_file',
58
+ 'order_by': 'id'
59
+ }
60
+
61
+ df_helper.save_to_clickhouse(**clk_creds)
62
+ ```
63
+
64
+ ### Saving Data to Parquet
65
+ ```python
66
+ df_helper.save_to_parquet(
67
+ parquet_filename='filename.parquet',
68
+ parquet_storage_path='/path/to/my/files/'
69
+ )
70
+ ```
71
+
72
+ Backends Supported
73
+ ---------------------
74
+ | Backend | Description |
75
+ |--------------|-------------|
76
+ | `sqlalchemy` | Load data from SQL databases using SQLAlchemy. |
77
+ | `django_db` | Load data from Django ORM models. |
78
+ | `parquet` | Load and save data from Parquet files. |
79
+ | `http` | Fetch data from HTTP endpoints. |
80
+ | `osmnx` | Geospatial mapping and routing using OpenStreetMap. |
81
+ | `geopy` | Geolocation services for address lookup and reverse geocoding. |
82
+
83
+ Geospatial Utilities
84
+ ---------------------
85
+ ### **OSMnx Helper (`sibi_dst.osmnx_helper`)
86
+ **
87
+ Provides **OpenStreetMap-based mapping utilities** using `osmnx` and `folium`.
88
+
89
+ #### 🔹 Key Features
90
+ - **BaseOsmMap**: Manages interactive Folium-based maps.
91
+ - **PBFHandler**: Loads `.pbf` (Protocolbuffer Binary Format) files for network graphs.
92
+
93
+ #### Example: Generating an OSM Map
94
+ ```python
95
+ from sibi_dst.osmnx_helper import BaseOsmMap
96
+ osm_map = BaseOsmMap(osmnx_graph=my_graph, df=my_dataframe)
97
+ osm_map.generate_map()
98
+ ```
99
+
100
+ ### **Geopy Helper (`sibi_dst.geopy_helper`)
101
+ **
102
+ Provides **geolocation services** using `Geopy` for forward and reverse geocoding.
103
+
104
+ #### 🔹 Key Features
105
+ - **GeolocationService**: Interfaces with `Nominatim` API for geocoding.
106
+ - **Error Handling**: Manages `GeocoderTimedOut` and `GeocoderServiceError` gracefully.
107
+ - **Singleton Geolocator**: Efficiently reuses a global geolocator instance.
108
+
109
+ #### Example: Reverse Geocoding
110
+ ```python
111
+ from sibi_dst.geopy_helper import GeolocationService
112
+ gs = GeolocationService()
113
+ location = gs.reverse_geocode(lat=9.935, lon=-84.091)
114
+ print(location)
115
+ ```
116
+
117
+ Advanced Features
118
+ ---------------------
119
+ ### Querying with Custom Filters
120
+ Filters can be applied dynamically using Django-style syntax:
121
+ ```python
122
+ result = df_helper.load(date__gte='2023-01-01', status='active')
123
+ ```
124
+
125
+ ### Parallel Processing
126
+ Leverage Dask for parallel execution:
127
+ ```python
128
+ results = df_helper.load_parallel(status='active')
129
+ ```
130
+
131
+ Testing
132
+ ---------------------
133
+ To run unit tests, use:
134
+ ```bash
135
+ pytest tests/
136
+ ```
137
+
138
+ Contributing
139
+ ---------------------
140
+ Contributions are welcome! Please submit pull requests or open issues for discussions.
141
+
142
+ License
143
+ ---------------------
144
+ sibi-dst is licensed under the MIT License.
145
+
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "sibi-dst"
3
- version = "0.3.40"
3
+ version = "0.3.43"
4
4
  description = "Data Science Toolkit"
5
5
  authors = ["Luis Valverde <lvalverdeb@gmail.com>"]
6
6
  readme = "README.md"
@@ -3,11 +3,13 @@ from __future__ import annotations
3
3
  from ._df_helper import DfHelper
4
4
  from ._parquet_artifact import ParquetArtifact
5
5
  from ._parquet_reader import ParquetReader
6
+ from ._artifact_updater_multi_wrapper import ArtifactUpdaterMultiWrapper
6
7
  #from .data_cleaner import DataCleaner
7
8
 
8
9
  __all__ = [
9
10
  'DfHelper',
10
11
  'ParquetArtifact',
11
12
  'ParquetReader',
13
+ 'ArtifactUpdaterMultiWrapper',
12
14
  #'DataCleaner'
13
15
  ]
@@ -0,0 +1,262 @@
1
+ import asyncio
2
+ import logging
3
+ import datetime
4
+ import psutil
5
+ import time
6
+ from functools import total_ordering
7
+ from collections import defaultdict
8
+ from contextlib import asynccontextmanager
9
+ import signal
10
+ from sibi_dst.utils import Logger
11
+
12
+ @total_ordering
13
+ class PrioritizedItem:
14
+ def __init__(self, priority, artifact):
15
+ self.priority = priority
16
+ self.artifact = artifact
17
+
18
+ def __lt__(self, other):
19
+ return self.priority < other.priority
20
+
21
+ def __eq__(self, other):
22
+ return self.priority == other.priority
23
+
24
+ class ArtifactUpdaterMultiWrapper:
25
+ def __init__(self, wrapped_classes=None, debug=False, **kwargs):
26
+ self.wrapped_classes = wrapped_classes or {}
27
+ self.debug = debug
28
+ self.logger = kwargs.setdefault('logger',Logger.default_logger(logger_name=self.__class__.__name__))
29
+ self.logger.set_level(logging.DEBUG if debug else logging.INFO)
30
+
31
+ today = datetime.datetime.today()
32
+ self.today_str = today.strftime('%Y-%m-%d')
33
+ self.current_year_starts_on_str = datetime.date(today.year, 1, 1).strftime('%Y-%m-%d')
34
+ self.parquet_start_date = kwargs.get('parquet_start_date', self.current_year_starts_on_str)
35
+ self.parquet_end_date = kwargs.get('parquet_end_date', self.today_str)
36
+
37
+ # track concurrency and locks
38
+ self.locks = {}
39
+ self.worker_heartbeat = defaultdict(float)
40
+
41
+ # graceful shutdown handling
42
+ loop = asyncio.get_event_loop()
43
+ self.register_signal_handlers(loop)
44
+
45
+ # dynamic scaling config
46
+ self.min_workers = kwargs.get('min_workers', 1)
47
+ self.max_workers = kwargs.get('max_workers', 8)
48
+ self.memory_per_worker_gb = kwargs.get('memory_per_worker_gb', 1) # default 2GB per worker
49
+ self.monitor_interval = kwargs.get('monitor_interval', 10) # default monitor interval in seconds
50
+ self.retry_attempts = kwargs.get('retry_attempts', 3)
51
+ self.update_timeout_seconds = kwargs.get('update_timeout_seconds', 600)
52
+ self.lock_acquire_timeout_seconds = kwargs.get('lock_acquire_timeout_seconds', 10)
53
+
54
+ def register_signal_handlers(self, loop):
55
+ for sig in (signal.SIGINT, signal.SIGTERM):
56
+ loop.add_signal_handler(sig, lambda: asyncio.create_task(self.shutdown()))
57
+
58
+ async def shutdown(self):
59
+ self.logger.info("Shutdown signal received. Cleaning up...")
60
+ tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
61
+ [task.cancel() for task in tasks]
62
+ await asyncio.gather(*tasks, return_exceptions=True)
63
+ self.logger.info("Shutdown complete.")
64
+
65
+ def get_lock_for_artifact(self, artifact):
66
+ artifact_key = artifact.__class__.__name__
67
+ if artifact_key not in self.locks:
68
+ self.locks[artifact_key] = asyncio.Lock()
69
+ return self.locks[artifact_key]
70
+
71
+ def get_artifacts(self, data_type):
72
+ if data_type not in self.wrapped_classes:
73
+ raise ValueError(f"Unsupported data type: {data_type}")
74
+
75
+ return [
76
+ artifact_class(
77
+ parquet_start_date=self.parquet_start_date,
78
+ parquet_end_date=self.parquet_end_date,
79
+ logger=self.logger,
80
+ debug=self.debug
81
+ )
82
+ for artifact_class in self.wrapped_classes[data_type]
83
+ ]
84
+
85
+ def estimate_complexity(self, artifact):
86
+ try:
87
+ if hasattr(artifact, 'get_size_estimate'):
88
+ return artifact.get_size_estimate()
89
+ except Exception as e:
90
+ self.logger.warning(f"Failed to estimate complexity for {artifact}: {e}")
91
+ return 1 # default
92
+
93
+ def prioritize_tasks(self, artifacts):
94
+ queue = asyncio.PriorityQueue()
95
+ for artifact in artifacts:
96
+ complexity = self.estimate_complexity(artifact)
97
+ # we invert the complexity to ensure higher complexity -> higher priority
98
+ # if you want high complexity first, store negative complexity in the priority queue
99
+ # or if the smaller number means earlier processing, just keep as is
100
+ queue.put_nowait(PrioritizedItem(complexity, artifact))
101
+ return queue
102
+
103
+ async def resource_monitor(self, queue, workers):
104
+ """Monitor system resources and adjust worker count while queue is not empty."""
105
+ while True:
106
+ # break if queue done
107
+ if queue.empty():
108
+ await asyncio.sleep(0.5)
109
+ if queue.empty():
110
+ break
111
+
112
+ try:
113
+ available_memory = psutil.virtual_memory().available
114
+ worker_memory_bytes = self.memory_per_worker_gb * (1024 ** 3)
115
+ max_workers_by_memory = available_memory // worker_memory_bytes
116
+
117
+ # figure out how many workers we can sustain
118
+ # note: we also cap by self.max_workers
119
+ optimal_workers = min(psutil.cpu_count(), max_workers_by_memory, self.max_workers)
120
+
121
+ # ensure at least self.min_workers is used
122
+ optimal_workers = max(self.min_workers, optimal_workers)
123
+
124
+ current_worker_count = len(workers)
125
+
126
+ if optimal_workers > current_worker_count:
127
+ # we can add more workers if queue is not empty
128
+ diff = optimal_workers - current_worker_count
129
+ for _ in range(diff):
130
+ worker_id = len(workers)
131
+ # create a new worker
132
+ w = asyncio.create_task(self.worker(queue, worker_id))
133
+ workers.append(w)
134
+ self.logger.info(f"Added worker {worker_id}. Total workers: {len(workers)}")
135
+ elif optimal_workers < current_worker_count:
136
+ # remove some workers
137
+ diff = current_worker_count - optimal_workers
138
+ for _ in range(diff):
139
+ w = workers.pop()
140
+ w.cancel()
141
+ self.logger.info(f"Removed a worker. Total workers: {len(workers)}")
142
+
143
+ await asyncio.sleep(self.monitor_interval)
144
+
145
+ except asyncio.CancelledError:
146
+ # monitor is being shut down
147
+ break
148
+ except Exception as e:
149
+ self.logger.error(f"Error in resource_monitor: {e}")
150
+ await asyncio.sleep(self.monitor_interval)
151
+
152
+ @asynccontextmanager
153
+ async def artifact_lock(self, artifact):
154
+ lock = self.get_lock_for_artifact(artifact)
155
+ try:
156
+ await asyncio.wait_for(lock.acquire(), timeout=self.lock_acquire_timeout_seconds)
157
+ yield
158
+ except asyncio.TimeoutError:
159
+ self.logger.error(f"Timeout acquiring lock for artifact: {artifact.__class__.__name__}")
160
+ yield # continue but no actual lock was acquired
161
+ finally:
162
+ if lock.locked():
163
+ lock.release()
164
+
165
+ async def async_update_artifact(self, artifact, **kwargs):
166
+ for attempt in range(self.retry_attempts):
167
+ try:
168
+ async with self.artifact_lock(artifact):
169
+ self.logger.info(
170
+ f"Updating artifact: {artifact.__class__.__name__}, Attempt: {attempt + 1} of {self.retry_attempts}" )
171
+ start_time = time.time()
172
+ await asyncio.wait_for(
173
+ asyncio.to_thread(artifact.update_parquet, **kwargs),
174
+ timeout=self.update_timeout_seconds
175
+ )
176
+ elapsed_time = time.time() - start_time
177
+ self.logger.info(
178
+ f"Successfully updated artifact: {artifact.__class__.__name__} in {elapsed_time:.2f}s." )
179
+ return
180
+
181
+ except asyncio.TimeoutError:
182
+ self.logger.error(f"Timeout updating artifact {artifact.__class__.__name__}, Attempt: {attempt + 1}")
183
+ except Exception as e:
184
+ self.logger.error(
185
+ f"Error updating artifact {artifact.__class__.__name__}, Attempt: {attempt + 1}: {e}" )
186
+
187
+ # exponential backoff
188
+ await asyncio.sleep(2 ** attempt)
189
+
190
+ self.logger.error(f"All retry attempts failed for artifact: {artifact.__class__.__name__}")
191
+
192
+ async def worker(self, queue, worker_id, **kwargs):
193
+ """A worker that dynamically pulls tasks from the queue."""
194
+ while True:
195
+ try:
196
+ prioritized_item = await queue.get()
197
+ if prioritized_item is None:
198
+ break
199
+ artifact = prioritized_item.artifact
200
+ # heartbeat
201
+ self.worker_heartbeat[worker_id] = time.time()
202
+
203
+ await self.async_update_artifact(artifact, **kwargs)
204
+
205
+ except asyncio.CancelledError:
206
+ self.logger.info(f"Worker {worker_id} shutting down gracefully.")
207
+ break
208
+ except Exception as e:
209
+ self.logger.error(f"Error in worker {worker_id}: {e}")
210
+ finally:
211
+ queue.task_done()
212
+
213
+ async def process_tasks(self, queue, initial_workers, **kwargs):
214
+ """Start a set of workers and a resource monitor to dynamically adjust them."""
215
+ # create initial workers
216
+ workers = []
217
+ for worker_id in range(initial_workers):
218
+ w = asyncio.create_task(self.worker(queue, worker_id, **kwargs))
219
+ workers.append(w)
220
+
221
+ # start resource monitor
222
+ monitor_task = asyncio.create_task(self.resource_monitor(queue, workers))
223
+
224
+ # wait until queue is done
225
+ try:
226
+ await queue.join()
227
+ finally:
228
+ # cancel resource monitor
229
+ monitor_task.cancel()
230
+ # all workers done
231
+ for w in workers:
232
+ w.cancel()
233
+ await asyncio.gather(*workers, return_exceptions=True)
234
+
235
+ async def update_data(self, data_type, **kwargs):
236
+ self.logger.info(f"Processing wrapper group: {data_type} with {kwargs}")
237
+ artifacts = self.get_artifacts(data_type)
238
+ queue = self.prioritize_tasks(artifacts)
239
+
240
+ # compute initial worker count (this can be low if memory is low initially)
241
+ initial_workers = self.calculate_initial_workers(len(artifacts))
242
+ self.logger.info(f"Initial worker count: {initial_workers} for {len(artifacts)} artifacts")
243
+
244
+ total_start_time = time.time()
245
+ await self.process_tasks(queue, initial_workers, **kwargs)
246
+ total_time = time.time() - total_start_time
247
+ self.logger.info(f"Total processing time: {total_time:.2f} seconds.")
248
+
249
+ def calculate_initial_workers(self, artifact_count: int) -> int:
250
+ """Compute the initial number of workers before resource_monitor can adjust."""
251
+ self.logger.info("Calculating initial worker count...")
252
+ available_memory = psutil.virtual_memory().available
253
+ self.logger.info(f"Available memory: {available_memory / (1024 ** 3):.2f} GB")
254
+ worker_memory_bytes = self.memory_per_worker_gb * (1024 ** 3)
255
+ self.logger.info(f"Memory per worker: {worker_memory_bytes / (1024 ** 3):.2f} GB")
256
+ max_workers_by_memory = available_memory // worker_memory_bytes
257
+ self.logger.info(f"Max workers by memory: {max_workers_by_memory}")
258
+ # also consider CPU count and artifact_count
259
+ initial = min(psutil.cpu_count(), max_workers_by_memory, artifact_count, self.max_workers)
260
+ self.logger.info(f"Optimal workers: {initial} CPU: {psutil.cpu_count()} Max Workers: {self.max_workers}")
261
+ return max(self.min_workers, initial)
262
+
@@ -112,6 +112,7 @@ class DfHelper:
112
112
  :return: None
113
113
  """
114
114
  self.logger.debug(f"backend used: {self.backend}")
115
+ self.logger.debug(f"kwargs passed to backend plugins: {kwargs}")
115
116
  self._backend_query = self.__get_config(QueryConfig, kwargs)
116
117
  self._backend_params = self.__get_config(ParamsConfig, kwargs)
117
118
  if self.backend == 'django_db':
@@ -124,8 +125,8 @@ class DfHelper:
124
125
  elif self.backend == 'sqlalchemy':
125
126
  self.backend_sqlalchemy = self.__get_config(SqlAlchemyConnectionConfig, kwargs)
126
127
 
127
- @staticmethod
128
- def __get_config(model: [T], kwargs: Dict[str, Any]) -> Union[T]:
128
+
129
+ def __get_config(self, model: [T], kwargs: Dict[str, Any]) -> Union[T]:
129
130
  """
130
131
  Initializes a Pydantic model with the keys it recognizes from the kwargs,
131
132
  and removes those keys from the kwargs dictionary.
@@ -135,7 +136,9 @@ class DfHelper:
135
136
  """
136
137
  # Extract keys that the model can accept
137
138
  recognized_keys = set(model.__annotations__.keys())
139
+ self.logger.debug(f"recognized keys: {recognized_keys}")
138
140
  model_kwargs = {k: kwargs.pop(k) for k in list(kwargs.keys()) if k in recognized_keys}
141
+ self.logger.debug(f"model_kwargs: {model_kwargs}")
139
142
  return model(**model_kwargs)
140
143
 
141
144
  def load_parallel(self, **options):
@@ -1,11 +1,11 @@
1
+ import logging
1
2
  from typing import Optional, Any, Dict
2
3
 
3
4
  import dask.dataframe as dd
4
5
  import fsspec
5
6
 
6
7
  from sibi_dst.df_helper import DfHelper
7
- from sibi_dst.utils import DataWrapper
8
- from sibi_dst.utils import DateUtils
8
+ from sibi_dst.utils import DataWrapper, DateUtils, Logger
9
9
 
10
10
 
11
11
  class ParquetArtifact(DfHelper):
@@ -82,7 +82,12 @@ class ParquetArtifact(DfHelper):
82
82
  **kwargs,
83
83
  }
84
84
  self.df: Optional[dd.DataFrame] = None
85
+ self.debug = self.config.setdefault('debug', False)
86
+ self.logger = self.config.setdefault('logger',Logger.default_logger(logger_name=f'parquet_artifact_{__class__.__name__}'))
87
+ self.logger.set_level(logging.DEBUG if self.debug else logging.INFO)
85
88
  self.data_wrapper_class = data_wrapper_class
89
+ self.class_params = self.config.setdefault('class_params', None)
90
+ self.load_params = self.config.setdefault('load_params', None)
86
91
  self.date_field = self.config.setdefault('date_field', None)
87
92
  if self.date_field is None:
88
93
  raise ValueError('date_field must be set')
@@ -150,6 +155,7 @@ class ParquetArtifact(DfHelper):
150
155
 
151
156
  def _prepare_params(self, kwargs: Dict[str, Any]) -> Dict[str, Any]:
152
157
  """Prepare the parameters for generating the Parquet file."""
158
+ kwargs = {**self.config, **kwargs}
153
159
  return {
154
160
  'class_params': kwargs.pop('class_params', None),
155
161
  'date_field': kwargs.pop('date_field', self.date_field),