com.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from utils.util import *
  2. from utils.conf import MAX_FILE_SIZE
  3. from flask import Blueprint, views, render_template, request
  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_FILE_SIZE:
  19. return Response("文件过大,请重新选择")
  20. file_path = f"static/images/{current_time()}_{rand_str()}.{ext}"
  21. save_img(file_path, content)
  22. img = read_img(content)
  23. ocr_res = Engine.rec_one(img)
  24. kind = request.form.get("type")
  25. if kind is not None:
  26. kind = kind.lower()
  27. if kind == "raw":
  28. return Response(data=ocr_res)
  29. elif kind == "html":
  30. data = [{"word": it[0], "rate": it[1], "index": i + 1} for i, it in enumerate(ocr_res)]
  31. return render_template("com_result.html", raw=file_path, data=data)
  32. else:
  33. return Response(data=[it[0] for it in ocr_res])
  34. com.add_url_rule("/", view_func=ComView.as_view("com"))