Spaces:
Sleeping
Sleeping
File size: 7,515 Bytes
31881e7 | 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 | #!/usr/bin/env python3
"""
AutoGrantED Setup Script
Automated installation and configuration for the AutoGrantED system
"""
import os
import sys
import subprocess
import shutil
from pathlib import Path
def run_command(command, description=""):
"""Run a shell command and handle errors."""
print(f"π§ {description}")
try:
result = subprocess.run(command, shell=True, check=True, capture_output=True, text=True)
if result.stdout:
print(f" β
{result.stdout.strip()}")
return True
except subprocess.CalledProcessError as e:
print(f" β Error: {e.stderr.strip()}")
return False
def check_prerequisites():
"""Check if required software is installed."""
print("π Checking prerequisites...")
prerequisites = {
'python3': 'Python 3.9+',
'pip': 'Python package manager',
'psql': 'PostgreSQL client',
'redis-cli': 'Redis client',
'google-chrome': 'Chrome browser (for scraping)'
}
missing = []
for cmd, desc in prerequisites.items():
if not shutil.which(cmd):
missing.append(f"{desc} ({cmd})")
if missing:
print("β Missing prerequisites:")
for item in missing:
print(f" - {item}")
print("\nPlease install missing prerequisites and run setup again.")
return False
print("β
All prerequisites found!")
return True
def create_virtual_environment():
"""Create and activate virtual environment."""
print("π Setting up virtual environment...")
if os.path.exists('venv'):
print(" Virtual environment already exists")
return True
return run_command('python3 -m venv venv', 'Creating virtual environment')
def install_dependencies():
"""Install Python dependencies."""
print("π¦ Installing Python dependencies...")
# Activate virtual environment and install requirements
if os.name == 'nt': # Windows
pip_cmd = 'venv\\Scripts\\pip install -r requirements.txt'
else: # Unix/Linux/macOS
pip_cmd = 'venv/bin/pip install -r requirements.txt'
return run_command(pip_cmd, 'Installing requirements')
def setup_environment_file():
"""Create .env file from template."""
print("βοΈ Setting up environment configuration...")
if os.path.exists('.env'):
print(" .env file already exists")
return True
if not os.path.exists('.env.example'):
print(" β .env.example not found")
return False
shutil.copy('.env.example', '.env')
print(" β
Created .env file from template")
print(" π Please edit .env with your configuration")
return True
def setup_database():
"""Set up PostgreSQL database."""
print("ποΈ Setting up database...")
# Check if database exists
db_check = subprocess.run(
'psql -lqt | cut -d \\| -f 1 | grep -qw autogranted',
shell=True,
capture_output=True
)
if db_check.returncode == 0:
print(" Database 'autogranted' already exists")
else:
if not run_command('createdb autogranted', 'Creating database'):
print(" β οΈ Could not create database. Please create manually:")
print(" createdb autogranted")
return False
# Initialize Flask database
if os.name == 'nt': # Windows
flask_cmd = 'venv\\Scripts\\flask'
else: # Unix/Linux/macOS
flask_cmd = 'venv/bin/flask'
commands = [
f'{flask_cmd} db init',
f'{flask_cmd} db migrate -m "Initial migration"',
f'{flask_cmd} db upgrade'
]
for cmd in commands:
if not run_command(cmd, f'Running: {cmd}'):
print(f" β οΈ Database setup may be incomplete")
break
return True
def create_directories():
"""Create necessary directories."""
print("π Creating directories...")
directories = [
'logs',
'uploads',
'generated_documents',
'instance'
]
for directory in directories:
Path(directory).mkdir(exist_ok=True)
print(f" β
Created {directory}/")
return True
def create_startup_scripts():
"""Create convenient startup scripts."""
print("π Creating startup scripts...")
# Unix/Linux/macOS startup script
startup_script = """#!/bin/bash
# AutoGrantED Startup Script
echo "π Starting AutoGrantED services..."
# Check if virtual environment exists
if [ ! -d "venv" ]; then
echo "β Virtual environment not found. Run setup.py first."
exit 1
fi
# Activate virtual environment
source venv/bin/activate
# Start services in background
echo "Starting Redis server..."
redis-server --daemonize yes
echo "Starting Celery worker..."
celery -A autogranted.celery worker --loglevel=info --detach
echo "Starting Celery beat scheduler..."
celery -A autogranted.celery beat --loglevel=info --detach
echo "Starting Flask application..."
export FLASK_APP=autogranted.py
export FLASK_ENV=development
flask run
echo "β
AutoGrantED is running at http://localhost:5000"
"""
with open('start.sh', 'w') as f:
f.write(startup_script)
os.chmod('start.sh', 0o755)
# Windows startup script
windows_script = """@echo off
REM AutoGrantED Startup Script for Windows
echo Starting AutoGrantED services...
REM Check if virtual environment exists
if not exist "venv" (
echo Virtual environment not found. Run setup.py first.
exit /b 1
)
REM Activate virtual environment
call venv\\Scripts\\activate
REM Start services
echo Starting Redis server...
start /B redis-server
echo Starting Celery worker...
start /B celery -A autogranted.celery worker --loglevel=info
echo Starting Celery beat scheduler...
start /B celery -A autogranted.celery beat --loglevel=info
echo Starting Flask application...
set FLASK_APP=autogranted.py
set FLASK_ENV=development
flask run
echo AutoGrantED is running at http://localhost:5000
"""
with open('start.bat', 'w') as f:
f.write(windows_script)
print(" β
Created start.sh (Unix/Linux/macOS)")
print(" β
Created start.bat (Windows)")
return True
def main():
"""Main setup function."""
print("π― AutoGrantED Setup")
print("=" * 50)
# Check if we're in the right directory
if not os.path.exists('autogranted.py'):
print("β Please run this script from the AutoGrantED root directory")
sys.exit(1)
steps = [
check_prerequisites,
create_virtual_environment,
install_dependencies,
setup_environment_file,
create_directories,
setup_database,
create_startup_scripts
]
for step in steps:
if not step():
print(f"\nβ Setup failed at step: {step.__name__}")
print("Please resolve the issue and run setup again.")
sys.exit(1)
print()
print("π Setup completed successfully!")
print("\nπ Next steps:")
print("1. Edit .env file with your configuration (OpenAI API key, database URL, etc.)")
print("2. Create an admin user: ./start.sh && flask create-admin")
print("3. Access the application at http://localhost:5000")
print("\nπ To start AutoGrantED:")
print(" Unix/Linux/macOS: ./start.sh")
print(" Windows: start.bat")
if __name__ == '__main__':
main()
|