Spaces:
Runtime error
Runtime error
File size: 46,308 Bytes
ce06eb4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 | """
数据指标建模助手 - Streamlit Web 应用主入口(v3.0)
模块说明:
本模块是数据指标建模助手的 Streamlit Web 应用主入口,提供完整的指标建模工作流。
应用采用三步式设计,引导用户从需求输入到方案生成的完整过程。
主要功能:
1. Step 1 - 输入需求:支持文本输入、文件上传、业务类型选择
2. Step 2 - 选择指标:展示 AI 生成的指标,支持多选
3. Step 3 - 查看方案:预览指标方案、BI 设计,支持文件下载
Bug 修复记录(v3.0):
- Bug 1: 修复 file_metadata 访问错误
- Bug 2: 修复复选框状态管理(使用 st.session_state 绑定)
- Bug 3: 修复 Step 3 条件检查错误
- Bug 4: 修复 BI 设计赋值错误
- Bug 5: 用户需求 - 添加 SQL 查询语句显示功能
- Bug 6: 用户需求 - 简化下载功能(只生成 2 个 Markdown 文件)
"""
import streamlit as st
import json
import os
from pathlib import Path
import sys
import logging
from typing import Dict, Any, List, Optional
from datetime import datetime
# 可选导入 matplotlib(用于图表渲染)
try:
import matplotlib
matplotlib.use('Agg') # 使用非交互式后端
import matplotlib.pyplot as plt
import numpy as np
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
plt = None
np = None
# 项目路径配置
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))
# 模块导入
from config.settings import FAISS_INDEX_PATH, DEEPSEEK_API_KEY, BUSINESS_TYPES
from agents.requirement_agent import RequirementAgent
from agents.modeling_agent import ModelingAgent
from agents.bi_design_agent import BIDesignAgent
from utils.file_parser import parse_uploaded_file
from models.indicator_set import IndicatorSet
# 日志配置
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ============================================================================
# 文件元数据格式化函数
# ============================================================================
def format_file_metadata(metadata: dict, filename: str = "") -> str:
"""
将文件元数据字典格式化为可读的字符串
参数:
metadata (dict): 文件元数据字典,包含 columns, dtypes, sample_data, row_count 等字段
filename (str): 文件名(可选)
返回:
str: 格式化的文件内容描述字符串,可供 AI 分析使用
"""
if not metadata or not isinstance(metadata, dict):
return "文件内容为空或格式错误"
content_parts = []
# 添加文件名
if filename:
content_parts.append(f"# 文件名称: {filename}\n")
# 添加行数信息
row_count = metadata.get("row_count", 0)
content_parts.append(f"## 数据概览\n- 总行数: {row_count} 行\n")
# 添加列信息
columns = metadata.get("columns", [])
dtypes = metadata.get("dtypes", {})
if columns:
content_parts.append("## 字段列表\n")
for col in columns:
col_type = dtypes.get(col, "未知")
content_parts.append(f"- **{col}** ({col_type})")
content_parts.append("") # 空行
# 添加样本数据
sample_data = metadata.get("sample_data", [])
if sample_data and len(sample_data) > 0:
content_parts.append("## 样本数据\n")
for i, row in enumerate(sample_data[:5], 1): # 只显示前5行
row_str = " | ".join([f"{k}: {v}" for k, v in row.items()])
content_parts.append(f"第 {i} 行: {row_str}")
content_parts.append("")
# 拼接所有部分
return "\n".join(content_parts)
# ============================================================================
# Matplotlib 图表渲染函数
# ============================================================================
def render_chart(chart_type: str, title: str, indicator_name: str):
"""
使用 matplotlib 渲染图表
参数:
chart_type (str): 图表类型(折线图/柱状图/饼图/散点图/热力图等)
title (str): 图表标题
indicator_name (str): 指标名称(用于生成示例数据)
返回:
matplotlib.figure.Figure: 渲染后的图表对象,如果 matplotlib 不可用则返回 None
"""
# 检查 matplotlib 是否可用
if not MATPLOTLIB_AVAILABLE:
return None
try:
# 设置中文字体(兼容不同系统)
plt.rcParams['font.sans-serif'] = ['SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
except:
pass
# 创建图表
fig, ax = plt.subplots(figsize=(8, 5))
# 根据图表类型生成示例数据并渲染
chart_type_lower = chart_type.lower()
if '折线' in chart_type or 'line' in chart_type_lower:
# 折线图:时间序列数据
months = ['1月', '2月', '3月', '4月', '5月', '6月']
if np is not None:
values = np.random.randint(100, 1000, size=6)
else:
values = [100, 300, 500, 400, 600, 800]
ax.plot(months, values, marker='o', linewidth=2, color='#1f77b4')
ax.set_ylabel(indicator_name)
ax.grid(True, alpha=0.3)
elif '柱状' in chart_type or 'bar' in chart_type_lower:
# 柱状图:分类数据
categories = ['品类A', '品类B', '品类C', '品类D', '品类E']
if np is not None:
values = np.random.randint(50, 500, size=5)
else:
values = [50, 200, 350, 150, 300]
ax.bar(categories, values, color='#2ca02c')
ax.set_ylabel(indicator_name)
ax.grid(True, alpha=0.3, axis='y')
elif '饼' in chart_type or 'pie' in chart_type_lower:
# 饼图:占比数据
labels = ['类别A', '类别B', '类别C', '类别D']
if np is not None:
sizes = np.random.randint(10, 40, size=4)
else:
sizes = [35, 25, 20, 20]
ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
elif '散点' in chart_type or 'scatter' in chart_type_lower:
# 散点图:分布数据
n = 50
if np is not None:
x = np.random.randn(n)
y = np.random.randn(n)
else:
x = list(range(n))
y = [i*0.5 + 5 for i in range(n)]
ax.scatter(x, y, alpha=0.6, color='#ff7f0e')
ax.set_xlabel('X 轴')
ax.set_ylabel(indicator_name)
ax.grid(True, alpha=0.3)
elif '热力' in chart_type or 'heat' in chart_type_lower:
# 热力图:矩阵数据
if np is not None:
data = np.random.rand(5, 5)
else:
data = [[0.1*i*j for j in range(5)] for i in range(5)]
im = ax.imshow(data, cmap='YlOrRd', aspect='auto')
plt.colorbar(im, ax=ax)
ax.set_xticks(range(5))
ax.set_yticks(range(5))
ax.set_xticklabels(['A', 'B', 'C', 'D', 'E'])
ax.set_yticklabels(['W1', 'W2', 'W3', 'W4', 'W5'])
elif '雷达' in chart_type or 'radar' in chart_type_lower:
# 雷达图:多维度对比
categories = ['维度A', '维度B', '维度C', '维度D', '维度E']
if np is not None:
values = np.random.randint(2, 10, size=5).tolist()
else:
values = [3, 5, 7, 4, 6]
values += values[:1] # 闭合圆形
angles = [n / float(len(categories)) * 2 * 3.14159 for n in range(len(categories))]
angles += angles[:1]
ax = plt.subplot(111, projection='polar')
ax.plot(angles, values, 'o-', linewidth=2)
ax.fill(angles, values, alpha=0.25)
ax.set_xticks(angles[:-1])
ax.set_xticklabels(categories)
elif '仪表' in chart_type or 'gauge' in chart_type_lower:
# 仪表盘:进度/完成率
if np is not None:
value = np.random.randint(30, 90)
else:
value = 65
# 创建仪表盘效果
ax.pie([value, 100-value], startangle=90, counterclock=False,
colors=['#2ca02c', '#d62728'], wedgeprops=dict(width=0.3))
ax.text(0, 0, f'{value}%', ha='center', va='center', fontsize=24, fontweight='bold')
ax.set_title('完成率', fontsize=12)
ax.axis('equal')
elif '漏斗' in chart_type or 'funnel' in chart_type_lower:
# 漏斗图:转化流程
stages = ['访问', '注册', '浏览', '加购', '下单', '支付']
if np is not None:
values = np.random.randint(100, 1000, size=6)
else:
values = [1000, 800, 600, 400, 200, 100]
# 归一化到0-1
max_val = max(values)
normalized = [v/max_val for v in values]
for i, (stage, val, norm) in enumerate(zip(stages, values, normalized)):
ax.barh(i, norm, height=0.6, color=plt.cm.Blues(0.3 + 0.7*norm))
ax.text(norm + 0.02, i, f'{stage}: {val}', va='center')
ax.set_yticks(range(len(stages)))
ax.set_yticklabels(stages)
ax.set_xlim(0, 1.2)
ax.set_xlabel('转化率')
else:
# 默认:折线图
months = ['1月', '2月', '3月', '4月', '5月', '6月']
values = [100, 300, 500, 400, 600, 800]
ax.plot(months, values, marker='o', linewidth=2)
ax.set_ylabel(indicator_name)
ax.set_title(title, fontsize=14, fontweight='bold')
plt.tight_layout()
return fig
# 页面配置
st.set_page_config(
page_title="数据指标建模助手 v3.0",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
def init_session_state():
"""初始化所有 session state 变量"""
if "requirement_input" not in st.session_state:
st.session_state.requirement_input = ""
if "uploaded_file_content" not in st.session_state:
st.session_state.uploaded_file_content = None
if "uploaded_file_name" not in st.session_state:
st.session_state.uploaded_file_name = None
if "selected_business_type" not in st.session_state:
st.session_state.selected_business_type = "电商" # 默认选第一个
if "generated_indicators" not in st.session_state:
st.session_state.generated_indicators = []
if "selected_indicators" not in st.session_state:
st.session_state.selected_indicators = []
if "generated_schemes" not in st.session_state:
st.session_state.generated_schemes = []
if "bi_design" not in st.session_state:
st.session_state.bi_design = None
if "current_step" not in st.session_state:
st.session_state.current_step = 1
if "checkboxes" not in st.session_state:
st.session_state.checkboxes = {}
# API 配置(默认使用用户提供的)
if "api_key" not in st.session_state:
st.session_state.api_key = "sk-c168056574f9479780ea52cd1853b219"
if "base_url" not in st.session_state:
st.session_state.base_url = "https://api.deepseek.com"
if "api_configured" not in st.session_state:
st.session_state.api_configured = True # 默认已配置
def apply_api_config():
"""
将 session_state 中的 API 配置应用到 config.settings
必须在创建 Agent 之前调用
"""
import os
import config.settings as settings
# 更新 environment variable
if st.session_state.api_key:
os.environ['DEEPSEEK_API_KEY'] = st.session_state.api_key
settings.DEEPSEEK_API_KEY = st.session_state.api_key
if st.session_state.base_url:
os.environ['DEEPSEEK_BASE_URL'] = st.session_state.base_url
if hasattr(settings, 'DEEPSEEK_BASE_URL'):
settings.DEEPSEEK_BASE_URL = st.session_state.base_url
logger.info(f"✅ API 配置已应用: base_url={st.session_state.base_url}")
def test_api_connection(api_key: str, base_url: str) -> tuple:
"""
测试 API 连接
返回: (success: bool, message: str)
"""
try:
import requests
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
# 测试一个简单的 API 调用(使用正确的 DeepSeek API 格式)
test_url = f"{base_url.rstrip('/')}/v1/chat/completions"
test_data = {
"model": "deepseek-chat",
"messages": [{"role": "user", "content": "Hi"}],
"max_tokens": 10
}
response = requests.post(test_url, headers=headers, json=test_data, timeout=10)
if response.status_code == 200:
return True, "✅ API 连接成功!"
else:
return False, f"❌ API 连接失败: {response.status_code} - {response.text[:200]}"
except Exception as e:
return False, f"❌ 连接测试失败: {str(e)}"
def save_uploaded_file(uploaded_file) -> Optional[str]:
"""保存上传的文件到临时目录,返回文件路径"""
if uploaded_file is None:
return None
try:
temp_dir = PROJECT_ROOT / "temp"
temp_dir.mkdir(exist_ok=True)
file_path = temp_dir / uploaded_file.name
with open(file_path, "wb") as f:
f.write(uploaded_file.getbuffer())
return str(file_path)
except Exception as e:
logger.error(f"保存上传文件失败: {e}")
return None
def display_indicator_card(indicator: Dict[str, Any], index: int):
"""显示单个指标的卡片(修复 Bug 2:复选框状态管理)"""
# 兼容 Indicator 对象和字典
if hasattr(indicator, 'indicator_name'):
# Indicator 对象
indicator_name = indicator.indicator_name
business_meaning = getattr(indicator, 'business_meaning', '')
business_formula = getattr(indicator, 'business_formula', '')
calculation_logic = getattr(indicator, 'calculation_logic', '')
dimension = getattr(indicator, 'dimension', [])
else:
# 字典格式
indicator_name = indicator.get("indicator_name", f"指标 {index+1}")
business_meaning = indicator.get("business_meaning", "")
business_formula = indicator.get("business_formula", "")
calculation_logic = indicator.get("calculation_logic", "")
dimension = indicator.get("dimension", [])
checkbox_key = f"checkbox_{index}"
with st.container():
col1, col2 = st.columns([1, 20])
with col1:
# Bug 2 修复:使用 st.session_state 绑定复选框状态
if checkbox_key not in st.session_state.checkboxes:
st.session_state.checkboxes[checkbox_key] = True
st.session_state.checkboxes[checkbox_key] = st.checkbox(
"",
value=st.session_state.checkboxes[checkbox_key],
key=f"cb_{index}"
)
with col2:
st.markdown(f"### {indicator_name}")
st.caption(business_meaning)
if st.session_state.checkboxes.get(checkbox_key, True):
if business_formula:
st.markdown(f"**业务公式**: {business_formula}")
if dimension:
if isinstance(dimension, list):
st.markdown(f"**分析维度**: {', '.join(dimension)}")
else:
st.markdown(f"**分析维度**: {dimension}")
st.divider()
def generate_download_files(schemes: List[Dict], bi_design: Dict, indicators: List[Dict]) -> tuple:
"""
生成下载所需的文件内容(Bug 6 修复:简化为 2 个 Markdown 文件)
Returns:
tuple: (方案预览.md 内容, BI设计方案.md 内容)
"""
# 文件 1: 方案预览.md - 包含所有指标的 SQL + Markdown 文档
preview_content = "# 数据指标建模方案预览\n\n"
preview_content += f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
preview_content += "---\n\n"
preview_content += "## 📋 指标列表\n\n"
for i, indicator in enumerate(indicators, 1):
# 兼容 Indicator 对象和字典格式
if hasattr(indicator, 'indicator_name'):
# Indicator 对象
indicator_name = indicator.indicator_name
business_meaning = getattr(indicator, 'business_meaning', '无')
business_formula = getattr(indicator, 'business_formula', '无')
dimension = getattr(indicator, 'dimension', []) or getattr(indicator, 'dimensions', [])
data_source = getattr(indicator, 'data_source', '')
update_frequency = getattr(indicator, 'update_frequency', '')
usage_scenario = getattr(indicator, 'usage_scenario', '')
else:
# 字典格式
indicator_name = indicator.get('indicator_name', f'指标 {i}')
business_meaning = indicator.get('business_meaning', '无')
business_formula = indicator.get('business_formula', '无')
dimension = indicator.get('dimension', [])
data_source = indicator.get('data_source', '')
update_frequency = indicator.get('update_frequency', '')
usage_scenario = indicator.get('usage_scenario', '')
preview_content += f"### {i}. {indicator_name}\n\n"
preview_content += f"**业务含义**: {business_meaning}\n\n"
preview_content += f"**业务公式**: {business_formula}\n\n"
if isinstance(dimension, list):
preview_content += f"**分析维度**: {', '.join(dimension) if dimension else '无'}\n\n"
else:
preview_content += f"**分析维度**: {dimension}\n\n"
# 添加新增字段
if data_source:
preview_content += f"**数据来源**: {data_source}\n\n"
if update_frequency:
preview_content += f"**更新频率**: {update_frequency}\n\n"
if usage_scenario:
preview_content += f"**使用场景**: {usage_scenario}\n\n"
# 显示对应的 SQL 查询语句
matching_scheme = next((s for s in schemes if s.get('indicator_name') == indicator_name), None)
if matching_scheme and matching_scheme.get('sql'):
preview_content += "**SQL 查询语句**:\n\n"
preview_content += f"```sql\n{matching_scheme.get('sql', '')}\n```\n\n"
preview_content += "---\n\n"
# 文件 2: BI设计方案.md - 包含所有图表信息和对应的 SQL
bi_content = "# BI 设计方案\n\n"
bi_content += f"**生成时间**: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n"
bi_content += "---\n\n"
if bi_design and isinstance(bi_design, dict) and "charts" in bi_design:
bi_content += "## 📊 图表设计\n\n"
for i, chart in enumerate(bi_design["charts"], 1):
bi_content += f"### {i}. {chart.get('chart_name', '未命名图表')}\n\n"
bi_content += f"**图表类型**: {chart.get('chart_type', '未指定')}\n\n"
bi_content += f"**描述**: {chart.get('description', '无')}\n\n"
# 显示该图表使用的指标
chart_indicators = chart.get('indicators', [])
if chart_indicators:
bi_content += f"**使用指标**: {', '.join(chart_indicators)}\n\n"
# Bug 5: 显示该图表对应的 SQL 查询语句
bi_content += "**SQL 查询语句**:\n\n"
matching_schemes = [s for s in schemes if s.get('indicator_name') in chart_indicators]
if matching_schemes:
for scheme in matching_schemes:
bi_content += f"#### {scheme.get('indicator_name', '')}\n\n"
bi_content += f"```sql\n{scheme.get('sql', '')}\n```\n\n"
bi_content += "---\n\n"
else:
bi_content += "⚠️ 未生成 BI 设计方案\n"
return preview_content, bi_content
def step1_input_requirement():
"""Step 1: 输入需求"""
st.header("📝 Step 1: 输入需求")
st.markdown("请描述您的业务需求,或上传参考文档,我们将为您生成完整的数据指标方案。")
# 业务类型选择
st.subheader("🏢 选择业务类型")
business_type = st.selectbox(
"选择业务类型",
options=BUSINESS_TYPES, # 直接使用列表,不需要 .keys()
index=0,
help="选择您的业务领域,以获得更精准的指标建议"
)
st.session_state.selected_business_type = business_type
# 文本输入区域
st.subheader("✍️ 文本输入")
requirement_text = st.text_area(
"请描述您的业务需求",
value=st.session_state.requirement_input,
height=200,
placeholder="例如:我希望分析电商平台的用户购买行为,需要了解用户的消费习惯、购买频率、以及商品的热度排名...",
help="详细描述您的业务场景和分析目标,AI 将为您生成相应的数据指标"
)
st.session_state.requirement_input = requirement_text
# 文件上传
st.subheader("📎 上传参考文档(可选)")
uploaded_file = st.file_uploader(
"支持 .txt, .md, .pdf, .docx, .xlsx 格式",
type=['txt', 'md', 'pdf', 'docx', 'xlsx'],
help="上传参考文档可以帮助 AI 更好地理解您的需求"
)
# Bug 1 修复:正确处理 file_metadata
if uploaded_file is not None:
file_path = save_uploaded_file(uploaded_file)
if file_path:
try:
result = parse_uploaded_file(file_path)
# 正确处理返回的字典格式
if isinstance(result, dict) and result.get("status") == "success":
file_metadata = result.get("data", {})
# 将文件元数据转换为可读的字符串格式
content = format_file_metadata(file_metadata, uploaded_file.name)
st.session_state.uploaded_file_content = content
else:
# 处理错误情况
error_msg = result.get("error", "未知错误") if isinstance(result, dict) else "文件解析失败"
st.error(f"❌ 文件解析失败: {error_msg}")
logger.error(f"文件解析失败: {error_msg}")
st.session_state.uploaded_file_content = ""
st.session_state.uploaded_file_name = uploaded_file.name
st.success(f"✅ 文件上传成功:{uploaded_file.name}")
with st.expander("查看文件内容"):
display_content = st.session_state.uploaded_file_content
st.text(display_content[:500] + "..." if len(display_content) > 500 else display_content)
except Exception as e:
st.error(f"❌ 文件解析失败: {e}")
logger.error(f"文件解析失败: {e}")
st.session_state.uploaded_file_content = ""
# 生成指标按钮
st.divider()
col1, col2, col3 = st.columns([1, 2, 1])
with col2:
if st.button("🚀 生成指标方案", use_container_width=True, type="primary"):
if not requirement_text and not st.session_state.uploaded_file_content:
st.warning("⚠️ 请至少输入文本需求或上传参考文档")
else:
with st.spinner("🤖 AI 正在分析需求并生成指标..."):
try:
# 应用 API 配置(必须在创建 Agent 前调用)
apply_api_config()
# 步骤1:调用 RequirementAgent 获取业务领域和分析目的
req_agent = RequirementAgent(api_key=st.session_state.api_key)
combined_input = requirement_text
if st.session_state.uploaded_file_content:
# 安全保护:确保是字符串类型
file_content = st.session_state.uploaded_file_content
if isinstance(file_content, dict):
file_content = format_file_metadata(file_content, st.session_state.uploaded_file_name)
combined_input += "\n\n【参考文档内容】\n" + str(file_content)
# 调用 RequirementAgent
req_result = req_agent.run(
input_data={
"user_input": combined_input,
"business_type": business_type
}
)
if req_result and req_result.get("status") == "success":
# 提取 business_domain 和 analysis_purpose
req_data = req_result.get("data", {})
business_domain = req_data.get("business_domain", business_type)
analysis_purpose = req_data.get("analysis_purpose", "")
# 步骤2:调用 RecommendationAgent 生成指标
from agents.recommendation_agent import RecommendationAgent
rec_agent = RecommendationAgent(api_key=st.session_state.api_key)
rec_result = rec_agent.run({
"business_domain": business_domain,
"analysis_purpose": analysis_purpose,
"top_k": 8
})
if rec_result and rec_result.get("status") == "success":
rec_data = rec_result.get("data", {})
indicators = rec_data.get("indicators", [])
if indicators and len(indicators) > 0:
st.session_state.generated_indicators = indicators
st.session_state.selected_indicators = [True] * len(indicators)
# 初始化复选框状态
st.session_state.checkboxes = {}
for i in range(len(indicators)):
st.session_state.checkboxes[f"checkbox_{i}"] = True
st.session_state.current_step = 2
st.success(f"✅ 成功生成 {len(indicators)} 个指标!请进入下一步选择需要的指标。")
st.rerun()
else:
st.error("❌ 生成指标失败:未生成任何指标")
logger.error("RecommendationAgent returned empty indicators")
else:
error_msg = rec_result.get("error", "未知错误") if rec_result else "返回为空"
st.error(f"❌ 生成指标失败: {error_msg}")
logger.error(f"RecommendationAgent 失败: {error_msg}")
else:
error_msg = req_result.get("error", "未知错误") if req_result else "返回为空"
st.error(f"❌ 需求分析失败: {error_msg}")
logger.error(f"RequirementAgent 失败: {error_msg}")
except Exception as e:
st.error(f"❌ 生成指标时发生错误: {e}")
logger.error(f"生成指标异常: {e}")
def step2_select_indicators():
"""Step 2: 选择指标"""
st.header("📊 Step 2: 选择指标")
st.markdown(f"AI 已生成 **{len(st.session_state.generated_indicators)}** 个指标,请选择您需要的部分:")
# Bug 3 修复:正确的条件检查
if not st.session_state.generated_indicators or len(st.session_state.generated_indicators) == 0:
st.warning("⚠️ 暂无生成的指标,请先完成 Step 1")
if st.button("← 返回 Step 1"):
st.session_state.current_step = 1
st.rerun()
return
st.divider()
# 显示指标卡片
selected_count = 0
for i, indicator in enumerate(st.session_state.generated_indicators):
display_indicator_card(indicator, i)
if st.session_state.checkboxes.get(f"checkbox_{i}", True):
selected_count += 1
# 显示已选择数量
st.info(f"已选择 **{selected_count}** 个指标")
# 操作按钮
st.divider()
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if st.button("← 上一步", key="back_to_step1"):
st.session_state.current_step = 1
st.rerun()
with col3:
if st.button("🚀 生成完整方案 →", use_container_width=True, type="primary", key="generate_scheme"):
selected = [i for i in range(len(st.session_state.generated_indicators))
if st.session_state.checkboxes.get(f"checkbox_{i}", True)]
if not selected:
st.warning("⚠️ 请至少选择一个指标")
else:
# 从 selected 索引获取指标对象
selected_inds = [st.session_state.generated_indicators[i] for i in selected]
st.session_state.selected_indicators = selected_inds
with st.spinner("🤖 AI 正在生成完整的指标方案和 BI 设计..."):
try:
# 应用 API 配置(必须在创建 Agent 前调用)
apply_api_config()
# 创建 IndicatorSet
from models.indicator_set import IndicatorSet
# 获取业务领域(从 session_state 或默认值)
business_domain = st.session_state.get("selected_business_type", "通用")
requirement_text = st.session_state.get("requirement_input", "")
indicator_set = IndicatorSet(
set_id="set_001",
set_name="生成的指标集",
business_domain=business_domain,
analysis_purpose=requirement_text[:100] if requirement_text else None,
indicators=selected_inds
)
# 生成 SQL 方案
model_agent = ModelingAgent(api_key=st.session_state.api_key)
modeling_result = model_agent.run({
"indicator_set": indicator_set,
"selected_indicators": [ind.indicator_id for ind in selected_inds]
})
if modeling_result["status"] == "success":
schemes = modeling_result["data"]["schemes"]
st.session_state.generated_schemes = schemes
# 生成 BI 设计
bi_agent = BIDesignAgent(api_key=st.session_state.api_key)
bi_result = bi_agent.run({
"indicator_set": indicator_set,
"schemes": schemes
})
if bi_result["status"] == "success":
bi_design = bi_result["data"]["bi_design"]
st.session_state.bi_design = bi_design
st.session_state.current_step = 3
st.success(f"✅ 成功生成方案!包含 {len(schemes)} 个指标方案和 BI 设计")
st.rerun()
else:
st.error(f"❌ BI设计生成失败: {bi_result.get('error', '未知错误')}")
else:
st.error(f"❌ 建模生成失败: {modeling_result.get('error', '未知错误')}")
except Exception as e:
error_msg = str(e)
st.error(f"❌ 生成失败: {error_msg}")
logger.error(f"生成方案失败: {error_msg}", exc_info=True)
def step3_view_scheme():
"""Step 3: 查看方案(包含 Bug 5 修复:SQL 显示)"""
st.header("📈 Step 3: 查看方案")
# Bug 3 修复:正确的条件检查
if not st.session_state.selected_indicators or len(st.session_state.selected_indicators) == 0:
st.warning("⚠️ 暂无选中的指标,请先完成 Step 2")
if st.button("← 返回 Step 2"):
st.session_state.current_step = 2
st.rerun()
return
# 调试模式:显示生成的方案原始数据
debug_mode = st.checkbox("🐛 调试模式(显示原始数据)", value=False, key="debug_mode")
if debug_mode:
st.subheader("🔍 调试信息")
st.write("**generated_schemes 内容**:")
if st.session_state.generated_schemes:
for i, scheme in enumerate(st.session_state.generated_schemes, 1):
with st.expander(f"方案 {i}: {scheme.get('indicator_name', '未知')}"):
st.json(scheme)
else:
st.warning("⚠️ generated_schemes 为空")
# 创建标签页
tab1, tab2 = st.tabs(["📋 方案预览", "🎨 BI 设计"])
with tab1:
st.subheader("📋 方案预览")
st.markdown("以下是为您生成的完整数据指标方案,包含 SQL 查询语句:")
for i, indicator in enumerate(st.session_state.selected_indicators, 1):
# 兼容 Indicator 对象和字典格式
if hasattr(indicator, 'indicator_name'):
# Indicator 对象
indicator_name = indicator.indicator_name
business_meaning = getattr(indicator, 'business_meaning', '')
business_formula = getattr(indicator, 'business_formula', '')
dimension = getattr(indicator, 'dimension', []) or getattr(indicator, 'dimensions', [])
data_source = getattr(indicator, 'data_source', '')
update_frequency = getattr(indicator, 'update_frequency', '')
usage_scenario = getattr(indicator, 'usage_scenario', '')
else:
# 字典格式
indicator_name = indicator.get('indicator_name', f'指标 {i}')
business_meaning = indicator.get('business_meaning', '无')
business_formula = indicator.get('business_formula', '无')
dimension = indicator.get('dimension', [])
data_source = indicator.get('data_source', '')
update_frequency = indicator.get('update_frequency', '')
usage_scenario = indicator.get('usage_scenario', '')
with st.expander(f"{i}. {indicator_name}", expanded=True):
st.markdown(f"**业务含义**: {business_meaning}")
# 显示取数逻辑(即 SQL 语句)
matching_scheme = next((s for s in st.session_state.generated_schemes
if s.get('indicator_name') == indicator_name), None)
if matching_scheme and matching_scheme.get('sql'):
st.markdown(f"**取数逻辑**:")
st.code(matching_scheme.get('sql', ''), language='sql')
else:
st.markdown(f"**取数逻辑**: 暂无")
if isinstance(dimension, list):
st.markdown(f"**分析维度**: {', '.join(dimension) if dimension else '无'}")
else:
st.markdown(f"**分析维度**: {dimension}")
# 显示新增字段
if data_source:
st.markdown(f"**数据来源**: {data_source}")
if update_frequency:
st.markdown(f"**更新频率**: {update_frequency}")
if usage_scenario:
st.markdown(f"**使用场景**: {usage_scenario}")
with tab2:
st.subheader("🎨 BI 设计方案")
st.markdown("以下是为您推荐的 BI 可视化设计方案,包含图表和对应的 SQL 查询语句:")
if st.session_state.bi_design and isinstance(st.session_state.bi_design, dict) and "charts" in st.session_state.bi_design:
for i, chart in enumerate(st.session_state.bi_design["charts"], 1):
chart_name = chart.get('chart_name', chart.get('title', f'图表 {i}'))
chart_type = chart.get('chart_type', '未指定')
description = chart.get('description', '')
with st.expander(f"📊 {i}. {chart_name}", expanded=True):
st.markdown(f"**图表类型**: {chart_type}")
st.markdown(f"**图表名称**: {chart_name}")
if description:
st.markdown(f"**描述**: {description}")
# 获取该图表使用的指标(在渲染图表前定义)
chart_indicators = chart.get('indicators', [])
# 统一使用 matplotlib 渲染图表
try:
if MATPLOTLIB_AVAILABLE:
fig = render_chart(chart_type, chart_name, chart_indicators[0] if chart_indicators else '指标')
if fig:
st.pyplot(fig)
st.success(f"✅ 图表类型: {chart_type}")
else:
st.warning("⚠️ matplotlib 未安装,无法渲染图表。请运行: pip install matplotlib")
except Exception as e:
st.warning(f"⚠️ 图表渲染失败: {e}")
if chart_indicators:
st.markdown(f"**使用指标**: {', '.join(chart_indicators)}")
# 显示该图表对应的 SQL 查询语句
st.markdown("**SQL 查询语句**:")
matching_schemes = [s for s in st.session_state.generated_schemes
if s.get('indicator_name') in chart_indicators]
if matching_schemes:
for scheme in matching_schemes:
st.code(scheme.get('sql', ''), language='sql')
else:
st.warning("⚠️ 暂无 BI 设计方案")
# Bug 6: 简化下载功能(只生成 2 个 Markdown 文件)
st.divider()
st.subheader("📥 下载方案")
st.markdown("点击以下按钮下载生成的方案文档(Markdown 格式):")
preview_content, bi_content = generate_download_files(
st.session_state.generated_schemes,
st.session_state.bi_design,
st.session_state.selected_indicators
)
col1, col2 = st.columns(2)
with col1:
st.download_button(
label="📥 下载方案预览 (Markdown)",
data=preview_content,
file_name="方案预览.md",
mime="text/markdown",
use_container_width=True,
key="download_preview"
)
with col2:
st.download_button(
label="📥 下载 BI 设计方案 (Markdown)",
data=bi_content,
file_name="BI设计方案.md",
mime="text/markdown",
use_container_width=True,
key="download_bi"
)
# 返回按钮
st.divider()
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if st.button("← 重新选择指标", key="back_to_step2"):
st.session_state.current_step = 2
st.rerun()
with col3:
if st.button("🔄 重新开始", use_container_width=True, key="restart"):
init_session_state()
st.session_state.current_step = 1
st.rerun()
def main():
"""主函数"""
init_session_state()
# 注入自定义 CSS,隐藏密码输入框的眼睛按钮(显示/隐藏密码)
st.markdown("""
<style>
/* 隐藏 Chrome/Edge 密码输入框的显示/隐藏按钮 */
input[type="password"]::-ms-reveal,
input[type="password"]::-ms-clear {
display: none !important;
}
input[type="password"]::-webkit-textfield-decoration-container {
display: none !important;
}
input[type="password"]::-webkit-inner-spin-button,
input[type="password"]::-webkit-outer-spin-button {
display: none !important;
}
/* 针对 Streamlit 的密码输入框按钮 */
.stTextInput div[data-baseweb="input"] button {
display: none !important;
}
.stTextInput div[data-baseweb="input"] svg {
display: none !important;
}
</style>
""", unsafe_allow_html=True)
# 侧边栏 - 左侧
with st.sidebar:
st.title("📊 数据指标建模助手")
st.markdown("**版本**: v3.0")
st.divider()
# API 配置(用户需求:完全隐藏 API Key)
st.subheader("🔑 API 配置")
# 优先从 HF Spaces Secrets 读取 API Key
if "DEEPSEEK_API_KEY" in st.secrets:
# HF Spaces 已配置 Secret,直接使用
st.session_state.api_key = st.secrets["DEEPSEEK_API_KEY"]
st.session_state.api_configured = True
st.success("✅ API 已通过 Secrets 配置(HF Spaces)")
with st.expander("高级选项"):
if st.button("🔧 修改配置", key="edit_api", use_container_width=True):
st.session_state.api_configured = False
st.rerun()
else:
# 如果已配置,只显示状态,不显示 Key
if st.session_state.api_configured:
st.success("✅ API 已配置")
with st.expander("高级选项"):
if st.button("🔧 修改配置", key="edit_api", use_container_width=True):
st.session_state.api_configured = False
st.rerun()
else:
# 输入模式(只在修改时显示)
# 不在输入框中显示已保存的 API Key,确保安全性
api_key = st.text_input(
"DeepSeek API Key",
value="", # 清空显示,用户需重新输入
type="password",
help="请输入新的 DeepSeek API Key(已保存的 Key 不会显示在这里)",
placeholder="输入新的 API Key..."
)
base_url = st.text_input(
"Base URL",
value=st.session_state.base_url,
help="API 的基础 URL 地址"
)
col1, col2 = st.columns(2)
with col1:
if st.button("💾 保存配置", key="save_api", use_container_width=True):
# 只有输入了新的 API Key 才更新(避免清空已保存的 Key)
if api_key:
st.session_state.api_key = api_key
st.session_state.base_url = base_url
st.session_state.api_configured = True
st.success("✅ 配置已保存")
st.rerun()
with col2:
if st.button("🔍 测试连接", key="test_api", use_container_width=True):
with st.spinner("正在测试连接..."):
success, msg = test_api_connection(api_key, base_url)
if success:
st.success(msg)
else:
st.error(msg)
st.divider()
# 进度显示
st.subheader("📍 当前进度")
steps = [
("Step 1: 输入需求", 1),
("Step 2: 选择指标", 2),
("Step 3: 查看方案", 3)
]
for step_name, step_num in steps:
if step_num == st.session_state.current_step:
st.markdown(f"**→ {step_name}**")
elif step_num < st.session_state.current_step:
st.markdown(f"~~{step_name}~~ ✅")
else:
st.markdown(f"{step_name}")
st.divider()
st.caption("© 2026 数据指标建模助手")
st.caption("Powered by DeepSeek & FAISS")
# 主内容区域 - 右侧
if st.session_state.current_step == 1:
step1_input_requirement()
elif st.session_state.current_step == 2:
step2_select_indicators()
elif st.session_state.current_step == 3:
step3_view_scheme()
if __name__ == "__main__":
main()
|