utils.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # -*- coding:utf-8 -*-
  2. """
  3. @author: yq
  4. @time: 2023/12/28
  5. @desc: 各种工具类
  6. """
  7. import base64
  8. import datetime
  9. import inspect
  10. import os
  11. from json import JSONEncoder
  12. from typing import Union
  13. import numpy as np
  14. import pandas as pd
  15. import pytz
  16. from PIL import Image
  17. from config import BaseConfig
  18. from .matplotlib_table import TableMaker
  19. def f_format_float(num: float, n=3):
  20. return f"{num: .{n}f}"
  21. def f_get_date(offset: int = 0, connect: str = "-") -> str:
  22. current_date = datetime.datetime.now(pytz.timezone("Asia/Shanghai")).date() + datetime.timedelta(days=offset)
  23. return current_date.strftime(f"%Y{connect}%m{connect}%d")
  24. def f_get_datetime(offset: int = 0, connect: str = "_") -> str:
  25. current_date = datetime.datetime.now(pytz.timezone("Asia/Shanghai")) + datetime.timedelta(days=offset)
  26. return current_date.strftime(f"%Y{connect}%m{connect}%d{connect}%H{connect}%M{connect}%S")
  27. def f_get_clazz_in_module(module):
  28. """
  29. 获取包下的所有类
  30. """
  31. classes = []
  32. for name, member in inspect.getmembers(module):
  33. if inspect.isclass(member):
  34. classes.append(member)
  35. return classes
  36. def f_save_train_df(file_name: str, df: pd.DataFrame):
  37. file_path = os.path.join(BaseConfig.train_path, file_name)
  38. df.to_excel(f"{file_path}.xlsx", index=False)
  39. def f_df_to_image(df: pd.DataFrame, filename, fontsize=12):
  40. converter = TableMaker(fontsize=fontsize, encode_base64=False, for_document=False)
  41. converter.run(df, filename)
  42. # if importlib.util.find_spec("dataframe_image"):
  43. # import dataframe_image as dfi
  44. #
  45. # dfi.export(obj=df, filename=filename, fontsize=fontsize, table_conversion='matplotlib')
  46. # elif importlib.util.find_spec("plotly"):
  47. # import plotly.graph_objects as go
  48. # import plotly.figure_factory as ff
  49. # import plotly.io as pio
  50. #
  51. # fig = ff.create_table(df)
  52. # fig.update_layout()
  53. # fig.write_image(filename)
  54. #
  55. # fig = go.Figure(data=go.Table(
  56. # header=dict(
  57. # values=df.columns.to_list(),
  58. # font=dict(color='black', size=fontsize),
  59. # fill_color="white",
  60. # line_color='black',
  61. # align="center"
  62. # ),
  63. # cells=dict(
  64. # values=[df[k].tolist() for k in df.columns],
  65. # font=dict(color='black', size=fontsize),
  66. # fill_color="white",
  67. # line_color='black',
  68. # align="center")
  69. # )).update_layout()
  70. # pio.write_image(fig, filename)
  71. # else:
  72. # raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"缺少画图依赖【dataframe_image】或者【plotly】")
  73. def _f_image_to_base64(image_path):
  74. with open(image_path, "rb") as image_file:
  75. img_str = base64.b64encode(image_file.read())
  76. return img_str.decode("utf-8")
  77. def f_image_crop_white_borders(image_path, output_path):
  78. # 打开图片
  79. image = Image.open(image_path)
  80. # 将图片转换为灰度图
  81. gray_image = image.convert('L')
  82. # 获取图片的宽度和高度
  83. width, height = gray_image.size
  84. # 初始化边界
  85. left, top, right, bottom = width, height, 0, 0
  86. # 遍历图片的每一行和每一列
  87. for y in range(height):
  88. for x in range(width):
  89. # 获取当前像素的灰度值
  90. pixel = gray_image.getpixel((x, y))
  91. # 如果像素不是白色(灰度值小于 255)
  92. if pixel < 255:
  93. # 更新边界
  94. if x < left:
  95. left = x
  96. if x > right:
  97. right = x
  98. if y < top:
  99. top = y
  100. if y > bottom:
  101. bottom = y
  102. # 裁剪图片
  103. cropped_image = image.crop((left, top, right + 1, bottom + 1))
  104. # 保存裁剪后的图片
  105. cropped_image.save(output_path)
  106. def f_display_images_by_side(display, image_path_list, title: str = "", width: int = 500,
  107. image_path_list2: Union[list, None] = None, title2: str = "", ):
  108. if isinstance(image_path_list, str):
  109. image_path_list = [image_path_list]
  110. # justify-content:space-around; 会导致某些情况下图片越界
  111. html_str = '<div style="display:flex;">'
  112. if title != "":
  113. html_str += '<div>{}</div>'.format(title)
  114. for image_path in image_path_list:
  115. html_str += f'<img src="data:image/png;base64,{_f_image_to_base64(image_path)}" style="width:{width}px;"/>'
  116. html_str += '</div>'
  117. if not (image_path_list2 is None or len(image_path_list2) == 0):
  118. html_str += '<div style="display:flex;">'
  119. if title2 != "":
  120. html_str += '<div>{}</div>'.format(title2)
  121. for image_path in image_path_list2:
  122. html_str += f'<img src="data:image/png;base64,{_f_image_to_base64(image_path)}" style="width:{width}px;"/>'
  123. html_str += '</div>'
  124. display.display(display.HTML(html_str))
  125. def f_display_title(display, title):
  126. html_str = f"<h2>{title}</h2>"
  127. display.display(display.HTML(html_str))
  128. class f_clazz_to_json(JSONEncoder):
  129. def default(self, o):
  130. return o.__dict__
  131. class NumpyEncoder(JSONEncoder):
  132. def default(self, obj):
  133. if isinstance(obj, np.integer):
  134. return int(obj)
  135. if isinstance(obj, np.floating):
  136. return float(obj)
  137. if isinstance(obj, np.ndarray):
  138. return obj.tolist()
  139. return super(NumpyEncoder, self).default(obj)