libs.commands.report.winner

libs/commands/report/slackpost.py

  1"""
  2libs/commands/report/slackpost.py
  3"""
  4
  5import os
  6
  7import matplotlib.font_manager as fm
  8import matplotlib.pyplot as plt
  9
 10import libs.global_value as g
 11from libs.data import loader
 12from libs.functions import configuration, message
 13from libs.utils import formatter
 14
 15
 16def plot() -> str | bool:
 17    """成績上位者を一覧化
 18
 19    Returns:
 20        Union[str,bool]:
 21        - str: 生成ファイルパス
 22        - False: 描写データなし
 23    """
 24
 25    plt.close()
 26    # --- データ取得
 27    results_df = loader.read_data("report/winner.sql")
 28    if len(results_df) == 0:
 29        return False
 30
 31    # --- 匿名化
 32    if g.params.get("anonymous"):
 33        name_list: list = []
 34        for col in [f"name{x}" for x in range(1, 6)]:
 35            name_list.extend(results_df[col].unique().tolist())
 36        mapping_dict = formatter.anonymous_mapping(list(set(name_list)))
 37        for col in [f"name{x}" for x in range(1, 6)]:
 38            results_df[col] = results_df[col].replace(mapping_dict)
 39
 40    # --- 集計
 41    results: dict = {}
 42    for _, v in results_df.iterrows():
 43        results[v["collection"]] = {}
 44        results[v["collection"]]["集計月"] = v["collection"]
 45        for x in range(1, 6):
 46            if v.isna()[f"point{x}"]:
 47                results[v["collection"]][f"{x}位"] = "該当者なし"
 48            else:
 49                results[v["collection"]][f"{x}位"] = "{} ({}pt)".format(  # pylint: disable=consider-using-f-string
 50                    v[f"name{x}"],
 51                    str("{:+}".format(v[f"point{x}"])).replace("-", "▲")  # pylint: disable=consider-using-f-string
 52                )
 53
 54    # --- グラフ設定
 55    configuration.graph_setup(plt, fm)
 56    plt.rcParams["font.size"] = 6
 57    report_file_path = os.path.join(
 58        g.cfg.setting.work_dir,
 59        f"{g.params["filename"]}.png" if g.params.get("filename") else "report.png",
 60    )
 61
 62    # 色彩設定
 63    match (plt.rcParams["text.color"], plt.rcParams["figure.facecolor"]):
 64        case text_color, bg_color if text_color == "black" and bg_color == "white":
 65            line_color1 = "#ffffff"
 66            line_color2 = "#dddddd"
 67        case text_color, bg_color if text_color == "white" and bg_color == "black":
 68            line_color1 = "#000000"
 69            line_color2 = "#111111"
 70        case _:
 71            line_color1 = plt.rcParams["figure.facecolor"]
 72            line_color2 = plt.rcParams["figure.facecolor"]
 73
 74    column_labels = list(results[list(results.keys())[0]].keys())
 75    column_color = ["#000080" for i in column_labels]
 76
 77    cell_param = []
 78    cell_color = []
 79    line_count = 0
 80    for _, val in results.items():
 81        line_count += 1
 82        cell_param.append([val[y] for y in column_labels])
 83        if int(line_count % 2):
 84            cell_color.append([line_color1 for i in column_labels])
 85        else:
 86            cell_color.append([line_color2 for i in column_labels])
 87
 88    fig = plt.figure(
 89        figsize=(6.5, (len(results) * 0.2) + 0.8),
 90        dpi=200,
 91        tight_layout=True
 92    )
 93    ax_dummy = fig.add_subplot(111)
 94    ax_dummy.axis("off")
 95
 96    plt.title("成績上位者", fontsize=12)
 97
 98    tb = plt.table(
 99        colLabels=column_labels,
100        colColours=column_color,
101        cellText=cell_param,
102        cellColours=cell_color,
103        loc="center",
104    )
105
106    tb.auto_set_font_size(False)
107    for i in range(len(column_labels)):
108        tb[0, i].set_text_props(color="#FFFFFF", weight="bold")
109    for i in range(len(results.keys()) + 1):
110        for j in range(len(column_labels)):
111            tb[i, j].set_text_props(ha="center")
112
113    # 追加テキスト
114    remark_text = message.remarks(True) + message.search_word(True)
115    add_text = "{} {}".format(  # pylint: disable=consider-using-f-string
116        f"[{message.item_search_range().strip()}]",
117        f"[{remark_text}]" if remark_text else "",
118    )
119
120    fig.text(
121        0.01, 0.02,  # 表示位置(左下0,0 右下0,1)
122        add_text,
123        transform=fig.transFigure,
124        fontsize=6,
125    )
126
127    fig.savefig(report_file_path)
128    plt.close()
129
130    return report_file_path
def plot() -> str | bool:
 17def plot() -> str | bool:
 18    """成績上位者を一覧化
 19
 20    Returns:
 21        Union[str,bool]:
 22        - str: 生成ファイルパス
 23        - False: 描写データなし
 24    """
 25
 26    plt.close()
 27    # --- データ取得
 28    results_df = loader.read_data("report/winner.sql")
 29    if len(results_df) == 0:
 30        return False
 31
 32    # --- 匿名化
 33    if g.params.get("anonymous"):
 34        name_list: list = []
 35        for col in [f"name{x}" for x in range(1, 6)]:
 36            name_list.extend(results_df[col].unique().tolist())
 37        mapping_dict = formatter.anonymous_mapping(list(set(name_list)))
 38        for col in [f"name{x}" for x in range(1, 6)]:
 39            results_df[col] = results_df[col].replace(mapping_dict)
 40
 41    # --- 集計
 42    results: dict = {}
 43    for _, v in results_df.iterrows():
 44        results[v["collection"]] = {}
 45        results[v["collection"]]["集計月"] = v["collection"]
 46        for x in range(1, 6):
 47            if v.isna()[f"point{x}"]:
 48                results[v["collection"]][f"{x}位"] = "該当者なし"
 49            else:
 50                results[v["collection"]][f"{x}位"] = "{} ({}pt)".format(  # pylint: disable=consider-using-f-string
 51                    v[f"name{x}"],
 52                    str("{:+}".format(v[f"point{x}"])).replace("-", "▲")  # pylint: disable=consider-using-f-string
 53                )
 54
 55    # --- グラフ設定
 56    configuration.graph_setup(plt, fm)
 57    plt.rcParams["font.size"] = 6
 58    report_file_path = os.path.join(
 59        g.cfg.setting.work_dir,
 60        f"{g.params["filename"]}.png" if g.params.get("filename") else "report.png",
 61    )
 62
 63    # 色彩設定
 64    match (plt.rcParams["text.color"], plt.rcParams["figure.facecolor"]):
 65        case text_color, bg_color if text_color == "black" and bg_color == "white":
 66            line_color1 = "#ffffff"
 67            line_color2 = "#dddddd"
 68        case text_color, bg_color if text_color == "white" and bg_color == "black":
 69            line_color1 = "#000000"
 70            line_color2 = "#111111"
 71        case _:
 72            line_color1 = plt.rcParams["figure.facecolor"]
 73            line_color2 = plt.rcParams["figure.facecolor"]
 74
 75    column_labels = list(results[list(results.keys())[0]].keys())
 76    column_color = ["#000080" for i in column_labels]
 77
 78    cell_param = []
 79    cell_color = []
 80    line_count = 0
 81    for _, val in results.items():
 82        line_count += 1
 83        cell_param.append([val[y] for y in column_labels])
 84        if int(line_count % 2):
 85            cell_color.append([line_color1 for i in column_labels])
 86        else:
 87            cell_color.append([line_color2 for i in column_labels])
 88
 89    fig = plt.figure(
 90        figsize=(6.5, (len(results) * 0.2) + 0.8),
 91        dpi=200,
 92        tight_layout=True
 93    )
 94    ax_dummy = fig.add_subplot(111)
 95    ax_dummy.axis("off")
 96
 97    plt.title("成績上位者", fontsize=12)
 98
 99    tb = plt.table(
100        colLabels=column_labels,
101        colColours=column_color,
102        cellText=cell_param,
103        cellColours=cell_color,
104        loc="center",
105    )
106
107    tb.auto_set_font_size(False)
108    for i in range(len(column_labels)):
109        tb[0, i].set_text_props(color="#FFFFFF", weight="bold")
110    for i in range(len(results.keys()) + 1):
111        for j in range(len(column_labels)):
112            tb[i, j].set_text_props(ha="center")
113
114    # 追加テキスト
115    remark_text = message.remarks(True) + message.search_word(True)
116    add_text = "{} {}".format(  # pylint: disable=consider-using-f-string
117        f"[{message.item_search_range().strip()}]",
118        f"[{remark_text}]" if remark_text else "",
119    )
120
121    fig.text(
122        0.01, 0.02,  # 表示位置(左下0,0 右下0,1)
123        add_text,
124        transform=fig.transFigure,
125        fontsize=6,
126    )
127
128    fig.savefig(report_file_path)
129    plt.close()
130
131    return report_file_path

成績上位者を一覧化

Returns:

Union[str,bool]:

  • str: 生成ファイルパス
  • False: 描写データなし