yj
2025-07-23 1225b6cbf0a028b765a0ab6d784bcb80459a67bb
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
"""
启动脚本 - 处理配置文件和目录初始化
"""
 
import os
import sys
import json
import shutil
from pathlib import Path
 
 
def get_exe_dir():
    """获取exe文件所在目录"""
    if getattr(sys, 'frozen', False):
        # 如果是打包后的exe文件
        return os.path.dirname(sys.executable)
    else:
        # 如果是开发环境
        return os.path.dirname(os.path.abspath(__file__))
 
 
def ensure_directories():
    """确保必要的目录存在"""
    exe_dir = get_exe_dir()
    
    # 创建日志目录
    logs_dir = os.path.join(exe_dir, 'logs')
    if not os.path.exists(logs_dir):
        os.makedirs(logs_dir)
        print(f"创建日志目录: {logs_dir}")
    
    return exe_dir
 
 
def ensure_config_file():
    """确保配置文件存在"""
    exe_dir = get_exe_dir()
    config_file = os.path.join(exe_dir, 'config.json')
    
    if not os.path.exists(config_file):
        # 如果config.json不存在,尝试复制生产配置模板
        production_config = os.path.join(exe_dir, 'config.production.json')
        example_config = os.path.join(exe_dir, 'config.example.json')
        
        if os.path.exists(production_config):
            shutil.copy2(production_config, config_file)
            print(f"复制生产配置文件: {production_config} -> {config_file}")
        elif os.path.exists(example_config):
            shutil.copy2(example_config, config_file)
            print(f"复制示例配置文件: {example_config} -> {config_file}")
        else:
            # 创建默认配置文件
            default_config = {
                "database": {
                    "url": "mysql+pymysql://root:password@localhost:3306/ecloud_dify"
                },
                "redis": {
                    "url": "redis://localhost:6379/0"
                },
                "ecloud": {
                    "base_url": "http://125.122.152.142:9899",
                    "authorization": "your_ecloud_authorization_token",
                    "w_id": "your_ecloud_w_id"
                },
                "dify": {
                    "base_url": "https://api.dify.ai/v1",
                    "api_key": "your_dify_api_key"
                },
                "server": {
                    "host": "0.0.0.0",
                    "port": 7979,
                    "debug": False
                },
                "logging": {
                    "level": "INFO",
                    "file": "logs/app.log"
                },
                "message_processing": {
                    "max_retry_count": 3,
                    "retry_delay": 5,
                    "queue_timeout": 300
                },
                "customer_service": {
                    "names": ["客服1", "客服2"]
                }
            }
            
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, indent=2, ensure_ascii=False)
            print(f"创建默认配置文件: {config_file}")
    
    return config_file
 
 
def setup_environment():
    """设置运行环境"""
    exe_dir = ensure_directories()
    config_file = ensure_config_file()
    
    # 设置工作目录为exe所在目录
    os.chdir(exe_dir)
    print(f"设置工作目录: {exe_dir}")
    
    return exe_dir, config_file
 
 
if __name__ == "__main__":
    setup_environment()
    
    # 导入并启动主应用
    try:
        from main import app
        import uvicorn
        from config import settings
        from loguru import logger
        
        # 配置日志
        logger.add(
            settings.log_file,
            rotation="1 day",
            retention="7 days",
            level=settings.log_level,
            format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{function}:{line} - {message}",
        )
        
        logger.info("启动E云管家-DifyAI对接服务")
        
        # 启动服务
        uvicorn.run(
            app,
            host=settings.server_host,
            port=settings.server_port,
            log_level=settings.log_level.lower(),
        )
        
    except Exception as e:
        print(f"启动失败: {e}")
        input("按任意键退出...")
        sys.exit(1)