Marthee commited on
Commit
205c053
·
verified ·
1 Parent(s): 46d0cdc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +322 -94
app.py CHANGED
@@ -1,19 +1,18 @@
1
  from __future__ import print_function
2
  from flask import Flask, render_template,request,flash , json, url_for,g , redirect , jsonify , send_file ,make_response
3
- import os
4
  import json
5
  import fitz
6
  from PIL import Image
7
- import cv2
8
  import numpy as np
9
- import pilecaps_adr
10
- import base64
11
  from db import dropbox_connect
12
- import db
13
  import cv2
14
  import pandas as pd
15
  import time
16
  from io import BytesIO, StringIO
 
17
  import tempfile
18
  from flask import Flask, Response
19
  from werkzeug.wsgi import wrap_file
@@ -21,7 +20,6 @@ import tameem3_2
21
  import pypdfium2 as pdfium
22
  import pixelconversion
23
  import tameem2_1
24
- import base64
25
  import io
26
  from urllib.parse import unquote
27
  import API
@@ -30,41 +28,96 @@ import tsadropboxretrieval
30
  import doc_search
31
  import google_sheet_Legend
32
  import dxf__omar3_2
 
33
  import google_sheet_to_xml
34
  from threading import Thread
35
  import mainDBAlaa
36
  import datetime
37
  import doors_fasterrcnn
38
  import deploying_3_3
 
 
39
  import Counting_Columns_2_1
40
-
41
  import ezdxf
 
 
42
  app = Flask(__name__)
43
 
 
 
 
44
 
45
- prjnamesURL= 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=0'
46
- prjpartsURL= 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=34865056'
47
- prjsectionsURL= 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=1751466819'
48
-
49
  global colorsused
50
  global pdflink
51
-
52
- @app.route("/",methods=["GET", "POST"])
 
 
 
 
 
 
 
 
 
 
 
 
53
  def getInfotoMeasure():
54
- API.AppendtablestoSheets()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  return render_template("proposed-GUI.html")
56
 
 
 
57
  @app.route("/WordSearch",methods=["GET", "POST"])
58
  def getInfo2toMeasure():
59
- API.AppendtablestoSheets()
60
  return render_template("wordSearch.html")
61
 
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 +131,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=tsadropboxretrieval.retrieveProjects(jsdata)
89
- if RelevantDocuments:
90
- return jsonify ([documnetsToMeasure, RelevantDocuments])
91
- else:
92
- return ['No projects found']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  #---------------------------------------------------------------
94
  @app.route('/WordSearch',methods=["GET", "POST"])
95
  def searchDocument():
@@ -175,7 +240,7 @@ def getfromdropboxImg(jsdata):
175
  def stringToRGB():
176
  vv = eval(request.form.get('answers'))
177
  print(vv)
178
- if ( vv[5][2].startswith('3.2') or vv[5][2].startswith('3.3') ) :
179
  print('3.2 section')
180
  pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=vv[0])
181
  dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
@@ -189,6 +254,8 @@ def stringToRGB():
189
  arr=measureproject(vv,dataDoc,0,file)
190
  return jsonify(arr)
191
 
 
 
192
  if vv[5][2].startswith('1.0'):
193
  opencv_img,dataDoc = plan2img( str(vv[0]) )
194
  if vv[1]==220:
@@ -273,6 +340,30 @@ def measureproject(result,dataDoc=0,img=0,dxffile=0):
273
  #
274
  pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
276
  _, buffer = cv2.imencode('.png', outputimg)
277
  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()]
278
  ################################# -2.8- #################################
@@ -283,13 +374,24 @@ def measureproject(result,dataDoc=0,img=0,dxffile=0):
283
  legendLinks=[]
284
  listofmarkups=[]
285
 
286
- annotatedimg,pdf_document,spreadsheet_url, list1 , df_doors=doors_fasterrcnn.main_run(img,dataDoc,'separated_classes.pth','separated_classes_all.pth',result[0],pdfpath, result[4]) #single_double.pth
287
-
 
 
 
 
 
288
  dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
289
  pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
290
  _, buffer = cv2.imencode('.png', annotatedimg)
291
- arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,spreadsheet_url,list1.to_dict(), df_doors.to_dict()]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
292
-
 
 
 
 
 
 
293
  ################################# -2.1- #################################
294
  elif result[5][2].startswith('2.1'): #section value - 2.8 floor finishes
295
  #vv[0] array of pdf names
@@ -297,12 +399,12 @@ def measureproject(result,dataDoc=0,img=0,dxffile=0):
297
  dpxlinks=[]
298
  legendLinks=[]
299
  listofmarkups=[]
300
- print('wasalt::',dataDoc)
301
  annotatedimg,pdf_document,spreadsheet_url, list1 , df_doors=Counting_Columns_2_1.mainfun(dataDoc,pdfpath,result[0])
302
 
303
- dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
304
- pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
305
- _, buffer = cv2.imencode('.png', annotatedimg)
306
  arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,spreadsheet_url,list1.to_dict(), df_doors.to_dict()]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
307
 
308
  ################################# -2.2- #################################
@@ -458,27 +560,37 @@ def get_pdf(jsdata):
458
  #PIXEL CONVERSION METHOD -- SAVES DOC ON DROPBOX TO BE MEASURED BY USER
459
  @app.route("/pixelimg/<jsdata>",methods=["GET", "POST"])
460
  def getimg(jsdata):
461
-
462
  jsdata=eval(jsdata)
463
- pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata[3])
464
- dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
465
- md, res =dbxTeam.files_download(path=pdfpath)
466
- data = res.content
467
- print('jsdata',jsdata)
468
- if str(jsdata[2]).startswith('1.0'):
469
- doc,areaPixel,perimeterPixel=pixelconversion.drawisrotated(data,300) # .openDrawPDF(data)
470
- else:
471
- doc,areaPixel,perimeterPixel,pdfdata=pixelconversion.drawisrotated(data) # .openDrawPDF(data)
472
- dbPath='/TSA JOBS/ADR Test/'+jsdata[0]+'/'+jsdata[1]+'/'+jsdata[2]+'/'+'Scale Document' +'/'
473
- dburl=tsadropboxretrieval.uploadanyFile(doc=doc,pdfname=str(jsdata[3]) ,path=dbPath)
474
- # areaPixel,perimeterPixel= pixelconversion.getAreaPerimeter(dbPath, str(jsdata[3]))
475
-
476
- outputs=[areaPixel,perimeterPixel , dburl]
477
- # pdf_data = io.BytesIO(res.content)
478
- # pdf_data.seek(0)
479
-
480
- return jsonify(outputs) #, send_file(pdf_data, as_attachment=True, mimetype='application/pdf', download_name='downloaded_file.pdf')
481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  #_________________________________________________________________________________________________________________________
483
  #_________________________________________________________________________________________________________________________
484
  #get sunburst from doc_search
@@ -544,6 +656,8 @@ def dltmarkupslegend():
544
  # myDict=eval(deletedrows)
545
  deletedrows=pd.DataFrame(deletedrows)
546
  print('deletedrows',deletedrows)
 
 
547
  if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
548
  newlgnd=google_sheet_Legend.deletefromlegend(deletedrows=deletedrows,SimilarAreaDictionarycopy=SimilarAreaDictionary, section=section,areaPermArr=areaPermArr)
549
  elif section.startswith('2.8'):
@@ -566,13 +680,121 @@ def dltmarkupslegend():
566
  #get pdf dropbox url after measurement is done
567
  @app.route('/getdropboxurl/<jsdata>',methods=["GET", "POST"])
568
  def calldropboxurl(jsdata):
569
- print(jsdata)
570
  pdfurl=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata)[1]
571
- print(pdfurl)
572
- return jsonify(pdfurl)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
 
574
  #_________________________________________________________________________________________________________________________
575
  #_________________________________________________________________________________________________________________________
 
576
  #Google sheet links
577
  @app.route('/getdrivelinks/<jsdata>',methods=["GET", "POST"])
578
  def getlinkscreated(jsdata):
@@ -670,40 +892,15 @@ def checktables():
670
  if len(differentSections)>0:
671
  returnString=['Changes have been made in Sections. Would you like to retrieve them in the console?','section',differentSections]
672
 
673
- # if not t2Diff.empty:
674
- # newvalues= t2Diff['ProjectName'].values
675
- # else:
676
- # newvalues= t2Diff1['ProjectName'].values
677
- # returnString=''
678
- # 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']
679
- # elif (not t3Diff.empty) or (not t3Diff1.empty):
680
- # returnString=''
681
-
682
- # 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']
683
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t2Diff.empty) or ( not t2Diff1.empty)):
684
- # returnString=''
685
- # 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']
686
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty) ):
687
- # returnString=''
688
- # 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']
689
- # elif ((not t2Diff.empty) or (not t2Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty)):
690
- # returnString=''
691
- # 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']
692
- # elif ((not t1Diff.empty) or (not t1Diff1.empty)) and ((not t2Diff.empty) or (not t2Diff1.empty)) and ((not t3Diff.empty) or (not t3Diff1.empty)):
693
- # returnString=''
694
- # 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']
695
  print(returnString)
696
- # if sectionData!='noSectionYet':
697
- # return jsonify([returnString,DictionaryOfTemplates])
698
- # else:
699
- # returnString=prjpartsRefreshAPItable2(table2,projectname)
700
 
701
  return jsonify(returnString)
702
 
703
  @app.route('/refreshDropbox',methods=["GET", "POST"])
704
  def checkdropbox():
705
  print('checkingggdf')
706
- dfFromDropbox=tsadropboxretrieval.DropboxItemstoDF( "/TSA JOBS")[0]
707
  dfParquet=tsadropboxretrieval.GetParquetDF()
708
 
709
  dfParquet1 = dfParquet[['name', 'path_display', 'client_modified', 'server_modified']]
@@ -718,13 +915,45 @@ def checkdropbox():
718
  stringReturned= 'Updated Sucessfully.'
719
  else:
720
  stringReturned= 'Nothing to update.'
721
- return stringReturned
 
 
 
 
722
 
 
723
 
 
 
 
 
 
 
 
 
 
724
 
725
- @app.route('/postdropboxprojects',methods=["GET", "POST"])
726
- def postDropboxprojectsinConsole():
727
- stringReturned=checkdropbox()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728
  print(stringReturned)
729
  return stringReturned
730
 
@@ -750,8 +979,7 @@ def cvtSummarytoXML(jsdata):
750
  # print(result[1])
751
  xmllink=google_sheet_to_xml.create_xml(documentname=result[1],dbPath=path)
752
  return jsonify(xmllink)
753
-
754
-
755
 
756
  #_________________________________________________________________________________________________________________________
757
  #_________________________________________________________________________________________________________________________
 
1
  from __future__ import print_function
2
  from flask import Flask, render_template,request,flash , json, url_for,g , redirect , jsonify , send_file ,make_response
 
3
  import json
4
  import fitz
5
  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
13
  import time
14
  from io import BytesIO, StringIO
15
+ import urllib
16
  import tempfile
17
  from flask import Flask, Response
18
  from werkzeug.wsgi import wrap_file
 
20
  import pypdfium2 as pdfium
21
  import pixelconversion
22
  import tameem2_1
 
23
  import io
24
  from urllib.parse import unquote
25
  import API
 
28
  import doc_search
29
  import google_sheet_Legend
30
  import dxf__omar3_2
31
+ import requests
32
  import google_sheet_to_xml
33
  from threading import Thread
34
  import mainDBAlaa
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
+ from flask_session import Session # Capital "S"
45
  app = Flask(__name__)
46
 
47
+ prjnamesURL = 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=0'
48
+ prjpartsURL = 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=34865056'
49
+ prjsectionsURL = 'https://docs.google.com/spreadsheets/d/1nsIgi9o9VSBKQlNxbxihPzG_N7s4um0eNVfgL4gaGPc/export?format=csv&gid=1751466819'
50
 
51
+ # Global variables (example)
 
 
 
52
  global colorsused
53
  global pdflink
54
+ # For 2.7
55
+ global hatched_areas2_7
56
+
57
+ # Configure Flask-Session for server-side session storage
58
+ app.config["SESSION_TYPE"] = "filesystem"
59
+ app.config["SESSION_PERMANENT"] = False
60
+ app.config["SESSION_FILE_DIR"] = "./flask_session_files"
61
+ app.secret_key = "your_secret_key"
62
+
63
+ # Initialize Flask-Session
64
+ sess = Session()
65
+ sess.init_app(app)
66
+
67
+ @app.route("/", methods=["GET", "POST"])
68
  def getInfotoMeasure():
69
+ return render_template("gui2.html")
70
+
71
+ @app.route("/password", methods=["GET", "POST"])
72
+ def password_page():
73
+ return render_template("gui2.html")
74
+
75
+ @app.route("/check_password", methods=["POST"])
76
+ def check_password():
77
+ password = request.form.get("password")
78
+ correct_password = "c900"
79
+
80
+ if password == correct_password:
81
+ session["authenticated"] = True
82
+ return jsonify({"authenticated": True}), 200
83
+ else:
84
+ return jsonify({"authenticated": False}), 200
85
+
86
+ @app.route("/mainGUI", methods=["GET", "POST"])
87
+ def main_gui():
88
+ if "authenticated" not in session or not session["authenticated"]:
89
+ return redirect(url_for("password_page"))
90
  return render_template("proposed-GUI.html")
91
 
92
+
93
+
94
  @app.route("/WordSearch",methods=["GET", "POST"])
95
  def getInfo2toMeasure():
96
+ # API.AppendtablestoSheets()
97
  return render_template("wordSearch.html")
98
 
99
+
100
+
101
  @app.route('/getprojectnames/',methods=['GET'])
102
  def getprjnamesfromTestAPI():
103
+ progress_updates = [] # Shared list to store progress
104
+
105
+ def generate_progressProjnames():
106
+ yield f"data: 10\n\n" # Initial progress
107
+ # Call retrieveProjects and pass a callback to update the shared list
108
+ prjnames,prjids=API.getPrjNames( progress_callback=lambda p: progress_updates.append(p))
109
+ # Continuously yield progress updates from the shared list
110
+
111
+ while progress_updates:
112
+ progress = progress_updates.pop(0) # Get the next progress value
113
+ yield f"data: {progress}\n\n"
114
+ # Final progress and result
115
+ yield f"data: 80\n\n"
116
+ yield f"data: 100\n\n"
117
+ result = json.dumps([prjnames,prjids])
118
+ yield f"data: {result}\n\n"
119
+ return Response(generate_progressProjnames(), content_type='text/event-stream')
120
+
121
 
122
  @app.route('/getprojectparts/<jsdata>',methods=['GET'])
123
  def getprjpartsfromTestAPI(jsdata):
 
131
  sections=API.getprjSections(data[0],data[1])
132
  return jsonify(sections)
133
 
134
+ @app.route('/getmethod/<jsdata>', methods=['GET'])
 
 
135
  def get_javascript_data(jsdata):
136
+ progress_updates = [] # Shared list to store progress
137
+
138
+ def generate_progress():
139
+ yield f"data: 5\n\n" # Initial progress
140
+ yield f"data: 10\n\n" # Initial progress
141
+ # Call retrieveProjects and pass a callback to update the shared list
142
+ documentsToMeasure, RelevantDocuments, extracted_path = tsadropboxretrieval.retrieveProjects(
143
+ jsdata,
144
+ progress_callback=lambda p: progress_updates.append(p)
145
+ )
146
+
147
+ # Continuously yield progress updates from the shared list
148
+ while progress_updates:
149
+ progress = progress_updates.pop(0) # Get the next progress value
150
+ yield f"data: {progress}\n\n"
151
+ # Final progress and result
152
+ yield f"data: 100\n\n"
153
+ result = json.dumps([documentsToMeasure, RelevantDocuments, extracted_path])
154
+ yield f"data: {result}\n\n"
155
+
156
+ return Response(generate_progress(), content_type='text/event-stream')
157
+
158
  #---------------------------------------------------------------
159
  @app.route('/WordSearch',methods=["GET", "POST"])
160
  def searchDocument():
 
240
  def stringToRGB():
241
  vv = eval(request.form.get('answers'))
242
  print(vv)
243
+ if ( vv[5][2].startswith('3.2') or vv[5][2].startswith('3.3') or vv[5][2].startswith('2.7')) :
244
  print('3.2 section')
245
  pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=vv[0])
246
  dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
 
254
  arr=measureproject(vv,dataDoc,0,file)
255
  return jsonify(arr)
256
 
257
+
258
+
259
  if vv[5][2].startswith('1.0'):
260
  opencv_img,dataDoc = plan2img( str(vv[0]) )
261
  if vv[1]==220:
 
340
  #
341
  pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
342
 
343
+ _, buffer = cv2.imencode('.png', outputimg)
344
+ 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()]
345
+ ################################# 2.7- #################################
346
+ elif result[5][2].startswith('2.7') : #section value - 2.7 floor finishes
347
+ print('code of 2.7')
348
+ dxfpath=dxffile.read()
349
+ with tempfile.NamedTemporaryFile(suffix='.dxf', delete=False) as temp_file:
350
+ temp_file.write(dxfpath)
351
+ temp_filename = temp_file.name
352
+ print(temp_filename)
353
+
354
+ SearchArray=result[6]
355
+ print(result)
356
+ print("SearchArray = ",SearchArray)
357
+ global hatched_areas2_7
358
+ doc,outputimg, SimilarAreaDictionary ,spreadsheetId, spreadsheet_url , namepathArr , list1,hatched_areas=Code_2_7.mainFunctionDrawImgPdf(dataDoc,temp_filename,result[4],SearchArray, pdfpath,result[0])
359
+ # global colorsused
360
+ hatched_areas2_7=hatched_areas
361
+ colorsused=list(SimilarAreaDictionary['Color'])
362
+ dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
363
+ print(dbPath,result[0])
364
+ #
365
+ pdflink= tsadropboxretrieval.uploadanyFile(doc=doc,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/'
366
+
367
  _, buffer = cv2.imencode('.png', outputimg)
368
  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()]
369
  ################################# -2.8- #################################
 
374
  legendLinks=[]
375
  listofmarkups=[]
376
 
377
+ pdfpathDoors,_=tsadropboxretrieval.getPathtoPDF_File(nameofPDF= str(result[6]))
378
+ dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
379
+ md, resDoors =dbxTeam.files_download(path=pdfpathDoors)
380
+ dataDocDoorsSchedule = resDoors.content
381
+
382
+ # 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
383
+ annotatedimg, pdf_document , list1, repeated_labels , not_found =Doors_Schedule.mainRun(dataDocDoorsSchedule, dataDoc)
384
  dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
385
  pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
386
  _, buffer = cv2.imencode('.png', annotatedimg)
387
+ repeatedLabelsReturn=''
388
+ NotFoundReturn=''
389
+ if len(repeated_labels)>0:
390
+ repeatedLabelsReturn=repeated_labels
391
+ if len(not_found)>0:
392
+ NotFoundReturn=not_found # , spreadsheetId, spreadsheet_url , list1.to_dict()]
393
+ else:
394
+ arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,list1.to_dict(),repeatedLabelsReturn, NotFoundReturn] # , spreadsheetId, spreadsheet_url , list1.to_dict()]
395
  ################################# -2.1- #################################
396
  elif result[5][2].startswith('2.1'): #section value - 2.8 floor finishes
397
  #vv[0] array of pdf names
 
399
  dpxlinks=[]
400
  legendLinks=[]
401
  listofmarkups=[]
402
+
403
  annotatedimg,pdf_document,spreadsheet_url, list1 , df_doors=Counting_Columns_2_1.mainfun(dataDoc,pdfpath,result[0])
404
 
405
+ # dbPath='/TSA JOBS/ADR Test'+pdfpath+'Measured Plan/'
406
+ # pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=result[0]) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
407
+ # _, buffer = cv2.imencode('.png', annotatedimg)
408
  arr=[base64.b64encode(buffer).decode('utf-8') ,pdflink,spreadsheet_url,list1.to_dict(), df_doors.to_dict()]# , spreadsheetId, spreadsheet_url , list1.to_dict()]
409
 
410
  ################################# -2.2- #################################
 
560
  #PIXEL CONVERSION METHOD -- SAVES DOC ON DROPBOX TO BE MEASURED BY USER
561
  @app.route("/pixelimg/<jsdata>",methods=["GET", "POST"])
562
  def getimg(jsdata):
563
+ progress_updates = [] # Shared list to store progress
564
  jsdata=eval(jsdata)
565
+ def generate_progressPixel():
566
+
567
+ yield f"data: 10\n\n" # Initial progress
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568
 
569
+ pdfpath,pdflink=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata[3], progress_callback=lambda p: progress_updates.append(p))
570
+ dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
571
+ md, res =dbxTeam.files_download(path=pdfpath)
572
+ data = res.content
573
+ print('jsdata',jsdata)
574
+ if str(jsdata[2]).startswith('1.0'):
575
+ doc,areaPixel,perimeterPixel=pixelconversion.drawisrotated(data,300) # .openDrawPDF(data)
576
+ else:
577
+ doc,areaPixel,perimeterPixel,pdfdata=pixelconversion.drawisrotated(data) # .openDrawPDF(data)
578
+ yield f"data: 20\n\n" # Initial progress
579
+ dbPath='/TSA JOBS/ADR Test/'+jsdata[0]+'/'+jsdata[1]+'/'+jsdata[2]+'/'+'Scale Document' +'/'
580
+ dburl=tsadropboxretrieval.uploadanyFile(doc=doc,pdfname=str(jsdata[3]) ,path=dbPath)
581
+ # areaPixel,perimeterPixel= pixelconversion.getAreaPerimeter(dbPath, str(jsdata[3]))
582
+ yield f"data: 40\n\n" # Initial progress
583
+ outputs=[areaPixel,perimeterPixel , dburl]
584
+ while progress_updates:
585
+ progress = progress_updates.pop(0) # Get the next progress value
586
+ yield f"data: {progress}\n\n"
587
+ # Final progress and result
588
+ yield f"data: 80\n\n"
589
+ yield f"data: 100\n\n"
590
+ result = json.dumps(outputs)
591
+ yield f"data: {result}\n\n"
592
+
593
+ return Response(generate_progressPixel(), content_type='text/event-stream')
594
  #_________________________________________________________________________________________________________________________
595
  #_________________________________________________________________________________________________________________________
596
  #get sunburst from doc_search
 
656
  # myDict=eval(deletedrows)
657
  deletedrows=pd.DataFrame(deletedrows)
658
  print('deletedrows',deletedrows)
659
+ if section.startswith('2.7'):
660
+ areaPermArr=hatched_areas2_7
661
  if section.startswith('1.0') or section.startswith('3.2') or section.startswith('3.3'):
662
  newlgnd=google_sheet_Legend.deletefromlegend(deletedrows=deletedrows,SimilarAreaDictionarycopy=SimilarAreaDictionary, section=section,areaPermArr=areaPermArr)
663
  elif section.startswith('2.8'):
 
680
  #get pdf dropbox url after measurement is done
681
  @app.route('/getdropboxurl/<jsdata>',methods=["GET", "POST"])
682
  def calldropboxurl(jsdata):
683
+ print('jsdata',jsdata)
684
  pdfurl=tsadropboxretrieval.getPathtoPDF_File(nameofPDF=jsdata)[1]
685
+ print('urll',pdfurl)
686
+ if pdfurl and ('http' in pdfurl or 'dropbox' in pdfurl):
687
+ if 'dl=0' in pdfurl:
688
+ pdfurl = pdfurl.replace('dl=0', 'dl=1')
689
+ print('urll1',pdfurl)
690
+ # Download the PDF content from the shareable link
691
+ response = requests.get(pdfurl)
692
+ pdf_content = BytesIO(response.content) # Store the content in memory
693
+ if pdf_content is None:
694
+ raise ValueError("No valid PDF content found.")
695
+
696
+ # Open the PDF using PyMuPDF
697
+ pdf_document = fitz.open(stream=pdf_content, filetype="pdf")
698
+ pdf_bytes = BytesIO()
699
+ pdf_document.save(pdf_bytes)
700
+ return Response(pdf_bytes.getvalue(), content_type='application/pdf')
701
+
702
+ #_________________________________________________________________________________________________________________________
703
+ #_________________________________________________________________________________________________________________________
704
+
705
+ pdf_content = None
706
+ pageNumTextFound = 0
707
+ BASE_URL = "https://marthee-nbslink.hf.space" # Hugging Face Spaces base URL
708
+
709
+ @app.route("/", methods=["GET", "POST"])
710
+ def thismain():
711
+ print('ayhaga')
712
+ return render_template("gui.html")
713
+
714
+ @app.route('/view-pdf', methods=['GET'])
715
+ def download_pdf():
716
+
717
+ # Manually parse the query parameters
718
+ full_query_string = request.query_string.decode() # Get raw query string
719
+ parsed_params = urllib.parse.parse_qs(full_query_string) # Parse it
720
+
721
+ # Extract pdfLink and keyword manually
722
+ pdf_link = parsed_params.get('pdfLink', [None])[0]
723
+ keyword = parsed_params.get('keyword', [None])[0]
724
+
725
+ if not pdf_link or not keyword:
726
+ return "Missing required parameters.", 400
727
+
728
+ # Decode the extracted values
729
+ pdf_link = urllib.parse.unquote(pdf_link)
730
+ keyword = urllib.parse.unquote(keyword)
731
+
732
+ # If the keyword is a JSON string, convert it back to a list
733
+ try:
734
+ keyword = json.loads(keyword)
735
+ except json.JSONDecodeError:
736
+ keyword = [keyword] # Treat it as a single keyword if not JSON
737
+
738
+ print("Extracted PDF Link:", pdf_link)
739
+ print("Extracted Keywords:", keyword)
740
+ createDF=False
741
+ pdf_content = Find_Hyperlinking_text.annotate_text_from_pdf([pdf_link], keyword)[0]
742
+ if pdf_content is None:
743
+ return "PDF content not found.", 404
744
+
745
+ pdf_bytes = BytesIO(pdf_content)
746
+ return send_file(
747
+ pdf_bytes,
748
+ mimetype='application/pdf',
749
+ as_attachment=False,
750
+ download_name=f"annotated_page_{pageNumTextFound}.pdf"
751
+ )
752
+
753
+ @app.route('/api/process-data', methods=['POST'])
754
+ def receive_pdf_data():
755
+ global pdf_content, pageNumTextFound
756
+
757
+ # Get PDF link and keyword from finddata()
758
+ pdfLink, keyword = finddata()
759
+
760
+ if not pdfLink or not keyword:
761
+ return jsonify({"error": "Both 'pdfLink' and 'keyword' must be provided."}), 400
762
+
763
+ try:
764
+ print(pdfLink, keyword)
765
+
766
+
767
+ pdfbytes, pdf_document , df ,tablepdfoutput= Find_Hyperlinking_text.annotate_text_from_pdf([pdfLink], keyword)
768
+ dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
769
+
770
+ # Get metadata using the shared link
771
+ metadata = dbxTeam.sharing_get_shared_link_metadata(pdfLink)
772
+ dbPath='/TSA JOBS/ADR Test/FIND/'
773
+ pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=metadata.name) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
774
+ print('LINKS0',pdflink)
775
+
776
+ dbPath='/TSA JOBS/ADR Test/FIND/'
777
+ tablepdfLink=tsadropboxretrieval.uploadanyFile(doc=tablepdfoutput,path=dbPath,pdfname=metadata.name.rsplit(".pdf", 1)[0] +' Markup Summary'+'.pdf')
778
+ print(f"PDF successfully uploaded to Dropbox at")
779
+ print('LINKS1',tablepdfLink)
780
+ return jsonify({
781
+ "message": "PDF processed successfully.",
782
+ "PDF_MarkedUp": pdflink,
783
+ 'Table_PDF_Markup_Summary': tablepdfLink
784
+ })
785
+
786
+ except Exception as e:
787
+ return jsonify({"error": str(e)}), 500
788
+
789
+ def finddata():
790
+ pdfLink = 'https://www.dropbox.com/scl/fi/hnp4mqigb51a5kp89kgfa/00801-ARC-20-ZZ-S-A-0002.pdf?rlkey=45abeoebzqw4qwnslnei6dkd6&st=m4yrcjm2&dl=1'
791
+ keyword = ['115 INTEGRATED MRI ROOM LININGS', '310 ACCURACY']
792
+ return pdfLink, keyword
793
+
794
 
795
  #_________________________________________________________________________________________________________________________
796
  #_________________________________________________________________________________________________________________________
797
+
798
  #Google sheet links
799
  @app.route('/getdrivelinks/<jsdata>',methods=["GET", "POST"])
800
  def getlinkscreated(jsdata):
 
892
  if len(differentSections)>0:
893
  returnString=['Changes have been made in Sections. Would you like to retrieve them in the console?','section',differentSections]
894
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
895
  print(returnString)
896
+
 
 
 
897
 
898
  return jsonify(returnString)
899
 
900
  @app.route('/refreshDropbox',methods=["GET", "POST"])
901
  def checkdropbox():
902
  print('checkingggdf')
903
+ dfFromDropbox=tsadropboxretrieval.DropboxItemstoDF("/TSA JOBS")[0]
904
  dfParquet=tsadropboxretrieval.GetParquetDF()
905
 
906
  dfParquet1 = dfParquet[['name', 'path_display', 'client_modified', 'server_modified']]
 
915
  stringReturned= 'Updated Sucessfully.'
916
  else:
917
  stringReturned= 'Nothing to update.'
918
+ return 'stringReturned'
919
+
920
+ def refreshDropboxRetrievals(extractedPath):
921
+ dfFromDropbox = tsadropboxretrieval.DropboxItemstoDF(extractedPath)[0]
922
+ dfParquet = tsadropboxretrieval.GetParquetDF()
923
 
924
+ # print("Original Parquet size:", len(dfParquet))
925
 
926
+ # Keep only relevant columns
927
+ dfParquet = dfParquet[['name', 'path_display', 'client_modified', 'server_modified']]
928
+ dfFromDropbox = dfFromDropbox[['name', 'path_display', 'client_modified', 'server_modified']]
929
+
930
+ # **Drop rows that start with extractedPath**
931
+ dfParquetUpdated = dfParquet[~dfParquet['path_display'].str.startswith(extractedPath)]
932
+
933
+ # **Append new data from Dropbox**
934
+ dfParquetUpdated = pd.concat([dfParquetUpdated, dfFromDropbox], ignore_index=True)
935
 
936
+ # print("Updated Parquet size:", len(dfParquetUpdated),dfParquetUpdated)
937
+
938
+ # **Save the updated Parquet file**
939
+ tsadropboxretrieval.dropbox_upload_file(dfParquetUpdated)
940
+
941
+ if len(dfFromDropbox) > 0:
942
+ print("Updated entries:", dfFromDropbox)
943
+ return 'Updated Successfully.'
944
+ else:
945
+ return 'Nothing to update.'
946
+
947
+
948
+
949
+
950
+
951
+ @app.route('/postdropboxprojects/<path:encoded_path>')
952
+ def handle_path(encoded_path):
953
+ decoded_path = urllib.parse.unquote(encoded_path) # Decode URL encoding
954
+ extracted_path = json.loads(decoded_path) # Convert back to Python object
955
+ print('path to refresh',extracted_path)
956
+ stringReturned=refreshDropboxRetrievals(extracted_path)
957
  print(stringReturned)
958
  return stringReturned
959
 
 
979
  # print(result[1])
980
  xmllink=google_sheet_to_xml.create_xml(documentname=result[1],dbPath=path)
981
  return jsonify(xmllink)
982
+
 
983
 
984
  #_________________________________________________________________________________________________________________________
985
  #_________________________________________________________________________________________________________________________