-
Notifications
You must be signed in to change notification settings - Fork 0
/
CLIENTRESUMEMATCHER.py
1747 lines (1709 loc) · 82.1 KB
/
CLIENTRESUMEMATCHER.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
#
#
#
# pip install -r requirements.txt
#
#
import datetime
STARTCODETIME = datetime.datetime.now() #Setting up time to find total time spent on code
import statistics
import numpy as np
import pandas as pd
from google.oauth2 import service_account #Control API Keys
from google.cloud import vision
import os, cv2
from pdf2image import convert_from_path
from collections import Counter
from IPython.display import Image
from shapely.geometry import Polygon
import io
import shutil
from google.cloud.vision import types
from PIL import Image, ImageDraw, ImageFont
import string, spacy
from pandas import ExcelWriter
from termcolor import colored
from stop_words import get_stop_words
from google.cloud import documentai_v1beta2 as documentai
from pyresparser import ResumeParser
from matplotlib import pyplot as plt
stop_words = get_stop_words('english')
nlp = spacy.load("en_core_web_sm")
# ------- Declare all Paths ---------
#doc = '/Users/kunal/Documents/VdartResumeProject/VisionAPi/Document_402.pdf'
keyDIRDocumentAI = "/Users/kunal/Documents/VdartResumeProject/APIKEYSGOOGLE/resumeMatcher-documentAI.json"
docPath = '/Users/kunal/Documents/VdartResumeProject/VisionAPi/'
imgTxtVisionAPIPath = "/Users/kunal/Documents/VdartResumeProject/APIKEYSGOOGLE/resumeMatcher-pdf2img.json"
pdfIMGPopplerPath = '/Users/kunal/Documents/VdartResumeProject/Poppler/poppler-0.68.0_x86/poppler-0.68.0/bin/'
fontPath = '/Users/kunal/Documents/VdartResumeProject/Font/FreeMonoBold.ttf'
allResumesPath = "/Users/kunal/Documents/VdartResumeProject/50_resumes/"
nlpAutoAPIPath = "/Users/kunal/Documents/VdartResumeProject/APIKEYSGOOGLE/resumeMatcher-NLP_create_data.json"
# ------- Checking for API -------
#Using API from Google and returns a JSON file but text is extracted from it
keyDIR = imgTxtVisionAPIPath #JSON key file to call the api
credentials = service_account.Credentials.from_service_account_file(keyDIR) #using service account to go through google
client = vision.ImageAnnotatorClient(credentials=credentials) # client api
filePDFPath = '/Users/kunal/Documents/VdartResumeProject/A_RunningFiles/Document_402.pdf'
def deleteEverythingInFolder(folder_pdf):
#deletes everything in the folder including folders and files
for file in os.listdir(folder_pdf):
try:
shutil.rmtree(folder_pdf+ file) #remove folder
except NotADirectoryError:
try:
os.remove(folder_pdf+ file) # if it is not a folder than it is a file so it removes it also
except:
pass
def convert_pdf_2_image(filePath):
#os.chdir(os.path.dirname(filePath))
uploaded_file = filePath
output_file = str(uploaded_file).replace('.pdf','')
pages = convert_from_path(uploaded_file, 200,poppler_path=pdfIMGPopplerPath)
pageCount = 1
if len(pages) != 1:
raise Exception ("Some of the code is not compatable for multiple pages")
for page in pages:
page.save(output_file + "_" + str(pageCount) + ".jpg", 'JPEG')
#print(output_file + "_" + str(pageCount) + ".jpg")
pageCount+=1
return output_file + "_1.jpg"
os.chdir(os.path.dirname(filePDFPath))
try:
os.mkdir(os.path.basename(filePDFPath)[:-4])
folderPath = os.path.dirname(filePDFPath)+"/"+os.path.basename(filePDFPath)[:-4]
except FileExistsError:
try:
os.mkdir(os.path.basename(filePDFPath)[:-4] + "_NEW")
folderPath = os.path.dirname(filePDFPath)+"/"+os.path.basename(filePDFPath)[:-4] + "_NEW"
except FileExistsError:
deleteEverythingInFolder(os.path.basename(filePDFPath)[:-4] + "_NEW")
folderPath = os.path.dirname(filePDFPath)+"/"+os.path.basename(filePDFPath)[:-4] + "_NEW"
try:
shutil.move(filePDFPath, folderPath)
if os.path.exists(folderPath+"/"+os.path.basename(filePDFPath)):
filePDFPath = folderPath+"/"+os.path.basename(filePDFPath)
except Exception:
pass
os.chdir(folderPath)
print(filePDFPath)
imagePath = convert_pdf_2_image(filePDFPath)
if os.path.exists(imagePath):
print("Running " + os.path.basename(imagePath))
else:
raise Exception("File Doesn't Exist")
global printingToDisplay
printingToDisplay = True
print("Printing ALL info about document") if printingToDisplay else print("Printing Nothing")
bounds = []
with io.open(imagePath, 'rb') as image_file:
content = image_file.read()
image = types.Image(content=content)
response = client.document_text_detection(image=image)
global document
document = response.full_text_annotation
global TOTALWIDTHOFDOCUMENT
global TOTALHEIGHTOFDOCUMENT
response4 = client.document_text_detection(image = image)
for i in response4.full_text_annotation.pages:
TOTALWIDTHOFDOCUMENT = i.width
TOTALHEIGHTOFDOCUMENT = i.height
if printingToDisplay: print("Called API --> Width:" + str(TOTALWIDTHOFDOCUMENT) + " -- Height: " + str(TOTALHEIGHTOFDOCUMENT))
# findArea --> Inputs the boundingbox from the API and returns area --> polygon calculation
def findArea(bounds):
matrix = ((bounds.vertices[0].x, bounds.vertices[0].y),
(bounds.vertices[1].x, bounds.vertices[1].y),
(bounds.vertices[2].x, bounds.vertices[2].y),
(bounds.vertices[3].x, bounds.vertices[3].y))
polygon = Polygon(matrix)
return polygon.area
# detect_Maximum_outlier --> Using z-score calculate the Outliers on MAX side (0.14% - equal distribution)
def detect_Maximum_outlier(data_1):
#z = (X — μ) / σ
#Formula for Z score = (Observation — Mean)/Standard Deviation
outliers=[]
threshold=3
mean_1 = np.mean(data_1)
std_1 =np.std(data_1)
for y in data_1:
z_score= (y - mean_1)/std_1
if np.abs(z_score) > threshold and y > mean_1:
outliers.append(y)
return outliers
# findMaxOutliersIQR --> Using IQR find maximum outliers (x>75%)
def findMaxOutliersIQR(datasetInput):
dataset = sorted(datasetInput)
q1, q3= np.percentile(dataset,[25,75])
iqr = q3 - q1
upper_bound = q3 +(1.5 * iqr)
outliers=[]
for num in dataset:
if num>upper_bound:
outliers.append(num)
return outliers
# find average of both of those outlier calculations
def averageOfBothOutliers(data):
return (min(detect_Maximum_outlier(data)) + min(findMaxOutliersIQR(data)))/2
# List of all types of character (not punctiuation [a,b....y,x,z,A,B,C...Y,X,Z])
alphaList = list(string.ascii_lowercase) + list(string.ascii_uppercase)
allbbChar = []
# groupsSymbols into 52 groups of alphaList
for charater in alphaList:
charbb = []
for page in document.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
for word in paragraph.words:
for symbol in word.symbols:
if symbol.text == charater:
charbb.append(symbol.bounding_box)
allbbChar.append(charbb)
dfList = []
for i in range(len(allbbChar)):
charLen = [alphaList[i], len(allbbChar[i])]
dfList.append(charLen)
#print(alphaList[i] + "\t" + str(len(allbbChar[i])))
df=pd.DataFrame(dfList, columns=['Char','NumberOfChars'])
if printingToDisplay: print(df)
def convertBoundBoxtodiagonalRectangual(polygon):
#print(polygon)
if (abs(polygon.vertices[0].x - polygon.vertices[3].x)<=1 and
abs(polygon.vertices[0].y - polygon.vertices[1].y)<=1 and
abs(polygon.vertices[1].x - polygon.vertices[2].x)<=1 and
abs(polygon.vertices[2].y - polygon.vertices[3].y)<=1):
matrixCrop = (min(polygon.vertices[0].x, polygon.vertices[3].x),
min(polygon.vertices[0].y, polygon.vertices[1].y),
max(polygon.vertices[1].x, polygon.vertices[2].x),
max(polygon.vertices[2].y, polygon.vertices[3].y))
else:
matrixCrop = (min(polygon.vertices[0].x, polygon.vertices[3].x),
min(polygon.vertices[0].y, polygon.vertices[1].y),
max(polygon.vertices[1].x, polygon.vertices[2].x),
max(polygon.vertices[2].y, polygon.vertices[3].y))
print("Maybe Error When Converting Polygon To Rectangle")
#raise Exception
#matrixCrop = (0,0,0,0)
return matrixCrop
# convertBoundBoxtodiagonalRectangual --
# Converts the boundingbox API to a matrix format
def findModeLongWay(lst):
if len(lst) == 0:
return 0
from collections import Counter
d_mem_count = Counter(lst)
modeLst = []
for k in d_mem_count.keys():
if d_mem_count[k] > 1:
modeLst.append(k)
try:
return int(round(statistics.mean(modeLst)))
except:
try:
return int(round(statistics.mean(modeLst)))
except:
try:
print("Error when calculating Mode")
return int(round(modeLst[0]))
except:
return 0
# findModeLongWay -- Sometime when calculating mode using statistics.mode() there could result in error when there
# are multiple modes so this function does it but takes longer
def cutTopandBottomBlackRowsFunction(new_img):
# GO THROUGH EACH ROW IN ORGINAL PICTURE AND MARK OUT THE ROWS THAT NEED TO BE DELETED
deleteRows = []
rowNum = 0
for row in new_img:
ct = 0
for rgb in row:
if not all(rgb == 0):
break
else:
ct+=1
#print(ct==len(row))
if (ct==len(row)):
deleteRows.append(rowNum)
rowNum+=1
# GO THROUGH EACH ROW AND DELETE THE ROWS -- IMG CROPPED TOP AND BOTTOM
rowCt = 0
croppedTopBottomImg = []
for row in new_img:
if rowCt not in deleteRows:
newrow = []
for rgb in row:
#print(rgb)
newrow.append([rgb[0], rgb[1], rgb[2]])
#print(newrow)
#print(row)
#print()
croppedTopBottomImg.append(newrow)
#print(rowCt)
rowCt+=1
return croppedTopBottomImg
# cutTopandBottomBlackRowsFunction --
# |-----------| |-XXXXXXXX--|
# |-XXXXXXXX--| |-X---------|
# |-X---------| |-XXXXXXXX--|
# |-XXXXXXXX--| ----> |-X---------|
# |-X---------| |-XXXXXXXX--|
# |-XXXXXXXX--| [Removes all the empty space below and above the image]
# |-----------|
def convertImgto01OrginalFunction(new_img):
# CONVERT IMAGE TO 0 AND 1 IMAGE FROM THE ORGINAL IMAGE
newImgOnly01 = []
for row in new_img:
newRow = []
for rgb in row:
newArrayRowz = []
for color in rgb:
if color >= 0.5:
newArrayRowz.append(255)
else:
newArrayRowz.append(0)
newRow.append(newArrayRowz)
newImgOnly01.append(newRow)
return newImgOnly01
# convertImgto01OrginalFunction--
# [255,255,255] --> 0/1
# [0,0,0] --> 0/1
# [255,250,249] --> 0/1
def cropTopBottomFrom01Img(newImgOnly01):
# FIND ROWS THAT NEED TO BE DELETED FROM 0 AND 1 IMAGE
deleteRows = []
rowNum = 0
for row in newImgOnly01:
ct = 0
#print(row)
for rgb in row:
#print(rgb)
if not rgb == [0,0,0]:
break
else:
ct+=1
#print(ct==len(row))
if (ct==len(row)):
deleteRows.append(rowNum)
rowNum+=1
# CREATE NEW IMAGE WITH CROPPED 0 AND 1 IMAGES
rowCt = 0
croppedTopBottomImgOnly01 = []
for row in newImgOnly01:
if rowCt not in deleteRows:
croppedTopBottomImgOnly01.append(row)
#print(rowCt)
rowCt+=1
return croppedTopBottomImgOnly01
# cropTopBottomFrom01Img -- Same as before crop top and bottom but works with the 0 and 1 image
# Cuts all top and bottom
def percentAreafromImg(img):
if len(img) == 0:
return 0
ctYes = 0
for row in img:
for value in row:
if value != [0,0,0]:
ctYes+=1
return round(ctYes/(len(croppedTopBottomImgOnly01)*len(croppedTopBottomImgOnly01[0]))*100,4)
# percentAreafromImg -- Calculates the percent area that is taken by the image
# pixelsAreBlack / totalNumPixels * 100 --> Percent area taken
def findOutlierCutoffIQR(datasetInput):
dataset = sorted(datasetInput)
q1, q3= np.percentile(dataset,[25,75])
iqr = q3 - q1
return q3 +(1.5 * iqr)
# findOutlierCutoffIQR -- finds the 75th percentile position of data
# this is where it will cut off the outliers (for percent area)
def displayImg(arrayofImgs):
#plt.figure()
#f, axarr = plt.subplots(1,len(display))
#for i in range(len(display)):
#axarr[i].imshow(display[i])
print("Display not working")
templst = []
finalListofDataAreataken = []
strokeWidthArray = []
for i in range(len(allbbChar)):
areaAllForChar = []
pictureForChar = []
heightChar = []
widthChar = []
for singleChar in allbbChar[i]:
#Crop the character out of the total image
cropPoints = convertBoundBoxtodiagonalRectangual(singleChar)
im = Image.open(imagePath).convert("RGBA")
im_crop = im.crop(cropPoints)
#Converts the image into a cv2 compatiable format
opencvImage = cv2.cvtColor(np.array(im_crop), cv2.COLOR_RGB2BGR)
img_reverted= cv2.bitwise_not(opencvImage)
new_img = img_reverted / 255.0
#Calculated the different values
heightChar.append(len(new_img)) #This is without cutting off the top and bottom
widthChar.append(len(new_img[0])) # Vaies due to different character M - big + I - small
#croppedTopBottomImg = cutTopandBottomBlackRowsFunction(new_img)
newImgOnly01 = convertImgto01OrginalFunction(new_img)
croppedTopBottomImgOnly01 = cropTopBottomFrom01Img(newImgOnly01)
#display = [new_img,croppedTopBottomImg, newImgOnly01, croppedTopBottomImgOnly01]
#displayImg(display)
percentAreaConvert = percentAreafromImg(croppedTopBottomImgOnly01)
areaAllForChar.append(percentAreaConvert)
pictureForChar.append(croppedTopBottomImgOnly01)
#totalWHAllChar.append([heightChar, widthChar])
try:
finalListofDataAreataken.append([areaAllForChar, statistics.mode(heightChar), statistics.mode(widthChar)])
except:
finalListofDataAreataken.append([areaAllForChar, findModeLongWay(heightChar), findModeLongWay(widthChar)])
strokeWidthArray.append(pictureForChar)
#print(templst)
dfAllDataForAllChars = []
for i in range(len(dfList)):
charLstbefore = [dfList[i][0], dfList[i][1]]
charLstbefore.append(finalListofDataAreataken[i][1])
charLstbefore.append(finalListofDataAreataken[i][2])
#print(charLstbefore)
if not len(finalListofDataAreataken[i][0]) == 0:
charLstbefore.append(round(statistics.median(finalListofDataAreataken[i][0]), 4))
charLstbefore.append(round(statistics.mean(finalListofDataAreataken[i][0]), 4))
try:
charLstbefore.append(round(statistics.mode(finalListofDataAreataken[i][0]), 4))
except:
charLstbefore.append(round(statistics.median(finalListofDataAreataken[i][0]), 4))
charLstbefore.append(round(findOutlierCutoffIQR(finalListofDataAreataken[i][0]), 4))
charLstbefore.append(round(len(detect_Maximum_outlier(finalListofDataAreataken[i][0])), 4))
charLstbefore.append(round(len(findMaxOutliersIQR(finalListofDataAreataken[i][0])), 4))
else:
charLstbefore.extend([0, 0, 0, 0, 0, 0])
dfAllDataForAllChars.append(charLstbefore)
colName = ['Char', 'NumberOfChars', 'ModeHeight', 'ModeWidth', 'MedianArea', 'MeanArea', 'ModeArea',
'MaxOutlierNum', 'NumOutlierZScore', 'NumOutlierIQR']
dfwithALLdata=pd.DataFrame(dfAllDataForAllChars, columns=colName)
FINALALLINFOLIST = dfAllDataForAllChars
#print(df)
#print("Height")
#print("Mode " + str(statistics.mode(totalWHAllChar[0][0])))
#print("Mean " + str(statistics.mean(totalWHAllChar[0][0])))
#print("Median " + str(statistics.median(totalWHAllChar[0][0])))
#print("Width")
#print("Mode " + str(statistics.mode(totalWHAllChar[0][1])))
#print("Mean " + str(statistics.mean(totalWHAllChar[0][1])))
#print("Median " + str(statistics.median(totalWHAllChar[0][1])))
#print("Height of the picture --> " + str(len(new_img)))
#print("Width of the picture --> " + str(len(new_img[0])))
# Calculates the mode of the Height and Width of each char
#totalWHAllChar = []
#for numbforChar in range(len(allbbChar)):
# heightChar = []
# widthChar = []
# for singleChar in allbbChar[numbforChar]:
# cropPoints = convertBoundBoxtodiagonalRectangual(singleChar)
# im = Image.open(imagePath).convert("RGBA")
# im_crop = im.crop(cropPoints)
# opencvImage = cv2.cvtColor(np.array(im_crop), cv2.COLOR_RGB2BGR)
# img_reverted= cv2.bitwise_not(opencvImage)
# new_img = img_reverted / 255.0
# heightChar.append(len(new_img))
# widthChar.append(len(new_img[0]))
# #totalWHAllChar.append([heightChar, widthChar])
# try:
# totalWHAllChar.append([statistics.mode(heightChar), statistics.mode(widthChar)])
# except:
# totalWHAllChar.append([findModeLongWay(heightChar), findModeLongWay(widthChar)])
#f, axarr = plt.subplots(1,4)
#axarr[0].imshow(new_img)
#axarr[1].imshow(croppedTopBottomImg)
#axarr[2].imshow(newImgOnly01)
#axarr[3].imshow(croppedTopBottomImgOnly01)
# Prints info -- Basic
if printingToDisplay: print("There is " + str(len(strokeWidthArray)) + " symbols in the array.\nIts a,b,c,d...x,y,z, "+
"A,B,C...X,Y,Z.\nIn each Position is the RGB for that image")
if printingToDisplay: print("Example")
if printingToDisplay: print(strokeWidthArray[0][0][:2])
if printingToDisplay:
for i in dfAllDataForAllChars:
if i[1] < 10:
print("Char "+ i[0] + " has only " + colored(str(i[1]), 'red', attrs=['bold']))
# findPosition -- doesn't do anything to help but just helps find positions
# Helpful for debugging --
def findPosition(value):
rowNumb = 0
for i in dfAllDataForAllChars:
if value == i[0]:
return (rowNumb)
rowNumb+=1
return 0
# These are a list of quartiles where to find the average stroke width
positions = [["b","0-25"],
["c","25-75"],
["d","0-25"],
["f","75-100"],
["h","0-25"],
["p","75-100"],
["q","75-100"],
["t","75-100"],
["F","75-100"],
["L","0-25"],
["T","75-100"],
["Y","75-100"]]
newvalue = []
for i in positions:
x = i
x.append(findPosition(i[0]))
newvalue.append(x)
# stokewidthofChar -- basically find the stroke width of the char
def strokewidthofChar(lstValue, quartile):
#print(0) #0th percentile
#print(int(heightPic/4)+1) #25 percentile
#print(int((heightPic/4)*2)+1) #50 percentile
#print(int((heightPic/4)*3)+1) #75 percentile
#print(heightPic)#100 percentile
lstStokeWidth = []
for i in lstValue:
running = i
heightPic = len(running)
rowNum = 1
if quartile == "0-25":
start = 0
end = int(heightPic/4)+1
elif quartile == "25-75":
start = int(heightPic/4)+1
end = int((heightPic/4)*3)+1
elif quartile == "75-100":
start = int((heightPic/4)*3)+1
end = heightPic
else:
print("invalid input for range")
raise Exception
for row in running:
if rowNum < end and rowNum >= start:
ctYes = 0
for i in row:
if i == [255,255,255]:
ctYes+=1
lstStokeWidth.append(ctYes)
rowNum+=1
return lstStokeWidth
def findq1q3(datasetInput):
dataset = sorted(datasetInput)
q1, q3= np.percentile(dataset,[25,75])
return q1, q3
def reject_outliers(data, m=2):
return data[abs(data - np.mean(data)) < m * np.std(data)]
totalStokeWidth = []
for i in newvalue:
totalStokeWidth.extend(strokewidthofChar(strokeWidthArray[i[2]], i[1]))
q1, q3 = findq1q3(totalStokeWidth)
#print("All Values")
lstofCount = []
for j in list(set(totalStokeWidth)):
lstofCount.append([j, sum(i == j for i in totalStokeWidth)])
#print(str(j) + "\t" + str(sum(i == j for i in totalStokeWidth)))
dfForStrokeWidth=pd.DataFrame(lstofCount, columns=['Detected Width','NumberOfCharsDetected'])
if printingToDisplay: print(dfForStrokeWidth)
if printingToDisplay: print("Stroke width is between " + str(q1) + " - " + str(q3) + ".\nMost likely --> " +
str(round(statistics.mean(totalStokeWidth),4)))
STROKEWIDTHFINAL = round(statistics.mean(totalStokeWidth),4)
FINALDFALLCHARINFOLST = []
for char in FINALALLINFOLIST:
tempArr = char
tempArr.extend([STROKEWIDTHFINAL])
FINALDFALLCHARINFOLST.append(tempArr)
colName = ['Char','NumberOfChars','ModeHeight','ModeWidth','MedianArea','MeanArea','ModeArea', 'MaxOutlierNum', 'NumOutlierZScore', 'NumOutlierIQR', 'AvgStrokeWidth']
dfCharacterData=pd.DataFrame(FINALDFALLCHARINFOLST, columns=colName)
lstMode = []
for i in FINALDFALLCHARINFOLST:
lstMode.append(i[3])
FINALAVGMODEOFCHARS = round(statistics.mean(lstMode),4) #Mode width of the char of ALL
#----------------------------
if printingToDisplay: print(df)
if printingToDisplay: print("Calculated all the infomation about the document now running the 2 differet tests")
#Repeat point
global vowelsNotI
global capitalWeight
global weights
vowelsNotI = ['a','e','o','u']
weights = [[[0, 0, 0, 0],0],
[[0, 0, 0, 1],0.1],
[[0, 0, 1, 0],0.2],
[[0, 0, 1, 1],0.4],
[[0, 1, 0, 0],0.1],
[[0, 1, 0, 1],0.3],
[[0, 1, 1, 0],0.4],
[[0, 1, 1, 1],0.75],
[[1, 0, 0, 0],0.1],
[[1, 0, 0, 1],0.4],
[[1, 0, 1, 0],0.7],
[[1, 0, 1, 1],1],
[[1, 1, 0, 0],0.4],
[[1, 1, 0, 1],0.75],
[[1, 1, 1, 0],1],
[[1, 1, 1, 1],1]]
capitalWeight = 0.6 + 1
# Basically how much extra weight do u want to put to a letter being capital for the first test only
print("CAPITAL WEIGHT IS " + str(capitalWeight-1))
def findMatrix(vert):
matrix = ((vert.vertices[0].x, vert.vertices[0].y),
(vert.vertices[1].x, vert.vertices[1].y),
(vert.vertices[2].x, vert.vertices[2].y),
(vert.vertices[3].x, vert.vertices[3].y))
return matrix
def findInfo(wordInfo):
totalPossibleWeight = 0
ctTrue1 = 0
ctTrue2 = 0
weight = 0
for i in wordInfo:
totalPossibleWeight+=4 if i in vowelsNotI else 3
if i[1] == True:
ctTrue1+=1
if i[2] == True:
ctTrue2+=1
if not i[0].isalpha():
weight+=-1
elif i[1] == True and i[2] == True and i[0].lower() in vowelsNotI:
weight+=5
elif i[1] == True and i[2] == True and not i[0].lower() in vowelsNotI:
weight+=3
elif (i[1] == True or i[2] == True) and i[0].lower() in vowelsNotI:
weight+=2
elif (i[1] == True or i[2] == True) and not i[0].lower() in vowelsNotI:
weight+=1
elif i[1] == False or i[2] == False and i[0].lower() in vowelsNotI:
weight+=-1
elif i[1] == False or i[2] == False and not i[0].lower() in vowelsNotI:
weight+=0
else:
print("ERROR")
#print("Weighted Score " + str((weight/totalPossibleWeight)*100))
#print("Total Percent Bold " + str(((ctTrue1+ctTrue2)/(len(wordInfo)*2))*100))
#print("Test 1 only Percent Bold " + str(((ctTrue1)/(len(wordInfo)))*100))
#print("Test 2 only Percent Bold " + str(((ctTrue2)/(len(wordInfo)))*100))
if (weight/totalPossibleWeight)*100 < 0:
weightscore = 0
else:
weightscore = (weight/totalPossibleWeight)*100
return [weightscore, ((ctTrue1+ctTrue2)/(len(wordInfo)*2))*100, ((ctTrue1)/(len(wordInfo)))*100, ((ctTrue2)/(len(wordInfo)))*100]
def findInfoSingle(i):
if i[1] == True and i[2] == True and i[0].lower() in vowelsNotI:
return True
elif i[1] == True and i[2] == True:
return True
else:
return False
def convertBoundBoxtodiagonalRectangual(polygon):
#print(polygon)
if (abs(polygon.vertices[0].x - polygon.vertices[3].x)<=1 and
abs(polygon.vertices[0].y - polygon.vertices[1].y)<=1 and
abs(polygon.vertices[1].x - polygon.vertices[2].x)<=1 and
abs(polygon.vertices[2].y - polygon.vertices[3].y)<=1):
matrixCrop = (min(polygon.vertices[0].x, polygon.vertices[3].x),
min(polygon.vertices[0].y, polygon.vertices[1].y),
max(polygon.vertices[1].x, polygon.vertices[2].x),
max(polygon.vertices[2].y, polygon.vertices[3].y))
else:
matrixCrop = (min(polygon.vertices[0].x, polygon.vertices[3].x),
min(polygon.vertices[0].y, polygon.vertices[1].y),
max(polygon.vertices[1].x, polygon.vertices[2].x),
max(polygon.vertices[2].y, polygon.vertices[3].y))
print("MaybeErrrorWhenConvertingPolygonToRectangle")
#raise Exception
#matrixCrop = (0,0,0,0)
return matrixCrop
def polygonwidthCal(polygon):
# NOT REALLY USED SO DW ABOUT IT
if (abs(polygon.vertices[0].x - polygon.vertices[3].x)<=1 and
abs(polygon.vertices[0].y - polygon.vertices[1].y)<=1 and
abs(polygon.vertices[1].x - polygon.vertices[2].x)<=1 and
abs(polygon.vertices[2].y - polygon.vertices[3].y)<=1):
end = max(polygon.vertices[1].x, polygon.vertices[2].x)
start = min(polygon.vertices[0].x, polygon.vertices[3].x)
if ((end-start)/TOTALWIDTHOFDOCUMENT)*100 > 80:#-------------------------------------
return True
return False
def polygonwidthCalulateOnly(polygon):
if (abs(polygon.vertices[0].x - polygon.vertices[3].x)<=1 and
abs(polygon.vertices[0].y - polygon.vertices[1].y)<=1 and
abs(polygon.vertices[1].x - polygon.vertices[2].x)<=1 and
abs(polygon.vertices[2].y - polygon.vertices[3].y)<=1):
end = max(polygon.vertices[1].x, polygon.vertices[2].x)
start = min(polygon.vertices[0].x, polygon.vertices[3].x)
return end-start
else:
print("MaybeError")
print(polygon.vertices[1].x, polygon.vertices[2].x)
end = max(polygon.vertices[1].x, polygon.vertices[2].x)
start = min(polygon.vertices[0].x, polygon.vertices[3].x)
return end-start
def calculateWeightForWord(newr):
if len(newr) == 0:
return ["", 0, 0, 0]
returnLst = []
totalSum = 0
wordtextrunningsmall = ""
weight = 0
for symbol in newr:
if symbol[0].isalpha():
if symbol[5] == 1:
currentValues = symbol[1:5]
for comb in weights:
if comb[0] == currentValues:
weight += (comb[1] * capitalWeight)
#print(comb, end= ' ')
#print(comb[1] * capitalWeight)
else:
currentValues = symbol[1:5]
for comb in weights:
if comb[0] == currentValues:
weight += comb[1]
#print(comb)
else:
weight = -1
totalSum+=symbol[1]+symbol[2]+symbol[3]+symbol[4]
wordtextrunningsmall+=symbol[0]
if not wordtextrunningsmall in stop_words:
returnLst.extend([wordtextrunningsmall, totalSum , weight, len(newr)])
else:
returnLst.extend([wordtextrunningsmall, 0, 0, len(newr)])
#print(wordtextrunningsmall + "--> " + str((totalSum/(len(newr)*4))*100))
#print((weight/len(newr)*100))
return returnLst
def countofEach2Lst(lst):
counterDict = Counter(lst)
dictList = []
for key, value in counterDict.items():
temp = [key,value]
dictList.append(temp)
return dictList
def createIMG(lstofthresholds):
if len(lstofthresholds) != 8:
raise Exception("Make sure thresholds are correct")
THRESHOLDSYMBOLMEANTESTWORD = lstofthresholds[0]
# Splits words into symbols and run tests for each symbol using the findInfo() and their weights.
# INSIDE THE FIND INFO FUNCTION FOR THE WEIGHTS
# If the average of all those weights are greater than this number then it is counted
THRESHOLDPARAGROUPSYMWORD = lstofthresholds[1]
# Uses same method as the avg of symbols but then add another layer of averge of words
THRESHOLDFORWORD = lstofthresholds[2]
# threshold for the weights of the entire word summary (out of 100)
# VAR = "weights" FOR ALL THE WEIGHTS 0 AND 1 are True and False for each out of the 4 tests
# 4 tests are mean, median, mode, and outlier
THRESHOLDFORPARA = lstofthresholds[3]
# Threshold for each word in the paragraph indiviually. Para can have different thresholds as a single word
# Also counts in the threshold of "TOTALSUMFINALPARATHRESHOLD"
CUTOFWORDSTHATARE3ORUNDER = lstofthresholds[4]
# simple cut off words that are under 3 letters.
# watch out for arconmys and for words that are incorectly detected EX: = "&"
MAXIMUMLENGTHOFWORDSPARA = lstofthresholds[5]
# the maximum number of words that should be in a paragraph for it to be even counted as a possiblity for bold
TOTALSUMFINALPARATHRESHOLD = lstofthresholds[6]
# threshold for average of the total weights for each word in the paragraph (out of 100)
# same as word (just average)
THRESHOLDFORANYTHINGTHATISNOTALETTER = lstofthresholds[7]
# There are 52 detected possible letters in the english dictionary. If it is a punctionaltion or special character
# it defaults to this number for all of the 4 tests (Mean,median,mode,outlier). EX: "." or "?"\
bigWordBoundBoxs = []
for page in document.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
for word in paragraph.words:
runningWord = ""
uppercaseLetterCt = 0
totalSymbolsLeterCt = 0
for symbol in word.symbols:
if symbol.text.isupper():
uppercaseLetterCt+=1
totalSymbolsLeterCt+=1
runningWord+=symbol.text
if uppercaseLetterCt == totalSymbolsLeterCt:
bigWordBoundBoxs.append(findArea(word.bounding_box))
try:
thresholdAreaCapitailWord = min(findMaxOutliersIQR(bigWordBoundBoxs))
except ValueError:
thresholdAreaCapitailWord = max(bigWordBoundBoxs)
punctionLst = []
for char in string.punctuation:
punctionLst.append(char)
boundingBoxForLargeCapital = []
for page in document.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
for word in paragraph.words:
runningWord = ""
uppercaseLetterCt = 0
totalSymbolsLeterCt = 0
for symbol in word.symbols:
if symbol.text.isupper():
uppercaseLetterCt+=1
if not symbol.text in punctionLst:
#print(symbol.text)
totalSymbolsLeterCt+=1
runningWord+=symbol.text
if abs(uppercaseLetterCt - totalSymbolsLeterCt) < 1 and findArea(word.bounding_box)/thresholdAreaCapitailWord > 0.5:
#print(uppercaseLetterCt, totalSymbolsLeterCt)
#print(findArea(word.bounding_box) > thresholdAreaCapitailWord)
#print(findArea(word.bounding_box))
#print(thresholdAreaCapitailWord)
#print(runningWord + "\t" + str(findArea(word.bounding_box)/thresholdAreaCapitailWord))
#print("")
#print(runningWord)
#print(findArea(word.bounding_box))
boundingBoxForLargeCapital.append([word.bounding_box, round((findArea(word.bounding_box)/thresholdAreaCapitailWord )* 100,2), runningWord])
boxesForCharsGoodMean = []
boxesForCharsbadMean = []
boxesForCharsGoodOutlier = []
boxesForCharsbadOutlier = []
avgSymbolsTest1 = []
for page in document.pages:
pg = []
for block in page.blocks:
blk = []
for paragraph in block.paragraphs:
para = []
for word in paragraph.words:
#numSymbols = 0
wordText = ""
wordInfo = []
for symbol in word.symbols:
symbolInfo = []
wordText += symbol.text
cropPoints = convertBoundBoxtodiagonalRectangual(symbol.bounding_box)
if cropPoints[0] == cropPoints[2]:
newcropPoints = (cropPoints[0], cropPoints[1], cropPoints[2] + 1, cropPoints[3])
cropPoints = newcropPoints
im = Image.open(imagePath).convert("RGBA")
im_crop = im.crop(cropPoints)
opencvImage = cv2.cvtColor(np.array(im_crop), cv2.COLOR_RGB2BGR)
img_reverted = cv2.bitwise_not(opencvImage)
new_img = img_reverted / 255.0
# croppedTopBottomImg = cutTopandBottomBlackRowsFunction(new_img)
newImgOnly01 = convertImgto01OrginalFunction(new_img)
croppedTopBottomImgOnly01 = cropTopBottomFrom01Img(newImgOnly01)
# display = [new_img,croppedTopBottomImg, newImgOnly01, croppedTopBottomImgOnly01]
# displayImg(display)
percentAreaConverd = percentAreafromImg(croppedTopBottomImgOnly01)
boxUpload = False
currentSymbolMean = False
currentSymbolOutlier = False
for charGroup in dfAllDataForAllChars:
if charGroup[0] == symbol.text.strip().lower():
boxUpload = True
# ----------------------------------------------------
boxesForCharsGoodMean.append(symbol.bounding_box) if percentAreaConverd >= charGroup[
5] else boxesForCharsbadMean.append(symbol.bounding_box)
currentSymbolMean = True if percentAreaConverd >= charGroup[5] else False
# ----------------------------------------------------
boxesForCharsGoodOutlier.append(symbol.bounding_box) if percentAreaConverd >= charGroup[
7] else boxesForCharsbadOutlier.append(symbol.bounding_box)
currentSymbolOutlier = True if percentAreaConverd >= charGroup[7] else False
if not boxUpload:
# print("Running Extra -->" + symbol.text)
# ----------------------------------------------------
boxesForCharsGoodMean.append(
symbol.bounding_box) if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER else boxesForCharsbadMean.append(
symbol.bounding_box)
currentSymbolMean = True if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER else False
# ----------------------------------------------------
boxesForCharsGoodOutlier.append(
symbol.bounding_box) if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER else boxesForCharsbadOutlier.append(
symbol.bounding_box)
currentSymbolOutlier = True if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER else False
symbolInfo.extend([symbol.text, currentSymbolMean, currentSymbolOutlier, symbol.bounding_box])
wordInfo.append(symbolInfo)
wordInfo.append(wordText)
wordInfo.append(word.bounding_box)
para.append(wordInfo)
# para.append()
blk.append(para)
blk.append(paragraph.bounding_box)
pg.append(blk)
pg.append(block.bounding_box)
avgSymbolsTest1.append(pg)
print("Finished")
"""
**MARKDDOWN**
|First Test|Second Test|Is Vowel| Weight |
|--|--|--|--|
|True|True|True|5|
|True|True|False|3|
|True|False|True|2|
|True|False|False|1|
|False|True|True|2|
|False|True|False|1|
|False|False|True|-1|
|False|False|False|0|
"""
avgSymbolsTest1 = avgSymbolsTest1[0]
boundingBoxAllTest1 = []
for paraGP in range(0, len(avgSymbolsTest1), 2):
#print("BLOCK " + str(paraGP/2) + "\t\t" + str(findMatrix(avgSymbolsTest1[paraGP+1])))
paraGroupTest1=avgSymbolsTest1[paraGP]
#print(str(len(paraGroupTest1)/2) + " Paragraphs")
for i in range(0, len(paraGroupTest1), 2):
#print("\t" + str(i/2) + "\tBounding Box Para\t" + str(findMatrix(paraGroupTest1[i+1])))
wordSingleRunTest1 = paraGroupTest1[i]
#print("\t\t" + str(len(wordSingleRunTest1)) + "\t Words")
stringPrint = ""
totalScoreForPara = []
for symbol in wordSingleRunTest1:
wordArray = symbol[:-2]
removedBDWordArray = []
for symbolsOnly in wordArray:
removedBDWordArray.append(symbolsOnly[:-1])
#print(wordArray[-1])
#for symbol in wordArray:
#print("Letter " + symbol[0] + " Test1 " + str(symbol[1]) + " Test2 " + str(symbol[2]))
scoreAll = findInfo(removedBDWordArray)
#print("fds" + str(scoreAll))
if statistics.mean(scoreAll) > THRESHOLDSYMBOLMEANTESTWORD:
boundingBoxAllTest1.append([symbol[-1],round(statistics.mean(scoreAll),2), symbol[-2]])
#print(symbol[-2] + " "+ str(scoreAll))
totalScoreForPara.append(scoreAll[0])
stringPrint += symbol[-2] + " "
#print(symbol[-1])
if statistics.mean(totalScoreForPara) > THRESHOLDPARAGROUPSYMWORD:
boundingBoxAllTest1.append([paraGroupTest1[i+1], round(statistics.mean(totalScoreForPara),4), "N/A"])
#print("Yes")
#else:
#Uncomment if you want it to also highlight small words that are bolded
#for symbol in wordSingleRunTest1:
#wordArray = symbol[:-1]
#for symbol in wordArray:
#print(symbol)
#if findInfoSingle(symbol) and symbol[0].isalpha():
#boundingBoxAllTest1.append(symbol[-1])
#print("\t\t" + stringPrint)
#print("-----------------------------------------------------------")
#print("===========================================================")
boundingBoxWordSimpleSymbolTest = []
for wordBDScore in boundingBoxAllTest1:
#print(wordBDScore[0])
boundingBoxWordSimpleSymbolTest.append([wordBDScore[0], wordBDScore[1], wordBDScore[2]])
joinedLst = []
for j in boundingBoxAllTest1: joinedLst.append(j[0])
for i in boundingBoxForLargeCapital: joinedLst.append(i[0])
pointsforBD = []
for i in joinedLst: pointsforBD.append(findMatrix(i))
ypointsLine = []
for i in pointsforBD: ypointsLine.append(i[0][1])
ypointsLine.sort()
#for x in ypointsLine:
#print(x, end=' ')
TINT_COLOR = (0,0,0)
#colors = [(0,255,0), (0,0,255), (255,0,0)]
TRANSPARENCY = 0.25
OPACITY = int(255 * TRANSPARENCY)
img = Image.open(imagePath)
img = img.convert("RGBA")
overlay = Image.new('RGBA', img.size, TINT_COLOR+(0,))
draw = ImageDraw.Draw(overlay) # Create a context for drawing things on it.
x, y= img.size
TINT_COLOR = (255,0,0)
for para in boundingBoxForLargeCapital:
matrix = findMatrix(para[0])
draw.polygon(matrix, fill=TINT_COLOR+(OPACITY,))
TINT_COLOR = (0,255,0)
for para in boundingBoxAllTest1:
matrix = findMatrix(para[0])
draw.polygon(matrix, fill=TINT_COLOR+(OPACITY,))
for yPos in ypointsLine:
shape = [(0, yPos-5), (x, yPos-5)]
draw.line(shape, fill ="black", width = 1)
img = Image.alpha_composite(img, overlay)
img = img.convert("RGB") # Remove alpha for saving in jpg format.
#img.show()
#--------------------------------------------------------------------------------------------------------------------------------------------------------
oldIMG = img
#os.chdir("/Users/kunal/Documents/VdartResumeProject/VisionAPi/ErosionSaveImg")
img.save(os.path.basename(imagePath)[:-4] + "1.jpg")
boxesForCharsGoodMedian = []
boxesForCharsbadMedian= []
boxesForCharsGoodMean= []
boxesForCharsbadMean= []
boxesForCharsGoodMode= []
boxesForCharsbadMode= []
boxesForCharsGoodOutlier= []
boxesForCharsbadOutlier= []
dfthingtester = []
BlockNum = 1
ParaNum = 1
WordNum = 1
for page in document.pages:
for block in page.blocks:
for paragraph in block.paragraphs:
for word in paragraph.words:
wordTextRunning = ""
for symbol in word.symbols:
wordTextRunning += symbol.text
cropPoints = convertBoundBoxtodiagonalRectangual(symbol.bounding_box)
im = Image.open(imagePath).convert("RGBA")
im_crop = im.crop(cropPoints)
opencvImage = cv2.cvtColor(np.array(im_crop), cv2.COLOR_RGB2BGR)
img_reverted = cv2.bitwise_not(opencvImage)
new_img = img_reverted / 255.0
# croppedTopBottomImg = cutTopandBottomBlackRowsFunction(new_img)
newImgOnly01 = convertImgto01OrginalFunction(new_img)
croppedTopBottomImgOnly01 = cropTopBottomFrom01Img(newImgOnly01)
# display = [new_img,croppedTopBottomImg, newImgOnly01, croppedTopBottomImgOnly01]
# displayImg(display)
percentAreaConverd = percentAreafromImg(croppedTopBottomImgOnly01)
boxUpload = False
medianTF = False
meanTF = False
modeTF = False
outlierTF = False
for charGroup in dfAllDataForAllChars:
if charGroup[0] == symbol.text.strip().lower():
boxUpload = True
# ----------------------------------------------------
if percentAreaConverd >= charGroup[4]:
boxesForCharsGoodMedian.append(symbol.bounding_box)
medianTF = True
else:
boxesForCharsbadMedian.append(symbol.bounding_box)
# ----------------------------------------------------
if percentAreaConverd >= charGroup[5]:
boxesForCharsGoodMean.append(symbol.bounding_box)
meanTF = True
else:
boxesForCharsbadMean.append(symbol.bounding_box)
# ----------------------------------------------------
if percentAreaConverd >= charGroup[6]:
boxesForCharsGoodMode.append(symbol.bounding_box)
modeTF = True
else:
boxesForCharsbadMode.append(symbol.bounding_box)
# ----------------------------------------------------
if percentAreaConverd >= charGroup[7]:
boxesForCharsGoodOutlier.append(symbol.bounding_box)
outlierTF = True
else:
boxesForCharsbadOutlier.append(symbol.bounding_box)
# ----------------------------------------------------
# break
if not boxUpload:
# print("Running Extra -->" + symbol.text)
# ----------------------------------------------------
if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER:
boxesForCharsGoodMedian.append(symbol.bounding_box)
medianTF = True
else:
boxesForCharsbadMedian.append(symbol.bounding_box)
# ----------------------------------------------------
if percentAreaConverd >= THRESHOLDFORANYTHINGTHATISNOTALETTER:
boxesForCharsGoodMean.append(symbol.bounding_box)
meanTF = True