Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -580,17 +580,54 @@ if uploaded_file is not None:
|
|
| 580 |
|
| 581 |
# 新文件或未處理過,開始預測
|
| 582 |
user_df = pd.read_csv(uploaded_file)
|
| 583 |
-
st.success(f"✅ 成功讀取 {len(user_df)} 筆資料
|
| 584 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
|
| 586 |
with st.spinner("正在進行預測..."):
|
| 587 |
-
df_result = predict_from_uploaded_csv(
|
| 588 |
|
| 589 |
if not df_result.empty:
|
| 590 |
st.session_state.prediction_data = df_result
|
| 591 |
st.session_state.all_columns = df_result.columns.tolist()
|
| 592 |
st.session_state.uploaded_file_name = current_file_name
|
| 593 |
-
st.session_state.processed_data =
|
| 594 |
st.success("🎉 預測完成!")
|
| 595 |
else:
|
| 596 |
st.error("預測失敗,請檢查資料格式")
|
|
@@ -606,21 +643,204 @@ if uploaded_file is not None:
|
|
| 606 |
# 預測結果展示與下載
|
| 607 |
if st.session_state.prediction_data is not None:
|
| 608 |
df = st.session_state.prediction_data
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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markdown("### 📊 統計圖表")
|
|
|
|
| 580 |
|
| 581 |
# 新文件或未處理過,開始預測
|
| 582 |
user_df = pd.read_csv(uploaded_file)
|
| 583 |
+
st.success(f"✅ 成功讀取 {len(user_df)} 筆資料")
|
| 584 |
+
|
| 585 |
+
# === 輸入篩選區域 ===
|
| 586 |
+
with st.expander("📅 資料期間篩選", expanded=True):
|
| 587 |
+
col1, col2 = st.columns(2)
|
| 588 |
+
|
| 589 |
+
# 獲取資料的時間範圍
|
| 590 |
+
user_df['event_time'] = pd.to_datetime(user_df['event_time'])
|
| 591 |
+
min_date = user_df['event_time'].min().date()
|
| 592 |
+
max_date = user_df['event_time'].max().date()
|
| 593 |
+
|
| 594 |
+
with col1:
|
| 595 |
+
start_date = st.date_input(
|
| 596 |
+
"起始日期",
|
| 597 |
+
value=min_date,
|
| 598 |
+
min_value=min_date,
|
| 599 |
+
max_value=max_date
|
| 600 |
+
)
|
| 601 |
+
|
| 602 |
+
with col2:
|
| 603 |
+
end_date = st.date_input(
|
| 604 |
+
"截止日期",
|
| 605 |
+
value=max_date,
|
| 606 |
+
min_value=min_date,
|
| 607 |
+
max_value=max_date
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
# 套用日期篩選
|
| 611 |
+
if start_date <= end_date:
|
| 612 |
+
filtered_df = user_df[
|
| 613 |
+
(user_df['event_time'].dt.date >= start_date) &
|
| 614 |
+
(user_df['event_time'].dt.date <= end_date)
|
| 615 |
+
]
|
| 616 |
+
st.info(f"篩選後資料: {len(filtered_df)} 筆 ({start_date} ~ {end_date})")
|
| 617 |
+
else:
|
| 618 |
+
st.error("起始日期不能大於截止日期")
|
| 619 |
+
filtered_df = user_df
|
| 620 |
+
|
| 621 |
+
st.dataframe(filtered_df.head(10), use_container_width=True)
|
| 622 |
|
| 623 |
with st.spinner("正在進行預測..."):
|
| 624 |
+
df_result = predict_from_uploaded_csv(filtered_df)
|
| 625 |
|
| 626 |
if not df_result.empty:
|
| 627 |
st.session_state.prediction_data = df_result
|
| 628 |
st.session_state.all_columns = df_result.columns.tolist()
|
| 629 |
st.session_state.uploaded_file_name = current_file_name
|
| 630 |
+
st.session_state.processed_data = filtered_df
|
| 631 |
st.success("🎉 預測完成!")
|
| 632 |
else:
|
| 633 |
st.error("預測失敗,請檢查資料格式")
|
|
|
|
| 643 |
# 預測結果展示與下載
|
| 644 |
if st.session_state.prediction_data is not None:
|
| 645 |
df = st.session_state.prediction_data
|
| 646 |
+
|
| 647 |
+
# === 輸出篩選區域 ===
|
| 648 |
+
st.markdown("### 🎯 結果篩選")
|
| 649 |
+
|
| 650 |
+
with st.expander("🔍 進階篩選選項", expanded=True):
|
| 651 |
+
col1, col2 = st.columns(2)
|
| 652 |
+
|
| 653 |
+
with col1:
|
| 654 |
+
# 1️⃣ 最近n步內踩過特定行為的用戶
|
| 655 |
+
st.markdown("**1️⃣ 歷史行為篩選**")
|
| 656 |
+
history_steps = st.selectbox("最近幾步內", options=list(range(2, 10)), index=6) # 預設8步
|
| 657 |
+
|
| 658 |
+
# 收集所有可能的 action_group
|
| 659 |
+
history_columns = [f"-{i}_action_group" for i in range(2, 10)]
|
| 660 |
+
all_history_actions = set()
|
| 661 |
+
for col in history_columns:
|
| 662 |
+
if col in df.columns:
|
| 663 |
+
all_history_actions.update(df[col].dropna().unique())
|
| 664 |
+
all_history_actions = sorted([x for x in all_history_actions if pd.notna(x)])
|
| 665 |
+
|
| 666 |
+
selected_history_actions = st.multiselect(
|
| 667 |
+
"曾經執行的行為",
|
| 668 |
+
options=all_history_actions,
|
| 669 |
+
help="選擇用戶在歷史中曾經執行過的行為"
|
| 670 |
+
)
|
| 671 |
+
|
| 672 |
+
with col2:
|
| 673 |
+
# 2️⃣ 下一步Top N預測篩選
|
| 674 |
+
st.markdown("**2️⃣ 預測行為篩選**")
|
| 675 |
+
top_n = st.selectbox("檢查Top幾的預測", options=[1, 2, 3, 4, 5], index=0)
|
| 676 |
+
|
| 677 |
+
# 收集所有可能的預測 action_group
|
| 678 |
+
prediction_columns = [f"Top{i}_next_action_group" for i in range(1, 6)]
|
| 679 |
+
all_prediction_actions = set()
|
| 680 |
+
for col in prediction_columns:
|
| 681 |
+
if col in df.columns:
|
| 682 |
+
all_prediction_actions.update(df[col].dropna().unique())
|
| 683 |
+
all_prediction_actions = sorted([x for x in all_prediction_actions if pd.notna(x)])
|
| 684 |
+
|
| 685 |
+
selected_prediction_actions = st.multiselect(
|
| 686 |
+
"預測的下一步行為",
|
| 687 |
+
options=all_prediction_actions,
|
| 688 |
+
help="選擇預測的下一步行為"
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
# 3️⃣ Top1 機率門檻
|
| 692 |
+
st.markdown("**3️⃣ 預測信心門檻**")
|
| 693 |
+
min_confidence = st.number_input(
|
| 694 |
+
"Top1 最低機率",
|
| 695 |
+
min_value=0.0,
|
| 696 |
+
max_value=1.0,
|
| 697 |
+
value=0.0,
|
| 698 |
+
step=0.01,
|
| 699 |
+
help="設定 Top1 預測的最低信心分數(0-1之間)"
|
| 700 |
)
|
| 701 |
+
|
| 702 |
+
if not (0.0 <= min_confidence <= 1.0):
|
| 703 |
+
st.error("⚠️ 機率值必須在 0.0 到 1.0 之間,請重新輸入")
|
| 704 |
+
min_confidence = 0.0
|
| 705 |
+
|
| 706 |
+
# 套用篩選邏輯
|
| 707 |
+
filtered_df = df.copy()
|
| 708 |
+
filter_conditions = [] # 記錄篩選條件
|
| 709 |
+
|
| 710 |
+
# 1️⃣ 歷史行為篩選
|
| 711 |
+
if selected_history_actions:
|
| 712 |
+
history_mask = pd.Series([False] * len(filtered_df))
|
| 713 |
+
for _, row in filtered_df.iterrows():
|
| 714 |
+
for step in range(2, history_steps + 2):
|
| 715 |
+
col_name = f"-{step}_action_group"
|
| 716 |
+
if col_name in row and row[col_name] in selected_history_actions:
|
| 717 |
+
history_mask[row.name] = True
|
| 718 |
+
break
|
| 719 |
+
filtered_df = filtered_df[history_mask]
|
| 720 |
+
|
| 721 |
+
# 記錄篩選條件
|
| 722 |
+
actions_text = "、".join(selected_history_actions)
|
| 723 |
+
filter_conditions.append(f"最近{history_steps}步內曾踩過:{actions_text}")
|
| 724 |
+
|
| 725 |
+
# 2️⃣ 預測行為篩選
|
| 726 |
+
if selected_prediction_actions:
|
| 727 |
+
prediction_mask = pd.Series([False] * len(filtered_df))
|
| 728 |
+
for _, row in filtered_df.iterrows():
|
| 729 |
+
for n in range(1, top_n + 1):
|
| 730 |
+
col_name = f"Top{n}_next_action_group"
|
| 731 |
+
if col_name in row and row[col_name] in selected_prediction_actions:
|
| 732 |
+
prediction_mask[row.name] = True
|
| 733 |
+
break
|
| 734 |
+
filtered_df = filtered_df[prediction_mask]
|
| 735 |
+
|
| 736 |
+
# 記錄篩選條件
|
| 737 |
+
actions_text = "、".join(selected_prediction_actions)
|
| 738 |
+
filter_conditions.append(f"下一步的Top{top_n}可能為:{actions_text}")
|
| 739 |
+
|
| 740 |
+
# 3️⃣ Top1 機率門檻篩選
|
| 741 |
+
if min_confidence > 0.0:
|
| 742 |
+
filtered_df = filtered_df[filtered_df['Top1_confidence'] >= min_confidence]
|
| 743 |
+
filter_conditions.append(f"Top1的最低機率需大於等於:{min_confidence}")
|
| 744 |
+
|
| 745 |
+
# 📋 篩選條件總結
|
| 746 |
+
st.markdown("### 📋 篩選條件總結")
|
| 747 |
+
|
| 748 |
+
if filter_conditions:
|
| 749 |
+
# 獲取日期篩選資訊
|
| 750 |
+
if 'start_date' in locals() and 'end_date' in locals():
|
| 751 |
+
date_range = f"在 {start_date} ~ {end_date} 之間"
|
| 752 |
+
else:
|
| 753 |
+
date_range = "在所選日期範圍內"
|
| 754 |
+
|
| 755 |
+
# 構建條件描述
|
| 756 |
+
conditions_text = f"""
|
| 757 |
+
**您的篩選條件為:**
|
| 758 |
+
|
| 759 |
+
{date_range},
|
| 760 |
+
"""
|
| 761 |
+
|
| 762 |
+
for i, condition in enumerate(filter_conditions):
|
| 763 |
+
if i == 0:
|
| 764 |
+
conditions_text += f"{condition}"
|
| 765 |
+
else:
|
| 766 |
+
conditions_text += f"\n且 {condition}"
|
| 767 |
+
|
| 768 |
+
conditions_text += f"""
|
| 769 |
+
|
| 770 |
+
**當前條件下,全數符合的用戶數量共有:{len(filtered_df)} 人**
|
| 771 |
+
"""
|
| 772 |
+
|
| 773 |
+
st.markdown(conditions_text)
|
| 774 |
+
|
| 775 |
+
# 如果有篩選但無結果
|
| 776 |
+
if len(filtered_df) == 0:
|
| 777 |
+
st.warning("⚠️ 沒有符合所有篩選條件的用戶")
|
| 778 |
+
else:
|
| 779 |
+
# 沒有設定任何篩選條件
|
| 780 |
+
st.info("🔍 目前未設定任何篩選條件,顯示所有預測結果")
|
| 781 |
+
st.markdown(f"**用戶總數:{len(filtered_df)} 人**")
|
| 782 |
+
|
| 783 |
+
# 顯示篩選結果
|
| 784 |
+
if len(filtered_df) > 0:
|
| 785 |
+
with st.expander("📊 查看篩選結果", expanded=False):
|
| 786 |
+
st.dataframe(filtered_df, use_container_width=True)
|
| 787 |
+
else:
|
| 788 |
+
st.warning("⚠️ 沒有符合篩選條件的資料")
|
| 789 |
|
| 790 |
+
# 4️⃣ 下載設定
|
| 791 |
+
if len(filtered_df) > 0:
|
| 792 |
+
with st.expander("📥 下載設定", expanded=True):
|
| 793 |
+
st.markdown("**選擇輸出欄位**")
|
| 794 |
+
|
| 795 |
+
# 提供快速選項
|
| 796 |
+
col1, col2, col3 = st.columns(3)
|
| 797 |
+
with col1:
|
| 798 |
+
if st.button("🔄 全選"):
|
| 799 |
+
st.session_state.selected_columns = st.session_state.all_columns
|
| 800 |
+
with col2:
|
| 801 |
+
if st.button("📊 核心欄位"):
|
| 802 |
+
core_columns = [
|
| 803 |
+
'user_pseudo_id', 'last_event_time', 'last_action_group',
|
| 804 |
+
'Top1_next_action_group', 'Top1_confidence',
|
| 805 |
+
'Online_conversion_prob', 'O2O_reservation_prob', 'Marketing_Strategy'
|
| 806 |
+
]
|
| 807 |
+
st.session_state.selected_columns = [col for col in core_columns if col in st.session_state.all_columns]
|
| 808 |
+
with col3:
|
| 809 |
+
if st.button("🎯 預測欄位"):
|
| 810 |
+
prediction_cols = [col for col in st.session_state.all_columns if 'Top' in col or 'prob' in col]
|
| 811 |
+
st.session_state.selected_columns = prediction_cols
|
| 812 |
+
|
| 813 |
+
# 欄位多選器
|
| 814 |
+
if 'selected_columns' not in st.session_state:
|
| 815 |
+
st.session_state.selected_columns = st.session_state.all_columns
|
| 816 |
+
|
| 817 |
+
selected_columns = st.multiselect(
|
| 818 |
+
"選擇要輸出的欄位",
|
| 819 |
+
options=st.session_state.all_columns,
|
| 820 |
+
default=st.session_state.selected_columns,
|
| 821 |
+
key="column_selector"
|
| 822 |
+
)
|
| 823 |
+
|
| 824 |
+
if selected_columns:
|
| 825 |
+
csv = filtered_df[selected_columns].to_csv(index=False).encode("utf-8-sig")
|
| 826 |
+
|
| 827 |
+
# 根據篩選條件生成檔名
|
| 828 |
+
if filter_conditions:
|
| 829 |
+
filename = f"prediction_result_filtered_{len(filtered_df)}users.csv"
|
| 830 |
+
else:
|
| 831 |
+
filename = f"prediction_result_all_{len(filtered_df)}users.csv"
|
| 832 |
+
|
| 833 |
+
st.download_button(
|
| 834 |
+
"📥 下載結果 CSV",
|
| 835 |
+
data=csv,
|
| 836 |
+
file_name=filename,
|
| 837 |
+
mime="text/csv",
|
| 838 |
+
help=f"下載 {len(filtered_df)} 位用戶的篩選結果"
|
| 839 |
+
)
|
| 840 |
+
else:
|
| 841 |
+
st.warning("請選擇至少一個欄位")
|
| 842 |
else:
|
| 843 |
+
st.error("📥 無法下載:沒有符合條件的資料")
|
| 844 |
|
| 845 |
# 視覺化圖表
|
| 846 |
st.markdown("### 📊 統計圖表")
|