File size: 7,947 Bytes
37b89b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/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)