views.py~ 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 base64
  10. import os
  11. import json
  12. import re
  13. import base64
  14. #https://medium.com/@emerico/convert-pdf-to-image-using-python-flask-2864fb655e01
  15. #path = "/home/bscheibel/app/app"
  16. path = "/home/centurio/Projects/engineering_drawings_ui/app"
  17. #path_extraction = '/home/bscheibel/PycharmProjects/dxf_reader/main.py'
  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 + '/temporary/out'])
  29. def extract_all(uuid, filename, db):
  30. #order_bounding_boxes_in_each_block.main(uuid, UPLOAD_FOLDER + "/" + filename)
  31. subprocess.call(['python3', path_extraction, str(uuid),UPLOAD_FOLDER + "/" + filename, db, str(0)])
  32. def get_file_size(file):
  33. pdf = PyPDF2.PdfFileReader(file)
  34. p = pdf.getPage(0)
  35. w = p.mediaBox.getWidth()
  36. h= p.mediaBox.getHeight()
  37. OrientationDegrees = p.get('/Rotate')
  38. if OrientationDegrees != 0 :
  39. orientation = "landscape"
  40. else:
  41. orientation = "portrait"
  42. print(w,h,OrientationDegrees)
  43. return w,h, orientation
  44. def check_config_file(d):
  45. reg_search = d
  46. #print(reg_search)
  47. for conf in d:
  48. print(conf)
  49. return "blub"
  50. def check_links(isos):
  51. link_names = {}
  52. isos_names = []
  53. isos = list(set(isos))
  54. reg_isos = r"(ISO\s\d*)\s1\-(\d?)"
  55. print(isos)
  56. isos_new = []
  57. for name in isos:
  58. if re.search(reg_isos, name):
  59. n = 1
  60. #print(name)
  61. new_isos = re.search(reg_isos,name).group(1)
  62. number = re.search(reg_isos,name).group(2)
  63. while n <= int(number):
  64. isos_new.append(new_isos+"-"+str(n))
  65. n += 1
  66. else:
  67. isos_new.append(name)
  68. for name in isos_new:
  69. try:
  70. name = name.replace(" ", "")
  71. #name = name.replace("-"," ")
  72. url1 = name + ".PDF"
  73. #print(url)
  74. file = send_from_directory("static/isos",url1)
  75. url = "isos/" + url1
  76. #link_names.append(url)
  77. link_names[name] = url
  78. #print(link_names)
  79. except:
  80. #print(name)
  81. isos_names.append(name)
  82. return link_names, isos_names
  83. @app.route('/', methods=['GET', 'POST'])
  84. def upload_file():
  85. if request.method == 'POST':
  86. file = request.files['file']
  87. if file and allowed_file(file.filename):
  88. filename = file.filename
  89. basedir = os.path.abspath(os.path.dirname(__file__))
  90. file.save(os.path.join(basedir,app.config["UPLOAD_FOLDER"], filename))
  91. uuid = random.randint(100,10000000)
  92. extract_all(uuid, filename, 'localhost')
  93. return redirect(url_for('uploaded_file', filename=filename, uuid=uuid))
  94. return '''
  95. <!doctype html>
  96. <title>Upload new File</title>
  97. <h1>Upload new File</h1>
  98. <form action="" method=post enctype=multipart/form-data>
  99. <p><input type=file name=file>
  100. <input type=submit value=Upload>
  101. </form>
  102. '''
  103. @app.route('/show/<filename>&<uuid>')
  104. def uploaded_file(filename, uuid):
  105. file_out = "out.jpg"
  106. #file_out = filename
  107. #if request.method == 'POST':
  108. # uuid = 433
  109. if filename.endswith(".pdf") or filename.endswith(".PDF"):
  110. w,h, orientation = get_file_size(UPLOAD_FOLDER +"/" + filename)
  111. convert_pdf_img(filename)
  112. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  113. #db = redis.Redis("unix_socket_path='127.0.0.1',6379,db=7")
  114. #isos = db.get(uuid+"dims")
  115. #print(iso)
  116. gen_tol = db.get(str(uuid)+"tol")
  117. print(gen_tol)
  118. isos = json.loads(db.get(str(uuid)+"isos"))
  119. links, isos_names = check_links(isos)
  120. dims = json.loads(db.get(str(uuid)+"dims"))
  121. details = json.loads(db.get(str(uuid) + "details"))
  122. number_blocks = db.get(str(uuid)+"eps")
  123. html_code = "General tolerances according to: " + str(gen_tol) + "<br>"
  124. html_general = ""
  125. reg = r"(-?\d{1,}\.?\d*)"
  126. #re_gewinde = r"M\d{1,2}"
  127. #re_passungen = r"h\d{1,2}|H\d{1,2}"
  128. det_coords= "0,0,0,0"
  129. with open(path+ '/config.json') as f:
  130. config_file = json.load(f)
  131. for dim in sorted(dims):
  132. #print(dim)
  133. for det in details:
  134. #print(det)
  135. try:
  136. if dim == det:
  137. det_coords = details[det]
  138. det_coords = ",".join(str(det) for det in det_coords)
  139. except:
  140. det_coords = "0,0,0,0"
  141. if "ZZZZ" in dim:
  142. for d in dims[dim]:
  143. html_general += d + "<br>"
  144. continue
  145. else:
  146. html_code += "<td><h4>" + dim + "</h4></td>"
  147. for d in dims[dim]:
  148. relevant_isos = []
  149. search_terms = {}
  150. terms = ''
  151. #if "Ra" in d or "Rz" in d or "Rpk" in d:
  152. # relevant_isos.append("ISO4287.PDF")
  153. #if u"\u27C2" in d or u"\u25CE" in d or u"\u232D" in d or u"\u2225" in d or u"\u232F" in d or u"\u2316" in d or u"\u2313" in d or u"\u23E5" in d:
  154. # relevant_isos.append("ISO1101.PDF")
  155. #if re.search(re_gewinde,d):
  156. # relevant_isos.append("ISO6410.PDF")
  157. #if "GG" in d or "CT" in d or "GX" in d:
  158. # relevant_isos.append("ISO14405-1.PDF")
  159. #if re.search(re_passungen,d):
  160. # relevant_isos.append("ISO286-1.PDF")
  161. for conf in config_file:
  162. if re.search(conf,d):
  163. iso = config_file[conf]
  164. for key in iso:
  165. relevant_isos.append(key)
  166. for blub in iso[key]:
  167. search_terms[blub] = iso[key][blub]
  168. #terms = '{"Symbole":1,"Tabelle":2,"Definition":3}'
  169. if len(search_terms) < 1:
  170. search_terms["Beginn"] = 1
  171. terms = json.dumps(search_terms)
  172. #print(terms)
  173. terms = base64.b64encode(terms.encode())
  174. #terms = "blub"
  175. try:
  176. number = re.search(reg, d)
  177. number = number.group(1)
  178. try:
  179. floats = len(number.split(".")[1])
  180. if floats <= 1:
  181. steps = 0.1
  182. elif floats == 2:
  183. steps = 0.01
  184. elif floats == 3:
  185. steps = 0.001
  186. else:
  187. steps = 0.001
  188. except:
  189. steps = 0.1
  190. except:
  191. number = d
  192. steps = 0.1
  193. coords = ",".join(str(e) for e in dims[dim][d])
  194. html_code += "<tr><td style='text-align:center'> <input type='checkbox' name='relevant." + d + "' value='checked'> </td>" + \
  195. "<td style='text-align:center'>" + d + "</td>" + \
  196. "<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>"
  197. relevant_isos = list(set(relevant_isos))
  198. for x in relevant_isos:
  199. #html_code += "<td style='text-align:left'> <a href=" + url_for('static', filename="isos/"+x) + " >"+ x.partition(".")[0] +"</a> </td>"
  200. 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>"
  201. #print(html_code)
  202. html_code += "</tr>"
  203. html_links = ""
  204. for link in links:
  205. html_links += "<a onclick =ui_add_tab_active('#main','" + link + "','" + link +"',true,'isotab','empty')> Open " + link + "</a> <br>"
  206. #html_links += "<tr> <td> <a onclick =ui_add_tab_active('#main','iso1','iso1',true,'isotab')> Open " + link + " in Tab </a> </td> </tr>"""
  207. #print("teeest")
  208. 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)
  209. #return render_template('test_pdfjs_textlayer.html', og_filename=filename)
  210. #else:
  211. # filename = filename
  212. # return render_template('show_image.html', filename=filename)
  213. @app.route('/uploads/<filename>')
  214. def send_file(filename):
  215. return send_from_directory(UPLOAD_FOLDER, filename)
  216. # No caching at all for API endpoints.
  217. @app.after_request
  218. def add_header(response):
  219. # response.cache_control.no_store = True
  220. response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  221. response.headers['Pragma'] = 'no-cache'
  222. response.headers['Expires'] = '-1'
  223. response.headers['Access-Control-Allow-Origin'] = '*'
  224. response.headers.add("Access-Control-Allow-Headers", "*")
  225. response.headers.add("Access-Control-Allow-Methods", "*")
  226. return response
  227. @app.route('/redis/get/<key>',methods=['GET'])
  228. def redis_get(key):
  229. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  230. result = json.loads(db.get(key))
  231. return result
  232. @app.route('/redis/set/<key>',methods=['POST'])
  233. def redis_set(key):
  234. value = request.get_json(force=True)
  235. value = value["value"]
  236. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  237. value_name = value[0]
  238. value_v = value[1]
  239. try:
  240. result = json.loads(db.get(key))
  241. result[value_name] = value_v
  242. json_res = json.dumps(result)
  243. db.set(key,json_res)
  244. except:
  245. dict_res = {}
  246. dict_res[value_name] = value_v
  247. json_dict = json.dumps(dict_res)
  248. db.set(key, json_dict)
  249. return "OK"
  250. @app.route('/index')
  251. def test():
  252. return render_template('index.html')