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. #path = "/home/bscheibel/app/app"
  15. path = "/home/centurio/Projects/engineering_drawings_ui/app"
  16. #path_extraction = '/home/bscheibel/PycharmProjects/dxf_reader/main.py'
  17. path_extraction = "/home/centurio/Projects/engineering_drawings_extraction/main.py"
  18. UPLOAD_FOLDER = path + "/temporary/"
  19. app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
  20. ALLOWED_EXTENSIONS = set(['pdf', 'png', 'jpg', 'jpeg', 'PDF'])
  21. def allowed_file(filename):
  22. return '.' in filename and \
  23. filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
  24. def convert_pdf_img(filename):
  25. PDFFILE = UPLOAD_FOLDER +"/" + filename
  26. subprocess.call(['pdftoppm', '-jpeg', '-singlefile',
  27. PDFFILE, '/home/centurio/web/edi2/out'])
  28. def extract_all(uuid, filename, db):
  29. #order_bounding_boxes_in_each_block.main(uuid, UPLOAD_FOLDER + "/" + filename)
  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. OrientationDegrees = p.get('/Rotate')
  37. if OrientationDegrees != 0 :
  38. orientation = "landscape"
  39. else:
  40. orientation = "portrait"
  41. print(w,h,OrientationDegrees)
  42. return w,h, orientation
  43. def check_config_file(d):
  44. reg_search = d
  45. #print(reg_search)
  46. for conf in d:
  47. print(conf)
  48. return "blub"
  49. def check_links(isos):
  50. link_names = {}
  51. isos_names = []
  52. isos = list(set(isos))
  53. reg_isos = r"(ISO\s\d*)\s1\-(\d?)"
  54. print(isos)
  55. isos_new = []
  56. for name in isos:
  57. if re.search(reg_isos, name):
  58. n = 1
  59. #print(name)
  60. new_isos = re.search(reg_isos,name).group(1)
  61. number = re.search(reg_isos,name).group(2)
  62. while n <= int(number):
  63. isos_new.append(new_isos+"-"+str(n))
  64. n += 1
  65. else:
  66. isos_new.append(name)
  67. for name in isos_new:
  68. try:
  69. name = name.replace(" ", "")
  70. #name = name.replace("-"," ")
  71. url1 = name + ".PDF"
  72. #print(url)
  73. file = send_from_directory("static/isos",url1)
  74. url = "isos/" + url1
  75. #link_names.append(url)
  76. link_names[name] = url
  77. #print(link_names)
  78. except:
  79. #print(name)
  80. isos_names.append(name)
  81. return link_names, isos_names
  82. @app.route('/', methods=['GET', 'POST'])
  83. def upload_file():
  84. if request.method == 'POST':
  85. file = request.files['file']
  86. if file and allowed_file(file.filename):
  87. filename = file.filename
  88. basedir = os.path.abspath(os.path.dirname(__file__))
  89. file.save(os.path.join(basedir,app.config["UPLOAD_FOLDER"], filename))
  90. uuid = random.randint(100,10000000)
  91. extract_all(uuid, filename, 'localhost')
  92. return redirect(url_for('uploaded_file', filename=filename, uuid=uuid))
  93. return '''
  94. <!doctype html>
  95. <title>Upload new File</title>
  96. <h1>Upload new File</h1>
  97. <form action="" method=post enctype=multipart/form-data>
  98. <p><input type=file name=file>
  99. <input type=submit value=Upload>
  100. </form>
  101. '''
  102. @app.route('/show/<filename>&<uuid>')
  103. def uploaded_file(filename, uuid):
  104. file_out = "out.jpg"
  105. #file_out = filename
  106. #if request.method == 'POST':
  107. # uuid = 433
  108. if filename.endswith(".pdf") or filename.endswith(".PDF"):
  109. w,h, orientation = get_file_size(UPLOAD_FOLDER +"/" + filename)
  110. convert_pdf_img(filename)
  111. db = redis.Redis(unix_socket_path='/tmp/redis.sock',db=7)
  112. #db = redis.Redis("unix_socket_path='127.0.0.1',6379,db=7")
  113. #isos = db.get(uuid+"dims")
  114. #print(iso)
  115. gen_tol = db.get(str(uuid)+"tol")
  116. print(gen_tol)
  117. isos = json.loads(db.get(str(uuid)+"isos"))
  118. links, isos_names = check_links(isos)
  119. dims = json.loads(db.get(str(uuid)+"dims"))
  120. details = json.loads(db.get(str(uuid) + "details"))
  121. number_blocks = db.get(str(uuid)+"eps")
  122. html_code = "General tolerances according to: " + str(gen_tol) + "<br>"
  123. html_general = ""
  124. reg = r"(-?\d{1,}\.?\d*)"
  125. #re_gewinde = r"M\d{1,2}"
  126. #re_passungen = r"h\d{1,2}|H\d{1,2}"
  127. det_coords= "0,0,0,0"
  128. with open(path +'/static/config.json') as f:
  129. config_file = json.load(f)
  130. print(config_file)
  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()).decode('utf-8')
  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')