Spaces:
Sleeping
Sleeping
File size: 13,103 Bytes
dca8e8f e72ad57 dca8e8f 33e722c dca8e8f b87c24f dca8e8f ef850dc dca8e8f b87c24f dca8e8f b87c24f dca8e8f ef850dc dca8e8f d19d78e ce2c42f dca8e8f 820b0b1 ce2c42f b87c24f dca8e8f 3b804ce dca8e8f 3b804ce dca8e8f 1756c04 fca93e8 1756c04 1c729d5 6339e12 1756c04 6339e12 dca8e8f 3b804ce dca8e8f 3b804ce dca8e8f b87c24f dca8e8f 9d35b62 dca8e8f 9d35b62 dca8e8f fd4cb96 9933281 dca8e8f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
from flask import Flask, request, jsonify, abort , render_template , send_file
import tsadropboxretrieval
import json
import Find_Hyperlinking_text
import findspecsv1
import InitialMarkups
import requests
from io import BytesIO
import datetime
import time
from threading import Thread
import urllib
from urllib.parse import quote
app = Flask(__name__)
pageNumTextFound = 0
BASE_URL = "https://findconsole-initialmarkups2.hf.space"
# Simulate a backend readiness flag (replace with actual check if possible)
backend_ready = False
# @app.route("/")
# def thismain():
# print('Home page loaded')
# return render_template("gui.html")
@app.route("/keepaliveapii", methods=["GET", "POST"])
def keepaliveapi():
try:
print('Keepalive pinged')
return 'alivee'
except Exception as error:
print('Error in keepalive:', error)
return jsonify(status="error", message=str(error)), 500
@app.route("/")
def home():
global backend_ready
# If backend not ready, show loading page
if not backend_ready:
return render_template("wake_and_redirect.html")
else:
# Redirect to your PDF viewer route when ready
return redirect(url_for("view_pdf", **request.args))
################################################################################################################################################################
################################################################################################################################################################
##################### Main console ###########################################################################################################
################################################################################################################################################################
################################################################################################################################################################
@app.route('/view-pdf', methods=['GET'])
def download_pdf():
# Parse and decode pdfLink safely
full_query_string = request.query_string.decode()
parsed_params = urllib.parse.parse_qs(full_query_string)
encoded_pdf_link = parsed_params.get('pdfLink', [None])[0]
if not encoded_pdf_link:
return "Missing pdfLink parameter.", 400
# Decode the URL-encoded PDF link
pdf_link = urllib.parse.unquote(encoded_pdf_link)
print("Extracted PDF Link:", pdf_link)
try:
# Use InitialMarkups to extract content
pdf_content = InitialMarkups.extract_section_under_header(pdf_link)[0]
except Exception as e:
print("Error during PDF extraction:", e)
return "PDF could not be processed.", 500
if pdf_content is None or not pdf_content.startswith(b"%PDF"):
return "PDF content not found or broken.", 404
pdf_bytes = BytesIO(pdf_content)
return send_file(
pdf_bytes,
mimetype='application/pdf',
as_attachment=False,
download_name=f"annotated_page_{pageNumTextFound}.pdf"
)
@app.route('/api/process-data', methods=['POST'])
def receive_pdf_data():
global pdf_content, pageNumTextFound
# Get PDF link and keyword from finddata()
pdfLink = finddata()
if not pdfLink :
return jsonify({"error": "'pdfLink' must be provided."}), 400
try:
print(pdfLink)
pdfbytes, pdf_document,tablepdfoutput= InitialMarkups.extract_section_under_header(pdfLink)
dbxTeam= tsadropboxretrieval.ADR_Access_DropboxTeam('user')
# Get metadata using the shared link
metadata = dbxTeam.sharing_get_shared_link_metadata(pdfLink)
dbPath='/TSA JOBS/ADR Test/FIND/'
pdflink= tsadropboxretrieval.uploadanyFile(doc=pdf_document,path=dbPath,pdfname=metadata.name) #doc=doc,pdfname=path,pdfpath=pdfpath+'Measured Plan/
print('LINKS0',pdflink)
dbPath='/TSA JOBS/ADR Test/FIND/'
tablepdfLink=tsadropboxretrieval.uploadanyFile(doc=tablepdfoutput,path=dbPath,pdfname=metadata.name.rsplit(".pdf", 1)[0] +' Markup Summary'+'.pdf')
print(f"PDF successfully uploaded to Dropbox at")
print('LINKS1',tablepdfLink)
return jsonify({
"message": "PDF processed successfully.",
"PDF_MarkedUp": pdflink,
'Table_PDF_Markup_Summary': tablepdfLink
})
except Exception as e:
return jsonify({"error": str(e)}), 500
################################################################################################################################################################
################################################################################################################################################################
##################### Not to billed not markuped up ###########################################################################################################
################################################################################################################################################################
################################################################################################################################################################
@app.route('/findapitobebilled1', methods=['GET','POST'])
def findapitobebilled1():
try:
print('In process [Try]')
data = request.get_json()
# Extracting values
pdfLink = data.get('filePath')
pdfbytes, pdf_document,tablepdfoutput, alltext_tobebilled= InitialMarkups.extract_section_under_header_tobebilledOnly(pdfLink)
return jsonify(alltext_tobebilled)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/view-pdf-tobebilled', methods=['GET'])
def download_pdf_tobebilled():
# Parse and decode pdfLink safely
full_query_string = request.query_string.decode()
parsed_params = urllib.parse.parse_qs(full_query_string)
encoded_pdf_link = parsed_params.get('pdfLink', [None])[0]
if not encoded_pdf_link:
return "Missing pdfLink parameter.", 400
# Decode the URL-encoded PDF link
pdf_link = urllib.parse.unquote(encoded_pdf_link)
print("Extracted PDF Link:", pdf_link)
try:
# Use InitialMarkups to extract content
pdf_content = InitialMarkups.extract_section_under_header_tobebilledOnly(pdf_link)[0]
except Exception as e:
print("Error during PDF extraction:", e)
return "PDF could not be processed.", 500
if pdf_content is None or not pdf_content.startswith(b"%PDF"):
return "PDF content not found or broken.", 404
pdf_bytes = BytesIO(pdf_content)
return send_file(
pdf_bytes,
mimetype='application/pdf',
as_attachment=False,
download_name=f"annotated_page_{pageNumTextFound}.pdf"
)
################################################################################################################################################################
################################################################################################################################################################
##################### For final markups - view one highlight at a time - not used yet ###########################################################################################################
################################################################################################################################################################
################################################################################################################################################################
@app.route('/view-highlight', methods=['GET','POST'])
def download_pdfHighlight():
# Manually parse the query parameters
full_query_string = request.query_string.decode() # Get raw query string
parsed_params = urllib.parse.parse_qs(full_query_string) # Parse it
# Extract pdfLink and keyword manually
pdf_link = parsed_params.get('pdfLink', [None])[0]
keyword = parsed_params.get('keyword', [None])[0]
# linktoreplace = [listofheadingsfromrawan["Link"]]
if not pdf_link :
return "Missing required parameters.", 400
# Decode the extracted values
pdf_link = urllib.parse.unquote(pdf_link)
print("Extracted PDF Link:", pdf_link)
print("Extracted Keywords:", keyword)
createDF=False
global jsonoutput
matching_item = next((item for item in jsonoutput if item.get("Subject") == keyword), None)
if matching_item:
page_number = int(matching_item.get("Page"))-1
stringtowrite = matching_item.get("head above 1")
print(f"Page number for '{keyword}': {page_number}")
else:
page_number=0
print("No match found.")
pdf_content = InitialMarkups.extract_section_under_headerRawan(pdf_link,keyword,page_number,stringtowrite)[0]
if pdf_content is None:
return "PDF content not found.", 404
pdf_bytes = BytesIO(pdf_content)
return send_file(
pdf_bytes,
mimetype='application/pdf',
as_attachment=False,
download_name=f"annotated_page_{pageNumTextFound}.pdf"
)
@app.route('/findapiFilteredHeadings', methods=['GET','POST'])
def findapiFilteredHeadings():
try:
print('In process [Try]')
data = request.get_json()
# Extracting values
pdfLink = data.get('filePath')
print(pdfLink)
listofheadings = data.get('listofheadings') #in json format
print(listofheadings)
pdfbytes, pdf_document,tablepdfoutput,alltext= InitialMarkups.extract_section_under_headerRawan(pdfLink,listofheadings)
global jsonoutput
jsonoutput=tablepdfoutput
return jsonify(alltext)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route('/findapiAllDocNoNotbilled', methods=['GET','POST'])
def findapiAllDocNoNotbilled():
try:
print('In process [Try]')
data = request.get_json()
# Extracting values
pdfLink = data.get('filePath')
print(pdfLink)
pdfbytes, pdf_document,tablepdfoutput, alltext_tobebilled,alltextNoNotbilled= InitialMarkups.extract_section_under_header_tobebilledOnly(pdfLink)
return jsonify(alltextNoNotbilled)
except Exception as e:
return jsonify({"error": str(e)}), 500
################################################################################################################################################################
################################################################################################################################################################
##################### For Rawan - MC Connection ###########################################################################################################
################################################################################################################################################################
################################################################################################################################################################
@app.route('/findapi', methods=['GET','POST'])
def findapi():
try:
print('In process [Try]')
data = request.get_json()
# Extracting values
pdfLink = data.get('filePath')
pdfbytes, pdf_document,tablepdfoutput= InitialMarkups.extract_section_under_header(pdfLink)
global jsonoutput
jsonoutput=tablepdfoutput
return jsonify(tablepdfoutput)
except Exception as e:
return jsonify({"error": str(e)}), 500
############################################# Testing #################################################
def finddata():
pdfLink = 'https://www.dropbox.com/scl/fi/hnp4mqigb51a5kp89kgfa/00801-ARC-20-ZZ-S-A-0002.pdf?rlkey=45abeoebzqw4qwnslnei6dkd6&st=m4yrcjm2&dl=1'
keyword = ['115 INTEGRATED MRI ROOM LININGS', '310 ACCURACY']
return pdfLink, keyword
########################################### Running #####################################################
#_________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________
#_________________________________________________________________________________________________________________________
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)
|