CoolFace
Apppublic

WebashalarForML/scratch_chat

sourceHugging Facemitupdated 1y agoView on Hugging Face
0likes
setup_environment.py262 linesDownload Raw Back to scripts
1#!/usr/bin/env python3
2"""Environment setup script for the chat agent application."""
3
4import os
5import sys
6import shutil
7import subprocess
8from pathlib import Path
9
10
11def create_directories():
12    """Create necessary directories for the application."""
13    directories = [
14        'logs',
15        'instance',
16        'ssl',
17        'backups',
18        'config'
19    ]
20    
21    for directory in directories:
22        Path(directory).mkdir(exist_ok=True)
23        print(f"Created directory: {directory}")
24
25
26def setup_environment_file(environment='development'):
27    """Set up environment file for specified environment."""
28    env_file = f"config/{environment}.env"
29    target_file = ".env"
30    
31    if Path(env_file).exists():
32        shutil.copy(env_file, target_file)
33        print(f"Copied {env_file} to {target_file}")
34    else:
35        print(f"Warning: {env_file} not found")
36        
37        # Create basic .env from .env.example if it exists
38        if Path(".env.example").exists():
39            shutil.copy(".env.example", target_file)
40            print(f"Copied .env.example to {target_file}")
41        else:
42            print("Warning: No environment template found")
43
44
45def install_dependencies():
46    """Install Python dependencies."""
47    print("Installing Python dependencies...")
48    try:
49        subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], 
50                      check=True)
51        print("Dependencies installed successfully!")
52    except subprocess.CalledProcessError as e:
53        print(f"Error installing dependencies: {e}")
54        sys.exit(1)
55
56
57def check_system_requirements():
58    """Check if system requirements are met."""
59    print("Checking system requirements...")
60    
61    # Check Python version
62    if sys.version_info < (3, 8):
63        print("Error: Python 3.8 or higher is required")
64        sys.exit(1)
65    
66    print(f"✓ Python {sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}")
67    
68    # Check if PostgreSQL is available
69    try:
70        import psycopg2
71        print("✓ PostgreSQL driver available")
72    except ImportError:
73        print("Warning: PostgreSQL driver not available. Install with: pip install psycopg2-binary")
74    
75    # Check if Redis is available
76    try:
77        import redis
78        print("✓ Redis client available")
79    except ImportError:
80        print("Warning: Redis client not available. Install with: pip install redis")
81
82
83def setup_git_hooks():
84    """Set up Git hooks for development."""
85    hooks_dir = Path(".git/hooks")
86    if not hooks_dir.exists():
87        print("Warning: Not a Git repository, skipping Git hooks setup")
88        return
89    
90    # Pre-commit hook for code quality
91    pre_commit_hook = hooks_dir / "pre-commit"
92    pre_commit_content = """#!/bin/bash
93# Pre-commit hook for code quality checks
94
95echo "Running pre-commit checks..."
96
97# Run tests
98python -m pytest tests/ --quiet
99if [ $? -ne 0 ]; then
100    echo "Tests failed. Commit aborted."
101    exit 1
102fi
103
104# Check for common issues
105python -m flake8 chat_agent/ --max-line-length=100 --ignore=E203,W503
106if [ $? -ne 0 ]; then
107    echo "Code style issues found. Please fix before committing."
108    exit 1
109fi
110
111echo "Pre-commit checks passed!"
112"""
113    
114    with open(pre_commit_hook, 'w') as f:
115        f.write(pre_commit_content)
116    
117    # Make executable
118    os.chmod(pre_commit_hook, 0o755)
119    print("✓ Git pre-commit hook installed")
120
121
122def generate_secret_key():
123    """Generate a secure secret key for Flask."""
124    import secrets
125    secret_key = secrets.token_urlsafe(32)
126    print(f"Generated secret key: {secret_key}")
127    print("Add this to your environment configuration:")
128    print(f"SECRET_KEY={secret_key}")
129    return secret_key
130
131
132def setup_logging():
133    """Set up logging configuration."""
134    log_config = """
135import logging
136import logging.config
137
138LOGGING_CONFIG = {
139    'version': 1,
140    'disable_existing_loggers': False,
141    'formatters': {
142        'default': {
143            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
144        },
145        'detailed': {
146            'format': '[%(asctime)s] %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]: %(message)s',
147        }
148    },
149    'handlers': {
150        'console': {
151            'class': 'logging.StreamHandler',
152            'level': 'INFO',
153            'formatter': 'default',
154            'stream': 'ext://sys.stdout'
155        },
156        'file': {
157            'class': 'logging.handlers.RotatingFileHandler',
158            'level': 'DEBUG',
159            'formatter': 'detailed',
160            'filename': 'logs/chat_agent.log',
161            'maxBytes': 10485760,  # 10MB
162            'backupCount': 5
163        }
164    },
165    'loggers': {
166        'chat_agent': {
167            'level': 'DEBUG',
168            'handlers': ['console', 'file'],
169            'propagate': False
170        }
171    },
172    'root': {
173        'level': 'INFO',
174        'handlers': ['console']
175    }
176}
177
178def setup_logging():
179    logging.config.dictConfig(LOGGING_CONFIG)
180"""
181    
182    with open('chat_agent/utils/logging_setup.py', 'w') as f:
183        f.write(log_config)
184    
185    print("✓ Logging configuration created")
186
187
188def main():
189    """Main setup function."""
190    import argparse
191    
192    parser = argparse.ArgumentParser(description="Environment setup for chat agent")
193    parser.add_argument(
194        "--environment",
195        default="development",
196        choices=["development", "production", "testing"],
197        help="Environment to set up"
198    )
199    parser.add_argument(
200        "--skip-deps",
201        action="store_true",
202        help="Skip dependency installation"
203    )
204    parser.add_argument(
205        "--skip-db",
206        action="store_true",
207        help="Skip database initialization"
208    )
209    
210    args = parser.parse_args()
211    
212    print(f"Setting up environment: {args.environment}")
213    print("=" * 50)
214    
215    # Check system requirements
216    check_system_requirements()
217    
218    # Create directories
219    create_directories()
220    
221    # Set up environment file
222    setup_environment_file(args.environment)
223    
224    # Install dependencies
225    if not args.skip_deps:
226        install_dependencies()
227    
228    # Set up Git hooks (development only)
229    if args.environment == 'development':
230        setup_git_hooks()
231    
232    # Generate secret key
233    if args.environment != 'testing':
234        generate_secret_key()
235    
236    # Set up logging
237    setup_logging()
238    
239    # Initialize database
240    if not args.skip_db:
241        print("\nInitializing database...")
242        try:
243            from scripts.init_db import init_database
244            init_database(args.environment)
245        except Exception as e:
246            print(f"Database initialization failed: {e}")
247            print("You can run it manually later with: python scripts/init_db.py init")
248    
249    print("\n" + "=" * 50)
250    print("Environment setup completed!")
251    print(f"Environment: {args.environment}")
252    print("\nNext steps:")
253    print("1. Update your .env file with actual API keys and database credentials")
254    print("2. Start the application with: python app.py")
255    print("3. Visit http://localhost:5000 to test the chat interface")
256    
257    if args.environment == 'development':
258        print("4. Run tests with: python -m pytest tests/")
259
260
261if __name__ == "__main__":
262    main()