pyannote-pt-diarization / test_simple.py
marcosremar2's picture
Add basic test script for space connectivity
37b89b9
#!/usr/bin/env python3
"""
Script de teste simples para verificar se o Space está funcionando
Não requer dependências pesadas - apenas requests
"""
import requests
import time
import json
# Configurações
SPACE_URL = "https://marcosremar2-pyannote-pt-diarization.hf.space"
def test_space_online():
"""Testa se o space está online"""
print("🌐 Testando se o space está online...")
try:
response = requests.get(SPACE_URL, timeout=15)
if response.status_code == 200:
print("✅ Space está online e respondendo")
return True
else:
print(f"❌ Space retornou status code: {response.status_code}")
return False
except requests.exceptions.Timeout:
print("⏰ Timeout - Space pode estar iniciando")
return False
except requests.exceptions.ConnectionError:
print("❌ Erro de conexão - Space pode estar offline")
return False
except Exception as e:
print(f"❌ Erro inesperado: {e}")
return False
def test_gradio_api():
"""Testa se a API do Gradio está respondendo"""
print("🔗 Testando API do Gradio...")
try:
# Tentar acessar a informação da API
api_url = f"{SPACE_URL}/api"
response = requests.get(api_url, timeout=10)
if response.status_code == 200:
print("✅ API do Gradio está respondendo")
return True
else:
print(f"❌ API retornou status: {response.status_code}")
return False
except Exception as e:
print(f"❌ Erro na API: {e}")
return False
def test_health_endpoint():
"""Testa o endpoint de health check"""
print("🏥 Testando health check...")
try:
# Tentar fazer request para o health check
health_url = f"{SPACE_URL}/api/predict"
payload = {
"data": [],
"fn_index": 1 # Index da função health_check
}
response = requests.post(
health_url,
json=payload,
timeout=30,
headers={'Content-Type': 'application/json'}
)
if response.status_code == 200:
result = response.json()
print("✅ Health check funcionando")
# Tentar extrair informações úteis
if 'data' in result and len(result['data']) > 0:
health_data = result['data'][0]
if isinstance(health_data, str):
try:
health_info = json.loads(health_data)
print(f" 📊 Status: {health_info.get('status', 'N/A')}")
print(f" 🖥️ Device: {health_info.get('device', 'N/A')}")
print(f" 🔧 GPU: {health_info.get('gpu_available', 'N/A')}")
print(f" 🤖 Modelo carregado: {health_info.get('model_loaded', 'N/A')}")
except:
print(f" 📄 Resposta: {health_data[:100]}...")
return True
else:
print(f"❌ Health check falhou com status: {response.status_code}")
return False
except Exception as e:
print(f"❌ Erro no health check: {e}")
return False
def test_space_logs():
"""Verifica se consegue acessar informações básicas do space"""
print("📋 Verificando informações do space...")
try:
# Fazer request para a página principal e procurar por indicadores
response = requests.get(SPACE_URL, timeout=10)
if response.status_code == 200:
content = response.text.lower()
# Verificar indicadores de funcionamento
indicators = {
"gradio_running": "gradio" in content,
"pyannote_mentioned": "pyannote" in content,
"diarization_mentioned": "diarization" in content,
"audio_upload": "audio" in content
}
print(" 🔍 Indicadores encontrados:")
for indicator, found in indicators.items():
status = "✅" if found else "❌"
print(f" {status} {indicator}")
return any(indicators.values())
else:
print(f"❌ Não conseguiu acessar a página: {response.status_code}")
return False
except Exception as e:
print(f"❌ Erro ao verificar logs: {e}")
return False
def wait_for_space_ready(max_wait: int = 300):
"""Aguarda o space ficar pronto, com timeout"""
print(f"⏳ Aguardando space ficar pronto (máximo {max_wait}s)...")
start_time = time.time()
while time.time() - start_time < max_wait:
if test_space_online():
print("✅ Space está pronto!")
return True
print(" ⏳ Aguardando 10 segundos...")
time.sleep(10)
print(f"⏰ Timeout após {max_wait}s - Space pode estar com problemas")
return False
def run_basic_tests():
"""Executa testes básicos de conectividade"""
print("🧪 TESTE BÁSICO DO PYANNOTE SPACE")
print("=" * 40)
results = {}
# Teste 1: Space online
results['space_online'] = test_space_online()
if not results['space_online']:
print("\n⏳ Space parece estar offline, tentando aguardar...")
results['space_ready'] = wait_for_space_ready(120) # 2 minutos
else:
results['space_ready'] = True
if results['space_ready'] or results['space_online']:
# Teste 2: API Gradio
results['gradio_api'] = test_gradio_api()
# Teste 3: Health check
results['health_check'] = test_health_endpoint()
# Teste 4: Informações básicas
results['space_info'] = test_space_logs()
else:
results['gradio_api'] = False
results['health_check'] = False
results['space_info'] = False
# Resumo
print("\n" + "=" * 40)
print("📊 RESUMO DOS TESTES:")
print("=" * 40)
for test_name, result in results.items():
status = "✅ PASSOU" if result else "❌ FALHOU"
print(f"{test_name:<15}: {status}")
# Status geral
passed = sum(results.values())
total = len(results)
print(f"\n🎯 RESULTADO: {passed}/{total} testes passaram")
if passed == total:
print("🎉 TODOS OS TESTES BÁSICOS PASSARAM!")
print(" 💡 O space parece estar funcionando corretamente")
return 0
elif passed >= total // 2:
print("⚠️ ALGUNS TESTES FALHARAM")
print(" 💡 O space pode estar iniciando ou com problemas menores")
return 1
else:
print("🚨 MUITOS TESTES FALHARAM")
print(" 💡 O space provavelmente tem problemas ou está offline")
return 2
if __name__ == "__main__":
try:
exit_code = run_basic_tests()
print(f"\n📝 PRÓXIMOS PASSOS:")
if exit_code == 0:
print(" ✅ Space funcionando - pode testar upload de áudio")
print(" 🔗 Acesse: https://marcosremar2-pyannote-pt-diarization.hf.space")
elif exit_code == 1:
print(" ⏳ Aguarde alguns minutos e teste novamente")
print(" 🔧 Verifique se o token HUGGINGFACE_TOKEN foi configurado")
else:
print(" 🔧 Verifique os logs do space no Hugging Face")
print(" 🔑 Confirme se o token foi configurado corretamente")
exit(exit_code)
except KeyboardInterrupt:
print("\n⛔ Teste interrompido pelo usuário")
exit(130)
except Exception as e:
print(f"\n💥 Erro inesperado: {e}")
exit(1)