config.py
5.08 KB
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
"""
Report Engine配置管理模块
处理环境变量和配置参数
"""
import os
from dataclasses import dataclass
from typing import Optional
@dataclass
class Config:
"""Report Engine配置类"""
# API密钥
gemini_api_key: Optional[str] = None
# 模型配置
default_llm_provider: str = "gemini"
gemini_model: str = "gemini-2.5-pro"
# 报告配置
max_content_length: int = 50000
output_dir: str = "final_reports"
template_dir: str = "ReportEngine/report_template"
# 日志配置
log_file: str = "logs/report.log"
# HTML导出配置
enable_pdf_export: bool = True
chart_style: str = "modern" # modern, classic, minimal
def validate(self) -> bool:
"""验证配置"""
if not self.gemini_api_key:
print("错误: Gemini API Key未设置")
return False
return True
@classmethod
def from_file(cls, config_file: str) -> "Config":
"""从配置文件创建配置"""
if config_file.endswith('.py'):
# Python配置文件
import importlib.util
# 动态导入配置文件
spec = importlib.util.spec_from_file_location("config", config_file)
config_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(config_module)
return cls(
gemini_api_key=getattr(config_module, "GEMINI_API_KEY", None),
default_llm_provider=getattr(config_module, "DEFAULT_LLM_PROVIDER", "gemini"),
gemini_model=getattr(config_module, "GEMINI_MODEL", "gemini-2.5-pro"),
max_content_length=getattr(config_module, "MAX_CONTENT_LENGTH", 50000),
output_dir=getattr(config_module, "REPORT_OUTPUT_DIR", "final_reports"),
template_dir=getattr(config_module, "TEMPLATE_DIR", "ReportEngine/report_template"),
log_file=getattr(config_module, "REPORT_LOG_FILE", "logs/report.log"),
enable_pdf_export=getattr(config_module, "ENABLE_PDF_EXPORT", True),
chart_style=getattr(config_module, "CHART_STYLE", "modern")
)
else:
# .env格式配置文件
config_dict = {}
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
config_dict[key.strip()] = value.strip()
return cls(
gemini_api_key=config_dict.get("GEMINI_API_KEY"),
default_llm_provider=config_dict.get("DEFAULT_LLM_PROVIDER", "gemini"),
gemini_model=config_dict.get("GEMINI_MODEL", "gemini-2.5-pro"),
max_content_length=int(config_dict.get("MAX_CONTENT_LENGTH", "50000")),
output_dir=config_dict.get("REPORT_OUTPUT_DIR", "final_reports"),
template_dir=config_dict.get("TEMPLATE_DIR", "ReportEngine/report_template"),
log_file=config_dict.get("REPORT_LOG_FILE", "logs/report.log"),
enable_pdf_export=config_dict.get("ENABLE_PDF_EXPORT", "true").lower() == "true",
chart_style=config_dict.get("CHART_STYLE", "modern")
)
def load_config(config_file: Optional[str] = None) -> Config:
"""
加载配置
Args:
config_file: 配置文件路径,如果不指定则使用默认路径
Returns:
配置对象
"""
# 确定配置文件路径
if config_file:
if not os.path.exists(config_file):
raise FileNotFoundError(f"配置文件不存在: {config_file}")
file_to_load = config_file
else:
# 尝试加载常见的配置文件
for config_path in ["config.py", "config.env", ".env"]:
if os.path.exists(config_path):
file_to_load = config_path
break
else:
raise FileNotFoundError("未找到配置文件,请创建 config.py 文件")
# 创建配置对象
config = Config.from_file(file_to_load)
# 验证配置
if not config.validate():
raise ValueError("Report Engine配置验证失败,请检查配置文件中的API密钥")
return config
def print_config(config: Config):
"""打印配置信息(隐藏敏感信息)"""
print("\n=== Report Engine配置 ===")
print(f"LLM提供商: {config.default_llm_provider}")
print(f"Gemini模型: {config.gemini_model}")
print(f"最大内容长度: {config.max_content_length}")
print(f"输出目录: {config.output_dir}")
print(f"模板目录: {config.template_dir}")
print(f"日志文件: {config.log_file}")
print(f"PDF导出: {config.enable_pdf_export}")
print(f"图表样式: {config.chart_style}")
print(f"Gemini API Key: {'已设置' if config.gemini_api_key else '未设置'}")
print("========================\n")