utils.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 pandas as pd
  14. import pytz
  15. from config import BaseConfig
  16. from .matplotlib_table import TableMaker
  17. def f_format_float(num: float, n=3):
  18. return f"{num: .{n}f}"
  19. def f_get_date(offset: int = 0, connect: str = "-") -> str:
  20. current_date = datetime.datetime.now(pytz.timezone("Asia/Shanghai")).date() + datetime.timedelta(days=offset)
  21. return current_date.strftime(f"%Y{connect}%m{connect}%d")
  22. def f_get_datetime(offset: int = 0, connect: str = "_") -> str:
  23. current_date = datetime.datetime.now(pytz.timezone("Asia/Shanghai")) + datetime.timedelta(days=offset)
  24. return current_date.strftime(f"%Y{connect}%m{connect}%d{connect}%H{connect}%M{connect}%S")
  25. def f_get_clazz_in_module(module):
  26. """
  27. 获取包下的所有类
  28. """
  29. classes = []
  30. for name, member in inspect.getmembers(module):
  31. if inspect.isclass(member):
  32. classes.append(member)
  33. return classes
  34. def f_save_train_df(file_name: str, df: pd.DataFrame):
  35. file_path = os.path.join(BaseConfig.train_path, file_name)
  36. df.to_excel(f"{file_path}.xlsx", index=False)
  37. def f_df_to_image(df: pd.DataFrame, filename, fontsize=12):
  38. converter = TableMaker(fontsize=fontsize, encode_base64=False, for_document=False)
  39. converter.run(df, filename)
  40. # if importlib.util.find_spec("dataframe_image"):
  41. # import dataframe_image as dfi
  42. #
  43. # dfi.export(obj=df, filename=filename, fontsize=fontsize, table_conversion='matplotlib')
  44. # elif importlib.util.find_spec("plotly"):
  45. # import plotly.graph_objects as go
  46. # import plotly.figure_factory as ff
  47. # import plotly.io as pio
  48. #
  49. # fig = ff.create_table(df)
  50. # fig.update_layout()
  51. # fig.write_image(filename)
  52. #
  53. # fig = go.Figure(data=go.Table(
  54. # header=dict(
  55. # values=df.columns.to_list(),
  56. # font=dict(color='black', size=fontsize),
  57. # fill_color="white",
  58. # line_color='black',
  59. # align="center"
  60. # ),
  61. # cells=dict(
  62. # values=[df[k].tolist() for k in df.columns],
  63. # font=dict(color='black', size=fontsize),
  64. # fill_color="white",
  65. # line_color='black',
  66. # align="center")
  67. # )).update_layout()
  68. # pio.write_image(fig, filename)
  69. # else:
  70. # raise GeneralException(ResultCodesEnum.NOT_FOUND, message=f"缺少画图依赖【dataframe_image】或者【plotly】")
  71. def _f_image_to_base64(image_path):
  72. with open(image_path, "rb") as image_file:
  73. img_str = base64.b64encode(image_file.read())
  74. return img_str.decode("utf-8")
  75. def f_display_images_by_side(image_path_list, display, title: str = "", width: int = 500,
  76. image_path_list2: Union[list, None] = None, title2: str = "", ):
  77. if isinstance(image_path_list, str):
  78. image_path_list = [image_path_list]
  79. # justify-content:space-around; 会导致某些情况下图片越界
  80. html_str = '<div style="display:flex;">'
  81. if title != "":
  82. html_str += '<h3>{}</h3>'.format(title)
  83. for image_path in image_path_list:
  84. html_str += f'<img src="data:image/png;base64,{_f_image_to_base64(image_path)}" style="width:{width}px;"/>'
  85. html_str += '</div>'
  86. if not (image_path_list2 is None or len(image_path_list2) == 0):
  87. html_str += '<div style="display:flex;">'
  88. if title2 != "":
  89. html_str += '<h3>{}</h3>'.format(title2)
  90. for image_path in image_path_list2:
  91. html_str += f'<img src="data:image/png;base64,{_f_image_to_base64(image_path)}" style="width:{width}px;"/>'
  92. html_str += '</div>'
  93. display.display(display.HTML(html_str))
  94. class f_clazz_to_json(JSONEncoder):
  95. def default(self, o):
  96. return o.__dict__