quick-pp 0.2.2__tar.gz → 0.2.3__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 (104) hide show
  1. quick_pp-0.2.3/.gitignore +119 -0
  2. {quick_pp-0.2.2 → quick_pp-0.2.3}/LICENSE +1 -1
  3. quick_pp-0.2.3/PKG-INFO +103 -0
  4. quick_pp-0.2.3/README.md +68 -0
  5. quick_pp-0.2.3/pyproject.toml +59 -0
  6. quick_pp-0.2.3/quick_pp/api/exceptions.py +61 -0
  7. quick_pp-0.2.3/quick_pp/api/fastapi_mlflow/__init__.py +1 -0
  8. quick_pp-0.2.3/quick_pp/api/fastapi_mlflow/_mlflow_types.py +59 -0
  9. quick_pp-0.2.3/quick_pp/api/fastapi_mlflow/applications.py +72 -0
  10. quick_pp-0.2.3/quick_pp/api/fastapi_mlflow/exceptions.py +22 -0
  11. quick_pp-0.2.3/quick_pp/api/fastapi_mlflow/predictors.py +96 -0
  12. quick_pp-0.2.3/quick_pp/api/main.py +90 -0
  13. quick_pp-0.2.3/quick_pp/api/mlflow_model_deployment.py +99 -0
  14. quick_pp-0.2.3/quick_pp/api/qpp_assistant.py +160 -0
  15. quick_pp-0.2.3/quick_pp/api/router.py +18 -0
  16. quick_pp-0.2.3/quick_pp/api/schemas/lithology_hc_correction.py +39 -0
  17. quick_pp-0.2.3/quick_pp/api/schemas/lithology_ssc.py +37 -0
  18. quick_pp-0.2.3/quick_pp/api/schemas/lithology_vsh_gr.py +25 -0
  19. quick_pp-0.2.3/quick_pp/api/schemas/permeability_choo.py +25 -0
  20. quick_pp-0.2.3/quick_pp/api/schemas/permeability_others.py +24 -0
  21. quick_pp-0.2.3/quick_pp/api/schemas/porosity.py +22 -0
  22. quick_pp-0.2.3/quick_pp/api/schemas/ressum.py +29 -0
  23. quick_pp-0.2.3/quick_pp/api/schemas/saturation_archie.py +25 -0
  24. quick_pp-0.2.3/quick_pp/api/schemas/saturation_b.py +24 -0
  25. quick_pp-0.2.3/quick_pp/api/schemas/saturation_qv.py +26 -0
  26. quick_pp-0.2.3/quick_pp/api/schemas/saturation_rw.py +24 -0
  27. quick_pp-0.2.3/quick_pp/api/schemas/saturation_temp_grad.py +24 -0
  28. quick_pp-0.2.3/quick_pp/api/schemas/saturation_waxman_smits.py +28 -0
  29. quick_pp-0.2.3/quick_pp/api/services/las_handler.py +136 -0
  30. quick_pp-0.2.3/quick_pp/api/services/lithology.py +278 -0
  31. quick_pp-0.2.3/quick_pp/api/services/permeability.py +252 -0
  32. quick_pp-0.2.3/quick_pp/api/services/porosity.py +151 -0
  33. quick_pp-0.2.3/quick_pp/api/services/reservoir_summary.py +78 -0
  34. quick_pp-0.2.3/quick_pp/api/services/saturation.py +359 -0
  35. quick_pp-0.2.3/quick_pp/api/static/favicon.ico +0 -0
  36. quick_pp-0.2.3/quick_pp/api/static/logo.png +0 -0
  37. quick_pp-0.2.3/quick_pp/cli.py +118 -0
  38. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/config.py +14 -25
  39. quick_pp-0.2.3/quick_pp/logger.py +19 -0
  40. quick_pp-0.2.3/quick_pp/modelling/__init__.py +0 -0
  41. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/modelling/config.py +8 -0
  42. quick_pp-0.2.3/quick_pp/modelling/mock_data/mock_data.parquet +0 -0
  43. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/modelling/predict_pipeline.py +10 -4
  44. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/modelling/train_pipeline.py +46 -3
  45. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/modelling/utils.py +13 -9
  46. quick_pp-0.2.3/quick_pp/plotter/__init__.py +0 -0
  47. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/plotter/plotter.py +13 -0
  48. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/plotter/well_log.py +4 -2
  49. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/rock_type.py +1 -1
  50. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/utils.py +1 -0
  51. quick_pp-0.2.2/CONTRIBUTING.rst +0 -128
  52. quick_pp-0.2.2/HISTORY.rst +0 -71
  53. quick_pp-0.2.2/MANIFEST.in +0 -11
  54. quick_pp-0.2.2/PKG-INFO +0 -145
  55. quick_pp-0.2.2/README.rst +0 -26
  56. quick_pp-0.2.2/docs/Makefile +0 -22
  57. quick_pp-0.2.2/docs/_build/html/_static/file.png +0 -0
  58. quick_pp-0.2.2/docs/_build/html/_static/minus.png +0 -0
  59. quick_pp-0.2.2/docs/_build/html/_static/plus.png +0 -0
  60. quick_pp-0.2.2/docs/make.bat +0 -36
  61. quick_pp-0.2.2/docs/source/authors.rst +0 -1
  62. quick_pp-0.2.2/docs/source/conf.py +0 -170
  63. quick_pp-0.2.2/docs/source/contributing.rst +0 -1
  64. quick_pp-0.2.2/docs/source/history.rst +0 -1
  65. quick_pp-0.2.2/docs/source/index.rst +0 -40
  66. quick_pp-0.2.2/docs/source/installation.rst +0 -51
  67. quick_pp-0.2.2/docs/source/quick_pp.lithology.rst +0 -37
  68. quick_pp-0.2.2/docs/source/quick_pp.modelling.rst +0 -23
  69. quick_pp-0.2.2/docs/source/quick_pp.plotter.rst +0 -16
  70. quick_pp-0.2.2/docs/source/quick_pp.rst +0 -114
  71. quick_pp-0.2.2/docs/source/usage.rst +0 -7
  72. quick_pp-0.2.2/docs/static/quick_pp_demo.gif +0 -0
  73. quick_pp-0.2.2/quick_pp/__init__.py +0 -5
  74. quick_pp-0.2.2/quick_pp/logger.py +0 -22
  75. quick_pp-0.2.2/quick_pp.egg-info/PKG-INFO +0 -145
  76. quick_pp-0.2.2/quick_pp.egg-info/SOURCES.txt +0 -63
  77. quick_pp-0.2.2/quick_pp.egg-info/dependency_links.txt +0 -1
  78. quick_pp-0.2.2/quick_pp.egg-info/entry_points.txt +0 -2
  79. quick_pp-0.2.2/quick_pp.egg-info/not-zip-safe +0 -1
  80. quick_pp-0.2.2/quick_pp.egg-info/requires.txt +0 -17
  81. quick_pp-0.2.2/quick_pp.egg-info/top_level.txt +0 -1
  82. quick_pp-0.2.2/setup.cfg +0 -23
  83. quick_pp-0.2.2/setup.py +0 -56
  84. quick_pp-0.2.2/tests/__init__.py +0 -1
  85. quick_pp-0.2.2/tests/test_quick_pp.py +0 -33
  86. {quick_pp-0.2.2 → quick_pp-0.2.3}/AUTHORS.rst +0 -0
  87. {quick_pp-0.2.2/quick_pp/modelling → quick_pp-0.2.3/quick_pp}/__init__.py +0 -0
  88. {quick_pp-0.2.2/quick_pp/plotter → quick_pp-0.2.3/quick_pp/api}/__init__.py +0 -0
  89. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/core_calibration.py +0 -0
  90. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/fluid_type.py +0 -0
  91. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/geomechanics.py +0 -0
  92. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/las_handler.py +0 -0
  93. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/lithology/__init__.py +0 -0
  94. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/lithology/carbonate.py +0 -0
  95. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/lithology/multi_mineral.py +0 -0
  96. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/lithology/sand_shale.py +0 -0
  97. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/lithology/sand_silt_clay.py +0 -0
  98. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/objects.py +0 -0
  99. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/permeability.py +0 -0
  100. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/plotter/well_log_config.py +0 -0
  101. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/porosity.py +0 -0
  102. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/qaqc.py +0 -0
  103. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/ressum.py +0 -0
  104. {quick_pp-0.2.2 → quick_pp-0.2.3}/quick_pp/saturation.py +0 -0
@@ -0,0 +1,119 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ env/
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ .hypothesis/
48
+ .pytest_cache/
49
+
50
+ # Translations
51
+ *.mo
52
+ *.pot
53
+
54
+ # Django stuff:
55
+ *.log
56
+ local_settings.py
57
+
58
+ # Flask stuff:
59
+ instance/
60
+ .webassets-cache
61
+
62
+ # Scrapy stuff:
63
+ .scrapy
64
+
65
+ # Sphinx documentation
66
+ docs/_build/
67
+
68
+ # PyBuilder
69
+ target/
70
+
71
+ # Jupyter Notebook
72
+ .ipynb_checkpoints
73
+
74
+ # pyenv
75
+ .python-version
76
+
77
+ # celery beat schedule file
78
+ celerybeat-schedule
79
+
80
+ # SageMath parsed files
81
+ *.sage.py
82
+
83
+ # dotenv
84
+ .env
85
+
86
+ # virtualenv
87
+ .venv
88
+ venv**
89
+ ENV/
90
+
91
+ # Spyder project settings
92
+ .spyderproject
93
+ .spyproject
94
+
95
+ # Rope project settings
96
+ .ropeproject
97
+
98
+ # mkdocs documentation
99
+ /site
100
+
101
+ # mypy
102
+ .mypy_cache/
103
+
104
+ # IDE settings
105
+ .vscode/
106
+ .idea/
107
+
108
+ # Folders
109
+ notebooks/outputs/*
110
+ notebooks/data/02_intermediate/*
111
+ notebooks/data/03_processed/*
112
+ notebooks/data/04_project/*
113
+ notebooks/local/*
114
+ notebooks/03_qpp__*
115
+ uploads/*
116
+ mlruns/*
117
+ data/*
118
+ .chainlit*
119
+ chainlit*
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2023, Imran Fadhil
3
+ Copyright (c) 2025, Imran Fadhil
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: quick-pp
3
+ Version: 0.2.3
4
+ Summary: Python package to assist in providing quick-look/ preliminary petrophysical estimation.
5
+ Project-URL: Homepage, https://github.com/imranfadhil/quick_pp
6
+ Author-email: Imran Fadhil <imranfadhil@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: AUTHORS.rst
9
+ License-File: LICENSE
10
+ Keywords: analysis,geoscience,log,petrophysics,quick_pp,well
11
+ Classifier: Development Status :: 2 - Pre-Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Natural Language :: English
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Requires-Python: >=3.11
17
+ Requires-Dist: chainlit==2.5.5
18
+ Requires-Dist: click>=7.0
19
+ Requires-Dist: fastapi
20
+ Requires-Dist: fastapi-mcp
21
+ Requires-Dist: langchain-ollama==0.3.3
22
+ Requires-Dist: loguru
23
+ Requires-Dist: matplotlib==3.8.0
24
+ Requires-Dist: mlflow
25
+ Requires-Dist: orjson
26
+ Requires-Dist: pandas
27
+ Requires-Dist: psycopg2-binary
28
+ Requires-Dist: ptitprince
29
+ Requires-Dist: ruptures
30
+ Requires-Dist: salib==1.5.1
31
+ Requires-Dist: scikit-learn
32
+ Requires-Dist: statsmodels
33
+ Requires-Dist: welly
34
+ Description-Content-Type: text/markdown
35
+
36
+ # quick_pp
37
+
38
+ Python package to assist in providing quick-look/ preliminary petrophysical estimation.
39
+ ![quick_pp demo](docs/static/quick_pp_demo.gif)
40
+
41
+ ## Quick Start (Jupyter Notebook Examples)
42
+ 1. Create virtual environment (tested working with Python3.10.9)
43
+ > python -m venv venv
44
+
45
+ 2. Activate virtual environment
46
+ > venv\Scripts\activate (Windows)
47
+
48
+ > source venv/bin/activate (Linux)
49
+
50
+ 3. Install requirements
51
+ > pip install -r requirements.txt
52
+
53
+ 4. Launch the notebook and run the cells
54
+ - 01_data_handler: create the MOCK qppp project file.
55
+ - 02_EDA: quick look on the data
56
+ - 03_*: quick petropohysical interpretation of the MOCK wells.
57
+ - For API notebook, need to run the following before running the cells
58
+ > uvicorn quick_pp.api.main:app
59
+
60
+ ## Install
61
+ To install, use the following command:
62
+
63
+ `pip install quick_pp`
64
+
65
+ To use qpp_assistant, you would need to;
66
+ 1. Install Ollama
67
+ 2. Run `ollama pull qwen3` in the terminal
68
+
69
+ ## CLI
70
+ To start the App
71
+ > quick_pp app
72
+
73
+ You can then access the Swagger UI at http://localhost:8888/docs and qpp_assistant at http://localhost:8888/qpp_assistant.
74
+
75
+ To use the mcp tools, you would need to first add the following SSE URLS through the interface;
76
+ http://localhost:8888/mcp - quick_pp tools.
77
+
78
+ http://localhost:5555/mcp - quick_pp ML model prediction tools (will only be available after ML models are trained and registered).
79
+
80
+
81
+ To train an ML model, these are the requirements;
82
+ 1. The input file in parquet format need to be available; /data/input/<data_hash>___.parquet
83
+ 2. The parquet file need to have the input and target features as specified in MODELLING_CONFIG in config.py.
84
+ > quick_pp train <model_config> <data_hash>
85
+
86
+ > Example >> quick_pp train mock mock
87
+
88
+ To run the MLflow server
89
+ > quick_pp mlflow-server
90
+
91
+ To run prediction, the trained models need to be registered in MLflow first.
92
+ > quick_pp predict <model_config> <data_hash>
93
+
94
+ You can access the mlflow server at http://localhost:5015
95
+
96
+ To deploy the trained ML models
97
+ > quick_pp model-deployment
98
+
99
+ You can access the deployed model Swagger UI at http://localhost:5555/docs
100
+
101
+ ## Documentation
102
+ Documentation is available at:
103
+ <https://quick-pp.readthedocs.io/en/latest/index.html>
@@ -0,0 +1,68 @@
1
+ # quick_pp
2
+
3
+ Python package to assist in providing quick-look/ preliminary petrophysical estimation.
4
+ ![quick_pp demo](docs/static/quick_pp_demo.gif)
5
+
6
+ ## Quick Start (Jupyter Notebook Examples)
7
+ 1. Create virtual environment (tested working with Python3.10.9)
8
+ > python -m venv venv
9
+
10
+ 2. Activate virtual environment
11
+ > venv\Scripts\activate (Windows)
12
+
13
+ > source venv/bin/activate (Linux)
14
+
15
+ 3. Install requirements
16
+ > pip install -r requirements.txt
17
+
18
+ 4. Launch the notebook and run the cells
19
+ - 01_data_handler: create the MOCK qppp project file.
20
+ - 02_EDA: quick look on the data
21
+ - 03_*: quick petropohysical interpretation of the MOCK wells.
22
+ - For API notebook, need to run the following before running the cells
23
+ > uvicorn quick_pp.api.main:app
24
+
25
+ ## Install
26
+ To install, use the following command:
27
+
28
+ `pip install quick_pp`
29
+
30
+ To use qpp_assistant, you would need to;
31
+ 1. Install Ollama
32
+ 2. Run `ollama pull qwen3` in the terminal
33
+
34
+ ## CLI
35
+ To start the App
36
+ > quick_pp app
37
+
38
+ You can then access the Swagger UI at http://localhost:8888/docs and qpp_assistant at http://localhost:8888/qpp_assistant.
39
+
40
+ To use the mcp tools, you would need to first add the following SSE URLS through the interface;
41
+ http://localhost:8888/mcp - quick_pp tools.
42
+
43
+ http://localhost:5555/mcp - quick_pp ML model prediction tools (will only be available after ML models are trained and registered).
44
+
45
+
46
+ To train an ML model, these are the requirements;
47
+ 1. The input file in parquet format need to be available; /data/input/<data_hash>___.parquet
48
+ 2. The parquet file need to have the input and target features as specified in MODELLING_CONFIG in config.py.
49
+ > quick_pp train <model_config> <data_hash>
50
+
51
+ > Example >> quick_pp train mock mock
52
+
53
+ To run the MLflow server
54
+ > quick_pp mlflow-server
55
+
56
+ To run prediction, the trained models need to be registered in MLflow first.
57
+ > quick_pp predict <model_config> <data_hash>
58
+
59
+ You can access the mlflow server at http://localhost:5015
60
+
61
+ To deploy the trained ML models
62
+ > quick_pp model-deployment
63
+
64
+ You can access the deployed model Swagger UI at http://localhost:5555/docs
65
+
66
+ ## Documentation
67
+ Documentation is available at:
68
+ <https://quick-pp.readthedocs.io/en/latest/index.html>
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "quick-pp"
7
+ version = "0.2.3"
8
+ description = "Python package to assist in providing quick-look/ preliminary petrophysical estimation."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.11"
12
+ authors = [
13
+ { name = "Imran Fadhil", email = "imranfadhil@gmail.com" },
14
+ ]
15
+ keywords = [
16
+ "analysis",
17
+ "geoscience",
18
+ "log",
19
+ "petrophysics",
20
+ "quick_pp",
21
+ "well",
22
+ ]
23
+ classifiers = [
24
+ "Development Status :: 2 - Pre-Alpha",
25
+ "Intended Audience :: Developers",
26
+ "License :: OSI Approved :: MIT License",
27
+ "Natural Language :: English",
28
+ "Programming Language :: Python :: 3.11",
29
+ ]
30
+ dependencies = [
31
+ "chainlit==2.5.5",
32
+ "Click>=7.0",
33
+ "fastapi",
34
+ "fastapi_mcp",
35
+ "langchain_ollama==0.3.3",
36
+ "loguru",
37
+ "matplotlib==3.8.0",
38
+ "mlflow",
39
+ "orjson",
40
+ "pandas",
41
+ "psycopg2-binary",
42
+ "ptitprince",
43
+ "ruptures",
44
+ "SALib==1.5.1",
45
+ "scikit-learn",
46
+ "statsmodels",
47
+ "welly",
48
+ ]
49
+
50
+ [project.scripts]
51
+ quick_pp = "quick_pp.cli:cli"
52
+
53
+ [project.urls]
54
+ Homepage = "https://github.com/imranfadhil/quick_pp"
55
+
56
+ [tool.hatch.build.targets.sdist]
57
+ include = [
58
+ "/quick_pp",
59
+ ]
@@ -0,0 +1,61 @@
1
+ """Exception definition"""
2
+ from sqlalchemy.exc import IntegrityError
3
+ from psycopg2.errors import UniqueViolation
4
+
5
+
6
+ class BadRequestException(Exception):
7
+ """
8
+ This exception could be raise when receiving unexpected input from user
9
+ """
10
+ def __init__(self, name: str) -> None:
11
+ self.name = name
12
+
13
+
14
+ class DataNotFoundException(Exception):
15
+ """
16
+ This exception could be raise when receiving unexpected input from user
17
+ """
18
+ def __init__(self, name: str) -> None:
19
+ self.name = name
20
+
21
+
22
+ class MethodNotAllowedException(Exception):
23
+ """
24
+ This exception could be raise when receiving unexpected input from user
25
+ """
26
+ def __init__(self, name: str) -> None:
27
+ self.name = name
28
+
29
+
30
+ class NotAuthorizedException(Exception):
31
+ """
32
+ This exception could be raise when receiving unexpected input from user
33
+ """
34
+ def __init__(self, name: str) -> None:
35
+ self.name = name
36
+
37
+
38
+ class UnknownException(Exception):
39
+ """
40
+ This exception could be raise when receiving unexpected input from user
41
+ """
42
+ def __init__(self, name: str) -> None:
43
+ self.name = name
44
+
45
+
46
+ def return_exception_message(exc: Exception) -> str:
47
+ if isinstance(exc, DataNotFoundException):
48
+ return "Not Found!"
49
+ if isinstance(exc, NotAuthorizedException):
50
+ return "Not Authorized!"
51
+ if isinstance(exc, BadRequestException):
52
+ return "Bad request!"
53
+ if isinstance(exc, UnknownException):
54
+ return "Unrecognized error!"
55
+ return "Oops! Something was wrong"
56
+
57
+
58
+ def return_database_integrity_error_message(exc: IntegrityError) -> str:
59
+ if isinstance(exc.orig, UniqueViolation):
60
+ return "Unique Violation! Data input already exists"
61
+ return "Oops! Data Inegrity Error, please check the input data"
@@ -0,0 +1 @@
1
+ __version__ = "0.1.2"
@@ -0,0 +1,59 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Mapping from mlflow schemas to Pydantic models and native Python types.
3
+
4
+ Copyright (C) 2022, Auto Trader UK
5
+
6
+ """
7
+
8
+ from datetime import date, datetime
9
+ from typing import Dict, Optional, Union
10
+
11
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP = {
12
+ "boolean": bool,
13
+ "integer": int,
14
+ "long": int,
15
+ "int32": int,
16
+ "int64": int,
17
+ "double": float,
18
+ "float": float,
19
+ "float32": float,
20
+ "float64": float,
21
+ "string": str,
22
+ "str": str,
23
+ "object": str,
24
+ "binary": bytes,
25
+ "datetime": Union[datetime, date],
26
+ }
27
+
28
+
29
+ class UnsupportedFieldTypeError(Exception):
30
+ pass
31
+
32
+
33
+ def get_field(type_name: str, nullable: bool):
34
+ """
35
+ :param nullable (bool): Should field be nullable
36
+ """
37
+ try:
38
+ type_ = MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP[type_name]
39
+ except KeyError:
40
+ raise UnsupportedFieldTypeError(f"Field type not supported: {type_name}")
41
+
42
+ if nullable:
43
+ type_ = Optional[type_]
44
+
45
+ field = (type_, ...) # Ellipsis (...) because default value is unknown
46
+ return field
47
+
48
+
49
+ def build_model_fields(schema, nullable: bool = False) -> Dict:
50
+ """Return a dict mapping field names -> (type, default).
51
+
52
+ :param nullable (bool): Should fields be nullable
53
+ """
54
+ if schema.has_input_names():
55
+ return {
56
+ item["name"]: get_field(item["type"], nullable) for item in schema.to_dict()
57
+ }
58
+ else:
59
+ return {"prediction": get_field(schema.numpy_types()[0].name, nullable)}
@@ -0,0 +1,72 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Build FastAPI applications for mlflow model predictions.
3
+
4
+ Copyright (C) 2022, Auto Trader UK
5
+
6
+ """
7
+
8
+ import logging
9
+ from inspect import signature
10
+
11
+ from fastapi import FastAPI, Request
12
+ from fastapi.responses import ORJSONResponse
13
+ from mlflow.pyfunc import PyFuncModel # type: ignore
14
+
15
+ from quick_pp.api.fastapi_mlflow.exceptions import DictSerialisableException
16
+ from quick_pp.api.fastapi_mlflow.predictors import build_predictor
17
+
18
+
19
+ def build_app(app, pyfunc_model: PyFuncModel, route: str) -> FastAPI:
20
+ """Build and return a FastAPI app for the mlflow model."""
21
+ logger = logging.getLogger(__name__)
22
+ predictor = build_predictor(pyfunc_model)
23
+ response_model = signature(predictor).return_annotation
24
+
25
+ # Get input and output schemas from the model metadata
26
+ input_schema = pyfunc_model.metadata.get_input_schema()
27
+ input_features = [item['name'] for item in input_schema.to_dict()]
28
+ output_schema = pyfunc_model.metadata.get_output_schema()
29
+ target_features = [item['name'] for item in output_schema.to_dict()]
30
+
31
+ model_name = route.removeprefix('/')
32
+ input_example = ', '.join([f'\"{f}\": <value>' for f in input_features])
33
+ output_example = ', '.join([f'\"{f}\": <predicted_value>' for f in target_features])
34
+ app.add_api_route(
35
+ f"{route}",
36
+ predictor,
37
+ response_model=response_model,
38
+ response_class=ORJSONResponse,
39
+ methods=["POST"],
40
+ description=(
41
+ f"Predict using the '{model_name}' MLflow model.\n\n"
42
+ f"**Input:**\n"
43
+ f"- Request body must be a JSON object with the following features as keys:\n"
44
+ f" {', '.join(input_features)}\n"
45
+ f"- Example: {{ {input_example} }}\n\n"
46
+ f"**Output:**\n"
47
+ f"- JSON object with the following keys: {', '.join(target_features)}\n"
48
+ f"- Example: {{ {output_example} }}\n"
49
+ ),
50
+ operation_id=f"predict_{model_name}",
51
+ )
52
+
53
+ @app.exception_handler(DictSerialisableException)
54
+ def handle_serialisable_exception(
55
+ req: Request, exc: DictSerialisableException
56
+ ) -> ORJSONResponse:
57
+ nonlocal logger
58
+ req_id = req.headers.get("x-request-id")
59
+ extra = {"x-request-id": req_id} if req_id is not None else {}
60
+ logger.exception(exc.message, extra=extra)
61
+ return ORJSONResponse(
62
+ status_code=500,
63
+ content=exc.to_dict(),
64
+ )
65
+
66
+ @app.exception_handler(Exception)
67
+ def handle_exception(req: Request, exc: Exception) -> ORJSONResponse:
68
+ return handle_serialisable_exception(
69
+ req, DictSerialisableException.from_exception(exc)
70
+ )
71
+
72
+ return app
@@ -0,0 +1,22 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Exceptions.
3
+
4
+ Copyright (C) 2023, Auto Trader UK
5
+ Created 17. Apr 2023
6
+
7
+ """
8
+
9
+
10
+ class DictSerialisableException(Exception):
11
+ """An Exception wrapper for formatting."""
12
+
13
+ def __init__(self, name: str, message: str):
14
+ self.name = name
15
+ self.message = message
16
+
17
+ @classmethod
18
+ def from_exception(cls, exc: Exception):
19
+ return cls(name=exc.__class__.__name__, message=str(exc))
20
+
21
+ def to_dict(self):
22
+ return {"name": self.name, "message": self.message}
@@ -0,0 +1,96 @@
1
+ # -*- coding: utf-8 -*-
2
+ """Build functions to wrap mlflow models.
3
+
4
+ Existing implementation returns a synchronous/blocking function. This decision
5
+ was taken because applying ML models is probably CPU-bound. Not having
6
+ unnecessary asynchronous code also makes testing simpler.
7
+
8
+ Current supports only the pyfunc flavour.
9
+
10
+ Copyright (C) 2022, Auto Trader UK
11
+
12
+ """
13
+
14
+ from typing import Any, Callable, Dict, List, no_type_check
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ from mlflow.pyfunc import PyFuncModel # type: ignore
19
+ from pydantic import BaseModel, create_model
20
+
21
+ from quick_pp.api.fastapi_mlflow._mlflow_types import (
22
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP,
23
+ build_model_fields,
24
+ )
25
+ from quick_pp.api.fastapi_mlflow.exceptions import DictSerialisableException
26
+
27
+
28
+ @no_type_check # Some types here are too dynamic for type checking
29
+ def build_predictor(model: PyFuncModel) -> Callable[[BaseModel], Any]:
30
+ """Build and return a function that wraps the mlflow model.
31
+
32
+ Currently supports only the `pyfunc`_ flavour of mlflow.
33
+
34
+ :param model: PyFuncModel
35
+ :return: Function suitable for mounting as a FastAPI endpoint or route.
36
+
37
+ Example::
38
+
39
+ model = load_model("/Users/me/path/to/local/model")
40
+ predictor = build_predictor(model)
41
+
42
+ .. _pyfunc: https://www.mlflow.org/docs/latest/python_api/mlflow.pyfunc.html
43
+
44
+ """
45
+ input_schema = model.metadata.get_input_schema()
46
+ input_model = create_model("RequestRow", **(build_model_fields(input_schema)))
47
+ output_schema = model.metadata.get_output_schema()
48
+ output_features = [item['name'] for item in output_schema.to_dict()]
49
+ output_model = create_model("ResponseRow", **(build_model_fields(output_schema, nullable=True)))
50
+
51
+ class Request(BaseModel):
52
+ data: List[input_model]
53
+
54
+ class Response(BaseModel):
55
+ data: List[output_model]
56
+
57
+ async def request_to_dataframe(request: Request) -> pd.DataFrame:
58
+ df = pd.DataFrame([row.model_dump() for row in request.data], dtype=object)
59
+ for item in input_schema.to_dict():
60
+ if item["type"] in ("integer", "int32"):
61
+ df[item["name"]] = df[item["name"]].astype(np.int32)
62
+ elif item["type"] == "datetime":
63
+ df[item["name"]] = pd.to_datetime(df[item["name"]], utc=True)
64
+ else:
65
+ df[item["name"]] = df[item["name"]].astype(
66
+ MLFLOW_SIGNATURE_TO_PYTHON_TYPE_MAP.get(item["type"], object)
67
+ )
68
+
69
+ return df
70
+
71
+ async def predictor(request: Request) -> Response:
72
+ try:
73
+ predictions = model.predict(await request_to_dataframe(request))
74
+ response_data = await convert_predictions_to_python(predictions, output_features)
75
+ return Response(data=response_data)
76
+ except Exception as exc:
77
+ raise DictSerialisableException.from_exception(exc) from exc
78
+
79
+ return predictor # type: ignore
80
+
81
+
82
+ async def convert_predictions_to_python(results, output_features) -> List[Dict[str, Any]]:
83
+ """Convert and return predictions in native Python types."""
84
+ try:
85
+ results = pd.DataFrame(results, columns=output_features)
86
+ response_data = (
87
+ results.fillna(np.nan).replace([np.nan], [None]).to_dict(orient="records")
88
+ )
89
+ except (AttributeError, TypeError):
90
+ # Return type is probably a simple array-like
91
+ # Replace NaN with None
92
+ response_data = []
93
+ for row in results:
94
+ value = row if not pd.isnull(row) else None
95
+ response_data.append({"prediction": value})
96
+ return response_data