bioage-es 1.0.2__py3-none-any.whl
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.
- bioage/README.md +11 -0
- bioage/__init__.py +1 -0
- bioage/app/README.md +15 -0
- bioage/app/__init__.py +1 -0
- bioage/app/api.py +232 -0
- bioage/app/calculate.py +106 -0
- bioage/app/cmd_predict.py +52 -0
- bioage/app/correct.py +38 -0
- bioage/app/logs.py +120 -0
- bioage/app/pdf_reader/README.md +13 -0
- bioage/app/pdf_reader/__init__.py +1 -0
- bioage/app/pdf_reader/convert_units.py +40 -0
- bioage/app/pdf_reader/estimate_missing.py +56 -0
- bioage/app/pdf_reader/extract_values.py +463 -0
- bioage/app/pdf_reader/find_sections.py +50 -0
- bioage/app/pdf_reader/pdf_to_table.py +172 -0
- bioage/app/pdf_reader/read_patient.py +203 -0
- bioage/app/pdf_reader/read_pdf.py +96 -0
- bioage/app/pdf_reader/standardize_names.py +154 -0
- bioage/app/predict.py +81 -0
- bioage/app/schemas.py +132 -0
- bioage/app/utils.py +62 -0
- bioage/app/validation.py +98 -0
- bioage/config/README.md +23 -0
- bioage/config/__init__.py +1 -0
- bioage/config/app.py +54 -0
- bioage/config/biomarker_names.py +167 -0
- bioage/config/biomarker_units.py +102 -0
- bioage/config/corrections.py +45 -0
- bioage/config/gold_columns.py +43 -0
- bioage/config/model_levels.py +99 -0
- bioage/config/nhanes_codes.py +39 -0
- bioage/config/paths.py +30 -0
- bioage/config/pdf_settings.py +47 -0
- bioage/config/phenoage.py +52 -0
- bioage/config/plausible_ranges.py +71 -0
- bioage/config/renames.py +96 -0
- bioage/config/sources.py +69 -0
- bioage/config/study.py +96 -0
- bioage/config/validation_rules.py +35 -0
- bioage/main.py +29 -0
- bioage/modeling/README.md +13 -0
- bioage/modeling/__init__.py +1 -0
- bioage/modeling/s1_split.py +51 -0
- bioage/modeling/s2_preprocessing.py +203 -0
- bioage/modeling/s3_algorithms.py +108 -0
- bioage/modeling/s4_biological_age.py +180 -0
- bioage/modeling/s5_evaluation.py +436 -0
- bioage/modeling/s6_group_years.py +141 -0
- bioage/modeling/s7_margin.py +225 -0
- bioage/models/README.md +8 -0
- bioage/models/extras.joblib +0 -0
- bioage/models/full.joblib +0 -0
- bioage/models/questionnaire.joblib +0 -0
- bioage/models/routine.joblib +0 -0
- bioage/pipeline/README.md +10 -0
- bioage/pipeline/__init__.py +1 -0
- bioage/pipeline/s1_download_bronze.py +181 -0
- bioage/pipeline/s2_build_raw_silver.py +176 -0
- bioage/pipeline/s3_build_clean_silver.py +447 -0
- bioage/pipeline/s4_build_gold.py +51 -0
- bioage/pipeline/s5_build_model.py +70 -0
- bioage/utils/README.md +11 -0
- bioage/utils/__init__.py +1 -0
- bioage/utils/data_download.py +91 -0
- bioage/utils/features.py +81 -0
- bioage/utils/nhanes.py +74 -0
- bioage/utils/notebook_helpers.py +137 -0
- bioage/utils/phenoage.py +94 -0
- bioage/utils/provenance.py +85 -0
- bioage/utils/step_info.py +60 -0
- bioage/utils/validation.py +280 -0
- bioage_es-1.0.2.dist-info/METADATA +199 -0
- bioage_es-1.0.2.dist-info/RECORD +77 -0
- bioage_es-1.0.2.dist-info/WHEEL +4 -0
- bioage_es-1.0.2.dist-info/entry_points.txt +4 -0
- bioage_es-1.0.2.dist-info/licenses/LICENSE +661 -0
bioage/README.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# bioage/
|
|
2
|
+
|
|
3
|
+
The project package: from the NHANES download to the biological age of a person.
|
|
4
|
+
|
|
5
|
+
- `main.py`: entry point of the pipeline, runs every step in order (`uv run bioage-train`); the prediction command is `app/cmd_predict.py` (`uv run bioage-predict`), apart because the app does not install the pipeline libraries.
|
|
6
|
+
- `config/`: paths, external sources and study tables. No logic.
|
|
7
|
+
- `pipeline/`: one file per step, numbered, each with its `run()`.
|
|
8
|
+
- `modeling/`: the steps of the model.
|
|
9
|
+
- `models/`: the trained model of each level, inside the package so that it travels with it.
|
|
10
|
+
- `app/`: what the app runs, starting with `predict.py`.
|
|
11
|
+
- `utils/`: functions shared across the project, one file per topic.
|
bioage/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Biological age calculator from a routine blood test (+ optional questionnaire)."""
|
bioage/app/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# app/
|
|
2
|
+
What the app runs:
|
|
3
|
+
|
|
4
|
+
- `api.py`: Web server; receives the requests and hands them to the rest.
|
|
5
|
+
- `schemas.py`: What enters and leaves each endpoint, and its error.
|
|
6
|
+
- `calculate.py`: Picks the model and calculates the result.
|
|
7
|
+
- `correct.py`: Values the user corrected, in model units, and those still impossible.
|
|
8
|
+
- `validation.py`: Checks before calculating.
|
|
9
|
+
- `predict.py`: Loads a saved model and computes the biological age.
|
|
10
|
+
- `cmd_predict.py`: Only for the `bioage-predict` command: the result of the people in a JSON file, without the web.
|
|
11
|
+
- `utils.py`: Functions shared within the app.
|
|
12
|
+
- `logs.py`: One line of JSON per request, with nothing of the user.
|
|
13
|
+
- `pdf_reader/`: Reads a blood test in PDF: the values of the model, and age and sex if it has them.
|
|
14
|
+
|
|
15
|
+
Run it with `uv run uvicorn bioage.app.api:app --reload`; the endpoints can be tried at http://127.0.0.1:8000/docs.
|
bioage/app/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""What the app runs: prediction with a saved model."""
|
bioage/app/api.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""Web server of the app: receives the requests and hands them to the code that does the work.
|
|
2
|
+
|
|
3
|
+
Endpoints:
|
|
4
|
+
- POST /api/read?mode=quick|full: PDF → Reading
|
|
5
|
+
- POST /api/correct: list of OddValue → Correction
|
|
6
|
+
- POST /api/calculate: Person → Result
|
|
7
|
+
- GET /api/health: the server is running
|
|
8
|
+
- Everything else: the web interface built by npm, if it is built
|
|
9
|
+
|
|
10
|
+
Errors:
|
|
11
|
+
- AppError: Give its code.
|
|
12
|
+
- DataError: Give the field that doesn't match the schema.
|
|
13
|
+
|
|
14
|
+
Logs: one line of JSON per request, with nothing of the user (see logs.py).
|
|
15
|
+
|
|
16
|
+
NOTE: Nothing is stored; between requests, the browser keeps the values.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
# Imports
|
|
20
|
+
import time
|
|
21
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
22
|
+
from contextlib import asynccontextmanager
|
|
23
|
+
from os import stat_result
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from fastapi import FastAPI, Request
|
|
27
|
+
from fastapi.concurrency import run_in_threadpool
|
|
28
|
+
from fastapi.exceptions import RequestValidationError
|
|
29
|
+
from fastapi.responses import JSONResponse, Response
|
|
30
|
+
from fastapi.staticfiles import StaticFiles
|
|
31
|
+
from starlette.types import Scope
|
|
32
|
+
|
|
33
|
+
from bioage.app.calculate import calculate, choose_level
|
|
34
|
+
from bioage.app.correct import correct_values
|
|
35
|
+
from bioage.app.logs import crash_place, note, setup_logs, write_line
|
|
36
|
+
from bioage.app.pdf_reader.read_pdf import read_pdf
|
|
37
|
+
from bioage.app.predict import load_bundle
|
|
38
|
+
from bioage.app.schemas import AppError, Correction, Mode, OddValue, Person, Reading, Result
|
|
39
|
+
from bioage.app.utils import extras_known, max_missing, routine_missing
|
|
40
|
+
from bioage.config.model_levels import LEVEL_COLUMNS
|
|
41
|
+
from bioage.config.paths import FRONTEND_BUILD
|
|
42
|
+
from bioage.config.pdf_settings import MAX_PDF_MB
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@asynccontextmanager
|
|
46
|
+
async def load_models(app: FastAPI) -> AsyncIterator[None]:
|
|
47
|
+
"""Load the models and set the logs once, when the server starts.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
app: The web server.
|
|
51
|
+
|
|
52
|
+
Yields:
|
|
53
|
+
Nothing: the server runs meanwhile.
|
|
54
|
+
"""
|
|
55
|
+
setup_logs()
|
|
56
|
+
app.state.bundles = {level: load_bundle(level) for level in LEVEL_COLUMNS}
|
|
57
|
+
yield
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
app = FastAPI(title="BioAge", lifespan=load_models)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@app.middleware("http")
|
|
64
|
+
async def log_requests(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:
|
|
65
|
+
"""Write one line per request of the API, also when the code fails; the health check is left out.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
request: The request.
|
|
69
|
+
call_next: What answers it.
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
The answer.
|
|
73
|
+
"""
|
|
74
|
+
if not request.url.path.startswith("/api/") or request.url.path == "/api/health":
|
|
75
|
+
return await call_next(request)
|
|
76
|
+
if request.url.path not in {route.path for route in app.routes}:
|
|
77
|
+
note(request, endpoint="unknown") # the path is written by whoever calls
|
|
78
|
+
started = time.perf_counter()
|
|
79
|
+
try:
|
|
80
|
+
response = await call_next(request)
|
|
81
|
+
except Exception as error:
|
|
82
|
+
note(request, error="crash", where=crash_place(error))
|
|
83
|
+
write_line(request, 500, started)
|
|
84
|
+
raise
|
|
85
|
+
write_line(request, response.status_code, started)
|
|
86
|
+
return response
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@app.post("/api/read")
|
|
90
|
+
async def post_read(request: Request, mode: Mode) -> Reading:
|
|
91
|
+
"""PDF (raw body) → what was read from it.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
request: Request with the PDF as its body.
|
|
95
|
+
mode: Mode the user chose.
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
What was read.
|
|
99
|
+
"""
|
|
100
|
+
note(request, mode=mode)
|
|
101
|
+
most = max_missing(request.app.state.bundles, mode)
|
|
102
|
+
reading = await run_in_threadpool(read_pdf, await body_in_memory(request), most)
|
|
103
|
+
known = set(reading.lab_values) | {odd.variable for odd in reading.odd}
|
|
104
|
+
note(request, missing=routine_missing(known), extras=extras_known(known))
|
|
105
|
+
return reading
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
async def body_in_memory(request: Request) -> bytes:
|
|
109
|
+
"""Body of a request, kept in memory (a file form is written to disk above 1 MB).
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
request: The request.
|
|
113
|
+
|
|
114
|
+
Returns:
|
|
115
|
+
Its body.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
AppError: If it is larger than the largest PDF accepted.
|
|
119
|
+
"""
|
|
120
|
+
body = bytearray()
|
|
121
|
+
async for chunk in request.stream():
|
|
122
|
+
body += chunk
|
|
123
|
+
if len(body) > MAX_PDF_MB * 1024**2:
|
|
124
|
+
raise AppError("unreadable")
|
|
125
|
+
return bytes(body)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@app.post("/api/correct")
|
|
129
|
+
def post_correct(odd: list[OddValue]) -> Correction:
|
|
130
|
+
"""Values corrected by the user → in model units, or odd again if still impossible.
|
|
131
|
+
|
|
132
|
+
Args:
|
|
133
|
+
odd: Odd values, with the text the user wrote.
|
|
134
|
+
|
|
135
|
+
Returns:
|
|
136
|
+
What was corrected and what is still odd.
|
|
137
|
+
"""
|
|
138
|
+
return correct_values(odd)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@app.post("/api/calculate")
|
|
142
|
+
def post_calculate(person: Person, request: Request) -> Result:
|
|
143
|
+
"""Data of a person → result.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
person: Data of the person.
|
|
147
|
+
request: The request, to reach the models.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Result to show.
|
|
151
|
+
"""
|
|
152
|
+
known = set(person.lab_values)
|
|
153
|
+
level = choose_level(person, request.app.state.bundles)
|
|
154
|
+
model = request.app.state.bundles[level]["trained_on"]["code"]
|
|
155
|
+
note(request, mode=person.mode, level=level, model=model)
|
|
156
|
+
note(request, missing=routine_missing(known), extras=extras_known(known))
|
|
157
|
+
return calculate(person, request.app.state.bundles)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
@app.get("/api/health")
|
|
161
|
+
def get_health() -> dict[str, str]:
|
|
162
|
+
"""Tell that the server is running.
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
Its status.
|
|
166
|
+
"""
|
|
167
|
+
return {"status": "ok"}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
@app.exception_handler(AppError)
|
|
171
|
+
def tell_error(request: Request, error: AppError) -> JSONResponse:
|
|
172
|
+
"""Error of the app → its code, for the front.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
request: The request that failed.
|
|
176
|
+
error: The error.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
Answer with the code.
|
|
180
|
+
"""
|
|
181
|
+
note(request, error=error.code)
|
|
182
|
+
return JSONResponse({"error": error.code}, status_code=422)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@app.exception_handler(RequestValidationError)
|
|
186
|
+
def tell_invalid_fields(request: Request, error: RequestValidationError) -> JSONResponse:
|
|
187
|
+
"""Data that does not match the schema → the fields at fault, without repeating their values.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
request: The request that failed.
|
|
191
|
+
error: The error.
|
|
192
|
+
|
|
193
|
+
Returns:
|
|
194
|
+
Answer with the fields.
|
|
195
|
+
"""
|
|
196
|
+
note(request, error="invalid")
|
|
197
|
+
fields = [{"field": list(detail["loc"]), "message": detail["msg"]} for detail in error.errors()]
|
|
198
|
+
return JSONResponse({"invalid": fields}, status_code=422)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class FrontFiles(StaticFiles):
|
|
202
|
+
"""Files of the web interface, which the browser checks again on every visit."""
|
|
203
|
+
|
|
204
|
+
def file_response(self, full_path: str, stat: stat_result, scope: Scope, status_code: int = 200) -> Response:
|
|
205
|
+
"""Answer with a file, asking the browser not to use it before checking it is still the same.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
full_path: Where the file is.
|
|
209
|
+
stat: Its size and dates.
|
|
210
|
+
scope: The request.
|
|
211
|
+
status_code: Code of the answer.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
The file.
|
|
215
|
+
"""
|
|
216
|
+
response = super().file_response(full_path, stat, scope, status_code)
|
|
217
|
+
response.headers["Cache-Control"] = "no-cache" # after a deploy, an old page would ask for files gone
|
|
218
|
+
return response
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def serve_front(server: FastAPI, build: Path) -> None:
|
|
222
|
+
"""Serve the web interface at the root, after the API, so that the API answers first.
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
server: The web server.
|
|
226
|
+
build: Folder with the built interface; if it does not exist (tests, development with Vite), nothing.
|
|
227
|
+
"""
|
|
228
|
+
if build.is_dir():
|
|
229
|
+
server.mount("/", FrontFiles(directory=build, html=True), name="front")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
serve_front(app, FRONTEND_BUILD)
|
bioage/app/calculate.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Person → result: picks the model and calculates the biological age, its margin and the years of each group."""
|
|
2
|
+
|
|
3
|
+
# Imports
|
|
4
|
+
import math
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import pandas as pd
|
|
8
|
+
|
|
9
|
+
from bioage.app.predict import predict_age, predict_groups, predict_risk
|
|
10
|
+
from bioage.app.schemas import Person, Result
|
|
11
|
+
from bioage.app.utils import bmi, extras_known, max_missing, routine_missing
|
|
12
|
+
from bioage.app.validation import check_person
|
|
13
|
+
from bioage.config.app import BLOOD_GROUPS, EXTRAS_LEVELS, HABIT_GROUPS, MODE_LEVELS
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def calculate(person: Person, bundles: dict[str, dict]) -> Result:
|
|
17
|
+
"""Biological age of a person, with the model their data allow.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
person: Data of the person.
|
|
21
|
+
bundles: Bundle of each level.
|
|
22
|
+
|
|
23
|
+
Returns:
|
|
24
|
+
Result to show.
|
|
25
|
+
|
|
26
|
+
Raises:
|
|
27
|
+
AppError: If no age can be calculated with those data.
|
|
28
|
+
"""
|
|
29
|
+
check_person(person, max_missing(bundles, person.mode))
|
|
30
|
+
bundle = bundles[choose_level(person, bundles)]
|
|
31
|
+
row = model_row(person, bundle["columns"])
|
|
32
|
+
years = predict_groups(bundle, row)
|
|
33
|
+
return Result( # age and margin unrounded: the front rounds them once, to whole years
|
|
34
|
+
age=person.age,
|
|
35
|
+
bio_age=float(predict_age(bundle, row)[0]),
|
|
36
|
+
margin=float(margin(person, bundle, predict_risk(bundle, row)[0])),
|
|
37
|
+
blood={group: one_decimal(years.get(group)) for group in BLOOD_GROUPS},
|
|
38
|
+
habits=None if person.habits is None else {group: one_decimal(years[group]) for group in HABIT_GROUPS},
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def choose_level(person: Person, bundles: dict[str, dict]) -> str:
|
|
43
|
+
"""Level whose model is used: with Extras if there are enough of them to make it better.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
person: Data of the person.
|
|
47
|
+
bundles: Bundle of each level.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Name of the level.
|
|
51
|
+
"""
|
|
52
|
+
level = MODE_LEVELS[person.mode]
|
|
53
|
+
with_extras = EXTRAS_LEVELS[level]
|
|
54
|
+
is_enough = extras_known(set(person.lab_values)) >= bundles[with_extras]["margin"]["min_extras"]
|
|
55
|
+
return with_extras if is_enough else level
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def margin(person: Person, bundle: dict, risk: float) -> float:
|
|
59
|
+
"""Margin ± of the biological age: base error and error for what is missing, from the bundle of the level.
|
|
60
|
+
|
|
61
|
+
Args:
|
|
62
|
+
person: Data of the person.
|
|
63
|
+
bundle: Bundle of the level used.
|
|
64
|
+
risk: 10-year risk of the person.
|
|
65
|
+
|
|
66
|
+
Returns:
|
|
67
|
+
Years.
|
|
68
|
+
"""
|
|
69
|
+
parts = bundle["margin"]
|
|
70
|
+
base = np.interp(risk, parts["base"]["risk"], parts["base"]["years"]) # straight lines between tenths
|
|
71
|
+
known = set(person.lab_values)
|
|
72
|
+
missing = parts["routine_missing"][routine_missing(known)]
|
|
73
|
+
extras = parts["extras_known"][extras_known(known)] if "extras_known" in parts else 0
|
|
74
|
+
return math.sqrt(base**2 + missing**2 + extras**2)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def model_row(person: Person, columns: list[str]) -> pd.DataFrame:
|
|
78
|
+
"""Table of one person with the columns of a model; what is not known stays missing.
|
|
79
|
+
|
|
80
|
+
Args:
|
|
81
|
+
person: Data of the person.
|
|
82
|
+
columns: Columns of the model.
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
One row.
|
|
86
|
+
"""
|
|
87
|
+
known = {
|
|
88
|
+
**person.lab_values,
|
|
89
|
+
"age": person.age,
|
|
90
|
+
"sex": person.sex,
|
|
91
|
+
"bmi": bmi(person.weight, person.height),
|
|
92
|
+
**({} if person.habits is None else person.habits.model_dump()),
|
|
93
|
+
}
|
|
94
|
+
return pd.DataFrame([{column: known.get(column, np.nan) for column in columns}])
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def one_decimal(years: float | None) -> float | None:
|
|
98
|
+
"""Years with one decimal, never -0.0.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
years: Years, or None if there are no data.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
The rounded years.
|
|
105
|
+
"""
|
|
106
|
+
return None if years is None else round(float(years), 1) + 0.0
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Only for the `bioage-predict` command: JSON file with one person or a list → one line of JSON per person.
|
|
2
|
+
|
|
3
|
+
Run it with `uv run bioage-predict <file>.json` (example: `docs/example_person.json`). The app's calculation
|
|
4
|
+
without the web; the web server does the same through `api.py`.
|
|
5
|
+
|
|
6
|
+
- `predict` : Print one line per person in the file given
|
|
7
|
+
- `answer` : One person → their result, or why it cannot be calculated
|
|
8
|
+
|
|
9
|
+
NOTE: It lives in app/ and not in main.py, next to the training command: main.py imports the pipeline, whose
|
|
10
|
+
libraries the app (Docker, Vercel) does not install.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
# Imports
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
|
|
20
|
+
from bioage.app.calculate import calculate
|
|
21
|
+
from bioage.app.predict import load_bundle
|
|
22
|
+
from bioage.app.schemas import AppError, Person
|
|
23
|
+
from bioage.config.model_levels import LEVEL_COLUMNS
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def predict() -> None:
|
|
27
|
+
"""Print one line per person in the JSON file given (one person or a list): their result, or why not."""
|
|
28
|
+
parser = argparse.ArgumentParser(description="Biological age of the people in a JSON file.")
|
|
29
|
+
parser.add_argument("file", type=Path, help="JSON with one person or a list, as /api/calculate receives them")
|
|
30
|
+
people = json.loads(parser.parse_args().file.read_text(encoding="utf-8"))
|
|
31
|
+
bundles = {level: load_bundle(level) for level in LEVEL_COLUMNS}
|
|
32
|
+
for raw in people if isinstance(people, list) else [people]:
|
|
33
|
+
print(answer(raw, bundles))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def answer(raw: dict, bundles: dict[str, dict]) -> str:
|
|
37
|
+
"""One person → their result as one line of JSON, or the reason why it cannot be calculated.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
raw: Data of the person, as written in the file.
|
|
41
|
+
bundles: Bundle of each level.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
The result; {"invalid": fields} if the data do not match the schema; {"error": code} if the app cannot
|
|
45
|
+
calculate. The same as the API answers.
|
|
46
|
+
"""
|
|
47
|
+
try:
|
|
48
|
+
return calculate(Person.model_validate(raw), bundles).model_dump_json()
|
|
49
|
+
except ValidationError as error:
|
|
50
|
+
return json.dumps({"invalid": [".".join(map(str, detail["loc"])) for detail in error.errors()]})
|
|
51
|
+
except AppError as error:
|
|
52
|
+
return json.dumps({"error": error.code})
|
bioage/app/correct.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""Values the user corrected → in model units, and those still impossible.
|
|
2
|
+
|
|
3
|
+
- `correct_values` : Each corrected value into lab_values if it is possible now, or back to odd.
|
|
4
|
+
- `lab_number` : Text as a lab writes it ("4,5") → number.
|
|
5
|
+
|
|
6
|
+
The unit of each value is the one of the PDF, and its factor comes from the table of the parser.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
# Imports
|
|
10
|
+
from bioage.app.pdf_reader.convert_units import unit_factor
|
|
11
|
+
from bioage.app.schemas import Correction, OddValue
|
|
12
|
+
from bioage.app.validation import is_possible
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def correct_values(odd: list[OddValue]) -> Correction:
|
|
16
|
+
"""Values the user corrected, each in model units if it is possible now, or odd again.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
odd: Odd values, with the text the user wrote.
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
What was corrected and what is still odd.
|
|
23
|
+
"""
|
|
24
|
+
corrected = {value.variable: lab_number(value.text) * unit_factor(value.variable, value.unit) for value in odd}
|
|
25
|
+
possible = {variable: value for variable, value in corrected.items() if is_possible(variable, value)}
|
|
26
|
+
return Correction(lab_values=possible, odd=[value for value in odd if value.variable not in possible])
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def lab_number(text: str) -> float:
|
|
30
|
+
"""Text as a lab writes it → number.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
text: E.g. "4,5" or "4.5".
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
The number.
|
|
37
|
+
"""
|
|
38
|
+
return float(text.strip().replace(",", "."))
|
bioage/app/logs.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""One line of JSON per request of the app, with nothing of the user.
|
|
2
|
+
|
|
3
|
+
- `setup_logs` : Logger of the requests in JSON; uvicorn stops writing the IP and the message of a crash.
|
|
4
|
+
- `note` : Add fields to the line of a request, from the code that handles it.
|
|
5
|
+
- `write_line` : Write the line of a finished request.
|
|
6
|
+
- `crash_place` : Kind of error and file:line of a crash, without its message.
|
|
7
|
+
- `JsonFormatter` : A log record → one line of JSON.
|
|
8
|
+
- `NoMessage` : A crash written by uvicorn → only its kind and place.
|
|
9
|
+
|
|
10
|
+
NOTE: Only what helps to see why the app fails: endpoint, mode, level, model, result, error code, where it
|
|
11
|
+
crashed, how many Routine values are missing, how many Extras there are and time. Never values, age, sex,
|
|
12
|
+
weight, height, biological age, margin, variable names, IP or the message of an error (it can carry values).
|
|
13
|
+
Severity by the answer: ERROR if the code failed (5xx), WARNING if the request was refused (4xx), INFO otherwise.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
# Imports
|
|
17
|
+
import json
|
|
18
|
+
import logging
|
|
19
|
+
import sys
|
|
20
|
+
import time
|
|
21
|
+
import traceback
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from fastapi import Request
|
|
25
|
+
|
|
26
|
+
logger = logging.getLogger("bioage.requests")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def setup_logs() -> None:
|
|
30
|
+
"""Requests → JSON on the standard output, where the hosting shows it; uvicorn writes no IP nor messages."""
|
|
31
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
32
|
+
handler.setFormatter(JsonFormatter())
|
|
33
|
+
logger.handlers = [handler]
|
|
34
|
+
logger.setLevel(logging.INFO)
|
|
35
|
+
logger.propagate = False
|
|
36
|
+
logging.getLogger("uvicorn.access").disabled = True
|
|
37
|
+
uvicorn_errors = logging.getLogger("uvicorn.error")
|
|
38
|
+
if not any(isinstance(kept, NoMessage) for kept in uvicorn_errors.filters):
|
|
39
|
+
uvicorn_errors.addFilter(NoMessage())
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def note(request: Request, **fields: object) -> None:
|
|
43
|
+
"""Add fields to the line of a request.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
request: The request.
|
|
47
|
+
**fields: Name → value.
|
|
48
|
+
"""
|
|
49
|
+
request.state.log = {**getattr(request.state, "log", {}), **fields}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def write_line(request: Request, status_code: int, started: float) -> None:
|
|
53
|
+
"""Write the line of a finished request.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
request: The request.
|
|
57
|
+
status_code: HTTP status of the answer.
|
|
58
|
+
started: When it began (time.perf_counter).
|
|
59
|
+
"""
|
|
60
|
+
fields = {
|
|
61
|
+
"endpoint": request.url.path.removeprefix("/api/"),
|
|
62
|
+
"status": "ok" if status_code < 400 else "error",
|
|
63
|
+
"error": None,
|
|
64
|
+
**getattr(request.state, "log", {}),
|
|
65
|
+
"ms": round((time.perf_counter() - started) * 1000),
|
|
66
|
+
}
|
|
67
|
+
severity = logging.ERROR if status_code >= 500 else logging.WARNING if status_code >= 400 else logging.INFO
|
|
68
|
+
logger.log(severity, "request", extra={"fields": fields})
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def crash_place(error: BaseException) -> str:
|
|
72
|
+
"""Kind of error and where it happened, without its message.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
error: The error.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
E.g. "ValueError at calculate.py:42".
|
|
79
|
+
"""
|
|
80
|
+
frames = traceback.extract_tb(error.__traceback__)
|
|
81
|
+
place = f" at {Path(frames[-1].filename).name}:{frames[-1].lineno}" if frames else ""
|
|
82
|
+
return type(error).__name__ + place
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class JsonFormatter(logging.Formatter):
|
|
86
|
+
"""A log record → one line of JSON, with its time, severity, message and fields."""
|
|
87
|
+
|
|
88
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
89
|
+
"""Turn a record into one line of JSON.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
record: The record, with its fields in `fields`.
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
The line.
|
|
96
|
+
"""
|
|
97
|
+
time_text = self.formatTime(record, "%Y-%m-%dT%H:%M:%S")
|
|
98
|
+
line = {"time": time_text, "severity": record.levelname, "message": record.getMessage()}
|
|
99
|
+
return json.dumps({**line, **getattr(record, "fields", {})})
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class NoMessage(logging.Filter):
|
|
103
|
+
"""A crash that uvicorn writes → only its kind and place: its message and traceback can carry values."""
|
|
104
|
+
|
|
105
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
106
|
+
"""Strip the details of a crash during a request; other records pass as they are.
|
|
107
|
+
|
|
108
|
+
Args:
|
|
109
|
+
record: A record of uvicorn.
|
|
110
|
+
|
|
111
|
+
Returns:
|
|
112
|
+
Always True: the record is kept.
|
|
113
|
+
"""
|
|
114
|
+
is_crash = str(record.msg).startswith("Exception in ASGI application") # not, e.g., failing to start
|
|
115
|
+
if is_crash and record.exc_info and record.exc_info[1] is not None:
|
|
116
|
+
record.msg = "Exception in ASGI application: " + crash_place(record.exc_info[1])
|
|
117
|
+
record.args = ()
|
|
118
|
+
record.exc_info = None
|
|
119
|
+
record.exc_text = None
|
|
120
|
+
return True
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# pdf_reader/
|
|
2
|
+
Reads a blood test in PDF: the values of the model, and age and sex if it has them.
|
|
3
|
+
|
|
4
|
+
- `read_pdf.py`: PDF → what the app needs from it; the only file the rest of the app calls.
|
|
5
|
+
- `pdf_to_table.py`: PDF → rows of its tables, each as a list of cells.
|
|
6
|
+
- `find_sections.py`: Which rows are in a section of urine, stool or another fluid.
|
|
7
|
+
- `standardize_names.py`: Name of a biomarker as a lab writes it → variable of the app.
|
|
8
|
+
- `convert_units.py`: Unit of a biomarker as a lab writes it → factor to the unit of the model.
|
|
9
|
+
- `extract_values.py`: Rows → value of each biomarker of the model, with its unit and factor.
|
|
10
|
+
- `estimate_missing.py`: Missing values worked out from their pair with an exact formula (hemoglobin = MCHC × hematocrit / 100…).
|
|
11
|
+
- `read_patient.py`: Rows → age at the blood test, its date and sex.
|
|
12
|
+
|
|
13
|
+
Its tables live in `config/`: `pdf_settings.py`, `biomarker_names.py` and `biomarker_units.py`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""PDF reader: blood test in PDF → values of the model, and age and sex if it has them."""
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Unit of a biomarker as a lab writes it → factor to the unit of the model.
|
|
2
|
+
|
|
3
|
+
- `unit_factor` : Biomarker and lab unit → factor, or None if the unit is unknown for it.
|
|
4
|
+
- `normalize_unit` : Lab unit → unit as it is looked up ("10³/µL" → "10^3/ul").
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
# Imports
|
|
8
|
+
import re
|
|
9
|
+
import unicodedata
|
|
10
|
+
|
|
11
|
+
from bioage.config.biomarker_units import LAB_UNITS, UNIT_REWRITES
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def unit_factor(variable: str, unit: str) -> float | None:
|
|
15
|
+
"""Variable and lab unit → factor that takes its value to the unit of the model.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
variable: Variable of the app or of the parser, e.g. "glucose".
|
|
19
|
+
unit: Unit as the lab writes it, e.g. "mmol/L".
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
Factor (value × factor = value in the unit of the model), or None if the unit is not known for it.
|
|
23
|
+
"""
|
|
24
|
+
return LAB_UNITS[variable][1].get(normalize_unit(unit))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def normalize_unit(unit: str) -> str:
|
|
28
|
+
"""Lab unit → unit as it is looked up: lowercase, no accents or spaces, and the rewrites of the config.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
unit: Unit as the lab writes it, e.g. "x10³ /µL".
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
Unit as it is looked up, e.g. "10^3/ul".
|
|
35
|
+
"""
|
|
36
|
+
unit = unicodedata.normalize("NFKD", unit.lower()) # also "³" → "3" and "µ" → "μ"
|
|
37
|
+
unit = re.sub(r"\s+", "", "".join(char for char in unit if not unicodedata.combining(char)))
|
|
38
|
+
for pattern, replacement in UNIT_REWRITES:
|
|
39
|
+
unit = re.sub(pattern, replacement, unit)
|
|
40
|
+
return unit
|