libs.commands.report.winner

libs/commands/report/winner.py

  1"""
  2libs/commands/report/winner.py
  3"""
  4
  5from typing import TYPE_CHECKING
  6
  7import matplotlib.pyplot as plt
  8
  9import libs.global_value as g
 10from libs.data import loader
 11from libs.datamodels import GameInfo
 12from libs.functions import compose, message
 13from libs.types import StyleOptions
 14from libs.utils import formatter, graphutil, textutil
 15
 16if TYPE_CHECKING:
 17    from integrations.protocols import MessageParserProtocol
 18
 19
 20def plot(m: "MessageParserProtocol"):
 21    """成績上位者を一覧化
 22
 23    Args:
 24        m (MessageParserProtocol): メッセージデータ
 25    """
 26
 27    # --- データ取得
 28    game_info = GameInfo()
 29    results_df = loader.read_data("REPORT_WINNER")
 30    if len(results_df) == 0:
 31        m.post.headline = {"成績上位": message.random_reply(m, "no_hits")}
 32        m.status.result = False
 33        return
 34
 35    # 匿名化
 36    if g.params.get("anonymous"):
 37        name_list: list = []
 38        for col in [f"name{x}" for x in range(1, 6)]:
 39            name_list.extend(results_df[col].unique().tolist())
 40        mapping_dict = formatter.anonymous_mapping(list(set(name_list)))
 41        for col in [f"name{x}" for x in range(1, 6)]:
 42            results_df[col] = results_df[col].replace(mapping_dict)
 43
 44    # --- 集計
 45    results: dict = {}
 46    for _, v in results_df.iterrows():
 47        results[v["collection"]] = {}
 48        results[v["collection"]]["集計月"] = v["collection"]
 49        for x in range(1, 6):
 50            if v.isna()[f"point{x}"]:
 51                results[v["collection"]][f"{x}位"] = "該当者なし"
 52            else:
 53                results[v["collection"]][f"{x}位"] = "{} ({}pt)".format(  # pylint: disable=consider-using-f-string
 54                    v[f"name{x}"],
 55                    str("{:+}".format(v[f"point{x}"])).replace("-", "▲")  # pylint: disable=consider-using-f-string
 56                )
 57
 58    m.post.headline = {"成績上位者": message.header(game_info, m)}
 59
 60    # --- グラフ設定
 61    match g.adapter.conf.plotting_backend:
 62        case "plotly":
 63            pass
 64        case _:
 65            graphutil.setup()
 66            report_file_path = textutil.save_file_path("report.png")
 67            plt.rcParams["font.size"] = 6
 68
 69            # 色彩設定
 70            match (plt.rcParams["text.color"], plt.rcParams["figure.facecolor"]):
 71                case text_color, bg_color if text_color == "black" and bg_color == "white":
 72                    line_color1 = "#ffffff"
 73                    line_color2 = "#dddddd"
 74                case text_color, bg_color if text_color == "white" and bg_color == "black":
 75                    line_color1 = "#000000"
 76                    line_color2 = "#111111"
 77                case _:
 78                    line_color1 = plt.rcParams["figure.facecolor"]
 79                    line_color2 = plt.rcParams["figure.facecolor"]
 80
 81            column_labels = list(results[list(results.keys())[0]].keys())
 82            column_color = ["#000080" for i in column_labels]
 83
 84            cell_param = []
 85            cell_color = []
 86            line_count = 0
 87            for _, val in results.items():
 88                line_count += 1
 89                cell_param.append([val[y] for y in column_labels])
 90                if int(line_count % 2):
 91                    cell_color.append([line_color1 for i in column_labels])
 92                else:
 93                    cell_color.append([line_color2 for i in column_labels])
 94
 95            fig = plt.figure(
 96                figsize=(6.5, (len(results) * 0.2) + 0.8),
 97                dpi=200,
 98                tight_layout=True
 99            )
100            ax_dummy = fig.add_subplot(111)
101            ax_dummy.axis("off")
102
103            plt.title("成績上位者", fontsize=12)
104
105            tb = plt.table(
106                colLabels=column_labels,
107                colColours=column_color,
108                cellText=cell_param,
109                cellColours=cell_color,
110                loc="center",
111            )
112
113            tb.auto_set_font_size(False)
114            for i in range(len(column_labels)):
115                tb[0, i].set_text_props(color="#FFFFFF", weight="bold")
116            for i in range(len(results.keys()) + 1):
117                for j in range(len(column_labels)):
118                    tb[i, j].set_text_props(ha="center")
119
120            # 追加テキスト
121            remark_text = "".join(compose.text_item.remarks(True)) + compose.text_item.search_word(True)
122            add_text = "{} {}".format(  # pylint: disable=consider-using-f-string
123                f"[検索範囲:{compose.text_item.search_range()}]",
124                f"[{remark_text}]" if remark_text else "",
125            )
126
127            fig.text(
128                0.01, 0.02,  # 表示位置(左下0,0 右下0,1)
129                add_text,
130                transform=fig.transFigure,
131                fontsize=6,
132            )
133
134            fig.savefig(report_file_path)
135
136    match g.adapter.interface_type:
137        case "slack":
138            m.set_data("成績上位者", report_file_path, StyleOptions(use_comment=True, header_hidden=True))
139        case "web":
140            m.set_data("月別集計結果", formatter.df_rename(results_df), StyleOptions())
 21def plot(m: "MessageParserProtocol"):
 22    """成績上位者を一覧化
 23
 24    Args:
 25        m (MessageParserProtocol): メッセージデータ
 26    """
 27
 28    # --- データ取得
 29    game_info = GameInfo()
 30    results_df = loader.read_data("REPORT_WINNER")
 31    if len(results_df) == 0:
 32        m.post.headline = {"成績上位": message.random_reply(m, "no_hits")}
 33        m.status.result = False
 34        return
 35
 36    # 匿名化
 37    if g.params.get("anonymous"):
 38        name_list: list = []
 39        for col in [f"name{x}" for x in range(1, 6)]:
 40            name_list.extend(results_df[col].unique().tolist())
 41        mapping_dict = formatter.anonymous_mapping(list(set(name_list)))
 42        for col in [f"name{x}" for x in range(1, 6)]:
 43            results_df[col] = results_df[col].replace(mapping_dict)
 44
 45    # --- 集計
 46    results: dict = {}
 47    for _, v in results_df.iterrows():
 48        results[v["collection"]] = {}
 49        results[v["collection"]]["集計月"] = v["collection"]
 50        for x in range(1, 6):
 51            if v.isna()[f"point{x}"]:
 52                results[v["collection"]][f"{x}位"] = "該当者なし"
 53            else:
 54                results[v["collection"]][f"{x}位"] = "{} ({}pt)".format(  # pylint: disable=consider-using-f-string
 55                    v[f"name{x}"],
 56                    str("{:+}".format(v[f"point{x}"])).replace("-", "▲")  # pylint: disable=consider-using-f-string
 57                )
 58
 59    m.post.headline = {"成績上位者": message.header(game_info, m)}
 60
 61    # --- グラフ設定
 62    match g.adapter.conf.plotting_backend:
 63        case "plotly":
 64            pass
 65        case _:
 66            graphutil.setup()
 67            report_file_path = textutil.save_file_path("report.png")
 68            plt.rcParams["font.size"] = 6
 69
 70            # 色彩設定
 71            match (plt.rcParams["text.color"], plt.rcParams["figure.facecolor"]):
 72                case text_color, bg_color if text_color == "black" and bg_color == "white":
 73                    line_color1 = "#ffffff"
 74                    line_color2 = "#dddddd"
 75                case text_color, bg_color if text_color == "white" and bg_color == "black":
 76                    line_color1 = "#000000"
 77                    line_color2 = "#111111"
 78                case _:
 79                    line_color1 = plt.rcParams["figure.facecolor"]
 80                    line_color2 = plt.rcParams["figure.facecolor"]
 81
 82            column_labels = list(results[list(results.keys())[0]].keys())
 83            column_color = ["#000080" for i in column_labels]
 84
 85            cell_param = []
 86            cell_color = []
 87            line_count = 0
 88            for _, val in results.items():
 89                line_count += 1
 90                cell_param.append([val[y] for y in column_labels])
 91                if int(line_count % 2):
 92                    cell_color.append([line_color1 for i in column_labels])
 93                else:
 94                    cell_color.append([line_color2 for i in column_labels])
 95
 96            fig = plt.figure(
 97                figsize=(6.5, (len(results) * 0.2) + 0.8),
 98                dpi=200,
 99                tight_layout=True
100            )
101            ax_dummy = fig.add_subplot(111)
102            ax_dummy.axis("off")
103
104            plt.title("成績上位者", fontsize=12)
105
106            tb = plt.table(
107                colLabels=column_labels,
108                colColours=column_color,
109                cellText=cell_param,
110                cellColours=cell_color,
111                loc="center",
112            )
113
114            tb.auto_set_font_size(False)
115            for i in range(len(column_labels)):
116                tb[0, i].set_text_props(color="#FFFFFF", weight="bold")
117            for i in range(len(results.keys()) + 1):
118                for j in range(len(column_labels)):
119                    tb[i, j].set_text_props(ha="center")
120
121            # 追加テキスト
122            remark_text = "".join(compose.text_item.remarks(True)) + compose.text_item.search_word(True)
123            add_text = "{} {}".format(  # pylint: disable=consider-using-f-string
124                f"[検索範囲:{compose.text_item.search_range()}]",
125                f"[{remark_text}]" if remark_text else "",
126            )
127
128            fig.text(
129                0.01, 0.02,  # 表示位置(左下0,0 右下0,1)
130                add_text,
131                transform=fig.transFigure,
132                fontsize=6,
133            )
134
135            fig.savefig(report_file_path)
136
137    match g.adapter.interface_type:
138        case "slack":
139            m.set_data("成績上位者", report_file_path, StyleOptions(use_comment=True, header_hidden=True))
140        case "web":
141            m.set_data("月別集計結果", formatter.df_rename(results_df), StyleOptions())

成績上位者を一覧化

Arguments:
  • m (MessageParserProtocol): メッセージデータ