fix problem from claude

This commit is contained in:
SlimusMinus
2026-10-20 00:37:43 +03:00
parent f01f776d32
commit 28d91ce6d4
31 changed files with 994 additions and 284 deletions

View File

@@ -2,8 +2,23 @@ import torch
from PIL import Image
from transformers import Owlv2ForObjectDetection, Owlv2Processor
from app.config.logging import logger
from app.config.settings import settings
from app.ml.image.weapon_prediction_result import WeaponPredictionResult
from app.ml.model_manager import model_manager
def owlv2_target_size(width: int, height: int) -> tuple[int, int]:
"""
Размер для пересчёта боксов OWLv2 в пиксели.
OWLv2 дополняет картинку до квадрата, и координаты боксов относительны
этого квадрата. Масштабирование на (height, width) сжимает боксы по
короткой стороне — площадь занижается, и реальное оружие на вытянутом фото
отсекается фильтром WEAPON_MIN_AREA_FRACTION.
"""
side = max(width, height)
return side, side
class WeaponDetector:
@@ -27,42 +42,42 @@ class WeaponDetector:
]
def __init__(self):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Loading OWLv2 weapon detector on {self.device}")
self.device = model_manager.get_device()
logger.info("Loading OWLv2 weapon detector on %s", self.device)
self.model = Owlv2ForObjectDetection.from_pretrained(
settings.WEAPON_MODEL
)
self.processor = Owlv2Processor.from_pretrained(
settings.WEAPON_MODEL
)
self.model = Owlv2ForObjectDetection.from_pretrained(settings.WEAPON_MODEL)
self.processor = Owlv2Processor.from_pretrained(settings.WEAPON_MODEL)
self.model.to(self.device)
self.model.eval()
# Запросы постоянные — токенизируем один раз (и не трогаем
# непотокобезопасный токенизатор из параллельных запросов).
self.text_inputs = {
key: value.to(self.device)
for key, value in self.processor(
text=self.QUERIES,
return_tensors="pt"
).items()
}
def predict(
self,
image: Image.Image
) -> WeaponPredictionResult:
inputs = self.processor(
text=self.QUERIES,
pixel_values = self.processor(
images=image,
return_tensors="pt"
)
)["pixel_values"].to(self.device)
inputs = {
key: value.to(self.device)
for key, value in inputs.items()
}
with torch.inference_mode():
outputs = self.model(pixel_values=pixel_values, **self.text_inputs)
with torch.no_grad():
outputs = self.model(**inputs)
target_sizes = torch.tensor([image.size[::-1]])
target_sizes = torch.tensor([owlv2_target_size(image.width, image.height)])
results = self.processor.post_process_grounded_object_detection(
outputs,
threshold=0.0,
threshold=settings.WEAPON_THRESHOLD,
target_sizes=target_sizes
)[0]
@@ -74,7 +89,10 @@ class WeaponDetector:
label_scores = {}
for score, label_index, box in zip(scores, labels, boxes):
box_area = (box[2] - box[0]) * (box[3] - box[1])
# Бокс может частично лежать в паддинге — обрезаем по самой картинке
x0, y0 = max(box[0], 0.0), max(box[1], 0.0)
x1, y1 = min(box[2], image.width), min(box[3], image.height)
box_area = max(x1 - x0, 0.0) * max(y1 - y0, 0.0)
if box_area < image_area * settings.WEAPON_MIN_AREA_FRACTION:
continue
@@ -97,13 +115,11 @@ class WeaponDetector:
key=label_scores.get
)
print("====================")
print("WEAPON RESULT")
print("Scores:", label_scores)
logger.debug("Weapon detector scores: %s", label_scores)
return WeaponPredictionResult(
label=best_label,
score=label_scores[best_label],
detected_labels=sorted(label_scores.keys()),
box_count=len(label_scores)
)
)