Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
1429e38
1
Parent(s):
1ccfc24
feat: atualização do detector com otimizações para GPU T4
Browse files- README.md +101 -56
- docs/api/interface.md +167 -0
- docs/architecture/overview.md +94 -0
- docs/development/contributing.md +228 -0
- docs/setup/installation.md +128 -0
- src/presentation/web/gradio_interface.py +2 -6
README.md
CHANGED
@@ -14,98 +14,143 @@ resources:
|
|
14 |
gpu: true
|
15 |
---
|
16 |
|
17 |
-
#
|
18 |
|
19 |
-
|
20 |
|
21 |
-
|
|
|
22 |
|
23 |
-
|
24 |
-
- pip (gerenciador de pacotes Python)
|
25 |
-
- Ambiente virtual Python (recomendado)
|
26 |
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
1. Clone o repositório:
|
30 |
```bash
|
31 |
-
git clone
|
32 |
-
cd
|
33 |
```
|
34 |
|
35 |
-
2.
|
36 |
```bash
|
37 |
-
|
38 |
-
source .venv/bin/activate # Linux/Mac
|
39 |
-
# OU
|
40 |
-
.venv\Scripts\activate # Windows
|
41 |
```
|
42 |
|
43 |
-
3.
|
44 |
```bash
|
45 |
-
|
46 |
```
|
47 |
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
```
|
51 |
-
|
|
|
|
|
|
|
|
|
52 |
```
|
53 |
|
54 |
-
|
55 |
|
56 |
-
|
57 |
|
58 |
-
|
59 |
```bash
|
60 |
-
|
61 |
```
|
62 |
|
63 |
-
|
|
|
|
|
|
|
64 |
|
65 |
-
|
66 |
|
67 |
-
|
68 |
-
- Detecção de objetos em tempo real
|
69 |
-
- Configuração de parâmetros de detecção
|
70 |
-
- Sistema de notificações
|
71 |
-
- Monitoramento de recursos do sistema
|
72 |
|
73 |
-
|
|
|
|
|
|
|
74 |
|
75 |
-
|
|
|
|
|
|
|
76 |
|
77 |
-
|
78 |
-
- `application/`: Casos de uso e interfaces
|
79 |
-
- `infrastructure/`: Implementações concretas
|
80 |
-
- `presentation/`: Interface com usuário (Gradio)
|
81 |
|
82 |
-
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
4. Push para a branch (`git push origin feature/AmazingFeature`)
|
88 |
-
5. Abra um Pull Request
|
89 |
|
90 |
-
|
|
|
|
|
|
|
91 |
|
92 |
-
|
93 |
-
- PyTorch com CUDA
|
94 |
-
- OWL-ViT
|
95 |
-
- Gradio
|
96 |
-
- FFmpeg
|
97 |
|
98 |
-
|
99 |
|
100 |
-
|
101 |
-
|
102 |
-
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
##
|
105 |
|
106 |
-
-
|
107 |
-
-
|
108 |
-
-
|
109 |
|
110 |
---
|
111 |
Desenvolvido com ❤️ para o Hackathon FIAP
|
|
|
14 |
gpu: true
|
15 |
---
|
16 |
|
17 |
+
# Detector de Riscos em Vídeo
|
18 |
|
19 |
+
Sistema de detecção de objetos de risco em vídeos usando OWL-ViT e processamento GPU/CPU otimizado.
|
20 |
|
21 |
+
[](https://huggingface.co/spaces/seu-usuario/seu-espaco)
|
22 |
+
[](https://github.com/seu-usuario/hackatoon-1iadt)
|
23 |
|
24 |
+
## 🚀 Funcionalidades
|
|
|
|
|
25 |
|
26 |
+
- Detecção de objetos de risco em vídeos
|
27 |
+
- Processamento otimizado em GPU (NVIDIA T4) e CPU
|
28 |
+
- Interface web intuitiva com Gradio
|
29 |
+
- API REST para integração
|
30 |
+
- Suporte a webhooks para notificações
|
31 |
+
- Métricas detalhadas de processamento
|
32 |
+
|
33 |
+
## 📋 Requisitos
|
34 |
+
|
35 |
+
- Python 3.10+
|
36 |
+
- CUDA 11.8+ (para GPU)
|
37 |
+
- NVIDIA T4 16GB ou superior (recomendado)
|
38 |
+
- 16GB RAM mínimo
|
39 |
+
|
40 |
+
## 🔧 Instalação
|
41 |
|
42 |
1. Clone o repositório:
|
43 |
```bash
|
44 |
+
git clone https://github.com/seu-usuario/hackatoon-1iadt.git
|
45 |
+
cd hackatoon-1iadt
|
46 |
```
|
47 |
|
48 |
+
2. Instale as dependências:
|
49 |
```bash
|
50 |
+
pip install -r requirements.txt
|
|
|
|
|
|
|
51 |
```
|
52 |
|
53 |
+
3. Configure o ambiente:
|
54 |
```bash
|
55 |
+
cp .env.example .env
|
56 |
```
|
57 |
|
58 |
+
[Documentação completa de instalação](docs/setup/installation.md)
|
59 |
+
|
60 |
+
## 💻 Uso
|
61 |
+
|
62 |
+
1. Inicie a aplicação:
|
63 |
+
```bash
|
64 |
+
python app.py
|
65 |
+
```
|
66 |
+
|
67 |
+
2. Acesse: http://localhost:7860
|
68 |
+
|
69 |
+
3. Upload de vídeo:
|
70 |
+
- Arraste ou selecione um vídeo
|
71 |
+
- Ajuste as configurações
|
72 |
+
- Clique em "Detectar"
|
73 |
+
|
74 |
+
## 📚 Documentação
|
75 |
+
|
76 |
+
- [Arquitetura do Sistema](docs/architecture/overview.md)
|
77 |
+
- [Instalação e Configuração](docs/setup/installation.md)
|
78 |
+
- [API e Interface](docs/api/interface.md)
|
79 |
+
|
80 |
+
## 🏗️ Arquitetura
|
81 |
+
|
82 |
+
O projeto segue os princípios da Clean Architecture:
|
83 |
+
|
84 |
```
|
85 |
+
src/
|
86 |
+
├── domain/ # Regras de negócio
|
87 |
+
├── application/ # Casos de uso
|
88 |
+
├── infrastructure/ # Implementações
|
89 |
+
└── presentation/ # Interface
|
90 |
```
|
91 |
|
92 |
+
[Detalhes da arquitetura](docs/architecture/overview.md)
|
93 |
|
94 |
+
## 🚀 Deploy no Hugging Face
|
95 |
|
96 |
+
1. Configure as credenciais:
|
97 |
```bash
|
98 |
+
cp .env.example .env.huggingface
|
99 |
```
|
100 |
|
101 |
+
2. Execute o deploy:
|
102 |
+
```bash
|
103 |
+
./deploy.sh
|
104 |
+
```
|
105 |
|
106 |
+
[Instruções detalhadas de deploy](docs/setup/installation.md#deployment-no-hugging-face)
|
107 |
|
108 |
+
## 💪 Máquinas Recomendadas
|
|
|
|
|
|
|
|
|
109 |
|
110 |
+
### GPU
|
111 |
+
- NVIDIA T4 16GB (Hugging Face Pro)
|
112 |
+
- NVIDIA A100 (Performance máxima)
|
113 |
+
- NVIDIA V100 (Alternativa)
|
114 |
|
115 |
+
### CPU
|
116 |
+
- 8+ cores
|
117 |
+
- 32GB+ RAM
|
118 |
+
- SSD para armazenamento
|
119 |
|
120 |
+
## 🔍 Interface
|
|
|
|
|
|
|
121 |
|
122 |
+
### Componentes
|
123 |
+
- Upload de vídeo (MP4, AVI, MOV)
|
124 |
+
- Configurações de detecção
|
125 |
+
- Visualização de resultados
|
126 |
+
- Métricas em tempo real
|
127 |
|
128 |
+
[Documentação da interface](docs/api/interface.md)
|
129 |
+
|
130 |
+
## 🔗 Links
|
|
|
|
|
131 |
|
132 |
+
- [Hugging Face Space](https://huggingface.co/spaces/seu-usuario/seu-espaco)
|
133 |
+
- [GitHub Repository](https://github.com/seu-usuario/hackatoon-1iadt)
|
134 |
+
- [Documentação](docs/)
|
135 |
+
- [Issues](https://github.com/seu-usuario/hackatoon-1iadt/issues)
|
136 |
|
137 |
+
## 📄 Licença
|
|
|
|
|
|
|
|
|
138 |
|
139 |
+
Este projeto está licenciado sob a MIT License - veja o arquivo [LICENSE](LICENSE) para detalhes.
|
140 |
|
141 |
+
## 👥 Contribuição
|
142 |
+
|
143 |
+
1. Fork o projeto
|
144 |
+
2. Crie sua feature branch (`git checkout -b feature/AmazingFeature`)
|
145 |
+
3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`)
|
146 |
+
4. Push para a branch (`git push origin feature/AmazingFeature`)
|
147 |
+
5. Abra um Pull Request
|
148 |
|
149 |
+
## 📞 Suporte
|
150 |
|
151 |
+
- Abra uma [issue](https://github.com/seu-usuario/hackatoon-1iadt/issues)
|
152 |
+
- Consulte a [documentação](docs/)
|
153 |
+
- Entre em contato com a equipe
|
154 |
|
155 |
---
|
156 |
Desenvolvido com ❤️ para o Hackathon FIAP
|
docs/api/interface.md
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Interface e API
|
2 |
+
|
3 |
+
## Interface Web (Gradio)
|
4 |
+
|
5 |
+
### Componentes Principais
|
6 |
+
|
7 |
+
1. **Upload de Vídeo**
|
8 |
+
- Formatos suportados: MP4, AVI, MOV
|
9 |
+
- Tamanho máximo: 100MB
|
10 |
+
- Duração máxima: 5 minutos
|
11 |
+
|
12 |
+
2. **Configurações de Detecção**
|
13 |
+
- Limiar de confiança (0-100%)
|
14 |
+
- Modo de processamento (GPU/CPU)
|
15 |
+
- Tamanho do lote de frames
|
16 |
+
|
17 |
+
3. **Visualização de Resultados**
|
18 |
+
- Vídeo com anotações
|
19 |
+
- Timeline de detecções
|
20 |
+
- Métricas de processamento
|
21 |
+
|
22 |
+
### Exemplos de Uso
|
23 |
+
|
24 |
+
1. **Upload Simples**
|
25 |
+
```python
|
26 |
+
with gr.Blocks() as demo:
|
27 |
+
video_input = gr.Video()
|
28 |
+
detect_btn = gr.Button("Detectar")
|
29 |
+
output_display = gr.Video()
|
30 |
+
```
|
31 |
+
|
32 |
+
2. **Configurações Avançadas**
|
33 |
+
```python
|
34 |
+
with gr.Blocks() as demo:
|
35 |
+
with gr.Row():
|
36 |
+
confidence = gr.Slider(0, 100)
|
37 |
+
batch_size = gr.Number(value=4)
|
38 |
+
```
|
39 |
+
|
40 |
+
## API REST
|
41 |
+
|
42 |
+
### Endpoints
|
43 |
+
|
44 |
+
#### 1. Detecção em Vídeo
|
45 |
+
```http
|
46 |
+
POST /api/detect
|
47 |
+
Content-Type: multipart/form-data
|
48 |
+
|
49 |
+
{
|
50 |
+
"video": binary_data,
|
51 |
+
"confidence": 0.5,
|
52 |
+
"use_gpu": true
|
53 |
+
}
|
54 |
+
```
|
55 |
+
|
56 |
+
**Resposta:**
|
57 |
+
```json
|
58 |
+
{
|
59 |
+
"detections": [
|
60 |
+
{
|
61 |
+
"frame": 0,
|
62 |
+
"timestamp": "00:00:01",
|
63 |
+
"objects": [
|
64 |
+
{
|
65 |
+
"label": "arma",
|
66 |
+
"confidence": 95.5,
|
67 |
+
"bbox": [x1, y1, x2, y2]
|
68 |
+
}
|
69 |
+
]
|
70 |
+
}
|
71 |
+
],
|
72 |
+
"metrics": {
|
73 |
+
"frames_processed": 150,
|
74 |
+
"processing_time": 2.5,
|
75 |
+
"fps": 60
|
76 |
+
}
|
77 |
+
}
|
78 |
+
```
|
79 |
+
|
80 |
+
#### 2. Status do Serviço
|
81 |
+
```http
|
82 |
+
GET /api/status
|
83 |
+
|
84 |
+
Response:
|
85 |
+
{
|
86 |
+
"status": "online",
|
87 |
+
"gpu_available": true,
|
88 |
+
"memory_usage": "45%",
|
89 |
+
"queue_size": 2
|
90 |
+
}
|
91 |
+
```
|
92 |
+
|
93 |
+
### Códigos de Erro
|
94 |
+
|
95 |
+
- `400`: Parâmetros inválidos
|
96 |
+
- `413`: Vídeo muito grande
|
97 |
+
- `500`: Erro interno
|
98 |
+
- `503`: Serviço indisponível
|
99 |
+
|
100 |
+
### Rate Limiting
|
101 |
+
|
102 |
+
- 10 requisições/minuto por IP
|
103 |
+
- 100 requisições/hora por usuário
|
104 |
+
- Tamanho máximo do vídeo: 100MB
|
105 |
+
|
106 |
+
## Webhooks
|
107 |
+
|
108 |
+
### Configuração
|
109 |
+
```http
|
110 |
+
POST /api/webhooks/configure
|
111 |
+
{
|
112 |
+
"url": "https://seu-servidor.com/callback",
|
113 |
+
"events": ["detection", "error"],
|
114 |
+
"secret": "seu_secret"
|
115 |
+
}
|
116 |
+
```
|
117 |
+
|
118 |
+
### Formato do Callback
|
119 |
+
```json
|
120 |
+
{
|
121 |
+
"event": "detection",
|
122 |
+
"timestamp": "2024-03-20T15:30:00Z",
|
123 |
+
"data": {
|
124 |
+
"video_id": "abc123",
|
125 |
+
"detections": []
|
126 |
+
},
|
127 |
+
"signature": "hash_hmac"
|
128 |
+
}
|
129 |
+
```
|
130 |
+
|
131 |
+
## Integração com Outros Serviços
|
132 |
+
|
133 |
+
### 1. Hugging Face
|
134 |
+
```python
|
135 |
+
from huggingface_hub import HfApi
|
136 |
+
|
137 |
+
api = HfApi()
|
138 |
+
api.upload_file(
|
139 |
+
path_or_fileobj="./video.mp4",
|
140 |
+
path_in_repo="videos/test.mp4",
|
141 |
+
repo_id="seu-espaco"
|
142 |
+
)
|
143 |
+
```
|
144 |
+
|
145 |
+
### 2. Sistemas de Notificação
|
146 |
+
```python
|
147 |
+
def notify(detection):
|
148 |
+
requests.post(
|
149 |
+
"https://seu-servidor.com/notify",
|
150 |
+
json={"detection": detection}
|
151 |
+
)
|
152 |
+
```
|
153 |
+
|
154 |
+
## Considerações de Segurança
|
155 |
+
|
156 |
+
1. **Autenticação**
|
157 |
+
- Token JWT obrigatório
|
158 |
+
- Renovação automática
|
159 |
+
|
160 |
+
2. **Rate Limiting**
|
161 |
+
- Por IP e usuário
|
162 |
+
- Cooldown progressivo
|
163 |
+
|
164 |
+
3. **Validação de Entrada**
|
165 |
+
- Tamanho máximo
|
166 |
+
- Formatos permitidos
|
167 |
+
- Sanitização
|
docs/architecture/overview.md
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Arquitetura do Sistema
|
2 |
+
|
3 |
+
## Visão Geral
|
4 |
+
|
5 |
+
O sistema de detecção de riscos em vídeo é construído seguindo os princípios da Clean Architecture, garantindo separação de responsabilidades e facilitando a manutenção e evolução do código.
|
6 |
+
|
7 |
+
## Camadas da Arquitetura
|
8 |
+
|
9 |
+
### 1. Domain (Núcleo)
|
10 |
+
- Contém as regras de negócio e entidades fundamentais
|
11 |
+
- Independente de frameworks e bibliotecas externas
|
12 |
+
- Localização: `src/domain/`
|
13 |
+
|
14 |
+
#### Componentes Principais:
|
15 |
+
- `detectors/`: Implementações dos detectores (GPU/CPU)
|
16 |
+
- `entities/`: Objetos de domínio
|
17 |
+
- `factories/`: Fábricas para criação de objetos
|
18 |
+
- `interfaces/`: Contratos e interfaces
|
19 |
+
|
20 |
+
### 2. Application
|
21 |
+
- Implementa os casos de uso da aplicação
|
22 |
+
- Orquestra o fluxo de dados entre as camadas
|
23 |
+
- Localização: `src/application/`
|
24 |
+
|
25 |
+
#### Casos de Uso:
|
26 |
+
- `process_video`: Processamento e análise de vídeos
|
27 |
+
- Notificações de detecções
|
28 |
+
- Gerenciamento de cache
|
29 |
+
|
30 |
+
### 3. Infrastructure
|
31 |
+
- Implementações concretas de interfaces
|
32 |
+
- Integrações com serviços externos
|
33 |
+
- Localização: `src/infrastructure/`
|
34 |
+
|
35 |
+
#### Serviços:
|
36 |
+
- `WeaponDetectorService`: Serviço principal de detecção
|
37 |
+
- `NotificationService`: Serviço de notificações
|
38 |
+
- Gerenciamento de GPU/CPU
|
39 |
+
|
40 |
+
### 4. Presentation
|
41 |
+
- Interface com usuário via Gradio
|
42 |
+
- Localização: `src/presentation/`
|
43 |
+
|
44 |
+
#### Componentes:
|
45 |
+
- Interface web responsiva
|
46 |
+
- Configurações de processamento
|
47 |
+
- Visualização de resultados
|
48 |
+
|
49 |
+
## Fluxo de Dados
|
50 |
+
|
51 |
+
1. Upload do vídeo via interface Gradio
|
52 |
+
2. Processamento pelo caso de uso
|
53 |
+
3. Detecção de objetos usando GPU/CPU
|
54 |
+
4. Notificações (se configuradas)
|
55 |
+
5. Retorno dos resultados
|
56 |
+
|
57 |
+
## Otimizações
|
58 |
+
|
59 |
+
### GPU
|
60 |
+
- Detecção automática de hardware
|
61 |
+
- Configurações específicas para T4 e Zero-GPU
|
62 |
+
- Gerenciamento de memória otimizado
|
63 |
+
|
64 |
+
### CPU
|
65 |
+
- Fallback automático
|
66 |
+
- Otimizações para processamento em CPU
|
67 |
+
- Cache de resultados
|
68 |
+
|
69 |
+
## Diagrama de Componentes
|
70 |
+
|
71 |
+
```mermaid
|
72 |
+
graph TD
|
73 |
+
A[Interface Web] --> B[Casos de Uso]
|
74 |
+
B --> C[Detector Service]
|
75 |
+
C --> D[GPU Detector]
|
76 |
+
C --> E[CPU Detector]
|
77 |
+
B --> F[Notification Service]
|
78 |
+
D --> G[OWL-ViT Model]
|
79 |
+
E --> G
|
80 |
+
```
|
81 |
+
|
82 |
+
## Considerações de Design
|
83 |
+
|
84 |
+
1. **Inversão de Dependência**
|
85 |
+
- Interfaces abstratas no domínio
|
86 |
+
- Implementações concretas na infraestrutura
|
87 |
+
|
88 |
+
2. **Single Responsibility**
|
89 |
+
- Cada componente com responsabilidade única
|
90 |
+
- Separação clara de concerns
|
91 |
+
|
92 |
+
3. **Open/Closed**
|
93 |
+
- Extensível para novos detectores
|
94 |
+
- Fácil adição de novos serviços
|
docs/development/contributing.md
ADDED
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Guia de Desenvolvimento
|
2 |
+
|
3 |
+
## Ambiente de Desenvolvimento
|
4 |
+
|
5 |
+
### Setup Inicial
|
6 |
+
|
7 |
+
1. **IDE Recomendada**
|
8 |
+
- VSCode com extensões:
|
9 |
+
- Python
|
10 |
+
- Pylance
|
11 |
+
- GitLens
|
12 |
+
- Python Test Explorer
|
13 |
+
|
14 |
+
2. **Configuração do Git**
|
15 |
+
```bash
|
16 |
+
git config --global user.name "Seu Nome"
|
17 |
+
git config --global user.email "[email protected]"
|
18 |
+
```
|
19 |
+
|
20 |
+
3. **Pre-commit Hooks**
|
21 |
+
```bash
|
22 |
+
pip install pre-commit
|
23 |
+
pre-commit install
|
24 |
+
```
|
25 |
+
|
26 |
+
## Padrões de Código
|
27 |
+
|
28 |
+
### 1. Estilo
|
29 |
+
- PEP 8
|
30 |
+
- Máximo 88 caracteres por linha
|
31 |
+
- Docstrings em todas as funções/classes
|
32 |
+
- Type hints obrigatórios
|
33 |
+
|
34 |
+
Exemplo:
|
35 |
+
```python
|
36 |
+
def process_frame(
|
37 |
+
frame: np.ndarray,
|
38 |
+
confidence: float = 0.5
|
39 |
+
) -> List[Detection]:
|
40 |
+
"""Processa um frame para detecção de objetos.
|
41 |
+
|
42 |
+
Args:
|
43 |
+
frame: Array numpy do frame
|
44 |
+
confidence: Limiar de confiança
|
45 |
+
|
46 |
+
Returns:
|
47 |
+
Lista de detecções encontradas
|
48 |
+
"""
|
49 |
+
pass
|
50 |
+
```
|
51 |
+
|
52 |
+
### 2. Estrutura de Arquivos
|
53 |
+
```
|
54 |
+
src/
|
55 |
+
├── domain/
|
56 |
+
│ ├── entities/
|
57 |
+
│ │ └── detection.py
|
58 |
+
│ └── interfaces/
|
59 |
+
│ └── detector.py
|
60 |
+
├── application/
|
61 |
+
│ └── use_cases/
|
62 |
+
│ └── process_video.py
|
63 |
+
└── infrastructure/
|
64 |
+
└── services/
|
65 |
+
└── weapon_detector.py
|
66 |
+
```
|
67 |
+
|
68 |
+
### 3. Testes
|
69 |
+
- pytest para testes unitários
|
70 |
+
- pytest-cov para cobertura
|
71 |
+
- Mocking para dependências externas
|
72 |
+
|
73 |
+
Exemplo:
|
74 |
+
```python
|
75 |
+
def test_process_frame():
|
76 |
+
detector = WeaponDetector()
|
77 |
+
frame = np.zeros((640, 480, 3))
|
78 |
+
result = detector.process_frame(frame)
|
79 |
+
assert len(result) >= 0
|
80 |
+
```
|
81 |
+
|
82 |
+
## Fluxo de Trabalho
|
83 |
+
|
84 |
+
### 1. Branches
|
85 |
+
- `main`: Produção
|
86 |
+
- `develop`: Desenvolvimento
|
87 |
+
- `feature/*`: Novas funcionalidades
|
88 |
+
- `fix/*`: Correções
|
89 |
+
- `release/*`: Preparação de release
|
90 |
+
|
91 |
+
### 2. Commits
|
92 |
+
```
|
93 |
+
feat: Adiciona detecção em tempo real
|
94 |
+
^--^ ^------------------------^
|
95 |
+
| |
|
96 |
+
| +-> Descrição no presente
|
97 |
+
|
|
98 |
+
+-------> Tipo: feat, fix, docs, style, refactor
|
99 |
+
```
|
100 |
+
|
101 |
+
### 3. Pull Requests
|
102 |
+
- Template obrigatório
|
103 |
+
- Code review necessário
|
104 |
+
- CI deve passar
|
105 |
+
- Squash merge preferido
|
106 |
+
|
107 |
+
## CI/CD
|
108 |
+
|
109 |
+
### GitHub Actions
|
110 |
+
```yaml
|
111 |
+
name: CI
|
112 |
+
|
113 |
+
on:
|
114 |
+
push:
|
115 |
+
branches: [ main, develop ]
|
116 |
+
pull_request:
|
117 |
+
branches: [ main ]
|
118 |
+
|
119 |
+
jobs:
|
120 |
+
test:
|
121 |
+
runs-on: ubuntu-latest
|
122 |
+
steps:
|
123 |
+
- uses: actions/checkout@v2
|
124 |
+
- name: Set up Python
|
125 |
+
uses: actions/setup-python@v2
|
126 |
+
- name: Run tests
|
127 |
+
run: |
|
128 |
+
pip install -r requirements.txt
|
129 |
+
pytest
|
130 |
+
```
|
131 |
+
|
132 |
+
### Deploy
|
133 |
+
1. Staging
|
134 |
+
```bash
|
135 |
+
./deploy.sh staging
|
136 |
+
```
|
137 |
+
|
138 |
+
2. Produção
|
139 |
+
```bash
|
140 |
+
./deploy.sh production
|
141 |
+
```
|
142 |
+
|
143 |
+
## Debugging
|
144 |
+
|
145 |
+
### 1. Logs
|
146 |
+
```python
|
147 |
+
import logging
|
148 |
+
|
149 |
+
logger = logging.getLogger(__name__)
|
150 |
+
logger.info("Processando frame %d", frame_number)
|
151 |
+
```
|
152 |
+
|
153 |
+
### 2. Profiling
|
154 |
+
```python
|
155 |
+
import cProfile
|
156 |
+
|
157 |
+
def profile_detection():
|
158 |
+
profiler = cProfile.Profile()
|
159 |
+
profiler.enable()
|
160 |
+
# código
|
161 |
+
profiler.disable()
|
162 |
+
profiler.print_stats()
|
163 |
+
```
|
164 |
+
|
165 |
+
### 3. GPU Monitoring
|
166 |
+
```python
|
167 |
+
import torch
|
168 |
+
|
169 |
+
def check_gpu():
|
170 |
+
print(torch.cuda.memory_summary())
|
171 |
+
```
|
172 |
+
|
173 |
+
## Otimizações
|
174 |
+
|
175 |
+
### 1. GPU
|
176 |
+
- Batch processing
|
177 |
+
- Memória pinned
|
178 |
+
- Async data loading
|
179 |
+
|
180 |
+
### 2. CPU
|
181 |
+
- Multiprocessing
|
182 |
+
- NumPy vectorization
|
183 |
+
- Cache de resultados
|
184 |
+
|
185 |
+
## Segurança
|
186 |
+
|
187 |
+
### 1. Dependências
|
188 |
+
- Safety check
|
189 |
+
- Dependabot
|
190 |
+
- SAST scanning
|
191 |
+
|
192 |
+
### 2. Código
|
193 |
+
- Input validation
|
194 |
+
- Error handling
|
195 |
+
- Secrets management
|
196 |
+
|
197 |
+
## Documentação
|
198 |
+
|
199 |
+
### 1. Docstrings
|
200 |
+
```python
|
201 |
+
def detect_objects(
|
202 |
+
self,
|
203 |
+
frame: np.ndarray
|
204 |
+
) -> List[Detection]:
|
205 |
+
"""Detecta objetos em um frame.
|
206 |
+
|
207 |
+
Args:
|
208 |
+
frame: Frame no formato BGR
|
209 |
+
|
210 |
+
Returns:
|
211 |
+
Lista de detecções
|
212 |
+
|
213 |
+
Raises:
|
214 |
+
ValueError: Se o frame for inválido
|
215 |
+
"""
|
216 |
+
pass
|
217 |
+
```
|
218 |
+
|
219 |
+
### 2. Sphinx
|
220 |
+
```bash
|
221 |
+
cd docs
|
222 |
+
make html
|
223 |
+
```
|
224 |
+
|
225 |
+
### 3. README
|
226 |
+
- Badges atualizados
|
227 |
+
- Exemplos práticos
|
228 |
+
- Troubleshooting comum
|
docs/setup/installation.md
ADDED
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Instalação e Configuração
|
2 |
+
|
3 |
+
## Requisitos do Sistema
|
4 |
+
|
5 |
+
### Hardware Recomendado
|
6 |
+
- **GPU**: NVIDIA T4 16GB ou superior
|
7 |
+
- **CPU**: 4+ cores
|
8 |
+
- **RAM**: 16GB mínimo
|
9 |
+
- **Armazenamento**: 10GB+ disponível
|
10 |
+
|
11 |
+
### Software Necessário
|
12 |
+
- Python 3.10+
|
13 |
+
- CUDA 11.8+ (para GPU)
|
14 |
+
- Git
|
15 |
+
|
16 |
+
## Instalação Local
|
17 |
+
|
18 |
+
1. Clone o repositório:
|
19 |
+
```bash
|
20 |
+
git clone https://github.com/seu-usuario/hackatoon-1iadt.git
|
21 |
+
cd hackatoon-1iadt
|
22 |
+
```
|
23 |
+
|
24 |
+
2. Crie e ative um ambiente virtual:
|
25 |
+
```bash
|
26 |
+
python -m venv venv
|
27 |
+
source venv/bin/activate # Linux/Mac
|
28 |
+
.\venv\Scripts\activate # Windows
|
29 |
+
```
|
30 |
+
|
31 |
+
3. Instale as dependências:
|
32 |
+
```bash
|
33 |
+
pip install -r requirements.txt
|
34 |
+
```
|
35 |
+
|
36 |
+
4. Configure as variáveis de ambiente:
|
37 |
+
```bash
|
38 |
+
cp .env.example .env
|
39 |
+
```
|
40 |
+
|
41 |
+
Edite o arquivo `.env` com suas configurações:
|
42 |
+
```
|
43 |
+
HUGGINGFACE_TOKEN=seu_token
|
44 |
+
GPU_MEMORY_FRACTION=0.9
|
45 |
+
MAX_CONCURRENT_REQUESTS=2
|
46 |
+
```
|
47 |
+
|
48 |
+
## Configuração do Ambiente
|
49 |
+
|
50 |
+
### GPU (NVIDIA)
|
51 |
+
|
52 |
+
1. Verifique a instalação do CUDA:
|
53 |
+
```bash
|
54 |
+
nvidia-smi
|
55 |
+
```
|
56 |
+
|
57 |
+
2. Ajuste as configurações de GPU em `.env`:
|
58 |
+
```
|
59 |
+
USE_GPU=true
|
60 |
+
GPU_DEVICE=0
|
61 |
+
```
|
62 |
+
|
63 |
+
### CPU
|
64 |
+
|
65 |
+
Para usar apenas CPU:
|
66 |
+
```
|
67 |
+
USE_GPU=false
|
68 |
+
```
|
69 |
+
|
70 |
+
## Deployment no Hugging Face
|
71 |
+
|
72 |
+
1. Configure as variáveis de ambiente do Hugging Face:
|
73 |
+
```bash
|
74 |
+
cp .env.example .env.huggingface
|
75 |
+
```
|
76 |
+
|
77 |
+
2. Edite `.env.huggingface`:
|
78 |
+
```
|
79 |
+
HF_SPACE_ID=seu-espaco
|
80 |
+
HF_TOKEN=seu_token
|
81 |
+
```
|
82 |
+
|
83 |
+
3. Execute o deploy:
|
84 |
+
```bash
|
85 |
+
./deploy.sh
|
86 |
+
```
|
87 |
+
|
88 |
+
## Verificação da Instalação
|
89 |
+
|
90 |
+
1. Execute os testes:
|
91 |
+
```bash
|
92 |
+
pytest
|
93 |
+
```
|
94 |
+
|
95 |
+
2. Inicie a aplicação:
|
96 |
+
```bash
|
97 |
+
python app.py
|
98 |
+
```
|
99 |
+
|
100 |
+
3. Acesse: http://localhost:7860
|
101 |
+
|
102 |
+
## Troubleshooting
|
103 |
+
|
104 |
+
### Problemas Comuns
|
105 |
+
|
106 |
+
1. **Erro CUDA**
|
107 |
+
- Verifique a instalação do CUDA
|
108 |
+
- Confirme compatibilidade de versões
|
109 |
+
|
110 |
+
2. **Memória Insuficiente**
|
111 |
+
- Ajuste `GPU_MEMORY_FRACTION`
|
112 |
+
- Reduza `MAX_CONCURRENT_REQUESTS`
|
113 |
+
|
114 |
+
3. **Falha no Deploy**
|
115 |
+
- Verifique credenciais do Hugging Face
|
116 |
+
- Confirme permissões do espaço
|
117 |
+
|
118 |
+
### Logs
|
119 |
+
|
120 |
+
- Logs da aplicação: `logs/app.log`
|
121 |
+
- Logs do GPU: `logs/gpu.log`
|
122 |
+
|
123 |
+
## Suporte
|
124 |
+
|
125 |
+
Para problemas e dúvidas:
|
126 |
+
1. Abra uma issue no GitHub
|
127 |
+
2. Consulte a documentação completa
|
128 |
+
3. Entre em contato com a equipe de suporte
|
src/presentation/web/gradio_interface.py
CHANGED
@@ -239,16 +239,12 @@ class GradioInterface:
|
|
239 |
format="mp4",
|
240 |
height=150,
|
241 |
interactive=True,
|
242 |
-
show_label=True)
|
243 |
-
fn=self.load_sample_video,
|
244 |
-
inputs=[gr.State(video['path'])],
|
245 |
-
outputs=[input_video]
|
246 |
-
)
|
247 |
|
248 |
with gr.Column(scale=1, min_width=100):
|
249 |
gr.Button(
|
250 |
"📥 Carregar",
|
251 |
-
size="
|
252 |
).click(
|
253 |
fn=self.load_sample_video,
|
254 |
inputs=[gr.State(video['path'])],
|
|
|
239 |
format="mp4",
|
240 |
height=150,
|
241 |
interactive=True,
|
242 |
+
show_label=True)
|
|
|
|
|
|
|
|
|
243 |
|
244 |
with gr.Column(scale=1, min_width=100):
|
245 |
gr.Button(
|
246 |
"📥 Carregar",
|
247 |
+
size="md"
|
248 |
).click(
|
249 |
fn=self.load_sample_video,
|
250 |
inputs=[gr.State(video['path'])],
|