views.py 8.5 KB

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