Compare commits

...

1 Commits

Author SHA1 Message Date
ulises 9a62ddcdaf CaMa recurrence: import schemas for the follow-up and the new patient variables, silver mappings and /cama/recurrencia
The patient takes the menopausal state, molecular and clinical subtype, integrative cluster, cellularity, mutation load,
Ki-67 category and source of the record; a new import entity carries the recurrence and the last contact; hormone and
anti-HER2 therapy are treatments. The route serves each cohort's scenarios, a scenario's figure and a patient's scenarios
over the live cohort build, computing the models and the bootstrap in the background and caching them per build. Includes
the survival import work this builds on.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 08:46:42 -06:00
21 changed files with 786 additions and 12 deletions
+1
View File
@@ -0,0 +1 @@
2026-11-22T10:18:21+00:00
+1 -1
View File
@@ -6,7 +6,7 @@ requires-python = ">=3.12"
dependencies = [
"flask>=3.0",
"persistance",
"models[notebooks]",
"models[notebooks,seer-survival]",
"extraction",
"apache-hamilton>=1.90",
"pandas>=2.0",
File diff suppressed because one or more lines are too long
Generated
+188 -3
View File
@@ -992,6 +992,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d1/86/32914542064b8aee77ac48142f8a1955df78da4eb905dd41697d26941d21/fhir_resources-8.3.0-py2.py3-none-any.whl", hash = "sha256:151e6c9b4336e36383cc2aaf2067a6f112a420fce1c7bd289182e55dd950871b", size = 2288069, upload-time = "2026-07-03T15:23:51.97Z" },
]
[[package]]
name = "filelock"
version = "4.3.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/6c/bf/a895b0b8e83d0a64d134f658e393e83998abfc22bbb8b58181ce55268706/filelock-4.3.0.tar.gz", hash = "sha256:143407310acf479e82d88068e3b9a6486f45fb410c0ed8729fe7359eaabeb6f1", size = 742199, upload-time = "2026-11-22T02:15:03.187Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/68/66/870b527908a06c7ec0e91239bd2c4d0bb22921efd4f915428b4e47d461a6/filelock-4.3.0-py3-none-any.whl", hash = "sha256:f933f39f7e01249a4a49b9abab30edc6d4b874624c3de5dd0b0d137aa8adb979", size = 244553, upload-time = "2026-11-22T02:15:01.667Z" },
]
[[package]]
name = "flask"
version = "3.1.3"
@@ -1354,6 +1363,69 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
]
[[package]]
name = "hf-xet"
version = "1.8.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2c/18/db7ebc58820d82fd5506aa405a75611e7a4398f573dc436f7387603bf63d/hf_xet-1.8.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:c74e3751cbcdae9222c5170e8d788e83201a03dc5e5f4308a20f17a5b6023b56", size = 3883873, upload-time = "2026-10-30T10:04:03.24Z" },
{ url = "https://files.pythonhosted.org/packages/37/bd/6c9ed89aafbeb4a7ee0d76d6b7b9365221e3e7ee47958aeecdc2c60a0511/hf_xet-1.8.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:56735c2d4f416d7473fc986586b26a8756e067832ca4b7fdaad32a0d6f2ce740", size = 3594510, upload-time = "2026-10-30T10:04:05.364Z" },
{ url = "https://files.pythonhosted.org/packages/0e/1f/c26154b3a053b637c0984db0db9fdacbbfc257bdc2e95e9bc0782b745b0c/hf_xet-1.8.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3ecfe2934448cca55a4c42732b60f985266aecb241905945219b3d388aceb7ba", size = 4281780, upload-time = "2026-10-30T10:04:07.35Z" },
{ url = "https://files.pythonhosted.org/packages/e3/9e/d84c31f8e3acc286c9c6a4fd85f7f332e3db40636595f0de5ad776b69beb/hf_xet-1.8.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:7edeb21c5d381903ee5f4857fc746fa7b52a4b374035e8811ecfb67ee27add0c", size = 4060223, upload-time = "2026-10-30T10:04:09.029Z" },
{ url = "https://files.pythonhosted.org/packages/a4/70/c142e4ad8a679ff6ffe40964a9d017fa0211aabca9ca4d3d547c3a2fc165/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:07a06d7481702616726c2d8578cfb00052a5b3f21beed6a674592bc837a10330", size = 4263619, upload-time = "2026-10-30T10:04:11.085Z" },
{ url = "https://files.pythonhosted.org/packages/9d/08/92e03e3ac4eaeab046359093c447c03c8c30b577c2b1e1687dc747654f1c/hf_xet-1.8.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f42940869572dc2b05dfe06f4cc398c6291503e086ddc4eddfb7a6ab9409ad01", size = 4493381, upload-time = "2026-10-30T10:04:13.022Z" },
{ url = "https://files.pythonhosted.org/packages/61/63/a512b2906d0f92b5d325f58169d1fd8c3202a9ee61bd8405ec78c67e5315/hf_xet-1.8.0-cp314-cp314t-win_amd64.whl", hash = "sha256:23c262e9f5e137b18dadbce60becfeea84156b0d43119c320bffe260d32cd2fa", size = 3901344, upload-time = "2026-10-30T10:04:15.051Z" },
{ url = "https://files.pythonhosted.org/packages/2d/5e/b453f82690cb36f176c4b01e64d6d32757fabbf34dbb9bcbdf747e429a79/hf_xet-1.8.0-cp314-cp314t-win_arm64.whl", hash = "sha256:62b056aedb89ac809f78940baf465fe553b70c8b25ee56890fbab3039fffec1b", size = 3731681, upload-time = "2026-10-30T10:04:16.855Z" },
{ url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" },
{ url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" },
{ url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" },
{ url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" },
{ url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" },
{ url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" },
{ url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" },
{ url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" },
]
[[package]]
name = "httpcore2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11" },
{ name = "truststore" },
]
sdist = { url = "https://files.pythonhosted.org/packages/92/9d/df40b41f7db0370f82019820709244e7b660c52aa3da3c9e5c4e8141f6e6/httpcore2-2.16.2.tar.gz", hash = "sha256:6c519d0f7b44f7269fa9bbb4d2763db395a4a2370f046d8e8e0a4b38227815d2", size = 70064, upload-time = "2026-11-16T10:12:19.491Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/2a/e8/009c347feac27f8960605aa98d55ed263b5870dd4fd80b82fd1d00d5716c/httpcore2-2.16.2-py3-none-any.whl", hash = "sha256:16051ae2a42f776007543f32de9349a317b23d2cbb4e1456b4bac0e88b87419a", size = 85551, upload-time = "2026-11-16T10:12:16.674Z" },
]
[[package]]
name = "httpx2"
version = "2.16.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "anyio", marker = "sys_platform != 'emscripten'" },
{ name = "httpcore2", marker = "sys_platform != 'emscripten'" },
{ name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" },
{ name = "idna" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
{ name = "typing-extensions", marker = "python_full_version < '3.13'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/1c/77/6515121dc5ac3c743ad1bff5afe635bcd1a3f23cc40db3c5c89f7d02917d/httpx2-2.16.2.tar.gz", hash = "sha256:748b615678f07d8e3b183efe81ad13b655ca88bfc56ce4589219b2d442860574", size = 103370, upload-time = "2026-11-16T10:12:20.49Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/77/de/8c4306a3d6aa2495111986addf33a9e561eff4c47552e4c4b9251160d0ad/httpx2-2.16.2-py3-none-any.whl", hash = "sha256:f05c13aade4c45dbf1c9060647a1058f0acad62398fad96e741269edb33d46f5", size = 97893, upload-time = "2026-11-16T10:12:18.192Z" },
]
[[package]]
name = "httpx2-jsfetch"
version = "1.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
]
[[package]]
name = "huey"
version = "3.4.0"
@@ -1363,6 +1435,26 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/57/31/cee585bd4d1e39947a426a6736f4e17d22b454952370fb9cf48eb3103085/huey-3.4.0-py3-none-any.whl", hash = "sha256:d0580762397744026f83baae5f2b97a62474a62b8565ac75bbafefe72f9c784f", size = 136493, upload-time = "2026-09-04T02:04:32.848Z" },
]
[[package]]
name = "huggingface-hub"
version = "2.4.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click" },
{ name = "filelock" },
{ name = "fsspec" },
{ name = "hf-xet", marker = "platform_machine == 'AMD64' or platform_machine == 'ARM64' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" },
{ name = "httpx2" },
{ name = "packaging" },
{ name = "pyyaml" },
{ name = "tqdm" },
{ name = "typing-extensions" },
]
sdist = { url = "https://files.pythonhosted.org/packages/b5/3b/2fcef1eabe52aec90fc8cd253cc154da1d02a446d7bbcdec59b4a51d4be7/huggingface_hub-2.4.0.tar.gz", hash = "sha256:13a6158b9e3393d9d3f248ce99074d50c2a0a1449fb9d8e2f710751e2084c188", size = 1066194, upload-time = "2026-10-29T15:30:12.321Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/d4/55/ff47f1b082ecf5f43f4bc1e3b932d68eead171dabbbd1a92666c686301d7/huggingface_hub-2.4.0-py3-none-any.whl", hash = "sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801", size = 857021, upload-time = "2026-10-29T15:30:10.421Z" },
]
[[package]]
name = "idna"
version = "3.20"
@@ -2068,32 +2160,66 @@ notebooks = [
{ name = "nbclient" },
{ name = "nbconvert" },
]
seer-survival = [
{ name = "matplotlib" },
{ name = "mpmath" },
{ name = "networkx" },
{ name = "pgmpy" },
{ name = "scipy" },
{ name = "statsmodels" },
]
[package.metadata]
requires-dist = [
{ name = "apache-hamilton", specifier = ">=1.90" },
{ name = "dcurves", marker = "extra == 'seer-survival-dca'", specifier = ">=1.1" },
{ name = "extraction", editable = "../Extraction" },
{ name = "ipykernel", marker = "extra == 'notebooks'", specifier = ">=6.29" },
{ name = "matplotlib", marker = "extra == 'seer-survival'", specifier = ">=3.8" },
{ name = "mlflow", specifier = ">=2.9" },
{ name = "mpmath", marker = "extra == 'seer-survival'", specifier = ">=1.3" },
{ name = "nbclient", marker = "extra == 'notebooks'", specifier = ">=0.10" },
{ name = "nbconvert", marker = "extra == 'notebooks'", specifier = ">=7.16" },
{ name = "networkx", marker = "extra == 'seer-survival'", specifier = ">=3.0" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pandera", specifier = ">=0.20" },
{ name = "persistance", editable = "../Persistance" },
{ name = "pgmpy", marker = "extra == 'seer-survival'", specifier = ">=1.0" },
{ name = "pyarrow", specifier = ">=15" },
{ name = "scikit-learn", specifier = ">=1.4" },
{ name = "scipy", marker = "extra == 'seer-survival'", specifier = ">=1.11" },
{ name = "statsmodels", marker = "extra == 'seer-survival'", specifier = ">=0.14" },
{ name = "tea", editable = "../models/libs/tea" },
{ name = "tea", extras = ["s3"], marker = "extra == 'eeg-reference'", editable = "../models/libs/tea" },
]
provides-extras = ["eeg-reference", "notebooks"]
provides-extras = ["eeg-reference", "notebooks", "seer-survival", "seer-survival-dca"]
[package.metadata.requires-dev]
dev = [
{ name = "ipykernel", specifier = ">=6.29" },
{ name = "matplotlib", specifier = ">=3.8" },
{ name = "mpmath", specifier = ">=1.3" },
{ name = "nbclient", specifier = ">=0.10" },
{ name = "nbconvert", specifier = ">=7.16" },
{ name = "networkx", specifier = ">=3.0" },
{ name = "pgmpy", specifier = ">=1.0" },
{ name = "pytest", specifier = ">=8.0.0" },
{ name = "reportlab", specifier = ">=4.0" },
{ name = "scipy", specifier = ">=1.11" },
{ name = "statsmodels", specifier = ">=0.14" },
]
notebooks = [
{ name = "graphviz", specifier = ">=0.20" },
{ name = "ipykernel", specifier = ">=6.29" },
]
[[package]]
name = "mpmath"
version = "1.4.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" },
]
[[package]]
@@ -2393,6 +2519,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/09/ed/559d2915dce85794bc0c36064043da170da50cd98746dcbddd85d5932017/nest_asyncio2-1.7.4-py3-none-any.whl", hash = "sha256:86e77b52c3d1496b294af3c944b44213b9b82a12a5ee590c0acc4ca4692ef6c7", size = 8543, upload-time = "2026-10-07T22:31:49.245Z" },
]
[[package]]
name = "networkx"
version = "3.7"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" },
]
[[package]]
name = "numba"
version = "0.68.1"
@@ -2564,6 +2699,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/bc/14/67f8aa798857f8cf686f515bf93d9bb877ce952ddc8efae0fa25b45ce0d6/opentelemetry_semantic_conventions-0.66b1-py3-none-any.whl", hash = "sha256:d4cddeb4315490b35213f55e2bdc9ac54bb1e4d318927475bed62b35545e581b", size = 206279, upload-time = "2026-10-06T17:32:56.103Z" },
]
[[package]]
name = "opt-einsum"
version = "3.4.0"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/8c/b9/2ac072041e899a52f20cf9510850ff58295003aa75525e58343591b0cbfb/opt_einsum-3.4.0.tar.gz", hash = "sha256:96ca72f1b886d148241348783498194c577fa30a8faac108586b14f1ba4473ac", size = 63004, upload-time = "2024-09-26T14:33:24.483Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/23/cd/066e86230ae37ed0be70aae89aabf03ca8d9f39c8aea0dec8029455b5540/opt_einsum-3.4.0-py3-none-any.whl", hash = "sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cd", size = 71932, upload-time = "2024-09-26T14:33:23.039Z" },
]
[[package]]
name = "packaging"
version = "26.3"
@@ -2763,6 +2907,29 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772, upload-time = "2023-11-25T06:56:14.81Z" },
]
[[package]]
name = "pgmpy"
version = "1.1.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "huggingface-hub" },
{ name = "joblib" },
{ name = "networkx" },
{ name = "numpy" },
{ name = "opt-einsum" },
{ name = "pandas" },
{ name = "pyparsing" },
{ name = "scikit-base" },
{ name = "scikit-learn" },
{ name = "scipy" },
{ name = "statsmodels" },
{ name = "tqdm" },
]
sdist = { url = "https://files.pythonhosted.org/packages/72/9a/b94ccd1d6cbf2982937c26e54e887b47ee10f848ad53c4427965578a358d/pgmpy-1.1.2.tar.gz", hash = "sha256:a62a89352f139a5d459839e54e6bfa202a7d8749e6dc6d7ceec088a71529af45", size = 2183113, upload-time = "2026-04-30T11:34:49.538Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c6/5d/d03634ed296986abad834a69b0df21510cc9b6c40fb8afaed5df1c4b6074/pgmpy-1.1.2-py3-none-any.whl", hash = "sha256:e55c78763a4a45dd644a13b250cea86af0c7e08590cf35de489624f34a4d9a0b", size = 2446383, upload-time = "2026-04-30T11:34:47.189Z" },
]
[[package]]
name = "pillow"
version = "12.3.0"
@@ -3826,6 +3993,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" },
]
[[package]]
name = "scikit-base"
version = "1.2.1"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/d9/e9/287707e71be93558076d873f92444fa788c1a11c259982a1967ad2071b0e/scikit_base-1.2.1.tar.gz", hash = "sha256:6cccfab1cf51e36141b731fe3248bd3c1a55361e965ddc7457be75ad8a9803eb", size = 136836, upload-time = "2026-11-08T20:24:26.859Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/c1/b4/21adac81fbb522bdbb74c4809c7ea06fbde847a24c54b68dfed1519ff3dc/scikit_base-1.2.1-py3-none-any.whl", hash = "sha256:8695538dcf61c5439752b56baeca9d4ce52de012ddc4cee50ee67c910a9b5fb9", size = 163886, upload-time = "2026-11-08T20:24:25.324Z" },
]
[[package]]
name = "scikit-learn"
version = "1.9.1"
@@ -4324,6 +4500,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/ad/66/0d785f0bc5e4315a96c989bb476d0fc07ea4f85132550c7b156ca2035d52/traitlets-5.16.1-py3-none-any.whl", hash = "sha256:f775618166caa0396c8e337099240f2bd3e5e917d203b2e6fbe21a58d3cb1f6b", size = 86211, upload-time = "2026-08-03T08:32:34.48Z" },
]
[[package]]
name = "truststore"
version = "0.10.5"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" },
]
[[package]]
name = "typeguard"
version = "4.6.0"
@@ -4503,7 +4688,7 @@ dependencies = [
{ name = "flask" },
{ name = "flask-cors" },
{ name = "gunicorn" },
{ name = "models", extra = ["notebooks"] },
{ name = "models", extra = ["notebooks", "seer-survival"] },
{ name = "openpyxl" },
{ name = "pandas" },
{ name = "pdfplumber" },
@@ -4539,7 +4724,7 @@ requires-dist = [
{ name = "flask", specifier = ">=3.0" },
{ name = "flask-cors", specifier = ">=4.0" },
{ name = "gunicorn", specifier = ">=23.0" },
{ name = "models", extras = ["notebooks"], editable = "../models" },
{ name = "models", extras = ["notebooks", "seer-survival"], editable = "../models" },
{ name = "openpyxl", specifier = ">=3.1" },
{ name = "pandas", specifier = ">=2.0" },
{ name = "pdfplumber", specifier = ">=0.11" },
+4
View File
@@ -12,6 +12,8 @@ from webapi.blueprints.imports import imports_bp
from webapi.blueprints.reports import reports_bp
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
from webapi.cama_recurrence.routes import cama_recurrence_bp
from webapi.cama_survival.routes import cama_survival_bp
from webapi.follow_up.routes import follow_up_blueprint
@@ -102,6 +104,8 @@ def create_app() -> Flask:
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
app.register_blueprint(cama_survival_bp, url_prefix="/cama/supervivencia")
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
return app
View File
+42
View File
@@ -0,0 +1,42 @@
"""`/cama/recurrencia`: the scenarios of each cohort, the figure of one and the scenarios a patient meets."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_recurrence import service
cama_recurrence_bp = Blueprint("cama_recurrence", __name__)
@cama_recurrence_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_recurrence_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_recurrence_bp.get("/figura")
def figure():
cohort = request.args.get("cohorte", "").strip()
scenario = request.args.get("escenario", "").strip()
if not cohort or not scenario:
raise BadRequest("faltan los parámetros «cohorte» y «escenario»")
try:
return jsonify(service.figure(cohort, scenario))
except service.Calculating:
return jsonify({"estado": "calculando"}), 202
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}» en la cohorte «{cohort}»")
except LookupError:
raise NotFound(f"el escenario «{scenario}» no tiene recaídas suficientes para dibujarse")
@cama_recurrence_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+183
View File
@@ -0,0 +1,183 @@
"""CaMa's recurrence analysis over the live cohort build.
Each cohort (METABRIC, SCAN-B) is recoded from the latest build of `cama/cohorte_total` by the dictionary of
`models.cama.recurrence`. Its covariates, the terms of each horizon and the bootstrap of the combined estimate are
computed once per build, in the background, and kept on disk; a scenario's figure is computed when it is asked for and kept
in memory. A new build computes them again.
"""
import hashlib
import pickle
import tempfile
import threading
from dataclasses import dataclass, field
from importlib import import_module
from pathlib import Path
import numpy as np
import pandas as pd
from models.cama.recurrence import analysis, cohort as recurrence_cohort
from models.io.storage import KitBuild
DOMAIN, COHORT = "cama", "cama/cohorte_total"
CACHE_DIR = Path(tempfile.gettempdir()) / "cama_recurrence"
class NotAvailable(LookupError):
"""There is no cohort build to draw on."""
class Calculating(RuntimeError):
"""The cohort's models and bootstrap are still being computed."""
@dataclass
class CohortState:
name: str
frame: pd.DataFrame
scenarios: list[dict]
masks: dict
status: str = "calculando"
error: str | None = None
covariates: list[str] = field(default_factory=list)
dropped: list[str] = field(default_factory=list)
models: dict = field(default_factory=dict)
point: dict = field(default_factory=dict)
draws: dict = field(default_factory=dict)
figures: dict = field(default_factory=dict)
@dataclass
class Live:
build_id: int
model: dict
events: pd.DataFrame
cohorts: dict[str, CohortState]
_lock = threading.RLock()
_live: Live | None = None
def _cache_file(build_id: int, name: str, model_text: str, members: int) -> Path:
key = hashlib.sha256(f"{build_id}|{name}|{members}|{model_text}".encode()).hexdigest()[:20]
return CACHE_DIR / f"{name}-{key}.pkl"
def _compute(state: CohortState, model: dict, cache: Path) -> None:
try:
if cache.is_file():
with cache.open("rb") as handle:
saved = pickle.load(handle)
else:
settings, calculator = model["modeling"], model["calculator"]
horizons = model["config"]["horizons_months"]
cfg = model["cohorts"][state.name]
covariates, dropped = analysis.prune_covariates(state.frame, cfg["covariates"], cfg["treatment"], settings)
models = analysis.select_models(state.frame, covariates, horizons, settings)
calc = analysis.Calculator(state.frame, covariates, models, horizons, settings["bdeu_ess"])
point = calc.risk(np.arange(calc.n), state.masks)
draws = calc.bootstrap(state.masks, calculator["bootstrap_replicas"], settings["seed"])
saved = {"covariates": covariates, "dropped": dropped, "models": models, "point": point, "draws": draws}
CACHE_DIR.mkdir(parents=True, exist_ok=True)
with cache.open("wb") as handle:
pickle.dump(saved, handle)
with _lock:
state.covariates, state.dropped, state.models = saved["covariates"], saved["dropped"], saved["models"]
state.point, state.draws, state.status = saved["point"], saved["draws"], "listo"
except Exception as error: # the cohort reports its failure; the others keep working
with _lock:
state.status, state.error = "error", f"{type(error).__name__}: {error}"
def live() -> Live:
"""The latest build's cohorts; recoded again only when the build changed."""
global _live
repositories = import_module(f"persistance.{DOMAIN}")
build_id = repositories.cohort_repository.latest_build(COHORT)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el análisis de recurrencia")
with _lock:
if _live is not None and _live.build_id == int(build_id):
return _live
model = recurrence_cohort.load()
model_text = recurrence_cohort.TOML.read_text(encoding="utf-8")
events = KitBuild(DOMAIN, int(build_id)).frame()
cohorts = {}
for name, cfg in model["cohorts"].items():
frame = recurrence_cohort.recode(events, model, name)
if frame.empty:
continue
scenarios = cfg["scenarios"]
state = CohortState(name, frame, scenarios, analysis.scenario_masks(frame, scenarios))
cohorts[name] = state
cache = _cache_file(int(build_id), name, model_text, len(frame))
threading.Thread(target=_compute, args=(state, model, cache), daemon=True).start()
_live = Live(int(build_id), model, events, cohorts)
return _live
def _cohort(current: Live, name: str) -> CohortState:
if name not in current.cohorts:
raise KeyError(name)
return current.cohorts[name]
def scenarios() -> dict:
current = live()
minimum = current.model["calculator"]["min_events"]
cohorts = []
for name, state in current.cohorts.items():
rows = []
for scenario in state.scenarios:
mask = state.masks[scenario["name"]]
events = int(state.frame.loc[mask, "evento"].sum())
rows.append({"nombre": scenario["name"], "condiciones": scenario["when"], "n": int(mask.sum()),
"recaidas": events, "dibujable": events >= minimum})
cohorts.append({"id": name, "nombre": current.model["cohorts"][name]["name"], "estado": state.status,
"error": state.error, "escenarios": rows})
return {"build": current.build_id, "horizontes": current.model["config"]["horizons_months"], "cohortes": cohorts}
def figure(cohort: str, scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for an unknown cohort or scenario, `Calculating` while the cohort
is being computed, `LookupError` when the scenario has too few recurrences to be drawn."""
current = live()
state = _cohort(current, cohort)
if scenario not in state.masks:
raise KeyError(scenario)
with _lock:
if state.status == "calculando":
raise Calculating(cohort)
if state.status == "error":
raise RuntimeError(state.error)
if scenario not in state.figures:
figure_record = analysis.scenario_figure(
state.frame, scenario, state.masks[scenario], state.point[scenario], state.draws[scenario],
current.model["config"]["horizons_months"], current.model["calculator"])
if figure_record is None:
raise LookupError(scenario)
state.figures[scenario] = {"cohorte": cohort, "cohorte_nombre": current.model["cohorts"][cohort]["name"],
"condiciones": next(s["when"] for s in state.scenarios if s["name"] == scenario),
"build": current.build_id, **figure_record}
return state.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient's covariates meet in each cohort; one that needs a covariate she lacks does not include her."""
current = live()
events = current.events[current.events["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
found = []
# The analysis is for patients after treatment: those whose timeline holds the post-treatment scenario.
if not (events["tipo"] == "escenario_postratamiento").any():
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": False, "escenarios": found}
for name, state in current.cohorts.items():
recoded = recurrence_cohort.recode(events, current.model, name, of_source=False, follow_up=False)
if recoded.empty:
continue
masks = analysis.scenario_masks(recoded, state.scenarios)
found += [{"cohorte": name, "escenario": n} for n, mask in masks.items() if bool(mask[0])]
return {"build": current.build_id, "pac_id": pac_id, "postratamiento": True, "escenarios": found}
+5
View File
@@ -0,0 +1,5 @@
"""CaMa's survival figures over the model in production.
service.py the production model and the live cohort, a scenario's figure and a patient's scenarios, cached
routes.py the routes: `/cama/supervivencia/...`
"""
+37
View File
@@ -0,0 +1,37 @@
"""`/cama/supervivencia`: the survival figure of a clinical scenario and the scenarios of a patient."""
from flask import Blueprint, jsonify, request
from werkzeug.exceptions import BadRequest, NotFound
from webapi.cama_survival import service
cama_survival_bp = Blueprint("cama_survival", __name__)
@cama_survival_bp.errorhandler(service.NotAvailable)
def _not_available(error):
return jsonify({"error": str(error)}), 404
@cama_survival_bp.get("/escenarios")
def scenarios():
return jsonify(service.scenarios())
@cama_survival_bp.get("/figura")
def figure():
scenario = request.args.get("escenario", "").strip()
if not scenario:
raise BadRequest("falta el parámetro «escenario»")
try:
return jsonify(service.figure(scenario))
except KeyError:
raise NotFound(f"el modelo no define el escenario «{scenario}»")
@cama_survival_bp.get("/pacientes/<int:pac_id>")
def patient(pac_id: int):
try:
return jsonify(service.patient_scenarios(pac_id))
except KeyError:
raise NotFound("la paciente no está en la cohorte")
+124
View File
@@ -0,0 +1,124 @@
"""The production CaMa survival model over the live cohort build.
A scenario's figure is computed on request from the production version of `cama/seer_survival` and the latest build of its
cohort, and kept per (model version, cohort build, scenario): a new version or a new build computes it again. The saved model
is rehydrated with the current class before it scores (`SeerSurvivalModel.rehydrate`).
"""
import os
import pickle
import threading
from dataclasses import dataclass
from importlib import import_module
from pathlib import Path
import mlflow.sklearn
import pandas as pd
from models.cama.seer_survival import seer_model
from models.dags.training import Scenario
from models.io.registry import registry
from models.io.storage import KitBuild
DOMAIN, SCENARIO = "cama", "seer_survival"
class NotAvailable(LookupError):
"""There is no production version, or no cohort build to draw on."""
class SavedFile:
"""The model saved as a file (`CAMA_SURVIVAL_MODEL`), versioned by its modification time."""
def __init__(self, path: str):
self.path = Path(path)
self.version = f"archivo-{int(self.path.stat().st_mtime)}"
def load(self):
with self.path.open("rb") as handle:
return pickle.load(handle)
@dataclass
class Live:
"""The model of the production version and the live build's members, recoded once for both."""
version: str
build_id: int
model: seer_model.SeerSurvivalModel
cohort: pd.DataFrame
frame: object
figures: dict
_lock = threading.RLock()
_live: Live | None = None
def _resolve() -> tuple[str, int, object]:
scenario = Scenario.load(DOMAIN, SCENARIO)
repositories = import_module(f"persistance.{DOMAIN}")
file = os.environ.get("CAMA_SURVIVAL_MODEL")
if file:
if not Path(file).is_file():
raise NotAvailable("no hay un modelo de supervivencia guardado")
resolved = SavedFile(file)
else:
try:
resolved = registry.resolve(DOMAIN, SCENARIO)
except LookupError as error:
raise NotAvailable("no hay una versión del modelo de supervivencia en producción") from error
build_id = repositories.cohort_repository.latest_build(scenario.cohort)
if build_id is None:
raise NotAvailable("no hay una cohorte armada para el modelo de supervivencia")
return resolved.version, int(build_id), resolved
def live() -> Live:
"""The production version over the latest build; loaded again only when either changed."""
global _live
version, build_id, resolved = _resolve()
with _lock:
if _live is None or (_live.version, _live.build_id) != (version, build_id):
saved = resolved.load() if isinstance(resolved, SavedFile) else mlflow.sklearn.load_model(resolved.model_uri)
model = seer_model.SeerSurvivalModel.rehydrate(saved)
cohort = KitBuild(DOMAIN, build_id).frame()
recoded = model.recode(cohort)
_live = Live(version, build_id, model, cohort, model.frame(recoded), {})
return _live
def scenarios() -> dict:
current = live()
return {"model_version": current.version, "build": current.build_id, "scenarios": current.model.scenario_names()}
def figure(scenario: str) -> dict:
"""The record of one scenario's figure; `KeyError` for a scenario the model doesn't define."""
current = live()
if scenario not in current.model.scenario_names():
raise KeyError(scenario)
with _lock:
if scenario not in current.figures:
settings = seer_model.figure_settings()
current.figures[scenario] = {
"model_version": current.version, "build": current.build_id,
**current.model.figure_record(
current.frame, scenario, ks_max_seconds=settings["ks_max_seconds"], n_boot=settings["n_boot"],
min_members=settings["min_members"], min_deaths=settings["min_deaths"])}
return current.figures[scenario]
def patient_scenarios(pac_id: int) -> dict:
"""The scenarios a patient belongs to, from her variables over the timeline (age, stage, subtype, surgery)."""
current = live()
events = current.cohort[current.cohort["pac_id"] == pac_id]
if events.empty:
raise KeyError(pac_id)
model = current.model
recoded = model.recode(events)
names = []
if len(recoded):
masks = model.scenario_masks(model.frame(recoded))
names = [name for name, mask in masks.items() if bool(mask[0])]
return {"model_version": current.version, "build": current.build_id, "pac_id": pac_id, "scenarios": names}
@@ -19,3 +19,21 @@ class BiopsiaMamaImportSchema(ImportSchema):
bx_grado_histologico: CatalogValue(_GRADO_HISTOLOGICO_MAMA_CATALOG) = None
bx_pdf_blob: Optional[bytes] = None
bx_ocr_confianza: Optional[float] = None
bx_tipo_histologico: Optional[str] = None
bx_grado_nottingham: Optional[str] = None
bx_receptor_estrogeno: Optional[str] = None
bx_receptor_estrogeno_pct: Optional[float] = None
bx_receptor_progesterona: Optional[str] = None
bx_receptor_progesterona_pct: Optional[float] = None
bx_her2: Optional[str] = None
bx_her2_fish: Optional[str] = None
bx_ki67_pct: Optional[float] = None
bx_tamano_tumor_mm: Optional[float] = None
bx_ganglios_positivos: Optional[float] = None
bx_invasion_linfovascular: Optional[str] = None
bx_multifocalidad: Optional[str] = None
bx_margenes: Optional[str] = None
bx_pt: Optional[str] = None
bx_pn: Optional[str] = None
bx_lateralidad: Optional[str] = None
bx_localizacion: Optional[str] = None
@@ -22,3 +22,6 @@ class MastografiaImportSchema(ImportSchema):
mast_birads: CatalogValue(_BIRADS_CATALOG) = None
mast_dicom_blob: Optional[bytes] = None
mast_interpretacion: Optional[str] = None
mast_densidad: Optional[str] = None
mast_margen_masa: Optional[str] = None
mast_tipo_hallazgo: Optional[str] = None
@@ -36,3 +36,5 @@ class NotaMedicaImportSchema(ImportSchema):
nm_presion_arterial_sistolica: Optional[int] = None
nm_presion_arterial_diastolica: Optional[int] = None
nm_temperatura: Optional[float] = None
nm_estadio_clinico: Optional[str] = None
nm_metastasis: Optional[str] = None
+14
View File
@@ -6,6 +6,7 @@ from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import (
Catalog,
CatalogValue,
FlexDate,
PostalCode,
RequiredDate,
RequiredHospitalId,
@@ -25,6 +26,19 @@ class PacienteImportSchema(ImportSchema):
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
# IND-01: required, since age at each event of interest is derived from it.
pac_fecha_nacimiento: RequiredDate
pac_fecha_defuncion: FlexDate = None
pac_codigo_postal: PostalCode = None
pac_dependencia: CatalogValue(_DEPENDENCIA_CATALOG) = None
pac_parentesco: CatalogValue(_PARENTESCO_CATALOG) = None
pac_estado_civil: Optional[str] = None
pac_raza: Optional[str] = None
pac_brca1: Optional[str] = None
pac_brca2: Optional[str] = None
pac_estado_menopausico: Optional[str] = None
pac_pam50: Optional[str] = None
pac_subtipo_clinico: Optional[str] = None
pac_cluster_integrativo: Optional[str] = None
pac_celularidad: Optional[str] = None
pac_carga_mutacional: Optional[float] = None
pac_ki67_categoria: Optional[str] = None
pac_fuente: Optional[str] = None
@@ -0,0 +1,13 @@
"""Import schema for `core.cama.models.SeguimientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class SeguimientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
seg_tipo: RequiredStr
seg_fecha: FlexDate = None
seg_detalle: Optional[str] = None
@@ -0,0 +1,14 @@
"""Import schema for `core.cama.models.TratamientoMama`."""
from typing import Optional
from webapi.imports.schemas.base import ImportSchema
from webapi.imports.schemas.coercion import FlexDate, RequiredHospitalId, RequiredStr
class TratamientoMamaImportSchema(ImportSchema):
pac_id: Optional[int] = None
pac_id_hospital: RequiredHospitalId
trat_tipo: RequiredStr
trat_fecha: FlexDate = None
trat_detalle: Optional[str] = None
trat_lateralidad: Optional[str] = None
+14
View File
@@ -18,6 +18,8 @@ from persistance.cacu import paciente_repository as cacu_paciente_repository
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
from persistance.cama import tratamiento_mama_repository as cama_tratamiento_mama_repository
from persistance.cama import seguimiento_mama_repository as cama_seguimiento_mama_repository
from persistance.cama import mastografia_repository as cama_mastografia_repository
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
@@ -51,6 +53,8 @@ from webapi.imports.schemas.cama.episodio_clinico import (
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
)
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
from webapi.imports.schemas.cama.tratamiento_mama import TratamientoMamaImportSchema
from webapi.imports.schemas.cama.seguimiento_mama import SeguimientoMamaImportSchema
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
from webapi.imports.schemas.cama.ordenes_estudio import (
OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema,
@@ -150,6 +154,16 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
repository=cama_biometria_hematica_repository,
conflict_fields=None,
),
"cama.TratamientoMama": EntitySpec(
schema=TratamientoMamaImportSchema,
repository=cama_tratamiento_mama_repository,
conflict_fields=None,
),
"cama.SeguimientoMama": EntitySpec(
schema=SeguimientoMamaImportSchema,
repository=cama_seguimiento_mama_repository,
conflict_fields=None,
),
"cama.EpisodioClinico": EntitySpec(
schema=CamaEpisodioClinicoImportSchema,
repository=cama_episodio_clinico_repository,
+81 -8
View File
@@ -4,10 +4,10 @@
derivadas. La lee `plata_desde_staging` (`plata.carga.carga_desde_staging`).
"""
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente, SeguimientoMama, TratamientoMama
from core.cama.nota_medica.enums import ESPECIALIDAD_ALIAS, Especialidad
from webapi.orchestration.silver.extracted import DesdeTexto
from webapi.orchestration.silver.extracted import ConEstructurado, DesdeTexto
from webapi.orchestration.silver.orders_and_notes import nota_medica, orden_de_estudio
from webapi.orchestration.silver.procedures import DeStaging, Hija, Padre
@@ -36,11 +36,39 @@ DEL_REPORTE_DE_PATOLOGIA = DesdeTexto(
"biopsia.her2", "biopsia.ki67_pct"),
texto=lambda f: f.bx_pdf_blob,
)
DE_LA_MASTOGRAFIA = ConEstructurado(DE_LA_INTERPRETACION, {"mastografia.densidad": "mast_densidad"})
# A mammogram's findings, each a part of its report.
LOS_HALLAZGOS = (
Hija("mastografia", "parte", solo_si=("mast_margen_masa",), fecha="mast_fecha_reporte",
resultados={"mast_margen_masa": "mastografia.margen_masa"}),
Hija("mastografia", "parte", solo_si=("mast_tipo_hallazgo",), fecha="mast_fecha_reporte",
resultados={"mast_tipo_hallazgo": "mastografia.tipo_hallazgo"}),
)
DE_LA_NOTA = DesdeTexto(
"cama", ("nota_medica.estadio_clinico",),
texto=lambda f: "\n".join(t for t in (f.nm_diagnostico_texto, f.nm_pronostico) if t),
)
# What a biopsy report and a note carry structured wins over the text's reading; the rest is read from the text.
DE_LA_PATOLOGIA = ConEstructurado(DEL_REPORTE_DE_PATOLOGIA, {
"biopsia.tipo_histologico": "bx_tipo_histologico", "biopsia.grado_nottingham": "bx_grado_nottingham",
"biopsia.receptor_estrogeno": "bx_receptor_estrogeno", "biopsia.receptor_estrogeno_pct": "bx_receptor_estrogeno_pct",
"biopsia.receptor_progesterona": "bx_receptor_progesterona",
"biopsia.receptor_progesterona_pct": "bx_receptor_progesterona_pct", "biopsia.her2": "bx_her2",
"biopsia.ki67_pct": "bx_ki67_pct", "biopsia.her2_fish": "bx_her2_fish",
"biopsia.tamano_tumor_mm": "bx_tamano_tumor_mm", "biopsia.ganglios_positivos": "bx_ganglios_positivos",
"biopsia.invasion_linfovascular": "bx_invasion_linfovascular", "biopsia.multifocalidad": "bx_multifocalidad",
"biopsia.margenes": "bx_margenes", "biopsia.pt": "bx_pt", "biopsia.pn": "bx_pn",
})
DE_LA_NOTA_ESTRUCTURADA = ConEstructurado(DE_LA_NOTA, {
"nota_medica.estadio_clinico": "nm_estadio_clinico", "nota_medica.m": "nm_metastasis",
})
# The biopsy's sample: the breast and the site it was taken from, dated by its request or, without one, its report.
LA_TOMA_DE_LA_BIOPSIA = Hija(
"biopsia", "toma", solo_si=("bx_lateralidad", "bx_localizacion"), fecha="bx_fecha_toma",
resultados={"bx_lateralidad": "biopsia.lateralidad", "bx_localizacion": "biopsia.localizacion"},
)
DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "toma", estudio_id="mastografia", fecha="mast_fecha_toma",
@@ -51,17 +79,62 @@ DESDE_STAGING = (
DeStaging(
Mastografia, "mast_id", "reporte", estudio_id="mastografia", fecha="mast_fecha_reporte",
solo_si=lambda f: f.mast_fecha_reporte is not None, padres=(LA_MASTOGRAFIA_DE_SU_FILA,),
derivadas=DE_LA_INTERPRETACION.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_INTERPRETACION.resultados},
fuentes=DE_LA_INTERPRETACION.fuentes,
derivadas=DE_LA_MASTOGRAFIA.derivadas,
resultados={"mast_birads": "mastografia.birads", **DE_LA_MASTOGRAFIA.resultados},
fuentes=DE_LA_MASTOGRAFIA.fuentes, hijas=LOS_HALLAZGOS,
),
DeStaging(
BiopsiaMama, "bx_id", "orden", estudio_id="biopsia", fecha="bx_fecha_solicitud",
solo_si=_biopsia_que_pasa, padres=(LA_MASTOGRAFIA_DE_SU_FILA,), columnas={"orden_numero": "ord_numero_hospital"},
derivadas=DEL_REPORTE_DE_PATOLOGIA.derivadas, fuentes=DEL_REPORTE_DE_PATOLOGIA.fuentes,
derivadas={**DE_LA_PATOLOGIA.derivadas,
"bx_fecha_toma": lambda f: f.bx_fecha_solicitud or f.bx_fecha_reporte},
fuentes=DE_LA_PATOLOGIA.fuentes,
hijas=(Hija("biopsia", "reporte", solo_si=("bx_fecha_reporte",), fecha="bx_fecha_reporte",
resultados={"bx_grado_histologico": "biopsia.grado", **DEL_REPORTE_DE_PATOLOGIA.resultados}),),
resultados={"bx_grado_histologico": "biopsia.grado", **DE_LA_PATOLOGIA.resultados}),
LA_TOMA_DE_LA_BIOPSIA),
),
orden_de_estudio(OrdenesEstudio, ESPECIALIDAD_ALIAS, ESPECIALIDADES),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA),
nota_medica(NotaMedica, ESPECIALIDAD_ALIAS, ESPECIALIDADES, extraidos=DE_LA_NOTA_ESTRUCTURADA),
# Facts of the patient with no date of their own: dated at her birth, known as of the load.
DeStaging(
Paciente, "pac_id", "parte", estudio_id="sociodemografico", fecha="pac_fecha_nacimiento",
resultados={"pac_estado_civil": "sociodemografico.estado_civil", "pac_raza": "sociodemografico.raza",
"pac_estado_menopausico": "sociodemografico.estado_menopausico",
"pac_fuente": "sociodemografico.fuente"},
),
DeStaging(
Paciente, "pac_id", "reporte", estudio_id="prueba_genetica", fecha="pac_fecha_nacimiento",
solo_si=lambda f: f.pac_brca1 is not None or f.pac_brca2 is not None,
resultados={"pac_brca1": "prueba_genetica.brca1", "pac_brca2": "prueba_genetica.brca2"},
),
*(
DeStaging(
TratamientoMama, "trat_id", "encuentro", estudio_id=estudio, fecha="trat_fecha",
solo_si=lambda f, e=estudio: f.trat_tipo == e,
resultados={"trat_detalle": resultado, **({"trat_lateralidad": "cirugia.lateralidad"} if estudio == "cirugia" else {})},
)
for estudio, resultado in (
("cirugia", "cirugia.tipo_cirugia"), ("radioterapia", "radioterapia.intencion"),
("quimioterapia", "quimioterapia.intencion"), ("hormonoterapia", "hormonoterapia.intencion"),
("anti_her2", "anti_her2.intencion"),
)
),
*(
DeStaging(
SeguimientoMama, "seg_id", "encuentro", estudio_id=estudio, fecha="seg_fecha",
solo_si=lambda f, e=estudio: f.seg_tipo == e, resultados={"seg_detalle": resultado},
)
for estudio, resultado in (("recurrencia", "recurrencia.sitio"), ("ultimo_contacto", "ultimo_contacto.estado"))
),
DeStaging(
Paciente, "pac_id", "parte", estudio_id="perfil_molecular", fecha="pac_fecha_nacimiento",
solo_si=lambda f: any(getattr(f, c) is not None for c in (
"pac_pam50", "pac_subtipo_clinico", "pac_cluster_integrativo", "pac_celularidad", "pac_carga_mutacional",
"pac_ki67_categoria")),
resultados={"pac_pam50": "perfil_molecular.pam50", "pac_subtipo_clinico": "perfil_molecular.subtipo_clinico",
"pac_cluster_integrativo": "perfil_molecular.cluster_integrativo",
"pac_celularidad": "perfil_molecular.celularidad",
"pac_carga_mutacional": "perfil_molecular.carga_mutacional",
"pac_ki67_categoria": "perfil_molecular.ki67_categoria"},
),
)
+39
View File
@@ -117,3 +117,42 @@ def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
if texto is not None and str(texto.value).strip():
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
return None, None
@dataclass(frozen=True)
class ConEstructurado:
"""`DesdeTexto` whose results the row may carry already structured: a structured column wins over what the text
gives, and a column with no text twin is a result of its own. `estructurados`: result -> staging column;
each result keeps the text reading as its fallback when `lector` has it."""
lector: DesdeTexto | None
estructurados: dict[str, str]
@property
def derivadas(self) -> dict[str, Callable]:
columnas = dict(self.lector.derivadas) if self.lector else {}
leidos = set(self.lector.resultado_ids) if self.lector else set()
for resultado_id, columna in self.estructurados.items():
clave = _columna(resultado_id)
texto = self.lector.derivadas[clave] if resultado_id in leidos else (lambda f: None)
fuente = self.lector.derivadas[clave + "_fuente"] if resultado_id in leidos else (lambda f: None)
columnas[clave] = lambda f, c=columna, t=texto: _con_valor(getattr(f, c, None), t(f))
columnas[clave + "_fuente"] = lambda f, c=columna, t=fuente: (
None if _vacio(getattr(f, c, None)) else t(f))
return columnas
@property
def resultados(self) -> dict[str, str]:
return {_columna(r): r for r in {*(self.lector.resultado_ids if self.lector else ()), *self.estructurados}}
@property
def fuentes(self) -> dict[str, str]:
return {columna: columna + "_fuente" for columna in self.resultados}
def _vacio(valor) -> bool:
return valor is None or (isinstance(valor, str) and not valor.strip())
def _con_valor(estructurado, leido):
return leido if _vacio(estructurado) else estructurado
+1
View File
@@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict:
"dependencia": texto_limpio(paciente.pac_dependencia),
"parentesco": texto_limpio(paciente.pac_parentesco),
"codigo_postal": texto_limpio(paciente.pac_codigo_postal),
"fecha_defuncion": paciente.pac_fecha_defuncion,
}