"""Ejemplo de HCE para la API clínica de Pacientry. Requiere Python 3.10+. Para probar los cuatro servicios, usá este comando en la terminal. python clinical_services.py normalization terminology epicrisis differential Lee PACIENTRY_TOKEN del entorno o lo pide sin eco en una terminal interactiva. Usá notas ficticias o previamente desidentificadas. """ import argparse from concurrent.futures import ThreadPoolExecutor from getpass import getpass import json import os from pathlib import Path import re import sys from unicodedata import normalize from urllib.error import HTTPError, URLError from urllib.parse import urlsplit from urllib.request import HTTPRedirectHandler, Request, build_opener BASE_URL = "https://pacientry.com" CAPABILITIES_PATH = "/api/clinical/v1/capabilities" SERVICES = ("normalization", "terminology", "epicrisis", "differential") PATHS = { "normalization": "/api/clinical/v1/normalize", "terminology": "/api/clinical/v1/terminology/code", "terminology_literal": "/api/clinical/v1/terminology/matches", "epicrisis": "/api/clinical/v1/epicrisis", "differential": "/api/clinical/v1/differential-diagnoses", } TIMEOUTS = {"normalization": 50, "terminology": 80, "terminology_literal": 50, "epicrisis": 110, "differential": 110} NOTE = "Pcte con asma. Niega fiebre." CLINICAL_BODY_LIMIT = 64 * 1024 def json_bytes(value): return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8") def checked_origin(url): parsed = urlsplit(url) secure = parsed.scheme == "https" or ( parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"} ) if (not secure or not parsed.hostname or parsed.username is not None or parsed.path not in {"", "/"} or parsed.query or parsed.fragment): raise ValueError("PACIENTRY_BASE_URL debe ser un origen HTTPS, como https://pacientry.com.") return url.rstrip("/") class NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def call_api(origin, token, path, payload=None, *, timeout=20): headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"} body = None if payload is None else json_bytes(payload) if body is not None: headers["Content-Type"] = "application/json" request = Request(origin + path, data=body, headers=headers) try: # No sigas redirecciones porque la solicitud lleva una credencial. response = build_opener(NoRedirect).open(request, timeout=timeout) except HTTPError as error: response = error except (URLError, OSError): return {"path": path, "error": "connection_failed"} with response: result = {"path": path, "status": response.code} retry_after = response.headers.get("Retry-After", "") if retry_after.isascii() and retry_after.isdecimal(): result["retry_after_seconds"] = int(retry_after) try: result["body"] = json.load(response) except (UnicodeError, ValueError, OSError): result["error"] = "invalid_json_response" return result def successful_body(result): if result.get("status") == 200 and isinstance(result.get("body"), dict): return result["body"] return {} def contextual_events(findings, source): for finding in findings: evidence = finding["evidence"] start, end, fragment = evidence["start"], evidence["end"], evidence["fragment"] if 0 <= start < end <= len(source) and source[start:end] == fragment: event = {"term": finding["term"], "category": finding["category"], "context": finding["context"], "evidence": fragment} if finding["status"] == "matched" and (concept := finding.get("concept")): event.update(code=concept["code"], system=concept["system"]) yield event def run_services(call, selected, note, previous_notes, terminology_mode, normalization_format): capabilities = call(CAPABILITIES_PATH) info = successful_body(capabilities) if not info: return {"capabilities": capabilities}, False catalog = {item["id"]: item for item in info.get("services", [])} contextual = terminology_mode == "contextual" terminology_id = "terminology" if contextual else "terminology_literal" operations = [terminology_id if name == "terminology" else name for name in selected] unavailable = [name for name in operations if not catalog.get(name, {}).get("enabled")] if "normalization" in selected and normalization_format != "normalized_text" and "snomed" not in info["permissions"]: unavailable.append("snomed") if unavailable: return {"error": "missing_permissions", "unavailable": unavailable}, False jobs = {} with ThreadPoolExecutor(max_workers=4) as pool: def submit(service, operation, payload): jobs[service] = pool.submit(call, PATHS[operation], payload, timeout=TIMEOUTS[operation]) if "normalization" in selected: submit("normalization", "normalization", {"text": note, "output_format": normalization_format}) if "terminology" in selected: submit("terminology", terminology_id, {"text": note, "deidentified": True}) normalized = successful_body(jobs["normalization"].result()) if "normalization" in jobs else {} text = normalized.get("normalized_text") or note if "epicrisis" in selected: payload = {"evoluciones": [*previous_notes, text if len(text) <= 12_000 else note]} if len(json_bytes(payload)) > CLINICAL_BODY_LIMIT: payload = {"evoluciones": [*previous_notes, note]} submit("epicrisis", "epicrisis", payload) if "differential" in selected: payload = {"text": text} if contextual and "terminology" in jobs: findings = successful_body(jobs["terminology"].result()).get("findings", []) events = [] for event in contextual_events(findings, note): if len(events) == 100 or len(json_bytes({**payload, "events": [*events, event]})) > CLINICAL_BODY_LIMIT: break events.append(event) if events: payload["events"] = events submit("differential", "differential", payload) results = {name: jobs[name].result() for name in selected} return {"services": results}, all(successful_body(result) for result in results.values()) def read_note(path): try: return normalize("NFC", path.read_text(encoding="utf-8-sig").strip()) except (OSError, UnicodeError): raise ValueError("No se pudo leer una nota de entrada en UTF-8.") from None def main(): parser = argparse.ArgumentParser(description="Ejecutá uno o más servicios clínicos con un token de Pacientry.") parser.add_argument("services", nargs="+", choices=SERVICES) parser.add_argument("--terminology-mode", choices=("contextual", "literal"), default="contextual") parser.add_argument("--normalization-format", choices=("normalized_text", "snomed", "codes"), default="normalized_text") parser.add_argument("--note", type=Path, help="Nota desidentificada en UTF-8. Por defecto se usa la nota ficticia.") parser.add_argument("--previous-note", type=Path, action="append", default=[], help="Nota previa del mismo episodio para epicrisis. Repetí en orden cronológico.") args = parser.parse_args() selected = list(dict.fromkeys(args.services)) if args.previous_note and "epicrisis" not in selected: parser.error("--previous-note se usa con epicrisis.") try: origin = checked_origin(os.environ.get("PACIENTRY_BASE_URL", BASE_URL)) note = read_note(args.note) if args.note else NOTE previous = [read_note(path) for path in args.previous_note] except ValueError as error: parser.error(str(error)) limit = 4000 if "normalization" in selected else 12_000 if "terminology" in selected or "epicrisis" in selected else 20_000 if not 1 <= len(note) <= limit: parser.error(f"La nota debe tener entre 1 y {limit} caracteres para los servicios seleccionados.") if len(previous) > 49 or any(not 1 <= len(item) <= 12_000 for item in previous): parser.error("Epicrisis admite hasta 49 notas previas de 1 a 12.000 caracteres cada una.") if "epicrisis" in selected and len(json_bytes({"evoluciones": [*previous, note]})) > CLINICAL_BODY_LIMIT: parser.error("El cuerpo de la solicitud de epicrisis supera 64 KiB.") if "differential" in selected and len(json_bytes({"text": note})) > CLINICAL_BODY_LIMIT: parser.error("El cuerpo de la solicitud de diagnóstico diferencial supera 64 KiB.") token = os.environ.get("PACIENTRY_TOKEN", "").strip() if not token and sys.stdin.isatty(): token = getpass("Token institucional de Pacientry: ").strip() if not token: parser.error("Configurá PACIENTRY_TOKEN o ejecutá el ejemplo en una terminal interactiva.") if not re.fullmatch(r"pst_[A-Za-z0-9_-]{43}", token): parser.error("PACIENTRY_TOKEN debe ser un token institucional de Pacientry.") def call(path, payload=None, *, timeout=20): return call_api(origin, token, path, payload, timeout=timeout) result, ok = run_services(call, selected, note, previous, args.terminology_mode, args.normalization_format) print(json.dumps(result, indent=2).replace(token, "[credencial omitida]")) return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())