Repository navigation
Expand file tree
/
Copy pathsetup.py
More file actions
executable file
·308 lines (266 loc) · 10.3 KB
/
Copy pathsetup.py
File metadata and controls
executable file
·308 lines (266 loc) · 10.3 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
#!/usr/bin/env python3
"""
Symposium Setup Script
Initializes the Symposium environment, checks dependencies, and validates configuration.
"""
import os
import sys
import logging
from pathlib import Path
from typing import List, Tuple
# Setup logging first
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
logging.FileHandler('setup.log', mode='a')
]
)
logger = logging.getLogger(__name__)
# Add current directory to Python path
current_dir = Path(__file__).parent
if str(current_dir) not in sys.path:
sys.path.insert(0, str(current_dir))
logger.info(f"Added {current_dir} to Python path")
# Ensure we're in the right directory
os.chdir(current_dir)
def check_python_version() -> bool:
"""Check if Python version is compatible."""
version = sys.version_info
if version.major == 3 and version.minor >= 12:
print(f"✅ Python version: {version.major}.{version.minor}.{version.micro}")
return True
else:
print(f"❌ Python version: {version.major}.{version.minor}.{version.micro} (requires 3.12+)")
return False
def check_virtual_environment() -> bool:
"""Check if running in virtual environment."""
in_venv = hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix)
if in_venv:
print("✅ Virtual environment active")
return True
else:
print("⚠️ Warning: Not in virtual environment (recommended)")
return True # Don't fail, just warn
def check_dependencies() -> bool:
"""Check if required dependencies are installed."""
logger.info("Checking dependencies")
# Map of package names to their import names
package_imports = {
'openai': 'openai',
'pandas': 'pandas',
'numpy': 'numpy',
'matplotlib': 'matplotlib',
'seaborn': 'seaborn',
'networkx': 'networkx',
'scikit-learn': 'sklearn',
'python-dotenv': 'dotenv',
'pytest': 'pytest',
'wordcloud': 'wordcloud',
'adjusttext': 'adjustText',
'backoff': 'backoff'
}
all_installed = True
for package_name, import_name in package_imports.items():
try:
__import__(import_name)
logger.info(f"Dependency check passed: {package_name}")
print(f"✅ {package_name}")
except ImportError as e:
logger.error(f"Dependency missing: {package_name} - {e}")
print(f"❌ {package_name} - Missing")
all_installed = False
return all_installed
def check_environment_file() -> bool:
"""Check and setup environment file."""
env_file = Path('.env')
env_example = Path('.env.example')
if not env_example.exists():
print("❌ .env.example not found")
return False
if not env_file.exists():
print("⚠️ .env file not found - copying from .env.example")
try:
import shutil
shutil.copy(env_example, env_file)
print("✅ Created .env file from template")
return True
except Exception as e:
print(f"❌ Failed to create .env file: {e}")
return False
print("✅ .env file exists")
return True
def check_api_keys() -> Tuple[bool, bool]:
"""Check API key configuration."""
from dotenv import load_dotenv
load_dotenv()
perplexity_key = os.getenv('PERPLEXITY_API_KEY')
openrouter_key = os.getenv('OPENROUTER_API_KEY')
perplexity_ok = bool(perplexity_key)
openrouter_ok = bool(openrouter_key)
if perplexity_ok:
print("✅ Perplexity API key configured")
else:
print("❌ Perplexity API key missing (set PERPLEXITY_API_KEY)")
if openrouter_ok:
print("✅ OpenRouter API key configured")
else:
print("❌ OpenRouter API key missing (set OPENROUTER_API_KEY)")
return perplexity_ok, openrouter_ok
def check_data_structure() -> bool:
"""Check data directory structure."""
required_dirs = [
'data/inputs/aif_2024',
'data/inputs/aif_2026',
'data/inputs/aif_2026/presenters',
'data/catechisms',
'data/domains',
'data/prompts',
'outputs'
]
all_dirs_ok = True
for dir_path in required_dirs:
if Path(dir_path).exists():
print(f"✅ {dir_path}")
else:
print(f"⚠️ {dir_path} - Directory missing")
all_dirs_ok = False
return all_dirs_ok
def check_package_installation() -> bool:
"""Check if symposium package is installed."""
try:
import symposium
print(f"✅ Symposium package installed (v{symposium.__version__})")
return True
except ImportError:
print("❌ Symposium package not installed")
print(" Run: uv pip install -e .")
return False
def test_api_connectivity() -> Tuple[bool, bool]:
"""Test API connectivity."""
logger.info("Testing API connectivity")
perplexity_ok = False
openrouter_ok = False
try:
# Import modules with error handling
logger.info("Importing symposium modules for API testing")
from symposium.core.config import Config
from symposium.core.api import APIClient
logger.info("API modules imported successfully")
config = Config()
logger.info("Configuration loaded")
# Test Perplexity
try:
logger.info("Testing Perplexity API")
client = APIClient.create('perplexity')
response = client.get_response(
"Respond with 'API test successful' if you receive this message.",
"You are a helpful assistant."
)
if 'API test successful' in response:
perplexity_ok = True
logger.info("Perplexity API test successful")
print("✅ Perplexity API connectivity verified")
else:
logger.warning("Perplexity API response unexpected")
print("❌ Perplexity API response unexpected")
except ImportError as e:
logger.error(f"Perplexity API import failed: {e}")
print(f"❌ Perplexity API test failed: Module import error")
except Exception as e:
logger.error(f"Perplexity API test failed: {e}")
print(f"❌ Perplexity API test failed: {e}")
# Test OpenRouter
try:
logger.info("Testing OpenRouter API")
client = APIClient.create('openrouter')
response = client.get_response(
"Respond with 'API test successful' if you receive this message.",
"You are a helpful assistant."
)
if 'API test successful' in response:
openrouter_ok = True
logger.info("OpenRouter API test successful")
print("✅ OpenRouter API connectivity verified")
else:
logger.warning("OpenRouter API response unexpected")
print("❌ OpenRouter API response unexpected")
except ImportError as e:
logger.error(f"OpenRouter API import failed: {e}")
print(f"❌ OpenRouter API test failed: Module import error")
except Exception as e:
logger.error(f"OpenRouter API test failed: {e}")
print(f"❌ OpenRouter API test failed: {e}")
except ImportError as e:
logger.error(f"Symposium modules not available: {e}")
print(f"❌ API connectivity test failed: Symposium package not installed")
print(" Run: uv pip install -e \".[dev]\"")
return perplexity_ok, openrouter_ok
def main():
"""Run complete setup validation."""
logger.info("Starting Symposium setup validation")
print("🚀 SYMPOSIUM SETUP VALIDATION")
print("=" * 50)
# Check if running as script or module
if __name__ != "__main__":
logger.info("Running as module")
print("Running as module...")
# Adjust paths if needed
if not Path('pyproject.toml').exists():
# Try to find project root
for parent in Path(__file__).parents:
if (parent / 'pyproject.toml').exists():
os.chdir(parent)
logger.info(f"Changed to project root: {parent}")
break
# Basic checks
checks = [
("Python Version", check_python_version),
("Virtual Environment", check_virtual_environment),
("Package Installation", check_package_installation),
("Environment File", check_environment_file),
("Data Structure", check_data_structure),
("Dependencies", check_dependencies),
]
all_passed = True
for check_name, check_func in checks:
print(f"\n📋 {check_name}:")
result = check_func()
if not result:
all_passed = False
# API configuration
print("\n🔑 API Configuration:")
perplexity_ok, openrouter_ok = check_api_keys()
if not (perplexity_ok or openrouter_ok):
all_passed = False
# API connectivity (optional)
print("\n🌐 API Connectivity Test:")
api_perplexity_ok, api_openrouter_ok = test_api_connectivity()
print("\n📊 SETUP SUMMARY:")
print("-" * 30)
if all_passed:
print("🎉 Setup complete! Ready to run Symposium.")
print()
print("Next steps:")
print("1. Run: python run.py")
print("2. Choose from the interactive menu options")
print("3. Start analyzing research data and generating content")
# Show available data
data_dir = Path('data/inputs/aif_2024')
if data_dir.exists():
researchers = [d.name for d in data_dir.iterdir() if d.is_dir()]
if researchers:
print(f"\n📁 Available researcher data: {len(researchers)} profiles")
print(f" Sample: {', '.join(researchers[:3])}")
return True
else:
print("❌ Setup incomplete. Please resolve the issues above.")
print("\nTroubleshooting:")
print("1. Install dependencies: uv pip install -e \".[dev]\"")
print("2. Set API keys in .env file")
print("3. Create required directories")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)