Marthee commited on
Commit
49c1df5
·
verified ·
1 Parent(s): 2070f92

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -68
app.py CHANGED
@@ -6,7 +6,7 @@ from PIL import Image
6
  import cv2
7
  import numpy as np
8
  import pilecaps_adr
9
- import base64
10
  from db import dropbox_connect
11
  import cv2
12
  import pandas as pd
@@ -35,10 +35,13 @@ import mainDBAlaa
35
  import datetime
36
  import doors_fasterrcnn
37
  import deploying_3_3
 
38
  import Code_2_7
39
  import Counting_Columns_2_1
40
  import Find_Hyperlinking_text
41
  import ezdxf
 
 
42
  app = Flask(__name__)
43
 
44
 
@@ -51,20 +54,67 @@ global pdflink
51
  #for 2.7
52
  global hatched_areas2_7
53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  @app.route("/",methods=["GET", "POST"])
55
  def getInfotoMeasure():
56
- API.AppendtablestoSheets()
57
- return render_template("proposed-GUI.html")
58
  @app.route("/WordSearch",methods=["GET", "POST"])
59
  def getInfo2toMeasure():
60
- API.AppendtablestoSheets()
61
  return render_template("wordSearch.html")
62
 
 
 
63
  @app.route('/getprojectnames/',methods=['GET'])
64
  def getprjnamesfromTestAPI():
65
- prjnames,prjids=API.getPrjNames()
66
- # API.AppendtablestoSheets()
67
- return jsonify([prjnames,prjids])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  @app.route('/getprojectparts/<jsdata>',methods=['GET'])
70
  def getprjpartsfromTestAPI(jsdata):
@@ -78,18 +128,30 @@ def getprjSectionsfromTestAPI(jsdata):
78
  sections=API.getprjSections(data[0],data[1])
79
  return jsonify(sections)
80
 
81
-
82
- #retrieves projects
83
- @app.route('/getmethod/<jsdata>',methods=['GET','POST'])
84
  def get_javascript_data(jsdata):
85
- #get project from the first dropdown
86
- # jsdata=eval(jsdata)
87
- print('tsa')
88
- documnetsToMeasure,RelevantDocuments,extracted_path=tsadropboxretrieval.retrieveProjects(jsdata)
89
- if RelevantDocuments:
90
- return jsonify ([documnetsToMeasure, RelevantDocuments,extracted_path])
91
- else:
92
- return ['No projects found']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  #---------------------------------------------------------------
94
  @app.route('/WordSearch',methods=["GET", "POST"])
95
  def searchDocument():
@@ -300,7 +362,7 @@ def measureproject(result,dataDoc=0,img=0,dxffile=0):
300
  pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
301
 
302
  _, buffer = cv2.imencode('.png', outputimg)
303
- arr=[ base64.b64encode(buffer).decode('utf-8'),SimilarAreaDictionary.to_dict(), spreadsheet_url,spreadsheetId,[],list1.to_dict(),pdflink,[],namepathArr]#,hatched_areas,namepathArr]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
304
  ################################# -2.8- #################################
305
  elif result[5][2].startswith('2.8'): #section value - 2.8 floor finishes
306
  #vv[0] array of pdf names
@@ -309,13 +371,24 @@ def measureproject(result,dataDoc=0,img=0,dxffile=0):
309
  legendLinks=[]
310
  listofmarkups=[]
311
 
312
- annotatedimg,pdf_document,spreadsheet_url, list1 , df_doors=doors_fasterrcnn.main_run(img,dataDoc,'separated_classes_all.pth',result[0],pdfpath, result[4]) #single_double.pth
313
-
 
 
 
 
 
314
  dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
315
  pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
316
  _, buffer = cv2.imencode('.png', annotatedimg)
317
- arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,spreadsheet_url,list1.to_dict(), df_doors.to_dict()]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
318
-
 
 
 
 
 
 
319
  ################################# -2.1- #################################
320
  elif result[5][2].startswith('2.1'): #section value - 2.8 floor finishes
321
  #vv[0] array of pdf names
@@ -484,27 +557,37 @@ def get_pdf(jsdata):
484
  #PIXEL CONVERSION METHOD -- SAVES DOC ON DROPBOX TO BE MEASURED BY USER
485
  @app.route("/pixelimg/<jsdata>",methods=["GET", "POST"])
486
  def getimg(jsdata):
487
-
488
  jsdata=eval(jsdata)
489
- pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata[3])
490
- dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
491
- md, res =dbxTeam.files_download(path=pdfpath)
492
- data = res.content
493
- print('jsdata',jsdata)
494
- if str(jsdata[2]).startswith('1.0'):
495
- doc,areaPixel,perimeterPixel=pixelconversion.drawisrotated(data,300) # .openDrawPDF(data)
496
- else:
497
- doc,areaPixel,perimeterPixel,pdfdata=pixelconversion.drawisrotated(data) # .openDrawPDF(data)
498
- dbPath='/TSA JOBS/ADR Test/'+jsdata[0]+'/'+jsdata[1]+'/'+jsdata[2]+'/'+'Scale Document' +'/'
499
- dburl=tsadropboxretrieval.uploadanyFile(doc=doc,pdfname=str(jsdata[3]) ,path=dbPath)
500
- # areaPixel,perimeterPixel= pixelconversion.getAreaPerimeter(dbPath, str(jsdata[3]))
501
-
502
- outputs=[areaPixel,perimeterPixel , dburl]
503
- # pdf_data = io.BytesIO(res.content)
504
- # pdf_data.seek(0)
505
-
506
- return jsonify(outputs) #, send_file(pdf_data, as_attachment=True, mimetype='application/pdf', download_name='downloaded_file.pdf')
507
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  #_________________________________________________________________________________________________________________________
509
  #_________________________________________________________________________________________________________________________
510
  #get sunburst from doc_search
@@ -806,33 +889,8 @@ def checktables():
806
  if len(differentSections)>0:
807
  returnString=['Changes have been made in Sections. Would you like to retrieve them in the console?','section',differentSections]
808
 
809
- # if not t2Diff.empty:
810
- # newvalues= t2Diff['ProjectName'].values
811
- # else:
812
- # newvalues= t2Diff1['ProjectName'].values
813
- # returnString=''
814
- # returnString=['Changes have been made in Parts. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','part']
815
- # elif (not t3Diff.empty) or (not t3Diff1.empty):
816
- # returnString=''
817
-
818
- # returnString=['Changes have been made in Sections. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','section']
819
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t2Diff.empty) or ( not t2Diff1.empty)):
820
- # returnString=''
821
- # returnString=['Changes have been made in Projects and Parts. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','projectpart']
822
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty) ):
823
- # returnString=''
824
- # returnString=['Changes have been made in Projects and Sections. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','projectsection']
825
- # elif ((not t2Diff.empty) or (not t2Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty)):
826
- # returnString=''
827
- # returnString=['Changes have been made in Parts and Sections. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','partsection']
828
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t2Diff.empty) or (not t2Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty)):
829
- # returnString=''
830
- # returnString=['Changes have been made in Projects, Parts and Sections. Would you like to retrieve them in the console? By saying yes, you may need to repeat the website related processes(if any).','project']
831
  print(returnString)
832
- # if sectionData!='noSectionYet':
833
- # return jsonify([returnString,DictionaryOfTemplates])
834
- # else:
835
- # returnString=prjpartsRefreshAPItable2(table2,projectname)
836
 
837
  return jsonify(returnString)
838
 
 
6
  import cv2
7
  import numpy as np
8
  import pilecaps_adr
9
+ import base64
10
  from db import dropbox_connect
11
  import cv2
12
  import pandas as pd
 
35
  import datetime
36
  import doors_fasterrcnn
37
  import deploying_3_3
38
+ import Doors_Schedule
39
  import Code_2_7
40
  import Counting_Columns_2_1
41
  import Find_Hyperlinking_text
42
  import ezdxf
43
+ from flask import Flask, render_template, session, redirect, url_for
44
+
45
  app = Flask(__name__)
46
 
47
 
 
54
  #for 2.7
55
  global hatched_areas2_7
56
 
57
+
58
+ app.secret_key = 'your_secret_key' # Make sure you have a secret key for session management
59
+
60
+
61
+ # Password page route
62
+ @app.route("/password", methods=["GET", "POST"])
63
+ def password_page():
64
+ return render_template("gui2.html") # Render the password page (gui2.html)
65
+
66
+ # Password check route
67
+ @app.route("/check_password", methods=["POST"])
68
+ def check_password():
69
+ password = request.form.get('password') # Get the password entered by the user
70
+ correct_password = 'c900' # Password for validation
71
+
72
+ if password == correct_password: # Validate the password
73
+ session['authenticated'] = True # Set the authenticated flag in the session
74
+ return {"authenticated": True}, 200 # Respond with success
75
+ else:
76
+ return {"authenticated": False}, 200 # Respond with failure
77
+
78
+ # Main GUI page route
79
+ @app.route("/mainGUI", methods=["GET", "POST"])
80
+ def main_gui():
81
+ if 'authenticated' not in session or not session['authenticated']:
82
+ return redirect(url_for('password_page')) # Redirect to the password page if not authenticated
83
+ return render_template("proposed-GUI.html") # Main page content after successful password check
84
+
85
+
86
+
87
  @app.route("/",methods=["GET", "POST"])
88
  def getInfotoMeasure():
89
+ # API.AppendtablestoSheets()
90
+ return render_template("gui2.html")
91
  @app.route("/WordSearch",methods=["GET", "POST"])
92
  def getInfo2toMeasure():
93
+ # API.AppendtablestoSheets()
94
  return render_template("wordSearch.html")
95
 
96
+
97
+
98
  @app.route('/getprojectnames/',methods=['GET'])
99
  def getprjnamesfromTestAPI():
100
+ progress_updates = [] # Shared list to store progress
101
+
102
+ def generate_progressProjnames():
103
+ yield f"data: 10\n\n" # Initial progress
104
+ # Call retrieveProjects and pass a callback to update the shared list
105
+ prjnames,prjids=API.getPrjNames( progress_callback=lambda p: progress_updates.append(p))
106
+ # Continuously yield progress updates from the shared list
107
+
108
+ while progress_updates:
109
+ progress = progress_updates.pop(0) # Get the next progress value
110
+ yield f"data: {progress}\n\n"
111
+ # Final progress and result
112
+ yield f"data: 80\n\n"
113
+ yield f"data: 100\n\n"
114
+ result = json.dumps([prjnames,prjids])
115
+ yield f"data: {result}\n\n"
116
+ return Response(generate_progressProjnames(), content_type='text/event-stream')
117
+
118
 
119
  @app.route('/getprojectparts/<jsdata>',methods=['GET'])
120
  def getprjpartsfromTestAPI(jsdata):
 
128
  sections=API.getprjSections(data[0],data[1])
129
  return jsonify(sections)
130
 
131
+ @app.route('/getmethod/<jsdata>', methods=['GET'])
 
 
132
  def get_javascript_data(jsdata):
133
+ progress_updates = [] # Shared list to store progress
134
+
135
+ def generate_progress():
136
+ yield f"data: 5\n\n" # Initial progress
137
+ yield f"data: 10\n\n" # Initial progress
138
+ # Call retrieveProjects and pass a callback to update the shared list
139
+ documentsToMeasure, RelevantDocuments, extracted_path = tsadropboxretrieval.retrieveProjects(
140
+ jsdata,
141
+ progress_callback=lambda p: progress_updates.append(p)
142
+ )
143
+
144
+ # Continuously yield progress updates from the shared list
145
+ while progress_updates:
146
+ progress = progress_updates.pop(0) # Get the next progress value
147
+ yield f"data: {progress}\n\n"
148
+ # Final progress and result
149
+ yield f"data: 100\n\n"
150
+ result = json.dumps([documentsToMeasure, RelevantDocuments, extracted_path])
151
+ yield f"data: {result}\n\n"
152
+
153
+ return Response(generate_progress(), content_type='text/event-stream')
154
+
155
  #---------------------------------------------------------------
156
  @app.route('/WordSearch',methods=["GET", "POST"])
157
  def searchDocument():
 
362
  pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
363
 
364
  _, buffer = cv2.imencode('.png', outputimg)
365
+ arr=[ base64.b64encode(buffer).decode('utf-8'),SimilarAreaDictionary.to_dict(), spreadsheet_url,spreadsheetId,[],list1.to_dict(),pdflink,hatched_areas,namepathArr]#,hatched_areas,namepathArr]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
366
  ################################# -2.8- #################################
367
  elif result[5][2].startswith('2.8'): #section value - 2.8 floor finishes
368
  #vv[0] array of pdf names
 
371
  legendLinks=[]
372
  listofmarkups=[]
373
 
374
+ pdfpathDoors,_=tsadropboxretrieval.getPathtoPDF_File(nameofPDF= str(result[6]))
375
+ dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
376
+ md, resDoors =dbxTeam.files_download(path=pdfpathDoors)
377
+ dataDocDoorsSchedule = resDoors.content
378
+
379
+ # annotatedimg,pdf_document,spreadsheet_url, list1 , df_doors=doors_fasterrcnn.main_run(img,dataDoc,'separated_classes_all.pth',result[0],pdfpath, result[4]) #single_double.pth
380
+ annotatedimg, pdf_document , list1, repeated_labels , not_found =Doors_Schedule.mainRun(dataDocDoorsSchedule, dataDoc)
381
  dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
382
  pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
383
  _, buffer = cv2.imencode('.png', annotatedimg)
384
+ repeatedLabelsReturn=''
385
+ NotFoundReturn=''
386
+ if len(repeated_labels)>0:
387
+ repeatedLabelsReturn=repeated_labels
388
+ if len(not_found)>0:
389
+ NotFoundReturn=not_found # , spreadsheetId, spreadsheet_url , list1.to_dict()]
390
+ else:
391
+ arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,list1.to_dict(),repeatedLabelsReturn, NotFoundReturn] # , spreadsheetId, spreadsheet_url , list1.to_dict()]
392
  ################################# -2.1- #################################
393
  elif result[5][2].startswith('2.1'): #section value - 2.8 floor finishes
394
  #vv[0] array of pdf names
 
557
  #PIXEL CONVERSION METHOD -- SAVES DOC ON DROPBOX TO BE MEASURED BY USER
558
  @app.route("/pixelimg/<jsdata>",methods=["GET", "POST"])
559
  def getimg(jsdata):
560
+ progress_updates = [] # Shared list to store progress
561
  jsdata=eval(jsdata)
562
+ def generate_progressPixel():
563
+
564
+ yield f"data: 10\n\n" # Initial progress
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565
 
566
+ pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata[3], progress_callback=lambda p: progress_updates.append(p))
567
+ dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
568
+ md, res =dbxTeam.files_download(path=pdfpath)
569
+ data = res.content
570
+ print('jsdata',jsdata)
571
+ if str(jsdata[2]).startswith('1.0'):
572
+ doc,areaPixel,perimeterPixel=pixelconversion.drawisrotated(data,300) # .openDrawPDF(data)
573
+ else:
574
+ doc,areaPixel,perimeterPixel,pdfdata=pixelconversion.drawisrotated(data) # .openDrawPDF(data)
575
+ yield f"data: 20\n\n" # Initial progress
576
+ dbPath='/TSA JOBS/ADR Test/'+jsdata[0]+'/'+jsdata[1]+'/'+jsdata[2]+'/'+'Scale Document' +'/'
577
+ dburl=tsadropboxretrieval.uploadanyFile(doc=doc,pdfname=str(jsdata[3]) ,path=dbPath)
578
+ # areaPixel,perimeterPixel= pixelconversion.getAreaPerimeter(dbPath, str(jsdata[3]))
579
+ yield f"data: 40\n\n" # Initial progress
580
+ outputs=[areaPixel,perimeterPixel , dburl]
581
+ while progress_updates:
582
+ progress = progress_updates.pop(0) # Get the next progress value
583
+ yield f"data: {progress}\n\n"
584
+ # Final progress and result
585
+ yield f"data: 80\n\n"
586
+ yield f"data: 100\n\n"
587
+ result = json.dumps(outputs)
588
+ yield f"data: {result}\n\n"
589
+
590
+ return Response(generate_progressPixel(), content_type='text/event-stream')
591
  #_________________________________________________________________________________________________________________________
592
  #_________________________________________________________________________________________________________________________
593
  #get sunburst from doc_search
 
889
  if len(differentSections)>0:
890
  returnString=['Changes have been made in Sections. Would you like to retrieve them in the console?','section',differentSections]
891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
892
  print(returnString)
893
+
 
 
 
894
 
895
  return jsonify(returnString)
896