views.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 os
  9. import json
  10. import re
  11. import base64
  12. path = "/home/bscheibel/app/app"
  13. #path = "/home/centurio/Projects/engineering_drawings_ui/app"
  14. #db_params = "unix_socket_path='/tmp/redis.sock',db=7"
  15. #path_image = "/home/centurio/web/edi2/out"
  16. path_image = "/home/bscheibel/app/app/temporary/out"
  17. db_params = "localhost"
  18. path_extraction = '/home/bscheibel/PycharmProjects/engineering_drawings_extraction/main.py'
  19. #path_extraction = "/home/centurio/Projects/engineering_drawings_extraction/main.py"
  20. UPLOAD_FOLDER = path + "/temporary/"
  21. app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
  22. ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg', 'PDF'])
  23. def allowed_file(filename):
  24. return '.' in filename and \
  25. filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  26. def convert_pdf_img(filename):
  27. PDFFILE = UPLOAD_FOLDER +"/" + filename
  28. subprocess.call(['pdftoppm', '-jpeg', '-singlefile',
  29. PDFFILE, path_image])
  30. def extract_all(uuid, filename, db):
  31. #order_bounding_boxes_in_each_block.main(uuid, UPLOAD_FOLDER + "/" + filename)
  32. subprocess.call(['python3', path_extraction, str(uuid),UPLOAD_FOLDER + "/" + filename, db, str(0)])
  33. def get_file_size(file):
  34. pdf = PyPDF2.PdfFileReader(file)
  35. p = pdf.getPage(0)
  36. w = p.mediaBox.getWidth()
  37. h= p.mediaBox.getHeight()
  38. OrientationDegrees = p.get('/Rotate')
  39. if OrientationDegrees != 0 :
  40. orientation = "landscape"
  41. else:
  42. orientation = "portrait"
  43. print(w,h,OrientationDegrees)
  44. return w,h, orientation
  45. def check_links(isos):
  46. link_names = {}
  47. isos_names = []
  48. isos = list(set(isos))
  49. reg_isos = r"(ISO\s\d*)\s1\-(\d?)"
  50. print(isos)
  51. isos_new = []
  52. for name in isos:
  53. if re.search(reg_isos, name):
  54. n = 1
  55. new_isos = re.search(reg_isos,name).group(1)
  56. number = re.search(reg_isos,name).group(2)
  57. while n <= int(number):
  58. isos_new.append(new_isos+"-"+str(n))
  59. n += 1
  60. else:
  61. isos_new.append(name)
  62. for name in isos_new:
  63. try:
  64. name = name.replace(" ", "")
  65. url1 = name + ".PDF"
  66. #file = send_from_directory("static/isos",url1)
  67. url = "isos/" + url1
  68. link_names[name] = url
  69. except:
  70. isos_names.append(name)
  71. return link_names, isos_names
  72. @app.route('/', methods=['GET', 'POST'])
  73. def upload_file():
  74. if request.method == 'POST':
  75. file = request.files['file']
  76. if file and allowed_file(file.filename):
  77. filename = file.filename
  78. basedir = os.path.abspath(os.path.dirname(__file__))
  79. file.save(os.path.join(basedir,app.config["UPLOAD_FOLDER"], filename))
  80. uuid = random.randint(100,10000000)
  81. extract_all(uuid, filename, db_params)
  82. return redirect(url_for('uploaded_file', filename=filename, uuid=uuid))
  83. return '''
  84. <!doctype html>
  85. <title>Upload new File</title>
  86. <h1>Upload new File</h1>
  87. <form action="" method=post enctype=multipart/form-data>
  88. <p><input type=file name=file>
  89. <input type=submit value=Upload>
  90. </form>
  91. '''
  92. @app.route('/show/<filename>&<uuid>')
  93. def uploaded_file(filename, uuid):
  94. file_out = "out.jpg"
  95. if filename.endswith(".pdf") or filename.endswith(".PDF"):
  96. w,h, orientation = get_file_size(UPLOAD_FOLDER +"/" + filename)
  97. convert_pdf_img(filename)
  98. db = redis.Redis(db_params)
  99. print(db_params)
  100. gen_tol = db.get(str(uuid)+"tol")
  101. print(gen_tol)
  102. isos = json.loads(db.get(str(uuid)+"isos"))
  103. links, isos_names = check_links(isos)
  104. dims = json.loads(db.get(str(uuid)+"dims"))
  105. details = json.loads(db.get(str(uuid) + "details"))
  106. number_blocks = db.get(str(uuid)+"eps")
  107. html_code = "General tolerances according to: " + str(gen_tol) + "<br>"
  108. html_general = ""
  109. reg = r"(-?\d{1,}\.?\d*)"
  110. det_coords= "0,0,0,0"
  111. with open(path +'/static/config.json') as f:
  112. config_file = json.load(f)
  113. print(config_file)
  114. for dim in sorted(dims):
  115. for det in details:
  116. try:
  117. if dim == det:
  118. det_coords = details[det]
  119. det_coords = ",".join(str(det) for det in det_coords)
  120. except:
  121. det_coords = "0,0,0,0"
  122. if "ZZZZ" in dim:
  123. for d in dims[dim]:
  124. html_general += d + "<br>"
  125. continue
  126. else:
  127. html_code += "<td><h4>" + dim + "</h4></td>"
  128. for d in dims[dim]:
  129. relevant_isos = []
  130. search_terms = {}
  131. terms = ''
  132. for conf in config_file:
  133. if re.search(conf,d):
  134. iso = config_file[conf]
  135. for key in iso:
  136. relevant_isos.append(key)
  137. for blub in iso[key]:
  138. search_terms[blub] = iso[key][blub]
  139. if len(search_terms) < 1:
  140. search_terms["Beginn"] = 1
  141. terms = json.dumps(search_terms)
  142. terms = base64.b64encode(terms.encode()).decode('utf-8')
  143. try:
  144. number = re.search(reg, d)
  145. number = number.group(1)
  146. try:
  147. floats = len(number.split(".")[1])
  148. if floats <= 1:
  149. steps = 0.1
  150. elif floats == 2:
  151. steps = 0.01
  152. elif floats == 3:
  153. steps = 0.001
  154. else:
  155. steps = 0.001
  156. except:
  157. steps = 0.1
  158. except:
  159. number = d
  160. steps = 0.1
  161. coords = ",".join(str(e) for e in dims[dim][d])
  162. html_code += "<tr><td style='text-align:center'> <input type='checkbox' name='relevant." + d + "' value='checked'> </td>" + \
  163. "<td style='text-align:center'>" + d + "</td>" + \
  164. "<td max='3' style='text-align:center'> <input type='number' step='" + str(steps) + "' data-coords='" + coords + " 'data-details='" + det_coords +"'' name='" + d + "' value='" + number + "'> </td>"
  165. relevant_isos = list(set(relevant_isos))
  166. for x in relevant_isos:
  167. html_code += "<td style='text-align:left' data-terms='" + terms + "'> <a onclick=ui_add_tab_active('#main','" + x.partition(".")[0] + "','" + x.partition(".")[0] +"',true,'isotab','"+terms+"')>" + x.partition(".")[0] + "</a> </td>"
  168. html_code += "</tr>"
  169. html_links = ""
  170. for link in links:
  171. html_links += "<a onclick =ui_add_tab_active('#main','" + link + "','" + link +"',true,'isotab','empty')> Open " + link + "</a> <br>"
  172. return render_template('index.html', filename=file_out, isos=isos, dims=dims, text=html_code,html_general=html_general, number=number_blocks, og_filename=filename, w=w, h=h, html_links=html_links, isos_names=isos_names, orientation=orientation)
  173. @app.route('/uploads/<filename>')
  174. def send_file(filename):
  175. return send_from_directory(UPLOAD_FOLDER, filename)
  176. @app.after_request
  177. def add_header(response):
  178. response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  179. response.headers['Pragma'] = 'no-cache'
  180. response.headers['Expires'] = '-1'
  181. response.headers['Access-Control-Allow-Origin'] = '*'
  182. response.headers.add("Access-Control-Allow-Headers", "*")
  183. response.headers.add("Access-Control-Allow-Methods", "*")
  184. return response
  185. @app.route('/redis/get/<key>',methods=['GET'])
  186. def redis_get(key):
  187. db = redis.Redis(db_params)
  188. result = json.loads(db.get(key))
  189. return result
  190. @app.route('/redis/set/<key>',methods=['POST'])
  191. def redis_set(key):
  192. value = request.get_json(force=True)
  193. value = value["value"]
  194. db = redis.Redis(db_params)
  195. value_name = value[0]
  196. value_v = value[1]
  197. try:
  198. result = json.loads(db.get(key))
  199. result[value_name] = value_v
  200. json_res = json.dumps(result)
  201. db.set(key,json_res)
  202. except:
  203. dict_res = {}
  204. dict_res[value_name] = value_v
  205. json_dict = json.dumps(dict_res)
  206. db.set(key, json_dict)
  207. return "OK"