com.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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. save_img(raw_path, content)
  24. ocr_res, img_shape = recognize(content)
  25. kind = request.form.get("type")
  26. if kind is not None:
  27. kind = kind.lower()
  28. if kind == "raw":
  29. return Response(data=[{"pos": it[0], "word": it[1][0], "rate": it[1][1]} for it in ocr_res])
  30. elif kind == "html":
  31. data = [{"pos": it[0], "word": it[1][0], "rate": it[1][1]} for it in ocr_res]
  32. draw_img(img_shape, data, rec_path)
  33. return render_template("com_result.html", raw=raw_path, rec=rec_path, data=data)
  34. else:
  35. return Response(data=[it[1][0] for it in ocr_res])
  36. com.add_url_rule("/", view_func=ComView.as_view("com"))