Añadir tipo histológico y tratamientos a los datos de demostración de CaMa

This commit is contained in:
2026-12-04 01:58:18 -06:00
parent 6abb124a68
commit 35576087a3
+83
View File
@@ -0,0 +1,83 @@
"""Demo data only, no clinical value: give the made-up CaMa hospital the two things its screens
need and it lacks, the biopsy's histologic type and a treatment table, and extend its pipeline
to read them. Run where the hospital file and the API are (the API container):
python demo_datos_cama.py /data/hospital/hospital_cama.db http://localhost:8000
Repeating it changes nothing. Back the deployment up first."""
import json
import random
import sqlite3
import sys
import urllib.request
from datetime import date, timedelta
TYPES = {"CARCINOMA_INVASOR": ["8500/3", "8500/3", "8500/3", "8520/3"],
"CARCINOMA_IN_SITU": ["8500/2"], "BENIGNO": ["9016/0"]}
TREATMENTS = ["breast_conserving_surgery", "mastectomy", "chemotherapy"]
def augment(path: str) -> int:
with sqlite3.connect(path) as db:
if "bx_tipo_histologico" not in [r[1] for r in db.execute("pragma table_info(biopsiamama)")]:
db.execute("alter table biopsiamama add column bx_tipo_histologico text")
db.execute("create table if not exists tratamiento (tx_id integer primary key, "
"pac_id_hospital text, tx_fecha_inicio text, tx_tipo text)")
rows = db.execute("select bx_id, pac_id_hospital, bx_grado_histologico, bx_fecha_reporte "
"from biopsiamama where bx_grado_histologico is not null").fetchall()
for bx_id, patient, grade, reported in rows:
chance = random.Random(bx_id)
db.execute("update biopsiamama set bx_tipo_histologico = ? where bx_id = ?",
(chance.choice(TYPES[grade]), bx_id))
if not grade.startswith("CARCINOMA") or not reported:
continue
# her first breast cancer note after the report; most are treated after it
note = db.execute("select min(substr(nm_fecha, 1, 10)) from notamedica where "
"pac_id_hospital = ? and nm_cie_codigo like 'C50%' and "
"substr(nm_fecha, 1, 10) > ?", (patient, reported[:10])).fetchone()[0]
if note and chance.random() < 0.85:
start = date.fromisoformat(note) + timedelta(days=chance.randint(0, 45))
db.execute("insert or replace into tratamiento values (?, ?, ?, ?)",
(bx_id, patient, start.isoformat(), chance.choice(TREATMENTS)))
return db.execute("select count(*) from tratamiento").fetchone()[0]
def extend(doc: dict) -> dict:
nodes = {n["id"]: n for n in doc["nodes"]}
source = nodes["biopsias"]
for columns in (source["args"]["included_columns"],
source.get("guided", {}).get("answers", {}).get("columns", [])):
if columns and "bx_tipo_histologico" not in columns:
columns.append("bx_tipo_histologico")
nodes["biopsy"]["fields"]["histologic_type"] = "bx_tipo_histologico"
if "tratamientos" not in nodes:
columns = ["tx_id", "pac_id_hospital", "tx_fecha_inicio", "tx_tipo"]
doc["nodes"] += [
{"id": "tratamientos", "kind": "source", "label": "Tratamientos", "inputs": [],
"source": source["source"],
"args": {**source["args"], "table": "tratamiento", "included_columns": columns}},
{"id": "treatment_identity", "kind": "map", "label": "Identidad (tratamientos)",
"inputs": ["tratamientos"], "fields": {"record_number": "pac_id_hospital"}},
{"id": "treatment", "kind": "map", "label": "Tratamiento", "inputs": ["tratamientos"],
"fields": {"start_date": "tx_fecha_inicio", "kind": "tx_tipo"}},
{"id": "treatments_out", "kind": "target", "label": "Tratamientos de mama",
"inputs": ["treatment", "persons"], "entity": "breast_treatment"},
]
nodes["persons"]["inputs"].append("treatment_identity")
return doc
def call(url: str, method: str = "GET", body: dict | None = None):
request = urllib.request.Request(url, method=method, headers={"Content-Type": "application/json"},
data=None if body is None else json.dumps(body).encode())
with urllib.request.urlopen(request, timeout=120) as answer:
return json.loads(answer.read() or "null")
if __name__ == "__main__":
path, api = sys.argv[1], sys.argv[2].rstrip("/")
print("tratamientos en la base de demostración:", augment(path))
saved = call(f"{api}/ingest/pipelines/cama")["pipeline"]
call(f"{api}/ingest/pipelines/cama", "PUT", extend(saved))
print("corrida:", call(f"{api}/ingest/pipelines/cama/runs", "POST", {})["run_id"])