Merge pull request #55 from SlimusMinus/fix/ai-moderation-mapping
All checks were successful
deploy-backend / deploy (push) Successful in 1m29s

fix AI moderation response mapping and long post text
This commit is contained in:
SlimusMinus
2026-10-20 00:35:17 +03:00
committed by GitHub
7 changed files with 310 additions and 7 deletions

View File

@@ -25,4 +25,11 @@ public class AiProperties {
* обрабатывает заметно дольше текста, особенно первую после простоя.
*/
private int imageTimeout = 30;
/**
* Максимальная длина текста в одном запросе к AI-сервису (TEXT_MAX_LENGTH
* на его стороне). Более длинный текст отправляется частями — иначе сервис
* отвечает 422, и пост ошибочно отклоняется.
*/
private int textMaxLength = 5000;
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Data;
@@ -11,5 +12,7 @@ public class ImageModerationResponse {
private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels;
}

View File

@@ -1,5 +1,6 @@
package com.krylov.refound.ai.dto;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import lombok.Builder;
import lombok.Data;
@@ -14,6 +15,8 @@ public class ModerationResponse {
private String reason;
// AI-сервис (Python) отдаёт поля в snake_case
@JsonProperty("detected_labels")
private List<String> detectedLabels;
}

View File

@@ -1,8 +1,11 @@
package com.krylov.refound.ai.pipeline;
import com.krylov.refound.ai.client.TextModerationClient;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.exception.ContentBlockedException;
import java.util.ArrayList;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
@@ -14,7 +17,13 @@ import org.springframework.stereotype.Component;
@Order(10)
public class TextModerationProcessor implements ModerationProcessor {
/**
* Перекрытие соседних частей: фраза на стыке целиком попадает хотя бы в одну.
*/
static final int CHUNK_OVERLAP = 200;
private final TextModerationClient client;
private final AiProperties properties;
@Override
public Boolean process(ModerationContext context) {
@@ -24,7 +33,23 @@ public class TextModerationProcessor implements ModerationProcessor {
context.getDescription()
);
ModerationResponse response = client.moderate(text);
// Пустой текст AI-сервис отклоняет как невалидный запрос (400/422) —
// проверять нечего, это не повод отклонять пост
if (text.isBlank()) {
log.info("Текст поста пустой, пропускаем модерацию текста");
return Boolean.TRUE;
}
List<String> chunks = splitText(text, properties.getTextMaxLength(), CHUNK_OVERLAP);
if (chunks.size() > 1) {
log.info("Текст длиной {} отправляется на модерацию частями: {}", text.length(), chunks.size());
}
for (String chunk : chunks) {
if (chunk.isBlank()) {
continue;
}
ModerationResponse response = client.moderate(chunk);
if (response == null) {
log.warn("AI TextModeration вернул null, пропускаем модерацию текста");
return null;
@@ -35,10 +60,49 @@ public class TextModerationProcessor implements ModerationProcessor {
if (!Boolean.TRUE.equals(response.getApproved())) {
throw new ContentBlockedException(response.getReason(), response.getDetectedLabels());
}
}
return Boolean.TRUE;
}
/**
* Режет текст на части не длиннее maxLength с перекрытием overlap.
* Граница по возможности ставится на пробел, чтобы не разрезать слово.
*/
static List<String> splitText(String text, int maxLength, int overlap) {
if (text.length() <= maxLength) {
return List.of(text);
}
int safeOverlap = Math.min(overlap, maxLength / 4);
List<String> chunks = new ArrayList<>();
int start = 0;
while (start < text.length()) {
int end = Math.min(start + maxLength, text.length());
if (end < text.length()) {
int space = lastWhitespace(text, start + maxLength / 2, end);
if (space > 0) {
end = space;
}
}
chunks.add(text.substring(start, end));
if (end == text.length()) {
break;
}
start = Math.max(end - safeOverlap, start + 1);
}
return chunks;
}
private static int lastWhitespace(String text, int from, int to) {
for (int i = to - 1; i >= from; i--) {
if (Character.isWhitespace(text.charAt(i))) {
return i;
}
}
return -1;
}
private String buildText(String title, String description) {
StringBuilder builder = new StringBuilder();

View File

@@ -50,6 +50,8 @@ ai:
url: ${AI_SERVICE_URL:http://localhost:8000}
timeout: 10
image-timeout: ${AI_IMAGE_TIMEOUT:30}
# Должно совпадать с TEXT_MAX_LENGTH AI-сервиса; длиннее — отправляется частями
text-max-length: ${AI_TEXT_MAX_LENGTH:5000}
retry:
max-attempts: 3
delay: 500

View File

@@ -0,0 +1,102 @@
package com.krylov.refound.ai.client;
import static org.assertj.core.api.Assertions.assertThat;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.config.WebClientConfig;
import com.krylov.refound.ai.dto.ImageModerationResponse;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.dto.TextModerationRequest;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
/**
* Ответы AI-сервиса (Python, snake_case) должны разбираться в DTO целиком —
* в том числе detected_labels, которые уходят в ContentBlockedException.
*/
class AiResponseMappingTest {
private HttpServer server;
@AfterEach
void stopServer() {
if (server != null) {
server.stop(0);
}
}
@Test
void imageResponseMapsDetectedLabels() throws IOException {
startServer("/api/v1/moderation/image",
"{\"approved\":false,\"score\":0.93,\"reason\":\"FORBIDDEN_CONTENT\","
+ "\"label\":\"a gun\",\"detected_labels\":[\"a gun\",\"a knife\"]}");
ImageModerationResponse response = new AiMultipartHttpClient(webClient(), properties())
.post("/api/v1/moderation/image",
new MockMultipartFile("file", "photo.jpg", "image/jpeg", new byte[] {1, 2, 3}),
ImageModerationResponse.class);
assertThat(response.getApproved()).isFalse();
assertThat(response.getScore()).isEqualTo(0.93);
assertThat(response.getReason()).isEqualTo("FORBIDDEN_CONTENT");
assertThat(response.getDetectedLabels()).containsExactly("a gun", "a knife");
}
@Test
void textResponseIsDeserialized() throws IOException {
startServer("/api/v1/moderation/text",
"{\"approved\":false,\"score\":1.0,\"reason\":\"PROFANITY\",\"detected_labels\":[\"word\"]}");
ModerationResponse response = new AiHttpClient(webClient())
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
assertThat(response.getApproved()).isFalse();
assertThat(response.getScore()).isEqualTo(1.0);
assertThat(response.getReason()).isEqualTo("PROFANITY");
assertThat(response.getDetectedLabels()).containsExactly("word");
}
@Test
void textResponseWithoutLabelsIsDeserialized() throws IOException {
// Сейчас текстовый эндпоинт отдаёт только эти три поля
startServer("/api/v1/moderation/text", "{\"approved\":true,\"score\":0.01,\"reason\":\"OK\"}");
ModerationResponse response = new AiHttpClient(webClient())
.post("/api/v1/moderation/text", new TextModerationRequest("text"), ModerationResponse.class);
assertThat(response.getApproved()).isTrue();
assertThat(response.getDetectedLabels()).isNull();
}
private void startServer(String uri, String body) throws IOException {
server = HttpServer.create(new InetSocketAddress("localhost", 0), 0);
server.createContext(uri, exchange -> {
exchange.getRequestBody().readAllBytes();
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().add("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream out = exchange.getResponseBody()) {
out.write(bytes);
}
});
server.start();
}
private AiProperties properties() {
AiProperties properties = new AiProperties();
properties.setUrl("http://localhost:" + server.getAddress().getPort());
properties.setTimeout(5);
properties.setImageTimeout(5);
return properties;
}
private org.springframework.web.reactive.function.client.WebClient webClient() {
return new WebClientConfig().aiWebClient(properties());
}
}

View File

@@ -0,0 +1,122 @@
package com.krylov.refound.ai.pipeline;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import com.krylov.refound.ai.client.TextModerationClient;
import com.krylov.refound.ai.config.AiProperties;
import com.krylov.refound.ai.dto.ModerationResponse;
import com.krylov.refound.ai.exception.ContentBlockedException;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
class TextModerationProcessorTest {
private static final int MAX = 5000;
private TextModerationClient client;
private TextModerationProcessor processor;
@BeforeEach
void setUp() {
client = mock(TextModerationClient.class);
AiProperties properties = new AiProperties();
properties.setTextMaxLength(MAX);
processor = new TextModerationProcessor(client, properties);
}
@Test
void shortTextIsSentAsIs() {
when(client.moderate(anyString())).thenReturn(ok());
assertThat(processor.process(context("Потерял кошелёк", "В парке"))).isTrue();
verify(client).moderate("Потерял кошелёк\nВ парке");
}
@Test
void longTextIsSentInChunksWithinServiceLimit() {
when(client.moderate(anyString())).thenReturn(ok());
String description = "Потерял кошелёк в парке у фонтана. ".repeat(500); // ~17 500 символов
assertThat(processor.process(context("Кошелёк", description))).isTrue();
ArgumentCaptor<String> sent = ArgumentCaptor.forClass(String.class);
verify(client, times(4)).moderate(sent.capture());
assertThat(sent.getAllValues()).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(MAX));
}
@Test
void toxicTailOfLongTextBlocksPost() {
String description = "Нейтральный текст объявления. ".repeat(300) + "ТОКСИЧНО";
when(client.moderate(anyString())).thenAnswer(invocation ->
invocation.<String>getArgument(0).contains("ТОКСИЧНО") ? blocked() : ok());
assertThatThrownBy(() -> processor.process(context("Заголовок", description)))
.isInstanceOf(ContentBlockedException.class)
.satisfies(ex -> assertThat(((ContentBlockedException) ex).getDetectedLabels()).containsExactly("word"));
}
@Test
void unavailableServiceOnAnyChunkGivesNull() {
when(client.moderate(anyString())).thenReturn(ok()).thenReturn(null);
assertThat(processor.process(context("Заголовок", "а ".repeat(4000)))).isNull();
}
@Test
void blankTextIsNotSentToService() {
assertThat(processor.process(context(null, " "))).isTrue();
assertThat(processor.process(context(null, null))).isTrue();
verify(client, never()).moderate(anyString());
}
@Test
void splitCoversWholeTextWithOverlapAndRespectsLimit() {
String text = "слово ".repeat(3000);
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
assertThat(chunks).hasSizeGreaterThan(1);
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
assertThat(text).startsWith(chunks.get(0));
assertThat(text).endsWith(chunks.get(chunks.size() - 1));
for (int i = 1; i < chunks.size(); i++) {
String previous = chunks.get(i - 1);
// первые 200 символов следующей части повторяют конец предыдущей
assertThat(previous).endsWith(chunks.get(i).substring(0, 200));
}
}
@Test
void splitWithoutSpacesStillTerminates() {
String text = "x".repeat(12_345);
List<String> chunks = TextModerationProcessor.splitText(text, 5000, 200);
assertThat(chunks).allSatisfy(chunk -> assertThat(chunk.length()).isLessThanOrEqualTo(5000));
assertThat(String.join("", chunks).length()).isGreaterThanOrEqualTo(text.length());
}
private static ModerationContext context(String title, String description) {
return ModerationContext.builder().title(title).description(description).build();
}
private static ModerationResponse ok() {
return ModerationResponse.builder().approved(true).score(0.01).reason("OK").build();
}
private static ModerationResponse blocked() {
return ModerationResponse.builder()
.approved(false).score(1.0).reason("PROFANITY").detectedLabels(List.of("word")).build();
}
}