views.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #encoding
  2. from app import app
  3. from flask import request, redirect, url_for, send_from_directory, render_template
  4. import subprocess
  5. import redis
  6. import random
  7. import PyPDF2
  8. import json
  9. import os
  10. import json
  11. import re
  12. import base64
  13. #https://medium.com/@emerico/convert-pdf-to-image-using-python-flask-2864fb655e01
  14. UPLOAD_FOLDER = "/home/bscheibel/app/app/temporary"
  15. app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
  16. ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg', 'PDF'])
  17. def allowed_file(filename):
  18. return '.' in filename and \
  19. filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  20. def convert_pdf_img(filename):
  21. PDFFILE = UPLOAD_FOLDER +"/" + filename
  22. subprocess.call(['pdftoppm', '-jpeg', '-singlefile',
  23. PDFFILE, '/home/bscheibel//app/app/temporary/out'])
  24. def extract_all(uuid, filename, db):
  25. #order_bounding_boxes_in_each_block.main(uuid, UPLOAD_FOLDER + "/" + filename)
  26. subprocess.call(['python3','/home/bscheibel/PycharmProjects/dxf_reader/main.py', str(uuid),UPLOAD_FOLDER + "/" + filename, db, str(0)])
  27. def get_file_size(file):
  28. pdf = PyPDF2.PdfFileReader(file)
  29. p = pdf.getPage(0)
  30. w = p.mediaBox.getWidth()
  31. h= p.mediaBox.getHeight()
  32. print(w,h)
  33. return w,h
  34. def check_links(isos):
  35. link_names = {}
  36. for name in isos:
  37. try:
  38. name = name.replace(" ", "")
  39. url1 = name + ".PDF"
  40. #print(url)
  41. file = send_from_directory("static/isos",url1)
  42. url = "isos/" + url1
  43. #link_names.append(url)
  44. link_names[url1] = url
  45. print(link_names)
  46. except:
  47. print("Sorry file not found")
  48. return link_names
  49. @app.route('/', methods=['GET', 'POST'])
  50. def upload_file():
  51. if request.method == 'POST':
  52. file = request.files['file']
  53. if file and allowed_file(file.filename):
  54. filename = file.filename
  55. basedir = os.path.abspath(os.path.dirname(__file__))
  56. file.save(os.path.join(basedir,app.config["UPLOAD_FOLDER"], filename))
  57. uuid = random.randint(100,10000000)
  58. extract_all(uuid, filename, 'localhost')
  59. return redirect(url_for('uploaded_file', filename=filename, uuid=uuid))
  60. return '''
  61. <!doctype html>
  62. <title>Upload new File</title>
  63. <h1>Upload new File</h1>
  64. <form action="" method=post enctype=multipart/form-data>
  65. <p><input type=file name=file>
  66. <input type=submit value=Upload>
  67. </form>
  68. '''
  69. @app.route('/show/<filename>&<uuid>')
  70. def uploaded_file(filename, uuid):
  71. file_out = "out.jpg"
  72. #file_out = filename
  73. #if request.method == 'POST':
  74. # uuid = 433
  75. if filename.endswith(".pdf") or filename.endswith(".PDF"):
  76. w,h = get_file_size(UPLOAD_FOLDER +"/" + filename)
  77. convert_pdf_img(filename)
  78. db = redis.Redis("localhost")
  79. #isos = db.get(uuid+"dims")
  80. #print(iso)
  81. isos = json.loads(db.get(str(uuid)+"isos"))
  82. links = check_links(isos)
  83. dims = json.loads(db.get(str(uuid)+"dims"))
  84. details = json.loads(db.get(str(uuid) + "details"))
  85. number_blocks = db.get(str(uuid)+"eps")
  86. html_code = ""
  87. reg = r"(-?\d{1,}\.?\d*)"
  88. for dim in dims:
  89. print(dim)
  90. for det in details:
  91. print(det)
  92. try:
  93. if dim == det:
  94. det_coords = details[det]
  95. det_coords = ",".join(str(det) for det in det_coords)
  96. except:
  97. det_coords = "0"
  98. html_code += "<td><h4>" + dim + "</h4></td>"
  99. for d in dims[dim]:
  100. try:
  101. number = re.search(reg, d)
  102. number = number.group(1)
  103. try:
  104. floats = len(number.split(".")[1])
  105. if floats <= 1:
  106. steps = 0.1
  107. elif floats == 2:
  108. steps = 0.01
  109. elif floats == 3:
  110. steps = 0.001
  111. else:
  112. steps = 0.001
  113. except:
  114. steps = 0.1
  115. except:
  116. number = d
  117. steps = 0.1
  118. coords = ",".join(str(e) for e in dims[dim][d])
  119. html_code += "<tr><td style='text-align:center'> <input type='checkbox' name='relevant." + d + "' value='checked'> </td>" + \
  120. "<td style='text-align:center'>" + d + "</td>" + \
  121. "<td style='text-align:center'> <input type='number' step='" + str(steps) + "' data-coords='" + coords + " 'data-details='" + det_coords +"'' name='" + d + "' value='" + number + "' size='10'> </td></tr>"
  122. #print(html_code)
  123. return render_template('show_image_old_working.html', filename=file_out, isos=isos, dims=dims, text=html_code, number=number_blocks, og_filename=filename, w=w, h=h, links=links)
  124. else:
  125. filename = filename
  126. return render_template('show_image.html', filename=filename)
  127. @app.route('/uploads/<filename>')
  128. def send_file(filename):
  129. return send_from_directory(UPLOAD_FOLDER, filename)
  130. # No caching at all for API endpoints.
  131. @app.after_request
  132. def add_header(response):
  133. # response.cache_control.no_store = True
  134. response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  135. response.headers['Pragma'] = 'no-cache'
  136. response.headers['Expires'] = '-1'
  137. response.headers['Access-Control-Allow-Origin'] = '*'
  138. response.headers.add("Access-Control-Allow-Headers", "*")
  139. response.headers.add("Access-Control-Allow-Methods", "*")
  140. return response
  141. @app.route('/redis/get/<key>',methods=['GET'])
  142. def redis_get(key):
  143. db = redis.Redis("localhost")
  144. result = json.loads(db.get(key))
  145. return result
  146. @app.route('/redis/set/<key>',methods=['POST'])
  147. def redis_set(key):
  148. value = request.get_json(force=True)
  149. value = value["value"]
  150. db = redis.Redis("localhost")
  151. value_name = value[0]
  152. value_v = value[1]
  153. try:
  154. result = json.loads(db.get(key))
  155. result[value_name] = value_v
  156. json_res = json.dumps(result)
  157. db.set(key,json_res)
  158. except:
  159. dict_res = {}
  160. dict_res[value_name] = value_v
  161. json_dict = json.dumps(dict_res)
  162. db.set(key, json_dict)
  163. return "OK"