-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_environment.py
More file actions
347 lines (288 loc) · 11.7 KB
/
Copy pathsetup_environment.py
File metadata and controls
347 lines (288 loc) · 11.7 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
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
新电脑环境配置脚本
用于在新电脑上快速配置项目运行环境
"""
import os
import sys
import subprocess
import json
import platform
from pathlib import Path
class EnvironmentSetup:
def __init__(self):
self.system = platform.system()
self.python_version = sys.version
self.project_root = os.getcwd()
def check_python_version(self):
"""检查Python版本"""
print("🐍 检查Python版本...")
version_info = sys.version_info
if version_info.major == 3 and version_info.minor >= 8:
print(f"✅ Python版本: {sys.version}")
return True
else:
print(f"❌ Python版本过低: {sys.version}")
print("💡 建议安装Python 3.8或更高版本")
return False
def check_pip(self):
"""检查pip是否可用"""
print("📦 检查pip...")
try:
result = subprocess.run([sys.executable, "-m", "pip", "--version"],
capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ pip版本: {result.stdout.strip()}")
return True
else:
print("❌ pip不可用")
return False
except Exception as e:
print(f"❌ pip检查失败: {e}")
return False
def install_requirements(self):
"""安装项目依赖"""
print("📋 安装项目依赖...")
requirements_file = os.path.join(self.project_root, "requirements.txt")
if not os.path.exists(requirements_file):
print("❌ requirements.txt文件不存在")
return False
try:
# 使用国内镜像源加速安装
cmd = [
sys.executable, "-m", "pip", "install", "-r", requirements_file,
"-i", "https://pypi.tuna.tsinghua.edu.cn/simple/"
]
print("⏳ 正在安装依赖包,请耐心等待...")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
print("✅ 依赖包安装成功")
return True
else:
print(f"❌ 依赖包安装失败: {result.stderr}")
return False
except Exception as e:
print(f"❌ 安装过程中发生错误: {e}")
return False
def create_virtual_environment(self):
"""创建虚拟环境"""
print("🔧 创建虚拟环境...")
venv_name = "cursor_env"
venv_path = os.path.join(self.project_root, venv_name)
try:
# 创建虚拟环境
result = subprocess.run([sys.executable, "-m", "venv", venv_path],
capture_output=True, text=True)
if result.returncode == 0:
print(f"✅ 虚拟环境已创建: {venv_path}")
# 生成激活脚本
self.create_activation_scripts(venv_path)
return True
else:
print(f"❌ 虚拟环境创建失败: {result.stderr}")
return False
except Exception as e:
print(f"❌ 创建虚拟环境时发生错误: {e}")
return False
def create_activation_scripts(self, venv_path):
"""创建激活脚本"""
print("📝 创建激活脚本...")
# Windows激活脚本
if self.system == "Windows":
activate_script = os.path.join(self.project_root, "activate_env.bat")
with open(activate_script, 'w', encoding='utf-8') as f:
f.write(f"""@echo off
echo 激活虚拟环境...
call "{venv_path}\\Scripts\\activate.bat"
echo 虚拟环境已激活!
echo 现在可以运行项目了。
echo 使用 'deactivate' 命令退出虚拟环境。
cmd /k
""")
print(f"✅ Windows激活脚本已创建: {activate_script}")
# Linux/Mac激活脚本
activate_script = os.path.join(self.project_root, "activate_env.sh")
with open(activate_script, 'w', encoding='utf-8') as f:
f.write(f"""#!/bin/bash
echo "激活虚拟环境..."
source "{venv_path}/bin/activate"
echo "虚拟环境已激活!"
echo "现在可以运行项目了。"
echo "使用 'deactivate' 命令退出虚拟环境。"
bash
""")
# 设置执行权限
if self.system != "Windows":
os.chmod(activate_script, 0o755)
print(f"✅ Linux/Mac激活脚本已创建: {activate_script}")
def setup_config_files(self):
"""设置配置文件"""
print("⚙️ 设置配置文件...")
# 检查claude-config.json
config_file = os.path.join(self.project_root, "claude-config.json")
if os.path.exists(config_file):
print("✅ claude-config.json已存在")
# 检查API密钥
try:
with open(config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
if config.get("apiKey") == "your-api-key-here":
print("⚠️ 请更新API密钥配置")
print("💡 编辑claude-config.json文件,将'your-api-key-here'替换为实际的API密钥")
else:
print("✅ API密钥配置正常")
except Exception as e:
print(f"⚠️ 配置文件格式错误: {e}")
else:
print("❌ claude-config.json文件不存在")
return False
return True
def create_run_scripts(self):
"""创建运行脚本"""
print("🚀 创建运行脚本...")
# 主程序运行脚本
if self.system == "Windows":
run_script = os.path.join(self.project_root, "run_main.bat")
with open(run_script, 'w', encoding='utf-8') as f:
f.write("""@echo off
echo 启动Google Play评论分析系统...
python main.py
pause
""")
print(f"✅ Windows运行脚本已创建: {run_script}")
# Linux/Mac运行脚本
run_script = os.path.join(self.project_root, "run_main.sh")
with open(run_script, 'w', encoding='utf-8') as f:
f.write("""#!/bin/bash
echo "启动Google Play评论分析系统..."
python main.py
read -p "按回车键继续..."
""")
if self.system != "Windows":
os.chmod(run_script, 0o755)
print(f"✅ Linux/Mac运行脚本已创建: {run_script}")
def create_project_info(self):
"""创建项目信息文件"""
print("📄 创建项目信息文件...")
project_info = {
"project_name": "Cursor工作项目",
"setup_time": subprocess.run(["date"], capture_output=True, text=True).stdout.strip(),
"python_version": sys.version,
"system": self.system,
"project_root": self.project_root,
"main_scripts": [
"main.py - 主程序入口",
"scraper.py - 爬虫工具",
"review_analyzer.py - 评论分析",
"review_visualizer.py - 数据可视化",
"talkie_analysis.py - Talkie项目分析"
],
"data_directories": [
"Talkie项目/ - Talkie应用分析数据",
"SpotDL音乐下载/ - 音乐下载工具",
"Twitter爬虫/ - Twitter数据爬取",
"通用工具/ - 通用分析工具"
],
"output_directories": [
"analysis_output/ - 分析结果输出",
"visualization_output/ - 可视化输出",
"talkie_analysis_output/ - Talkie分析输出"
]
}
info_file = os.path.join(self.project_root, "project_info.json")
with open(info_file, 'w', encoding='utf-8') as f:
json.dump(project_info, f, ensure_ascii=False, indent=2)
print(f"✅ 项目信息文件已创建: {info_file}")
def test_environment(self):
"""测试环境配置"""
print("🧪 测试环境配置...")
try:
# 测试导入主要模块
test_imports = [
"pandas",
"numpy",
"matplotlib",
"seaborn",
"requests",
"jieba"
]
failed_imports = []
for module in test_imports:
try:
__import__(module)
print(f"✅ {module} - 导入成功")
except ImportError:
print(f"❌ {module} - 导入失败")
failed_imports.append(module)
if failed_imports:
print(f"⚠️ 以下模块导入失败: {', '.join(failed_imports)}")
return False
else:
print("✅ 所有核心模块导入成功")
return True
except Exception as e:
print(f"❌ 环境测试失败: {e}")
return False
def run_setup(self):
"""运行完整的环境配置"""
print("🚀 开始配置新电脑环境...")
print(f"📁 项目目录: {self.project_root}")
print(f"💻 操作系统: {self.system}")
print("=" * 50)
success_steps = 0
total_steps = 8
# 1. 检查Python版本
if self.check_python_version():
success_steps += 1
# 2. 检查pip
if self.check_pip():
success_steps += 1
# 3. 安装依赖
if self.install_requirements():
success_steps += 1
# 4. 创建虚拟环境
if self.create_virtual_environment():
success_steps += 1
# 5. 设置配置文件
if self.setup_config_files():
success_steps += 1
# 6. 创建运行脚本
self.create_run_scripts()
success_steps += 1
# 7. 创建项目信息
self.create_project_info()
success_steps += 1
# 8. 测试环境
if self.test_environment():
success_steps += 1
print("=" * 50)
print(f"📊 配置完成: {success_steps}/{total_steps} 步骤成功")
if success_steps == total_steps:
print("🎉 环境配置完全成功!")
print("\n💡 下一步操作:")
print("1. 双击运行 'activate_env.bat' (Windows) 或 'activate_env.sh' (Linux/Mac)")
print("2. 双击运行 'run_main.bat' (Windows) 或 'run_main.sh' (Linux/Mac)")
print("3. 或者直接运行: python main.py")
else:
print("⚠️ 环境配置部分成功,请检查失败的步骤")
return success_steps == total_steps
def main():
"""主函数"""
print("🔧 新电脑环境配置工具")
print("=" * 50)
# 检查是否在正确的目录
if not os.path.exists("requirements.txt"):
print("❌ 未找到requirements.txt文件")
print("💡 请确保在项目根目录下运行此脚本")
return
# 创建配置实例
setup = EnvironmentSetup()
# 运行配置
success = setup.run_setup()
if success:
print("\n✅ 环境配置成功完成!")
else:
print("\n❌ 环境配置失败,请检查错误信息")
if __name__ == "__main__":
main()