Spaces:
Runtime error
Runtime error
Marcus Vinicius Zerbini Canhaço
commited on
Commit
·
62fec37
1
Parent(s):
810f531
feat: atualização do detector com otimizações para GPU T4
Browse files- src/domain/detectors/gpu.py +13 -11
src/domain/detectors/gpu.py
CHANGED
@@ -6,6 +6,7 @@ import gc
|
|
6 |
import numpy as np
|
7 |
import cv2
|
8 |
from PIL import Image
|
|
|
9 |
from transformers import Owlv2Processor, Owlv2ForObjectDetection
|
10 |
from .base import BaseDetector
|
11 |
|
@@ -29,7 +30,7 @@ class WeaponDetectorGPU(BaseDetector):
|
|
29 |
raise RuntimeError("CUDA não está disponível!")
|
30 |
|
31 |
# Configurar device corretamente
|
32 |
-
self.device = 0 # Usar
|
33 |
|
34 |
# Carregar modelo e processador
|
35 |
logger.info("Carregando modelo e processador...")
|
@@ -39,7 +40,7 @@ class WeaponDetectorGPU(BaseDetector):
|
|
39 |
self.owlv2_model = Owlv2ForObjectDetection.from_pretrained(
|
40 |
model_name,
|
41 |
torch_dtype=torch.float16,
|
42 |
-
device_map={"":
|
43 |
)
|
44 |
|
45 |
# Otimizar modelo
|
@@ -64,12 +65,11 @@ class WeaponDetectorGPU(BaseDetector):
|
|
64 |
logger.error(f"Erro na inicialização GPU: {str(e)}")
|
65 |
raise
|
66 |
|
67 |
-
def detect_objects(self, image: Image.Image, threshold: float = 0.3) ->
|
68 |
"""Detecta objetos em uma imagem."""
|
69 |
try:
|
70 |
# Pré-processar imagem
|
71 |
-
|
72 |
-
image = image.convert('RGB')
|
73 |
|
74 |
# Processar imagem
|
75 |
image_inputs = self.owlv2_processor(
|
@@ -116,16 +116,18 @@ class WeaponDetectorGPU(BaseDetector):
|
|
116 |
logger.error(f"Erro em detect_objects: {str(e)}")
|
117 |
return []
|
118 |
|
119 |
-
def _get_best_device(self):
|
120 |
"""Retorna o melhor dispositivo disponível."""
|
121 |
-
|
|
|
|
|
122 |
|
123 |
def _clear_gpu_memory(self):
|
124 |
"""Limpa memória GPU."""
|
125 |
torch.cuda.empty_cache()
|
126 |
gc.collect()
|
127 |
|
128 |
-
def process_video(self, video_path: str, fps: int = None, threshold: float = 0.3, resolution: int = 640) ->
|
129 |
"""Processa um vídeo."""
|
130 |
metrics = {
|
131 |
"total_time": 0,
|
@@ -182,16 +184,16 @@ class WeaponDetectorGPU(BaseDetector):
|
|
182 |
logger.error(f"Erro no pré-processamento: {str(e)}")
|
183 |
return image
|
184 |
|
185 |
-
def _apply_nms(self, detections:
|
186 |
"""Aplica Non-Maximum Suppression nas detecções."""
|
187 |
try:
|
188 |
if not detections or len(detections) <= 1:
|
189 |
return detections
|
190 |
|
191 |
# Extrair scores e boxes
|
192 |
-
scores = torch.tensor([d["confidence"] for d in detections])
|
193 |
boxes = torch.tensor([[d["box"][0], d["box"][1], d["box"][2], d["box"][3]]
|
194 |
-
for d in detections])
|
195 |
|
196 |
# Ordenar por score
|
197 |
_, order = scores.sort(descending=True)
|
|
|
6 |
import numpy as np
|
7 |
import cv2
|
8 |
from PIL import Image
|
9 |
+
from typing import List, Dict, Any, Tuple
|
10 |
from transformers import Owlv2Processor, Owlv2ForObjectDetection
|
11 |
from .base import BaseDetector
|
12 |
|
|
|
30 |
raise RuntimeError("CUDA não está disponível!")
|
31 |
|
32 |
# Configurar device corretamente
|
33 |
+
self.device = torch.device("cuda:0") # Usar device CUDA
|
34 |
|
35 |
# Carregar modelo e processador
|
36 |
logger.info("Carregando modelo e processador...")
|
|
|
40 |
self.owlv2_model = Owlv2ForObjectDetection.from_pretrained(
|
41 |
model_name,
|
42 |
torch_dtype=torch.float16,
|
43 |
+
device_map={"": 0} # Mapear todo o modelo para GPU 0
|
44 |
)
|
45 |
|
46 |
# Otimizar modelo
|
|
|
65 |
logger.error(f"Erro na inicialização GPU: {str(e)}")
|
66 |
raise
|
67 |
|
68 |
+
def detect_objects(self, image: Image.Image, threshold: float = 0.3) -> List[Dict]:
|
69 |
"""Detecta objetos em uma imagem."""
|
70 |
try:
|
71 |
# Pré-processar imagem
|
72 |
+
image = self._preprocess_image(image)
|
|
|
73 |
|
74 |
# Processar imagem
|
75 |
image_inputs = self.owlv2_processor(
|
|
|
116 |
logger.error(f"Erro em detect_objects: {str(e)}")
|
117 |
return []
|
118 |
|
119 |
+
def _get_best_device(self) -> torch.device:
|
120 |
"""Retorna o melhor dispositivo disponível."""
|
121 |
+
if torch.cuda.is_available():
|
122 |
+
return torch.device("cuda:0")
|
123 |
+
return torch.device("cpu")
|
124 |
|
125 |
def _clear_gpu_memory(self):
|
126 |
"""Limpa memória GPU."""
|
127 |
torch.cuda.empty_cache()
|
128 |
gc.collect()
|
129 |
|
130 |
+
def process_video(self, video_path: str, fps: int = None, threshold: float = 0.3, resolution: int = 640) -> Tuple[str, Dict]:
|
131 |
"""Processa um vídeo."""
|
132 |
metrics = {
|
133 |
"total_time": 0,
|
|
|
184 |
logger.error(f"Erro no pré-processamento: {str(e)}")
|
185 |
return image
|
186 |
|
187 |
+
def _apply_nms(self, detections: List[Dict], iou_threshold: float = 0.5) -> List[Dict]:
|
188 |
"""Aplica Non-Maximum Suppression nas detecções."""
|
189 |
try:
|
190 |
if not detections or len(detections) <= 1:
|
191 |
return detections
|
192 |
|
193 |
# Extrair scores e boxes
|
194 |
+
scores = torch.tensor([d["confidence"] for d in detections], device=self.device)
|
195 |
boxes = torch.tensor([[d["box"][0], d["box"][1], d["box"][2], d["box"][3]]
|
196 |
+
for d in detections], device=self.device)
|
197 |
|
198 |
# Ordenar por score
|
199 |
_, order = scores.sort(descending=True)
|