1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.10.0" />
<title>Gnumed.business.gmHL7 API documentation</title>
<meta name="description" content="Some HL7 handling." />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>Gnumed.business.gmHL7</code></h1>
</header>
<section id="section-intro">
<p>Some HL7 handling.</p>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python"># -*- coding: utf-8 -*-
"""Some HL7 handling."""
#============================================================
__author__ = "K.Hilbert <Karsten.Hilbert@gmx.net>"
__license__ = "GPL v2 or later"
import sys
import os
import logging
import time
import shutil
import datetime as pyDT
import hl7 as pyhl7
from xml.etree import ElementTree as pyxml
if __name__ == '__main__':
sys.path.insert(0, '../../')
_ = lambda x:x
from Gnumed.pycommon import gmI18N
if __name__ == '__main__':
gmI18N.activate_locale()
gmI18N.install_domain()
from Gnumed.pycommon import gmTools
from Gnumed.pycommon import gmPG2
from Gnumed.pycommon import gmDateTime
from Gnumed.business import gmIncomingData
from Gnumed.business import gmPathLab
from Gnumed.business import gmPerson
from Gnumed.business import gmPraxis
from Gnumed.business import gmStaff
_log = logging.getLogger('gm.hl7')
# constants
HL7_EOL = '\r'
HL7_BRK = '\.br\\'
HL7_SEGMENTS = 'FHS BHS MSH PID PV1 OBX NTE ORC OBR'.split()
HL7_segment2field_count = {
'FHS': 12,
'BHS': 12,
'MSH': 19,
'PID': 30,
'PV1': 52,
'OBR': 43,
'OBX': 17,
'NTE': 3,
'ORC': 19
}
MSH_field__sending_lab = 3
PID_field__name = 5
PID_field__dob = 7
PID_field__gender = 8
PID_component__lastname = 1
PID_component__firstname = 2
PID_component__middlename = 3
OBR_field__service_name = 4
OBR_field__ts_requested = 6
OBR_field__ts_started = 7
OBR_field__ts_ended = 8
OBR_field__ts_specimen_received = 14
OBX_field__set_id = 1
OBX_field__datatype = 2
OBX_field__type = 3
# components of 3rd field:
OBX_component__loinc = 1
OBX_component__name = 2
OBX_field__subid = 4
OBX_field__value = 5
OBX_field__unit = 6
OBX_field__range = 7
OBX_field__abnormal_flag = 8
OBX_field__status = 11
OBX_field__timestamp = 14
NET_field__set_id = 1
NET_field__src = 2
NET_field__note = 3
HL7_field_labels = {
'MSH': {
0: 'Segment Type',
1: 'Field Separator',
2: 'Encoding Characters',
3: 'Sending Application',
4: 'Sending Facility',
5: 'Receiving Application',
6: 'Receiving Facility',
7: 'Date/Time of Message',
8: 'Security',
9: 'Message Type',
10: 'ID: Message Control',
11: 'ID: Processing',
12: 'ID: Version',
14: 'Continuation Pointer',
15: 'Accept Acknowledgement Type',
16: 'Application Acknowledgement Type'
},
'PID': {
0: 'Segment Type',
1: '<PID> Set ID',
2: 'Patient ID (external)',
3: 'Patient ID (internal)',
4: 'Patient ID (alternate)',
5: 'Patient Name',
7: 'Date/Time of birth',
8: 'Administrative Gender',
11: 'Patient Address',
13: 'Patient Phone Number - Home'
},
'OBR': {
0: 'Segment Type',
1: 'ID: Set',
3: 'Filler Order Number (= ORC-3)',
4: 'ID: Universal Service',
5: 'Priority',
6: 'Date/Time requested',
7: 'Date/Time Observation started',
14: 'Date/Time Specimen received',
16: 'Ordering Provider',
18: 'Placer Field 1',
20: 'Filler Field 1',
21: 'Filler Field 2',
22: 'Date/Time Results reported/Status changed',
24: 'ID: Diagnostic Service Section',
25: 'Result Status',
27: 'Quantity/Timing',
28: 'Result Copies To'
},
'ORC': {
0: 'Segment Type',
1: 'Order Control',
3: 'Filler Order Number',
12: 'Ordering Provider'
},
'OBX': {
0: 'Segment Type',
1: 'Set ID',
2: 'Value Type',
3: 'Identifier (LOINC)',
4: 'Observation Sub-ID',
5: 'Value',
6: 'Units',
7: 'References Range (Low - High)',
8: 'Abnormal Flags',
11: 'Result Status',
14: 'Date/Time of Observation'
},
'NTE': {
0: 'Segment Type',
3: 'Comment'
}
}
HL7_GENDERS = {
'F': 'f',
'M': 'm',
'O': None,
'U': None,
None: None
}
#============================================================
# public API
#============================================================
def extract_HL7_from_XML_CDATA(filename, xml_path, target_dir=None):
_log.debug('extracting HL7 from CDATA of <%s> nodes in XML file [%s]', xml_path, filename)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
work_filename = gmTools.get_unique_filename(prefix = 'gm-x2h-%s-' % gmTools.fname_stem(filename), suffix = '.hl7')
if target_dir is None:
target_dir = os.path.join(orig_dir, 'HL7')
done_dir = os.path.join(orig_dir, 'done')
else:
done_dir = os.path.join(target_dir, 'done')
_log.debug('target dir: %s', target_dir)
gmTools.mkdir(target_dir)
gmTools.mkdir(done_dir)
except Exception:
_log.exception('cannot setup unwrapping environment')
return None
hl7_xml = pyxml.ElementTree()
try:
hl7_xml.parse(filename)
except pyxml.ParseError:
_log.exception('cannot parse [%s]' % filename)
return None
nodes = hl7_xml.findall(xml_path)
if len(nodes) == 0:
_log.debug('no nodes found for data extraction')
return None
_log.debug('unwrapping HL7 from XML into [%s]', work_filename)
hl7_file = open(work_filename, mode = 'wt', encoding = 'utf8', newline = '') # universal newlines acceptance but no translation on output
for node in nodes:
# hl7_file.write(node.text.rstrip() + HL7_EOL)
hl7_file.write(node.text + '') # trick to make node.text unicode
hl7_file.close()
target_fname = os.path.join(target_dir, os.path.split(work_filename)[1])
shutil.copy(work_filename, target_dir)
shutil.move(filename, done_dir)
return target_fname
#------------------------------------------------------------
def split_hl7_file(filename, target_dir=None, encoding='utf8'):
"""Multi-step processing of HL7 files.
- input can be multi-MSH / multi-PID / partially malformed HL7
- tries to fix oddities
- splits by MSH
- splits by PID into <target_dir>
- needs write permissions in dir_of(filename)
- moves HL7 files which were successfully split up into dir_of(filename)/done/
- returns (True|False, list_of_PID_files)
"""
local_log_name = gmTools.get_unique_filename (
prefix = gmTools.fname_stem(filename) + '-',
suffix = '.split.log'
)
local_logger = logging.FileHandler(local_log_name)
local_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(local_logger)
_log.info('splitting HL7 file: %s', filename)
_log.debug('log file: %s', local_log_name)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
done_dir = os.path.join(orig_dir, 'done')
gmTools.mkdir(done_dir)
error_dir = os.path.join(orig_dir, 'failed')
gmTools.mkdir(error_dir)
work_filename = gmTools.get_unique_filename(prefix = gmTools.fname_stem(filename) + '-', suffix = '.hl7')
if target_dir is None:
target_dir = os.path.join(orig_dir, 'PID')
_log.debug('target dir: %s', target_dir)
gmTools.mkdir(target_dir)
except Exception:
_log.exception('cannot setup splitting environment')
root_logger.removeHandler(local_logger)
return False, None
# split
target_names = []
try:
shutil.copy(filename, work_filename)
fixed_filename = __fix_malformed_hl7_file(work_filename, encoding = encoding)
MSH_fnames = __split_hl7_file_by_MSH(fixed_filename, encoding)
PID_fnames = []
for MSH_fname in MSH_fnames:
PID_fnames.extend(__split_MSH_by_PID(MSH_fname))
for PID_fname in PID_fnames:
shutil.move(PID_fname, target_dir)
target_names.append(os.path.join(target_dir, os.path.split(PID_fname)[1]))
except Exception:
_log.exception('cannot split HL7 file')
for target_name in target_names:
try: os.remove(target_name)
except Exception: pass
root_logger.removeHandler(local_logger)
shutil.move(local_log_name, error_dir)
return False, None
_log.info('successfully split')
root_logger.removeHandler(local_logger)
try:
shutil.move(filename, done_dir)
shutil.move(local_log_name, done_dir)
except shutil.Error:
_log.exception('cannot move hl7 file or log file to holding area')
return True, target_names
#------------------------------------------------------------
def format_hl7_message(message=None, skip_empty_fields=True, eol='\n ', source=None):
# a segment is a line starting with a type
msg = pyhl7.parse(message)
output = []
if source is not None:
output.append([_('HL7 Source'), '%s' % source])
output.append([_('HL7 data size'), _('%s bytes') % len(message)])
output.append([_('HL7 Message'), _(' %s segments (lines)%s') % (len(msg), gmTools.bool2subst(skip_empty_fields, _(', skipping empty fields'), ''))])
max_len = 0
for seg_idx in range(len(msg)):
seg = msg[seg_idx]
seg_type = seg[0][0]
output.append([_('Segment #%s <%s>') % (seg_idx, seg_type), _('%s fields') % len(seg)])
for field_idx in range(len(seg)):
field = seg[field_idx]
try:
label = HL7_field_labels[seg_type][field_idx]
except KeyError:
label = _('HL7 %s field') % seg_type
max_len = max(max_len, len(label))
if len(field) == 0:
if not skip_empty_fields:
output.append(['%2s - %s' % (field_idx, label), _('<EMTPY>')])
continue
if (len(field) == 1) and (('%s' % field[0]).strip() == ''):
if not skip_empty_fields:
output.append(['%2s - %s' % (field_idx, label), _('<EMTPY>')])
continue
content_lines = ('%s' % field).split(HL7_BRK)
output.append(['%2s - %s' % (field_idx, label), content_lines[0]])
for line in content_lines[1:]:
output.append(['', line])
#output.append([u'%2s - %s' % (field_idx, label), u'%s' % field])
if eol is None:
return output
max_len += 7
return eol.join([ '%s: %s' % ((o[0] + (' ' * max_len))[:max_len], o[1]) for o in output ])
#------------------------------------------------------------
def format_hl7_file(filename, skip_empty_fields=True, eol='\n ', return_filename=False, fix_hl7=True):
if fix_hl7:
fixed_name = __fix_malformed_hl7_file(filename)
hl7_file = open(fixed_name, mode = 'rt', encoding = 'utf-8-sig', newline = '') # read universal but pass on untranslated
source = '%s (<- %s)' % (fixed_name, filename)
else:
hl7_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '') # read universal but pass on untranslated
source = filename
output = format_hl7_message (
message = hl7_file.read(1024 * 1024 * 5), # 5 MB max
skip_empty_fields = skip_empty_fields,
eol = eol,
source = source
)
hl7_file.close()
if not return_filename:
return output
max_len = 120
if eol is None:
output = '\n '.join([ '%s: %s' % ((o[0] + (' ' * max_len))[:max_len], o[1]) for o in output ])
out_name = gmTools.get_unique_filename(prefix = 'gm-formatted_hl7-', suffix = '.hl7')
out_file = open(out_name, mode = 'wt', encoding = 'utf8')
out_file.write(output)
out_file.close()
return out_name
#------------------------------------------------------------
# this is used in the main code:
def stage_single_PID_hl7_file(filename, source=None, encoding='utf8'):
"""Multi-step processing of HL7 files.
- input must be single-MSH / single-PID / normalized HL7
- imports into clin.incoming_data
- needs write permissions in dir_of(filename)
- moves PID files which were successfully staged into dir_of(filename)/done/PID/
"""
local_log_name = gmTools.get_unique_filename (
prefix = gmTools.fname_stem(filename) + '-',
suffix = '.stage.log'
)
local_logger = logging.FileHandler(local_log_name)
local_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(local_logger)
_log.info('staging [%s] as unmatched incoming HL7%s', filename, gmTools.coalesce(source, '', ' (%s)'))
_log.debug('log file: %s', local_log_name)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
done_dir = os.path.join(orig_dir, 'done')
gmTools.mkdir(done_dir)
error_dir = os.path.join(orig_dir, 'failed')
gmTools.mkdir(error_dir)
except Exception:
_log.exception('cannot setup staging environment')
root_logger.removeHandler(local_logger)
return False
# stage
try:
incoming = gmIncomingData.create_incoming_data('HL7%s' % gmTools.coalesce(source, '', ' (%s)'), filename)
if incoming is None:
_log.error('cannot stage PID file: %s', filename)
root_logger.removeHandler(local_logger)
shutil.move(filename, error_dir)
shutil.move(local_log_name, error_dir)
return False
incoming.update_data_from_file(fname = filename)
except Exception:
_log.exception('error staging PID file')
root_logger.removeHandler(local_logger)
shutil.move(filename, error_dir)
shutil.move(local_log_name, error_dir)
return False
# set additional data
MSH_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '')
raw_hl7 = MSH_file.read(1024 * 1024 * 5) # 5 MB max
MSH_file.close()
shutil.move(filename, done_dir)
incoming['comment'] = format_hl7_message (
message = raw_hl7,
skip_empty_fields = True,
eol = '\n'
)
HL7 = pyhl7.parse(raw_hl7)
del raw_hl7
incoming['comment'] += '\n'
incoming['comment'] += ('-' * 80)
incoming['comment'] += '\n\n'
log = open(local_log_name, mode = 'rt', encoding = 'utf-8-sig')
incoming['comment'] += log.read()
log.close()
try:
incoming['lastnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
incoming['firstnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
if val is not None:
incoming['firstnames'] += ' '
incoming['firstnames'] += val
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__dob)
if val is not None:
tmp = time.strptime(val, '%Y%m%d')
incoming['dob'] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__gender)
if val is not None:
incoming['gender'] = val
incoming['external_data_id'] = filename
#u'fk_patient_candidates',
# u'request_id', # request ID as found in <data>
# u'postcode',
# u'other_info', # other identifying info in .data
# u'requestor', # Requestor of data (e.g. who ordered test results) if available in source data.
# u'fk_identity',
# u'comment', # a free text comment on this row, eg. why is it here, error logs etc
# u'fk_provider_disambiguated' # The provider the data is relevant to.
except Exception:
_log.exception('cannot add more data')
incoming.save()
_log.info('successfully staged')
root_logger.removeHandler(local_logger)
shutil.move(local_log_name, done_dir)
return True
#------------------------------------------------------------
def process_staged_single_PID_hl7_file(staged_item):
log_name = gmTools.get_unique_filename (
prefix = 'gm-staged_hl7_import-',
suffix = '.log'
)
import_logger = logging.FileHandler(log_name)
import_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(import_logger)
_log.debug('log file: %s', log_name)
if not staged_item.lock():
_log.error('cannot lock staged data for HL7 import')
root_logger.removeHandler(import_logger)
return False, log_name
_log.debug('reference ID of staged HL7 data: %s', staged_item['external_data_id'])
filename = staged_item.save_to_file()
_log.debug('unstaged HL7 data into: %s', filename)
if staged_item['pk_identity'] is None:
emr = None
else:
emr = gmPerson.cPatient(staged_item['pk_identity']).emr
success = False
try:
success = __import_single_PID_hl7_file(filename, emr = emr)
if success:
gmIncomingData.delete_incoming_data(pk_incoming_data = staged_item['pk_incoming_data'])
staged_item.unlock()
root_logger.removeHandler(import_logger)
return True, log_name
_log.error('error when importing single-PID/single-MSH file')
except Exception:
_log.exception('error when importing single-PID/single-MSH file')
if not success:
staged_item['comment'] = _('failed import: %s\n') % gmDateTime.pydt_strftime(gmDateTime.pydt_now_here())
staged_item['comment'] += '\n'
staged_item['comment'] += ('-' * 80)
staged_item['comment'] += '\n\n'
log = open(log_name, mode = 'rt', encoding = 'utf-8-sig')
staged_item['comment'] += log.read()
log.close()
staged_item['comment'] += '\n'
staged_item['comment'] += ('-' * 80)
staged_item['comment'] += '\n\n'
staged_item['comment'] += format_hl7_file (
filename,
skip_empty_fields = True,
eol = '\n ',
return_filename = False
)
staged_item.save()
staged_item.unlock()
root_logger.removeHandler(import_logger)
return success, log_name
#------------------------------------------------------------
def import_single_PID_hl7_file(filename):
log_name = '%s.import.log' % filename
import_logger = logging.FileHandler(log_name)
import_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(import_logger)
_log.debug('log file: %s', log_name)
success = True
try:
success = __import_single_PID_hl7_file(filename)
if not success:
_log.error('error when importing single-PID/single-MSH file')
except Exception:
_log.exception('error when importing single-PID/single-MSH file')
root_logger.removeHandler(import_logger)
return success, log_name
#============================================================
# internal helpers
#============================================================
def __fix_malformed_hl7_file(filename, encoding='utf8'):
_log.debug('fixing HL7 file [%s]', filename)
# first pass:
# - remove empty lines
# - normalize line endings
# - unwrap wrapped segments (based on the assumption that segments are wrapped until a line starts with a known segment marker)
out1_fname = gmTools.get_unique_filename (
prefix = 'gm_fix1-%s-' % gmTools.fname_stem(filename),
suffix = '.hl7'
)
hl7_in = open(filename, mode = 'rt', encoding = encoding) # universal newlines: translate any type of EOL to \n
hl7_out = open(out1_fname, mode = 'wt', encoding = 'utf8', newline = '') # newline='' -> no translation of EOL at all
is_first_line = True
for line in hl7_in:
# skip empty line
if line.strip() == '':
continue
# starts with known segment ?
segment = line[:3]
if (segment in HL7_SEGMENTS) and (line[3] == '|'):
if not is_first_line:
hl7_out.write(HL7_EOL)
else:
is_first_line = False
else:
hl7_out.write(' ')
hl7_out.write(line.rstrip())
hl7_out.write(HL7_EOL)
hl7_out.close()
hl7_in.close()
# second pass:
# - normalize # of fields per line
# - remove '\.br.\'-only fields ;-)
out2_fname = gmTools.get_unique_filename (
prefix = 'gm_fix2-%s-' % gmTools.fname_stem(filename),
suffix = '.hl7'
)
# we can now _expect_ lines to end in HL7_EOL, anything else is an error
hl7_in = open(out1_fname, mode = 'rt', encoding = 'utf-8-sig', newline = HL7_EOL)
hl7_out = open(out2_fname, mode = 'wt', encoding = 'utf8', newline = '')
for line in hl7_in:
line = line.strip()
seg_type = line[:3] # assumption: field separator = '|'
field_count = line.count('|') + 1 # assumption: no '|' in data ...
try:
required_fields = HL7_segment2field_count[seg_type]
except KeyError:
required_fields = field_count
missing_fields_count = required_fields - field_count
if missing_fields_count > 0:
line += ('|' * missing_fields_count)
cleaned_fields = []
for field in line.split('|'):
if field.replace(HL7_BRK, '').strip() == '':
cleaned_fields.append('')
continue
cleaned = gmTools.strip_prefix(field, HL7_BRK, remove_repeats = True, remove_whitespace = True)
cleaned = gmTools.strip_suffix(cleaned, HL7_BRK, remove_repeats = True, remove_whitespace = True)
cleaned_fields.append(cleaned)
hl7_out.write('|'.join(cleaned_fields) + HL7_EOL)
hl7_out.close()
hl7_in.close()
# third pass:
# - unsplit same-name, same-time, text-type OBX segments
out3_fname = gmTools.get_unique_filename (
prefix = 'gm_fix3-%s-' % gmTools.fname_stem(filename),
suffix = '.hl7'
)
# we can now _expect_ lines to end in HL7_EOL, anything else is an error
hl7_in = open(out2_fname, mode = 'rt', encoding = 'utf-8-sig', newline = HL7_EOL)
hl7_out = open(out3_fname, mode = 'wt', encoding = 'utf8', newline = '')
prev_identity = None
prev_fields = None
for line in hl7_in:
line = line.strip()
if not line.startswith('OBX|'):
if prev_fields is not None:
hl7_out.write('|'.join(prev_fields) + HL7_EOL)
hl7_out.write(line + HL7_EOL)
prev_identity = None
prev_fields = None
curr_fields = None
continue
# first OBX
curr_fields = line.split('|')
if curr_fields[OBX_field__datatype] != 'FT':
hl7_out.write(line + HL7_EOL)
prev_identity = None
prev_fields = None
curr_fields = None
continue
# first FT type OBX
if prev_fields is None:
prev_fields = line.split('|')
prev_identity = line.split('|')
prev_identity[OBX_field__set_id] = ''
prev_identity[OBX_field__subid] = ''
prev_identity[OBX_field__value] = ''
prev_identity = '|'.join(prev_identity)
continue
# non-first FT type OBX
curr_identity = line.split('|')
curr_identity[OBX_field__set_id] = ''
curr_identity[OBX_field__subid] = ''
curr_identity[OBX_field__value] = ''
curr_identity = '|'.join(curr_identity)
if curr_identity != prev_identity:
# write out previous line
hl7_out.write('|'.join(prev_fields) + HL7_EOL)
# keep current fields, since it may start a "repeat FT type OBX block"
prev_fields = curr_fields
prev_identity = curr_identity
continue
if prev_fields[OBX_field__value].endswith(HL7_BRK):
prev_fields[OBX_field__value] += curr_fields[OBX_field__value]
else:
if curr_fields[OBX_field__value].startswith(HL7_BRK):
prev_fields[OBX_field__value] += curr_fields[OBX_field__value]
else:
prev_fields[OBX_field__value] += HL7_BRK
prev_fields[OBX_field__value] += curr_fields[OBX_field__value]
if prev_fields is not None:
hl7_out.write('|'.join(prev_fields) + HL7_EOL)
hl7_out.close()
hl7_in.close()
return out3_fname
#------------------------------------------------------------
def __split_hl7_file_by_MSH(filename, encoding='utf8'):
_log.debug('splitting [%s] into single-MSH files', filename)
hl7_in = open(filename, mode = 'rt', encoding = encoding)
idx = 0
first_line = True
MSH_file = None
MSH_fnames = []
for line in hl7_in:
line = line.strip()
# first line must be MSH
if first_line:
# ignore empty / FHS / BHS lines
if line == '':
continue
if line.startswith('FHS|'):
_log.debug('ignoring FHS')
continue
if line.startswith('BHS|'):
_log.debug('ignoring BHS')
continue
if not line.startswith('MSH|'):
raise ValueError('HL7 file <%s> does not start with "MSH" line' % filename)
first_line = False
# start new file
if line.startswith('MSH|'):
if MSH_file is not None:
MSH_file.close()
idx += 1
out_fname = gmTools.get_unique_filename(prefix = '%s-MSH_%s-' % (gmTools.fname_stem(filename), idx), suffix = 'hl7')
_log.debug('writing message %s to [%s]', idx, out_fname)
MSH_fnames.append(out_fname)
MSH_file = open(out_fname, mode = 'wt', encoding = 'utf8', newline = '')
# ignore BTS / FTS lines
if line.startswith('BTS|'):
_log.debug('ignoring BTS')
continue
if line.startswith('FTS|'):
_log.debug('ignoring FTS')
continue
# else write line to new file
MSH_file.write(line + HL7_EOL)
if MSH_file is not None:
MSH_file.close()
hl7_in.close()
return MSH_fnames
#------------------------------------------------------------
def __split_MSH_by_PID(filename):
"""Assumes:
- ONE MSH per file
- utf8 encoding
- first non-empty line must be MSH line
- next line must be PID line
IOW, what's created by __split_hl7_file_by_MSH()
"""
_log.debug('splitting single-MSH file [%s] into single-PID files', filename)
MSH_in = open(filename, mode = 'rt', encoding = 'utf-8-sig')
looking_for_MSH = True
MSH_line = None
looking_for_first_PID = True
PID_file = None
PID_fnames = []
idx = 0
for line in MSH_in:
line = line.strip()
# ignore empty
if line == '':
continue
# first non-empty line must be MSH
if looking_for_MSH:
if line.startswith('MSH|'):
looking_for_MSH = False
MSH_line = line + HL7_EOL
continue
raise ValueError('HL7 MSH file <%s> does not start with "MSH" line' % filename)
else:
if line.startswith('MSH|'):
raise ValueError('HL7 single-MSH file <%s> contains more than one MSH line' % filename)
# first non-empty line after MSH must be PID
if looking_for_first_PID:
if not line.startswith('PID|'):
raise ValueError('HL7 MSH file <%s> does not have "PID" line follow "MSH" line' % filename)
looking_for_first_PID = False
# start new file if line is PID
if line.startswith('PID|'):
if PID_file is not None:
PID_file.close()
idx += 1
out_fname = gmTools.get_unique_filename(prefix = '%s-PID_%s-' % (gmTools.fname_stem(filename), idx), suffix = 'hl7')
_log.debug('writing message for PID %s to [%s]', idx, out_fname)
PID_fnames.append(out_fname)
PID_file = open(out_fname, mode = 'wt', encoding = 'utf8', newline = '')
PID_file.write(MSH_line)
# else write line to new file
PID_file.write(line + HL7_EOL)
if PID_file is not None:
PID_file.close()
MSH_in.close()
return PID_fnames
#------------------------------------------------------------
def __find_or_create_lab(hl7_lab, link_obj=None):
comment_tag = '[HL7 name::%s]' % hl7_lab
for gm_lab in gmPathLab.get_test_orgs():
if comment_tag in gmTools.coalesce(gm_lab['comment'], ''):
_log.debug('found lab [%s] from HL7 file in GNUmed database:', hl7_lab)
_log.debug(gm_lab)
return gm_lab
_log.debug('lab not found: %s', hl7_lab)
gm_lab = gmPathLab.create_test_org(link_obj = link_obj, name = hl7_lab, comment = comment_tag)
if gm_lab is None:
raise ValueError('cannot create lab [%s] in GNUmed' % hl7_lab)
_log.debug('created lab: %s', gm_lab)
return gm_lab
#------------------------------------------------------------
def __find_or_create_test_type(loinc=None, name=None, pk_lab=None, unit=None, link_obj=None, abbrev=None):
tt = gmPathLab.find_measurement_type(link_obj = link_obj, lab = pk_lab, name = name)
if tt is None:
_log.debug('test type [%s::%s::%s] not found for lab #%s, creating', name, unit, loinc, pk_lab)
tt = gmPathLab.create_measurement_type(link_obj = link_obj, lab = pk_lab, abbrev = gmTools.coalesce(abbrev, name), unit = unit, name = name)
_log.debug('created as: %s', tt)
if loinc is None:
return tt
if loinc.strip() == '':
return tt
if tt['loinc'] is None:
tt['loinc'] = loinc
tt.save(conn = link_obj)
return tt
if tt['loinc'] != loinc:
# raise ValueError('LOINC code mismatch between GM (%s) and HL7 (%s) for result type [%s]' % (tt['loinc'], loinc, name))
_log.error('LOINC code mismatch between GM (%s) and HL7 (%s) for result type [%s]', tt['loinc'], loinc, name)
return tt
#------------------------------------------------------------
def __ensure_hl7_test_types_exist_in_gnumed(link_obj=None, hl7_data=None, pk_test_org=None):
try:
OBX_count = len(hl7_data.segments('OBX'))
except KeyError:
_log.error("HL7 does not contain OBX segments, nothing to do")
return
for OBX_idx in range(OBX_count):
unit = hl7_data.extract_field(segment = 'OBX', segment_num = OBX_idx, field_num = OBX_field__unit)
if unit == '':
unit = None
LOINC = hl7_data.extract_field(segment = 'OBX', segment_num = OBX_idx, field_num = OBX_field__type, component_num = OBX_component__loinc)
tname = hl7_data.extract_field(segment = 'OBX', segment_num = OBX_idx, field_num = OBX_field__type, component_num = OBX_component__name)
__find_or_create_test_type (
loinc = LOINC,
name = tname,
pk_lab = pk_test_org,
unit = unit,
link_obj = link_obj
)
#------------------------------------------------------------
def __PID2dto(HL7=None):
pat_lname = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
pat_fname = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
pat_mname = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
if pat_mname is not None:
pat_fname += ' '
pat_fname += pat_mname
_log.debug('patient data from PID segment: first=%s (middle=%s) last=%s', pat_fname, pat_mname, pat_lname)
dto = gmPerson.cDTO_person()
dto.firstnames = pat_fname
dto.lastnames = pat_lname
dto.gender = HL7_GENDERS[HL7.extract_field('PID', segment_num = 1, field_num = PID_field__gender)]
hl7_dob = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__dob)
if hl7_dob is not None:
tmp = time.strptime(hl7_dob, '%Y%m%d')
dto.dob = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
idents = dto.get_candidate_identities()
if len(idents) == 0:
_log.warning('no match candidate, not auto-importing')
_log.debug(dto)
return []
if len(idents) > 1:
_log.warning('more than one match candidate, not auto-importing')
_log.debug(dto)
return idents
return [gmPerson.cPatient(idents[0].ID)]
#------------------------------------------------------------
def __hl7dt2pydt(hl7dt):
if hl7dt == '':
return None
if len(hl7dt) == 8:
tmp = time.strptime(hl7dt, '%Y%m%d')
return pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
if len(hl7dt) == 12:
tmp = time.strptime(hl7dt, '%Y%m%d%H%M')
return pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tmp.tm_hour, tmp.tm_min, tzinfo = gmDateTime.gmCurrentLocalTimezone)
if len(hl7dt) == 14:
tmp = time.strptime(hl7dt, '%Y%m%d%H%M%S')
return pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tmp.tm_hour, tmp.tm_min, tmp.tm_sec, tzinfo = gmDateTime.gmCurrentLocalTimezone)
raise ValueError('Observation timestamp not parseable: [%s]', hl7dt)
#------------------------------------------------------------
def __import_single_PID_hl7_file(filename, emr=None):
"""Assumes single-PID/single-MSH HL7 file."""
_log.debug('importing single-PID single-MSH HL7 data from [%s]', filename)
# read the file
MSH_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '')
HL7 = pyhl7.parse(MSH_file.read(1024 * 1024 * 5)) # 5 MB max
MSH_file.close()
# sanity checks
if len(HL7.segments('MSH')) != 1:
_log.error('more than one MSH segment')
return False
if len(HL7.segments('PID')) != 1:
_log.error('more than one PID segment')
return False
# ensure lab is in database
hl7_lab = HL7.extract_field('MSH', field_num = MSH_field__sending_lab)
gm_lab = __find_or_create_lab(hl7_lab)
# ensure test types exist
conn = gmPG2.get_connection(readonly = False)
__ensure_hl7_test_types_exist_in_gnumed(link_obj = conn, hl7_data = HL7, pk_test_org = gm_lab['pk_test_org'])
# find patient
if emr is None:
#PID = HL7.segment('PID')
pats = __PID2dto(HL7 = HL7)
if len(pats) == 0:
conn.rollback()
return False
if len(pats) > 1:
conn.rollback()
return False
emr = pats[0].emr
# import values: loop over segments
when_list = {}
current_result = None
previous_segment = None
had_errors = False
msh_seen = False
#pid_seen = False
last_obr = None
obr = {}
for seg_idx in range(len(HL7)):
seg = HL7[seg_idx]
seg_type = seg[0][0]
_log.debug('processing line #%s = segment of type <%s>', seg_idx, seg_type)
if seg_type == 'MSH':
msh_seen = True
if seg_type == 'PID':
if not msh_seen:
conn.rollback()
_log.error('PID segment before MSH segment')
return False
#pid_seen = True
if seg_type in ['MSH', 'PID']:
_log.info('segment already handled')
previous_segment = seg_type
obr = {}
current_result = None
continue
if seg_type in ['ORC']:
_log.info('currently ignoring %s segments', seg_type)
previous_segment = seg_type
obr = {}
current_result = None
continue
if seg_type == 'OBR':
previous_segment = seg_type
last_obr = seg
current_result = None
obr['abbrev'] = ('%s' % seg[OBR_field__service_name][0]).strip()
try:
obr['name'] = ('%s' % seg[OBR_field__service_name][1]).strip()
except IndexError:
obr['name'] = obr['abbrev']
for field_name in [OBR_field__ts_ended, OBR_field__ts_started, OBR_field__ts_specimen_received, OBR_field__ts_requested]:
obr['clin_when'] = seg[field_name][0].strip()
if obr['clin_when'] != '':
break
continue
if seg_type == 'OBX':
current_result = None
# determine value
val_alpha = seg[OBX_field__value][0].strip()
is_num, val_num = gmTools.input2decimal(initial = val_alpha)
if is_num:
val_alpha = None
else:
val_num = None
val_alpha = val_alpha.replace('\.br\\', '\n')
# determine test type
unit = seg[OBX_field__unit][0].strip()
if unit == '':
if is_num:
unit = '1/1'
else:
unit = None
test_type = __find_or_create_test_type (
loinc = '%s' % seg[OBX_field__type][0][OBX_component__loinc-1],
name = '%s' % seg[OBX_field__type][0][OBX_component__name-1],
pk_lab = gm_lab['pk_test_org'],
unit = unit,
link_obj = conn
)
# eventually, episode should be read from lab_request
epi = emr.add_episode (
link_obj = conn,
episode_name = 'administrative',
is_open = False,
allow_dupes = False
)
current_result = emr.add_test_result (
link_obj = conn,
episode = epi['pk_episode'],
type = test_type['pk_test_type'],
intended_reviewer = gmStaff.gmCurrentProvider()['pk_staff'],
val_num = val_num,
val_alpha = val_alpha,
unit = unit
)
# handle range information et al
ref_range = seg[OBX_field__range][0].strip()
if ref_range != '':
current_result.reference_range = ref_range
flag = seg[OBX_field__abnormal_flag][0].strip()
if flag != '':
current_result['abnormality_indicator'] = flag
current_result['status'] = seg[OBX_field__status][0].strip()
current_result['val_grouping'] = seg[OBX_field__subid][0].strip()
current_result['source_data'] = ''
if last_obr is not None:
current_result['source_data'] += str(last_obr)
current_result['source_data'] += '\n'
current_result['source_data'] += str(seg)
clin_when = seg[OBX_field__timestamp][0].strip()
if clin_when == '':
_log.warning('no <Observation timestamp> in OBX, trying OBR timestamp')
clin_when = obr['clin_when']
try:
clin_when = __hl7dt2pydt(clin_when)
except ValueError:
_log.exception('clin_when from OBX or OBR not useable, assuming <today>')
if clin_when is not None:
current_result['clin_when'] = clin_when
current_result.save(conn = conn)
when_list[gmDateTime.pydt_strftime(current_result['clin_when'], '%Y %b %d')] = 1
previous_segment = seg_type
continue
if seg_type == 'NTE':
note = seg[NET_field__note][0].strip().replace('\.br\\', '\n')
if note == '':
_log.debug('empty NTE segment')
previous_segment = seg_type # maybe not ? (HL7 providers happen to use empty NTE segments to "structure" raw HL7 |-)
continue
# if this is an NTE following an OBR (IOW an order-related
# comment): make this a test result all of its own :-)
if previous_segment == 'OBR':
_log.debug('NTE following OBR: general note, using OBR timestamp [%s]', obr['clin_when'])
current_result = None
name = obr['name']
if name == '':
name = _('Comment')
# FIXME: please suggest a LOINC for "order comment"
test_type = __find_or_create_test_type(name = name, pk_lab = gm_lab['pk_test_org'], abbrev = obr['abbrev'], link_obj = conn)
# eventually, episode should be read from lab_request
epi = emr.add_episode (
link_obj = conn,
episode_name = 'administrative',
is_open = False,
allow_dupes = False
)
nte_result = emr.add_test_result (
link_obj = conn,
episode = epi['pk_episode'],
type = test_type['pk_test_type'],
intended_reviewer = gmStaff.gmCurrentProvider()['pk_staff'],
val_alpha = note
)
#nte_result['val_grouping'] = seg[OBX_field__subid][0].strip()
nte_result['source_data'] = str(seg)
try:
nte_result['clin_when'] = __hl7dt2pydt(obr['clin_when'])
except ValueError:
_log.exception('no .clin_when from OBR for NTE pseudo-OBX available')
nte_result.save(conn = conn)
continue
if (previous_segment == 'OBX') and (current_result is not None):
current_result['source_data'] += '\n'
current_result['source_data'] += str(seg)
current_result['note_test_org'] = gmTools.coalesce (
current_result['note_test_org'],
note,
'%%s\n%s' % note
)
current_result.save(conn = conn)
previous_segment = seg_type
continue
_log.error('unexpected NTE segment')
had_errors = True
break
_log.error('unknown segment, aborting')
_log.debug('line: %s', seg)
had_errors = True
break
if had_errors:
conn.rollback()
return False
conn.commit()
# record import in chart
try:
no_results = len(HL7.segments('OBX'))
except KeyError:
no_results = '?'
soap = _(
'Imported HL7 file [%s]:\n'
' lab "%s" (%s@%s), %s results (%s)'
) % (
filename,
hl7_lab,
gm_lab['unit'],
gm_lab['organization'],
no_results,
' / '.join(list(when_list))
)
epi = emr.add_episode (
episode_name = 'administrative',
is_open = False,
allow_dupes = False
)
emr.add_clin_narrative (
note = soap,
soap_cat = None,
episode = epi
)
# keep copy of HL7 data in document archive
folder = gmPerson.cPatient(emr.pk_patient).document_folder
hl7_docs = folder.get_documents (
doc_type = 'HL7 data',
pk_episodes = [epi['pk_episode']],
order_by = 'clin_when DESC'
)
if len(hl7_docs) > 0:
# there should only ever be one unless the user manually creates more,
# also, it should always be the latest since "ORDER BY clin_when DESC"
hl7_doc = hl7_docs[0]
else:
hl7_doc = folder.add_document (
document_type = 'HL7 data',
encounter = emr.active_encounter['pk_encounter'],
episode = epi['pk_episode']
)
hl7_doc['comment'] = _('list of imported HL7 data files')
hl7_doc['pk_org_unit'] = gmPraxis.gmCurrentPraxisBranch()['pk_org_unit']
hl7_doc['clin_when'] = gmDateTime.pydt_now_here()
hl7_doc.save()
part = hl7_doc.add_part(file = filename)
part['obj_comment'] = _('Result dates: %s') % ' / '.join(list(when_list))
part.save()
hl7_doc.set_reviewed(technically_abnormal = False, clinically_relevant = False)
return True
#------------------------------------------------------------
# this is only used for testing here in this file
def __stage_MSH_as_incoming_data(filename, source=None, logfile=None):
"""Consumes single-MSH single-PID HL7 files."""
_log.debug('staging [%s] as unmatched incoming HL7%s', gmTools.coalesce(source, '', ' (%s)'), filename)
# parse HL7
MSH_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '')
raw_hl7 = MSH_file.read(1024 * 1024 * 5) # 5 MB max
MSH_file.close()
formatted_hl7 = format_hl7_message (
message = raw_hl7,
skip_empty_fields = True,
eol = '\n'
)
HL7 = pyhl7.parse(raw_hl7)
del raw_hl7
# import file
incoming = gmIncomingData.create_incoming_data('HL7%s' % gmTools.coalesce(source, '', ' (%s)'), filename)
if incoming is None:
return None
incoming.update_data_from_file(fname = filename)
incoming['comment'] = formatted_hl7
if logfile is not None:
log = open(logfile, mode = 'rt', encoding = 'utf-8-sig')
incoming['comment'] += '\n'
incoming['comment'] += ('-' * 80)
incoming['comment'] += '\n\n'
incoming['comment'] += log.read()
log.close()
try:
incoming['lastnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
incoming['firstnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
if val is not None:
incoming['firstnames'] += ' '
incoming['firstnames'] += val
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__dob)
if val is not None:
tmp = time.strptime(val, '%Y%m%d')
incoming['dob'] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__gender)
if val is not None:
incoming['gender'] = val
incoming['external_data_id'] = filename
#u'fk_patient_candidates',
# u'request_id', # request ID as found in <data>
# u'postcode',
# u'other_info', # other identifying info in .data
# u'requestor', # Requestor of data (e.g. who ordered test results) if available in source data.
# u'fk_identity',
# u'comment', # a free text comment on this row, eg. why is it here, error logs etc
# u'fk_provider_disambiguated' # The provider the data is relevant to.
except KeyError:
_log.exception('no PID segment, cannot add more data')
incoming.save()
return incoming
#============================================================
# main
#------------------------------------------------------------
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit()
if sys.argv[1] != 'test':
sys.exit()
gmDateTime.init()
gmTools.gmPaths()
#-------------------------------------------------------
def test_import_HL7(filename):
# would normally be set by external configuration:
from Gnumed.business import gmPraxis
gmPraxis.gmCurrentPraxisBranch(branch = gmPraxis.get_praxis_branches()[0])
#if not import_hl7_file(filename):
# print("error with", filename)
#-------------------------------------------------------
def test_xml_extract():
hl7 = extract_HL7_from_XML_CDATA(sys.argv[2], './/Message')
print("HL7:", hl7)
#result, PID_fnames = split_hl7_file(hl7)
#print "result:", result
#print "per-PID MSH files:"
#for name in PID_fnames:
# print " ", name
#-------------------------------------------------------
def test_stage_hl7_from_xml():
hl7 = extract_HL7_from_XML_CDATA(sys.argv[2], './/Message')
print("HL7:", hl7)
result, PID_fnames = split_hl7_file(hl7)
print("result:", result)
print("staging per-PID HL7 files:")
for name in PID_fnames:
print(" file:", name)
__stage_MSH_as_incoming_data(name, source = 'Excelleris')
#-------------------------------------------------------
def test_split_hl7_file():
result, PID_fnames = split_hl7_file(sys.argv[2])
print("result:", result)
print("per-PID HL7 files:")
for name in PID_fnames:
print(" file:", name)
#-------------------------------------------------------
def test_stage_hl7():
fixed = __fix_malformed_hl7_file(sys.argv[2])
print("fixed HL7:", fixed)
#PID_fnames = split_HL7_by_PID(fixed, encoding='utf8')
print("staging per-PID HL7 files:")
for name in []: #PID_fnames:
print(" file:", name)
#print "", __stage_MSH_as_incoming_data(name, source = u'?')
#-------------------------------------------------------
def test_format_hl7_message():
tests = [
"OBR|1||03-1350023-LIP-0|LIP^Lipids||20031004073300|20031004073300|||||||20031004073300||22333^MEDIC^IAN^TEST||031350023||03-1350023|031350023|20031004131600||CHEM|F|||22333^MEDIC^IAN^TEST",
"OBX|2|NM|22748-8^LDL Cholesterol||4.0|mmol/L|1.5 - 3.4|H|||F|||20031004073300"
]
for test in tests:
print(format_hl7_message (
# skip_empty_fields = True,
message = test
))
#-------------------------------------------------------
def test_format_hl7_file(filename):
print(format_hl7_file (
filename,
# skip_empty_fields = True
return_filename = True
))
#-------------------------------------------------------
def test___fix_malformed_hl7():
print("fixed HL7:", __fix_malformed_hl7_file(sys.argv[2]))
#-------------------------------------------------------
def test_parse_hl7():
MSH_file = open(sys.argv[2], mode = 'rt', encoding = 'utf-8-sig', newline = '')
raw_hl7 = MSH_file.read(1024 * 1024 * 5) # 5 MB max
MSH_file.close()
print(format_hl7_message (
message = raw_hl7,
skip_empty_fields = True,
eol = '\n'
))
HL7 = pyhl7.parse(raw_hl7)
del raw_hl7
for seg in HL7.segments('MSH'):
print(seg)
print("PID:")
print(HL7.extract_field('PID'))
print(HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname))
print(HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname))
# incoming['firstnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
# val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
# if val is not None:
# incoming['firstnames'] += u' '
# incoming['firstnames'] += val
# val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__dob)
# if val is not None:
# tmp = time.strptime(val, '%Y%m%d')
# incoming['dob'] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
# val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__gender)
# if val is not None:
# incoming['gender'] = val
# incoming['external_data_id'] = filename
#-------------------------------------------------------
#test_import_HL7(sys.argv[2])
#test_xml_extract()
#test_stage_hl7_from_xml()
#test_stage_hl7()
#test_format_hl7_message()
#test_format_hl7_file(sys.argv[2])
#test___fix_malformed_hl7()
#test_split_hl7_file()
test_parse_hl7()</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="Gnumed.business.gmHL7.extract_HL7_from_XML_CDATA"><code class="name flex">
<span>def <span class="ident">extract_HL7_from_XML_CDATA</span></span>(<span>filename, xml_path, target_dir=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def extract_HL7_from_XML_CDATA(filename, xml_path, target_dir=None):
_log.debug('extracting HL7 from CDATA of <%s> nodes in XML file [%s]', xml_path, filename)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
work_filename = gmTools.get_unique_filename(prefix = 'gm-x2h-%s-' % gmTools.fname_stem(filename), suffix = '.hl7')
if target_dir is None:
target_dir = os.path.join(orig_dir, 'HL7')
done_dir = os.path.join(orig_dir, 'done')
else:
done_dir = os.path.join(target_dir, 'done')
_log.debug('target dir: %s', target_dir)
gmTools.mkdir(target_dir)
gmTools.mkdir(done_dir)
except Exception:
_log.exception('cannot setup unwrapping environment')
return None
hl7_xml = pyxml.ElementTree()
try:
hl7_xml.parse(filename)
except pyxml.ParseError:
_log.exception('cannot parse [%s]' % filename)
return None
nodes = hl7_xml.findall(xml_path)
if len(nodes) == 0:
_log.debug('no nodes found for data extraction')
return None
_log.debug('unwrapping HL7 from XML into [%s]', work_filename)
hl7_file = open(work_filename, mode = 'wt', encoding = 'utf8', newline = '') # universal newlines acceptance but no translation on output
for node in nodes:
# hl7_file.write(node.text.rstrip() + HL7_EOL)
hl7_file.write(node.text + '') # trick to make node.text unicode
hl7_file.close()
target_fname = os.path.join(target_dir, os.path.split(work_filename)[1])
shutil.copy(work_filename, target_dir)
shutil.move(filename, done_dir)
return target_fname</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.format_hl7_file"><code class="name flex">
<span>def <span class="ident">format_hl7_file</span></span>(<span>filename, skip_empty_fields=True, eol='\n ', return_filename=False, fix_hl7=True)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def format_hl7_file(filename, skip_empty_fields=True, eol='\n ', return_filename=False, fix_hl7=True):
if fix_hl7:
fixed_name = __fix_malformed_hl7_file(filename)
hl7_file = open(fixed_name, mode = 'rt', encoding = 'utf-8-sig', newline = '') # read universal but pass on untranslated
source = '%s (<- %s)' % (fixed_name, filename)
else:
hl7_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '') # read universal but pass on untranslated
source = filename
output = format_hl7_message (
message = hl7_file.read(1024 * 1024 * 5), # 5 MB max
skip_empty_fields = skip_empty_fields,
eol = eol,
source = source
)
hl7_file.close()
if not return_filename:
return output
max_len = 120
if eol is None:
output = '\n '.join([ '%s: %s' % ((o[0] + (' ' * max_len))[:max_len], o[1]) for o in output ])
out_name = gmTools.get_unique_filename(prefix = 'gm-formatted_hl7-', suffix = '.hl7')
out_file = open(out_name, mode = 'wt', encoding = 'utf8')
out_file.write(output)
out_file.close()
return out_name</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.format_hl7_message"><code class="name flex">
<span>def <span class="ident">format_hl7_message</span></span>(<span>message=None, skip_empty_fields=True, eol='\n ', source=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def format_hl7_message(message=None, skip_empty_fields=True, eol='\n ', source=None):
# a segment is a line starting with a type
msg = pyhl7.parse(message)
output = []
if source is not None:
output.append([_('HL7 Source'), '%s' % source])
output.append([_('HL7 data size'), _('%s bytes') % len(message)])
output.append([_('HL7 Message'), _(' %s segments (lines)%s') % (len(msg), gmTools.bool2subst(skip_empty_fields, _(', skipping empty fields'), ''))])
max_len = 0
for seg_idx in range(len(msg)):
seg = msg[seg_idx]
seg_type = seg[0][0]
output.append([_('Segment #%s <%s>') % (seg_idx, seg_type), _('%s fields') % len(seg)])
for field_idx in range(len(seg)):
field = seg[field_idx]
try:
label = HL7_field_labels[seg_type][field_idx]
except KeyError:
label = _('HL7 %s field') % seg_type
max_len = max(max_len, len(label))
if len(field) == 0:
if not skip_empty_fields:
output.append(['%2s - %s' % (field_idx, label), _('<EMTPY>')])
continue
if (len(field) == 1) and (('%s' % field[0]).strip() == ''):
if not skip_empty_fields:
output.append(['%2s - %s' % (field_idx, label), _('<EMTPY>')])
continue
content_lines = ('%s' % field).split(HL7_BRK)
output.append(['%2s - %s' % (field_idx, label), content_lines[0]])
for line in content_lines[1:]:
output.append(['', line])
#output.append([u'%2s - %s' % (field_idx, label), u'%s' % field])
if eol is None:
return output
max_len += 7
return eol.join([ '%s: %s' % ((o[0] + (' ' * max_len))[:max_len], o[1]) for o in output ])</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.import_single_PID_hl7_file"><code class="name flex">
<span>def <span class="ident">import_single_PID_hl7_file</span></span>(<span>filename)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def import_single_PID_hl7_file(filename):
log_name = '%s.import.log' % filename
import_logger = logging.FileHandler(log_name)
import_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(import_logger)
_log.debug('log file: %s', log_name)
success = True
try:
success = __import_single_PID_hl7_file(filename)
if not success:
_log.error('error when importing single-PID/single-MSH file')
except Exception:
_log.exception('error when importing single-PID/single-MSH file')
root_logger.removeHandler(import_logger)
return success, log_name</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.process_staged_single_PID_hl7_file"><code class="name flex">
<span>def <span class="ident">process_staged_single_PID_hl7_file</span></span>(<span>staged_item)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def process_staged_single_PID_hl7_file(staged_item):
log_name = gmTools.get_unique_filename (
prefix = 'gm-staged_hl7_import-',
suffix = '.log'
)
import_logger = logging.FileHandler(log_name)
import_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(import_logger)
_log.debug('log file: %s', log_name)
if not staged_item.lock():
_log.error('cannot lock staged data for HL7 import')
root_logger.removeHandler(import_logger)
return False, log_name
_log.debug('reference ID of staged HL7 data: %s', staged_item['external_data_id'])
filename = staged_item.save_to_file()
_log.debug('unstaged HL7 data into: %s', filename)
if staged_item['pk_identity'] is None:
emr = None
else:
emr = gmPerson.cPatient(staged_item['pk_identity']).emr
success = False
try:
success = __import_single_PID_hl7_file(filename, emr = emr)
if success:
gmIncomingData.delete_incoming_data(pk_incoming_data = staged_item['pk_incoming_data'])
staged_item.unlock()
root_logger.removeHandler(import_logger)
return True, log_name
_log.error('error when importing single-PID/single-MSH file')
except Exception:
_log.exception('error when importing single-PID/single-MSH file')
if not success:
staged_item['comment'] = _('failed import: %s\n') % gmDateTime.pydt_strftime(gmDateTime.pydt_now_here())
staged_item['comment'] += '\n'
staged_item['comment'] += ('-' * 80)
staged_item['comment'] += '\n\n'
log = open(log_name, mode = 'rt', encoding = 'utf-8-sig')
staged_item['comment'] += log.read()
log.close()
staged_item['comment'] += '\n'
staged_item['comment'] += ('-' * 80)
staged_item['comment'] += '\n\n'
staged_item['comment'] += format_hl7_file (
filename,
skip_empty_fields = True,
eol = '\n ',
return_filename = False
)
staged_item.save()
staged_item.unlock()
root_logger.removeHandler(import_logger)
return success, log_name</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.split_hl7_file"><code class="name flex">
<span>def <span class="ident">split_hl7_file</span></span>(<span>filename, target_dir=None, encoding='utf8')</span>
</code></dt>
<dd>
<div class="desc"><p>Multi-step processing of HL7 files.</p>
<ul>
<li>input can be multi-MSH / multi-PID / partially malformed HL7</li>
<li>tries to fix oddities</li>
<li>splits by MSH</li>
<li>
<p>splits by PID into <target_dir></p>
</li>
<li>
<p>needs write permissions in dir_of(filename)</p>
</li>
<li>
<p>moves HL7 files which were successfully split up into dir_of(filename)/done/</p>
</li>
<li>
<p>returns (True|False, list_of_PID_files)</p>
</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def split_hl7_file(filename, target_dir=None, encoding='utf8'):
"""Multi-step processing of HL7 files.
- input can be multi-MSH / multi-PID / partially malformed HL7
- tries to fix oddities
- splits by MSH
- splits by PID into <target_dir>
- needs write permissions in dir_of(filename)
- moves HL7 files which were successfully split up into dir_of(filename)/done/
- returns (True|False, list_of_PID_files)
"""
local_log_name = gmTools.get_unique_filename (
prefix = gmTools.fname_stem(filename) + '-',
suffix = '.split.log'
)
local_logger = logging.FileHandler(local_log_name)
local_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(local_logger)
_log.info('splitting HL7 file: %s', filename)
_log.debug('log file: %s', local_log_name)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
done_dir = os.path.join(orig_dir, 'done')
gmTools.mkdir(done_dir)
error_dir = os.path.join(orig_dir, 'failed')
gmTools.mkdir(error_dir)
work_filename = gmTools.get_unique_filename(prefix = gmTools.fname_stem(filename) + '-', suffix = '.hl7')
if target_dir is None:
target_dir = os.path.join(orig_dir, 'PID')
_log.debug('target dir: %s', target_dir)
gmTools.mkdir(target_dir)
except Exception:
_log.exception('cannot setup splitting environment')
root_logger.removeHandler(local_logger)
return False, None
# split
target_names = []
try:
shutil.copy(filename, work_filename)
fixed_filename = __fix_malformed_hl7_file(work_filename, encoding = encoding)
MSH_fnames = __split_hl7_file_by_MSH(fixed_filename, encoding)
PID_fnames = []
for MSH_fname in MSH_fnames:
PID_fnames.extend(__split_MSH_by_PID(MSH_fname))
for PID_fname in PID_fnames:
shutil.move(PID_fname, target_dir)
target_names.append(os.path.join(target_dir, os.path.split(PID_fname)[1]))
except Exception:
_log.exception('cannot split HL7 file')
for target_name in target_names:
try: os.remove(target_name)
except Exception: pass
root_logger.removeHandler(local_logger)
shutil.move(local_log_name, error_dir)
return False, None
_log.info('successfully split')
root_logger.removeHandler(local_logger)
try:
shutil.move(filename, done_dir)
shutil.move(local_log_name, done_dir)
except shutil.Error:
_log.exception('cannot move hl7 file or log file to holding area')
return True, target_names</code></pre>
</details>
</dd>
<dt id="Gnumed.business.gmHL7.stage_single_PID_hl7_file"><code class="name flex">
<span>def <span class="ident">stage_single_PID_hl7_file</span></span>(<span>filename, source=None, encoding='utf8')</span>
</code></dt>
<dd>
<div class="desc"><p>Multi-step processing of HL7 files.</p>
<ul>
<li>
<p>input must be single-MSH / single-PID / normalized HL7</p>
</li>
<li>
<p>imports into clin.incoming_data</p>
</li>
<li>
<p>needs write permissions in dir_of(filename)</p>
</li>
<li>moves PID files which were successfully staged into dir_of(filename)/done/PID/</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def stage_single_PID_hl7_file(filename, source=None, encoding='utf8'):
"""Multi-step processing of HL7 files.
- input must be single-MSH / single-PID / normalized HL7
- imports into clin.incoming_data
- needs write permissions in dir_of(filename)
- moves PID files which were successfully staged into dir_of(filename)/done/PID/
"""
local_log_name = gmTools.get_unique_filename (
prefix = gmTools.fname_stem(filename) + '-',
suffix = '.stage.log'
)
local_logger = logging.FileHandler(local_log_name)
local_logger.setLevel(logging.DEBUG)
root_logger = logging.getLogger('')
root_logger.addHandler(local_logger)
_log.info('staging [%s] as unmatched incoming HL7%s', filename, gmTools.coalesce(source, '', ' (%s)'))
_log.debug('log file: %s', local_log_name)
# sanity checks/setup
try:
open(filename).close()
orig_dir = os.path.split(filename)[0]
done_dir = os.path.join(orig_dir, 'done')
gmTools.mkdir(done_dir)
error_dir = os.path.join(orig_dir, 'failed')
gmTools.mkdir(error_dir)
except Exception:
_log.exception('cannot setup staging environment')
root_logger.removeHandler(local_logger)
return False
# stage
try:
incoming = gmIncomingData.create_incoming_data('HL7%s' % gmTools.coalesce(source, '', ' (%s)'), filename)
if incoming is None:
_log.error('cannot stage PID file: %s', filename)
root_logger.removeHandler(local_logger)
shutil.move(filename, error_dir)
shutil.move(local_log_name, error_dir)
return False
incoming.update_data_from_file(fname = filename)
except Exception:
_log.exception('error staging PID file')
root_logger.removeHandler(local_logger)
shutil.move(filename, error_dir)
shutil.move(local_log_name, error_dir)
return False
# set additional data
MSH_file = open(filename, mode = 'rt', encoding = 'utf-8-sig', newline = '')
raw_hl7 = MSH_file.read(1024 * 1024 * 5) # 5 MB max
MSH_file.close()
shutil.move(filename, done_dir)
incoming['comment'] = format_hl7_message (
message = raw_hl7,
skip_empty_fields = True,
eol = '\n'
)
HL7 = pyhl7.parse(raw_hl7)
del raw_hl7
incoming['comment'] += '\n'
incoming['comment'] += ('-' * 80)
incoming['comment'] += '\n\n'
log = open(local_log_name, mode = 'rt', encoding = 'utf-8-sig')
incoming['comment'] += log.read()
log.close()
try:
incoming['lastnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
incoming['firstnames'] = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
if val is not None:
incoming['firstnames'] += ' '
incoming['firstnames'] += val
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__dob)
if val is not None:
tmp = time.strptime(val, '%Y%m%d')
incoming['dob'] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
val = HL7.extract_field('PID', segment_num = 1, field_num = PID_field__gender)
if val is not None:
incoming['gender'] = val
incoming['external_data_id'] = filename
#u'fk_patient_candidates',
# u'request_id', # request ID as found in <data>
# u'postcode',
# u'other_info', # other identifying info in .data
# u'requestor', # Requestor of data (e.g. who ordered test results) if available in source data.
# u'fk_identity',
# u'comment', # a free text comment on this row, eg. why is it here, error logs etc
# u'fk_provider_disambiguated' # The provider the data is relevant to.
except Exception:
_log.exception('cannot add more data')
incoming.save()
_log.info('successfully staged')
root_logger.removeHandler(local_logger)
shutil.move(local_log_name, done_dir)
return True</code></pre>
</details>
</dd>
</dl>
</section>
<section>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="Gnumed.business" href="http://www.gnumed.de/downloads/docs/api/business/index.html">Gnumed.business</a></code></li>
</ul>
</li>
<li><h3><a href="gmHL7.html#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="Gnumed.business.gmHL7.extract_HL7_from_XML_CDATA" href="gmHL7.html#Gnumed.business.gmHL7.extract_HL7_from_XML_CDATA">extract_HL7_from_XML_CDATA</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.format_hl7_file" href="gmHL7.html#Gnumed.business.gmHL7.format_hl7_file">format_hl7_file</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.format_hl7_message" href="gmHL7.html#Gnumed.business.gmHL7.format_hl7_message">format_hl7_message</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.import_single_PID_hl7_file" href="gmHL7.html#Gnumed.business.gmHL7.import_single_PID_hl7_file">import_single_PID_hl7_file</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.process_staged_single_PID_hl7_file" href="gmHL7.html#Gnumed.business.gmHL7.process_staged_single_PID_hl7_file">process_staged_single_PID_hl7_file</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.split_hl7_file" href="gmHL7.html#Gnumed.business.gmHL7.split_hl7_file">split_hl7_file</a></code></li>
<li><code><a title="Gnumed.business.gmHL7.stage_single_PID_hl7_file" href="gmHL7.html#Gnumed.business.gmHL7.stage_single_PID_hl7_file">stage_single_PID_hl7_file</a></code></li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc" title="pdoc: Python API documentation generator"><cite>pdoc</cite> 0.10.0</a>.</p>
</footer>
</body>
</html>
|