-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickstart_validate.py
More file actions
executable file
·433 lines (351 loc) · 14.7 KB
/
Copy pathquickstart_validate.py
File metadata and controls
executable file
·433 lines (351 loc) · 14.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
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
#!/usr/bin/env python3
"""
Quickstart Validation Script for Experts Panel
This script validates that the project can be started from scratch
and all dependencies are properly configured.
"""
import os
import sys
import subprocess
import json
import time
import sqlite3
from pathlib import Path
from typing import Tuple, List, Dict
# ANSI color codes for terminal output
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
BLUE = '\033[94m'
BOLD = '\033[1m'
RESET = '\033[0m'
class QuickstartValidator:
"""Validates project setup and configuration"""
def __init__(self):
self.errors = []
self.warnings = []
self.successes = []
self.project_root = Path(__file__).parent.absolute()
def print_header(self, text: str):
"""Print a formatted header"""
print(f"\n{BOLD}{BLUE}{'=' * 60}{RESET}")
print(f"{BOLD}{BLUE}{text}{RESET}")
print(f"{BOLD}{BLUE}{'=' * 60}{RESET}\n")
def print_success(self, message: str):
"""Print success message"""
print(f"{GREEN}✓{RESET} {message}")
self.successes.append(message)
def print_warning(self, message: str):
"""Print warning message"""
print(f"{YELLOW}⚠{RESET} {message}")
self.warnings.append(message)
def print_error(self, message: str):
"""Print error message"""
print(f"{RED}✗{RESET} {message}")
self.errors.append(message)
def check_python_version(self) -> bool:
"""Check Python version is 3.11+"""
self.print_header("Checking Python Version")
version = sys.version_info
if version.major >= 3 and version.minor >= 11:
self.print_success(f"Python {version.major}.{version.minor}.{version.micro} ✓")
return True
else:
self.print_error(f"Python 3.11+ required, found {version.major}.{version.minor}")
return False
def check_node_version(self) -> bool:
"""Check Node.js installation"""
self.print_header("Checking Node.js")
try:
result = subprocess.run(
["node", "--version"],
capture_output=True,
text=True
)
version = result.stdout.strip()
self.print_success(f"Node.js {version} ✓")
# Check npm as well
npm_result = subprocess.run(
["npm", "--version"],
capture_output=True,
text=True
)
npm_version = npm_result.stdout.strip()
self.print_success(f"npm {npm_version} ✓")
return True
except FileNotFoundError:
self.print_error("Node.js not found. Please install Node.js 18+")
return False
def check_python_dependencies(self) -> bool:
"""Check if Python dependencies are installed"""
self.print_header("Checking Python Dependencies")
requirements_file = self.project_root / "backend" / "requirements.txt"
if not requirements_file.exists():
self.print_error(f"requirements.txt not found at {requirements_file}")
return False
# Check for key packages
key_packages = [
"fastapi",
"sqlalchemy",
"openai",
"pydantic",
"uvicorn",
"sse-starlette"
]
missing_packages = []
for package in key_packages:
try:
__import__(package.replace("-", "_"))
self.print_success(f"Package {package} ✓")
except ImportError:
missing_packages.append(package)
self.print_error(f"Package {package} not installed")
if missing_packages:
print(f"\n{YELLOW}To install missing packages:{RESET}")
print(f"cd backend && pip install -r requirements.txt")
return False
return True
def check_npm_dependencies(self) -> bool:
"""Check if npm dependencies are installed"""
self.print_header("Checking Frontend Dependencies")
node_modules = self.project_root / "frontend" / "node_modules"
package_json = self.project_root / "frontend" / "package.json"
if not package_json.exists():
self.print_error("frontend/package.json not found")
return False
if not node_modules.exists():
self.print_warning("node_modules not found")
print(f"\n{YELLOW}To install dependencies:{RESET}")
print("cd frontend && npm install")
return False
# Check for key packages
key_packages = [
"react",
"typescript",
"vite",
"@tanstack/react-query",
"react-markdown",
"react-syntax-highlighter"
]
with open(package_json, 'r') as f:
pkg_data = json.load(f)
deps = {**pkg_data.get('dependencies', {}), **pkg_data.get('devDependencies', {})}
for package in key_packages:
if package in deps:
self.print_success(f"Package {package} ✓")
else:
self.print_error(f"Package {package} not in package.json")
return node_modules.exists()
def check_database(self) -> bool:
"""Check database setup"""
self.print_header("Checking Database")
db_path = self.project_root / "data" / "experts.db"
if not db_path.exists():
self.print_error(f"Database not found at {db_path}")
print(f"\n{YELLOW}To create database:{RESET}")
print("1. mkdir -p data")
print("2. sqlite3 data/experts.db < schema.sql")
return False
# Check if database has tables
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check for required tables
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [row[0] for row in cursor.fetchall()]
required_tables = ["posts", "links", "expert_comments"]
for table in required_tables:
if table in tables:
cursor.execute(f"SELECT COUNT(*) FROM {table}")
count = cursor.fetchone()[0]
self.print_success(f"Table '{table}' exists ({count} rows)")
else:
self.print_error(f"Table '{table}' not found")
conn.close()
if not all(t in tables for t in required_tables):
return False
# Check if we have data
if all(t in tables for t in required_tables):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
cursor.execute("SELECT COUNT(*) FROM posts")
post_count = cursor.fetchone()[0]
conn.close()
if post_count == 0:
self.print_warning("Database exists but has no posts")
print(f"\n{YELLOW}To import data:{RESET}")
print("1. Place Telegram JSON export in data/exports/")
print("2. cd backend && python -m src.data.json_parser <json_file>")
return True
except Exception as e:
self.print_error(f"Database error: {e}")
return False
def check_environment_variables(self) -> bool:
"""Check environment configuration"""
self.print_header("Checking Environment Variables")
backend_env = self.project_root / "backend" / ".env"
env_example = self.project_root / "backend" / ".env.example"
if not backend_env.exists():
if env_example.exists():
self.print_warning(".env not found, but .env.example exists")
print(f"\n{YELLOW}To create .env:{RESET}")
print("cp backend/.env.example backend/.env")
print("Then edit backend/.env and add your OPENAI_API_KEY")
else:
self.print_error("No .env or .env.example found")
return False
# Check for required variables
required_vars = ["OPENAI_API_KEY"]
found_vars = {}
with open(backend_env, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
if '=' in line:
key, value = line.split('=', 1)
found_vars[key.strip()] = value.strip()
for var in required_vars:
if var in found_vars:
value = found_vars[var]
if value and value != "your_openai_api_key_here":
if var == "OPENAI_API_KEY":
# Mask the API key
masked = value[:7] + "..." + value[-4:] if len(value) > 11 else "***"
self.print_success(f"{var} = {masked} ✓")
else:
self.print_error(f"{var} not configured (placeholder value)")
return False
else:
self.print_error(f"{var} not found in .env")
return False
return True
def check_ports_available(self) -> bool:
"""Check if required ports are available"""
self.print_header("Checking Port Availability")
ports = {
8000: "Backend API",
5173: "Frontend Dev Server"
}
blocked_ports = []
for port, service in ports.items():
try:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', port))
sock.close()
if result == 0:
self.print_warning(f"Port {port} ({service}) is already in use")
blocked_ports.append(port)
else:
self.print_success(f"Port {port} ({service}) is available ✓")
except Exception as e:
self.print_warning(f"Could not check port {port}: {e}")
if blocked_ports:
print(f"\n{YELLOW}Ports in use. You may need to:{RESET}")
print("1. Stop existing services, OR")
print("2. Use different ports in configuration")
return True # Non-critical, just warning
def test_backend_startup(self) -> bool:
"""Test if backend can start"""
self.print_header("Testing Backend Startup")
try:
# Start backend process
process = subprocess.Popen(
["python", "-m", "uvicorn", "src.api.main:app", "--port", "8000"],
cwd=self.project_root / "backend",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
print("Starting backend server...")
time.sleep(5) # Give it time to start
# Check if process is still running
if process.poll() is not None:
stdout, stderr = process.communicate()
self.print_error("Backend failed to start")
if stderr:
print(f"{RED}Error output:{RESET}")
print(stderr[:500]) # First 500 chars of error
return False
# Test health endpoint
import requests
try:
response = requests.get("http://localhost:8000/health", timeout=5)
if response.status_code == 200:
data = response.json()
self.print_success(f"Backend started successfully ✓")
self.print_success(f"Health check: {data['status']}")
if data.get('database') == 'healthy':
self.print_success("Database connection: healthy ✓")
if data.get('openai_configured'):
self.print_success("OpenAI API key: configured ✓")
else:
self.print_error(f"Health check failed: {response.status_code}")
except requests.exceptions.RequestException as e:
self.print_error(f"Could not connect to backend: {e}")
# Stop the process
process.terminate()
process.wait(timeout=5)
return True
except Exception as e:
self.print_error(f"Failed to test backend: {e}")
return False
def print_summary(self):
"""Print validation summary"""
self.print_header("Validation Summary")
total_checks = len(self.successes) + len(self.warnings) + len(self.errors)
print(f"{BOLD}Results:{RESET}")
print(f" {GREEN}✓ Passed:{RESET} {len(self.successes)}")
print(f" {YELLOW}⚠ Warnings:{RESET} {len(self.warnings)}")
print(f" {RED}✗ Failed:{RESET} {len(self.errors)}")
if self.errors:
print(f"\n{RED}{BOLD}❌ Validation FAILED{RESET}")
print("\nPlease fix the errors above before running the project.")
elif self.warnings:
print(f"\n{YELLOW}{BOLD}⚠️ Validation PASSED with warnings{RESET}")
print("\nThe project should run, but check the warnings.")
else:
print(f"\n{GREEN}{BOLD}✅ Validation PASSED{RESET}")
print("\nProject is ready to run!")
# Quick start commands
print(f"\n{BOLD}Quick Start Commands:{RESET}")
print("\n1. Start Backend:")
print(" cd backend")
print(" uvicorn src.api.main:app --reload --port 8000")
print("\n2. Start Frontend:")
print(" cd frontend")
print(" npm run dev")
print("\n3. Open Browser:")
print(" http://localhost:5173")
if not self.errors:
print(f"\n{GREEN}Ready to go! 🚀{RESET}")
def run(self) -> bool:
"""Run all validation checks"""
print(f"{BOLD}🔍 Experts Panel - Quickstart Validation{RESET}")
print(f"Project Root: {self.project_root}")
# Run checks
checks = [
self.check_python_version,
self.check_node_version,
self.check_python_dependencies,
self.check_npm_dependencies,
self.check_database,
self.check_environment_variables,
self.check_ports_available,
self.test_backend_startup,
]
for check in checks:
try:
check()
except Exception as e:
self.print_error(f"Check failed with exception: {e}")
# Print summary
self.print_summary()
return len(self.errors) == 0
def main():
"""Main entry point"""
validator = QuickstartValidator()
success = validator.run()
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()