views.py 10 KB

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