Download func_gui_multi_test.py from pengyuyan1222/Multi_ABtest_Result_Analytics: direct link, hf CLI and curl.
- Browser
- Download file 27.8 kB
-
https://huggingface.co/spaces/pengyuyan1222/Multi_ABtest_Result_Analytics/resolve/main/func_gui_multi_test.py
- Command line
-
hf download hf://spaces/pengyuyan1222/Multi_ABtest_Result_Analytics/func_gui_multi_test.py
-
curl -L -o func_gui_multi_test.py https://huggingface.co/spaces/pengyuyan1222/Multi_ABtest_Result_Analytics/resolve/main/func_gui_multi_test.py
27.8 kB
| # -------------------- GUI界面工具函数 -------------------- | |
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import io | |
| import tempfile | |
| import time | |
| import os | |
| from params import DEFAULT_CTRL_ROWS, DEFAULT_EXP_ROWS, CTRL_COLUMNS, EXP_COLUMNS, RESULT_COLUMNS, LOCK_METRIC_TYPES, LOCK_ALT_TYPES, LOCK_METHODS | |
| from func_stats_multi_test import ab_test_result, adjust_p_values | |
| from func_format import result_format | |
| def _empty_ctrl_df(): # 20251008 12:14,删除了"n: int = DEFAULT_CTRL_ROWS"一个参数 | |
| # 确保每行有7列 | |
| # return pd.DataFrame([["", "", "", None, None, None, None] for _ in range(n)], columns=CTRL_COLUMNS) | |
| return pd.DataFrame(columns=CTRL_COLUMNS) | |
| def _empty_exp_df(n: int = DEFAULT_EXP_ROWS): | |
| return pd.DataFrame([["", "", "", "", "two_sided", None, None, None, None, None, None, None, None] for _ in range(n)], columns=EXP_COLUMNS) | |
| def _validate_controls(row: dict): # 20251008 12:14,删除了"ctrl_row_idx, ctrl_del_row_idx, ctrl_df"三个参数 | |
| """校验对照组:名称/指标/类型/检验类型 必填;且按类型校验对应字段。返回 (ok, msg)""" | |
| # 1.检验是否输入内容全为空 | |
| if len(row) == 0: | |
| return False, "🚫输入信息为空,请补全信息" | |
| # 2.字段缺失判断 | |
| # 基本必填缺失判断 | |
| base_required = ["对照组名称", "指标名称", "指标类型"] | |
| if any(str(row.get(c, "")).strip() == "" for c in base_required): | |
| return False, "🚫必填字段【对照组名称/指标名称/指标类型】未填写完整,请补全信息" | |
| # 类型对应字段 | |
| t = str(row.get("指标类型", "")).strip() | |
| if t == "mean": | |
| req = ["对照组均值", "对照组标准差", "对照组样本量"] | |
| elif t == "ratio": | |
| req = ["对照组转化人数", "对照组样本量"] | |
| # 类型对应字段缺失判断 | |
| if any(str(row.get(c, "")).strip() == "" for c in req): | |
| return False, f"🚫必填字段{req}未填写完整,请补全信息" | |
| # 3.检验输入数据是否合法 | |
| if t == 'mean': | |
| if row.get("对照组样本量", 0) <= 0: | |
| return False, '🚫对照组样本量必须大于0' | |
| elif row.get("对照组标准差", 0) <= 0: | |
| return False, '🚫对照组标准差必须大于0' | |
| elif t == 'ratio': | |
| if row.get("对照组样本量", 0) <= 0: | |
| return False, '🚫对照组样本量必须大于0' | |
| elif row.get('对照组转化人数', 0) < 0: | |
| return False, '🚫对照组转化人数必须大于等于0' | |
| elif row.get("对照组转化人数", 0) > row.get("对照组样本量", 0): | |
| return False, '🚫对照组转化人数不得高于对照组样本量' | |
| return True, "✅录入成功,请继续输入实验组数据" | |
| def build_ctrl_dropdowns(ctrl_df: pd.DataFrame): | |
| """返回 (groups_update 一个 gr.update,用于更新下拉。 | |
| groups: 仅包含对照组名称(去重并排序)""" | |
| if ctrl_df is None or ctrl_df.empty: | |
| return gr.update(choices=[], value=None) | |
| tmp = ctrl_df.replace({np.nan: ""}) | |
| seen_g = set() | |
| groups = [] | |
| for _, r in tmp.iterrows(): | |
| g = str(r.get("对照组名称", "")).strip() | |
| if g: | |
| if g not in seen_g: | |
| seen_g.add(g) | |
| groups.append(g) | |
| return gr.update(choices=sorted(groups), value=None) | |
| def _validate_experiments(row: dict): # 20251008 10:53,删除了"exp_row_idx, exp_del_row_idx, exp_df"三个参数 | |
| """校验实验组:若一行有任意填写,则必须满足必填 + 类型对应字段。返回 (ok, msg)""" | |
| if len(row) == 0: | |
| return False, "🚫输入信息为空,请补全信息" | |
| base_required = ["实验组名称", "对比对照组", "对比指标", "指标类型", | |
| "检验类型"] | |
| if any(str(row.get(c, "")).strip() == "" for c in base_required): | |
| return False, "🚫必填字段【实验组名称/对比对照组/对比指标/检验类型】未填写完整,请补全信息" | |
| # 类型对应字段 | |
| t = str(row.get("指标类型", "")).strip() | |
| if t == "mean": | |
| req = ["实验组均值", "实验组标准差", "实验组样本量", "对照组均值", "对照组标准差", "对照组样本量"] | |
| elif t == "ratio": | |
| req = ["实验组转化人数", "实验组样本量", "对照组转化人数", "对照组样本量"] | |
| else: | |
| req = [] | |
| # 类型对应字段缺失判断 | |
| if any(str(row.get(c, "")).strip() == "" for c in req): | |
| return False, f"🚫必填字段{req}未填写完整,请补全信息" | |
| # 3.检验输入数据是否合法 -- 20250922 19:00 | |
| if t == 'mean': | |
| if row.get("实验组样本量", 0) <= 0: | |
| return False, '🚫实验组样本量必须大于0' | |
| elif row.get("实验组标准差", 0) <= 0: | |
| return False, '🚫实验组标准差必须大于0' | |
| elif t == 'ratio': | |
| if row.get("实验组样本量", 0) <= 0: | |
| return False, '🚫实验组样本量必须大于0' | |
| elif row.get('实验组转化人数', 0) < 0: | |
| return False, '🚫实验组转化人数必须大于等于0' | |
| elif row.get("实验组转化人数", 0) > row.get("实验组样本量", 0): | |
| return False, '🚫实验组转化人数不得高于实验组样本量' | |
| return True, "✅录入成功,请继续输入多重检验参数" | |
| def apply_ctrl_row(ctrl_df: pd.DataFrame, ctrl_row_idx: int | None, ctrl_del_row_idx: int | None, | |
| name: str, metric: str, metric_type: str, | |
| c_mean: float | None, c_sd: float | None, | |
| c_n_rate: float | None, c_n_mean: float | None, | |
| c_conv: float | None, | |
| edit_method = 'append'): | |
| # 1.创建存储新输入信息的变量row | |
| # 判断根据指标类型,确定c_n取值来源 | |
| if metric_type == 'mean': | |
| c_n = c_n_mean | |
| elif metric_type == 'ratio': | |
| c_n = c_n_rate | |
| else: | |
| c_n = None | |
| # 构造行数据 | |
| row = {c: None for c in CTRL_COLUMNS} | |
| row.update({ | |
| "对照组名称": (name or "").strip(), | |
| "指标名称": (metric or "").strip(), | |
| "指标类型": metric_type if metric_type in LOCK_METRIC_TYPES else "", | |
| }) | |
| if metric_type == "mean": | |
| row.update({"对照组均值": c_mean, "对照组标准差": c_sd, "对照组样本量": c_n, "对照组转化人数": None}) | |
| elif metric_type == "ratio": | |
| row.update({"对照组均值": None, "对照组标准差": None, "对照组样本量": c_n, "对照组转化人数": c_conv}) | |
| # 2.校验 | |
| feedback, validate_msg = _validate_controls(row) # 20251008 12:14,删除了"ctrl_row_idx, ctrl_del_row_idx, ctrl_df"三个参数 | |
| # 3.先准备 df 的副本并写入/追加(无论校验结果,都以此为基础更新下拉;校验失败则不变) | |
| if ctrl_df is None or ctrl_df.empty: | |
| df = _empty_ctrl_df().copy() | |
| else: | |
| df = ctrl_df.copy() | |
| # 4.根据输入信息正确情况,返回内容 | |
| if feedback: | |
| # 4.1.判断是否存在重复值,若存在则停止录入/编辑动作 | |
| if edit_method == 'append': | |
| if row["指标类型"] == 'ratio': | |
| is_duplicate = ((ctrl_df["对照组名称"] == row["对照组名称"]) & | |
| (ctrl_df["指标名称"] == row["指标名称"])).any() | |
| else: | |
| is_duplicate = ((ctrl_df["对照组名称"] == row["对照组名称"]) & | |
| (ctrl_df["指标名称"] == row["指标名称"])).any() | |
| elif edit_method == 'edit': | |
| if row["指标类型"] == 'ratio': | |
| is_duplicate = ((ctrl_df["对照组名称"] == row["对照组名称"]) & | |
| (ctrl_df["指标名称"] == row["指标名称"]) & | |
| (ctrl_df["对照组样本量"] == row["对照组样本量"]) & | |
| (ctrl_df["对照组转化人数"] == row["对照组转化人数"])).any() | |
| else: | |
| is_duplicate = ((ctrl_df["对照组名称"] == row["对照组名称"]) & | |
| (ctrl_df["指标名称"] == row["指标名称"]) & | |
| (ctrl_df["对照组均值"] == row["对照组均值"]) & | |
| (ctrl_df["对照组标准差"] == row["对照组标准差"]) & | |
| (ctrl_df["对照组样本量"] == row["对照组样本量"])).any() | |
| if is_duplicate: | |
| groups_update = build_ctrl_dropdowns(ctrl_df) | |
| return gr.update(value='🚫该对照组实验数据已存在,请勿重复录入'), groups_update, gr.update(value=ctrl_df) | |
| # 4.2.写入或追加 | |
| if ctrl_row_idx and int(ctrl_row_idx) >= 1 and int(ctrl_row_idx) <= len(ctrl_df): | |
| df.loc[int(ctrl_row_idx) - 1] = row | |
| else: | |
| df = pd.concat([df, pd.DataFrame([row])], ignore_index=True) | |
| # 4.3.基于已更新的 df 构造下拉 | |
| groups_update = build_ctrl_dropdowns(df) | |
| return gr.update(value=validate_msg), groups_update, gr.update(value=df) | |
| else: | |
| # 4.4.校验不通过:不修改 df,但仍返回(提示 + 使用当前 ctrl_df 构造下拉) | |
| groups_update = build_ctrl_dropdowns(ctrl_df) | |
| return gr.update(value=validate_msg), groups_update, gr.update(value=ctrl_df) | |
| def apply_ctrl_append(ctrl_df: pd.DataFrame, ctrl_row_idx: int | None, ctrl_del_row_idx: int | None, | |
| name: str, metric: str, metric_type: str, | |
| c_mean: float | None, c_sd: float | None, | |
| c_n_rate: float | None, c_n_mean: float | None, | |
| c_conv: float | None): | |
| # if all((pd.isna(x) or x == "") for x in ctrl_df.iloc[0]): # 20251008 13:29修改 | |
| if ctrl_df is None or ctrl_df.empty: | |
| return apply_ctrl_row(ctrl_df, 1, None, name, metric, metric_type, | |
| c_mean, c_sd, c_n_rate, c_n_mean, c_conv, 'append') | |
| else: | |
| # 调用 apply_ctrl_row 添加/覆盖行 | |
| return apply_ctrl_row(ctrl_df, None, None, name, metric, metric_type, | |
| c_mean, c_sd, c_n_rate, c_n_mean, c_conv, 'append') | |
| def apply_ctrl_edit(ctrl_df: pd.DataFrame, ctrl_row_idx: int | None, ctrl_del_row_idx: int | None, name: str, metric: str, metric_type: str, | |
| c_mean: float | None, c_sd: float | None, | |
| c_n_rate: float | None, c_n_mean: float | None, | |
| c_conv: float | None): | |
| # if all((pd.isna(x) or x == "") for x in ctrl_df.iloc[0]): | |
| if ctrl_df is None or ctrl_df.empty: # 20251008 13:29修改 | |
| return gr.update(value=f'🚫当前无可编辑记录'), [], gr.update(value=ctrl_df) | |
| elif ctrl_row_idx and int(ctrl_row_idx) >= 1 and int(ctrl_row_idx) <= len(ctrl_df): | |
| return apply_ctrl_row(ctrl_df, ctrl_row_idx, None, name, metric, metric_type, c_mean, c_sd, c_n_rate, c_n_mean, c_conv, 'edit') | |
| else: | |
| return gr.update(value=f'🚫编辑行数不存在,可编辑行数为[1 , {len(ctrl_df)}],请重新输入'), [], gr.update(value=ctrl_df) | |
| def apply_ctrl_delete(ctrl_df: pd.DataFrame, ctrl_del_row_idx: int | None): | |
| # if all((pd.isna(x) or x == "") for x in ctrl_df.iloc[0]): | |
| if ctrl_df is None or ctrl_df.empty: # 20251008 13:29修改 | |
| return gr.update(value=f'🚫当前无可删除记录'), [], gr.update(value=ctrl_df) | |
| elif ctrl_del_row_idx and int(ctrl_del_row_idx) >= 1 and int(ctrl_del_row_idx) <= len(ctrl_df): | |
| df = ctrl_df.drop(ctrl_del_row_idx-1,axis=0).reset_index(drop=True) | |
| groups_update = build_ctrl_dropdowns(df) | |
| return gr.update(value="✅删除成功"), groups_update, gr.update(value=df) | |
| else: | |
| return gr.update(value=f'🚫删除行数不存在,可删除行数为[1 , {len(ctrl_df)}],请重新输入'), [], gr.update(value=ctrl_df) | |
| # ---------- 行编辑/追加(实验组) ---------- | |
| def apply_exp_row(exp_df: pd.DataFrame, exp_row_idx: int | None, exp_del_row_idx: int | None, | |
| exp_name: str, group: str, pair: str, metric_type: str, | |
| alt: str, | |
| e_mean: float | None, e_sd: float | None, | |
| e_n_rate: float | None, e_n_mean: float | None, | |
| e_conv: float | None, | |
| ctrl_df: pd.DataFrame, | |
| edit_method = 'append'): | |
| # 1.获取对比对照组&指标的信息 | |
| # 若从 pair 里解析到 group/metric,则优先使用,再用独立的 group 覆盖 group | |
| metric = str(pair).strip() | |
| # 获取对照组的指标 | |
| target_row = ctrl_df.apply(lambda x: (str(x["对照组名称"]).strip() == str(group).strip()) & ( | |
| str(x["指标名称"]).strip() == str(pair).strip()), axis=1) | |
| target_ctrl_df = ctrl_df.loc[target_row] | |
| # 2.创建存储新输入信息的变量row | |
| # 添加新的行 | |
| row = {c: None for c in EXP_COLUMNS} | |
| row.update({ | |
| "实验组名称": (exp_name or "").strip(), | |
| "对比对照组": (group or "").strip(), | |
| "对比指标": metric, | |
| "指标类型": metric_type if metric_type in LOCK_METRIC_TYPES else "", | |
| "检验类型": alt if alt in LOCK_ALT_TYPES else "two-sided", | |
| }) | |
| # 判断根据指标类型,确定e_n取值来源 | |
| if metric_type == 'mean': | |
| e_n = e_n_mean | |
| c_mean = None if target_ctrl_df.empty else target_ctrl_df["对照组均值"].values[0] | |
| c_sd = None if target_ctrl_df.empty else target_ctrl_df["对照组标准差"].values[0] | |
| c_n = None if target_ctrl_df.empty else target_ctrl_df["对照组样本量"].values[0] | |
| row.update({"实验组均值": e_mean, "实验组标准差": e_sd, "实验组样本量": e_n, "实验组转化人数": None, | |
| "对照组均值": c_mean, "对照组标准差": c_sd, "对照组样本量": c_n, "对照组转化人数": None}) | |
| elif metric_type == 'ratio': | |
| e_n = e_n_rate | |
| c_n = None if target_ctrl_df.empty else target_ctrl_df["对照组样本量"].values[0] | |
| c_conv = None if target_ctrl_df.empty else target_ctrl_df["对照组转化人数"].values[0] | |
| row.update({"实验组均值": None, "实验组标准差": None, "实验组样本量": e_n, "实验组转化人数": e_conv, | |
| "对照组均值": None, "对照组标准差": None, "对照组样本量": c_n, "对照组转化人数": c_conv}) | |
| # 3.校验 | |
| feedback, validate_msg = _validate_experiments(row) # 20251008 10:53,删除了"exp_row_idx, exp_del_row_idx, exp_df"三个参数 | |
| # 4.检查 DataFrame 是否为空 | |
| if exp_df.empty: | |
| df = _empty_exp_df().copy() | |
| else: | |
| df = exp_df.copy() | |
| # 4.根据输入信息正确情况,返回内容 | |
| if feedback: | |
| # 4.1.判断是否存在重复值,若存在则停止录入/编辑动作 | |
| if edit_method == 'append': | |
| if row["指标类型"] == 'ratio': | |
| is_duplicate = ((exp_df["实验组名称"] == row["实验组名称"]) & | |
| (exp_df["对比对照组"] == row["对比对照组"]) & | |
| (exp_df["对比指标"] == row["对比指标"]) & | |
| (exp_df["检验类型"] == row["检验类型"])).any() | |
| else: | |
| is_duplicate = ((exp_df["实验组名称"] == row["实验组名称"]) & | |
| (exp_df["对比对照组"] == row["对比对照组"]) & | |
| (exp_df["对比指标"] == row["对比指标"]) & | |
| (exp_df["检验类型"] == row["检验类型"])).any() | |
| elif edit_method == 'edit': | |
| if row["指标类型"] == 'ratio': | |
| is_duplicate = ((exp_df["实验组名称"] == row["实验组名称"]) & | |
| (exp_df["对比对照组"] == row["对比对照组"]) & | |
| (exp_df["对比指标"] == row["对比指标"]) & | |
| (exp_df["检验类型"] == row["检验类型"]) & | |
| (exp_df["实验组样本量"] == row["实验组样本量"]) & | |
| (exp_df["实验组转化人数"] == row["实验组转化人数"])).any() | |
| else: | |
| is_duplicate = ((exp_df["实验组名称"] == row["实验组名称"]) & | |
| (exp_df["对比对照组"] == row["对比对照组"]) & | |
| (exp_df["对比指标"] == row["对比指标"]) & | |
| (exp_df["检验类型"] == row["检验类型"]) & | |
| (exp_df["实验组均值"] == row["实验组均值"]) & | |
| (exp_df["实验组标准差"] == row["实验组标准差"]) & | |
| (exp_df["实验组样本量"] == row["实验组样本量"])).any() | |
| if is_duplicate: | |
| return gr.update(value='🚫该实验组实验数据已存在,请勿重复录入'), gr.update(value=exp_df) | |
| # 4.2.写入或追加 | |
| # 应用到指定行(1-based),若无或越界则追加 | |
| if exp_row_idx and int(exp_row_idx) >= 1 and int(exp_row_idx) <= len(exp_df): | |
| df.loc[int(exp_row_idx) - 1] = row | |
| else: | |
| df = pd.concat([df, pd.DataFrame([row])], ignore_index=True) | |
| return gr.update(value=validate_msg),gr.update(value=df) | |
| else: | |
| # 4.3.校验不通过:不修改df,但仍返回提示 | |
| return gr.update(value=validate_msg), gr.update(value=df) | |
| def apply_exp_append(exp_df: pd.DataFrame, exp_row_idx: int | None, exp_del_row_idx: int | None, | |
| exp_name: str, group: str, pair: str, metric_type: str, | |
| alt: str, | |
| e_mean: float | None, e_sd: float | None, | |
| e_n_rate: float | None, e_n_mean: float | None, | |
| e_conv: float | None, | |
| ctrl_df: pd.DataFrame): | |
| # if all((pd.isna(x) or x == "") for x in exp_df.iloc[0]): | |
| if exp_df is None or exp_df.empty: # 20251008 13:29修改 | |
| return apply_exp_row(exp_df, 1, None, exp_name, group, pair, metric_type, | |
| alt, e_mean, e_sd, e_n_rate, e_n_mean, e_conv, ctrl_df, 'append') | |
| else: | |
| # 调用 apply_exp_row 添加/覆盖行 | |
| return apply_exp_row(exp_df, None, None, exp_name, group, pair, metric_type, | |
| alt, e_mean, e_sd, e_n_rate, e_n_mean, e_conv, ctrl_df, 'append') | |
| def apply_exp_edit(exp_df: pd.DataFrame, exp_row_idx: int | None, exp_del_row_idx: int | None, | |
| exp_name: str, group: str, pair: str, metric_type: str, | |
| alt: str, | |
| e_mean: float | None, e_sd: float | None, | |
| e_n_rate: float | None, e_n_mean: float | None, | |
| e_conv: float | None, | |
| ctrl_df: pd.DataFrame): | |
| # if all((pd.isna(x) or x == "") for x in exp_df.iloc[0]): | |
| if exp_df is None or exp_df.empty: # 20251008 13:29修改 | |
| return gr.update(value=f'🚫当前无可编辑记录'), gr.update(value=exp_df) | |
| elif exp_row_idx and int(exp_row_idx) >= 1 and int(exp_row_idx) <= len(exp_df): | |
| return apply_exp_row(exp_df, exp_row_idx, None, exp_name, group, pair, metric_type, | |
| alt, e_mean, e_sd, e_n_rate, e_n_mean, e_conv, ctrl_df, 'edit') | |
| else: | |
| return gr.update(value=f'🚫编辑行数不存在,可编辑行数为[1 , {len(exp_df)}],请重新输入'), gr.update(value=exp_df) | |
| def apply_exp_delete(exp_df: pd.DataFrame, exp_del_row_idx: int | None): | |
| # if all((pd.isna(x) or x == "") for x in exp_df.iloc[0]): | |
| if exp_df is None or exp_df.empty: # 20251008 13:29修改 | |
| return gr.update(value=f'🚫当前无可删除记录'), gr.update(value=exp_df) | |
| if exp_del_row_idx and int(exp_del_row_idx) >= 1 and int(exp_del_row_idx) <= len(exp_df): | |
| df = exp_df.drop(exp_del_row_idx-1,axis=0).reset_index(drop=True) | |
| return gr.update(value="✅删除成功"), gr.update(value=df) | |
| else: | |
| return gr.update(value=f'🚫删除行数不存在,可删除行数为[1 , {len(exp_df)}],请重新输入'), gr.update(value=exp_df) | |
| # ---------- 显隐切换 ---------- | |
| def toggle_mean_rate(metric_type: str): | |
| show_mean = metric_type == "mean" | |
| show_rate = metric_type == "ratio" | |
| return gr.update(visible=show_mean), gr.update(visible=show_rate) | |
| def update_exp_compare_metric(ctrl_df,dd_control_groups): | |
| if ctrl_df is None or ctrl_df.empty or not dd_control_groups: | |
| return gr.update(choices=[],value=None) | |
| target_row = ctrl_df.apply(lambda x: str(x["对照组名称"]).strip() == str(dd_control_groups).strip(),axis=1) | |
| options = ctrl_df.loc[target_row,"指标名称"].astype(str).str.strip().tolist() | |
| return gr.update(choices=options, value=None) | |
| def update_exp_metric_type(ctrl_df,dd_control_groups,dd_ctrl_pairs): | |
| if ctrl_df is None or ctrl_df.empty or not dd_control_groups or not dd_ctrl_pairs: | |
| return gr.update(value=None) | |
| target_row = ctrl_df.apply(lambda x: (str(x["对照组名称"]).strip() == str(dd_control_groups).strip()) & (str(x["指标名称"]).strip() == str(dd_ctrl_pairs).strip()),axis=1) | |
| metric_type = ctrl_df.loc[target_row,"指标类型"].astype(str).str.strip() | |
| return gr.update(value=metric_type.iloc[0] if not metric_type.empty else None) | |
| def _label_edit(n): | |
| try: | |
| i = int(n) | |
| return gr.update(value=f"编辑 {i} 行") | |
| except: | |
| return gr.update(value="编辑 行") | |
| def _label_delete(n): | |
| try: | |
| i = int(n) | |
| return gr.update(value=f"删除 {i} 行") | |
| except: | |
| return gr.update(value="删除 行") | |
| def upload_exp_df(file, exp_df): | |
| # 记录exp_df原始行数 | |
| rows_raw = len(exp_df) | |
| # 读取上传的Excel文件 | |
| new_exp_df = pd.read_excel(file) | |
| # 对齐列名 | |
| new_exp_df.columns = exp_df.columns | |
| # 校验每一行数据 | |
| new_exp_df = new_exp_df.fillna("") # 将空值替换为"",保证与_validate_experiments处理缺失值的格式能够对应 | |
| for i, row in new_exp_df.iterrows(): | |
| valid, msg = _validate_experiments(row) | |
| if not valid: | |
| gr.Info(f"🚫第{i + 1}行实验数据异常:{msg},请修正后再次上传") | |
| return exp_df | |
| # 校验无误后去重更新 | |
| exp_df = pd.concat([exp_df, new_exp_df], ignore_index=True) | |
| exp_df = exp_df.dropna(how='all').drop_duplicates() | |
| # 记录exp_df更新后行数 | |
| rows_update = len(exp_df) | |
| gr.Info(f"✅上传成功,共新增 {rows_update - rows_raw} 行数据。") | |
| return exp_df | |
| def clear_exp_df(exp_df): | |
| gr.Info("已清除上传文件,不影响当前已录入的数据") | |
| return exp_df | |
| # ---------- 分析(占位) ---------- | |
| def start_analysis(exp_df: pd.DataFrame, conf: float, method: str): | |
| res_df = exp_df.copy() | |
| exp_cnt = res_df.shape[0] # 实验数量 | |
| mapping = { | |
| "larger": "greater", | |
| "smaller": "less", | |
| } | |
| res_df["置信度"] = conf * 100 | |
| for i,r in res_df.iterrows(): | |
| ctrl_suc = r.get("对照组转化人数",None) | |
| ctrl_total = r.get("对照组样本量",None) | |
| ctrl_mean = r.get("对照组均值",None) | |
| ctrl_std = r.get("对照组标准差",None) | |
| exp_suc = r.get("实验组转化人数",None) | |
| exp_total = r.get("实验组样本量",None) | |
| exp_mean = r.get("实验组均值",None) | |
| exp_std = r.get("实验组标准差",None) | |
| metric_type = str(r.get("指标类型","")).strip() | |
| if metric_type == 'mean': | |
| r["检验类型"] = mapping.get( | |
| r.get("检验类型", ""), # 用 r.get 避免 KeyError | |
| r.get("检验类型", "") | |
| ) | |
| alternative = str(r.get("检验类型","")).strip() | |
| if metric_type == 'ratio': | |
| res_df.loc[i, "实验组转化率"] = r["实验组转化人数"] / r["实验组样本量"] | |
| res_df.loc[i, "对照组转化率"] = r["对照组转化人数"] / r["对照组样本量"] | |
| res_df.loc[i, "绝对提升"]= res_df.loc[i, "实验组转化率"] - res_df.loc[i, "对照组转化率"] | |
| res_df.loc[i, "相对提升"] = res_df.loc[i, "实验组转化率"] / res_df.loc[i, "对照组转化率"] - 1 | |
| elif metric_type == 'mean': | |
| res_df.loc[i, "实验组转化率"] = None | |
| res_df.loc[i, "对照组转化率"] = None | |
| res_df.loc[i, "绝对提升"] = r["实验组均值"] - r["对照组均值"] | |
| res_df.loc[i, "相对提升"] = r["实验组均值"] / r["对照组均值"] - 1 | |
| p_value, uplift_conf_interval, exp_conf_interval, ctrl_conf_interval,\ | |
| uplift_conf_interval_adj, exp_conf_interval_adj, ctrl_conf_interval_adj = ab_test_result( | |
| ctrl_suc, ctrl_total, ctrl_mean, ctrl_std, | |
| exp_suc, exp_total, exp_mean, exp_std, | |
| metric_type, alternative, | |
| conf, method, exp_cnt) | |
| res_df.loc[i,"p值(原始)"] = p_value | |
| res_df.loc[i, "提升置信区间(调整前)"] = uplift_conf_interval | |
| res_df.loc[i, "实验组置信区间(调整前)"] = exp_conf_interval | |
| res_df.loc[i, "对照组置信区间(调整前)"] = ctrl_conf_interval | |
| res_df.loc[i, "提升置信区间(调整后)"] = uplift_conf_interval_adj | |
| res_df.loc[i, "实验组置信区间(调整后)"] = exp_conf_interval_adj | |
| res_df.loc[i, "对照组置信区间(调整后)"] = ctrl_conf_interval_adj | |
| p_values_list = res_df["p值(原始)"].tolist() | |
| reject, p_value_corrected = adjust_p_values(p_values_list, conf, method) | |
| res_df["p值(调整后)"] = pd.Series(p_value_corrected, index=res_df.index) | |
| res_df["是否置信"] = pd.Series(reject, index=res_df.index) | |
| res_df = result_format(res_df) | |
| # res_df = res_df[["实验组名称","对比对照组","对比指标","指标类型","检验类型","实验组均值",\ | |
| # "实验组标准差","实验组样本量","实验组转化人数","实验组转化率","对照组均值","对照组标准差","对照组样本量","对照组转化人数",\ | |
| # "对照组转化率","置信度","是否置信","p值(调整后)","p值(原始)","提升置信区间(调整后)","提升置信区间(调整前)","实验组置信区间(调整后)",\ | |
| # "实验组置信区间(调整前)","对照组置信区间(调整后)","对照组置信区间(调整前)","绝对提升","相对提升"]] # 20251209 | |
| res_df = res_df[["实验组名称","对比对照组","对比指标","置信度","是否置信","绝对提升","相对提升","p值(调整后)","p值(原始)","指标类型","检验类型","实验组样本量","对照组样本量"]] # 20251209 | |
| gr.Info(f"✅多重检验分析已完成") | |
| return gr.update(value=res_df, visible=True) | |
| # 下载实验分析数据 | |
| def res_df_to_csv(res_df: pd.DataFrame): | |
| ts = time.strftime("%Y%m%d-%H%M%S") | |
| # 创建临时文件 | |
| tmpdir = tempfile.mkdtemp(prefix="abtest_") | |
| file_path = os.path.join(tmpdir, f"multi_test_results_{ts}.csv") | |
| # 写入文件 | |
| res_df.to_csv(file_path, index=False, encoding="utf-8-sig") | |
| # 返回文件路径给 DownloadButton | |
| return file_path | |