""" validate_setup.py - Valida configuração do scraper Author: Descomplicar® Crescimento Digital Link: https://descomplicar.pt Copyright: 2025 Descomplicar® """ import os import sys import json from pathlib import Path def check_file(filepath, required=True): """Verifica se ficheiro existe.""" exists = os.path.exists(filepath) status = "✅" if exists else ("❌" if required else "⚠️") print(f"{status} {filepath}") return exists def check_env_var(var_name, required=True): """Verifica variável de ambiente.""" value = os.getenv(var_name) has_value = value is not None and value.strip() != "" status = "✅" if has_value else ("❌" if required else "⚠️") print(f"{status} {var_name}: {'SET' if has_value else 'NOT SET'}") return has_value def check_python_package(package_name): """Verifica se pacote Python está instalado.""" try: __import__(package_name) print(f"✅ {package_name}") return True except ImportError: print(f"❌ {package_name}") return False def main(): print("="*60) print("VALIDAÇÃO DE SETUP - WEB SCRAPER") print("="*60) errors = [] warnings = [] # 1. Ficheiros essenciais print("\n📁 FICHEIROS ESSENCIAIS:") if not check_file("requirements.txt"): errors.append("requirements.txt não encontrado") if not check_file("sites_config.json"): errors.append("sites_config.json não encontrado") if not check_file("scraper.py"): errors.append("scraper.py não encontrado") if not check_file("batch_scraper.py"): errors.append("batch_scraper.py não encontrado") # 2. Ficheiros opcionais print("\n📄 FICHEIROS OPCIONAIS:") if not check_file(".env", required=False): warnings.append(".env não encontrado - cria com: cp .env.example .env") if not check_file("README.md", required=False): warnings.append("README.md não encontrado") # 3. Variáveis de ambiente print("\n🔐 VARIÁVEIS DE AMBIENTE:") from dotenv import load_dotenv load_dotenv() # OpenRouter (opcional para formatação AI) if not check_env_var("OPENROUTER_API_KEY", required=False): warnings.append("OPENROUTER_API_KEY não definida - formatação AI não disponível") # Reddit (opcional) has_reddit_id = check_env_var("REDDIT_CLIENT_ID", required=False) has_reddit_secret = check_env_var("REDDIT_CLIENT_SECRET", required=False) if not has_reddit_id or not has_reddit_secret: warnings.append("Credenciais Reddit incompletas - scraping Reddit não disponível") # 4. Pacotes Python print("\n📦 DEPENDÊNCIAS PYTHON:") packages = { "requests": True, "playwright": True, "markdownify": True, "dotenv": True, "praw": False # Opcional (Reddit) } for pkg, required in packages.items(): if not check_python_package(pkg): if required: errors.append(f"Pacote {pkg} não instalado - executar: pip install {pkg}") else: warnings.append(f"Pacote {pkg} não instalado (opcional)") # 5. Playwright browsers print("\n🌐 PLAYWRIGHT BROWSERS:") playwright_dir = Path.home() / ".cache/ms-playwright" if playwright_dir.exists(): print("✅ Browsers instalados") else: print("❌ Browsers não instalados") errors.append("Executar: python -m playwright install chromium") # 6. Diretórios de output print("\n📂 DIRETÓRIOS:") dirs = ["output_md", "output_cleaned", "formatted", "logs"] for d in dirs: if not os.path.exists(d): print(f"⚠️ {d}/ não existe (será criado automaticamente)") else: print(f"✅ {d}/") # 7. Validar sites_config.json print("\n⚙️ CONFIGURAÇÃO:") try: with open("sites_config.json") as f: config = json.load(f) total_sites = len(config.get("sites", [])) reddit_subs = len(config.get("reddit_subreddits", [])) print(f"✅ sites_config.json válido") print(f" • {total_sites} sites configurados") print(f" • {reddit_subs} subreddits Reddit") if total_sites == 0: warnings.append("Nenhum site configurado em sites_config.json") except Exception as e: errors.append(f"Erro ao ler sites_config.json: {e}") # Resumo final print("\n" + "="*60) print("RESUMO") print("="*60) if errors: print(f"\n❌ {len(errors)} ERROS CRÍTICOS:") for error in errors: print(f" • {error}") if warnings: print(f"\n⚠️ {len(warnings)} AVISOS:") for warning in warnings: print(f" • {warning}") if not errors and not warnings: print("\n✅ TUDO CONFIGURADO CORRETAMENTE!") print("\nPróximo passo:") print(" python batch_scraper.py --all") elif not errors: print("\n✅ CONFIGURAÇÃO BÁSICA OK") print("⚠️ Alguns recursos opcionais não disponíveis (ver avisos acima)") print("\nPodes executar:") print(" python batch_scraper.py --all") else: print("\n❌ CORRIGE OS ERROS ANTES DE EXECUTAR") print("\nVer: README.md ou QUICKSTART.md") sys.exit(1) print("="*60) if __name__ == "__main__": main()