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,21 +2,25 @@ import torch
from PIL import Image
from transformers import CLIPProcessor, CLIPModel
from app.config.logging import logger
from app.config.settings import settings
from app.ml.image.clip_prediction_result import ClipPredictionResult
from app.ml.model_manager import model_manager
class ClipClassifier:
NORMAL_LABEL = "a normal photo"
LABELS = [
"a normal photo",
NORMAL_LABEL,
"a photo containing marijuana",
"a photo containing drugs",
"a photo containing violence"
]
def __init__(self):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Loading CLIP on {self.device}")
self.device = model_manager.get_device()
logger.info("Loading CLIP on %s", self.device)
self.model = CLIPModel.from_pretrained(settings.IMAGE_CLIP_MODEL)
self.processor = CLIPProcessor.from_pretrained(settings.IMAGE_CLIP_MODEL)
@@ -24,19 +28,26 @@ class ClipClassifier:
self.model.to(self.device)
self.model.eval()
def predict(self, image: Image.Image) -> ClipPredictionResult:
inputs = self.processor(
text=self.LABELS,
images=image,
return_tensors="pt",
padding=True
)
inputs = {k: v.to(self.device) for k, v in inputs.items()}
# Метки постоянные — токенизируем один раз. Заодно запросы не трогают
# общий токенизатор, который не потокобезопасен.
self.text_inputs = {
key: value.to(self.device)
for key, value in self.processor(
text=self.LABELS,
padding=True,
return_tensors="pt"
).items()
}
with torch.no_grad():
outputs = self.model(**inputs)
logits = outputs.logits_per_image
probs = logits.softmax(dim=1)[0]
def predict(self, image: Image.Image) -> ClipPredictionResult:
pixel_values = self.processor(
images=image,
return_tensors="pt"
)["pixel_values"].to(self.device)
with torch.inference_mode():
outputs = self.model(pixel_values=pixel_values, **self.text_inputs)
probs = outputs.logits_per_image.softmax(dim=1)[0]
scores = {}
detected_labels = []
@@ -46,14 +57,16 @@ class ClipClassifier:
score = float(probability)
scores[label] = score
if label != "a normal photo" and score >= settings.CLIP_THRESHOLD:
if label != self.NORMAL_LABEL and score >= settings.CLIP_THRESHOLD:
detected_labels.append(label)
max_index = torch.argmax(probs).item()
max_index = int(torch.argmax(probs).item())
logger.debug("CLIP scores: %s", scores)
return ClipPredictionResult(
label=self.LABELS[max_index],
score=float(probs[max_index]),
detected_labels=detected_labels,
scores=scores
)
)

View File

@@ -1,6 +1,7 @@
import torch
from PIL import Image
from app.config.logging import logger
from app.ml.image.image_prediction_result import ImagePredictionResult
from app.ml.model_manager import model_manager
@@ -11,11 +12,9 @@ class ImageClassifier:
self,
image: Image.Image
) -> ImagePredictionResult:
inputs = (
model_manager.image_processor(
image,
return_tensors="pt"
)
inputs = model_manager.image_processor(
image,
return_tensors="pt"
)
inputs = {
@@ -23,10 +22,8 @@ class ImageClassifier:
for key, value in inputs.items()
}
with torch.no_grad():
outputs = (
model_manager.image_model(**inputs)
)
with torch.inference_mode():
outputs = model_manager.image_model(**inputs)
probabilities = torch.softmax(
outputs.logits,
@@ -35,35 +32,20 @@ class ImageClassifier:
raw_scores = probabilities[0].tolist()
predicted_index = (
torch.argmax(probabilities, dim=1)
.item()
)
predicted_index = int(torch.argmax(probabilities, dim=1).item())
labels = (
model_manager.image_model
.config
.id2label
)
label = labels[predicted_index]
label = model_manager.image_model.config.id2label[predicted_index]
score = raw_scores[predicted_index]
print("====================")
print("IMAGE RESULT")
print("Labels:", labels)
print("Label:", label)
print("Score:", score)
print("Scores:", raw_scores)
logger.debug(
"NSFW model: label=%s, score=%.4f, scores=%s",
label, score, raw_scores
)
return ImagePredictionResult(
label=label,
score=score,
approved=False,
raw_scores=raw_scores
)

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)
)
)