views.py~ 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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, '/edi2/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 +'/static/config.json') as f:
  130. config_file = json.load(f)
  131. print(config_file)
  132. for dim in sorted(dims):
  133. #print(dim)
  134. for det in details:
  135. #print(det)
  136. try:
  137. if dim == det:
  138. det_coords = details[det]
  139. det_coords = ",".join(str(det) for det in det_coords)
  140. except:
  141. det_coords = "0,0,0,0"
  142. if "ZZZZ" in dim:
  143. for d in dims[dim]:
  144. html_general += d + "<br>"
  145. continue
  146. else:
  147. html_code += "<td><h4>" + dim + "</h4></td>"
  148. for d in dims[dim]:
  149. relevant_isos = []
  150. search_terms = {}
  151. terms = ''
  152. #if "Ra" in d or "Rz" in d or "Rpk" in d:
  153. # relevant_isos.append("ISO4287.PDF")
  154. #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:
  155. # relevant_isos.append("ISO1101.PDF")
  156. #if re.search(re_gewinde,d):
  157. # relevant_isos.append("ISO6410.PDF")
  158. #if "GG" in d or "CT" in d or "GX" in d:
  159. # relevant_isos.append("ISO14405-1.PDF")
  160. #if re.search(re_passungen,d):
  161. # relevant_isos.append("ISO286-1.PDF")
  162. for conf in config_file:
  163. if re.search(conf,d):
  164. iso = config_file[conf]
  165. for key in iso:
  166. relevant_isos.append(key)
  167. for blub in iso[key]:
  168. search_terms[blub] = iso[key][blub]
  169. #terms = '{"Symbole":1,"Tabelle":2,"Definition":3}'
  170. if len(search_terms) < 1:
  171. search_terms["Beginn"] = 1
  172. terms = json.dumps(search_terms)
  173. #print(terms)
  174. terms = base64.b64encode(terms.encode()).decode('utf-8')
  175. #terms = "blub"
  176. try:
  177. number = re.search(reg, d)
  178. number = number.group(1)
  179. try:
  180. floats = len(number.split(".")[1])
  181. if floats <= 1:
  182. steps = 0.1
  183. elif floats == 2:
  184. steps = 0.01
  185. elif floats == 3:
  186. steps = 0.001
  187. else:
  188. steps = 0.001
  189. except:
  190. steps = 0.1
  191. except:
  192. number = d
  193. steps = 0.1
  194. coords = ",".join(str(e) for e in dims[dim][d])
  195. html_code += "<tr><td style='text-align:center'> <input type='checkbox' name='relevant." + d + "' value='checked'> </td>" + \
  196. "<td style='text-align:center'>" + d + "</td>" + \
  197. "<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>"
  198. relevant_isos = list(set(relevant_isos))
  199. for x in relevant_isos:
  200. #html_code += "<td style='text-align:left'> <a href=" + url_for('static', filename="isos/"+x) + " >"+ x.partition(".")[0] +"</a> </td>"
  201. 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>"
  202. #print(html_code)
  203. html_code += "</tr>"
  204. html_links = ""
  205. for link in links:
  206. html_links += "<a onclick =ui_add_tab_active('#main','" + link + "','" + link +"',true,'isotab','empty')> Open " + link + "</a> <br>"
  207. #html_links += "<tr> <td> <a onclick =ui_add_tab_active('#main','iso1','iso1',true,'isotab')> Open " + link + " in Tab </a> </td> </tr>"""
  208. #print("teeest")
  209. 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)
  210. #return render_template('test_pdfjs_textlayer.html', og_filename=filename)
  211. #else:
  212. # filename = filename
  213. # return render_template('show_image.html', filename=filename)
  214. @app.route('/uploads/<filename>')
  215. def send_file(filename):
  216. return send_from_directory(UPLOAD_FOLDER, filename)
  217. # No caching at all for API endpoints.
  218. @app.after_request
  219. def add_header(response):
  220. # response.cache_control.no_store = True
  221. response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
  222. response.headers['Pragma'] = 'no-cache'
  223. response.headers['Expires'] = '-1'
  224. response.headers['Access-Control-Allow-Origin'] = '*'
  225. response.headers.add("Access-Control-Allow-Headers", "*")
  226. response.headers.add("Access-Control-Allow-Methods", "*")
  227. return response
  228. @app.route('/redis/get/<key>',methods=['GET'])
  229. def redis_get(key):
  230. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  231. result = json.loads(db.get(key))
  232. return result
  233. @app.route('/redis/set/<key>',methods=['POST'])
  234. def redis_set(key):
  235. value = request.get_json(force=True)
  236. value = value["value"]
  237. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  238. value_name = value[0]
  239. value_v = value[1]
  240. try:
  241. result = json.loads(db.get(key))
  242. result[value_name] = value_v
  243. json_res = json.dumps(result)
  244. db.set(key,json_res)
  245. except:
  246. dict_res = {}
  247. dict_res[value_name] = value_v
  248. json_dict = json.dumps(dict_res)
  249. db.set(key, json_dict)
  250. return "OK"
  251. @app.route('/index')
  252. def test():
  253. return render_template('index.html')