#!/usr/bin/env python3 """ Setup script for Hugging Face deployment environment variables. This script helps you configure the required environment variables. """ import os import sys from pathlib import Path def print_banner(): """Print setup banner.""" print("Hugging Face Deployment Environment Setup") print("=" * 60) print() def get_user_input(prompt, default="", required=False, secret=False): """Get user input with validation.""" while True: if secret: import getpass value = getpass.getpass(prompt) else: value = input(prompt) if not value and required: print("[ERROR] This field is required. Please enter a value.") continue if not value and default: value = default return value def setup_environment(): """Setup environment variables.""" print_banner() print("This script will help you set up the required environment variables") print("for Hugging Face deployment. You'll need:") print() print("1. A Supabase project (https://supabase.com) - REQUIRED") print("2. Your OpenAI API key - REQUIRED") print("3. A secure secret key for JWT tokens - REQUIRED") print() print("[WARNING] Note: This project uses Supabase (PostgreSQL) only.") print(" SQLite is not supported.") print() # Check if .env file already exists env_file = Path(".env") if env_file.exists(): response = get_user_input("A .env file already exists. Overwrite it? (y/N): ", "N") if response.lower() != 'y': print("Setup cancelled.") return print("\nSetting up environment variables...") print() # Get Supabase configuration print("SUPABASE CONFIGURATION") print("-" * 30) print("You need to create a Supabase project at https://supabase.com") print("Then get your database connection string from:") print("Settings -> Database -> Connection string") print() supabase_url = get_user_input( "Enter your Supabase database URL (postgresql+asyncpg://postgres:[password]@[host]:5432/postgres): ", required=True ) # Validate Supabase URL format if not supabase_url.startswith("postgresql+asyncpg://"): print("[WARNING] Warning: URL should start with 'postgresql+asyncpg://'") print(" Make sure to add '+asyncpg' after 'postgresql'") # Get OpenAI API key print("\nOPENAI CONFIGURATION") print("-" * 30) openai_key = get_user_input( "Enter your OpenAI API key (sk-...): ", required=True, secret=True ) # Get secret key print("\nSECURITY CONFIGURATION") print("-" * 30) import secrets default_secret = secrets.token_urlsafe(32) secret_key = get_user_input( f"Enter a secret key for JWT tokens (press Enter for auto-generated): ", default_secret ) # Get other optional settings print("\nOPTIONAL SETTINGS") print("-" * 30) environment = get_user_input("Environment (production/development): ", "production") debug = get_user_input("Debug mode (true/false): ", "false") # Create .env file content env_content = f"""# ============================================================================= # Environment Configuration for Hugging Face Deployment # ============================================================================= # Generated by setup_huggingface_env.py # Never commit this file to version control # ============================================================================= # DATABASE CONFIGURATION # ============================================================================= SUPABASE_DB_URL={supabase_url} ENVIRONMENT={environment} # ============================================================================= # SECURITY SETTINGS # ============================================================================= SECRET_KEY={secret_key} ALGORITHM=HS256 ACCESS_TOKEN_EXPIRE_MINUTES=30 REFRESH_TOKEN_EXPIRE_DAYS=7 # ============================================================================= # AI SERVICE CONFIGURATION # ============================================================================= OPENAI_API_KEY={openai_key} OPENAI_MODEL=gpt-4o EMBEDDING_MODEL=text-embedding-3-small PRIMARY_AI_SERVICE=openai # ============================================================================= # APPLICATION SETTINGS # ============================================================================= DEBUG={debug} HOST=0.0.0.0 PORT=7860 # ============================================================================= # FILE UPLOAD SETTINGS # ============================================================================= UPLOAD_DIR=./uploads MAX_FILE_SIZE=10485760 # ============================================================================= # NOTES # ============================================================================= # This configuration is optimized for Hugging Face deployment # SQLite is disabled in favor of Supabase PostgreSQL # All sensitive data should be set as Hugging Face Space secrets """ # Write .env file try: with open(env_file, 'w') as f: f.write(env_content) print(f"\n[OK] Environment file created: {env_file}") except Exception as e: print(f"\n[ERROR] Error creating .env file: {e}") return # Create Hugging Face secrets template secrets_content = f"""# ============================================================================= # Hugging Face Space Secrets Template # ============================================================================= # Copy these values to your Hugging Face Space secrets # Go to: Settings -> Repository secrets SUPABASE_DB_URL={supabase_url} ENVIRONMENT={environment} OPENAI_API_KEY={openai_key} SECRET_KEY={secret_key} """ secrets_file = Path("huggingface_secrets.txt") try: with open(secrets_file, 'w') as f: f.write(secrets_content) print(f"[OK] Hugging Face secrets template created: {secrets_file}") except Exception as e: print(f"[ERROR] Error creating secrets template: {e}") print("\n[SUCCESS] Setup completed successfully!") print("\nNext steps:") print("1. Copy the values from huggingface_secrets.txt to your Hugging Face Space secrets") print("2. Test your configuration: python test_database_config.py") print("3. Deploy to Hugging Face Spaces") print("\nSecurity notes:") print("- Never commit .env files to version control") print("- Use Hugging Face secrets for production deployment") print("- Keep your API keys secure") def main(): """Main function.""" try: setup_environment() except KeyboardInterrupt: print("\n\nSetup cancelled by user.") sys.exit(1) except Exception as e: print(f"\n[ERROR] Setup failed: {e}") sys.exit(1) if __name__ == "__main__": main()