Skip to content

Commit

Permalink
Merge pull request #11 from LearnMate-Dev/feature/#7
Browse files Browse the repository at this point in the history
  • Loading branch information
daeun084 authored Nov 9, 2024
2 parents dbb782e + a92264a commit 4dd72a3
Show file tree
Hide file tree
Showing 13 changed files with 154 additions and 9 deletions.
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ dependencies {

// json
implementation 'org.json:json:20230227'

// google natural language
implementation 'com.google.cloud:google-cloud-language:2.53.0'
}

jib {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/LearnMate/dev/common/ErrorStatus.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public enum ErrorStatus implements BaseErrorCode {

// Emotion
_INVALID_EMOTION_SCORE(HttpStatus.BAD_REQUEST, "EMOTION400", "감정 점수는 -1과 1 사이여야 합니다."),
_INVALID_EMOTION_SPECTRUN(HttpStatus.BAD_REQUEST, "EMOTION400", "유효하지 않은 감정 지표입니다.")
_INVALID_EMOTION_SPECTRUN(HttpStatus.BAD_REQUEST, "EMOTION400", "유효하지 않은 감정 지표입니다."),
_ANALYZE_EMOTION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "EMOTION500", "감정 분석 API 호출 중 오류가 발생했습니다.")
;


Expand Down
33 changes: 33 additions & 0 deletions src/main/java/LearnMate/dev/common/config/AsyncConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package LearnMate.dev.common.config;

import LearnMate.dev.common.exception.CustomAsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {

@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(5);
executor.setQueueCapacity(5);
executor.setKeepAliveSeconds(30);
executor.setThreadNamePrefix("async-executor-");
executor.initialize();
return executor;
}

@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncUncaughtExceptionHandler();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package LearnMate.dev.common.config;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.language.v1.LanguageServiceSettings;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;

import java.io.IOException;

@Configuration
public class GoogleNaturalLanguageConfig {
@Value("classpath:nlp.json")
Resource gcsCredentials;

@Bean
public LanguageServiceSettings languageServiceSettings() {
try {
return LanguageServiceSettings.newBuilder()
.setCredentialsProvider(() ->
GoogleCredentials.fromStream(gcsCredentials.getInputStream()))
.build();
} catch (IOException e) {
throw new RuntimeException("Failed to initialize LanguageServiceSettings", e);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package LearnMate.dev.common;
package LearnMate.dev.common.exception;

import LearnMate.dev.common.ErrorStatus;
import LearnMate.dev.model.dto.ErrorReasonDto;
import lombok.Getter;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package LearnMate.dev.common.exception;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;

import java.lang.reflect.Method;

public class CustomAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
System.out.println("Exception message - " + ex.getMessage());
System.out.println("Method name - " + method.getName());

for (Object param : params) {
System.out.println("Parameter value - " + param);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package LearnMate.dev.common;
package LearnMate.dev.common.exception;

import LearnMate.dev.common.ApiResponse;
import LearnMate.dev.common.ErrorStatus;
import LearnMate.dev.model.dto.ErrorReasonDto;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static DiaryDetailResponse toDiaryDetailResponse(Diary diary) {
.build();
}

public static DiaryAnalysisResponse toDiaryAnalysisResponse(Double score, String actionTip) {
public static DiaryAnalysisResponse toDiaryAnalysisResponse(Float score, String actionTip) {
return DiaryAnalysisResponse.builder()
.emotionScore(score)
.actionTip(actionTip)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
@NoArgsConstructor
public class DiaryAnalysisResponse {

private Double emotionScore;
private Float emotionScore;
private String actionTip;

}
17 changes: 17 additions & 0 deletions src/main/java/LearnMate/dev/service/ActionTipService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package LearnMate.dev.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

@Service
public class ActionTipService {

@Async
public CompletableFuture<String> getActionTip(String content) {
String text = "Action Tip";

return CompletableFuture.completedFuture(text);
}
}
12 changes: 9 additions & 3 deletions src/main/java/LearnMate/dev/service/DiaryService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package LearnMate.dev.service;

import LearnMate.dev.common.ApiException;
import LearnMate.dev.common.exception.ApiException;
import LearnMate.dev.common.ErrorStatus;
import LearnMate.dev.model.converter.ActionTipConverter;
import LearnMate.dev.model.converter.DiaryConverter;
Expand All @@ -22,13 +22,16 @@
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;

@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class DiaryService {
private final UserRepository userRepository;
private final DiaryRepository diaryRepository;
private final NaturalLanguageService naturalLanguageService;
private final ActionTipService actionTipService;

/*
* 유저의 일기 내용을 기반으로 감정을 분석하고 행동 요령을 제안함
Expand All @@ -44,11 +47,14 @@ public DiaryAnalysisResponse analyzeDiary(Long userId, DiaryAnalysisRequest requ
String content = request.getContent();
validContentLength(content);

// TODO: 감정 분석 API 호출
// 감정 분석 후 감정 점수 반환
CompletableFuture<Float> scoreFuture = naturalLanguageService.analyzeEmotion(content);

// TODO: 행동 요령 제안 API 호출
CompletableFuture<String> actionTipFuture = actionTipService.getActionTip(content);

return DiaryConverter.toDiaryAnalysisResponse(1.0, "ActionTip");
// 두 CompletableFuture 조합
return scoreFuture.thenCombine(actionTipFuture, DiaryConverter::toDiaryAnalysisResponse).join();
}

/*
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/LearnMate/dev/service/NaturalLanguageService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package LearnMate.dev.service;

import LearnMate.dev.common.exception.ApiException;
import LearnMate.dev.common.ErrorStatus;
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

@Service
public class NaturalLanguageService {

/*
* cloud Natural Language API를 호출해 텍스트에 대한 감정을 분석
* @param text
* @return
*/
@Async
public CompletableFuture<Float> analyzeEmotion(String text) {
try (LanguageServiceClient language = LanguageServiceClient.create()) {

Document doc = Document.newBuilder().setContent(text).setType(Document.Type.PLAIN_TEXT).build();
Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

System.out.printf("Text: %s%n", text);
System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());

return CompletableFuture.completedFuture(sentiment.getScore());
} catch (IOException e) {
throw new ApiException(ErrorStatus._ANALYZE_EMOTION_ERROR);
}
}
}
2 changes: 1 addition & 1 deletion src/main/java/LearnMate/dev/service/UserService.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package LearnMate.dev.service;

import LearnMate.dev.common.ApiException;
import LearnMate.dev.common.exception.ApiException;
import LearnMate.dev.common.ErrorStatus;
import LearnMate.dev.model.dto.request.UserSignInRequest;
import LearnMate.dev.model.dto.request.UserSignUpRequest;
Expand Down

0 comments on commit 4dd72a3

Please sign in to comment.