Skip to content

Commit

Permalink
Merge pull request #68 from BbeumbungE/feat/BACK-293
Browse files Browse the repository at this point in the history
fix: 신규 레코드 생성시 예외처리 로직 수정
  • Loading branch information
Fishphobiagg authored Sep 27, 2023
2 parents 5f3ca6b + 5a1668c commit 276f4fc
Show file tree
Hide file tree
Showing 18 changed files with 203 additions and 19 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,13 @@ public SseEmitter connectSseForConvertedCanvas(
return canvasSseEmitterService.connect(profileId);
}

@GetMapping("")
public ResponseEntity<Response> convertSketchToCanvasTest(
@RequestParam MultipartFile sketchFile
)throws IOException{
String sketchUrl = s3ImageUploadService.uploadFile(sketchFile, "rendingPage");
Response response = canvasConvertService.convertSketchToCanvasDemo(sketchUrl);
return ResponseEntity.ok(response);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ public Response convertSketchToCanvas(Long profileId, Long subjectId, String ske
return convertRequestSender.sendSketchConversionRequest(sketch, canvas.getId(), profileId, subject);
}

public Response convertSketchToCanvasDemo(String sketch){

}

public Response updateSketchAndCanvas(Long profileId, Long canvasId, String sketch){
Canvas canvas = canvasFindDao.findById(canvasId);
return canvasUpdateService.updateSketchAndCanvas(canvas, sketch, profileId);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.siliconvalley.domain.google.controller;

import com.siliconvalley.domain.google.service.VisionDetectingService;
import com.siliconvalley.global.common.code.CommonCode;
import com.siliconvalley.global.common.dto.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/test/google")
@RequiredArgsConstructor
public class DetectingTestController {

private final VisionDetectingService visionDetectingService;

@GetMapping("{canvasId}")
public ResponseEntity<Response> test(
@PathVariable Long canvasId
){
return ResponseEntity.ok(visionDetectingService.testLabelDetecting(canvasId));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.siliconvalley.domain.google.dto;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class LabelResultDto {

private String label;
private Float confidence;;

public LabelResultDto(String label, Float confidence){
this.label = label;
this.confidence = confidence;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.vision.v1.*;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
Expand All @@ -24,14 +22,17 @@ public class GoogleVisionApiService {
@Value("${google.service.account.key}")
private String serviceAccountKey;

public Map<String, Float> detectObjects(String filePath) {
public Map<String, Float> detectLabels(String filePath) {
List<AnnotateImageRequest> requests = new ArrayList<>();
Map<String, Float> results = new HashMap<>();

try {
ImageSource imageSource = ImageSource.newBuilder().setImageUri(filePath).build();
Image img = Image.newBuilder().setSource(imageSource).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.OBJECT_LOCALIZATION).build();

// LABEL_DETECTION 유형으로 변경
Feature feat = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build();

AnnotateImageRequest request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
Expand All @@ -56,9 +57,10 @@ public Map<String, Float> detectObjects(String filePath) {
continue;
}

for (LocalizedObjectAnnotation entity : res.getLocalizedObjectAnnotationsList()) {
log.info("Detected object: " + entity.getName() + " with confidence: " + entity.getScore());
results.put(entity.getName().toLowerCase(), entity.getScore());
// EntityAnnotation 리스트로 변경
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
log.info("Detected label: " + annotation.getDescription() + " with confidence: " + annotation.getScore());
results.put(annotation.getDescription().toLowerCase(), annotation.getScore());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@

import com.siliconvalley.domain.canvas.dao.CanvasFindDao;
import com.siliconvalley.domain.canvas.domain.Canvas;
import com.siliconvalley.domain.google.dto.LabelResultDto;
import com.siliconvalley.domain.stage.domain.Score;
import com.siliconvalley.global.common.code.CommonCode;
import com.siliconvalley.global.common.dto.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
Expand All @@ -21,12 +26,22 @@ public class VisionDetectingService {

public Score calculateCanvasScore(Long canvasId) {
Canvas canvas = canvasFindDao.findById(canvasId);
Map<String, Float> detectResult = visionService.detectObjects(canvas.getCanvas());

if (detectResult.size() == 0) {return Score.LOW;}
Float detectionScore = detectResult.get(canvas.getSubject().getPix2Pix().getModelName());
Map<String, Float> detectResult = visionService.detectLabels(canvas.getCanvas());
if (detectResult.size() == 0 || canvas.getSubject().getPix2Pix().getVisionName().equals(null)) {return Score.LOW;}
Float detectionScore = detectResult.get(canvas.getSubject().getPix2Pix().getVisionName());

return Score.determineScore(detectionScore);
}

public Response testLabelDetecting(Long canvasId){
Canvas canvas = canvasFindDao.findById(canvasId);
List<LabelResultDto> results = new ArrayList<>();
for (Map.Entry<String ,Float> entry : visionService.detectLabels(canvas.getCanvas()).entrySet()){
results.add(new LabelResultDto(entry.getKey(), entry.getValue()));
}

return Response.of(CommonCode.GOOD_REQUEST, results);

}

}
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ public ResponseEntity getStageWithRecord(
return ResponseEntity.status(HttpStatus.OK).body(stageFindDao.getStageWithRecord(profileId, stageId));
}


@PostMapping("/{profileId}/stages/{stageId}/records")
public ResponseEntity evaluateCanvasAndcreateRecord(
@PathVariable(name = "profileId") Long profileId,
Expand All @@ -254,7 +255,7 @@ public ResponseEntity evaluateCanvasAndcreateRecord(
}

@PatchMapping("/{profileId}/stages/{stageId}/records/{recordId}")
public ResponseEntity evaluateCanvasAndupdateRecord(
public ResponseEntity evaluateCanvasAndUpdateRecord(
@PathVariable(name = "recordId") Long recordId,
@RequestBody RecordUpdateRequest dto
) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public enum RabbitMQCode implements ResponseCode {
CONVERSION_REQUEST_FAILURE(400, "변환 요청에 실패하였습니다.", HttpStatus.BAD_REQUEST),
CONVERSION_RESPONSE_SUCCESS(200, "변환 응답을 성공적으로 수신하였습니다.", HttpStatus.OK),
CONVERSION_RESPONSE_FAILURE(500, "변환 응답 수신에 실패하였습니다.", HttpStatus.INTERNAL_SERVER_ERROR),
DEMO_CONVERSION_SUCCESS(200, "체험 변환 요청에 성공하였습니다.", HttpStatus.OK)
;

private final int code;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.siliconvalley.domain.rabbitMQ.dto;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DemoConversionRequest {
private String sketchUrl;
private String modelName;

public DemoConversionRequest(String sketchUrl, String modelName){
this.sketchUrl = sketchUrl;
this.modelName = modelName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.siliconvalley.domain.rabbitMQ.dto;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DemoConversionResponse {
private String canvasUrl;
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.siliconvalley.domain.item.subject.domain.Subject;
import com.siliconvalley.domain.post.service.RankCachingService;
import com.siliconvalley.domain.rabbitMQ.code.RabbitMQCode;
import com.siliconvalley.domain.rabbitMQ.dto.DemoConversionRequest;
import com.siliconvalley.domain.rabbitMQ.dto.SketchConversionRequest;
import com.siliconvalley.global.common.dto.Response;
import lombok.RequiredArgsConstructor;
Expand All @@ -28,4 +29,10 @@ public Response sendSketchConversionRequest(String sketchUrl, Long canvasId, Lon
rabbitTemplate.convertAndSend(exchange, "sketch_conversion_request_queue" , request);
return Response.of(RabbitMQCode.CONVERSION_REQUEST_SUCCESS, new CanvasConvertResponse(canvasId, rankCachingService.getTopPostThisWeek(subject.getId())));
}

public Response sendDemoConversionRequest(String sketchUrl){
DemoConversionRequest request = new DemoConversionRequest(sketchUrl, "panda");
rabbitTemplate.convertAndSend(exchange, "demo_conversion_request_queue", request);
return Response.of(RabbitMQCode.CONVERSION_REQUEST_SUCCESS);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public Response evaluateCanvasAndcreateRecord(Long profileId, Long stageId,Recor
Profile profile = profileFindDao.findById(profileId);
Stage stage = stageFindDao.findById(stageId);

if (recordFindDao.findByProfileId(profileId).isPresent()) {
if (recordFindDao.findByProfileIdAndStageId(profileId, stageId).isPresent()) {
throw new RecordAlreadyExist(stage.getStageNum() + "번 스테이지 기록");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,5 @@ public Optional<Record> findByProfileId(Long profileId) {
public Optional<Record> findByProfileIdAndStageId(Long profileId, Long stageId) {
return recordRepository.findByProfileIdAndStageId(profileId, stageId);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ public class CanvasSseEmitterService {

private final CanvasSseEmitterRepository canvasSseEmitterRepository;
private final CanvasSseEmitterCreater canvasSseEmitterCreater;
private final SseEmitterSender sseEmitterSender;

public SseEmitter connect(Long profileId) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ Queue requestQueue() {
return new Queue("sketch_conversion_request_queue", true);
}

@Bean
Queue demoConversionRequestQueue() {return new Queue("demo_conversion_request_queue", true);}

@Bean
Queue responseQueue() {
return QueueBuilder.durable("sketch_conversion_response_queue")
Expand Down Expand Up @@ -85,6 +88,11 @@ public Binding bindingRequestQueue(Queue requestQueue, TopicExchange topicExchan
return BindingBuilder.bind(requestQueue).to(topicExchange).with("sketch_conversion_request_queue");
}

@Bean
public Binding bindingDemoRequestQueue(Queue demoConversionRequestQueue, TopicExchange topicExchange){
return BindingBuilder.bind(demoConversionRequestQueue).to(topicExchange).with("demo_conversion_request_queue");
}

@Bean
public Binding bindingResponseQueue(Queue responseQueue, TopicExchange topicExchange) {
return BindingBuilder.bind(responseQueue).to(topicExchange).with("sketch_conversion_response_queue");
Expand Down
4 changes: 4 additions & 0 deletions src/test/java/com/siliconvalley/post/EmotionServiceTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.siliconvalley.post;

public class EmotionServiceTests {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package com.siliconvalley.profile;

import com.siliconvalley.domain.profile.dao.ProfileFindDao;
import com.siliconvalley.domain.profile.exception.ProfileNameDuplicateException;
import com.siliconvalley.domain.profile.exception.ProfileNameIncludeBadWordException;
import com.siliconvalley.domain.profile.application.ProfileNameFilterService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.Mockito.when;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

@ExtendWith(MockitoExtension.class)
@DisplayName("프로필 이름 생성 정책 테스트")
public class ProfileNameServiceTests {

@InjectMocks
private ProfileNameFilterService profileNameFilterService;

@Mock
private ProfileFindDao profileFindDao;

@Test
@DisplayName("정책에 위반되지 않는 프로필 이름 생성")
void 유효한_프로필_이름_테스트() {
//given
String 유효한프로필이름 = "유효한이름";

//when
when(profileFindDao.existsByProfileName(유효한프로필이름)).thenReturn(false);

//then
assertDoesNotThrow(() -> profileNameFilterService.profileNameFilter(유효한프로필이름));
}

@Test
@DisplayName("프로필 이름에 부적절한 단어 포함 시 예외 발생")
void 부적절한_단어_테스트() {
//given
String 부적절한단어포함프로필이름 = "지랄";

//then
assertThrows(ProfileNameIncludeBadWordException.class, () -> profileNameFilterService.profileNameFilter(부적절한단어포함프로필이름));
}

@Test
@DisplayName("이미 사용 중인 프로필 이름 제공 시 예외 발생")
void 중복_프로필_이름_테스트() {
//given
String 중복된프로필이름 = "중복이름";

//when
when(profileFindDao.existsByProfileName(중복된프로필이름)).thenReturn(true);

//then
assertThrows(ProfileNameDuplicateException.class, () -> profileNameFilterService.profileNameFilter(중복된프로필이름));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public class VisionDetectingServiceTests {
Canvas mockCanvas = mock(Canvas.class, RETURNS_DEEP_STUBS);
when(canvasFindDao.findById(canvasId)).thenReturn(mockCanvas);
when(mockCanvas.getCanvas()).thenReturn("sampleCanvasData");
when(visionService.detectObjects("sampleCanvasData")).thenReturn(Map.of("anotherModelName", 0.8f)); // 수정된 점수
when(visionService.detectLabels("sampleCanvasData")).thenReturn(Map.of("anotherModelName", 0.8f)); // 수정된 점수
when(mockCanvas.getSubject().getPix2Pix().getModelName()).thenReturn("sampleModelName");

// When
Expand All @@ -59,7 +59,7 @@ public class VisionDetectingServiceTests {
Canvas mockCanvas = mock(Canvas.class, RETURNS_DEEP_STUBS);
when(canvasFindDao.findById(canvasId)).thenReturn(mockCanvas);
when(mockCanvas.getCanvas()).thenReturn("sampleCanvasData");
when(visionService.detectObjects("sampleCanvasData")).thenReturn(Map.of("sampleModelName", 0.3f)); // 수정된 점수
when(visionService.detectLabels("sampleCanvasData")).thenReturn(Map.of("sampleModelName", 0.3f)); // 수정된 점수
when(mockCanvas.getSubject().getPix2Pix().getModelName()).thenReturn("sampleModelName");

// When
Expand All @@ -77,7 +77,7 @@ public class VisionDetectingServiceTests {
Canvas mockCanvas = mock(Canvas.class, RETURNS_DEEP_STUBS);
when(canvasFindDao.findById(canvasId)).thenReturn(mockCanvas);
when(mockCanvas.getCanvas()).thenReturn("sampleCanvasData");
when(visionService.detectObjects("sampleCanvasData")).thenReturn(Map.of("sampleModelName", 0.8f)); // 수정된 점수
when(visionService.detectLabels("sampleCanvasData")).thenReturn(Map.of("sampleModelName", 0.8f)); // 수정된 점수
when(mockCanvas.getSubject().getPix2Pix().getModelName()).thenReturn("sampleModelName");

// When
Expand All @@ -97,7 +97,7 @@ public class VisionDetectingServiceTests {
when(mockCanvas.getCanvas()).thenReturn("sampleCanvasData");

// 탐지된 물체가 없을 경우 빈 Map 반환
when(visionService.detectObjects("sampleCanvasData")).thenReturn(Map.of());
when(visionService.detectLabels("sampleCanvasData")).thenReturn(Map.of());

// When
Score result = visionDetectingService.calculateCanvasScore(canvasId);
Expand All @@ -116,7 +116,7 @@ public class VisionDetectingServiceTests {
when(mockCanvas.getCanvas()).thenReturn("sampleCanvasData");

// 탐지된 물체가 없을 경우 빈 Map 반환
when(visionService.detectObjects("sampleCanvasData")).thenReturn(Map.of("Error", -1f));
when(visionService.detectLabels("sampleCanvasData")).thenReturn(Map.of("Error", -1f));

// When
Score result = visionDetectingService.calculateCanvasScore(canvasId);
Expand Down

0 comments on commit 276f4fc

Please sign in to comment.