-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPDFUnstructedTextSearch.py
4799 lines (4426 loc) · 240 KB
/
PDFUnstructedTextSearch.py
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
# Import libraries
from os import listdir
from os.path import isfile, join
import pandas as pd
import itertools
from zipfile import ZipFile
import random
firstNames = []
middleNames = []
lastNames = []
jrSrs = []
testTexts = []
fullTexts = []
birthDates = []
testTypes = []
testReceivedDates = []
testOrderedDates = []
testDateTypes = []
diagnoses = []
primaries = []
specimenTypes = []
specimenSites = []
problems = []
sources = []
fileNames = []
mrns = []
docIds = []
datasourceTypes = []
accessionNumbers = []
# These are for genes and labels - indeterminates, wild types, etc.
geneList = []
exonList = []
variantList = []
platformList = []
typeList = []
callList = []
negGeneList = []
negExonList = []
negPlatformList = []
negTypeList = []
negCallList = []
# For finding Tempus files with no gene lists
tempusNoLists = []
tempusNoListDates = []
# Split up the ingest if desired
getCaris = False
getFMI = True
getTempus = False
getGuardant = False
getNeogenomics = False
getInvitae = False
sampleName = "/Users/bholmes/Desktop/LatestNLP/PDFGeneList/PDFs/FMISample.csv"
zipName = '/Users/bholmes/Desktop/LatestNLP/PDFGeneList/PDFs/FMISample.zip'
# To see the files go by
countFiles = True
# For finding the rightmost value
def listRightIndex(alist, value):
return len(alist) - alist[-1::-1].index(value) -1
def standardAppends():
firstNames.append(firstName)
middleNames.append(middleName)
lastNames.append(lastName)
jrSrs.append(srJr)
testTexts.append(testText)
fullTexts.append('')
birthDates.append(birthdate)
diagnoses.append(diagnosis)
primaries.append(primary)
specimenSites.append(specimenSite)
specimenTypes.append(specimenType)
sources.append(source)
fileNames.append(filename)
testReceivedDates.append(received)
testOrderedDates.append(ordered)
testDateTypes.append(dateType)
testTypes.append(testType)
mrns.append(mrn)
docIds.append(docId)
datasourceTypes.append(datasource)
accessionNumbers.append(accession)
if getCaris:
# Caris doesn't seem to send test types in their reports?
testType = ''
# or MRNs
mrn = ''
mypath = '/Users/bholmes/Desktop/LatestNLP/PDFGeneList/PDFs/Caris/'
txts = [f for f in listdir(mypath) if isfile(join(mypath, f)) and '.txt' in f]
fnum = 0
brokens = []
for txt in txts:
if countFiles:
print(fnum, ' of ', len(txts))
fnum = fnum + 1
file = mypath + txt
file = open(file, mode='r')
all_of_it = file.read()
file.close()
source = 'Caris'
filename = txt[:-20]
######
# Let's get the test recieved date
#####
all_of_it = all_of_it.replace('Specimen Recieved:', 'Specimen Received:')
if 'Completion of Testing:' in all_of_it:
space = all_of_it[all_of_it.index('Completion of Testing:') + len('Completion of Testing:'):]
space = space[:space.index('\n')]
if ' ' in space:
space = space[:space.index(' ')]
space = space.strip()
space = space
received = space
dateType = 'Testing Completed'
elif 'Specimen Received:' in all_of_it:
space = all_of_it[all_of_it.index('Specimen Received:') + len('Specimen Received:'):]
space = space[:space.index('\n')]
if ' ' in space:
space = space[:space.index(' ')]
space = space.strip()
space = space
dateType = 'Specimen Recieved'
received = space
elif 'FINAL REPORT - ' in all_of_it:
space = all_of_it[all_of_it.index('FINAL REPORT - ') + len('FINAL REPORT - '):]
space = space[:space.index('\n')]
received = space
dateType = 'Final Report Date'
else:
print(all_of_it)
input()
#####
# First, for identification, we get the name
#####
if 'Name:' in all_of_it:
section = all_of_it[all_of_it.index('Name:') + len('Name:'):]
section = section[:section.index(' ')].strip()
elif 'ORDERED BY' in all_of_it:
section = all_of_it[all_of_it.index('ORDERED BY') + len('ORDERED BY'):]
section = section[:section.index('Primary Tumor Site')].strip()
lastName = section.split(',')[0].strip()
firstName = section.split(',')[1].strip()
if len(firstName.split()) > 1:
middleName = firstName.split()[1].strip()
firstName = firstName.split()[0].strip()
else:
middleName = ''
if len(lastName.split()) > 1 and ('jr' in lastName.lower() or 'sr' in lastName.lower() or lastName.lower().split()[1].replace('i', '') == ''):
srJr = lastName.split()[1].strip()
lastName = lastName.split()[0].strip()
else:
srJr = ''
firstName = firstName.replace(' ', '')
middleName = middleName.replace(' ', '')
lastName = lastName.replace(' ', '')
srJr = srJr.replace(' ', '')
#####
# Next let's find the date of birth
#####
if 'date of birth:' in all_of_it.lower():
section = all_of_it[all_of_it.lower().index('date of birth:') + len('date of birth:'):]
section = section[:section.index(' ')].strip()
elif 'birthdate:' in all_of_it.lower():
section = all_of_it[all_of_it.lower().index('birthdate:') + len('birthdate:'):]
section = section[:section.index(' ')].strip()
birthdate = section
#####
# Next, let's get the diagnosis
#####
if 'Diagnosis:' in all_of_it:
section = all_of_it[all_of_it.index('Diagnosis:') + len('Diagnosis:'):]
section = section[:section.index(' ')].strip()
# This is a workaround for some wonky formatting. Lots more of this if we start extracting in earnest!
if section.endswith(',') or section.endswith('with'):
oldSection = section
section = all_of_it[all_of_it.index('Diagnosis:') + len('Diagnosis:'):]
section = section[:section.index('\n\n')].strip()
bitToRemove = section[section.index(oldSection) + len(oldSection):section.index('\n')]
section = section.replace(bitToRemove, '')
section = section.split('\n')
for sectionB in range(0, len(section)):
if section[sectionB].replace(' ', '').replace('(', '').replace(')', '').replace('-', '').replace(' ', '').isnumeric():
section[sectionB] = ''
if section[sectionB].replace(' ', '').replace('USA', '') == '':
section[sectionB] = ''
section = list(filter(None, section))
sectionKeep = section[0] + ' ' + section[-1]
section = sectionKeep
if ' ' in section:
section = section[:section.index(' ')]
if '.' in section:
section = section[:section.index('.') + len('.')]
while ' ' in section:
section = section.replace(' ', ' ')
diagnosis = section
else:
diagnosis = 'Not Given'
#####
# Finally, let's get the primary site
#####
if 'Primary Tumor Site:' in all_of_it:
section = all_of_it[all_of_it.index('Primary Tumor Site:') + len('Primary Tumor Site:'):]
section = section[:section.index(' ')].strip()
if section.endswith('of'):
origSection = section
if 'Date of Birth:' not in all_of_it:
startSection = 'Case Number:'
else:
startSection = 'Date of Birth:'
section = all_of_it[all_of_it.index(startSection) + len(startSection):]
section = section[:section.index('\n')].strip()
while ' ' in section:
section = section.replace(' ', ' ')
if section.split()[1].endswith(','):
newsection = ''
start = 1
while (not section.split()[start][0].isupper() or section.split()[start].isupper()):
newsection = newsection + ' ' + section.split()[start]
start = start + 1
section = origSection + ' ' + newsection.strip()
else:
section = section.split()[1]
section = origSection + ' ' + section
primary = section
else:
primary = 'Not Given'
#####
# Extra-Finally, let's get the specimen site
#####
if 'Specimen Site: ' in all_of_it:
section = all_of_it[all_of_it.index('Specimen Site: ') + len('Specimen Site: '):]
section = section[:section.index(' ')]
if section.endswith('and') or section.endswith('subcutaneous'):
specimenLine = 0
split = all_of_it.split('\n')
while 'Specimen Site:' not in split[specimenLine]:
specimenLine = specimenLine + 1
specimenLine = specimenLine + 1
nextRow = split[specimenLine]
nextRow = nextRow.split(' ')
nextRow = list(filter(None, nextRow))
if len(nextRow) == 1:
sectionTop = split[specimenLine-1].split(' ')
sectionBottom = split[specimenLine+1].split(' ')
sectionTop = list(filter(None, sectionTop))
sectionBottom = list(filter(None, sectionBottom))
section = sectionTop[0] + ' ' + sectionBottom[0]
while ' ' in section:
section = section.replace(' ', ' ')
if 'Specimen Site: ' in section:
section = section[section.index('Specimen Site: ') + len('Specimen Site: '):]
else:
nextRow = nextRow[1]
section = section + ' ' + nextRow
while ' ' in section:
section = section.replace(' ', ' ')
if 'Specimen ID' in section:
section = section[:section.index('Specimen ID')]
#print(section)
else:
specimenSite = 'Not Given'
#print(all_of_it)
#input()
specimenSite = section
# Specimen Type is not given in caris
specimenType = 'Not Given'
# Lookin' for LOH
if 'GENOMIC LOSS OF HETEROZYGOSITY' in all_of_it:
section = all_of_it[all_of_it.index('GENOMIC LOSS OF HETEROZYGOSITY'):]
section = section[:section.index('Genomic Loss of Heterozygosity Analysis:')]
origSection = section
section = section.split('\n')
section = list(filter(None, section))
section = section[-1]
while ' ' in section:
section = section.replace(' ', ' ')
section = section[section.index('(LOH)') + len('(LOH)'):].strip()
if len(section.split()) == 1:
section = section
else:
section = section.split()[2]
if section == 'performed' or section == 'Indeterminate':
section = 'Test not performed'
LOH = section
geneList.append('LOH')
exonList.append('{}')
variantList.append('')
platformList.append('LOH')
typeList.append('LOH')
callList.append(LOH)
standardAppends()
# Now let's find the rest of the stuff in the appendix:
# We'll start with tumor mutational burden / total mutational load!
totalLoads = ['TOTAL MUTATIONAL LOAD', 'TUMOR MUTATIONAL BURDEN']
ends = ['TMB', 'Interpretation:', 'TOTAL', 'MICROSATELLITE', 'TML']
while any(load in all_of_it for load in totalLoads):
for l in range(0, len(totalLoads)):
wholeSection = ''
if totalLoads[l] in all_of_it:
start = totalLoads[l]
wholeSection = all_of_it[all_of_it.index(start):]
section = all_of_it[all_of_it.index(start) + len(start):]
endIndex = 99999999
for end in ends:
if end in section:
if section.index(end) < endIndex:
endIndex = section.index(end)
section = section[:endIndex]
wholeSection = wholeSection[:len(end) + endIndex]
# Now let's split it up
section = section.split('\n')
section = list(filter(None, section))
for sec in range(0, len(section)):
while ' ' in section[sec]:
section[sec] = section[sec].replace(' ', ' ')
if 'Result:' in section[0]:
mutationNumber = section[0][section[0].index('Megabase: ') + len('Megabase: '):section[0].index('Result:')].strip()
mutationCall = section[0][section[0].index('Result:') + len('Result: '):].strip()
elif 'Megabase Result' in section[0]:
if 'Indeterminate' in section[1]:
mutationNumber = ''
mutationCall = 'Untested - Indeterminate'
else:
mutationNumber = section[1].strip().split()[0]
mutationCall = section[1].strip().split()[1]
elif 'Megabase (Mb)' in section[0]:
mutationNumber = section[1].strip().split()[1]
mutationCall = section[1].strip().split()[0]
geneList.append('TMB')
exonList.append('{}')
variantList.append('')
platformList.append('NGS')
typeList.append('TMB')
callList.append(mutationCall)
standardAppends()
all_of_it = all_of_it.replace(wholeSection, '')
# Now let's move to microsatellite instability
micros = ['MICROSATELLITE INSTABILITY ANALYSIS', 'MICROSATELLITE INSTABILITY (MSI) BY NEXT-GENERATION SEQUENCING']
ends = ['Microsatellite Instability', 'GENES']
while any(ms in all_of_it for ms in micros):
for l in range(0, len(micros)):
wholeSection = ''
if micros[l] in all_of_it:
start = micros[l]
wholeSection = all_of_it[all_of_it.index(start):]
section = all_of_it[all_of_it.index(start) + len(start):]
endIndex = 99999999
for end in ends:
if end in section:
if section.index(end) < endIndex:
endIndex = section.index(end)
section = section[:endIndex]
wholeSection = wholeSection[:len(end) + endIndex]
section = section.split('\n')
section = list(filter(None, section))
if 'Result:' in section[0]:
MSI = section[0].split()[-1]
else:
MSI = section[1].split()[-1]
geneList.append("MSI")
exonList.append('{}')
variantList.append('')
platformList.append('MSI')
typeList.append('MSI')
callList.append(MSI)
standardAppends()
all_of_it = all_of_it.replace(wholeSection, '')
# CISH is here
while 'AM PLIFICATION BY CHROMOG ENIC IN SITU HYBRIDIZATION (CISH)' in all_of_it:
section = all_of_it[all_of_it.index('AM PLIFICATION BY CHROMOG ENIC IN SITU HYBRIDIZATION (CISH)'):]
section = section[:section.index(' Reference')]
origSection = section
section = section.split('\n')
for x in range(0, len(section)):
while ' ' in section[x]:
section[x] = section[x].replace(' ', ' ')
if 'nuc ish' in section[x]:
amplified = section[x-1]
geneList.append(amplified.strip())
exonList.append('{}')
variantList.append('')
platformList.append('CISH')
typeList.append('Amplification')
callList.append('yes')
standardAppends()
all_of_it = all_of_it.replace(origSection, '')
# There are a number of sections with one gene per line. Let's get that
# This section is unique - it's not a gene list, it's a table with a whole series of pieces of information in it about the genes found
# I figure that we can do a full dive and pull out everything in here later if necessary? But since the positives should already
# be coming through, if I just get the gene list for positive alterations, we can go back later and compare.
while 'GENES TESTED WITH ALTERATIONS' in all_of_it:
wholeSection = section = all_of_it[all_of_it.index('GENES TESTED WITH ALTERATIONS'):]
section = all_of_it[all_of_it.index('GENES TESTED WITH ALTERATIONS') + len('GENES TESTED WITH ALTERATIONS'):]
endingPos = 9999999999999
sectionEndings = ['GENES TESTED', 'PATIENT']
for ending in sectionEndings:
if ending in section:
if section.index(ending) < endingPos:
endingPos = section.index(ending)
section = section[:endingPos]
wholeSection = wholeSection[:endingPos]
origSection = section
section = section.split('\n')
indentForGene = 0
for line in section:
if 'Gene' in line and indentForGene == 0:
while line.startswith(' '):
indentForGene = indentForGene + 1
line = line[1:]
continue
lineIndent = 0
while line.startswith(' '):
line = line[1:]
lineIndent = lineIndent + 1
if abs(indentForGene - lineIndent) <= 5 and indentForGene != 0 and lineIndent > 1 and line != '':
while ' ' in line:
line = line.replace(' ', ' ')
section = list(filter(None, section))
gene = line.split()[0]
if gene not in ['Gene', 'Genes']:
geneList.append(gene)
exonList.append('{}')
variantList.append('')
platformList.append('NGS')
typeList.append('Gene tested with alteration')
if 'Variant of Uncertain Significance' in line:
callList.append('VUS')
else:
callList.append('Positive')
standardAppends()
all_of_it = all_of_it.replace(wholeSection, '')
# Rearrangement by FISH:
while 'REARRANGEMENT BY FLUORESCENCE IN SITU HYBRIDIZATION (FISH)' in all_of_it:
section = all_of_it[all_of_it.index('REARRANGEMENT BY FLUORESCENCE IN SITU HYBRIDIZATION (FISH)'):]
section = section[:section.index('Electronic')]
origSection = section
section = section.split('\n')
section = list(filter(None, section))
for x in range(0, len(section)):
while ' ' in section[x]:
section[x] = section[x].replace(' ', ' ')
if 'Reference' in section[x]:
bit = section[x-1]
b = x-1
while 'Detected' not in bit and 'QNS' not in bit and 'Negative' not in bit and 'See Below' not in bit and \
'Positive' not in bit and 'Other' not in bit and 'Test not performed' not in bit:
b = b - 1
bit = section[b]
if 'Positive' in bit:
call = 'Positive'
elif 'Test not performed' in bit:
call = 'TNP'
elif 'Other' in bit:
call = 'Other'
elif 'QNS' in bit:
call = 'QNS'
elif 'Negative' in bit:
call = 'Negative, explicit'
# Get aberrent comments
elif 'See Below' in bit:
call = all_of_it[all_of_it.index('Comments on FISH Analysis'):]
# Sometimes we jsut need the next line
if 'comments.' not in call:
call = call[call.index('\n')+1:]
call = call[call.index('\n')+1:]
call = call[:call.index('\n')]
else:
call = call[call.index('comments.') + len('comments.'):]
call = call[:call.index('\n')].strip()
else:
call = bit[:bit.index('Detected') + len('Detected')].strip()
gene = section[x-1].split()[-1].replace('ish(', '').replace(')','')
if 'x' in gene:
gene = gene[:gene.index('x')]
geneList.append(gene)
exonList.append('{}')
variantList.append('')
platformList.append('FISH')
typeList.append('Rearrangement')
callList.append(call)
standardAppends()
all_of_it = all_of_it.replace(origSection, '')
# We'll get the PD-L1s here
while any(pd in all_of_it for pd in ['PD-L1 TUMOR CELL STAINING', 'PD-L1 COMBINED POSITIVE SCORE', 'PD-L1 TUMOR PROPORTION SCORE (TPS)', 'PD-L1 IMMUNE CELL (IC) SCORE']):
for pdl in ['PD-L1 TUMOR CELL STAINING', 'PD-L1 COMBINED POSITIVE SCORE', 'PD-L1 TUMOR PROPORTION SCORE (TPS)', 'PD-L1 IMMUNE CELL (IC) SCORE']:
if pdl in all_of_it:
section = all_of_it[all_of_it.index(pdl):]
if 'Scoring' not in section:
if 'Utilizing' in section:
section = section[:section.index('Utilizing')]
elif 'CPS:' in section:
section = section[:section.index('CPS:')]
elif 'Clones' in section:
section = section[:section.index('Clones')]
else:
section = section[:section.index('IC scoring')]
else:
section = section[:section.index('Scoring')]
origSection = section
all_of_it = all_of_it.replace(origSection, '')
section = section.split('\n')
section = list(filter(None, section))
for x in range(1, len(section)):
if 'PD-L1' in section[x] and len(section[x].split(' ')) > 1:
bit = section[x].split(' ')
for b in bit:
if 'PD-L1' in b:
geneList.append(b.strip())
exonList.append('{}')
variantList.append('')
platformList.append('FISH')
typeList.append('PD-L1')
callList.append(pdl)
standardAppends()
continue
# Clones. Easy to get!
while 'Clones used:' in all_of_it:
section = all_of_it[all_of_it.index('Clones used:'):]
section = section[:section.index('.\n')]
all_of_it = all_of_it.replace(section, '')
section = section[len('Clones used: '):]
for clone in section.split(','):
geneList.append(clone)
exonList.append('{}')
variantList.append('')
platformList.append('Clone')
typeList.append('Clone Used')
callList.append('Clone used')
standardAppends()
# This is a low-number assay, but let's get it
while 'Her-2 IHC: Gastroesophageal Cancer (Biopsy/FNA)' in all_of_it:
section = all_of_it[all_of_it.index('Her-2 IHC: Gastroesophageal Cancer (Biopsy/FNA)'):]
section = section[:section.index('\n\n\n')]
fullSection = section
section = section.split('\n')
section = list(filter(None, section))
for sec in section:
if sec == '.':
section.remove(sec)
section = section[-1]
while section.startswith(' '):
section = section[1:]
geneList.append('Her-2 FNA IHC')
exonList.append('{}')
variantList.append('')
platformList.append('IHC')
typeList.append('FNA')
callList.append(section.split(' ')[0].replace('|', '-'))
standardAppends()
all_of_it = all_of_it.replace(fullSection, '')
# Put this one off for too long - protein expression by IHC babeee
all_of_it = all_of_it.replace('PROTEIN EXPRESSION BY IMMUNOHISTOCHEMISTRY (IHC)', 'Protein Expression by Immunohistochemistry (IHC)')
while 'Protein Expression by Immunohistochemistry (IHC)' in all_of_it:
section = all_of_it[all_of_it.index('Protein Expression by Immunohistochemistry (IHC)'):]
wholeSection = section
if 'Scoring' not in section:
ends = ['Comments', 'IHC Methods', 'immunohistochemistry', 'IHC was', 'IHC stains', 'failed', 'Appropriate staining', 'The sarcoma', 'Utilizing',
'PD-L1 TUMOR', 'PD-L1 COMBINED', 'RESULT', 'This case']
if not any(end in section for end in ends):
print(section)
print("HERE")
input()
continue
endIndex = 999999999999
for end in ends:
if end in section:
if section.index(end) < endIndex:
endIndex = section.index(end)
section = section[:endIndex]
else:
section = section[:section.index('Scoring')]
otherEnds = ['PD-L1 Tumor Cell', 'PD-L1 Tumor Proportion', 'PD-L1 Combined', 'PD-L1 COMBINED', 'PD-L1 TUMOR', 'CPS:']
for end in otherEnds:
if end in section:
section = section[:section.index(end)]
all_of_it = all_of_it.replace(section, '')
if '(0, 1+, 2+, 3+)' not in section:
continue
else:
section = section[section.index('(0, 1+, 2+, 3+)') + len('(0, 1+, 2+, 3+)'):]
if 'Electronic Signature' in section:
section = section[:section.index('Electronic Signature')]
section = section.split('\n')
section = list(filter(None, section))
for sec in section:
while sec.startswith(' '):
sec = sec[1:]
sec = sec.split(' ')
sec = list(filter(None, sec))
if len(sec) > 1:
if len(sec) < 4:
print(sec)
print(section)
continue
geneList.append(sec[0].strip())
exonList.append('{}')
variantList.append('')
platformList.append('IHC')
typeList.append('Protein IHC')
callList.append(sec[3].strip())
standardAppends()
# Finally, these tests are just brute lists.
all_of_it = all_of_it.replace('*', '')
sectionStarts = ['GENES TESTED WITH NO MUTATIONS DETECTED', 'GENES TESTED WITH INDETERMINATE RESULTS BY TUMOR DNA SEQUENCING', 'GENES WITH INDETERMINATE CNA RESULTS',
'GENES TESTED WITH NO AMPLIFICATION DETECTED', 'GENES TESTED WITH UNEVALUATED AMPLIFICATION',
'GENES TESTED WITH INDETERMINATE GENE FUNCTION OR TRANSCRIPT VARIANT RESULTS', 'GENES TESTED WITH INDETERMINATE RESULTS',
'Genes Tested with Intermediate CNA Results by Tumor DNA Sequencing']
sectionEnds = ['COMPLETE', 'Additional', 'PATIENT:', 'Electronic', 'For', 'Sequencing', 'GENES', 'The', '¶', 'CNA', 'Genes', 'CNA', 'IN SITU', 'South', 'Comments']
typeOList = ['No mutations detected', 'Indeterminate mutation result', 'Indetermiante CNA result', 'No Amplification', 'Unevaluated Amplification',
'Untested Gene - Indeterminate', 'Untested Gene - Indeterminate', 'Untested CNA - Intermediate']
while any(section in all_of_it for section in sectionStarts):
for sectionStarter in range(0, len(sectionStarts)):
if sectionStarts[sectionStarter] in all_of_it:
start = sectionStarts[sectionStarter]
type = typeOList[sectionStarter]
# We take out the name of the section for analysis, but we leave it in to delete the section
section = all_of_it[all_of_it.index(start) + len(start):]
wholeSection = all_of_it[all_of_it.index(start):]
endIndex = 999999999999
for end in sectionEnds:
if end in section:
if section.index(end) < endIndex:
endIndex = section.index(end)
section = section[:endIndex]
wholeSection = wholeSection[:endIndex + len(start)]
# Now we remove that section from the main report
all_of_it = all_of_it.replace(wholeSection, '')
section = section.replace('\n', ' ')
while ' ' in section:
section = section.replace(' ', ' ')
section = section.strip()
section = section.split()
while section[0] in ['BY', 'TUMOR', 'DNA', 'SEQUENCING']:
section = section[1:]
for gene in section:
if gene[0].isupper() and gene[1].islower() and gene not in ['Androgen', 'Receptor', 'Her2/Neu', 'Neu)', 'Tertiary', 'Mutation']:
print(section)
print(gene)
print(txt)
input()
if gene.startswith('(') or gene in ['Receptor', 'Neu)', 'Tertiary', 'Mutation']:
geneList[-1] = geneList[-1] + ' ' + gene
else:
geneList.append(gene)
exonList.append('{}')
variantList.append('')
platformList.append('NGS')
if len(type.split()) == 3 and type.split()[2] == 'result':
typeList.append(type.split()[1])
callList.append(type.split()[0])
elif type == 'No mutations detected':
typeList.append('Mutation')
callList.append('Negative, explicit')
elif type == 'No Amplification':
typeList.append('Amplification')
callList.append('Negative, explicit')
elif type == 'Unevaluated Amplification':
typeList.append('Amplification')
callList.append('Unevaluated')
elif type == 'Untested Gene - Indeterminate':
typeList.append('Mutation')
callList.append('Untested - Indeterminate')
elif type == 'Untested CNA - Intermediate':
typeList.append('CNA')
callList.append('Untested - Intermediate')
elif type == 'VUS Mutation':
typeList.append('Gene tested with alteration')
callList.append('VUS')
else:
print(type)
input()
standardAppends()
if getFMI:
mypath = '/Users/bholmes/Desktop/LatestNLP/PDFGeneList/PDFs/FMI/'
txts = [f for f in listdir(mypath) if isfile(join(mypath, f)) and '.txt' in f]
fnum = 0
brokens = []
num = 1
# No MRNs from FMI
mrn = ''
for txt in txts:
txtNames = ["fmi_file.f7b2dee4-4616-4f9a-9676-8fa272f54d26",
"fmi_file.c909377f-fef0-49d5-92f9-52b8db0dad98",
"TRF136486.02f8971f-e1c4-416a-9481-7aaba163b9bd",
"QRF049489.af7c7441-89e4-4edd-b5ae-7c3fd1921a3e",
"QRF048483.1e062feb-9586-466b-b0af-55e43de1abcb",
"fmi_file.ed2b9090-6285-4792-991d-43caf3941647",
"fmi_file.dc1d28d2-5642-40cf-bbde-6332d0724d57",
"fmi_file.d7e30826-3aaa-488b-b37c-f1b173066fad",
"fmi_file.d6bac8e4-bcaf-4244-a45c-820cdf330e89",
"fmi_file.d05e0b0b-c923-479f-a4b8-45f9ccb6a7da",
"fmi_file.b3f34b26-71d4-47ce-a5cc-63dac9406b04",
"fmi_file.a7b5a908-eb2c-42d4-8d55-2ae3a0a3b887",
"TRF324799.ff9dbefe-9850-40c5-bb74-c49a8dc4f4ae",
"TRF323991.50e0452c-8965-4783-89b4-212282674555",
"TRF322133.d9935631-3f77-47ef-a2a1-293bdfa06808",
"TRF268949.b44d918f-add4-4ddd-9858-c6b9c24ce548",
"TRF242784.bac4836e-f37a-40dd-8838-2b9324b9277d",
"fmi_file.833546c0-e1e4-4d30-8242-fcf6b7c41c27",
"fmi_file.6b613e12-fd73-4257-8251-6654e4dabfe3",
"fmi_file.545a3042-d460-400e-ae87-2268bb6e00f7",
"fmi_file.536facb4-fc60-44d4-9798-c90454e51cde",
"fmi_file.3e92797b-1a1a-4e4c-9606-e3395795921b",
"fmi_file.39c6736a-595a-48c6-8bd9-eb936a4d3022",
"fmi_file.2d9656d7-ed40-44f5-9123-8200b04b85d1",
"fmi_file.2b449fa0-8fe0-4e95-a7c4-20f0b04a341f",
"fmi_file.14270e3a-7721-4636-9666-d47de5648a5a",
"fmi_file.11f8ebe3-beb5-407a-b18a-feefcf6ab5ed",
"fmi_file.0133741b-ca28-4706-b26b-a33d51c71963",
"QRF043068.52f089bb-139c-419e-afd6-c006bf9e7eee",
"QRF040084.9dd1034e-b079-4cf0-a356-7e4af1cdb53f",
"QRF036513.e14274fd-35ae-4c70-9db3-669a57052ba3",
"fmi_file.9ed62f9a-6283-4a3a-b633-1d331ef2ea18",
"fmi_file.9ab79950-be2f-435d-a675-4de2e80906c8",
"fmi_file.5d9b1461-d489-4aeb-9e72-e508506de99d",
"fmi_file.4b1dfb07-d063-4f42-af79-095054aecf22",
"fmi_file.020134e3-5a24-4e7c-98ed-aecad03e28a2",
"fmi_file.9f758274-bd7c-4f83-92c7-78becccceb84",
"fmi_file.097534d2-2336-4a59-91cf-5e60da05a058",
"fmi_file.f8ffc97d-5c66-4453-a30a-5782069b5554",
"fmi_file.f5d9794b-0c3b-4f46-8ce2-8d7f7d3632e0",
"fmi_file.c8beed2d-7901-4ad6-b00e-c03d07dd1e1b",
"fmi_file.c077966f-e923-4347-a9c3-3c05044b5388",
"fmi_file.b71ae296-53e4-4855-ae51-da655cd59e1c",
"fmi_file.b4c4f2c0-7c84-479a-8a99-a074d151dace",
"fmi_file.a361c90b-44c3-4122-b02f-47a145ea0564",
"TRF405013.b1dabcd9-4104-4234-bbb3-f9044bb763af",
"TRF103820.aad82dac-8603-4dec-8e35-2014fcb8d483",
"QRF156032.0b32de73-87a5-4d7b-9891-7b19108e44de",
"QRF132980.447f7bea-8e90-4077-a802-fbf83c6aaffa",
"QRF125745.21607c9b-8bb9-478d-b41a-6cb687e99a04",
"QRF112631.b18d317c-b9df-4942-be21-a3b167cd7118",
"QRF110835.4a577aa1-50e5-4646-8586-73a0db341054",
"QRF101016.59afb0bb-d007-4013-b8b8-face4223db00",
"QRF076852.1fe8894d-804c-4b2b-8efc-8afae9af6e8d",
"QRF070276.be8b95f1-eeaf-43b3-a969-c321c71e2f3b",
"ORD-0991801-01.7d8b748e-ce67-4e58-8bf2-78ea4f1e7dd0",
"ORD-0980541-01.235f37af-e800-45b9-908a-8166a9ac2473",
"ORD-0939862-01.0e04869f-b6cf-4bbe-b7de-3e009e40c388",
"ORD-0898417-01.70857fe3-f2fb-441a-bbf6-f0cf1f6e1096",
"ORD-0867169-01.daf30056-5c19-47a0-830c-da54c508ee4c",
"ORD-0830899-01.e475c8f2-a193-4c1f-a95f-49a014141f33",
"ORD-0821851-01.74fe62b9-b6f1-4916-bf43-404e5f7ce8e9",
"ORD-0643162-01.bab62e5c-9e1d-4074-a118-b0dde28a81ff",
"ORD-0636741-01.97c3c420-8408-4f7d-879b-e4dab3d7050e",
"fmi_file.966eef6a-5246-4f43-a455-6143fd2fa943",
"fmi_file.96530131-35ea-451c-ba6b-8b0d45de7f8c",
"fmi_file.844cf425-b2d6-4e79-b444-db576446fa35",
"fmi_file.618b660c-9cba-4661-bcad-b79cf4e28686",
"fmi_file.5a368766-4f52-4ea7-ac04-6f16e3d82586",
"fmi_file.5165ddff-8379-4ac8-b7dc-76f159e3397c",
"fmi_file.4d2e4152-d65a-4fcf-8301-b6b01e952751",
"fmi_file.42bb0c7e-7e17-4481-83f4-3d996cce342a",
"fmi_file.29da9616-50b0-4c27-b656-8e7c762d97a2",
"fmi_file.28160058-7725-4a7f-90ab-a0a5ccad3b1c",
"fmi_file.208d5242-6e91-4d01-a0a0-401e73206ecb",
"fmi_file.13a3d56e-8a01-443d-bc1c-49ec9c1384f5",
"fmi_file.1115424f-1ec4-4869-94ad-9633c43f45e8"]
#if not any(x in txt for x in txtNames):
# continue
#if not 'QRF125745.21607c9b-8bb9-478d-b41a-6cb687e99a04' in txt:
# continue
truncdGenes = []
if countFiles:
print(str(num), ' of ', str(len(txts)))
num = num + 1
file = mypath + txt
file = open(file, mode='r')
all_of_it = file.read()
file.close()
source = 'FMI'
filename = txt[:-20]
received = ''
dateType = ''
# We only want to add these once
addedMSI = False
addedTMB = False
# This indicates a blank test. Add it to a list of mangled tests for later?
if len(all_of_it.split('\n')) < 2:
continue
testNames = ['FoundationOne CDx', 'FoundationACT', 'FoundationOne™', 'FoundationOne Liquid', 'FoundationOne Heme', 'FoundationOne®']
if not any(tn in all_of_it for tn in testNames):
print(all_of_it)
input()
else:
for tn in ['FoundationOne CDx', 'FoundationACT', 'FoundationOne™', 'FoundationOne Liquid', 'FoundationOne Heme', 'FoundationOne®']:
if tn in all_of_it:
testType = tn
# Getting doc id
docId = txt.replace('fmi_file.', '').replace('_out_text_SAMPLE.txt', '')
datasource = 'PDF'
# Let's get the accession
if 'FMI Case #' in all_of_it:
accession = all_of_it[all_of_it.index('FMI Case #') + len('FMI Case #') + 1:]
accession = accession[:accession.index(' ')]
elif any(x in all_of_it for x in ['QRF#', 'TRF#', 'CRF#']):
for y in ['QRF#', 'TRF#', 'CRF#']:
if y in all_of_it:
tag = y
accession = all_of_it[all_of_it.index(tag) + len(tag) + 1:]
accession = accession[:accession.index('\n')]
elif 'ORDERED TEST #' in all_of_it:
accession = all_of_it[all_of_it.index('ORDERED TEST #') + len('ORDERED TEST #') + 1:]
accession = accession[:accession.index('\n')]
else:
print(all_of_it)
input()
# Getting test date
if 'REPORT DATE' in all_of_it:
dateLine = 0
split = all_of_it.split('\n')
while 'REPORT DATE' not in split[dateLine]:
dateLine = dateLine + 1
lineWithDate = split[dateLine + 1]
lwdSplit = lineWithDate.split()
lwdBit = 0
while not lwdSplit[lwdBit].isnumeric():
lineWithDate = lineWithDate.replace(lwdSplit[lwdBit], '')
lwdBit = lwdBit + 1
lineWithDate = lineWithDate.strip()
received = lineWithDate
dateType = 'Report Date'
elif 'Patient Name Report Date Tumor Type' in all_of_it:
space = all_of_it.split('\n')[1]
space = ' '.join(space.split()[2:5])
received = space
dateType = 'Report Date'
start = 2
end = 5
while not received.split()[-1].isnumeric():
space = all_of_it.split('\n')[1]
space = ' '.join(space.split()[start:end])
received = space
dateType = 'Report Date'
start = start + 1
end = end + 1
elif 'Patient Name Report Date' in all_of_it:
spaceLine = 0
while 'Patient Name Report Date' not in all_of_it.split('\n')[spaceLine]:
spaceLine = spaceLine + 1
space = all_of_it.split('\n')[spaceLine + 1]
space = space.split()
while not space[-1].isnumeric():
space = space[:-1]
space = ' '.join(space[-3:])
received = space
dateType = 'Report Date'
elif 'SPECIMEN RECEIVED' in all_of_it:
space = all_of_it[all_of_it.index('SPECIMEN RECEIVED') + len('SPECIMEN RECEIVED'):]
space = space[:space.index('\n')]
received = space.strip()
dateType = 'Speciment Received'
elif 'page 1 of' in all_of_it:
pageLine = 0
while 'page 1 of' not in all_of_it.split('\n')[pageLine]:
pageLine = pageLine + 1
section = all_of_it[all_of_it.index(all_of_it.split('\n')[pageLine]) + len(all_of_it.split('\n')[pageLine]):]
reportLine = 0
section = section[section.index('Report Date'):]
section = section[section.index('\n')+1:]
section = section[:section.index('\n')]
section = section.split()
while not section[0].isnumeric():
section = section[1:]
section = ' '.join(section[0:3])
received = section
dateType = 'Report Date'
else:
print(all_of_it)
input()
while received.startswith(',') or received.startswith(' '):
received = received[1:]
# Getting test date
if 'DATE OF COLLECTION' in all_of_it:
ordered = all_of_it[all_of_it.index('DATE OF COLLECTION') + len('DATE OF COLLECTION '):]
ordered = ordered[:ordered.index('\n')]
elif 'Date of Collection' in all_of_it:
ordered = all_of_it[all_of_it.index('Date of Collection') + len('Date of Collection '):]
ordered = ordered[:ordered.index('\n')]
elif 'DDAATTEE OOFF CCOOLLLLEECCTTIIOONN' in all_of_it:
ordered = all_of_it[all_of_it.index('DDAATTEE OOFF CCOOLLLLEECCTTIIOONN') + len('DDAATTEE OOFF CCOOLLLLEECCTTIIOONN'):]
ordered = ordered[:ordered.index('\n')]
else:
print(all_of_it)
input()
# Getting name here
if 'NAME' in all_of_it:
section = all_of_it[all_of_it.index('NAME') + len('NAME'):]
section = section[:section.index('\n')]
name = ' '.join(section.split()[0:2])
if name.split()[1].replace('I', '').replace('V', '') == '' or name.endswith(','):
name = ' '.join(section.split()[0:3])
elif 'PATIENT TUMOR TYPE' in all_of_it.split('\n')[0]:
section = all_of_it.split('\n')[1]
name = ' '.join(section.split()[0:2])
if name.split()[1].replace('I', '').replace('V', '') == '' or name.endswith(','):
name = ' '.join(section.split()[0:3])
else:
split = all_of_it.split('\n')
lineNum = 0
# There can be a variable number of lines where the patient name is, but it's always below the line that says 'Patient'
while 'Patient' not in split[lineNum]:
lineNum = lineNum + 1
lineNum = lineNum + 1
section = split[lineNum]
name = ' '.join(section.split()[0:2])
if name.split()[1].replace('I', '').replace('V', '') == '' or name.endswith(','):
name = ' '.join(section.split()[0:3])
nameSplit = name.split()
nameSplit = list(filter(None, nameSplit))
if len(nameSplit) == 3:
if nameSplit[1].endswith(','):
if nameSplit[1].lower() in ['jr', 'sr'] or nameSplit[1].lower().replace('i', '') == '':
firstName = nameSplit[2]
lastName = nameSplit[0]
srJr = nameSplit[1].replace(',', '')
middleName = ''
else:
firstName = nameSplit[2]
lastName = nameSplit[0] + ' ' + nameSplit[1].replace(',', '')
srJr = ''