Marthee commited on
Commit
4fc5744
·
1 Parent(s): 6eaacff

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -65
app.py CHANGED
@@ -9,8 +9,15 @@ import numpy as np
9
  import sys
10
  import pilecaps_adr
11
  import base64
12
-
13
-
 
 
 
 
 
 
 
14
 
15
  app = Flask(__name__)
16
 
@@ -18,6 +25,7 @@ out_file = open("static/data/myfile.json", "w")
18
 
19
 
20
 
 
21
  # @app.route("/")
22
  # def home():
23
  # #lists of the projects el httb3t lel dropdowns w tro7 lel html through the return b nfs el esm hna w hnak
@@ -27,62 +35,44 @@ out_file = open("static/data/myfile.json", "w")
27
  #info from javascript to python
28
  @app.route('/getmethod/<jsdata>',methods=['GET','POST'])
29
  def get_javascript_data(jsdata):
 
30
  #get project from the first dropdown
31
- print(jsdata)
32
- matches=update_dropdown(jsdata) #list f of projects
33
- d =[ {'project':(jsdata , matches)} ]
34
 
35
- with open('static/data/myfile.json', 'w', encoding ='utf8') as json_file:
36
- json.dump(d, json_file, ensure_ascii = False)
37
-
38
 
39
- #get projects bl esm da ex: BMW job1
40
-
41
-
42
- return render_template("proposed-GUI.html",matches=matches)
43
- #info from python to js
44
- @app.route('/getpythondata')
45
- def get_python_data():
46
- SITE_ROOT = os.path.realpath(os.path.dirname(__file__))
47
- json_url = os.path.join(SITE_ROOT, "static/data", "myfile.json")
48
- data = json.load(open(json_url))
49
- #data[0]['project']
50
- #matches=update_dropdown(data[0]['project']) #list f of projects
51
-
52
- return jsonify(data[0]['project'] )
53
 
54
  #get projects of 'project name'
55
- def update_dropdown(project):
56
-
57
- plans_inrepo=os.listdir('dropbox_plans')
 
 
 
 
58
  #if 'foundation' in radio and project in plans_inrepo
59
  matches=[]
60
- if project==None:
61
  print('no proj')
62
  # drop=gr.Dropdown.update(choices=matches)
63
  else:
64
  for x in plans_inrepo:
65
- if (project in x): #project name and section in a plan
66
  matches.append(x)
67
  print(matches)
68
  #drop=gr.Dropdown.update(choices=matches)
69
  return matches
70
- #make the img global using(g) from flask
71
  # @app.before_request
72
- # def measureImg(img='aa'):
73
- # if type(img) is str:
74
- # g.img='aa'
75
- # print('striiing')
76
- # g.measuredimg='aa'
77
- # else:
78
- # imgPerimeter1,image_new1,SimilarAreaDictionary , colorsUsed=pilecaps_adr.drawAllContours(img,0,[],0,0,'area')
79
-
80
- # g.image_new1 =image_new1
81
- # return image_new1
82
 
83
  #retrieve all info of elements after clicking 'measure' button
84
  @app.route("/",methods=["GET", "POST"])
85
  def getInfotoMeasure():
 
86
  mylist=[1,2,3,4]
87
  return render_template("proposed-GUI.html",mylist=mylist)
88
 
@@ -97,31 +87,31 @@ def hexRGB(color):
97
  @app.route('/projecttomeasure/<jsdata>',methods=["GET","POST"])
98
  def measureproject(jsdata):
99
  colorarr=[]
100
- result = json.loads(jsdata)
101
- print('RESULT HEREEE', result)
102
-
103
- img = plan2img('dropbox_plans/'+str(result[0]) )
104
- # g.img=img
105
- for item in result[2]:
106
- item1 ='#'+item
107
- c=hexRGB(item1)
108
- colorarr.append(c)
109
-
110
- imgPerimeter1,image_new1,SimilarAreaDictionary , colorsUsed,spreadsheet_url, spreadsheetId=pilecaps_adr.drawAllContours(img,int(result[1]),colorarr,1.11,25500,'area')
111
-
112
- print('measuredddddd')
113
-
114
- # img2 = cv2.cvtColor(image_new1, cv2.COLOR_RGB2BGR)
115
- _, buffer = cv2.imencode('.png', image_new1)
116
-
117
- # return SimilarAreaDictionary.to_dict()
118
- #return
119
- arr=[base64.b64encode(buffer).decode('utf-8'), SimilarAreaDictionary.to_dict() ,spreadsheet_url , spreadsheetId]
120
- return jsonify(arr)#'{}, {} '.format(base64.b64encode(buffer).decode('utf-8') , SimilarAreaDictionary )
121
- # return Flask.jsonify(data=base64.b64encode(buffer).decode('utf-8'), data1=SimilarAreaDictionary)
122
- # return str(measuredimg)
123
- # return render_template("proposed-GUI.html")
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
 
126
  #retrieve all info of elements after clicking 'done' button
127
  @app.route("/forward/",methods=["GET", "POST"])
@@ -139,7 +129,7 @@ def move_forward():
139
  #####################
140
  #pdf to img
141
  def plan2img(path):
142
-
143
  doc = fitz.open(path)
144
  for page in doc:
145
 
@@ -154,8 +144,166 @@ def plan2img(path):
154
  def sendmctnametoLegend(jsdata):
155
  result = json.loads(jsdata)
156
  print(result)
157
- pilecaps_adr.mapnametoLegend(result)
158
- return jsdata
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
  if __name__ == "__main__":
161
  app.run(host="0.0.0.0", port=7860)
 
9
  import sys
10
  import pilecaps_adr
11
  import base64
12
+ from db import dropbox_connect
13
+ import db
14
+ import cv2
15
+ import pandas as pd
16
+ import ast
17
+ import time
18
+ from io import BytesIO
19
+ from flask import Flask, Response
20
+ from werkzeug.wsgi import wrap_file
21
 
22
  app = Flask(__name__)
23
 
 
25
 
26
 
27
 
28
+
29
  # @app.route("/")
30
  # def home():
31
  # #lists of the projects el httb3t lel dropdowns w tro7 lel html through the return b nfs el esm hna w hnak
 
35
  #info from javascript to python
36
  @app.route('/getmethod/<jsdata>',methods=['GET','POST'])
37
  def get_javascript_data(jsdata):
38
+
39
  #get project from the first dropdown
 
 
 
40
 
41
+ matches=update_dropdown(jsdata) #list f of projects
42
+ print(matches)
43
+ return jsonify (list(matches))
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  #get projects of 'project name'
47
+ def update_dropdown(section):
48
+ if section.startswith('1.0'):
49
+ plans_inrepo=os.listdir('dropbox_plans/1.0')
50
+ elif section.startswith('3.2'):
51
+ plans_inrepo=os.listdir('dropbox_plans/3.2')
52
+ else:
53
+ return ''
54
  #if 'foundation' in radio and project in plans_inrepo
55
  matches=[]
56
+ if section==None:
57
  print('no proj')
58
  # drop=gr.Dropdown.update(choices=matches)
59
  else:
60
  for x in plans_inrepo:
61
+ # if (project in x): #project name and section in a plan
62
  matches.append(x)
63
  print(matches)
64
  #drop=gr.Dropdown.update(choices=matches)
65
  return matches
66
+
67
  # @app.before_request
68
+ # def load_user():
69
+ # g.doc='none'
70
+ # g.__doc__ = 'none'
 
 
 
 
 
 
 
71
 
72
  #retrieve all info of elements after clicking 'measure' button
73
  @app.route("/",methods=["GET", "POST"])
74
  def getInfotoMeasure():
75
+ # db.create_folder()
76
  mylist=[1,2,3,4]
77
  return render_template("proposed-GUI.html",mylist=mylist)
78
 
 
87
  @app.route('/projecttomeasure/<jsdata>',methods=["GET","POST"])
88
  def measureproject(jsdata):
89
  colorarr=[]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ result = json.loads(jsdata)
92
+
93
+ pdfpath='/'
94
+ for word in result[5]:
95
+ pdfpath+=word +'/'
96
+ print(pdfpath)
97
+ #result[3] ratio of area ,, result[4] ratio of perimeter
98
+ if result[5][2].startswith('1.0'):
99
+ img = plan2img('dropbox_plans/1.0/'+str(result[0]) )
100
+
101
+ # g.img=img
102
+ for item in result[2]:
103
+ item1 ='#'+item
104
+ c=hexRGB(item1)
105
+ colorarr.append(c)
106
+ # result[3],result[4] (img,number,finalColorArray,ratioarea,ratioperim,flag , path,pdfpath):
107
+ imgPerimeter1,image_new1,SimilarAreaDictionary , colorsUsed,spreadsheet_url, spreadsheetId,list1, pdflink, areas_Perimeters =pilecaps_adr.drawAllContours(img,int(result[1]),colorarr,1.11/25500,0.1,'area', result[0],pdfpath)
108
+
109
+ _, buffer = cv2.imencode('.png', image_new1)
110
+ arr=[base64.b64encode(buffer).decode('utf-8'),SimilarAreaDictionary.to_dict(),spreadsheet_url , spreadsheetId,colorsUsed,list1.to_dict(), pdflink, areas_Perimeters]
111
+ elif result[5][2].startswith('3.2'): #section value
112
+ img = plan2img('dropbox_plans/3.2/'+str(result[0]) )
113
+ #call main function here
114
+ return jsonify(arr )
115
 
116
  #retrieve all info of elements after clicking 'done' button
117
  @app.route("/forward/",methods=["GET", "POST"])
 
129
  #####################
130
  #pdf to img
131
  def plan2img(path):
132
+
133
  doc = fitz.open(path)
134
  for page in doc:
135
 
 
144
  def sendmctnametoLegend(jsdata):
145
  result = json.loads(jsdata)
146
  print(result)
147
+ summaryid,guessednamesfinal=pilecaps_adr.mapnametoLegend(result)
148
+
149
+ allreturns=[summaryid,guessednamesfinal]
150
+ return jsonify(allreturns)
151
+
152
+ # #####################################
153
+ def calcRef(img):
154
+ blk = np.ones(img.shape, dtype="uint8") * [[[np.uint8(0), np.uint8(0), np.uint8(0)]]]
155
+
156
+ start_point = (50, 100)
157
+ end_point = (120, 200)
158
+ color = (255, 255, 255) # white BGR
159
+ thickness = -1 # Thickness of -1 will fill the entire shape
160
+
161
+ blk = cv2.rectangle(blk, start_point, end_point, color, thickness)
162
+
163
+ blk = cv2.cvtColor(blk, cv2.COLOR_BGR2GRAY)
164
+
165
+ contourzz, hierarchy = cv2.findContours(image=blk, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
166
+ for i, cnt3 in enumerate(contourzz):
167
+ M = cv2.moments(cnt3)
168
+ if M['m00'] != 0.0:
169
+ x2 = int(M['m10']/M['m00'])
170
+ y2 = int(M['m01']/M['m00'])
171
+ area = cv2.contourArea(cnt3)
172
+ perimeter = cv2.arcLength(cnt3, True)
173
+ return area,perimeter , blk
174
+ # #################################################
175
+
176
+ def modifyingcalcRefDynamic(img):
177
+ imgcopy = img.copy()
178
+
179
+ blk = np.ones(img.shape, dtype="uint8") * [[[np.uint8(0), np.uint8(0), np.uint8(0)]]]
180
+
181
+ x = 50
182
+ y = 100
183
+ xD = int(img.shape[1] * 0.10)
184
+ yD = int(img.shape[0] * 0.10)
185
+ start_point = (x, y)
186
+ end_point = (x+xD, y+yD)
187
+ blue = (255, 0, 0) # BGR
188
+ white = (255, 255, 255) # BGR
189
+ thickness = -1 # Thickness of -1 will fill the entire shape
190
+
191
+ imgcopy = cv2.rectangle(imgcopy, start_point, end_point, blue, thickness)
192
+ blk = cv2.rectangle(blk, start_point, end_point, white, thickness)
193
+
194
+ blk = cv2.cvtColor(blk, cv2.COLOR_BGR2GRAY)
195
+
196
+ contourzz, hierarchy = cv2.findContours(image=blk, mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_NONE)
197
+ for i, cnt3 in enumerate(contourzz):
198
+ M = cv2.moments(cnt3)
199
+ if M['m00'] != 0.0:
200
+ x2 = int(M['m10']/M['m00'])
201
+ y2 = int(M['m01']/M['m00'])
202
+ area = cv2.contourArea(cnt3)
203
+ perimeter = cv2.arcLength(cnt3, True)
204
+ return area, perimeter, blk , imgcopy
205
+
206
+
207
+
208
+
209
+ @app.route("/pixelimg/<jsdata>",methods=["GET", "POST"])
210
+ def getimg(jsdata):
211
+
212
+ jsdata=eval(jsdata)
213
+ # img = plan2img('dropbox_plans/'+str(jsdata) )
214
+ if jsdata[1].startswith('1.0'):
215
+ doc = fitz.open('dropbox_plans/1.0/'+str(jsdata[0]) )
216
+ elif jsdata[1].startswith('3.2'):
217
+ doc = fitz.open('dropbox_plans/3.2/'+str(jsdata[0]) )
218
+ else:
219
+ return ''
220
+ for page in doc:
221
+
222
+ pix = page.get_pixmap() # render page to an image
223
+ pl=Image.frombytes('RGB', [pix.width,pix.height],pix.samples)
224
+ img=np.array(pl)
225
+ print(img.shape)
226
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
227
+
228
+
229
+ areapixel,perimeterpixel , blkRectImg , imgcopy=modifyingcalcRefDynamic(img)
230
+ PIL_image = Image.fromarray(np.uint8(imgcopy))
231
+ PIL_image.save('toMeasure'+str(jsdata)+'.pdf')
232
+
233
+ print(areapixel)
234
+ outputs=[areapixel,perimeterpixel]
235
+ return jsonify(outputs)
236
+
237
+
238
+ @app.route('/_submission',methods=["GET", "POST"])
239
+ def getnewlegend():
240
+ pdfpth=''
241
+ # SimilarAreaDictionary = request.args.get('dict')
242
+ list1 = request.args.get('dict1')
243
+ path = request.args.get('path')
244
+ spreadsheetId =request.args.get('spreadsheetId')
245
+ pdfpathpath=request.args.get('pdfpathpath')
246
+
247
+ pdfname=request.args.get('pdfname')
248
+ for word in eval(pdfpathpath):
249
+ pdfpth+='/' +word
250
+ pdfpth+='/'
251
+
252
+ # res = ast.literal_eval(ini_list)
253
+
254
+ deletedrows1=pilecaps_adr.deletemarkups(list1=list1,pdfpath=pdfpth,path=path)
255
+ print(deletedrows1)
256
+ arr1=[deletedrows1.to_dict()]
257
+ return jsonify(arr1)
258
+
259
+ @app.route('/deletemarkupsroute',methods=["GET", "POST"])
260
+ def dltmarkupslegend():
261
+
262
+ SimilarAreaDictionary = request.args.get('dict')
263
+ deletedrows = request.args.get('deletedrows')
264
+ path = request.args.get('path')
265
+ spreadsheetId =request.args.get('spreadsheetId')
266
+ areaPermArr=request.args.get('areaPermArr')
267
+
268
+
269
+ myDict=eval(deletedrows)
270
+ print(type(myDict))
271
+ deletedrows=pd.DataFrame(myDict)
272
+ print(deletedrows,type(deletedrows))
273
+ print(type(SimilarAreaDictionary),type(deletedrows),type(path),type(spreadsheetId))
274
+ newlgnd=pilecaps_adr.deletefromlegend(deletedrows=deletedrows,SimilarAreaDictionarycopy=SimilarAreaDictionary, areaPermArr=areaPermArr)
275
+ try:
276
+ newlgnd1=pilecaps_adr.legendGoogleSheets(SimilarAreaDictionary=newlgnd,path=path, colorsUsed=[1,2,3],spreadsheetId=spreadsheetId) #new legend
277
+ except:
278
+ print("An exception occurred")
279
+ time.sleep(10)
280
+ newlgnd1=pilecaps_adr.legendGoogleSheets(SimilarAreaDictionary=newlgnd,path=path, colorsUsed=[1,2,3],spreadsheetId=spreadsheetId)
281
+
282
+ return jsonify('donee')
283
+
284
+
285
+ @app.route('/getdropboxurl/<jsdata>',methods=["GET", "POST"])
286
+ def calldropboxurl(jsdata):
287
+ pdfpth=''
288
+ for word in eval(jsdata):
289
+ pdfpth+='/' +word
290
+ print(pdfpth)
291
+ pdfurl=db.dropbox_shareableLink(pdfpth)
292
+ return jsonify(pdfurl)
293
+ # @app.route('/uploadtodropboxPath/<jsdata>',methods=["GET", "POST"])
294
+ # @app.teardown_request
295
+ # def upload_GetPath(jsdata):
296
+ # print('ayhagaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ', jsdata)
297
+ # return jsdata
298
+ # # db.dropbox_upload_file(doc=,pdfname=)
299
+
300
+ @app.route('/getdrivelinks/<jsdata>',methods=["GET", "POST"])
301
+ def getlinkscreated(jsdata):
302
+ spreadsheet_service,drive_service,gc= pilecaps_adr.authorizeLegend()
303
+ ids=gc.spreadsheet_ids()
304
+ titles=gc.spreadsheet_titles()
305
+ return jsonify(titles,ids)
306
+
307
 
308
  if __name__ == "__main__":
309
  app.run(host="0.0.0.0", port=7860)