File size: 3,104 Bytes
8fb6272
 
 
 
 
3374810
534b64d
8fb6272
 
 
 
 
 
 
 
3374810
 
534b64d
 
 
 
3374810
 
 
534b64d
 
 
 
 
 
 
 
3374810
8fb6272
 
 
 
 
 
 
 
 
 
3374810
8fb6272
 
 
 
 
 
 
 
 
 
534b64d
8fb6272
3374810
8fb6272
 
 
534b64d
8fb6272
 
 
 
3374810
 
8fb6272
 
 
 
 
3374810
 
8fb6272
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from dotenv import load_dotenv
from src.presentation.web.gradio_interface import GradioInterface
import logging
import torch
import gc
from src.domain.factories.detector_factory import force_gpu_init, is_gpu_available

# Configurar logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def setup_zero_gpu():
    """Configurações otimizadas para Zero-GPU."""
    # Forçar inicialização da GPU
    if is_gpu_available():
        force_gpu_init()
        # Limpar cache CUDA
        torch.cuda.empty_cache()
        gc.collect()
    
        # Configurações para otimizar memória
        os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.benchmark = True
        torch.backends.cudnn.allow_tf32 = True
        logger.info("Configurações Zero-GPU aplicadas com sucesso")
    else:
        logger.warning("GPU não disponível para configuração Zero-GPU")

def main():
    """Função principal que inicia a aplicação."""
    try:
        # Verificar se está rodando no Hugging Face
        IS_HUGGINGFACE = os.getenv('SPACE_ID') is not None
        
        # Carregar configurações do ambiente apropriado
        if IS_HUGGINGFACE:
            load_dotenv('.env.huggingface')
            logger.info("Ambiente HuggingFace detectado")
            setup_zero_gpu()
        else:
            load_dotenv('.env')
            logger.info("Ambiente local detectado")
        
        # Criar e configurar interface
        interface = GradioInterface()
        demo = interface.create_interface()
        
        if IS_HUGGINGFACE:
            # Calcular número ideal de workers baseado na GPU
            if is_gpu_available():
                gpu_mem = torch.cuda.get_device_properties(0).total_memory / (1024**3)  # em GB
                max_concurrent = 1  # Forçar single worker para Zero-GPU
                logger.info(f"GPU Memory: {gpu_mem:.1f}GB, Max Concurrent: {max_concurrent}")
            else:
                max_concurrent = 1
                logger.warning("GPU não disponível, usando configuração mínima")
            
            # Primeiro configurar a fila
            demo = demo.queue(
                api_open=False,
                status_update_rate="auto",
                max_size=5  # Reduzir tamanho da fila para economizar memória
            )
            # Depois fazer o launch
            demo.launch(
                server_name="0.0.0.0",
                server_port=7860,
                share=False,
                max_threads=2  # Reduzir número de threads
            )
        else:
            # Ambiente local - apenas launch direto
            demo.launch(
                server_name="0.0.0.0",
                server_port=7860,
                share=True
            )
            
    except Exception as e:
        logger.error(f"Erro ao iniciar aplicação: {str(e)}")
        raise

if __name__ == "__main__":
    main()