Spaces:
Sleeping
Sleeping
| """ | |
| Script interativo para configurar Supabase para RAG Template. | |
| Facilita a configuracao do DATABASE_URL e testa a conexao. | |
| """ | |
| import os | |
| import sys | |
| from urllib.parse import quote_plus | |
| def print_header(): | |
| """Imprime o cabecalho do script.""" | |
| print("=" * 60) | |
| print(" Setup Supabase para RAG Template") | |
| print("=" * 60) | |
| print() | |
| def get_project_ref(): | |
| """Solicita o Project Reference ID.""" | |
| print("1. Obter Project Reference") | |
| print(" - Acesse seu projeto no Supabase") | |
| print(" - Va para Settings > Database") | |
| print(" - Copie o 'Reference ID' (formato: xxxxxxxxxxxxx)") | |
| print() | |
| project_ref = input("Project Reference ID: ").strip() | |
| return project_ref | |
| def get_password(): | |
| """Solicita a senha do banco.""" | |
| print("\n2. Obter Senha do Banco") | |
| print(" - Use a senha que voce definiu ao criar o projeto") | |
| print(" - Ou resete em Settings > Database > Database Password") | |
| print() | |
| password = input("Database Password: ").strip() | |
| return password | |
| def build_database_url(project_ref: str, password: str) -> str: | |
| """Constroi a DATABASE_URL.""" | |
| # URL encode da senha para caracteres especiais | |
| encoded_password = quote_plus(password) | |
| # Construir URL | |
| database_url = ( | |
| f"postgresql://postgres:{encoded_password}" | |
| f"@db.{project_ref}.supabase.co:5432/postgres" | |
| ) | |
| return database_url | |
| def save_to_env(database_url: str) -> bool: | |
| """Salva DATABASE_URL no arquivo .env.""" | |
| print("\n3. Salvar no .env") | |
| # Verificar se .env ja existe | |
| env_path = ".env" | |
| if os.path.exists(env_path): | |
| print(f" Arquivo .env encontrado") | |
| overwrite = input(" Sobrescrever DATABASE_URL existente? (s/n): ").strip().lower() | |
| if overwrite != 's': | |
| print(" Pulando salvamento no .env") | |
| return False | |
| # Ler conteudo existente | |
| existing_content = "" | |
| if os.path.exists(env_path): | |
| with open(env_path, 'r') as f: | |
| lines = f.readlines() | |
| # Remover linha DATABASE_URL existente | |
| existing_content = "".join( | |
| line for line in lines if not line.startswith("DATABASE_URL=") | |
| ) | |
| # Adicionar nova DATABASE_URL | |
| with open(env_path, 'w') as f: | |
| f.write(existing_content) | |
| if existing_content and not existing_content.endswith('\n'): | |
| f.write('\n') | |
| f.write(f"DATABASE_URL={database_url}\n") | |
| print(f" DATABASE_URL salvo em {env_path}") | |
| return True | |
| def test_connection(database_url: str) -> bool: | |
| """Testa a conexao com o banco.""" | |
| print("\n4. Testar Conexao") | |
| test = input(" Testar conexao agora? (s/n): ").strip().lower() | |
| if test != 's': | |
| print(" Pulando teste de conexao") | |
| return False | |
| try: | |
| # Importar aqui para nao quebrar se dependencias nao instaladas | |
| import psycopg | |
| from psycopg import sql | |
| print(" Conectando ao Supabase...") | |
| with psycopg.connect(database_url) as conn: | |
| with conn.cursor() as cur: | |
| # Testar conexao | |
| cur.execute("SELECT version();") | |
| version = cur.fetchone()[0] | |
| print(f" Conexao bem-sucedida!") | |
| print(f" PostgreSQL version: {version[:50]}...") | |
| # Verificar extensao pgvector | |
| cur.execute( | |
| "SELECT EXISTS(SELECT 1 FROM pg_extension WHERE extname = 'vector');" | |
| ) | |
| has_vector = cur.fetchone()[0] | |
| if has_vector: | |
| print(" Extensao pgvector: INSTALADA") | |
| else: | |
| print(" Extensao pgvector: NAO ENCONTRADA") | |
| print(" Execute: CREATE EXTENSION vector;") | |
| print(" No SQL Editor do Supabase") | |
| return True | |
| except ImportError: | |
| print(" ERRO: psycopg nao instalado") | |
| print(" Execute: pip install psycopg[binary]") | |
| return False | |
| except Exception as e: | |
| print(f" ERRO ao conectar: {e}") | |
| print("\n Verifique:") | |
| print(" - Project Reference correto") | |
| print(" - Senha correta") | |
| print(" - Supabase nao pausado (free tier pausa apos 1 semana)") | |
| return False | |
| def print_next_steps(success: bool): | |
| """Imprime proximos passos.""" | |
| print("\n" + "=" * 60) | |
| print(" Proximos Passos") | |
| print("=" * 60) | |
| if success: | |
| print("\n Conexao configurada com sucesso!") | |
| print("\n 1. Certifique-se de ter HF_TOKEN no .env:") | |
| print(" HF_TOKEN=seu_token_huggingface") | |
| print("\n 2. Execute o app:") | |
| print(" python app.py") | |
| print("\n 3. Acesse: http://localhost:7860") | |
| else: | |
| print("\n Configure DATABASE_URL manualmente no .env:") | |
| print(" DATABASE_URL=postgresql://postgres:SENHA@db.REF.supabase.co:5432/postgres") | |
| print("\n Ou execute este script novamente") | |
| print("\n Documentacao completa: docs/SUPABASE_SETUP.md") | |
| print("=" * 60) | |
| def main(): | |
| """Funcao principal.""" | |
| print_header() | |
| # Coletar informacoes | |
| project_ref = get_project_ref() | |
| if not project_ref: | |
| print("ERRO: Project Reference vazio") | |
| sys.exit(1) | |
| password = get_password() | |
| if not password: | |
| print("ERRO: Senha vazia") | |
| sys.exit(1) | |
| # Construir URL | |
| database_url = build_database_url(project_ref, password) | |
| print("\n" + "=" * 60) | |
| print(" DATABASE_URL Gerado") | |
| print("=" * 60) | |
| print(f"\n{database_url}\n") | |
| # Salvar no .env | |
| saved = save_to_env(database_url) | |
| # Testar conexao | |
| success = test_connection(database_url) | |
| # Proximos passos | |
| print_next_steps(success and saved) | |
| if __name__ == "__main__": | |
| try: | |
| main() | |
| except KeyboardInterrupt: | |
| print("\n\nSetup cancelado pelo usuario") | |
| sys.exit(0) | |