File: gmHL7.html

package info (click to toggle)
gnumed-client 1.8.21%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 37,764 kB
  • sloc: python: 126,692; javascript: 6,113; sh: 1,195; xml: 36; makefile: 33
file content (1930 lines) | stat: -rw-r--r-- 97,335 bytes parent folder | download
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 -*-
&#34;&#34;&#34;Some HL7 handling.&#34;&#34;&#34;
#============================================================
__author__ = &#34;K.Hilbert &lt;Karsten.Hilbert@gmx.net&gt;&#34;
__license__ = &#34;GPL v2 or later&#34;


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__ == &#39;__main__&#39;:
        sys.path.insert(0, &#39;../../&#39;)
        _ = lambda x:x

from Gnumed.pycommon import gmI18N
if __name__ == &#39;__main__&#39;:
        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(&#39;gm.hl7&#39;)

# constants
HL7_EOL = &#39;\r&#39;
HL7_BRK = &#39;\.br\\&#39;

HL7_SEGMENTS = &#39;FHS BHS MSH PID PV1 OBX NTE ORC OBR&#39;.split()

HL7_segment2field_count = {
        &#39;FHS&#39;: 12,
        &#39;BHS&#39;: 12,
        &#39;MSH&#39;: 19,
        &#39;PID&#39;: 30,
        &#39;PV1&#39;: 52,
        &#39;OBR&#39;: 43,
        &#39;OBX&#39;: 17,
        &#39;NTE&#39;: 3,
        &#39;ORC&#39;: 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 = {
        &#39;MSH&#39;: {
                0: &#39;Segment Type&#39;,
                1: &#39;Field Separator&#39;,
                2: &#39;Encoding Characters&#39;,
                3: &#39;Sending Application&#39;,
                4: &#39;Sending Facility&#39;,
                5: &#39;Receiving Application&#39;,
                6: &#39;Receiving Facility&#39;,
                7: &#39;Date/Time of Message&#39;,
                8: &#39;Security&#39;,
                9: &#39;Message Type&#39;,
                10: &#39;ID: Message Control&#39;,
                11: &#39;ID: Processing&#39;,
                12: &#39;ID: Version&#39;,
                14: &#39;Continuation Pointer&#39;,
                15: &#39;Accept Acknowledgement Type&#39;,
                16: &#39;Application Acknowledgement Type&#39;
        },
        &#39;PID&#39;: {
                0: &#39;Segment Type&#39;,
                1: &#39;&lt;PID&gt; Set ID&#39;,
                2: &#39;Patient ID (external)&#39;,
                3: &#39;Patient ID (internal)&#39;,
                4: &#39;Patient ID (alternate)&#39;,
                5: &#39;Patient Name&#39;,
                7: &#39;Date/Time of birth&#39;,
                8: &#39;Administrative Gender&#39;,
                11: &#39;Patient Address&#39;,
                13: &#39;Patient Phone Number - Home&#39;
        },
        &#39;OBR&#39;: {
                0: &#39;Segment Type&#39;,
                1: &#39;ID: Set&#39;,
                3: &#39;Filler Order Number (= ORC-3)&#39;,
                4: &#39;ID: Universal Service&#39;,
                5: &#39;Priority&#39;,
                6: &#39;Date/Time requested&#39;,
                7: &#39;Date/Time Observation started&#39;,
                14: &#39;Date/Time Specimen received&#39;,
                16: &#39;Ordering Provider&#39;,
                18: &#39;Placer Field 1&#39;,
                20: &#39;Filler Field 1&#39;,
                21: &#39;Filler Field 2&#39;,
                22: &#39;Date/Time Results reported/Status changed&#39;,
                24: &#39;ID: Diagnostic Service Section&#39;,
                25: &#39;Result Status&#39;,
                27: &#39;Quantity/Timing&#39;,
                28: &#39;Result Copies To&#39;
        },
        &#39;ORC&#39;: {
                0: &#39;Segment Type&#39;,
                1: &#39;Order Control&#39;,
                3: &#39;Filler Order Number&#39;,
                12: &#39;Ordering Provider&#39;
        },
        &#39;OBX&#39;: {
                0: &#39;Segment Type&#39;,
                1: &#39;Set ID&#39;,
                2: &#39;Value Type&#39;,
                3: &#39;Identifier (LOINC)&#39;,
                4: &#39;Observation Sub-ID&#39;,
                5: &#39;Value&#39;,
                6: &#39;Units&#39;,
                7: &#39;References Range (Low - High)&#39;,
                8: &#39;Abnormal Flags&#39;,
                11: &#39;Result Status&#39;,
                14: &#39;Date/Time of Observation&#39;
        },
        &#39;NTE&#39;: {
                0: &#39;Segment Type&#39;,
                3: &#39;Comment&#39;
        }
}

HL7_GENDERS = {
        &#39;F&#39;: &#39;f&#39;,
        &#39;M&#39;: &#39;m&#39;,
        &#39;O&#39;: None,
        &#39;U&#39;: None,
        None: None
}

#============================================================
# public API
#============================================================
def extract_HL7_from_XML_CDATA(filename, xml_path, target_dir=None):

        _log.debug(&#39;extracting HL7 from CDATA of &lt;%s&gt; nodes in XML file [%s]&#39;, xml_path, filename)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                work_filename = gmTools.get_unique_filename(prefix = &#39;gm-x2h-%s-&#39; % gmTools.fname_stem(filename), suffix = &#39;.hl7&#39;)
                if target_dir is None:
                        target_dir = os.path.join(orig_dir, &#39;HL7&#39;)
                        done_dir = os.path.join(orig_dir, &#39;done&#39;)
                else:
                        done_dir = os.path.join(target_dir, &#39;done&#39;)
                _log.debug(&#39;target dir: %s&#39;, target_dir)
                gmTools.mkdir(target_dir)
                gmTools.mkdir(done_dir)
        except Exception:
                _log.exception(&#39;cannot setup unwrapping environment&#39;)
                return None

        hl7_xml = pyxml.ElementTree()
        try:
                hl7_xml.parse(filename)
        except pyxml.ParseError:
                _log.exception(&#39;cannot parse [%s]&#39; % filename)
                return None
        nodes = hl7_xml.findall(xml_path)
        if len(nodes) == 0:
                _log.debug(&#39;no nodes found for data extraction&#39;)
                return None

        _log.debug(&#39;unwrapping HL7 from XML into [%s]&#39;, work_filename)
        hl7_file = open(work_filename, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)            # 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 + &#39;&#39;)          # 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=&#39;utf8&#39;):
        &#34;&#34;&#34;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 &lt;target_dir&gt;

        - 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)
        &#34;&#34;&#34;
        local_log_name = gmTools.get_unique_filename (
                prefix = gmTools.fname_stem(filename) + &#39;-&#39;,
                suffix = &#39;.split.log&#39;
        )
        local_logger = logging.FileHandler(local_log_name)
        local_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(local_logger)
        _log.info(&#39;splitting HL7 file: %s&#39;, filename)
        _log.debug(&#39;log file: %s&#39;, local_log_name)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                done_dir = os.path.join(orig_dir, &#39;done&#39;)
                gmTools.mkdir(done_dir)
                error_dir = os.path.join(orig_dir, &#39;failed&#39;)
                gmTools.mkdir(error_dir)
                work_filename = gmTools.get_unique_filename(prefix = gmTools.fname_stem(filename) + &#39;-&#39;, suffix = &#39;.hl7&#39;)
                if target_dir is None:
                        target_dir = os.path.join(orig_dir, &#39;PID&#39;)
                _log.debug(&#39;target dir: %s&#39;, target_dir)
                gmTools.mkdir(target_dir)
        except Exception:
                _log.exception(&#39;cannot setup splitting environment&#39;)
                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(&#39;cannot split HL7 file&#39;)
                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(&#39;successfully split&#39;)
        root_logger.removeHandler(local_logger)
        try:
                shutil.move(filename, done_dir)
                shutil.move(local_log_name, done_dir)
        except shutil.Error:
                _log.exception(&#39;cannot move hl7 file or log file to holding area&#39;)
        return True, target_names

#------------------------------------------------------------
def format_hl7_message(message=None, skip_empty_fields=True, eol=&#39;\n &#39;, source=None):
        # a segment is a line starting with a type
        msg = pyhl7.parse(message)

        output = []
        if source is not None:
                output.append([_(&#39;HL7 Source&#39;), &#39;%s&#39; % source])
        output.append([_(&#39;HL7 data size&#39;), _(&#39;%s bytes&#39;) % len(message)])
        output.append([_(&#39;HL7 Message&#39;), _(&#39; %s segments (lines)%s&#39;) % (len(msg), gmTools.bool2subst(skip_empty_fields, _(&#39;, skipping empty fields&#39;), &#39;&#39;))])

        max_len = 0
        for seg_idx in range(len(msg)):
                seg = msg[seg_idx]
                seg_type = seg[0][0]

                output.append([_(&#39;Segment #%s &lt;%s&gt;&#39;) % (seg_idx, seg_type), _(&#39;%s fields&#39;) % 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 = _(&#39;HL7 %s field&#39;) % seg_type

                        max_len = max(max_len, len(label))

                        if len(field) == 0:
                                if not skip_empty_fields:
                                        output.append([&#39;%2s - %s&#39; % (field_idx, label), _(&#39;&lt;EMTPY&gt;&#39;)])
                                continue
                        if (len(field) == 1) and ((&#39;%s&#39; % field[0]).strip() == &#39;&#39;):
                                if not skip_empty_fields:
                                        output.append([&#39;%2s - %s&#39; % (field_idx, label), _(&#39;&lt;EMTPY&gt;&#39;)])
                                continue

                        content_lines = (&#39;%s&#39; % field).split(HL7_BRK)
                        output.append([&#39;%2s - %s&#39; % (field_idx, label), content_lines[0]])
                        for line in content_lines[1:]:
                                output.append([&#39;&#39;, line])
                        #output.append([u&#39;%2s - %s&#39; % (field_idx, label), u&#39;%s&#39; % field])

        if eol is None:
                return output

        max_len += 7
        return eol.join([ &#39;%s: %s&#39; % ((o[0] + (&#39; &#39; * max_len))[:max_len], o[1]) for o in output ])

#------------------------------------------------------------
def format_hl7_file(filename, skip_empty_fields=True, eol=&#39;\n &#39;, return_filename=False, fix_hl7=True):
        if fix_hl7:
                fixed_name = __fix_malformed_hl7_file(filename)
                hl7_file = open(fixed_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)  # read universal but pass on untranslated
                source = &#39;%s (&lt;- %s)&#39; % (fixed_name, filename)
        else:
                hl7_file = open(filename, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)    # 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 = &#39;\n &#39;.join([ &#39;%s: %s&#39; % ((o[0] + (&#39; &#39; * max_len))[:max_len], o[1]) for o in output ])

        out_name = gmTools.get_unique_filename(prefix = &#39;gm-formatted_hl7-&#39;, suffix = &#39;.hl7&#39;)
        out_file = open(out_name, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;)
        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=&#39;utf8&#39;):
        &#34;&#34;&#34;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/
        &#34;&#34;&#34;
        local_log_name = gmTools.get_unique_filename (
                prefix = gmTools.fname_stem(filename) + &#39;-&#39;,
                suffix = &#39;.stage.log&#39;
        )
        local_logger = logging.FileHandler(local_log_name)
        local_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(local_logger)
        _log.info(&#39;staging [%s] as unmatched incoming HL7%s&#39;, filename, gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;))
        _log.debug(&#39;log file: %s&#39;, local_log_name)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                done_dir = os.path.join(orig_dir, &#39;done&#39;)
                gmTools.mkdir(done_dir)
                error_dir = os.path.join(orig_dir, &#39;failed&#39;)
                gmTools.mkdir(error_dir)
        except Exception:
                _log.exception(&#39;cannot setup staging environment&#39;)
                root_logger.removeHandler(local_logger)
                return False

        # stage
        try:
                incoming = gmIncomingData.create_incoming_data(&#39;HL7%s&#39; % gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;), filename)
                if incoming is None:
                        _log.error(&#39;cannot stage PID file: %s&#39;, 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(&#39;error staging PID file&#39;)
                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 = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)
        raw_hl7 = MSH_file.read(1024 * 1024 * 5)        # 5 MB max
        MSH_file.close()
        shutil.move(filename, done_dir)
        incoming[&#39;comment&#39;] = format_hl7_message (
                message = raw_hl7,
                skip_empty_fields = True,
                eol = &#39;\n&#39;
        )
        HL7 = pyhl7.parse(raw_hl7)
        del raw_hl7
        incoming[&#39;comment&#39;] += &#39;\n&#39;
        incoming[&#39;comment&#39;] += (&#39;-&#39; * 80)
        incoming[&#39;comment&#39;] += &#39;\n\n&#39;
        log = open(local_log_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)
        incoming[&#39;comment&#39;] += log.read()
        log.close()
        try:
                incoming[&#39;lastnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
                incoming[&#39;firstnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
                if val is not None:
                        incoming[&#39;firstnames&#39;] += &#39; &#39;
                        incoming[&#39;firstnames&#39;] += val
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__dob)
                if val is not None:
                        tmp = time.strptime(val, &#39;%Y%m%d&#39;)
                        incoming[&#39;dob&#39;] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__gender)
                if val is not None:
                        incoming[&#39;gender&#39;] = val
                incoming[&#39;external_data_id&#39;] = filename
                #u&#39;fk_patient_candidates&#39;,
                #       u&#39;request_id&#39;,                                          # request ID as found in &lt;data&gt;
                #       u&#39;postcode&#39;,
                #       u&#39;other_info&#39;,                                          # other identifying info in .data
                #       u&#39;requestor&#39;,                                           # Requestor of data (e.g. who ordered test results) if available in source data.
                #       u&#39;fk_identity&#39;,
                #       u&#39;comment&#39;,                                                     # a free text comment on this row, eg. why is it here, error logs etc
                #       u&#39;fk_provider_disambiguated&#39;            # The provider the data is relevant to.
        except Exception:
                _log.exception(&#39;cannot add more data&#39;)
        incoming.save()

        _log.info(&#39;successfully staged&#39;)
        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 = &#39;gm-staged_hl7_import-&#39;,
                suffix = &#39;.log&#39;
        )
        import_logger = logging.FileHandler(log_name)
        import_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(import_logger)
        _log.debug(&#39;log file: %s&#39;, log_name)

        if not staged_item.lock():
                _log.error(&#39;cannot lock staged data for HL7 import&#39;)
                root_logger.removeHandler(import_logger)
                return False, log_name

        _log.debug(&#39;reference ID of staged HL7 data: %s&#39;, staged_item[&#39;external_data_id&#39;])

        filename = staged_item.save_to_file()
        _log.debug(&#39;unstaged HL7 data into: %s&#39;, filename)

        if staged_item[&#39;pk_identity&#39;] is None:
                emr = None
        else:
                emr = gmPerson.cPatient(staged_item[&#39;pk_identity&#39;]).emr

        success = False
        try:
                success = __import_single_PID_hl7_file(filename, emr = emr)
                if success:
                        gmIncomingData.delete_incoming_data(pk_incoming_data = staged_item[&#39;pk_incoming_data&#39;])
                        staged_item.unlock()
                        root_logger.removeHandler(import_logger)
                        return True, log_name
                _log.error(&#39;error when importing single-PID/single-MSH file&#39;)
        except Exception:
                _log.exception(&#39;error when importing single-PID/single-MSH file&#39;)

        if not success:
                staged_item[&#39;comment&#39;] = _(&#39;failed import: %s\n&#39;) % gmDateTime.pydt_strftime(gmDateTime.pydt_now_here())
                staged_item[&#39;comment&#39;] += &#39;\n&#39;
                staged_item[&#39;comment&#39;] += (&#39;-&#39; * 80)
                staged_item[&#39;comment&#39;] += &#39;\n\n&#39;
                log = open(log_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)
                staged_item[&#39;comment&#39;] += log.read()
                log.close()
                staged_item[&#39;comment&#39;] += &#39;\n&#39;
                staged_item[&#39;comment&#39;] += (&#39;-&#39; * 80)
                staged_item[&#39;comment&#39;] += &#39;\n\n&#39;
                staged_item[&#39;comment&#39;] += format_hl7_file (
                        filename,
                        skip_empty_fields = True,
                        eol = &#39;\n &#39;,
                        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 = &#39;%s.import.log&#39; % filename
        import_logger = logging.FileHandler(log_name)
        import_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(import_logger)
        _log.debug(&#39;log file: %s&#39;, log_name)

        success = True
        try:
                success = __import_single_PID_hl7_file(filename)
                if not success:
                        _log.error(&#39;error when importing single-PID/single-MSH file&#39;)
        except Exception:
                _log.exception(&#39;error when importing single-PID/single-MSH file&#39;)

        root_logger.removeHandler(import_logger)
        return success, log_name

#============================================================
# internal helpers
#============================================================
def __fix_malformed_hl7_file(filename, encoding=&#39;utf8&#39;):

        _log.debug(&#39;fixing HL7 file [%s]&#39;, 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 = &#39;gm_fix1-%s-&#39; % gmTools.fname_stem(filename),
                suffix = &#39;.hl7&#39;
        )
        hl7_in = open(filename, mode = &#39;rt&#39;, encoding = encoding)                                       # universal newlines: translate any type of EOL to \n
        hl7_out = open(out1_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)        # newline=&#39;&#39; -&gt; no translation of EOL at all
        is_first_line = True
        for line in hl7_in:
                # skip empty line
                if line.strip() == &#39;&#39;:
                        continue
                # starts with known segment ?
                segment = line[:3]
                if (segment in HL7_SEGMENTS) and (line[3] == &#39;|&#39;):
                        if not is_first_line:
                                hl7_out.write(HL7_EOL)
                        else:
                                is_first_line = False
                else:
                        hl7_out.write(&#39; &#39;)
                hl7_out.write(line.rstrip())
        hl7_out.write(HL7_EOL)
        hl7_out.close()
        hl7_in.close()

        # second pass:
        # - normalize # of fields per line
        # - remove &#39;\.br.\&#39;-only fields ;-)
        out2_fname = gmTools.get_unique_filename (
                prefix = &#39;gm_fix2-%s-&#39; % gmTools.fname_stem(filename),
                suffix = &#39;.hl7&#39;
        )
        # we can now _expect_ lines to end in HL7_EOL, anything else is an error
        hl7_in = open(out1_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = HL7_EOL)
        hl7_out = open(out2_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)
        for line in hl7_in:
                line = line.strip()
                seg_type = line[:3]                                             # assumption: field separator = &#39;|&#39;
                field_count = line.count(&#39;|&#39;) + 1               # assumption: no &#39;|&#39; 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 &gt; 0:
                        line += (&#39;|&#39; * missing_fields_count)
                cleaned_fields = []
                for field in line.split(&#39;|&#39;):
                        if field.replace(HL7_BRK, &#39;&#39;).strip() == &#39;&#39;:
                                cleaned_fields.append(&#39;&#39;)
                                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(&#39;|&#39;.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 = &#39;gm_fix3-%s-&#39; % gmTools.fname_stem(filename),
                suffix = &#39;.hl7&#39;
        )
        # we can now _expect_ lines to end in HL7_EOL, anything else is an error
        hl7_in = open(out2_fname, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = HL7_EOL)
        hl7_out = open(out3_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)
        prev_identity = None
        prev_fields = None
        for line in hl7_in:
                line = line.strip()
                if not line.startswith(&#39;OBX|&#39;):
                        if prev_fields is not None:
                                hl7_out.write(&#39;|&#39;.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(&#39;|&#39;)
                if curr_fields[OBX_field__datatype] != &#39;FT&#39;:
                        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(&#39;|&#39;)
                        prev_identity = line.split(&#39;|&#39;)
                        prev_identity[OBX_field__set_id] = &#39;&#39;
                        prev_identity[OBX_field__subid] = &#39;&#39;
                        prev_identity[OBX_field__value] = &#39;&#39;
                        prev_identity = &#39;|&#39;.join(prev_identity)
                        continue
                # non-first FT type OBX
                curr_identity = line.split(&#39;|&#39;)
                curr_identity[OBX_field__set_id] = &#39;&#39;
                curr_identity[OBX_field__subid] = &#39;&#39;
                curr_identity[OBX_field__value] = &#39;&#39;
                curr_identity = &#39;|&#39;.join(curr_identity)
                if curr_identity != prev_identity:
                        # write out previous line
                        hl7_out.write(&#39;|&#39;.join(prev_fields) + HL7_EOL)
                        # keep current fields, since it may start a &#34;repeat FT type OBX block&#34;
                        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(&#39;|&#39;.join(prev_fields) + HL7_EOL)
        hl7_out.close()
        hl7_in.close()

        return out3_fname

#------------------------------------------------------------
def __split_hl7_file_by_MSH(filename, encoding=&#39;utf8&#39;):

        _log.debug(&#39;splitting [%s] into single-MSH files&#39;, filename)

        hl7_in = open(filename, mode = &#39;rt&#39;, 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 == &#39;&#39;:
                                continue
                        if line.startswith(&#39;FHS|&#39;):
                                _log.debug(&#39;ignoring FHS&#39;)
                                continue
                        if line.startswith(&#39;BHS|&#39;):
                                _log.debug(&#39;ignoring BHS&#39;)
                                continue
                        if not line.startswith(&#39;MSH|&#39;):
                                raise ValueError(&#39;HL7 file &lt;%s&gt; does not start with &#34;MSH&#34; line&#39; % filename)
                        first_line = False
                # start new file
                if line.startswith(&#39;MSH|&#39;):
                        if MSH_file is not None:
                                MSH_file.close()
                        idx += 1
                        out_fname = gmTools.get_unique_filename(prefix = &#39;%s-MSH_%s-&#39; % (gmTools.fname_stem(filename), idx), suffix = &#39;hl7&#39;)
                        _log.debug(&#39;writing message %s to [%s]&#39;, idx, out_fname)
                        MSH_fnames.append(out_fname)
                        MSH_file = open(out_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)
                # ignore BTS / FTS lines
                if line.startswith(&#39;BTS|&#39;):
                        _log.debug(&#39;ignoring BTS&#39;)
                        continue
                if line.startswith(&#39;FTS|&#39;):
                        _log.debug(&#39;ignoring FTS&#39;)
                        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):
        &#34;&#34;&#34;Assumes:
                - ONE MSH per file
                - utf8 encoding
                - first non-empty line must be MSH line
                - next line must be PID line

                IOW, what&#39;s created by __split_hl7_file_by_MSH()
        &#34;&#34;&#34;
        _log.debug(&#39;splitting single-MSH file [%s] into single-PID files&#39;, filename)

        MSH_in = open(filename, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)

        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 == &#39;&#39;:
                        continue

                # first non-empty line must be MSH
                if looking_for_MSH:
                        if line.startswith(&#39;MSH|&#39;):
                                looking_for_MSH = False
                                MSH_line = line + HL7_EOL
                                continue
                        raise ValueError(&#39;HL7 MSH file &lt;%s&gt; does not start with &#34;MSH&#34; line&#39; % filename)
                else:
                        if line.startswith(&#39;MSH|&#39;):
                                raise ValueError(&#39;HL7 single-MSH file &lt;%s&gt; contains more than one MSH line&#39; % filename)

                # first non-empty line after MSH must be PID
                if looking_for_first_PID:
                        if not line.startswith(&#39;PID|&#39;):
                                raise ValueError(&#39;HL7 MSH file &lt;%s&gt; does not have &#34;PID&#34; line follow &#34;MSH&#34; line&#39; % filename)
                        looking_for_first_PID = False

                # start new file if line is PID
                if line.startswith(&#39;PID|&#39;):
                        if PID_file is not None:
                                PID_file.close()
                        idx += 1
                        out_fname = gmTools.get_unique_filename(prefix = &#39;%s-PID_%s-&#39; % (gmTools.fname_stem(filename), idx), suffix = &#39;hl7&#39;)
                        _log.debug(&#39;writing message for PID %s to [%s]&#39;, idx, out_fname)
                        PID_fnames.append(out_fname)
                        PID_file = open(out_fname, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)
                        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 = &#39;[HL7 name::%s]&#39; % hl7_lab
        for gm_lab in gmPathLab.get_test_orgs():
                if comment_tag in gmTools.coalesce(gm_lab[&#39;comment&#39;], &#39;&#39;):
                        _log.debug(&#39;found lab [%s] from HL7 file in GNUmed database:&#39;, hl7_lab)
                        _log.debug(gm_lab)
                        return gm_lab
        _log.debug(&#39;lab not found: %s&#39;, 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(&#39;cannot create lab [%s] in GNUmed&#39; % hl7_lab)
        _log.debug(&#39;created lab: %s&#39;, 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(&#39;test type [%s::%s::%s] not found for lab #%s, creating&#39;, 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(&#39;created as: %s&#39;, tt)

        if loinc is None:
                return tt
        if loinc.strip() == &#39;&#39;:
                return tt
        if tt[&#39;loinc&#39;] is None:
                tt[&#39;loinc&#39;] = loinc
                tt.save(conn = link_obj)
                return tt
        if tt[&#39;loinc&#39;] != loinc:
#               raise ValueError(&#39;LOINC code mismatch between GM (%s) and HL7 (%s) for result type [%s]&#39; % (tt[&#39;loinc&#39;], loinc, name))
                _log.error(&#39;LOINC code mismatch between GM (%s) and HL7 (%s) for result type [%s]&#39;, tt[&#39;loinc&#39;], 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(&#39;OBX&#39;))
        except KeyError:
                _log.error(&#34;HL7 does not contain OBX segments, nothing to do&#34;)
                return
        for OBX_idx in range(OBX_count):
                unit = hl7_data.extract_field(segment = &#39;OBX&#39;, segment_num = OBX_idx, field_num = OBX_field__unit)
                if unit == &#39;&#39;:
                        unit = None
                LOINC = hl7_data.extract_field(segment = &#39;OBX&#39;, segment_num = OBX_idx, field_num = OBX_field__type, component_num = OBX_component__loinc)
                tname = hl7_data.extract_field(segment = &#39;OBX&#39;, 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(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
        pat_fname = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
        pat_mname = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
        if pat_mname is not None:
                pat_fname += &#39; &#39;
                pat_fname += pat_mname
        _log.debug(&#39;patient data from PID segment: first=%s (middle=%s) last=%s&#39;, 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(&#39;PID&#39;, segment_num = 1, field_num = PID_field__gender)]
        hl7_dob = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__dob)
        if hl7_dob is not None:
                tmp = time.strptime(hl7_dob, &#39;%Y%m%d&#39;)
                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(&#39;no match candidate, not auto-importing&#39;)
                _log.debug(dto)
                return []
        if len(idents) &gt; 1:
                _log.warning(&#39;more than one match candidate, not auto-importing&#39;)
                _log.debug(dto)
                return idents
        return [gmPerson.cPatient(idents[0].ID)]

#------------------------------------------------------------
def __hl7dt2pydt(hl7dt):
        if hl7dt == &#39;&#39;:
                return None

        if len(hl7dt) == 8:
                tmp = time.strptime(hl7dt, &#39;%Y%m%d&#39;)
                return pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)

        if len(hl7dt) == 12:
                tmp = time.strptime(hl7dt, &#39;%Y%m%d%H%M&#39;)
                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, &#39;%Y%m%d%H%M%S&#39;)
                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(&#39;Observation timestamp not parseable: [%s]&#39;, hl7dt)

#------------------------------------------------------------
def __import_single_PID_hl7_file(filename, emr=None):
        &#34;&#34;&#34;Assumes single-PID/single-MSH HL7 file.&#34;&#34;&#34;

        _log.debug(&#39;importing single-PID single-MSH HL7 data from [%s]&#39;, filename)

        # read the file
        MSH_file = open(filename, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)
        HL7 = pyhl7.parse(MSH_file.read(1024 * 1024 * 5))       # 5 MB max
        MSH_file.close()

        # sanity checks
        if len(HL7.segments(&#39;MSH&#39;)) != 1:
                _log.error(&#39;more than one MSH segment&#39;)
                return False
        if len(HL7.segments(&#39;PID&#39;)) != 1:
                _log.error(&#39;more than one PID segment&#39;)
                return False

        # ensure lab is in database
        hl7_lab = HL7.extract_field(&#39;MSH&#39;, 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[&#39;pk_test_org&#39;])

        # find patient
        if emr is None:
                #PID = HL7.segment(&#39;PID&#39;)
                pats = __PID2dto(HL7 = HL7)
                if len(pats) == 0:
                        conn.rollback()
                        return False
                if len(pats) &gt; 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(&#39;processing line #%s = segment of type &lt;%s&gt;&#39;, seg_idx, seg_type)

                if seg_type == &#39;MSH&#39;:
                        msh_seen = True

                if seg_type == &#39;PID&#39;:
                        if not msh_seen:
                                conn.rollback()
                                _log.error(&#39;PID segment before MSH segment&#39;)
                                return False
                        #pid_seen = True

                if seg_type in [&#39;MSH&#39;, &#39;PID&#39;]:
                        _log.info(&#39;segment already handled&#39;)
                        previous_segment = seg_type
                        obr = {}
                        current_result = None
                        continue

                if seg_type in [&#39;ORC&#39;]:
                        _log.info(&#39;currently ignoring %s segments&#39;, seg_type)
                        previous_segment = seg_type
                        obr = {}
                        current_result = None
                        continue

                if seg_type == &#39;OBR&#39;:
                        previous_segment = seg_type
                        last_obr = seg
                        current_result = None
                        obr[&#39;abbrev&#39;] = (&#39;%s&#39; % seg[OBR_field__service_name][0]).strip()
                        try:
                                obr[&#39;name&#39;] = (&#39;%s&#39; % seg[OBR_field__service_name][1]).strip()
                        except IndexError:
                                obr[&#39;name&#39;] = obr[&#39;abbrev&#39;]
                        for field_name in [OBR_field__ts_ended, OBR_field__ts_started, OBR_field__ts_specimen_received, OBR_field__ts_requested]:
                                obr[&#39;clin_when&#39;] = seg[field_name][0].strip()
                                if obr[&#39;clin_when&#39;] != &#39;&#39;:
                                        break
                        continue

                if seg_type == &#39;OBX&#39;:
                        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(&#39;\.br\\&#39;, &#39;\n&#39;)
                        # determine test type
                        unit = seg[OBX_field__unit][0].strip()
                        if unit == &#39;&#39;:
                                if is_num:
                                        unit = &#39;1/1&#39;
                                else:
                                        unit = None
                        test_type = __find_or_create_test_type (
                                loinc = &#39;%s&#39; % seg[OBX_field__type][0][OBX_component__loinc-1],
                                name = &#39;%s&#39; % seg[OBX_field__type][0][OBX_component__name-1],
                                pk_lab = gm_lab[&#39;pk_test_org&#39;],
                                unit = unit,
                                link_obj = conn
                        )
                        # eventually, episode should be read from lab_request
                        epi = emr.add_episode (
                                link_obj = conn,
                                episode_name = &#39;administrative&#39;,
                                is_open = False,
                                allow_dupes = False
                        )
                        current_result = emr.add_test_result (
                                link_obj = conn,
                                episode = epi[&#39;pk_episode&#39;],
                                type = test_type[&#39;pk_test_type&#39;],
                                intended_reviewer = gmStaff.gmCurrentProvider()[&#39;pk_staff&#39;],
                                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 != &#39;&#39;:
                                current_result.reference_range = ref_range
                        flag = seg[OBX_field__abnormal_flag][0].strip()
                        if flag != &#39;&#39;:
                                current_result[&#39;abnormality_indicator&#39;] = flag
                        current_result[&#39;status&#39;] = seg[OBX_field__status][0].strip()
                        current_result[&#39;val_grouping&#39;] = seg[OBX_field__subid][0].strip()
                        current_result[&#39;source_data&#39;] = &#39;&#39;
                        if last_obr is not None:
                                current_result[&#39;source_data&#39;] += str(last_obr)
                                current_result[&#39;source_data&#39;] += &#39;\n&#39;
                        current_result[&#39;source_data&#39;] += str(seg)
                        clin_when = seg[OBX_field__timestamp][0].strip()
                        if clin_when == &#39;&#39;:
                                _log.warning(&#39;no &lt;Observation timestamp&gt; in OBX, trying OBR timestamp&#39;)
                                clin_when = obr[&#39;clin_when&#39;]
                        try:
                                clin_when = __hl7dt2pydt(clin_when)
                        except ValueError:
                                _log.exception(&#39;clin_when from OBX or OBR not useable, assuming &lt;today&gt;&#39;)
                        if clin_when is not None:
                                current_result[&#39;clin_when&#39;] = clin_when
                        current_result.save(conn = conn)
                        when_list[gmDateTime.pydt_strftime(current_result[&#39;clin_when&#39;], &#39;%Y %b %d&#39;)] = 1
                        previous_segment = seg_type
                        continue

                if seg_type == &#39;NTE&#39;:
                        note = seg[NET_field__note][0].strip().replace(&#39;\.br\\&#39;, &#39;\n&#39;)
                        if note == &#39;&#39;:
                                _log.debug(&#39;empty NTE segment&#39;)
                                previous_segment = seg_type                     # maybe not ? (HL7 providers happen to use empty NTE segments to &#34;structure&#34; 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 == &#39;OBR&#39;:
                                _log.debug(&#39;NTE following OBR: general note, using OBR timestamp [%s]&#39;, obr[&#39;clin_when&#39;])
                                current_result = None
                                name = obr[&#39;name&#39;]
                                if name == &#39;&#39;:
                                        name = _(&#39;Comment&#39;)
                                # FIXME: please suggest a LOINC for &#34;order comment&#34;
                                test_type = __find_or_create_test_type(name = name, pk_lab = gm_lab[&#39;pk_test_org&#39;], abbrev = obr[&#39;abbrev&#39;], link_obj = conn)
                                # eventually, episode should be read from lab_request
                                epi = emr.add_episode (
                                        link_obj = conn,
                                        episode_name = &#39;administrative&#39;,
                                        is_open = False,
                                        allow_dupes = False
                                )
                                nte_result = emr.add_test_result (
                                        link_obj = conn,
                                        episode = epi[&#39;pk_episode&#39;],
                                        type = test_type[&#39;pk_test_type&#39;],
                                        intended_reviewer = gmStaff.gmCurrentProvider()[&#39;pk_staff&#39;],
                                        val_alpha = note
                                )
                                #nte_result[&#39;val_grouping&#39;] = seg[OBX_field__subid][0].strip()
                                nte_result[&#39;source_data&#39;] = str(seg)
                                try:
                                        nte_result[&#39;clin_when&#39;] = __hl7dt2pydt(obr[&#39;clin_when&#39;])
                                except ValueError:
                                        _log.exception(&#39;no .clin_when from OBR for NTE pseudo-OBX available&#39;)
                                nte_result.save(conn = conn)
                                continue

                        if (previous_segment == &#39;OBX&#39;) and (current_result is not None):
                                current_result[&#39;source_data&#39;] += &#39;\n&#39;
                                current_result[&#39;source_data&#39;] += str(seg)
                                current_result[&#39;note_test_org&#39;] = gmTools.coalesce (
                                        current_result[&#39;note_test_org&#39;],
                                        note,
                                        &#39;%%s\n%s&#39; % note
                                )
                                current_result.save(conn = conn)
                                previous_segment = seg_type
                                continue

                        _log.error(&#39;unexpected NTE segment&#39;)
                        had_errors = True
                        break

                _log.error(&#39;unknown segment, aborting&#39;)
                _log.debug(&#39;line: %s&#39;, seg)
                had_errors = True
                break

        if had_errors:
                conn.rollback()
                return False

        conn.commit()

        # record import in chart
        try:
                no_results = len(HL7.segments(&#39;OBX&#39;))
        except KeyError:
                no_results = &#39;?&#39;
        soap = _(
                &#39;Imported HL7 file [%s]:\n&#39;
                &#39; lab &#34;%s&#34; (%s@%s), %s results (%s)&#39;
        ) % (
                filename,
                hl7_lab,
                gm_lab[&#39;unit&#39;],
                gm_lab[&#39;organization&#39;],
                no_results,
                &#39; / &#39;.join(list(when_list))
        )
        epi = emr.add_episode (
                episode_name = &#39;administrative&#39;,
                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 = &#39;HL7 data&#39;,
                pk_episodes = [epi[&#39;pk_episode&#39;]],
                order_by = &#39;clin_when DESC&#39;
        )
        if len(hl7_docs) &gt; 0:
                # there should only ever be one unless the user manually creates more,
                # also, it should always be the latest since &#34;ORDER BY clin_when DESC&#34;
                hl7_doc = hl7_docs[0]
        else:
                hl7_doc = folder.add_document (
                        document_type = &#39;HL7 data&#39;,
                        encounter = emr.active_encounter[&#39;pk_encounter&#39;],
                        episode = epi[&#39;pk_episode&#39;]
                )
                hl7_doc[&#39;comment&#39;] = _(&#39;list of imported HL7 data files&#39;)
                hl7_doc[&#39;pk_org_unit&#39;] = gmPraxis.gmCurrentPraxisBranch()[&#39;pk_org_unit&#39;]
        hl7_doc[&#39;clin_when&#39;] = gmDateTime.pydt_now_here()
        hl7_doc.save()
        part = hl7_doc.add_part(file = filename)
        part[&#39;obj_comment&#39;] = _(&#39;Result dates: %s&#39;) % &#39; / &#39;.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):
        &#34;&#34;&#34;Consumes single-MSH single-PID HL7 files.&#34;&#34;&#34;

        _log.debug(&#39;staging [%s] as unmatched incoming HL7%s&#39;, gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;), filename)

        # parse HL7
        MSH_file = open(filename, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)
        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 = &#39;\n&#39;
        )
        HL7 = pyhl7.parse(raw_hl7)
        del raw_hl7

        # import file
        incoming = gmIncomingData.create_incoming_data(&#39;HL7%s&#39; % gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;), filename)
        if incoming is None:
                return None
        incoming.update_data_from_file(fname = filename)
        incoming[&#39;comment&#39;] = formatted_hl7
        if logfile is not None:
                log = open(logfile, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)
                incoming[&#39;comment&#39;] += &#39;\n&#39;
                incoming[&#39;comment&#39;] += (&#39;-&#39; * 80)
                incoming[&#39;comment&#39;] += &#39;\n\n&#39;
                incoming[&#39;comment&#39;] += log.read()
                log.close()
        try:
                incoming[&#39;lastnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
                incoming[&#39;firstnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
                if val is not None:
                        incoming[&#39;firstnames&#39;] += &#39; &#39;
                        incoming[&#39;firstnames&#39;] += val
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__dob)
                if val is not None:
                        tmp = time.strptime(val, &#39;%Y%m%d&#39;)
                        incoming[&#39;dob&#39;] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__gender)
                if val is not None:
                        incoming[&#39;gender&#39;] = val
                incoming[&#39;external_data_id&#39;] = filename
                #u&#39;fk_patient_candidates&#39;,
                #       u&#39;request_id&#39;,                                          # request ID as found in &lt;data&gt;
                #       u&#39;postcode&#39;,
                #       u&#39;other_info&#39;,                                          # other identifying info in .data
                #       u&#39;requestor&#39;,                                           # Requestor of data (e.g. who ordered test results) if available in source data.
                #       u&#39;fk_identity&#39;,
                #       u&#39;comment&#39;,                                                     # a free text comment on this row, eg. why is it here, error logs etc
                #       u&#39;fk_provider_disambiguated&#39;            # The provider the data is relevant to.
        except KeyError:
                _log.exception(&#39;no PID segment, cannot add more data&#39;)
        incoming.save()

        return incoming

#============================================================
# main
#------------------------------------------------------------
if __name__ == &#34;__main__&#34;:

        if len(sys.argv) &lt; 2:
                sys.exit()

        if sys.argv[1] != &#39;test&#39;:
                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(&#34;error with&#34;, filename)
        #-------------------------------------------------------
        def test_xml_extract():
                hl7 = extract_HL7_from_XML_CDATA(sys.argv[2], &#39;.//Message&#39;)
                print(&#34;HL7:&#34;, hl7)
                #result, PID_fnames = split_hl7_file(hl7)
                #print &#34;result:&#34;, result
                #print &#34;per-PID MSH files:&#34;
                #for name in PID_fnames:
                #       print &#34; &#34;, name
        #-------------------------------------------------------
        def test_stage_hl7_from_xml():
                hl7 = extract_HL7_from_XML_CDATA(sys.argv[2], &#39;.//Message&#39;)
                print(&#34;HL7:&#34;, hl7)
                result, PID_fnames = split_hl7_file(hl7)
                print(&#34;result:&#34;, result)
                print(&#34;staging per-PID HL7 files:&#34;)
                for name in PID_fnames:
                        print(&#34; file:&#34;, name)
                        __stage_MSH_as_incoming_data(name, source = &#39;Excelleris&#39;)
        #-------------------------------------------------------
        def test_split_hl7_file():
                result, PID_fnames = split_hl7_file(sys.argv[2])
                print(&#34;result:&#34;, result)
                print(&#34;per-PID HL7 files:&#34;)
                for name in PID_fnames:
                        print(&#34; file:&#34;, name)
        #-------------------------------------------------------
        def test_stage_hl7():
                fixed = __fix_malformed_hl7_file(sys.argv[2])
                print(&#34;fixed HL7:&#34;, fixed)
                #PID_fnames = split_HL7_by_PID(fixed, encoding=&#39;utf8&#39;)
                print(&#34;staging per-PID HL7 files:&#34;)
                for name in []: #PID_fnames:
                        print(&#34; file:&#34;, name)
                        #print &#34;&#34;, __stage_MSH_as_incoming_data(name, source = u&#39;?&#39;)
        #-------------------------------------------------------
        def test_format_hl7_message():
                tests = [
                        &#34;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&#34;,
                        &#34;OBX|2|NM|22748-8^LDL Cholesterol||4.0|mmol/L|1.5 - 3.4|H|||F|||20031004073300&#34;
                ]
                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(&#34;fixed HL7:&#34;, __fix_malformed_hl7_file(sys.argv[2]))
        #-------------------------------------------------------
        def test_parse_hl7():
                MSH_file = open(sys.argv[2], mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)
                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 = &#39;\n&#39;
                ))
                HL7 = pyhl7.parse(raw_hl7)
                del raw_hl7
                for seg in HL7.segments(&#39;MSH&#39;):
                        print(seg)
                print(&#34;PID:&#34;)
                print(HL7.extract_field(&#39;PID&#39;))
                print(HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname))
                print(HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname))

#                       incoming[&#39;firstnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
#                       val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
#                       if val is not None:
#                               incoming[&#39;firstnames&#39;] += u&#39; &#39;
#                               incoming[&#39;firstnames&#39;] += val
#                       val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__dob)
#                       if val is not None:
#                               tmp = time.strptime(val, &#39;%Y%m%d&#39;)
#                               incoming[&#39;dob&#39;] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
#                       val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__gender)
#                       if val is not None:
#                               incoming[&#39;gender&#39;] = val
#                       incoming[&#39;external_data_id&#39;] = 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(&#39;extracting HL7 from CDATA of &lt;%s&gt; nodes in XML file [%s]&#39;, xml_path, filename)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                work_filename = gmTools.get_unique_filename(prefix = &#39;gm-x2h-%s-&#39; % gmTools.fname_stem(filename), suffix = &#39;.hl7&#39;)
                if target_dir is None:
                        target_dir = os.path.join(orig_dir, &#39;HL7&#39;)
                        done_dir = os.path.join(orig_dir, &#39;done&#39;)
                else:
                        done_dir = os.path.join(target_dir, &#39;done&#39;)
                _log.debug(&#39;target dir: %s&#39;, target_dir)
                gmTools.mkdir(target_dir)
                gmTools.mkdir(done_dir)
        except Exception:
                _log.exception(&#39;cannot setup unwrapping environment&#39;)
                return None

        hl7_xml = pyxml.ElementTree()
        try:
                hl7_xml.parse(filename)
        except pyxml.ParseError:
                _log.exception(&#39;cannot parse [%s]&#39; % filename)
                return None
        nodes = hl7_xml.findall(xml_path)
        if len(nodes) == 0:
                _log.debug(&#39;no nodes found for data extraction&#39;)
                return None

        _log.debug(&#39;unwrapping HL7 from XML into [%s]&#39;, work_filename)
        hl7_file = open(work_filename, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;, newline = &#39;&#39;)            # 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 + &#39;&#39;)          # 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=&#39;\n &#39;, return_filename=False, fix_hl7=True):
        if fix_hl7:
                fixed_name = __fix_malformed_hl7_file(filename)
                hl7_file = open(fixed_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)  # read universal but pass on untranslated
                source = &#39;%s (&lt;- %s)&#39; % (fixed_name, filename)
        else:
                hl7_file = open(filename, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)    # 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 = &#39;\n &#39;.join([ &#39;%s: %s&#39; % ((o[0] + (&#39; &#39; * max_len))[:max_len], o[1]) for o in output ])

        out_name = gmTools.get_unique_filename(prefix = &#39;gm-formatted_hl7-&#39;, suffix = &#39;.hl7&#39;)
        out_file = open(out_name, mode = &#39;wt&#39;, encoding = &#39;utf8&#39;)
        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=&#39;\n &#39;, source=None):
        # a segment is a line starting with a type
        msg = pyhl7.parse(message)

        output = []
        if source is not None:
                output.append([_(&#39;HL7 Source&#39;), &#39;%s&#39; % source])
        output.append([_(&#39;HL7 data size&#39;), _(&#39;%s bytes&#39;) % len(message)])
        output.append([_(&#39;HL7 Message&#39;), _(&#39; %s segments (lines)%s&#39;) % (len(msg), gmTools.bool2subst(skip_empty_fields, _(&#39;, skipping empty fields&#39;), &#39;&#39;))])

        max_len = 0
        for seg_idx in range(len(msg)):
                seg = msg[seg_idx]
                seg_type = seg[0][0]

                output.append([_(&#39;Segment #%s &lt;%s&gt;&#39;) % (seg_idx, seg_type), _(&#39;%s fields&#39;) % 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 = _(&#39;HL7 %s field&#39;) % seg_type

                        max_len = max(max_len, len(label))

                        if len(field) == 0:
                                if not skip_empty_fields:
                                        output.append([&#39;%2s - %s&#39; % (field_idx, label), _(&#39;&lt;EMTPY&gt;&#39;)])
                                continue
                        if (len(field) == 1) and ((&#39;%s&#39; % field[0]).strip() == &#39;&#39;):
                                if not skip_empty_fields:
                                        output.append([&#39;%2s - %s&#39; % (field_idx, label), _(&#39;&lt;EMTPY&gt;&#39;)])
                                continue

                        content_lines = (&#39;%s&#39; % field).split(HL7_BRK)
                        output.append([&#39;%2s - %s&#39; % (field_idx, label), content_lines[0]])
                        for line in content_lines[1:]:
                                output.append([&#39;&#39;, line])
                        #output.append([u&#39;%2s - %s&#39; % (field_idx, label), u&#39;%s&#39; % field])

        if eol is None:
                return output

        max_len += 7
        return eol.join([ &#39;%s: %s&#39; % ((o[0] + (&#39; &#39; * 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 = &#39;%s.import.log&#39; % filename
        import_logger = logging.FileHandler(log_name)
        import_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(import_logger)
        _log.debug(&#39;log file: %s&#39;, log_name)

        success = True
        try:
                success = __import_single_PID_hl7_file(filename)
                if not success:
                        _log.error(&#39;error when importing single-PID/single-MSH file&#39;)
        except Exception:
                _log.exception(&#39;error when importing single-PID/single-MSH file&#39;)

        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 = &#39;gm-staged_hl7_import-&#39;,
                suffix = &#39;.log&#39;
        )
        import_logger = logging.FileHandler(log_name)
        import_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(import_logger)
        _log.debug(&#39;log file: %s&#39;, log_name)

        if not staged_item.lock():
                _log.error(&#39;cannot lock staged data for HL7 import&#39;)
                root_logger.removeHandler(import_logger)
                return False, log_name

        _log.debug(&#39;reference ID of staged HL7 data: %s&#39;, staged_item[&#39;external_data_id&#39;])

        filename = staged_item.save_to_file()
        _log.debug(&#39;unstaged HL7 data into: %s&#39;, filename)

        if staged_item[&#39;pk_identity&#39;] is None:
                emr = None
        else:
                emr = gmPerson.cPatient(staged_item[&#39;pk_identity&#39;]).emr

        success = False
        try:
                success = __import_single_PID_hl7_file(filename, emr = emr)
                if success:
                        gmIncomingData.delete_incoming_data(pk_incoming_data = staged_item[&#39;pk_incoming_data&#39;])
                        staged_item.unlock()
                        root_logger.removeHandler(import_logger)
                        return True, log_name
                _log.error(&#39;error when importing single-PID/single-MSH file&#39;)
        except Exception:
                _log.exception(&#39;error when importing single-PID/single-MSH file&#39;)

        if not success:
                staged_item[&#39;comment&#39;] = _(&#39;failed import: %s\n&#39;) % gmDateTime.pydt_strftime(gmDateTime.pydt_now_here())
                staged_item[&#39;comment&#39;] += &#39;\n&#39;
                staged_item[&#39;comment&#39;] += (&#39;-&#39; * 80)
                staged_item[&#39;comment&#39;] += &#39;\n\n&#39;
                log = open(log_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)
                staged_item[&#39;comment&#39;] += log.read()
                log.close()
                staged_item[&#39;comment&#39;] += &#39;\n&#39;
                staged_item[&#39;comment&#39;] += (&#39;-&#39; * 80)
                staged_item[&#39;comment&#39;] += &#39;\n\n&#39;
                staged_item[&#39;comment&#39;] += format_hl7_file (
                        filename,
                        skip_empty_fields = True,
                        eol = &#39;\n &#39;,
                        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=&#39;utf8&#39;):
        &#34;&#34;&#34;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 &lt;target_dir&gt;

        - 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)
        &#34;&#34;&#34;
        local_log_name = gmTools.get_unique_filename (
                prefix = gmTools.fname_stem(filename) + &#39;-&#39;,
                suffix = &#39;.split.log&#39;
        )
        local_logger = logging.FileHandler(local_log_name)
        local_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(local_logger)
        _log.info(&#39;splitting HL7 file: %s&#39;, filename)
        _log.debug(&#39;log file: %s&#39;, local_log_name)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                done_dir = os.path.join(orig_dir, &#39;done&#39;)
                gmTools.mkdir(done_dir)
                error_dir = os.path.join(orig_dir, &#39;failed&#39;)
                gmTools.mkdir(error_dir)
                work_filename = gmTools.get_unique_filename(prefix = gmTools.fname_stem(filename) + &#39;-&#39;, suffix = &#39;.hl7&#39;)
                if target_dir is None:
                        target_dir = os.path.join(orig_dir, &#39;PID&#39;)
                _log.debug(&#39;target dir: %s&#39;, target_dir)
                gmTools.mkdir(target_dir)
        except Exception:
                _log.exception(&#39;cannot setup splitting environment&#39;)
                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(&#39;cannot split HL7 file&#39;)
                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(&#39;successfully split&#39;)
        root_logger.removeHandler(local_logger)
        try:
                shutil.move(filename, done_dir)
                shutil.move(local_log_name, done_dir)
        except shutil.Error:
                _log.exception(&#39;cannot move hl7 file or log file to holding area&#39;)
        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=&#39;utf8&#39;):
        &#34;&#34;&#34;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/
        &#34;&#34;&#34;
        local_log_name = gmTools.get_unique_filename (
                prefix = gmTools.fname_stem(filename) + &#39;-&#39;,
                suffix = &#39;.stage.log&#39;
        )
        local_logger = logging.FileHandler(local_log_name)
        local_logger.setLevel(logging.DEBUG)
        root_logger = logging.getLogger(&#39;&#39;)
        root_logger.addHandler(local_logger)
        _log.info(&#39;staging [%s] as unmatched incoming HL7%s&#39;, filename, gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;))
        _log.debug(&#39;log file: %s&#39;, local_log_name)

        # sanity checks/setup
        try:
                open(filename).close()
                orig_dir = os.path.split(filename)[0]
                done_dir = os.path.join(orig_dir, &#39;done&#39;)
                gmTools.mkdir(done_dir)
                error_dir = os.path.join(orig_dir, &#39;failed&#39;)
                gmTools.mkdir(error_dir)
        except Exception:
                _log.exception(&#39;cannot setup staging environment&#39;)
                root_logger.removeHandler(local_logger)
                return False

        # stage
        try:
                incoming = gmIncomingData.create_incoming_data(&#39;HL7%s&#39; % gmTools.coalesce(source, &#39;&#39;, &#39; (%s)&#39;), filename)
                if incoming is None:
                        _log.error(&#39;cannot stage PID file: %s&#39;, 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(&#39;error staging PID file&#39;)
                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 = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;, newline = &#39;&#39;)
        raw_hl7 = MSH_file.read(1024 * 1024 * 5)        # 5 MB max
        MSH_file.close()
        shutil.move(filename, done_dir)
        incoming[&#39;comment&#39;] = format_hl7_message (
                message = raw_hl7,
                skip_empty_fields = True,
                eol = &#39;\n&#39;
        )
        HL7 = pyhl7.parse(raw_hl7)
        del raw_hl7
        incoming[&#39;comment&#39;] += &#39;\n&#39;
        incoming[&#39;comment&#39;] += (&#39;-&#39; * 80)
        incoming[&#39;comment&#39;] += &#39;\n\n&#39;
        log = open(local_log_name, mode = &#39;rt&#39;, encoding = &#39;utf-8-sig&#39;)
        incoming[&#39;comment&#39;] += log.read()
        log.close()
        try:
                incoming[&#39;lastnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__lastname)
                incoming[&#39;firstnames&#39;] = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__firstname)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__name, component_num = PID_component__middlename)
                if val is not None:
                        incoming[&#39;firstnames&#39;] += &#39; &#39;
                        incoming[&#39;firstnames&#39;] += val
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__dob)
                if val is not None:
                        tmp = time.strptime(val, &#39;%Y%m%d&#39;)
                        incoming[&#39;dob&#39;] = pyDT.datetime(tmp.tm_year, tmp.tm_mon, tmp.tm_mday, tzinfo = gmDateTime.gmCurrentLocalTimezone)
                val = HL7.extract_field(&#39;PID&#39;, segment_num = 1, field_num = PID_field__gender)
                if val is not None:
                        incoming[&#39;gender&#39;] = val
                incoming[&#39;external_data_id&#39;] = filename
                #u&#39;fk_patient_candidates&#39;,
                #       u&#39;request_id&#39;,                                          # request ID as found in &lt;data&gt;
                #       u&#39;postcode&#39;,
                #       u&#39;other_info&#39;,                                          # other identifying info in .data
                #       u&#39;requestor&#39;,                                           # Requestor of data (e.g. who ordered test results) if available in source data.
                #       u&#39;fk_identity&#39;,
                #       u&#39;comment&#39;,                                                     # a free text comment on this row, eg. why is it here, error logs etc
                #       u&#39;fk_provider_disambiguated&#39;            # The provider the data is relevant to.
        except Exception:
                _log.exception(&#39;cannot add more data&#39;)
        incoming.save()

        _log.info(&#39;successfully staged&#39;)
        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>