Spaces:
Runtime error
Runtime error
File size: 7,576 Bytes
330b6e4 |
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 |
#!/usr/bin/env python3
"""Environment setup script for the chat agent application."""
import os
import sys
import shutil
import subprocess
from pathlib import Path
def create_directories():
"""Create necessary directories for the application."""
directories = [
'logs',
'instance',
'ssl',
'backups',
'config'
]
for directory in directories:
Path(directory).mkdir(exist_ok=True)
print(f"Created directory: {directory}")
def setup_environment_file(environment='development'):
"""Set up environment file for specified environment."""
env_file = f"config/{environment}.env"
target_file = ".env"
if Path(env_file).exists():
shutil.copy(env_file, target_file)
print(f"Copied {env_file} to {target_file}")
else:
print(f"Warning: {env_file} not found")
# Create basic .env from .env.example if it exists
if Path(".env.example").exists():
shutil.copy(".env.example", target_file)
print(f"Copied .env.example to {target_file}")
else:
print("Warning: No environment template found")
def install_dependencies():
"""Install Python dependencies."""
print("Installing Python dependencies...")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"],
check=True)
print("Dependencies installed successfully!")
except subprocess.CalledProcessError as e:
print(f"Error installing dependencies: {e}")
sys.exit(1)
def check_system_requirements():
"""Check if system requirements are met."""
print("Checking system requirements...")
# Check Python version
if sys.version_info < (3, 8):
print("Error: Python 3.8 or higher is required")
sys.exit(1)
print(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
# Check if PostgreSQL is available
try:
import psycopg2
print("✓ PostgreSQL driver available")
except ImportError:
print("Warning: PostgreSQL driver not available. Install with: pip install psycopg2-binary")
# Check if Redis is available
try:
import redis
print("✓ Redis client available")
except ImportError:
print("Warning: Redis client not available. Install with: pip install redis")
def setup_git_hooks():
"""Set up Git hooks for development."""
hooks_dir = Path(".git/hooks")
if not hooks_dir.exists():
print("Warning: Not a Git repository, skipping Git hooks setup")
return
# Pre-commit hook for code quality
pre_commit_hook = hooks_dir / "pre-commit"
pre_commit_content = """#!/bin/bash
# Pre-commit hook for code quality checks
echo "Running pre-commit checks..."
# Run tests
python -m pytest tests/ --quiet
if [ $? -ne 0 ]; then
echo "Tests failed. Commit aborted."
exit 1
fi
# Check for common issues
python -m flake8 chat_agent/ --max-line-length=100 --ignore=E203,W503
if [ $? -ne 0 ]; then
echo "Code style issues found. Please fix before committing."
exit 1
fi
echo "Pre-commit checks passed!"
"""
with open(pre_commit_hook, 'w') as f:
f.write(pre_commit_content)
# Make executable
os.chmod(pre_commit_hook, 0o755)
print("✓ Git pre-commit hook installed")
def generate_secret_key():
"""Generate a secure secret key for Flask."""
import secrets
secret_key = secrets.token_urlsafe(32)
print(f"Generated secret key: {secret_key}")
print("Add this to your environment configuration:")
print(f"SECRET_KEY={secret_key}")
return secret_key
def setup_logging():
"""Set up logging configuration."""
log_config = """
import logging
import logging.config
LOGGING_CONFIG = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
},
'detailed': {
'format': '[%(asctime)s] %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]: %(message)s',
}
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level': 'INFO',
'formatter': 'default',
'stream': 'ext://sys.stdout'
},
'file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'DEBUG',
'formatter': 'detailed',
'filename': 'logs/chat_agent.log',
'maxBytes': 10485760, # 10MB
'backupCount': 5
}
},
'loggers': {
'chat_agent': {
'level': 'DEBUG',
'handlers': ['console', 'file'],
'propagate': False
}
},
'root': {
'level': 'INFO',
'handlers': ['console']
}
}
def setup_logging():
logging.config.dictConfig(LOGGING_CONFIG)
"""
with open('chat_agent/utils/logging_setup.py', 'w') as f:
f.write(log_config)
print("✓ Logging configuration created")
def main():
"""Main setup function."""
import argparse
parser = argparse.ArgumentParser(description="Environment setup for chat agent")
parser.add_argument(
"--environment",
default="development",
choices=["development", "production", "testing"],
help="Environment to set up"
)
parser.add_argument(
"--skip-deps",
action="store_true",
help="Skip dependency installation"
)
parser.add_argument(
"--skip-db",
action="store_true",
help="Skip database initialization"
)
args = parser.parse_args()
print(f"Setting up environment: {args.environment}")
print("=" * 50)
# Check system requirements
check_system_requirements()
# Create directories
create_directories()
# Set up environment file
setup_environment_file(args.environment)
# Install dependencies
if not args.skip_deps:
install_dependencies()
# Set up Git hooks (development only)
if args.environment == 'development':
setup_git_hooks()
# Generate secret key
if args.environment != 'testing':
generate_secret_key()
# Set up logging
setup_logging()
# Initialize database
if not args.skip_db:
print("\nInitializing database...")
try:
from scripts.init_db import init_database
init_database(args.environment)
except Exception as e:
print(f"Database initialization failed: {e}")
print("You can run it manually later with: python scripts/init_db.py init")
print("\n" + "=" * 50)
print("Environment setup completed!")
print(f"Environment: {args.environment}")
print("\nNext steps:")
print("1. Update your .env file with actual API keys and database credentials")
print("2. Start the application with: python app.py")
print("3. Visit http://localhost:5000 to test the chat interface")
if args.environment == 'development':
print("4. Run tests with: python -m pytest tests/")
if __name__ == "__main__":
main() |