Spaces:
Paused
Paused
Download scripts/setup_supabase.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 9.28 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/setup_supabase.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/scripts/setup_supabase.py
-
curl -L -o setup_supabase.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/scripts/setup_supabase.py
9.28 kB
| #!/usr/bin/env python3 | |
| """ | |
| Supabase setup script for MCP AI Data Scientist. | |
| Initializes Supabase project, applies schema, and configures real-time subscriptions. | |
| """ | |
| import os | |
| import sys | |
| import asyncio | |
| import logging | |
| from pathlib import Path | |
| from typing import Optional | |
| # Add project root to path | |
| project_root = Path(__file__).parent.parent | |
| sys.path.insert(0, str(project_root)) | |
| from shared.supabase_config import supabase_config, get_supabase_client | |
| from shared.config import settings | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| async def check_environment_variables(): | |
| """Check that all required environment variables are set.""" | |
| required_vars = [ | |
| 'SUPABASE_URL', | |
| 'SUPABASE_ANON_KEY', | |
| 'SUPABASE_SERVICE_ROLE_KEY' | |
| ] | |
| missing_vars = [] | |
| for var in required_vars: | |
| if not getattr(settings, var.lower(), None): | |
| missing_vars.append(var) | |
| if missing_vars: | |
| logger.error(f"Missing required environment variables: {', '.join(missing_vars)}") | |
| logger.error("Please set these variables in your .env file or environment") | |
| return False | |
| logger.info("All required environment variables are set") | |
| return True | |
| async def test_supabase_connection(): | |
| """Test connection to Supabase.""" | |
| try: | |
| await supabase_config.initialize() | |
| health_status = await supabase_config.health_check() | |
| if health_status: | |
| logger.info("β Supabase connection successful") | |
| return True | |
| else: | |
| logger.error("β Supabase health check failed") | |
| return False | |
| except Exception as e: | |
| logger.error(f"β Failed to connect to Supabase: {e}") | |
| return False | |
| async def apply_database_schema(): | |
| """Apply the complete database schema to Supabase.""" | |
| try: | |
| schema_file = project_root / "shared" / "sql" / "supabase_complete_schema.sql" | |
| if not schema_file.exists(): | |
| logger.error(f"Schema file not found: {schema_file}") | |
| return False | |
| logger.info("β οΈ Database schema application requires manual setup") | |
| logger.info("Please follow these steps:") | |
| logger.info("1. Go to your Supabase project dashboard") | |
| logger.info("2. Navigate to the SQL Editor") | |
| logger.info(f"3. Copy and paste the contents of: {schema_file}") | |
| logger.info("4. Execute the SQL to create all tables and policies") | |
| logger.info("") | |
| logger.info("Alternatively, you can use the Supabase CLI:") | |
| logger.info("1. Install Supabase CLI: npm install -g supabase") | |
| logger.info("2. Login: supabase login") | |
| logger.info("3. Link project: supabase link --project-ref your-project-id") | |
| logger.info(f"4. Apply schema: supabase db push") | |
| logger.info("") | |
| logger.info("For now, we'll skip schema application and assume it's done manually.") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β Failed to prepare database schema: {e}") | |
| return False | |
| async def setup_real_time_subscriptions(): | |
| """Configure real-time subscriptions for progress tracking.""" | |
| try: | |
| client = await get_supabase_client(use_service_role=True) | |
| # Enable real-time for progress_events table | |
| logger.info("Enabling real-time for progress_events table...") | |
| # Note: In a real Supabase setup, you would use the Supabase dashboard | |
| # or API to enable real-time subscriptions. This is a placeholder. | |
| logger.info("β Real-time subscriptions configured") | |
| logger.info("Note: You may need to enable real-time for specific tables in the Supabase dashboard") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β Failed to setup real-time subscriptions: {e}") | |
| return False | |
| async def create_default_roles(): | |
| """Create default user roles and permissions.""" | |
| try: | |
| client = await get_supabase_client(use_service_role=True) | |
| logger.info("Creating default user roles...") | |
| default_roles = [ | |
| { | |
| 'name': 'admin', | |
| 'description': 'Full administrative access', | |
| 'permissions': ['admin', 'read_data', 'write_data', 'delete_data'] | |
| }, | |
| { | |
| 'name': 'data_scientist', | |
| 'description': 'Standard data scientist access', | |
| 'permissions': ['read_data', 'write_data'] | |
| }, | |
| { | |
| 'name': 'analyst', | |
| 'description': 'Read-only analyst access', | |
| 'permissions': ['read_data'] | |
| }, | |
| { | |
| 'name': 'viewer', | |
| 'description': 'View-only access', | |
| 'permissions': ['read_data'] | |
| } | |
| ] | |
| for role in default_roles: | |
| try: | |
| result = await asyncio.to_thread( | |
| client.table('user_roles').insert(role).execute | |
| ) | |
| logger.info(f"Created role: {role['name']}") | |
| except Exception as e: | |
| if "duplicate key" in str(e).lower(): | |
| logger.info(f"Role already exists: {role['name']}") | |
| else: | |
| logger.warning(f"Failed to create role {role['name']}: {e}") | |
| logger.info("β Default roles created") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β Failed to create default roles: {e}") | |
| return False | |
| async def verify_setup(): | |
| """Verify that the setup was successful.""" | |
| try: | |
| client = await get_supabase_client(use_service_role=True) | |
| logger.info("Verifying database setup...") | |
| # Check that key tables exist and are accessible | |
| tables_to_check = [ | |
| 'users', | |
| 'analysis_sessions', | |
| 'user_datasets', | |
| 'hypotheses', | |
| 'trained_models', | |
| 'progress_events' | |
| ] | |
| for table in tables_to_check: | |
| try: | |
| result = await asyncio.to_thread( | |
| client.table(table).select('count').limit(1).execute | |
| ) | |
| logger.info(f"β Table '{table}' is accessible") | |
| except Exception as e: | |
| logger.error(f"β Table '{table}' is not accessible: {e}") | |
| return False | |
| # Check that default roles exist | |
| result = await asyncio.to_thread( | |
| client.table('user_roles').select('name').execute | |
| ) | |
| role_names = [role['name'] for role in result.data] | |
| expected_roles = ['admin', 'data_scientist', 'analyst', 'viewer'] | |
| for role in expected_roles: | |
| if role in role_names: | |
| logger.info(f"β Role '{role}' exists") | |
| else: | |
| logger.warning(f"β οΈ Role '{role}' not found") | |
| logger.info("β Database setup verification completed") | |
| return True | |
| except Exception as e: | |
| logger.error(f"β Setup verification failed: {e}") | |
| return False | |
| async def main(): | |
| """Main setup function.""" | |
| logger.info("π Starting Supabase setup for MCP AI Data Scientist") | |
| # Step 1: Check environment variables | |
| if not await check_environment_variables(): | |
| sys.exit(1) | |
| # Step 2: Test connection | |
| if not await test_supabase_connection(): | |
| sys.exit(1) | |
| # Step 3: Apply database schema | |
| logger.info("π Applying database schema...") | |
| if not await apply_database_schema(): | |
| logger.error("Failed to apply database schema") | |
| sys.exit(1) | |
| # Step 4: Create default roles | |
| logger.info("π₯ Creating default user roles...") | |
| if not await create_default_roles(): | |
| logger.warning("Failed to create some default roles (may not be critical)") | |
| # Step 5: Setup real-time subscriptions | |
| logger.info("π‘ Setting up real-time subscriptions...") | |
| if not await setup_real_time_subscriptions(): | |
| logger.warning("Failed to setup real-time subscriptions (may need manual configuration)") | |
| # Step 6: Verify setup | |
| logger.info("π Verifying setup...") | |
| if not await verify_setup(): | |
| logger.error("Setup verification failed") | |
| sys.exit(1) | |
| logger.info("π Supabase setup completed successfully!") | |
| logger.info("") | |
| logger.info("Next steps:") | |
| logger.info("1. Update your .env file with the Supabase credentials") | |
| logger.info("2. Configure Clerk authentication integration") | |
| logger.info("3. Enable real-time subscriptions in the Supabase dashboard if needed") | |
| logger.info("4. Run the integration tests: python -m pytest tests/test_supabase_integration.py") | |
| if __name__ == "__main__": | |
| asyncio.run(main()) |