util.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import cv2
  2. import numpy as np
  3. from typing import Union
  4. from flask import jsonify
  5. from random import randint
  6. from hmOCR import HuiMvOCR, Args
  7. from time import localtime, strftime
  8. __all__ = [
  9. "Response", "rand_str", "current_time", "get_ext_name", "is_image_ext",
  10. "json_all", "str_include", "read_img", "rot_img", "save_img", "Engine"
  11. ]
  12. __StrBase = "qwertyuioplkjhgfdsazxcvbnm1234567890ZXCVBNMLKJHGFDSAQWERTYUIOP"
  13. __StrBaseLen = len(__StrBase) - 1
  14. __AcceptExtNames = ["jpg", "jpeg", "bmp", "png", "rgb", "tif", "tiff", "gif"]
  15. Engine = HuiMvOCR(Args())
  16. def Response(message: "str" = None, data=None):
  17. if message is None:
  18. return jsonify(success=True, message="操作成功", data=data)
  19. return jsonify(success=False, message=message, data=data)
  20. def rand_str(size: "int" = 8) -> "str":
  21. return "".join([__StrBase[randint(0, __StrBaseLen)] for _ in range(size)])
  22. def current_time() -> "str":
  23. return strftime("%Y-%m-%d_%H-%M-%S", localtime())
  24. def get_ext_name(name: "str") -> "str":
  25. return name.split(".")[-1].lower()
  26. def is_image_ext(ext: "str") -> bool:
  27. return ext in __AcceptExtNames
  28. def json_all(data: "Union[list, dict]") -> "bool":
  29. if isinstance(data, list):
  30. for item in data:
  31. if isinstance(item, str) and not item:
  32. return False
  33. elif isinstance(item, (list, dict)) and not json_all(item):
  34. return False
  35. return True
  36. elif isinstance(data, dict):
  37. for value in data.values():
  38. if isinstance(value, str) and not value:
  39. return False
  40. elif isinstance(value, (list, dict)) and not json_all(value):
  41. return False
  42. return True
  43. raise TypeError(f"except node type are: [list, dict], but got a {type(data)} instead.")
  44. def str_include(str_long: "str", str_short: "str") -> "bool":
  45. for it in str_short:
  46. if it not in str_long:
  47. return False
  48. return True
  49. def read_img(content: "str") -> "np.ndarray":
  50. return cv2.imdecode(np.frombuffer(content, np.uint8), 1) # noqa
  51. def rot_img(img: "np.ndarray") -> "list[np.ndarray]":
  52. return [img, np.rot90(img), np.rot90(img, 2), np.rot90(img, 3)]
  53. def save_img(filename: "str", content: "Union[bytes, np.ndarray]"):
  54. if isinstance(content, np.ndarray):
  55. return cv2.imwrite(filename, content) # noqa
  56. with open(filename, "wb") as fp:
  57. fp.write(content)
  58. fp.close()