Skip to content

Commit

Permalink
Merge pull request #126 from Happy-HOBAK/feat/#125
Browse files Browse the repository at this point in the history
[#125] ๊ฐ์ •์–ด ๋ถ„์„ API ์ถ”๊ฐ€
  • Loading branch information
yel-m authored Jul 13, 2024
2 parents f790f9f + 5c2159a commit f784d3a
Show file tree
Hide file tree
Showing 7 changed files with 166 additions and 0 deletions.
5 changes: 5 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ configurations {

repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}

dependencies {
Expand All @@ -43,6 +44,10 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

// Gson ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ Json ํŒŒ์‹ฑ
implementation 'org.jsoup:jsoup:1.14.2'
implementation 'com.google.code.gson:gson:2.8.7'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
import com.hobak.happinessql.domain.activity.exception.ActivityNotFoundException;
import com.hobak.happinessql.domain.activity.repository.ActivityRepository;
import com.hobak.happinessql.domain.record.converter.RecordConverter;
import com.hobak.happinessql.domain.record.domain.Analysis;
import com.hobak.happinessql.domain.record.domain.Location;
import com.hobak.happinessql.domain.record.domain.Record;
import com.hobak.happinessql.domain.record.domain.RecordImg;
import com.hobak.happinessql.domain.record.dto.RecordCreateRequestDto;
import com.hobak.happinessql.domain.record.repository.AnalysisRepository;
import com.hobak.happinessql.domain.record.repository.LocationRepository;
import com.hobak.happinessql.domain.record.repository.RecordImgRepository;
import com.hobak.happinessql.domain.record.repository.RecordRepository;
Expand All @@ -19,6 +21,9 @@
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

@Service
@RequiredArgsConstructor
public class RecordCreateService {
Expand All @@ -30,6 +35,8 @@ public class RecordCreateService {

private final AwsS3Service awsS3Service;
private final UserFindService userFindService;
private final AnalysisRepository analysisRepository;
private final SentimentAnalyzeService sentimentAnalyzeService;


@Transactional
Expand All @@ -54,6 +61,16 @@ public Long createRecord(Long userId, RecordCreateRequestDto requestDto, Multipa
.build();
recordImgRepository.save(recordImg);
}
if (requestDto.getMemo() != null && !requestDto.getMemo().isEmpty()) {
Map<String, List<String>> analyzeResult = sentimentAnalyzeService.getAnalyzeResult(requestDto.getMemo());
Analysis analysis = Analysis.builder()
.record(newRecord)
.positiveSentiments(analyzeResult.get("positive"))
.negativeSentiments(analyzeResult.get("negative"))
.build();

analysisRepository.save(analysis);
}

return newRecord.getRecordId();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package com.hobak.happinessql.domain.record.application;

import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SentimentAnalyzeService {
@Value("${sentiment.clientId}")
private String clientId;

@Value("${sentiment.clientSecret}")
private String clientSecret;

public Map<String, List<String>> getAnalyzeResult(String content) {
String url = "https://naveropenapi.apigw.ntruss.com/sentiment-analysis/v1/analyze";

try {
RestTemplate restTemplate = new RestTemplate();

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("X-NCP-APIGW-API-KEY-ID", clientId);
headers.add("X-NCP-APIGW-API-KEY", clientSecret);

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("content", content);

HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(), headers);

ResponseEntity<Map<String, Object>> response = restTemplate.exchange(
url,
HttpMethod.POST,
entity,
new ParameterizedTypeReference<Map<String, Object>>() {}
);

Map<String, Object> responseBody = response.getBody();
if (responseBody != null && responseBody.containsKey("sentences")) {
List<Map<String, Object>> sentences = (List<Map<String, Object>>) responseBody.get("sentences");
List<Map<String, String>> emotionText = sentences.stream()
.map(sentence -> Map.of(
"content", (String) sentence.get("content"),
"sentiment", (String) sentence.get("sentiment")
))
.collect(Collectors.toList());

return separateSentiment(emotionText);
} else {
log.warn("Response does not contain 'sentences' key");
return Map.of("positive", List.of(), "negative", List.of());
}
} catch (HttpClientErrorException | HttpServerErrorException e) {
log.error("HTTP error: " + e.toString());
return Map.of("positive", List.of(), "negative", List.of());
} catch (Exception e) {
log.error("Unexpected error: " + e.toString());
return Map.of("positive", List.of(), "negative", List.of());
}
}

private Map<String, List<String>> separateSentiment(List<Map<String, String>> emotionText) {
Map<String, List<String>> groupedTexts = emotionText.stream()
.collect(Collectors.groupingBy(
map -> map.get("sentiment"),
Collectors.mapping(map -> map.get("content"), Collectors.toList())
));

List<String> positive = groupedTexts.getOrDefault("positive", List.of());
List<String> negative = groupedTexts.getOrDefault("negative", List.of());

return Map.of("positive", positive, "negative", negative);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.hobak.happinessql.domain.record.domain;

import com.hobak.happinessql.global.infra.database.BaseTimeEntity;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

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

@Getter
@Entity
@Table(name = "analysis")
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Analysis extends BaseTimeEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "analysis_id")
private Long analysisId;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "record_id")
private Record record;

@ElementCollection
@CollectionTable(name = "positive_sentiments", joinColumns = @JoinColumn(name = "analysis_id"))
@Column(name = "content")
private List<String> positiveSentiments = new ArrayList<>();

@ElementCollection
@CollectionTable(name = "negative_sentiments", joinColumns = @JoinColumn(name = "analysis_id"))
@Column(name = "content")
private List<String> negativeSentiments = new ArrayList<>();

@Builder
public Analysis(Record record, List<String> positiveSentiments, List<String> negativeSentiments) {
this.record = record;
this.positiveSentiments = positiveSentiments;
this.negativeSentiments = negativeSentiments;
}



}
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public class Record extends BaseTimeEntity {
@JoinColumn(name = "user_id", nullable = false)
private User user;

@OneToOne(mappedBy = "record", fetch = FetchType.LAZY)
private Analysis analysis;

@Builder
public Record(Integer happiness, String memo, User user, Activity activity) {
this.happiness = happiness;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package com.hobak.happinessql.domain.record.repository;

import com.hobak.happinessql.domain.record.domain.Analysis;
import org.springframework.data.jpa.repository.JpaRepository;

public interface AnalysisRepository extends JpaRepository<Analysis, Long> {
}
4 changes: 4 additions & 0 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,7 @@ cloud:
auto: false
jwt:
secret: ${JWT_SECRET_KEY}

sentiment:
clientId: ${NAVER_CLIENT_ID}
clientSecret: ${NAVER_CLIENT_SECRET}

0 comments on commit f784d3a

Please sign in to comment.