-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCJM RM NOTES.py
2469 lines (1919 loc) · 110 KB
/
CJM RM NOTES.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
# coding: utf-8
# In[1]:
import re
notes_header = ['Source Path', 'UniqueId14M', 'LoanTypeIdDesc', 'PaymentType', 'OrigMtgDt', 'OrigProductionsFundDt', 'USPSFullAddr', 'USPSCity' , 'USPSState', 'USPSZip5', 'OrigLoanAmt', 'LenderName', 'OrigNoteRate', 'OrigARMNoteRate14M', 'OrigFirstPmtDueDt', 'OrigIntOnlyFlag', 'OrigIntOnlyExpDt', 'OrigMaturityDt', 'ARMInitialRateResetMon', 'OrigAmortTermMonths', 'OrigIntOnlyTermMon', 'OrigLoanTypeId', 'OrigPIAmt', 'Change Date', 'ARMRecastFreqMonths', 'OrigARMIndexCd14M', 'ARMMarginRate14M', 'ARMSubseqAdjCapRate', 'ARMFloorRate', 'OrigARMLifeCapRate', 'OrigARMFloorRate14M', 'OrigARMCeilingRate14M','PayoffPenaltyFlag', 'PayoffPenaltyWinMonths', 'OrigChannelNum', 'Paragraphs Not Found' ,'Document Type']
source_path_index = 0
loan_number_index = 1
loan_type_index = 2
payment_type_index = 3
mortgage_date_index = 4
productions_fund_date_index = 5
usps_full_address_index= 6
usps_city_index = 7
usps_state_index = 8
usps_zip_index = 9
loan_amount_index = 10
lender_name_index = 11
note_rate_index = 12
arm_initial_rate_index = 13
first_payment_date_index = 14
interest_only_at_origination_flag_index = 15
interest_only_exp_date_index = 16
maturity_date_index = 17
initial_rate_period_index = 18
loan_term_index = 19
interest_only_term_index = 20
interest_type_at_origination_index = 21
pi_amount_index = 22
change_date_index = 23
arm_payment_reset_freq_index= 24
arm_index_index = 25
arm_margin_at_origination_index = 26
arm_periodic_rate_cap_index = 27
arm_periodic_rate_floor_index = 28
arm_lifetime_rate_cap_index = 29
arm_lifetime_rate_floor_index = 30
arm_lifetime_rate_ceiling_index = 31
prepayment_penalty_flag_index = 32
prepayment_penalty_term_index = 33
loan_source_index = 34
paragraphs_not_found_index = 35
# Regex for markers
note_re_string = '[NM]\s{0,}[OQo0]{0,1}.{0,1}[TLI].{0,1}[EC]'
note_re = re.compile(note_re_string)
fixed_re_string = '(?i)F\s{0,}[il]\s{0,}.{0,1}[xnvcl]\s{0,}[ecil]{0,1}\s{0,}[dj]{0,1}'
adjustable_re_string = '[AQ][DB][JIL\s]\s{0,1}[UIOL\s]\s{0,}S[TI]A[BEH][LI]E\s{0,}.{3,5}\s{0,}'
equity_re_string = 'EQUITY\s{0,}'
promissory_re_string = '.[RN][OQ][MN]\s{0,}[IlLHJ\]R].{0,2}[S]\s{0,}[S][OQGg\s]\s{0,}[R\sN].{0,2}\s{0,}'
balloon_re_string = 'BALLOON\s{0,}'
consolidated_re_string = 'CON\s{0,}SOLIDATE{0,1}.\s{0,}'
restated_re_string = 'RESTATED\s{0,}'
interest_only_period_re_string = 'INTEREST.{0,1}ONLY\s{0,}PERIOD\s{0,}'
addendum_re_string = 'ADDENDUM\s{0,}'
allonge_re_string = 'ALL[O0]NGE\s{0,}'
multistate_re_string = '.{0,4}[TI]S[TIY]A[TI]E\s{0,}'
adjustable_re = re.compile(adjustable_re_string)
fixed_re= re.compile(fixed_re_string)
equity_re = re.compile(equity_re_string)
promissory_re = re.compile(promissory_re_string)
balloon_re = re.compile(balloon_re_string)
restated_re = re.compile(restated_re_string)
interest_only_period_re = re.compile(interest_only_period_re_string)
addendum_re = re.compile(addendum_re_string)
allonge_re = re.compile(allonge_re_string)
multistate_re = re.compile(multistate_re_string)
#consolidated_adjustable_re = re.compile(consolidated_re_string + adjustable_re_string + note_re_string)
# We don't want this (just saw one where this is good)
loan_type_re_string = '(' + adjustable_re_string + '|' + equity_re_string + '|' + promissory_re_string + '|' + balloon_re_string + '|' + restated_re_string + '|' + consolidated_re_string + ')' + note_re_string
loan_type_re = re.compile(loan_type_re_string)
date_re = re.compile('[\[\{\(l\|]D\s{0,1}[ai].{0,1}[tlKrv]{1,2}[eoca][\]\}\)\sl\|]')
city_re = re.compile('[\[\{\(\|lY]\s{0,1}C.{0,2}[trR][yvY][\]\}\)\|l]')
state_re = re.compile('[\[\{\(\|l]\s{0,1}S[tl]a[tl][eco][\]\}\)\|lt]')
# Regex's for dates
letters_could_be_numbers = 'OoDUuLlIi!\|\[\]\(\)\{\}ZzSsGB'
# We always have full month names for the Notes
# months_re_string = '(?i)((Jan(?:uary)?)|(Feb(?:ruar[yv])?)|(Mar(?:ch)?)|(Apr(?:il)?)|(May)|([JL]un(?:e)?)|\
# (Jul(?:y)?)|(Aug(?:u[sa]t)?)|(Sep(?:tember)?)|(Oct(?:ober)?)|(Nov(?:ember)?)|(Dec(?:ember)?))'
months_re_string = '(?i)(([JI\)]an[ua]{1,3}[rm]y)|([FE][ec]bruar[yv])|(March)|(A\s{0,}p\s{0,}r\s{0,}[ilt1\s]{2,3})|(May)|([JLT\)]\s{0,}[ui0]\s{0,}[nm]\s{0,}e)|([JI\)]u\s{0,}[lt1I]y)|(Aug[ug][sa]t)|(Sep[tb]em\s{0,1}ber)|(O{0,1}ctober)|(Nov[em]{2}ber)|([Dp]ec[em][mne]{1,2}[be]{2}r{0,1}))'
date_number_re_string = '[\d' + letters_could_be_numbers + ']'
# The day could have 1 or 2 digits
complete_date_re_string = '(' + months_re_string + '\s{0,}[,\.]{0,1}\s{0,}' + '(.{0,3}\s{0,}' + date_number_re_string + '{0,1}\s{0,}' + date_number_re_string + '{0,1}\s{0,}' + '.{0,3}\s{0,}' + ')'+ '[,\.\s]\s{0,}' + '(' + date_number_re_string + '\s{0,}' + date_number_re_string + '\s{0,}' + date_number_re_string + '\s{0,}' + date_number_re_string + ')' + ')'
# Note - the .{0,3} is just for the unreadable characters that sometimes replace the ordinal stuff
# or sometimes a random character is inserted before or after the number
complete_date_re = re.compile(complete_date_re_string)
clean_months = ['JANUARY', 'FEBRUARY', 'MARCH', 'APRIL', 'MAY', 'JUNE', 'JULY', 'AUGUST', 'SEPTEMBER', 'OCTOBER', 'NOVEMBER', 'DECEMBER']
property_address_re = re.compile('.{1,6}[riomu]{1,2}p.{1,3}[yzv]\s{0,}[Aa].{0,1}[dl]d{0,1}.[eun]{0,1}[sea]{1,2}[:\]\)\}\|l]| \[Property\]|P[ROM]{1,2}PE[RI][TL]Y\s{0,}ADDRES\s{0,1}S')
# If no colon, the address is above
# I with colon, the address is next to the marker and line below (if it is not empty)
# Check for the zip and state - insert comma before state if not found - to be able to separate the city
state_abbr_list = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY', 'DC']
state_names_list_re = re.compile('(ALABAMA)|(ARKANSAS)|(ARIZONA)|(ARKANSAS)|(CALIFORNIA)|(COLORADO)|(CONN.{0,7})' '|(DELAWARE)|(FLOR[IL]DA.{0,1})|(GEORGIA)|(HAWAII)|(IDAHO)|([IL]{4}NOIS)|(INDIANA)|(IOWA)' '|(KANSAS)|(KENTUCKY)|(LOUISIANA)|(MAINE)|(MARYLAND)|(MASSACHUSET{1,2}S)|(MICHIGAN)' '|(MINNESOTA)|(MISSISSIPPI)|(MISSOURI)|(MONTANA)|(NEBRASKA)|(NEVADA)|(NEW HAMPSHIRE)' '|(NEW JERSEY)|(NEW MEX[IL]CO)|(NEW\s{0,}YORK)|(NORTH CAROLINA)|(NORTH DAKOTA)|(OHIO)' '|(OKLAHOMA)|(OREGON)|(PENNSY[LI]VAN[IL]A)|(RHODE ISLAND)|(SOUTH CAROLINA)|(SOUTH DAKOTA)' '|(TENNESSEE)|(TEXAS)|(UTAH)|(VERMONT)|(VIRGINIA)|(WASHINGTON)|(WEST VIRGINIA)' '|(WISCONSIN)|(WYOMING)|(DISTRICT OF COLUMBIA)')
# BORROWER'S PROMISE TO PAY/RIGHT TO PREPAY components
borrowers_re_string = '(?i)[BIE83aD]{1,2}[O0DU][rnaBE]{2}\s{0,1}[O0DU].{0,2}[WV].{0,1}[EOA]{0,1}[RLFN].{0,3}\s{0,}[^A-Z]{0,2}'
promise_re_string = '(?i).{1,2}[RB]{0,1}[OE]{0,1}[MNH][ILT].{0,1}S{0,1}E\s{0,}'
to_pay_re_string = '(?i).{1,5}\s{0,1}[Oo0][E\s]{0,}[PAmFL]{1,2}.{0,1}[YxIlV]'
right_re_string = '(?i)R[Il1E][GC]H.{0,1}[TIl1].{0,1}\s{0,}'
to_prepay_re_string = '(?i).{1,3}[Oo0] [PF][RB]E[PF]AY'
borrowers_promise_to_pay_re_string = borrowers_re_string + promise_re_string + to_pay_re_string + '|' + 'In return for a loan' + '|' + 'For value received'
interest_uc_re_string = '[Iil1!\]\[\|].{0,1}N.{0,1}T.{0,1}[EF].{0,1}R[EB][SsI].{0,1}[T1I]{0,1}'
interest_lc_re_string = '\d\s{0,}[\.,]{0,1}\s{0,}[Il1i!\]\[\|]nterest|Interest will [bh]e charged'
payment_re_string = '.AY[MIWNVL\s]{1,3}[EIu]{1,2}N.'
payments_re_string = payment_re_string + 'S|\d\s{0,}[,\.]\s{0,}Payments'
time_and_place_of_payments_re_string = '[T\s][ilt][mn][ebc].{0,2}[aj]nd.{0,2}P[lI][a\s][ct]{1,2}[ec]' + '.{2,9}[aon][yv\s]t{0,1}[mn][ec][nua].{1,3}'
interest_rate_and_payment_changes_re_string = '.*' + interest_uc_re_string + '\s{0,}RATE AND.*' + payment_re_string +'.{1,9}AN\s{0,}G\s{0,}ES' + '|' +'Interest Rate and Payment Changes'
change_dates_re_string = 'Change Dates'
borrowers_right_to_prepay_re_string = borrowers_re_string + right_re_string + to_prepay_re_string + '|' + 'I\s{0,}have the right to make payments'
loan_charges_re_string = 'LOAN CHARGES|Loan Charges'
borrowers_promise_to_pay_re = re.compile(borrowers_promise_to_pay_re_string)
interest_uc_re = re.compile(interest_uc_re_string)
interest_lc_re = re.compile(interest_lc_re_string)
payments_re = re.compile(payments_re_string)
time_and_place_of_payments_re = re.compile(time_and_place_of_payments_re_string)
interest_rate_and_payment_changes_re = re.compile(interest_rate_and_payment_changes_re_string)
change_dates_re = re.compile(change_dates_re_string)
borrowers_right_to_prepay_re = re.compile(borrowers_right_to_prepay_re_string)
loan_charges_re = re.compile(loan_charges_re_string)
thereafter_re_string = '[Tt][hlr]{1,2}[ec]r[ec]a.{2}[ec]r'
# In[2]:
import re
def getLoanAndPaymentTypes(line, previous_line, attributes_row, in_file):
# There are cases where the actual NOTE is at the bottom/middle of the document
# Need to check the previous lines since sometimes 'INTEREST ONLY PERIOD' and 'ADJUSTABLE RATE NOTE'
# are in separate lines
loan_type = cleanLoanType(line)
attributes_row[loan_type_index] = loan_type
attributes_row = getPaymentType(loan_type, attributes_row, in_file)
# Check if 'INTEREST-ONLY PERIOD' is in the previous line
if len(interest_only_period_re.findall(previous_line)) > 0:
attributes_row[loan_type_index] = 'INTEREST-ONLY PERIOD ' + attributes_row[loan_type_index]
if debug:
print('Found loan type: ' + attributes_row[loan_type_index])
print('Found payment type: ' + attributes_row[payment_type_index] )
return attributes_row
def cleanLoanType(loan_type):
# If the first word is Note, then the type is just NOTE
if debug:
print('Loan type: ' + loan_type)
# Set to all caps
loan_type = loan_type.upper()
# Clean the common words
if len(adjustable_re.findall(loan_type)) > 0:
# Convert the regex version to just say 'ADJUSTABLE RATE'
arn_marker = adjustable_re.findall(loan_type)[0]
loan_type = loan_type.replace(arn_marker, 'ADJUSTABLE RATE ')
if len(promissory_re.findall(loan_type)) > 0:
promissory_marker = promissory_re.findall(loan_type)[0]
loan_type = loan_type.replace(promissory_marker, 'PROMISSORY ')
if len(fixed_re.findall(loan_type)) > 0:
fixed_marker = fixed_re.findall(loan_type)[0]
loan_type = loan_type.replace(fixed_marker, 'FIXED ')
if len(multistate_re.findall(loan_type)) > 0:
multistate_marker = multistate_re.findall(loan_type)[0]
loan_type = loan_type.replace(multistate_marker, 'MULSTISTATE ')
# Remove everything that is not a letter or space
# Convert multiple spaces to just one space
loan_type = re.sub('[^A-Za-z\s/]', '', loan_type).strip()
loan_type = re.sub('\s+', ' ', loan_type)
# Remove everything after note
loan_type_words = loan_type.split()
loan_type = ''
for loan_type_word in loan_type_words:
note_marker = note_re.findall(loan_type_word)
if len(note_marker) > 0 and loan_type_word == note_marker[0]:
loan_type = loan_type + ' NOTE'
break;
else:
loan_type = loan_type + ' ' + loan_type_word
# Remove everything before 'FIXED
fixed_index = loan_type.find('FIXED')
if fixed_index != -1:
loan_type = loan_type[fixed_index:]
loan_type = loan_type.strip()
# Split the words by space and if it has less than 3 characters, remove it
# Remove the extra characters in the beginning
loan_type_words = loan_type.split()
if len(loan_type_words[0].strip()) < 3:
loan_type = ' '.join(loan_type_words[1:])
if debug:
print('Cleaned loan type: ' + loan_type)
return loan_type
def getPaymentType(loan_type, attributes_row, in_file):
# Get the line below for certail loan types
payment_type= ''
if len(adjustable_re.findall(loan_type)) > 0 or len(equity_re.findall(loan_type)) > 0 or len(balloon_re.findall(loan_type)) > 0 or len(promissory_re.findall(loan_type)) > 0:
payment_type_found = False
end_of_file_found = False
while not (payment_type_found or end_of_file_found):
payment_type = in_file.readline()
if len(payment_type) == 0:
# End of file
end_of_file_found = True
else:
payment_type = payment_type.replace('\n', '').strip()
if len(payment_type) > 5:
this_note_marker_re = re.compile('(?i)TH[EIS]{1,2} NOTE')
if len(this_note_marker_re.findall(payment_type)) > 0:
# 'THIS NOTE' is not the string we want for payment type
payment_type = ''
payment_type_found = True
elif len(promissory_re.findall(payment_type)) > 0 or len(interest_only_period_re.findall(payment_type)) > 0:
# There are cases where a promissory note has CONSOLIDATED, RESTATED, etc and the next line
# has the words PROMISSORY NOTE. We want the line after this
payment_type_found = False
else:
payment_type_found = True
attributes_row[payment_type_index] = cleanPaymentType(payment_type)
return attributes_row
def cleanPaymentType(payment_type):
# Clean payment type
start_marker_re = re.compile('[\(\[\{\|C]')
end_marker_re = re.compile('[\)\]]')
start_marker = start_marker_re.findall(payment_type)
end_marker = end_marker_re.findall(payment_type)
if len(start_marker) > 0 and len(end_marker) > 0:
start_index = payment_type.find(start_marker[0]) # Get the first one
end_index = payment_type.find(end_marker[-1]) # Get the last one
payment_type = payment_type[start_index + 1: end_index]
elif len(start_marker) > 0:
start_index = payment_type.find(start_marker[0]) # Get the first one
payment_type = payment_type[start_index + 1]
elif len(end_marker) > 0:
end_index = payment_type.find(end_marker[-1]) # Get the last one
payment_type = payment_type[:end_index]
treasury_re = re.compile('(?i).{2,3}[ane][sm]u\s{0,}ry')
index_re = re.compile('(?i)Inde[xk]')
month_re = re.compile('(?i)mont[hl]{1,2}')
arm_re = re.compile('AR[MNI\s]{1,2}')
rate_re = re.compile('R[aui]\s{0,}[tli].{0,1}[eE]')
cr_re = re.compile('Cons.*v[ec]r')
if len(treasury_re.findall(payment_type)) > 0:
# Convert the regex version to just say 'Treasury'
treasury_marker = treasury_re.findall(payment_type)[0]
payment_type = payment_type.replace(treasury_marker, 'Treasury ')
if debug:
print('Treasury marker + cleaned payment type: ', str(treasury_marker), payment_type)
if len(index_re.findall(payment_type)) > 0:
# Convert the regex version to just say 'Index'
index_marker = index_re.findall(payment_type)[0]
payment_type = payment_type.replace(index_marker, 'Index ')
if debug:
print('Index marker + cleaned payment type: ', str(index_marker), payment_type)
if len(month_re.findall(payment_type)) > 0:
# Convert the regex version to just say 'Month'
month_marker = month_re.findall(payment_type)[0]
payment_type = payment_type.replace(month_marker, 'Month ')
if debug:
print('Month marker + cleaned payment type: ', str(month_marker), payment_type)
if len(arm_re.findall(payment_type)) > 0:
# Convert the regex version to just say 'Index'
arm_marker = arm_re.findall(payment_type)[0]
payment_type = payment_type.replace(arm_marker, 'ARM ')
if debug:
print('ARM marker + cleaned payment type: ', str(arm_marker), payment_type)
if len(fixed_re.findall(payment_type)) > 0:
fixed_marker = fixed_re.findall(payment_type)[0]
payment_type = payment_type.replace(fixed_marker, 'Fixed ')
if debug:
print('Fixed marker + cleaned payment type: ', str(fixed_marker), payment_type)
if len(rate_re.findall(payment_type)) > 0:
rate_marker = rate_re.findall(payment_type)[0]
payment_type = payment_type.replace(rate_marker, 'Rate ')
if debug:
print('Rate marker + cleaned payment type: ', str(rate_marker), payment_type)
if len(cr_re.findall(payment_type)) > 0:
cr_marker = cr_re.findall(payment_type)[0]
payment_type = payment_type.replace(cr_marker, 'Construction/Rollover')
if debug:
print('Construction/Rollover marker + cleaned payment type: ', str(cr_marker), payment_type)
fixed_rate_re = re.compile('.{0,3}[ecn]d\s{0,}.{0,3}\s{0,}Rate|Fixed\s{0,}[Rmtun]{1,3}')
if len(fixed_rate_re.findall(payment_type)) > 0:
fixed_rate_marker = fixed_rate_re.findall(payment_type)[0]
payment_type = 'Fixed Rate'
if debug:
print('Fixed Rate marker + cleaned payment type: ', str(fixed_rate_marker), payment_type)
# Remove everything that is not a letter, number, / or space
# Convert multiple spaces to just one space
payment_type = re.sub('[^A-Za-z0-9/\s]', '', payment_type).strip()
payment_type = re.sub('\s+', ' ', payment_type)
payment_type = payment_type.strip()
if len(payment_type) < 5:
payment_type = ''
return payment_type
def getDateAndCity(line, previous_lines, attributes_row):
# There are other parts of the document that has one of the 3 and that is not what we want
# Prioritize the lines in previous_lines when getting dates
# We are just checking the lengths of the lines
if len(previous_lines[2].strip()) > 10:
date_line = previous_lines[2]
elif len(previous_lines[1].strip()) > 10:
date_line = previous_lines[1]
else:
date_line = previous_lines[0]
date_line_splits = re.split(r'\s{5,}', date_line)
# Make sure the date_line_splits only contain "valid" data; Remove a split that do not have alphanumeric characters
date_line_splits = [date_line_split for date_line_split in date_line_splits if (sum(c.isdigit() for c in date_line_split) > 2 or sum(c.isalpha() for c in date_line_split) > 2 ) ]
if debug:
print('Found date city marker: ' + line)
print('Date line splits: ' , date_line_splits)
mortgage_date = ''
date_city = ''
split_index = 0
for split in date_line_splits:
if len(complete_date_re.findall(split)) > 0:
# This split has the date
mortgage_date = split
break;
split_index +=1
if split_index < len(date_line_splits) - 1:
date_city = date_line_splits[split_index + 1]
if debug:
print('Found date: ' + mortgage_date)
print('Found city: ' + date_city)
if mortgage_date.startswith('Error'):
cleaned_date = mortgage_date
formatted_date = ''
else:
cleaned_date, formatted_date = cleanAndFormatDate(mortgage_date)
attributes_row[mortgage_date_index] = cleaned_date
attributes_row[productions_fund_date_index] = cleaned_date
attributes_row[usps_city_index] = date_city
return attributes_row
def getMortgageDate(line):
# Get date from line
# We keep dates until we find 'BORROWERS PROMISE TO PAY'
line_splits = re.split(r'\s{3,}', line)
split_with_possible_date = ''
for line_split in line_splits:
# Check the number of characters (without spaces in each split)
chars_count = len(line_split.strip().replace(' ', ''))
if chars_count > 5 and chars_count < 20:
split_with_possible_date = line_split
date_marker = complete_date_re.findall(split_with_possible_date)
if len(date_marker) > 0:
date = date_marker[0][0]
remaining_characters = split_with_possible_date.replace(date, '').strip()
if debug:
print('Found the date in: ', split_with_possible_date)
print('Date is: ', date)
return date
return ''
def cleanAndFormatDate(date):
if len(date.strip()) == 0:
return '', ''
if debug:
print('Input date: ', date)
# Remove . if it is the first/last character in the number
if date[-1] == '.':
date = date[:-1]
if date[0] == '.':
date = date[1:]
if debug:
print('Date after removing . in front/end:', date)
# Remove , if it is the first/last character in the number
if date[-1] == ',':
date = date[:-1]
if date[0] == ',':
date = date[1:]
if debug:
print('Date after removing , in front/end:', date)
# Remove 'st', 'nd', 'rd', and 'th'
ordinal_re_string = '[1liIL:\|\[\]\(\)]st|[2Zz]nd|3rd|[45Ss6G78B90OoDUu]th'
ordinal_re = re.compile(ordinal_re_string)
ordinal_marker = ordinal_re.findall(date)
if len(ordinal_marker) > 0:
ordinal_marker_removed = re.sub('st|nd|rd|th', '', ordinal_marker[0])
date = date.replace(ordinal_marker[0], ordinal_marker_removed)
if debug:
print('After removing the ordinal stuff: ', date)
date_marker = complete_date_re.findall(date)
cleaned_date = 'Error: Date not found: ' + date
formatted_date = ''
if len(date_marker) > 0:
if debug:
print('Date marker: ', str(date_marker))
date = date_marker[0][2:]
# 2: since the first two are the complete date and the month name
month_found = False
month_index = 0
while not month_found and month_index < 12:
if len(date[month_index].strip()) > 0:
month_found = True
break;
month_index += 1
month_name = clean_months[month_index]
month_number = str(month_index+1)
if len(month_number) == 1:
month_number = '0' + month_number
day = date[-2]
day = day.replace(' ', '')
if len(day) > 2:
day = day[0:2]
day = convertLettersToNumbers(day)
day = re.sub('[^0-9]', '', day)
if len(day) == 0:
day = '01'
if int(day) > 31:
day = day[0]
if len(day) == 1:
day = '0' + day
year = date[-1]
year = year.replace(' ', '')
year = convertLettersToNumbers(year)
# For now, the cleaned date is in the format Month Day, Year (Day is 1 or 2 characters)
cleaned_date = month_name + ' ' + str(int(day)) + ', ' + year
formatted_date = year + month_number + day
# Have restrictions/error-checking for date
if year[0] == '0' or int(year[0]) > 2:
# This is a wrong year
cleaned_date = 'Error: Year is wrong: ' + year
elif year[0] == '1' and year[1] == '0':
year = '2' + year[1:]
cleaned_date = month_name + ' ' + str(int(day)) + ', ' + year
formatted_date = year + month_number + day
elif year[0] == '2' and year[1] == '9':
year = '1' + year[1:]
cleaned_date = month_name + ' ' + str(int(day)) + ', ' + year
formatted_date = year + month_number + day
if debug:
print(date_marker)
print(date)
print(month_name)
print(month_number)
print(day)
print(year)
print(cleaned_date)
return cleaned_date, formatted_date
def getPropertyAddressFromLines(previous_lines, line_with_date):
property_address = ''
# Start from the last line (so switch up the first and last lines)
temp_line = previous_lines[0]
previous_lines[0] = previous_lines[2]
previous_lines[2] = temp_line
for previous_line in previous_lines:
if len(previous_line.strip()) > 0:
if len(property_address.strip()) > 0 and previous_line[-1] != ',':
# Concatenate lines (remember the lines are reversed in order)
property_address = ', ' + property_address
property_address = previous_line + property_address
if previous_line[0].isdigit():
# This line starts with a number (which means it is most likely an address), this is the only address line
break;
address_words = re.split('\s',property_address)
if len(address_words) <= 5:
if debug:
print('Address is too short - get the other part from line_with_date')
line_with_date_splits = re.split('\s{3,}', line_with_date)
if len(line_with_date_splits) > 1:
other_address = line_with_date_splits[1].strip()
property_address = other_address + ', ' + property_address
# Get last 6 characters of property_address - remove spaces and convert numbers to letters
last_6 = property_address[-6:].strip()
last_6 = re.sub('[\s\.]', '', last_6)
new_last_6 = convertLettersToNumbers(last_6)
if new_last_6.isdigit():
# Don't replace unless we are able to turn it into a zip
property_address = property_address[:-6] + ' ' + new_last_6
if debug:
print('last 6 charcters: ', last_6)
print('new last 6 characters: ', new_last_6)
print('new property address: ', property_address)
# Find any 5-digit number - get the last occurrence and remove everything else after that (assuming it's the zip)
zip_re = re.compile('\d{5}')
zip_re_marker = zip_re.findall(property_address)
if len(zip_re_marker) > 0:
zip = zip_re_marker[-1]
zip_end_index = property_address.find(zip) + 5
property_address = property_address[:zip_end_index]
if debug:
print('Previous lines: ', str(previous_lines))
print('Line with date: ', line_with_date)
print('Zip marker: ', zip_re_marker)
print('Property address: ', property_address)
# Change X.Y. to XY
dot_marker_re = re.compile('[A-Za-z]\.[A-Za-z]\.')
dot_marker = dot_marker_re.findall(property_address)
for marker in dot_marker:
property_address = property_address.replace(marker, marker.replace('.', ''))
if debug:
print('Property Address after changing X.Y. to XY: ', property_address)
# Replace '.' with ',' in address
property_address = property_address.replace('.', ',')
# Replace 2 commas together (since we have replaced . with ,)
property_address = re.sub(',\s{0,},', ',', property_address)
if debug:
print('Property Address after replacing the . to , and replacing 2 commas to 1: ', property_address)
if len(property_address.strip()) > 105:
# This is when the last 3 sentences of a paragraph are mistaken to be the addresses
if debug:
print('Property address is too long: ', str(len(property_address.strip())))
property_address = ''
return property_address
def streetWordInAddress(street_word, address):
# Only keep alpha-numeric characters in the address
address_words = address.split()
if any (street_word == address_word for address_word in address_words):
return True
else:
return False
def getAddressValues(property_address, attributes_row):
if debug:
print('Property Address: ' + property_address)
city = attributes_row[usps_city_index]
# Remove anything at the end/beginning that has more than 5 spaces
address_line_splits = re.split(r'\s{5,}', property_address)
property_address = ''
for split in address_line_splits:
if len(split) > 3:
property_address = property_address + ' ' + split
# Change address to upper case and replace multiple spaces with just one
property_address = property_address.strip().upper()
property_address = re.sub('\s{2,}', ' ', property_address)
city = city.upper()
if debug:
print('Property Address after removing the extra stuff at the end/beginning: ', property_address)
if len(property_address.strip()) == 0:
return attributes_row
# Remove 'PROPERTY ADDRESS' from the line (sometimes the marker is not caught if : is not present)
property_address_marker = property_address_re.findall(property_address)
if len(property_address_marker) > 0:
property_address = property_address.replace(property_address_marker[0], '').strip()
if debug:
print('Property address marker: ', str(property_address_marker))
# Replace a comma surrounded by spaces with just the comma
property_address = re.sub('\s{0,},\s{0,}', ', ', property_address)
# Replace D.C. with DC
property_address = re.sub('D\s{0,}[\.,]\s{0,}C\s{0,}[\.,]', 'DC', property_address)
# If the address ends or begins with , or ., remove those
# This makes sure we don't have an empty split
property_address = property_address.strip()
if property_address[-1] == '.' or property_address[-1] == ',':
property_address = property_address[:-1]
if property_address[0] == '.' or property_address[0] == ',':
property_address = property_address[0:]
property_address = property_address.strip()
# Split by space
# Do not want to split by comma since we want to keep it in cases where there are multipel street addresses
address_words = re.split('\s',property_address)
if debug:
print('Address splits by space: ', str(address_words))
# Address are in the form street, city, state, zip
# However, there are cases when the zip or street are not available
property_street_address = ''
property_city_address = ''
property_state_address = ''
property_zip_address = ''
property_street_city_address = ''
property_street_city_state_address = ''
property_state_zip_address = ''
if len(city.strip()) > 0 and city in property_address:
# City data is in property_address, so can figure out state-zip and street
address_splits = property_address.split(city)
property_street_address = address_splits[0].strip()
property_city_address = city.strip()
property_state_zip_address = address_splits[1][1:].strip()
property_state_address, property_zip_address = splitStateZip(property_state_zip_address)
if debug:
print('state_zip: ' + str(property_state_zip_address))
else:
# The city name obtained with the date line is not in the address (probably misspelled) or no city info found
# Check for street name and add a comma if needed
# Check for street name and see if there is somewhere where we can insert the commas
street_words = ['AVENUE', 'BOULEVARD', 'CIRCLE', 'COURT', 'DRIVE', 'LANE', 'PLACE', 'ROAD', 'STREET', 'TRAIL', 'WAY', 'AVE', 'BLVD', 'CIR', 'CT', 'DR', 'LN', 'PL', 'RD', 'ST']
for street_word in street_words:
if streetWordInAddress(street_word, property_address):
property_address = property_address.replace(street_word, street_word + ',')
break;
# Re-split after adding the ,
address_words = re.split('\s',property_address)
if debug:
print('Property Address after adding , if needed: ', property_address)
print('Address splits by space: ', str(address_words))
print('Last split, checking if zip: ', address_words[-1])
zip_re = re.compile('\d{4,6}')
if len(zip_re.findall(address_words[-1])) > 0:
# This is the zip, check for the word/s before it if it matches a state
property_zip_address = address_words[-1].strip()
property_street_city_state_address = ' '.join(address_words[0:-1])
if debug:
print('Last split is a zip: ', property_zip_address)
print('Property Street, City, State Address: ', property_street_city_state_address)
if stateIsInPropertyAddress(property_street_city_state_address):
property_street_address, property_city_address, property_state_address = splitStreetCityStateAddress(property_street_city_state_address)
else:
# Error in state - parse using splits
if debug:
print('Last split was a zip but error on state, property_street_city_state_address: ', property_street_city_state_address)
property_street_address, property_city_address, property_state_address, property_zip_address = getAddressValuesBasedOnSplits(property_address)
else:
# Last split is either part of a state or a wrong format for zip
# First check if the last split or last 2 splits correspond to a state
# If not, try and parse based on splits
property_street_city_state_address = property_address
if stateIsInPropertyAddress(property_street_city_state_address):
# No zip
# The last split/s correspond to the state
property_zip_address = ''
property_street_address, property_city_address, property_state_address = splitStreetCityStateAddress(property_street_city_state_address)
else:
if debug:
print('Last split not a zip, property_street_city_state_address: ', property_street_city_state_address)
# Error with the zip/state, parse based on ','
property_street_address, property_city_address, property_state_address, property_zip_address = getAddressValuesBasedOnSplits(property_address)
if debug:
print('ADDRESSES: ')
print(property_street_address)
print(property_city_address)
print(property_state_address)
print(property_zip_address)
# Clean the data
attributes_row[usps_full_address_index] = cleanAddress(property_street_address)
attributes_row[usps_city_index] = cleanAddress(property_city_address)
attributes_row[usps_state_index] = getStateCode(cleanAddress(property_state_address))
attributes_row[usps_zip_index] = cleanZip(property_zip_address)
return attributes_row
def cleanAddress(address):
address = re.sub('[^A-Za-z0-9#\.,\-&\(\)\s]', '', address)
return address
def cleanZip(property_zip_address):
# Convert letters to numbers
# Remove spaces
# Only return the first 5 digits
# If I don't have 5 numbers, return an empty string
zip = property_zip_address.replace(' ', '')
zip = convertLettersToNumbers(zip)
if len(zip) >= 5:
return zip[:5]
else:
return ''
def stateIsInPropertyAddress(address):
# This checks if the last word/s hsa the state
# If the zip is still here, this will return a False
if len(address.strip()) == 0:
return False
address_words = address.strip().split()
first_state_word_marker_re = re.compile('NEW|NORTH|SOUTH|WEST|RHODE')
state_name_marker = state_names_list_re.findall(address_words[-1])
# Check for the state
if address_words[-1][-1] == ',' or address_words[-1][-1] == '.':
# Remove the comma or period
address_words[-1] = address_words[-1][:-1]
if len(address_words[-1]) == 2 or len(state_name_marker) > 0:
state_is_here = True
elif len(address_words) > 1 and len(first_state_word_marker_re.findall(address_words[-2])) > 0:
# State has 2 words
state_is_here = True
elif len(address_words) > 2 and address_words[-2] == 'OF':
# State is DC - has 3 words
state_is_here = True
else:
state_is_here = False
return state_is_here
def splitStreetCityStateAddress(property_street_city_state_address):
if len(property_street_city_state_address.strip()) == 0:
return '', '', ''
# Only gets called when state exists (but still added an error-checking in the end just in case)
address_words = property_street_city_state_address.strip().split()
first_state_word_marker_re = re.compile('NEW|NORTH|SOUTH|WEST|RHODE')
state_name_marker = state_names_list_re.findall(address_words[-1])
# Check for the state
if address_words[-1][-1] == ',' or address_words[-1][-1] == '.':
# Remove the comma or period
address_words[-1] = address_words[-1][:-1]
if len(address_words[-1]) == 2 or len(state_name_marker) > 0:
state_start_index = len(address_words) - 1
elif len(address_words) > 1 and len(first_state_word_marker_re.findall(address_words[-2])) > 0:
# State has 2 words
state_start_index = len(address_words) - 2
elif len(address_words) > 2 and address_words[-2] == 'OF':
# State is DC - has 3 words
state_start_index = len(address_words) - 3
else:
state_start_index = -1
if state_start_index >= 0:
property_state_address = ' '.join(address_words[state_start_index:])
if state_start_index > 0:
property_street_city_address = ' '.join(address_words[0:state_start_index])
property_street_address, property_city_address = splitStreetCity(property_street_city_address)
else:
property_street_address = ''
property_city_address = ''
if debug:
print('splitStreetCityStateAddress: Property State Address: ', property_state_address)
print('splitStreetCityStateAddress: Property Street, City Address: ', property_street_city_address)
else:
property_state_address = 'Error on Parsing: ' + property_street_city_state_address
property_street_address = 'Error on Parsing: ' + property_street_city_state_address
property_city_address = 'Error on Parsing: ' + property_street_city_state_address
return property_street_address, property_city_address, property_state_address
def splitStateZip(property_state_zip_address):
address_words = re.split('[\s,]', property_state_zip_address)
if debug:
print('splitStateZip: address_words: ', str(address_words))
if len(address_words) > 0:
# Check first if the last split is a zip and get its index
zip_re = re.compile('\d{4,6}')
if len(zip_re.findall(address_words[-1])) > 0:
zip_marker = zip_re.findall(address_words[-1])[0]
zip_start_index = property_state_zip_address.find(zip_marker)
property_zip_address = property_state_zip_address[zip_start_index:zip_start_index+5]
property_state_address = property_state_zip_address[:zip_start_index-1]
else:
# Either error with zip or no zip
if debug:
print('splitStateZip: There was an error with zip')
if stateIsInPropertyAddress(property_state_zip_address):
state_end_index = len(address_words)
property_zip_address = ''
else:
state_end_index = len(address_words) - 1
property_zip_address = address_words[-1]
property_state_address = ' '.join(address_words[0:state_end_index])
else:
property_state_address = 'Error - no StateZip data'
property_zip_address = 'Error - no StateZip data'
if debug:
print('splitStateZip: Property State Address: ', property_state_address)
print('splitStateZip: Property Zip Address: ', property_zip_address)
return property_state_address, property_zip_address
def splitStreetCity(property_street_city_address):
if property_street_city_address[-1] == ',' or property_street_city_address[-1] == '.':
# Remove the , or . at the end
property_street_city_address = property_street_city_address[:-1]
addresses = re.split('[,\.]', property_street_city_address.strip())
# Lots of cases where 'NEW YORK' is not parsed correctly
new_york_index = property_street_city_address.find('NEW YORK')
if new_york_index != -1:
property_city_address = property_street_city_address[new_york_index:].strip()
property_street_address = property_street_city_address[:new_york_index-1].strip()
elif len(addresses) >= 2:
property_street_address = ', '.join(addresses[0:-1]).strip()
property_city_address = addresses[-1].strip()
else:
property_street_address = 'Error in parsing street city:' + property_street_city_address
property_city_address = 'Error in parsing street city:' + property_street_city_address
if debug:
print('splitStreetCity: Property Street Address: ', property_street_address)
print('splitStreetCity: Property City Address: ', property_city_address)
return property_street_address, property_city_address
def getAddressValuesBasedOnSplits(property_address):
addresses = property_address.strip().split(',')
property_street_address = ''
property_city_address = ''
property_state_address = ''
property_zip_address = ''
if len(addresses) == 4:
if len(addresses[-1].strip()) >= 4 and len(addresses[-1].strip()) <= 6:
# Could be one group for street address and state and zip are separated by a comma
property_street_address = addresses[0].strip()
property_city_address = addresses[1].strip()
property_state_address = addresses[2].strip()
property_zip_address = addresses[3].strip()
state_zip_together = False
else:
# Or 2 groups for street address and state and zip are together
property_street_address = addresses[0].strip() + ', ' + addresses[1].strip()
property_city_address = addresses[2].strip()
property_state_zip_address = addresses[3].strip()
state_zip_together = True
elif len(addresses) >= 5:
# Two or more groups for street address and state and zip could be together or separated
# If the last split contains only the zip (5 digits), then state and zip are separated
if addresses[-1].isdigit() or (len(addresses[-1]) >= 4 and len(addresses[-1]) <= 6):
property_city_address = addresses[-3].strip()
property_state_address = addresses[-2].strip()
property_zip_address = addresses[-1].strip()
state_zip_together = False
end_street_index = len(addresses) - 4
else:
property_city_address = addresses[-2].strip()
property_state_zip_address = addresses[len(addresses)-1].strip()
state_zip_together = True
end_street_index = len(addresses) - 3
property_street_address = ' '.join(addresses[0:end_street_index])
elif len(addresses) == 3:
property_street_address = addresses[0].strip()
property_city_address = addresses[1].strip()
property_state_zip_address = addresses[len(addresses)-1].strip()
state_zip_together = True