Spaces:
Sleeping
Sleeping
Update pilecaps_adr.py
Browse files- pilecaps_adr.py +46 -165
pilecaps_adr.py
CHANGED
|
@@ -6,39 +6,23 @@ Automatically generated by Colaboratory.
|
|
| 6 |
Original file is located at
|
| 7 |
https://colab.research.google.com/drive/16RHtRae7VU_fqHMAjOUL4ET5slEFo3pf
|
| 8 |
"""
|
| 9 |
-
# pip install pdf-annotate
|
| 10 |
-
# pip install pdf-annotate
|
| 11 |
-
#pip install pdf2image
|
| 12 |
-
#!pip install -q gradio
|
| 13 |
-
#pip install pygsheets
|
| 14 |
-
# !apt-get install poppler-utils
|
| 15 |
import numpy as np
|
| 16 |
import cv2
|
| 17 |
-
#from google.colab.patches import cv2_imshow
|
| 18 |
from matplotlib import pyplot as plt
|
| 19 |
-
#from pdf2image import convert_from_path
|
| 20 |
-
import math
|
| 21 |
from math import sin, cos, radians
|
| 22 |
import pandas as pd
|
| 23 |
-
import
|
| 24 |
-
# import imutils
|
| 25 |
-
# from imutils import contours
|
| 26 |
-
import colorsys
|
| 27 |
-
from PIL import Image , ImageDraw, ImageFont , ImageColor
|
| 28 |
import numpy as np
|
| 29 |
-
#import gradio as gr
|
| 30 |
-
|
| 31 |
-
# from __future__ import print_function
|
| 32 |
from googleapiclient.discovery import build
|
| 33 |
from google.oauth2 import service_account
|
| 34 |
import pygsheets
|
| 35 |
import re
|
| 36 |
-
import pandas
|
| 37 |
import fitz
|
| 38 |
-
import json
|
| 39 |
import db
|
| 40 |
import ast
|
| 41 |
-
|
|
|
|
|
|
|
| 42 |
def detectCircles(imgOriginal ):
|
| 43 |
im=imgOriginal.copy()
|
| 44 |
imgGry1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
|
@@ -46,9 +30,6 @@ def detectCircles(imgOriginal ):
|
|
| 46 |
er1=cv2.erode(imgGry1,kernel, iterations=2)
|
| 47 |
|
| 48 |
er1=cv2.dilate(er1,kernel, iterations=1)
|
| 49 |
-
# gray_blurred = cv2.blur(er1, (3,3 ))
|
| 50 |
-
# Apply Hough transform on the blurred image.
|
| 51 |
-
# min distance between circles, Upper threshold for the internal Canny edge detector.
|
| 52 |
detected_circles = cv2.HoughCircles( er1, cv2.HOUGH_GRADIENT, 1, 50, param1= 550,
|
| 53 |
param2 =21, minRadius = 20, maxRadius = 50) #18 param2
|
| 54 |
|
|
@@ -83,7 +64,7 @@ def detectSmallCircles(img ):
|
|
| 83 |
cv2.circle(im, (x, y), r+3, (255, 255, 255), -1)
|
| 84 |
# cv2_imshow(im)
|
| 85 |
return im
|
| 86 |
-
|
| 87 |
|
| 88 |
def DashedPreprocessing(imgOriginal,imgnoSmall):
|
| 89 |
h,w=imgOriginal.shape[0:2]
|
|
@@ -182,20 +163,12 @@ def ConnectBeamLines(smalldashesOut):
|
|
| 182 |
green1=cv2.bitwise_not(smalldashesOut)
|
| 183 |
green2=smalldashesOut.copy()
|
| 184 |
green2=cv2.cvtColor(green2,cv2.COLOR_GRAY2BGR)
|
| 185 |
-
# imgLines= cv2.HoughLinesP(green1,0.05,np.pi/250,10,minLineLength=25,maxLineGap = 20) #was w-h , gap=150 #50
|
| 186 |
-
# for i in range(len(imgLines)):
|
| 187 |
-
# for x1,y1,x2,y2 in imgLines[i]:
|
| 188 |
-
# cv2.line(green2,(x1,y1),(x2,y2),(0,0,0),2)
|
| 189 |
-
|
| 190 |
imgLines= cv2.HoughLinesP(green1,0.3,np.pi/180,20,minLineLength=25,maxLineGap = 25) #try 180
|
| 191 |
-
|
| 192 |
-
|
| 193 |
for i in range(len(imgLines)):
|
| 194 |
for x1,y1,x2,y2 in imgLines[i]:
|
| 195 |
cv2.line(green2,(x1,y1),(x2,y2),(0,0,0),2)
|
| 196 |
-
# cv2_imshow(green2)
|
| 197 |
return green2
|
| 198 |
-
|
| 199 |
def allpreSteps(imgOriginal):
|
| 200 |
noCircles=detectCircles(imgOriginal)
|
| 201 |
imgnoSmall=detectSmallCircles(noCircles )
|
|
@@ -209,10 +182,9 @@ def allpreSteps(imgOriginal):
|
|
| 209 |
|
| 210 |
def ChangeBrightness(img,k):
|
| 211 |
imgdarker = 255 * (img/255)**k # k>1 darker , k <1 lighter
|
| 212 |
-
# cv2_imshow(imgdarker)
|
| 213 |
imgdarker = imgdarker.astype('uint8')
|
| 214 |
return imgdarker
|
| 215 |
-
|
| 216 |
def preprocessold(img,number):
|
| 217 |
blurG = ChangeBrightness(img,3)
|
| 218 |
imgGry = cv2.cvtColor(blurG, cv2.COLOR_BGR2GRAY)
|
|
@@ -223,8 +195,7 @@ def preprocessold(img,number):
|
|
| 223 |
ret3, thresh = cv2.threshold(er1, 254, 255, cv2.THRESH_BINARY_INV )
|
| 224 |
thresh=cv2.medianBlur(thresh,5)
|
| 225 |
return thresh
|
| 226 |
-
|
| 227 |
-
|
| 228 |
def preprocess(imgOriginal,number,green2,flag,layeredflag,BlackmaskDetected1=0):
|
| 229 |
#first preprocessing ( old method - black img with white shapes)
|
| 230 |
img1=preprocessold(imgOriginal,number)
|
|
@@ -258,13 +229,12 @@ def preprocess(imgOriginal,number,green2,flag,layeredflag,BlackmaskDetected1=0):
|
|
| 258 |
"""# ROI (levels)
|
| 259 |
## Detect regions with specific color and mask them
|
| 260 |
"""
|
| 261 |
-
|
| 262 |
def hexRGB(color):
|
| 263 |
color=color.lstrip('#')
|
| 264 |
-
|
| 265 |
color= tuple(int(color[i:i+2], 16) for i in (0, 2, 4)) #hex to rgb
|
| 266 |
color=np.array(color) #rgb to bgr
|
| 267 |
return color
|
|
|
|
| 268 |
def DetectColor(img,color=0):
|
| 269 |
|
| 270 |
imgCopy=img.copy()
|
|
@@ -292,45 +262,6 @@ def DetectColor(img,color=0):
|
|
| 292 |
cv2.imwrite('det.png',detectedColors)
|
| 293 |
return mask, detectedColors, color
|
| 294 |
|
| 295 |
-
|
| 296 |
-
def detectAllColors(img,finalColorArray):
|
| 297 |
-
for i in range(len(finalColorArray)):
|
| 298 |
-
detectedColors= DetectColor(img,finalColorArray[i])[1]
|
| 299 |
-
if i == 0:
|
| 300 |
-
allcolorsImg=cv2.bitwise_or(detectedColors,detectedColors)
|
| 301 |
-
else:
|
| 302 |
-
allcolorsImg=cv2.bitwise_or(allcolorsImg,detectedColors)
|
| 303 |
-
allcolorsImg= cv2.medianBlur(allcolorsImg,7)
|
| 304 |
-
|
| 305 |
-
return allcolorsImg
|
| 306 |
-
|
| 307 |
-
def colorOrder(img,finalColorArray):
|
| 308 |
-
newimg=img.copy()
|
| 309 |
-
arraycolor=[]
|
| 310 |
-
allcolorsImg= detectAllColors(img,finalColorArray)
|
| 311 |
-
allcolorsImgG= cv2.cvtColor(allcolorsImg, cv2.COLOR_BGR2GRAY)
|
| 312 |
-
|
| 313 |
-
ColoredContour, Coloredhierarchy = cv2.findContours(allcolorsImgG, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
|
| 314 |
-
Coloredhierarchy=Coloredhierarchy[0]
|
| 315 |
-
for cnt in ColoredContour :
|
| 316 |
-
Blackmask = np.zeros(img.shape[:2], dtype="uint8")
|
| 317 |
-
cv2.drawContours(Blackmask,[cnt],0,(255,255,255),20)
|
| 318 |
-
coloredand=cv2.bitwise_and(allcolorsImg,allcolorsImg,mask=Blackmask)
|
| 319 |
-
|
| 320 |
-
for colors in finalColorArray:
|
| 321 |
-
getColor=DetectColor(coloredand,colors)[1]
|
| 322 |
-
|
| 323 |
-
pil_image=Image.fromarray(getColor)
|
| 324 |
-
extrema = pil_image.convert("L").getextrema()
|
| 325 |
-
if extrema != (0, 0): # if image is not black --> has a colored mask within
|
| 326 |
-
arraycolor.append(colors)
|
| 327 |
-
break
|
| 328 |
-
|
| 329 |
-
res = []
|
| 330 |
-
[res.append(x) for x in arraycolor if x not in res]
|
| 331 |
-
|
| 332 |
-
return res
|
| 333 |
-
|
| 334 |
def getinnerColor(BlackmaskDetected,img,detectedColors,finalColorArray,ratioarea,ratioperim,flag,eachcolor):
|
| 335 |
|
| 336 |
countBlackMasks=0
|
|
@@ -441,8 +372,6 @@ def allLevelsofColor(BlackmaskDetected,img,levelonly, invertedmask,color,finalCo
|
|
| 441 |
return firstLevel1, BlackmaskDetected
|
| 442 |
|
| 443 |
def getColoredContour(mask,img,finalColorArray,ratioarea,ratioperim,flag,eachcolor):
|
| 444 |
-
print('uuuuuuuuummmmmmmmmmmmm')
|
| 445 |
-
|
| 446 |
ColoredContour, Coloredhierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
| 447 |
Coloredhierarchy=Coloredhierarchy[0]
|
| 448 |
|
|
@@ -498,8 +427,7 @@ def findContoursFullImage(green2,img,number,finalColorArray,ratioarea,ratioperim
|
|
| 498 |
|
| 499 |
return contourss,color ,mask
|
| 500 |
|
| 501 |
-
|
| 502 |
-
|
| 503 |
def StraightenImage(contour,imgArea):
|
| 504 |
rect = cv2.minAreaRect(contour)
|
| 505 |
|
|
@@ -526,7 +454,7 @@ def StraightenImage(contour,imgArea):
|
|
| 526 |
# warped = cv2.warpPerspective(imgArea, M, (width, height))
|
| 527 |
##############
|
| 528 |
return angleR,width,height
|
| 529 |
-
|
| 530 |
def getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArray,color=[0,0,0]):
|
| 531 |
appended=[]
|
| 532 |
if number==0:
|
|
@@ -556,7 +484,7 @@ def getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArra
|
|
| 556 |
# print('numss')
|
| 557 |
# if flag=='area':
|
| 558 |
# addedMargin=area1+perimeter1*2
|
| 559 |
-
areaa=area1* ratioarea# true value of area of any shape/ area px value of same shape
|
| 560 |
appended.append([areaa,width,height])
|
| 561 |
|
| 562 |
#else:
|
|
@@ -564,8 +492,7 @@ def getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArra
|
|
| 564 |
#appended.append([perimeter,width,height])
|
| 565 |
|
| 566 |
return appended
|
| 567 |
-
|
| 568 |
-
|
| 569 |
def FillDictionary(green2,SimilarAreaDictionary,img,number,ratioarea,ratioperim,flag,finalColorArray,rgbcolor=[0,0,0],color=[0,0,0]):
|
| 570 |
#fills dictionary with key areas and number of occurences
|
| 571 |
areas_Perimeters=sorted(getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArray,color) )
|
|
@@ -644,13 +571,10 @@ def FillDictionary(green2,SimilarAreaDictionary,img,number,ratioarea,ratioperim,
|
|
| 644 |
|
| 645 |
|
| 646 |
return SimilarAreaDictionary, colorsUsed , areas_Perimeters
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
def drawAllContours(img,number,finalColorArray,ratioarea,ratioperim,flag , path,pdfpath):
|
| 652 |
green2=allpreSteps(img)
|
| 653 |
-
doc = fitz.open(
|
| 654 |
page = doc[0]
|
| 655 |
pix=page.get_pixmap()
|
| 656 |
ratio = pix.width / img.shape[1]
|
|
@@ -861,16 +785,11 @@ def drawAllContours(img,number,finalColorArray,ratioarea,ratioperim,flag , path,
|
|
| 861 |
|
| 862 |
alpha = 0.4 # Transparency factor.
|
| 863 |
image_new1 = cv2.addWeighted(imgArea1, alpha, imgtransparent1, 1 - alpha, 0)
|
| 864 |
-
# SimilarAreaDictionary.drop(['Rounded', 'Width','Height','R','G','B'], axis=1, inplace=True)
|
| 865 |
-
|
| 866 |
-
print(SimilarAreaDictionary)
|
| 867 |
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
dbx=db.dropbox_connect()
|
| 873 |
-
md, res =dbx.files_download(path= pdfpath+path)
|
| 874 |
data = res.content
|
| 875 |
doc=fitz.open("pdf", data)
|
| 876 |
# list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
|
|
@@ -885,7 +804,7 @@ def drawAllContours(img,number,finalColorArray,ratioarea,ratioperim,flag , path,
|
|
| 885 |
|
| 886 |
######################################################
|
| 887 |
|
| 888 |
-
def deletemarkups(list1,
|
| 889 |
'''list1 : original markup pdf
|
| 890 |
list2 : deleted markup pdf
|
| 891 |
deletedrows : deleted markups - difference betw both dfs
|
|
@@ -898,9 +817,9 @@ def deletemarkups(list1, pdfpath , path):
|
|
| 898 |
areastodelete = []
|
| 899 |
perimstodelete=[]
|
| 900 |
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
md, res =
|
| 904 |
data = res.content
|
| 905 |
doc=fitz.open("pdf", data)
|
| 906 |
list2=pd.DataFrame(columns=['content', 'id', 'subject'])
|
|
@@ -921,8 +840,6 @@ def deletemarkups(list1, pdfpath , path):
|
|
| 921 |
flag=0
|
| 922 |
return deletedrows
|
| 923 |
|
| 924 |
-
|
| 925 |
-
|
| 926 |
def deletefromlegend(deletedrows,SimilarAreaDictionarycopy,section, areaPermArr=[]):
|
| 927 |
items=[]
|
| 928 |
idx=0
|
|
@@ -931,17 +848,20 @@ def deletefromlegend(deletedrows,SimilarAreaDictionarycopy,section, areaPermArr=
|
|
| 931 |
myDict=eval(SimilarAreaDictionarycopy)
|
| 932 |
SimilarAreaDictionarycopy=pd.DataFrame(myDict)
|
| 933 |
strings=deletedrows['content']
|
| 934 |
-
|
| 935 |
areastodelete = []
|
| 936 |
perimstodelete=[]
|
| 937 |
-
|
|
|
|
| 938 |
for item in strings:
|
| 939 |
items.append(str(item).split('\n \n'))
|
| 940 |
# print('itemsssssss',float(re.findall("\d+\.\d+", str(items[i][0]).split()[0])[0])) #take area and perim mn hna l sec 3.2 and +/- value margin
|
|
|
|
| 941 |
for i in range(len(items)):
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
|
|
|
|
|
|
| 945 |
for i in range(len(areastodelete)):#item in areastodelete:
|
| 946 |
areamin=round(areastodelete[i],1)- 0.3
|
| 947 |
areamax=round(areastodelete[i],1)+ 0.3
|
|
@@ -949,16 +869,17 @@ def deletefromlegend(deletedrows,SimilarAreaDictionarycopy,section, areaPermArr=
|
|
| 949 |
perimmax=round(perimstodelete[i],1)+ 0.3
|
| 950 |
if section.startswith('1.0'):
|
| 951 |
for p in range(len(areaPermArr)):
|
|
|
|
| 952 |
if areastodelete[i] in areaPermArr[p]:
|
|
|
|
| 953 |
area= areaPermArr[p][0]
|
| 954 |
width= areaPermArr[p][1]
|
| 955 |
height= areaPermArr[p][2]
|
| 956 |
-
if section.startswith('1.0'):
|
| 957 |
widthMin= width -10
|
| 958 |
widthMax= width +10
|
| 959 |
heightMin = height-10
|
| 960 |
heightMax=height+10
|
| 961 |
-
print(width, widthMin ,height, heightMin)
|
| 962 |
found=SimilarAreaDictionarycopy.loc[SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Rounded'] >=areamin) & (SimilarAreaDictionarycopy['Rounded']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) ) & ( ((SimilarAreaDictionarycopy['Width']>=widthMin) & (SimilarAreaDictionarycopy['Width']<=widthMax) & (SimilarAreaDictionarycopy['Height']>=heightMin) & (SimilarAreaDictionarycopy['Height']<=heightMax) ) | ((SimilarAreaDictionarycopy['Width']>=heightMin) & (SimilarAreaDictionarycopy['Width']<=heightMax) & (SimilarAreaDictionarycopy['Height']>=widthMin) & (SimilarAreaDictionarycopy['Height']<=widthMax) )) ]]
|
| 963 |
elif section.startswith('3.2'):
|
| 964 |
areamin=round(areastodelete[i],1)- 0.1
|
|
@@ -982,52 +903,11 @@ def deletefromlegend(deletedrows,SimilarAreaDictionarycopy,section, areaPermArr=
|
|
| 982 |
idx=SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Area'] >=areamin) & (SimilarAreaDictionarycopy['Area']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) )]
|
| 983 |
SimilarAreaDictionarycopy.loc[idx,'Total Area'] = SimilarAreaDictionarycopy.loc[idx,'Total Area'] - areastodelete[i]
|
| 984 |
SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] = SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] - perimstodelete[i]
|
| 985 |
-
|
| 986 |
SimilarAreaDictionarycopy.loc[idx,'Occurences'] = int(SimilarAreaDictionarycopy.loc[idx,'Occurences']) - 1
|
| 987 |
-
print(SimilarAreaDictionarycopy)
|
| 988 |
return SimilarAreaDictionarycopy
|
| 989 |
#######################################################
|
| 990 |
-
|
| 991 |
-
def getTitle(path):
|
| 992 |
-
planName= path.split("/")[-1].split('.')
|
| 993 |
-
LegendName='Legend of ' + str(planName[0]) + ' plan'
|
| 994 |
-
return LegendName
|
| 995 |
-
|
| 996 |
-
def retrieveMCCol(gc):
|
| 997 |
-
ws=gc.open_by_key('1A8VtqLFhe2NXPxIjfAilbxF9xV2eSzZ-yZ9GP8_5jSo')
|
| 998 |
-
worksheet = ws.worksheet(0)
|
| 999 |
-
mcT_Names=worksheet.get_col(1)
|
| 1000 |
-
newMcTNames=[]
|
| 1001 |
-
for i in mcT_Names:
|
| 1002 |
-
if i != '':
|
| 1003 |
-
newMcTNames.append(i)
|
| 1004 |
-
return newMcTNames
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
def getdropdownValues(gc,spreadsheet_service,spreadsheetid):
|
| 1008 |
-
dropdownValues=[]
|
| 1009 |
-
ws=gc.open_by_key('1A8VtqLFhe2NXPxIjfAilbxF9xV2eSzZ-yZ9GP8_5jSo') ## spreadsheet containing mc-t names
|
| 1010 |
-
|
| 1011 |
-
worksheet = ws.worksheet(0)
|
| 1012 |
-
response = spreadsheet_service.spreadsheets().get(
|
| 1013 |
-
spreadsheetId=spreadsheetid, fields='*',
|
| 1014 |
-
ranges='A2:A60',includeGridData=True).execute()
|
| 1015 |
-
r=list(response['sheets'][0]['data'][0]['rowData'][0]['values'][0])
|
| 1016 |
-
print(r)
|
| 1017 |
-
if 'dataValidation' in r:
|
| 1018 |
-
print('yes')
|
| 1019 |
-
colvals= response['sheets'][0]['data'][0]['rowData'][0]['values'][0]['dataValidation']
|
| 1020 |
-
colvalsList=list(colvals.items())
|
| 1021 |
-
print(colvalsList[0][1])
|
| 1022 |
-
lengthVals=len(colvalsList[0][1]['values'])
|
| 1023 |
-
for i in range(lengthVals):
|
| 1024 |
-
dictVal=(colvalsList[0][1]['values'][i].values())
|
| 1025 |
-
# val=[*dictVal]
|
| 1026 |
-
|
| 1027 |
-
dropdownValues.append(*dictVal)
|
| 1028 |
-
print(dropdownValues)
|
| 1029 |
-
worksheet.update_col(index=1, values=dropdownValues)
|
| 1030 |
-
return dropdownValues
|
| 1031 |
def authorizeLegend():
|
| 1032 |
SCOPES = [
|
| 1033 |
'https://www.googleapis.com/auth/spreadsheets',
|
|
@@ -1039,7 +919,7 @@ def authorizeLegend():
|
|
| 1039 |
drive_service = build('drive', 'v3', credentials=credentials)
|
| 1040 |
gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
|
| 1041 |
return spreadsheet_service,drive_service,gc
|
| 1042 |
-
|
| 1043 |
def legendGoogleSheets(SimilarAreaDictionary,path ,pdfpath, spreadsheetId=0):
|
| 1044 |
|
| 1045 |
spreadsheet_service,drive_service,gc=authorizeLegend()
|
|
@@ -1086,7 +966,7 @@ def legendGoogleSheets(SimilarAreaDictionary,path ,pdfpath, spreadsheetId=0):
|
|
| 1086 |
worksheet = ws.worksheet(0)
|
| 1087 |
worksheet.title='Legend and data created'
|
| 1088 |
worksheet.clear()
|
| 1089 |
-
|
| 1090 |
ws.create_developer_metadata('path',pdfpath)
|
| 1091 |
splittedpdfpath=re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,/<>?]', pdfpath)
|
| 1092 |
namepathArr=[legendTitle , spreadsheetId,ws.get_developer_metadata('path')[0].value]
|
|
@@ -1336,7 +1216,7 @@ def mapnametoLegend(McTName):
|
|
| 1336 |
spreadsheet_key =str(key) # Please set the Spreadsheet ID.
|
| 1337 |
|
| 1338 |
ws = gc.open_by_key(spreadsheet_key)
|
| 1339 |
-
guessednamesfinal=getguessnames(gc,ws)
|
| 1340 |
sheetnames=[]
|
| 1341 |
unit=''
|
| 1342 |
# ws.add_worksheet("Summary") # Please set the new sheet name.
|
|
@@ -1351,6 +1231,8 @@ def mapnametoLegend(McTName):
|
|
| 1351 |
worksheetw = ws.worksheet(0) #legend
|
| 1352 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 1353 |
summaryId= ws[1].id
|
|
|
|
|
|
|
| 1354 |
worksheetS.clear()
|
| 1355 |
countnames=0
|
| 1356 |
row0=['MC_T Name','Qty','Unit']
|
|
@@ -1363,7 +1245,7 @@ def mapnametoLegend(McTName):
|
|
| 1363 |
print(McTName[i][0])
|
| 1364 |
|
| 1365 |
# firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
|
| 1366 |
-
|
| 1367 |
if McTName[i][2].startswith('Area'):
|
| 1368 |
if section.startswith('1.0'):
|
| 1369 |
rowvalue=5# column 5
|
|
@@ -1396,9 +1278,7 @@ def mapnametoLegend(McTName):
|
|
| 1396 |
print('mcct',McTName[i][1])
|
| 1397 |
if isinstance(McTName[i][1], list):
|
| 1398 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 1399 |
-
|
| 1400 |
-
# guessednames=guessednames[3:]
|
| 1401 |
-
print('gg',guessednames)
|
| 1402 |
for m in McTName[i][1]:
|
| 1403 |
if m:
|
| 1404 |
if m.startswith('text1'):
|
|
@@ -1513,9 +1393,10 @@ def mapnametoLegend(McTName):
|
|
| 1513 |
]
|
| 1514 |
}
|
| 1515 |
spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_key, body=body2).execute()
|
| 1516 |
-
return summaryId
|
| 1517 |
|
| 1518 |
# print(x,xarea)
|
|
|
|
| 1519 |
def getguessnames(gc,ws):
|
| 1520 |
guessednamesfinal=[]
|
| 1521 |
worksheetw = ws.worksheet(0)
|
|
|
|
| 6 |
Original file is located at
|
| 7 |
https://colab.research.google.com/drive/16RHtRae7VU_fqHMAjOUL4ET5slEFo3pf
|
| 8 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
import numpy as np
|
| 10 |
import cv2
|
|
|
|
| 11 |
from matplotlib import pyplot as plt
|
|
|
|
|
|
|
| 12 |
from math import sin, cos, radians
|
| 13 |
import pandas as pd
|
| 14 |
+
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 16 |
from googleapiclient.discovery import build
|
| 17 |
from google.oauth2 import service_account
|
| 18 |
import pygsheets
|
| 19 |
import re
|
|
|
|
| 20 |
import fitz
|
|
|
|
| 21 |
import db
|
| 22 |
import ast
|
| 23 |
+
import Dropbox_TSA_API
|
| 24 |
+
import tsadropboxretrieval
|
| 25 |
+
#Prepare preprocessing
|
| 26 |
def detectCircles(imgOriginal ):
|
| 27 |
im=imgOriginal.copy()
|
| 28 |
imgGry1 = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
|
|
|
|
| 30 |
er1=cv2.erode(imgGry1,kernel, iterations=2)
|
| 31 |
|
| 32 |
er1=cv2.dilate(er1,kernel, iterations=1)
|
|
|
|
|
|
|
|
|
|
| 33 |
detected_circles = cv2.HoughCircles( er1, cv2.HOUGH_GRADIENT, 1, 50, param1= 550,
|
| 34 |
param2 =21, minRadius = 20, maxRadius = 50) #18 param2
|
| 35 |
|
|
|
|
| 64 |
cv2.circle(im, (x, y), r+3, (255, 255, 255), -1)
|
| 65 |
# cv2_imshow(im)
|
| 66 |
return im
|
| 67 |
+
|
| 68 |
|
| 69 |
def DashedPreprocessing(imgOriginal,imgnoSmall):
|
| 70 |
h,w=imgOriginal.shape[0:2]
|
|
|
|
| 163 |
green1=cv2.bitwise_not(smalldashesOut)
|
| 164 |
green2=smalldashesOut.copy()
|
| 165 |
green2=cv2.cvtColor(green2,cv2.COLOR_GRAY2BGR)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
imgLines= cv2.HoughLinesP(green1,0.3,np.pi/180,20,minLineLength=25,maxLineGap = 25) #try 180
|
|
|
|
|
|
|
| 167 |
for i in range(len(imgLines)):
|
| 168 |
for x1,y1,x2,y2 in imgLines[i]:
|
| 169 |
cv2.line(green2,(x1,y1),(x2,y2),(0,0,0),2)
|
|
|
|
| 170 |
return green2
|
| 171 |
+
#create img with solid lines
|
| 172 |
def allpreSteps(imgOriginal):
|
| 173 |
noCircles=detectCircles(imgOriginal)
|
| 174 |
imgnoSmall=detectSmallCircles(noCircles )
|
|
|
|
| 182 |
|
| 183 |
def ChangeBrightness(img,k):
|
| 184 |
imgdarker = 255 * (img/255)**k # k>1 darker , k <1 lighter
|
|
|
|
| 185 |
imgdarker = imgdarker.astype('uint8')
|
| 186 |
return imgdarker
|
| 187 |
+
#OLD method (White shapes)
|
| 188 |
def preprocessold(img,number):
|
| 189 |
blurG = ChangeBrightness(img,3)
|
| 190 |
imgGry = cv2.cvtColor(blurG, cv2.COLOR_BGR2GRAY)
|
|
|
|
| 195 |
ret3, thresh = cv2.threshold(er1, 254, 255, cv2.THRESH_BINARY_INV )
|
| 196 |
thresh=cv2.medianBlur(thresh,5)
|
| 197 |
return thresh
|
| 198 |
+
#anding of old method output with solid lines img
|
|
|
|
| 199 |
def preprocess(imgOriginal,number,green2,flag,layeredflag,BlackmaskDetected1=0):
|
| 200 |
#first preprocessing ( old method - black img with white shapes)
|
| 201 |
img1=preprocessold(imgOriginal,number)
|
|
|
|
| 229 |
"""# ROI (levels)
|
| 230 |
## Detect regions with specific color and mask them
|
| 231 |
"""
|
|
|
|
| 232 |
def hexRGB(color):
|
| 233 |
color=color.lstrip('#')
|
|
|
|
| 234 |
color= tuple(int(color[i:i+2], 16) for i in (0, 2, 4)) #hex to rgb
|
| 235 |
color=np.array(color) #rgb to bgr
|
| 236 |
return color
|
| 237 |
+
|
| 238 |
def DetectColor(img,color=0):
|
| 239 |
|
| 240 |
imgCopy=img.copy()
|
|
|
|
| 262 |
cv2.imwrite('det.png',detectedColors)
|
| 263 |
return mask, detectedColors, color
|
| 264 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 265 |
def getinnerColor(BlackmaskDetected,img,detectedColors,finalColorArray,ratioarea,ratioperim,flag,eachcolor):
|
| 266 |
|
| 267 |
countBlackMasks=0
|
|
|
|
| 372 |
return firstLevel1, BlackmaskDetected
|
| 373 |
|
| 374 |
def getColoredContour(mask,img,finalColorArray,ratioarea,ratioperim,flag,eachcolor):
|
|
|
|
|
|
|
| 375 |
ColoredContour, Coloredhierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
| 376 |
Coloredhierarchy=Coloredhierarchy[0]
|
| 377 |
|
|
|
|
| 427 |
|
| 428 |
return contourss,color ,mask
|
| 429 |
|
| 430 |
+
#Straighten tilted shapes
|
|
|
|
| 431 |
def StraightenImage(contour,imgArea):
|
| 432 |
rect = cv2.minAreaRect(contour)
|
| 433 |
|
|
|
|
| 454 |
# warped = cv2.warpPerspective(imgArea, M, (width, height))
|
| 455 |
##############
|
| 456 |
return angleR,width,height
|
| 457 |
+
#get all areas and perimeter present
|
| 458 |
def getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArray,color=[0,0,0]):
|
| 459 |
appended=[]
|
| 460 |
if number==0:
|
|
|
|
| 484 |
# print('numss')
|
| 485 |
# if flag=='area':
|
| 486 |
# addedMargin=area1+perimeter1*2
|
| 487 |
+
areaa=round(area1* ratioarea,3)# true value of area of any shape/ area px value of same shape
|
| 488 |
appended.append([areaa,width,height])
|
| 489 |
|
| 490 |
#else:
|
|
|
|
| 492 |
#appended.append([perimeter,width,height])
|
| 493 |
|
| 494 |
return appended
|
| 495 |
+
#fill dictionary with areas and perimeters and occurences
|
|
|
|
| 496 |
def FillDictionary(green2,SimilarAreaDictionary,img,number,ratioarea,ratioperim,flag,finalColorArray,rgbcolor=[0,0,0],color=[0,0,0]):
|
| 497 |
#fills dictionary with key areas and number of occurences
|
| 498 |
areas_Perimeters=sorted(getAreasPerimeter(green2,img,number,ratioarea,ratioperim,flag,finalColorArray,color) )
|
|
|
|
| 571 |
|
| 572 |
|
| 573 |
return SimilarAreaDictionary, colorsUsed , areas_Perimeters
|
| 574 |
+
#detect and draw and measure
|
| 575 |
+
def drawAllContours(dataDoc,img,number,finalColorArray,ratioarea,ratioperim,flag , path,pdfpath):
|
|
|
|
|
|
|
|
|
|
| 576 |
green2=allpreSteps(img)
|
| 577 |
+
doc = fitz.open("pdf",dataDoc)
|
| 578 |
page = doc[0]
|
| 579 |
pix=page.get_pixmap()
|
| 580 |
ratio = pix.width / img.shape[1]
|
|
|
|
| 785 |
|
| 786 |
alpha = 0.4 # Transparency factor.
|
| 787 |
image_new1 = cv2.addWeighted(imgArea1, alpha, imgtransparent1, 1 - alpha, 0)
|
|
|
|
|
|
|
|
|
|
| 788 |
|
| 789 |
+
dbPath='/TSA Team Folder/ADR Test'+pdfpath+'Measured Plan/'
|
| 790 |
+
pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=path) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
|
| 791 |
+
dbxTeam=tsadropboxretrieval.ADR_Access_DropboxTeam('user')
|
| 792 |
+
md, res =dbxTeam.files_download(path= dbPath+path)
|
|
|
|
|
|
|
| 793 |
data = res.content
|
| 794 |
doc=fitz.open("pdf", data)
|
| 795 |
# list1=pd.DataFrame(columns=['content', 'creationDate', 'id', 'modDate', 'name', 'subject', 'title'])
|
|
|
|
| 804 |
|
| 805 |
######################################################
|
| 806 |
|
| 807 |
+
def deletemarkups(list1, dbPath , path):
|
| 808 |
'''list1 : original markup pdf
|
| 809 |
list2 : deleted markup pdf
|
| 810 |
deletedrows : deleted markups - difference betw both dfs
|
|
|
|
| 817 |
areastodelete = []
|
| 818 |
perimstodelete=[]
|
| 819 |
|
| 820 |
+
dbxTeam=tsadropboxretrieval.ADR_Access_DropboxTeam('user')
|
| 821 |
+
print('pathhhhh',dbPath+path)
|
| 822 |
+
md, res =dbxTeam.files_download(path= dbPath+path)
|
| 823 |
data = res.content
|
| 824 |
doc=fitz.open("pdf", data)
|
| 825 |
list2=pd.DataFrame(columns=['content', 'id', 'subject'])
|
|
|
|
| 840 |
flag=0
|
| 841 |
return deletedrows
|
| 842 |
|
|
|
|
|
|
|
| 843 |
def deletefromlegend(deletedrows,SimilarAreaDictionarycopy,section, areaPermArr=[]):
|
| 844 |
items=[]
|
| 845 |
idx=0
|
|
|
|
| 848 |
myDict=eval(SimilarAreaDictionarycopy)
|
| 849 |
SimilarAreaDictionarycopy=pd.DataFrame(myDict)
|
| 850 |
strings=deletedrows['content']
|
|
|
|
| 851 |
areastodelete = []
|
| 852 |
perimstodelete=[]
|
| 853 |
+
lengthstodelete=[]
|
| 854 |
+
print('areaPermArr',areaPermArr)
|
| 855 |
for item in strings:
|
| 856 |
items.append(str(item).split('\n \n'))
|
| 857 |
# print('itemsssssss',float(re.findall("\d+\.\d+", str(items[i][0]).split()[0])[0])) #take area and perim mn hna l sec 3.2 and +/- value margin
|
| 858 |
+
|
| 859 |
for i in range(len(items)):
|
| 860 |
+
print('ITEMSS',str(items[i]).split())
|
| 861 |
+
areastodelete.append(float(re.findall("\d+\.\d+", str(items[i][0]).split()[1])[0]))
|
| 862 |
+
perimstodelete.append(float(re.findall("\d+\.\d+", str(items[i][1]).split()[1])[0]) )
|
| 863 |
+
lengthstodelete.append(float(re.findall("\d+\.\d+", str(items[i][2]).split()[1])[0]) )
|
| 864 |
+
|
| 865 |
for i in range(len(areastodelete)):#item in areastodelete:
|
| 866 |
areamin=round(areastodelete[i],1)- 0.3
|
| 867 |
areamax=round(areastodelete[i],1)+ 0.3
|
|
|
|
| 869 |
perimmax=round(perimstodelete[i],1)+ 0.3
|
| 870 |
if section.startswith('1.0'):
|
| 871 |
for p in range(len(areaPermArr)):
|
| 872 |
+
|
| 873 |
if areastodelete[i] in areaPermArr[p]:
|
| 874 |
+
print('AAA',areaPermArr[p])
|
| 875 |
area= areaPermArr[p][0]
|
| 876 |
width= areaPermArr[p][1]
|
| 877 |
height= areaPermArr[p][2]
|
| 878 |
+
# if section.startswith('1.0'):
|
| 879 |
widthMin= width -10
|
| 880 |
widthMax= width +10
|
| 881 |
heightMin = height-10
|
| 882 |
heightMax=height+10
|
|
|
|
| 883 |
found=SimilarAreaDictionarycopy.loc[SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Rounded'] >=areamin) & (SimilarAreaDictionarycopy['Rounded']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) ) & ( ((SimilarAreaDictionarycopy['Width']>=widthMin) & (SimilarAreaDictionarycopy['Width']<=widthMax) & (SimilarAreaDictionarycopy['Height']>=heightMin) & (SimilarAreaDictionarycopy['Height']<=heightMax) ) | ((SimilarAreaDictionarycopy['Width']>=heightMin) & (SimilarAreaDictionarycopy['Width']<=heightMax) & (SimilarAreaDictionarycopy['Height']>=widthMin) & (SimilarAreaDictionarycopy['Height']<=widthMax) )) ]]
|
| 884 |
elif section.startswith('3.2'):
|
| 885 |
areamin=round(areastodelete[i],1)- 0.1
|
|
|
|
| 903 |
idx=SimilarAreaDictionarycopy.index[((SimilarAreaDictionarycopy['Area'] >=areamin) & (SimilarAreaDictionarycopy['Area']<=areamax) & (SimilarAreaDictionarycopy['Perimeter'] >=perimmin) & (SimilarAreaDictionarycopy['Perimeter']<=perimmax) )]
|
| 904 |
SimilarAreaDictionarycopy.loc[idx,'Total Area'] = SimilarAreaDictionarycopy.loc[idx,'Total Area'] - areastodelete[i]
|
| 905 |
SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] = SimilarAreaDictionarycopy.loc[idx,'Total Perimeter'] - perimstodelete[i]
|
| 906 |
+
SimilarAreaDictionarycopy.loc[idx,'Total Length'] = SimilarAreaDictionarycopy.loc[idx,'Total Length'] - lengthstodelete[i]
|
| 907 |
SimilarAreaDictionarycopy.loc[idx,'Occurences'] = int(SimilarAreaDictionarycopy.loc[idx,'Occurences']) - 1
|
|
|
|
| 908 |
return SimilarAreaDictionarycopy
|
| 909 |
#######################################################
|
| 910 |
+
##Legend
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 911 |
def authorizeLegend():
|
| 912 |
SCOPES = [
|
| 913 |
'https://www.googleapis.com/auth/spreadsheets',
|
|
|
|
| 919 |
drive_service = build('drive', 'v3', credentials=credentials)
|
| 920 |
gc = pygsheets.authorize(custom_credentials=credentials, client_secret='credentials.json')
|
| 921 |
return spreadsheet_service,drive_service,gc
|
| 922 |
+
#create/update legend
|
| 923 |
def legendGoogleSheets(SimilarAreaDictionary,path ,pdfpath, spreadsheetId=0):
|
| 924 |
|
| 925 |
spreadsheet_service,drive_service,gc=authorizeLegend()
|
|
|
|
| 966 |
worksheet = ws.worksheet(0)
|
| 967 |
worksheet.title='Legend and data created'
|
| 968 |
worksheet.clear()
|
| 969 |
+
print('PDFPATHHH',pdfpath)
|
| 970 |
ws.create_developer_metadata('path',pdfpath)
|
| 971 |
splittedpdfpath=re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,/<>?]', pdfpath)
|
| 972 |
namepathArr=[legendTitle , spreadsheetId,ws.get_developer_metadata('path')[0].value]
|
|
|
|
| 1216 |
spreadsheet_key =str(key) # Please set the Spreadsheet ID.
|
| 1217 |
|
| 1218 |
ws = gc.open_by_key(spreadsheet_key)
|
| 1219 |
+
# guessednamesfinal=getguessnames(gc,ws)
|
| 1220 |
sheetnames=[]
|
| 1221 |
unit=''
|
| 1222 |
# ws.add_worksheet("Summary") # Please set the new sheet name.
|
|
|
|
| 1231 |
worksheetw = ws.worksheet(0) #legend
|
| 1232 |
worksheetS = ws.worksheet_by_title('XML Export Summary')
|
| 1233 |
summaryId= ws[1].id
|
| 1234 |
+
print('summaryyyID',summaryId)
|
| 1235 |
+
print('summaryyyID2',worksheetS.id)
|
| 1236 |
worksheetS.clear()
|
| 1237 |
countnames=0
|
| 1238 |
row0=['MC_T Name','Qty','Unit']
|
|
|
|
| 1245 |
print(McTName[i][0])
|
| 1246 |
|
| 1247 |
# firstpart= re.split(r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]', McTName[i][0])
|
| 1248 |
+
print('kkk' ,McTName[i][2])
|
| 1249 |
if McTName[i][2].startswith('Area'):
|
| 1250 |
if section.startswith('1.0'):
|
| 1251 |
rowvalue=5# column 5
|
|
|
|
| 1278 |
print('mcct',McTName[i][1])
|
| 1279 |
if isinstance(McTName[i][1], list):
|
| 1280 |
guessednames=worksheetw.get_col(1, returnas='matrix', include_tailing_empty=False)
|
| 1281 |
+
|
|
|
|
|
|
|
| 1282 |
for m in McTName[i][1]:
|
| 1283 |
if m:
|
| 1284 |
if m.startswith('text1'):
|
|
|
|
| 1393 |
]
|
| 1394 |
}
|
| 1395 |
spreadsheet_service.spreadsheets().batchUpdate(spreadsheetId=spreadsheet_key, body=body2).execute()
|
| 1396 |
+
return summaryId #,guessednamesfinal
|
| 1397 |
|
| 1398 |
# print(x,xarea)
|
| 1399 |
+
|
| 1400 |
def getguessnames(gc,ws):
|
| 1401 |
guessednamesfinal=[]
|
| 1402 |
worksheetw = ws.worksheet(0)
|