Files
post-moderation/ai-moderation/tests/test_image_service.py
2026-10-23 00:12:34 +03:00

73 lines
2.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from PIL import Image
from app.ml.image.clip_prediction_result import ClipPredictionResult
from app.ml.image.image_prediction_result import ImagePredictionResult
from app.ml.image.weapon_detector import owlv2_target_size
from app.ml.image.weapon_prediction_result import WeaponPredictionResult
from app.moderation.image.validator import ImageValidator
from app.services.image_moderation_service import ImageModerationService
class Stub:
def __init__(self, result):
self.result = result
self.calls = 0
def predict(self, image):
self.calls += 1
return self.result
def make_service(nsfw=("normal", 0.99), weapon=None, clip_labels=()):
nsfw_stub = Stub(ImagePredictionResult(label=nsfw[0], score=nsfw[1], approved=False))
weapon_stub = Stub(weapon or WeaponPredictionResult(label="normal", score=0.0))
clip_stub = Stub(ClipPredictionResult(
label=clip_labels[0] if clip_labels else "a normal photo",
score=0.9,
detected_labels=list(clip_labels),
scores={}
))
service = ImageModerationService(
classifier=nsfw_stub,
validator=ImageValidator(),
clip_classifier=clip_stub,
weapon_detector=weapon_stub
)
return service, nsfw_stub, weapon_stub, clip_stub
IMAGE = Image.new("RGB", (300, 200))
def test_clean_image_is_approved():
service, *_ = make_service()
result = service.moderate(IMAGE)
assert (result.approved, result.reason, result.label) == (True, "OK", "normal")
def test_nsfw_short_circuits_other_models():
service, _, weapon, clip = make_service(nsfw=("nsfw", 0.95))
result = service.moderate(IMAGE)
assert (result.approved, result.reason, result.detected_labels) == (False, "NSFW", ["nsfw"])
assert weapon.calls == 0 and clip.calls == 0
def test_weapon_is_forbidden():
weapon = WeaponPredictionResult(label="a gun", score=0.7, detected_labels=["a gun"], box_count=1)
service, *_ , clip = make_service(weapon=weapon)
result = service.moderate(IMAGE)
assert (result.approved, result.reason, result.detected_labels) == (False, "FORBIDDEN_CONTENT", ["a gun"])
assert clip.calls == 0
def test_clip_forbidden_label():
service, *_ = make_service(clip_labels=["a photo containing drugs"])
result = service.moderate(IMAGE)
assert (result.approved, result.reason) == (False, "FORBIDDEN_CONTENT")
def test_owlv2_boxes_scaled_to_padded_square():
# OWLv2 паддит до квадрата: обе оси масштабируются по длинной стороне
assert owlv2_target_size(1280, 720) == (1280, 1280)
assert owlv2_target_size(600, 900) == (900, 900)