Skip to content

Commit

Permalink
fix: cors 관련 파일 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
jhsong76 committed Jan 2, 2024
2 parents 18a2b97 + bd24b30 commit 664b122
Show file tree
Hide file tree
Showing 11 changed files with 140 additions and 14 deletions.
2 changes: 1 addition & 1 deletion .platform/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ http {
location / {
proxy_pass http://springboot;
# CORS 관련 헤더 추가
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Origin' 'http://localhost:5173';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
proxy_http_version 1.1;
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/hackerton/demo/domain/User/User.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package com.hackerton.demo.domain.User;

import com.hackerton.demo.domain.Keyword.Keyword;
import com.hackerton.demo.domain.common.BaseEntity;
import com.hackerton.demo.domain.keyword.Keyword;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package com.hackerton.demo.domain.Keyword;
package com.hackerton.demo.domain.keyword;

import com.theokanning.openai.completion.chat.ChatCompletionChoice;
import com.theokanning.openai.service.OpenAiService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.theokanning.openai.completion.chat.ChatCompletionRequest;
import com.theokanning.openai.completion.chat.ChatMessage;
import com.theokanning.openai.service.OpenAiService;


import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

Expand All @@ -24,10 +24,12 @@ public class ChatService {

private final KeywordRespository keywordRespository;

private final PlaceRepository placeRepository;

public List<KeywordDto> createGptComment(String content) {
this.openAiService = new OpenAiService(apiKey, Duration.ofSeconds(20));
String prompt = content + "대신 딱 10개만 아무런 부가 설명 없이 키워드만 알려줘.";
System.out.println(prompt);

ChatCompletionRequest requester = ChatCompletionRequest.builder()
.model(MODEL)
.maxTokens(2048)
Expand Down Expand Up @@ -79,4 +81,61 @@ private List<KeywordDto> convertToKeywordDtos(List<Keyword> keywords) {
}
return keywordDtos;
}

public List<PlaceDto> createGptPlace(String content) {
this.openAiService = new OpenAiService(apiKey, Duration.ofSeconds(20));
String prompt = content + "를 할 수 있는 대한민국에 있는 장소 5개만 부가 설명 없이 장소명만 알려줘. 장소명 말고 다른 설명은 필요 없어.";

ChatCompletionRequest requester = ChatCompletionRequest.builder()
.model(MODEL)
.maxTokens(2048)
.temperature(0.8)
.messages(List.of(
new ChatMessage("user", prompt)
)).build();

ChatCompletionChoice chatCompletionResult = openAiService.createChatCompletion(requester).getChoices().get(0);
String contentResult = chatCompletionResult.getMessage().getContent();

return extractPlaces(contentResult);
}

private List<PlaceDto> extractPlaces(String content) {
List<PlaceDto> placeDtos = new ArrayList<>();

// 개행 문자로 분할하여 리스트로 변환
String[] placeArray = content.split("\\r?\\n");

for (String placeName : placeArray) {
String cleanName = placeName.replaceAll("\\d+\\.\\s*", "");
PlaceDto placeDto = PlaceDto.builder().placeName(cleanName).build();
placeDtos.add(placeDto);
}

List<Place> places = placeRepository.saveAll(convertToPlace(placeDtos));

return convertToPlaceDtos(places);
}

private List<Place> convertToPlace(List<PlaceDto> placeDtos) {
List<Place> places = new ArrayList<>();
for (PlaceDto dto : placeDtos) {
Place place = new Place();
place.setPlaceName(dto.getPlaceName());
places.add(place);
}
return places;
}

private List<PlaceDto> convertToPlaceDtos(List<Place> places) {
List<PlaceDto> placeDtos = new ArrayList<>();
for (Place place : places) {
PlaceDto dto = PlaceDto.builder()
.placeName(place.getPlaceName())
.build();
placeDtos.add(dto);
}
return placeDtos;
}

}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.hackerton.demo.domain.Keyword;
package com.hackerton.demo.domain.keyword;

import com.hackerton.demo.domain.common.ApiResponse;
import com.hackerton.demo.domain.common.ApiResponseStatus;
Expand All @@ -19,7 +19,7 @@ public class GptController {
private final ChatService chatService;

@GetMapping("/result")
@Operation(summary = "음석인식/텍스트 ChatGPT로 전달하여 키워드 추출", description = "음성인식/텍스트를 통해 ChatGPT 검색을 실행합니다. " + "검색 결과를 List로 반환하여 Keyword에 저장합니다.")
@Operation(summary = "음성인식/텍스트 ChatGPT로 전달하여 키워드 추출", description = "음성인식/텍스트를 통해 ChatGPT 검색을 실행합니다. " + "검색 결과를 List로 반환하여 Keyword에 저장합니다.")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "GET_SUCCESS", description = "조회 성공"),
})
Expand All @@ -28,4 +28,15 @@ public ResponseEntity<ApiResponse<List<KeywordDto>>> createGptComment(@RequestPa
ApiResponse<List<KeywordDto>> apiResponse = new ApiResponse<>(ApiResponseStatus.GET_SUCCESS, keywordDtos);
return ResponseEntity.ok(apiResponse);
}

@GetMapping("/result/place")
@Operation(summary = "선택된 키워드와 관련된 장소 추천", description = "키워드와 관련된 장소를 추천합니다.")
@ApiResponses({
@io.swagger.v3.oas.annotations.responses.ApiResponse(responseCode = "GET_SUCCESS", description = "조회 성공"),
})
public ResponseEntity<ApiResponse<List<PlaceDto>>> createGptPlace(@RequestParam String content) {
List<PlaceDto> placeDtos = chatService.createGptPlace(content);
ApiResponse<List<PlaceDto>> apiResponse = new ApiResponse<>(ApiResponseStatus.GET_SUCCESS, placeDtos);
return ResponseEntity.ok(apiResponse);
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.hackerton.demo.domain.Keyword;
package com.hackerton.demo.domain.keyword;

import com.hackerton.demo.domain.User.User;
import com.hackerton.demo.domain.common.BaseEntity;
Expand All @@ -10,7 +10,6 @@
@Setter
@Builder
@NoArgsConstructor(access = AccessLevel.PUBLIC)

@AllArgsConstructor
public class Keyword extends BaseEntity {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package com.hackerton.demo.domain.Keyword;
package com.hackerton.demo.domain.keyword;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Builder
@Getter
@NoArgsConstructor
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.hackerton.demo.domain.Keyword;
package com.hackerton.demo.domain.keyword;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
Expand Down
20 changes: 20 additions & 0 deletions src/main/java/com/hackerton/demo/domain/keyword/Place.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.hackerton.demo.domain.keyword;

import com.hackerton.demo.domain.common.BaseEntity;
import jakarta.persistence.*;
import lombok.*;

@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor(access = AccessLevel.PUBLIC)
@AllArgsConstructor
public class Place extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "place_id")
private Long id;

private String placeName;
}
14 changes: 14 additions & 0 deletions src/main/java/com/hackerton/demo/domain/keyword/PlaceDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.hackerton.demo.domain.keyword;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class PlaceDto {
private String placeName;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.hackerton.demo.domain.keyword;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PlaceRepository extends JpaRepository<Place, Long> {
}
17 changes: 17 additions & 0 deletions src/main/java/com/hackerton/demo/domain/utils/WebMvcConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.hackerton.demo.domain.utils;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:5173")
.allowedMethods("OPTIONS","GET","POST","PUT","DELETE");
}
}

0 comments on commit 664b122

Please sign in to comment.