views.py 10 KB

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