com.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from flask import Blueprint, views, render_template, request
  2. from utils.util import *
  3. from utils.conf import MAX_CONTENT_LENGTH
  4. com = Blueprint("com", __name__, url_prefix="/com")
  5. class ComView(views.MethodView):
  6. @staticmethod
  7. def get():
  8. return render_template("com_index.html")
  9. @staticmethod
  10. def post():
  11. pic = request.files.get("picture")
  12. if pic is None:
  13. return Response("empty body")
  14. ext = get_ext_name(pic.filename)
  15. if not is_image_ext(ext):
  16. return Response("文件类型错误")
  17. content = pic.read()
  18. if len(content) > MAX_CONTENT_LENGTH:
  19. return Response("文件过大,请重新选择")
  20. cur, rnd = current_time(), rand_str()
  21. raw_path = f"static/images/{cur}_{rnd}.{ext}"
  22. rec_path = f"static/images/{cur}_{rnd}-rec.{ext}"
  23. with open(raw_path, "wb") as fp:
  24. fp.write(content)
  25. fp.close()
  26. ocr_res, img_shape = recognize(content)
  27. kind = request.form.get("type")
  28. if kind is not None:
  29. kind = kind.lower()
  30. if kind == "raw":
  31. return Response(data=[{"pos": it[0], "word": it[1][0], "rate": it[1][1]} for it in ocr_res])
  32. elif kind == "html":
  33. data = [{"pos": it[0], "word": it[1][0], "rate": it[1][1]} for it in ocr_res]
  34. draw_img(img_shape, data, rec_path)
  35. return render_template("com_result.html", raw=raw_path, rec=rec_path, data=data)
  36. else:
  37. return Response(data=[it[1][0] for it in ocr_res])
  38. com.add_url_rule("/", view_func=ComView.as_view("com"))