ensureAccepted 함수 InferenceCommonService 생성후 공통으로 생성 #107

Merged
teddy merged 3 commits from feat/infer_dev_260211 into develop 2026-02-26 16:56:04 +09:00
8 changed files with 172 additions and 246 deletions

View File

@@ -0,0 +1,111 @@
package com.kamco.cd.kamcoback.common.inference.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kamco.cd.kamcoback.common.exception.CustomApiException;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient.ExternalCallResult;
import com.kamco.cd.kamcoback.inference.dto.InferenceSendDto;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Log4j2
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class InferenceCommonService {
@Value("${spring.profiles.active}")
private String profile;
@Value("${inference.url}")
private String inferenceUrl;
private final ObjectMapper objectMapper;
private final ExternalHttpClient externalHttpClient;
/**
* 추론 AI API 호출 batch id를 리턴
*
* @param dto
* @return
*/
public Long ensureAccepted(InferenceSendDto dto) {
if (dto == null) {
log.warn("not InferenceSendDto dto");
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST);
}
log.info("");
log.info("========================================================");
log.info("[SEND INFERENCE] Inference request dto= {}", dto);
log.info("========================================================");
log.info("");
// 1) 요청 로그
try {
log.debug("Inference request dto={}", objectMapper.writeValueAsString(dto));
} catch (JsonProcessingException e) {
log.warn("Failed to serialize inference dto", e);
}
// 2) local 환경 임시 처리
// if ("local".equals(profile)) {
// if (dto.getPred_requests_areas() == null) {
// throw new IllegalStateException("pred_requests_areas is null");
// }
//
// dto.getPred_requests_areas().setInput1_scene_path("/kamco-nfs/requests/2023_local.geojson");
//
// dto.getPred_requests_areas().setInput2_scene_path("/kamco-nfs/requests/2024_local.geojson");
// }
// 3) HTTP 호출
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
// 4) 추론 실행 API 호출
ExternalCallResult<String> result =
externalHttpClient.call(inferenceUrl, HttpMethod.POST, dto, headers, String.class);
if (result.statusCode() < 200 || result.statusCode() >= 300) {
log.error("Inference API failed. status={}, body={}", result.statusCode(), result.body());
throw new CustomApiException("BAD_GATEWAY", HttpStatus.BAD_GATEWAY);
}
// 5) 응답 파싱
try {
List<Map<String, Object>> list =
objectMapper.readValue(result.body(), new TypeReference<>() {});
if (list.isEmpty()) {
throw new CustomApiException(
"NOT_FOUND", HttpStatus.NOT_FOUND, "Inference response is empty");
}
Object batchIdObj = list.get(0).get("batch_id");
if (batchIdObj == null) {
throw new CustomApiException(
"NOT_FOUND", HttpStatus.NOT_FOUND, "batch_id not found in response");
}
return Long.valueOf(batchIdObj.toString());
} catch (Exception e) {
log.error("Failed to parse inference response. body={}", result.body(), e);
throw new CustomApiException("INVALID_INFERENCE_RESPONSE", HttpStatus.BAD_GATEWAY);
}
}
}

View File

@@ -133,7 +133,7 @@ public class InferenceResultApiController {
}
/** 변화탐지 실행 정보 입력화면에서 호출 */
@Operation(summary = "변화탐지 실행 정보 입력", description = "추론관리 > 추론목록 > 변화탐지 실행 정보 입력")
@Operation(summary = "변화탐지 실행 정보 입력, 추론실행", description = "추론관리 > 추론목록 > 변화탐지 실행 정보 입력")
@ApiResponses(
value = {
@ApiResponse(

View File

@@ -1,11 +1,9 @@
package com.kamco.cd.kamcoback.inference.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kamco.cd.kamcoback.common.exception.CustomApiException;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.ImageFeature;
import com.kamco.cd.kamcoback.common.geometry.GeoJsonFileWriter.Scene;
import com.kamco.cd.kamcoback.common.inference.service.InferenceCommonService;
import com.kamco.cd.kamcoback.common.utils.UserUtil;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient.ExternalCallResult;
@@ -22,7 +20,6 @@ import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.InferenceLearnDto
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.InferenceServerStatusDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.InferenceStatusDetailDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetFallbackYearDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.MapSheetNumDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.ResultList;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.SaveInferenceAiDto;
import com.kamco.cd.kamcoback.inference.dto.InferenceResultDto.Status;
@@ -76,14 +73,11 @@ public class InferenceResultService {
private final MapSheetMngCoreService mapSheetMngCoreService;
private final ModelMngCoreService modelMngCoreService;
private final AuditLogCoreService auditLogCoreService;
private final InferenceCommonService inferenceCommonService;
private final ExternalHttpClient externalHttpClient;
private final ObjectMapper objectMapper;
private final UserUtil userUtil;
@Value("${inference.url}")
private String inferenceUrl;
@Value("${inference.batch-url}")
private String batchUrl;
@@ -93,9 +87,6 @@ public class InferenceResultService {
@Value("${file.dataset-dir}")
private String datasetDir;
@Value("${spring.profiles.active}")
private String profile;
/**
* 추론관리 목록
*
@@ -120,7 +111,7 @@ public class InferenceResultService {
}
/**
* 추론 실행 - 추론제외, 이전도 도엽 사용 분기
* 추론 실행 - 추론제외, 이전도 도엽 사용 분기
*
* @param req
* @return
@@ -128,8 +119,11 @@ public class InferenceResultService {
@Transactional
public UUID run(InferenceResultDto.RegReq req) {
if (req.getDetectOption().equals(DetectOption.EXCL.getId())) {
// 추론 제외 일때
return runExcl(req);
}
// 이전연도 도엽 사용 일때
return runPrev(req);
}
@@ -143,6 +137,10 @@ public class InferenceResultService {
// target 도엽 조회
List<MngListDto> targetDtoList = mapSheetMngCoreService.getHstMapSheetList(req);
if (targetDtoList == null || targetDtoList.isEmpty()) {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "기준년도 추론가능한 도엽이 없습니다.");
}
// target 리스트 추출 (null 제거 + 중복 제거)
List<String> targetList =
targetDtoList.stream()
@@ -151,7 +149,7 @@ public class InferenceResultService {
.distinct()
.toList();
// compare 도엽번호 리스트 조회 (null 제거 + 중복 제거)
// compare 도엽번호 리스트 조회 (null 제거 + 중복 제거), 기준연도와 비교하여 실행하므로 부분, 전체 조건 걸지 않음
List<String> compareList =
mapSheetMngCoreService.getMapSheetNumByHst(req.getCompareYyyy()).stream()
.filter(Objects::nonNull)
@@ -167,6 +165,10 @@ public class InferenceResultService {
// 도엽 비교 로그 출력
logYearComparison(targetList, compareList, filteredTargetList);
if (filteredTargetList == null || filteredTargetList.isEmpty()) {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "추론 가능한 도엽을 확인해 주세요.");
}
// compare geojson 파일 생성
Scene compareScene =
getSceneInference(
@@ -204,6 +206,10 @@ public class InferenceResultService {
// target 목록 조회
List<MngListDto> targetDtoList = mapSheetMngCoreService.getHstMapSheetList(req);
if (targetDtoList == null || targetDtoList.isEmpty()) {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "기준년도 추론가능한 도엽이 없습니다.");
}
// target 도엽번호 리스트 추출 중복 제거
List<String> targetList =
targetDtoList.stream()
@@ -282,6 +288,10 @@ public class InferenceResultService {
targetList.size() - filteredTargetList.size(), // compare에 존재하지 않는 target 도엽 수
compareOnlyCount); // target 에 존재하지 않는 compare 도엽수
if (filteredTargetList == null || filteredTargetList.isEmpty()) {
throw new CustomApiException("NOT_FOUND", HttpStatus.NOT_FOUND, "추론 가능한 도엽을 확인해 주세요.");
}
// compare 기준 geojson 생성 (년도 fallback 반영)
Scene compareScene =
getSceneInference(
@@ -326,20 +336,24 @@ public class InferenceResultService {
.filter(m -> filteredSet.contains(m.getMapSheetNum()))
.toList();
// 추론 실행 목록 테이블 저장, 도엽목록별 상태 체크 테이블 저장
UUID uuid = inferenceResultCoreService.saveInferenceInfo(req, newTargetList);
// 추론 AI 전달 파라미터 생성
pred_requests_areas predRequestsAreas = new pred_requests_areas();
predRequestsAreas.setInput1_year(req.getCompareYyyy());
predRequestsAreas.setInput2_year(req.getTargetYyyy());
predRequestsAreas.setInput1_scene_path(modelComparePath.getFilePath());
predRequestsAreas.setInput2_scene_path(modelTargetPath.getFilePath());
// 모델정보 조회 dto 생성 후 반환
InferenceSendDto m1 = this.getModelInfo(req.getModel1Uuid());
m1.setPred_requests_areas(predRequestsAreas);
log.info("[INFERENCE] Start m1 = {}", m1);
Long batchId = ensureAccepted(m1);
// AI 호출
Long batchId = inferenceCommonService.ensureAccepted(m1);
SaveInferenceAiDto saveInferenceAiDto = new SaveInferenceAiDto();
saveInferenceAiDto.setUuid(uuid);
@@ -351,6 +365,7 @@ public class InferenceResultService {
saveInferenceAiDto.setModelTargetPath(modelTargetPath.getFilePath());
saveInferenceAiDto.setModelStartDttm(ZonedDateTime.now());
// AI 호출 하고 리턴 받은 정보 추론 실행 목록 테이블에 업데이트
inferenceResultCoreService.update(saveInferenceAiDto);
return uuid;
@@ -387,7 +402,7 @@ public class InferenceResultService {
}
/**
* 변화탐지 실행 정보 생성
* 변화탐지 실행 정보 생성 TODO 미사용, 새로운 추론실행 로직 테스트후 삭제 해야합니다.
*
* @param req
*/
@@ -513,7 +528,7 @@ public class InferenceResultService {
m1.setPred_requests_areas(predRequestsAreas);
// ai 추론 실행 api 호출
Long batchId = ensureAccepted(m1);
Long batchId = inferenceCommonService.ensureAccepted(m1);
// ai 추론 실행후 응답값 update
SaveInferenceAiDto saveInferenceAiDto = new SaveInferenceAiDto();
@@ -530,145 +545,6 @@ public class InferenceResultService {
return uuid;
}
// 비교년도 탐지 제이터 옵션 별로 조회하여 req에 적용
private List<MapSheetNumDto> createdMngDto(
InferenceResultDto.RegReq req, List<MngListDto> targetList) {
List<String> mapTargetIds = new ArrayList<>();
targetList.forEach(
hstMapSheet -> {
// 비교년도는 target 년도 기준으로 가져옴 파라미터 만들기
mapTargetIds.add(hstMapSheet.getMapSheetNum());
});
// 비교년도 조회
List<String> mapCompareIds = new ArrayList<>();
List<MngListCompareDto> compareList =
mapSheetMngCoreService.getByHstMapSheetCompareList(req.getCompareYyyy(), mapTargetIds);
for (MngListCompareDto dto : compareList) {
// 추론 제외일때 이전년도 파일이 없으면 제외
if (req.getDetectOption().equals(DetectOption.EXCL.getId())) {
int targetYear = req.getTargetYyyy() - 1;
if (dto.getBeforeYear() != targetYear) {
continue;
}
}
// 비교년도는 target 년도 기준으로 가져옴
mapCompareIds.add(dto.getMapSheetNum());
}
Set<String> compareSet =
mapCompareIds.stream()
.filter(Objects::nonNull)
.map(String::trim) // 공백/개행 방지
.collect(Collectors.toSet());
// target 기준 compare 비교하여 서로 있는것만 저장
List<String> commonIds =
mapTargetIds.stream()
.filter(Objects::nonNull)
.map(String::trim)
.filter(compareSet::contains)
.toList();
Set<String> commonIdSet =
commonIds.stream().filter(Objects::nonNull).map(String::trim).collect(Collectors.toSet());
// 저장하기위해 파라미터 다시 구성
List<MapSheetNumDto> mapSheetNum =
targetList.stream()
.filter(dto -> dto.getMapSheetNum() != null)
.filter(dto -> commonIdSet.contains(dto.getMapSheetNum().trim()))
.map(
dto -> {
MapSheetNumDto mapSheetNumDto = new MapSheetNumDto();
mapSheetNumDto.setMapSheetNum(dto.getMapSheetNum());
mapSheetNumDto.setMapSheetName(dto.getMapSheetName());
return mapSheetNumDto;
})
.toList();
return mapSheetNum;
}
/**
* 추론 AI API 호출 batch id를 리턴
*
* @param dto
*/
// 같은함수가 왜 두개지
private Long ensureAccepted(InferenceSendDto dto) {
if (dto == null) {
log.warn("not InferenceSendDto dto");
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST);
}
// [중복]운영환경일때 경로수정 dean 260226
if (profile != null && profile.equals("prod")) {
log.info("========================================================");
log.info("[CHANGE INFERENCE] profile = {} Inforence req", profile);
log.info("========================================================");
log.info("");
}
// 1) 요청 로그
try {
log.debug("Inference request dto={}", objectMapper.writeValueAsString(dto));
} catch (JsonProcessingException e) {
log.warn("Failed to serialize inference dto", e);
}
// 2) local 환경 임시 처리
// if ("local".equals(profile)) {
// if (dto.getPred_requests_areas() == null) {
// throw new IllegalStateException("pred_requests_areas is null");
// }
//
// dto.getPred_requests_areas().setInput1_scene_path("/kamco-nfs/requests/2023_local.geojson");
//
// dto.getPred_requests_areas().setInput2_scene_path("/kamco-nfs/requests/2024_local.geojson");
// }
// 3) HTTP 호출
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
// 추론 실행 API 호출
ExternalCallResult<String> result =
externalHttpClient.call(inferenceUrl, HttpMethod.POST, dto, headers, String.class);
if (result.statusCode() < 200 || result.statusCode() >= 300) {
log.error("Inference API failed. status={}, body={}", result.statusCode(), result.body());
throw new CustomApiException("BAD_GATEWAY", HttpStatus.BAD_GATEWAY);
}
// 4) 응답 파싱
try {
List<Map<String, Object>> list =
objectMapper.readValue(result.body(), new TypeReference<>() {});
if (list.isEmpty()) {
throw new CustomApiException(
"NOT_FOUND", HttpStatus.NOT_FOUND, "Inference response is empty");
}
Object batchIdObj = list.get(0).get("batch_id");
if (batchIdObj == null) {
throw new CustomApiException(
"NOT_FOUND", HttpStatus.NOT_FOUND, "batch_id not found in response");
}
return Long.valueOf(batchIdObj.toString());
} catch (Exception e) {
log.error("Failed to parse inference response. body={}", result.body(), e);
throw new CustomApiException("INVALID_INFERENCE_RESPONSE", HttpStatus.BAD_GATEWAY);
}
}
/**
* 모델정보 조회 dto 생성 후 반환
*

View File

@@ -79,12 +79,13 @@ public class InferenceResultCoreService {
}
/**
* 변화탐지 실행 정보 생성
* 변화탐지 실행 정보 생성 - 추론 실행 목록 테이블 저장, 도엽목록별 상태 체크 테이블 저장
*
* @param req
* @param req 추론 실행 목록 uuid
*/
public UUID saveInferenceInfo(InferenceResultDto.RegReq req, List<MngListDto> targetList) {
// 대표 도엽명 외 N 건 실행 문구 만들기 위해 Null, 중복 제거
List<MngListDto> distinctList =
targetList.stream()
.filter(dto -> dto.getMapSheetName() != null && !dto.getMapSheetName().isBlank())
@@ -124,17 +125,13 @@ public class InferenceResultCoreService {
mapSheetLearnEntity.setDetectingCnt(0L);
mapSheetLearnEntity.setTotalJobs((long) targetList.size());
// 회차는 국유인 반영할때 update로 변경됨
// mapSheetLearnEntity.setStage(
// mapSheetLearnRepository.getLearnStage(req.getCompareYyyy(), req.getTargetYyyy()));
// learn 테이블 저장
MapSheetLearnEntity savedLearn = mapSheetLearnRepository.save(mapSheetLearnEntity);
final int CHUNK = 1000;
List<MapSheetLearn5kEntity> buffer = new ArrayList<>(CHUNK);
// learn 도엽별 저장
// learn 도엽별 저장, 도엽수가 많으므로 1000개 씩 저장함
for (MngListDto mngDto : targetList) {
MapSheetLearn5kEntity entity = new MapSheetLearn5kEntity();
entity.setLearn(savedLearn);
@@ -145,12 +142,15 @@ public class InferenceResultCoreService {
buffer.add(entity);
if (buffer.size() == CHUNK) {
// 도엽별 저장 learn 5k 테이블
flushChunk(buffer);
buffer.clear();
}
}
// chunk 남은거 처리
if (!buffer.isEmpty()) {
// 도엽별 저장 learn 5k 테이블
flushChunk(buffer);
buffer.clear();
}
@@ -159,9 +159,9 @@ public class InferenceResultCoreService {
}
/**
* 도엽별 저장
* 도엽별 저장 learn 5k 테이블
*
* @param buffer
* @param buffer 저장 정보
*/
private void flushChunk(List<MapSheetLearn5kEntity> buffer) {
@@ -422,7 +422,7 @@ public class InferenceResultCoreService {
/**
* 추론 진행중인지 확인
*
* @return
* @return 추론 실행중인 추론 uuid, batch id
*/
public SaveInferenceAiDto getProcessing() {
MapSheetLearnEntity entity = mapSheetLearnRepository.getProcessing();

View File

@@ -431,6 +431,12 @@ public class MapSheetMngCoreService {
return mapSheetMngYearRepository.findByHstMapSheetCompareList(mngYyyy, mapId);
}
/**
* 연도 조건으로 실행 가능 도엽번호 조회
*
* @param year 연도
* @return 추론 가능한 도엽 정보
*/
public List<String> getMapSheetNumByHst(Integer year) {
List<MapSheetMngHstEntity> entity = mapSheetMngRepository.getMapSheetMngHst(year);
return entity.stream().map(MapSheetMngHstEntity::getMapSheetNum).toList();

View File

@@ -65,10 +65,10 @@ public interface MapSheetMngRepositoryCustom {
List<MapSheetMngDto.MngFilesDto> findByHstUidMapSheetFileList(Long hstUid);
/**
* 변화탐지 실행 가능 기준 연도 조회
* 기준년도 추론 실행 가능 도 조회
*
* @param req 조회 연도, 도엽번호 목록,
* @return
* @return 실행 가능한 도엽번호
*/
List<MngListDto> findByHstMapSheetTargetList(InferenceResultDto.RegReq req);
@@ -88,6 +88,12 @@ public interface MapSheetMngRepositoryCustom {
void insertMapSheetMngTile(@Valid AddReq addReq);
/**
* 연도 조건으로 도엽번호 조회
*
* @param year 연도
* @return 추론 가능한 도엽 정보
*/
List<MapSheetMngHstEntity> getMapSheetMngHst(Integer year);
List<MapSheetFallbackYearDto> findFallbackCompareYearByMapSheets(

View File

@@ -572,12 +572,6 @@ public class MapSheetMngRepositoryImpl extends QuerydslRepositorySupport
return foundContent;
}
/**
* 기준년도 추론 실행 가능 도엽 조회
*
* @param req
* @return
*/
@Override
public List<MngListDto> findByHstMapSheetTargetList(InferenceResultDto.RegReq req) {
BooleanBuilder whereBuilder = new BooleanBuilder();
@@ -594,6 +588,7 @@ public class MapSheetMngRepositoryImpl extends QuerydslRepositorySupport
BooleanBuilder likeBuilder = new BooleanBuilder();
// 부분 선택 실행이면 도엽번호 검색조건 추가
if (MapSheetScope.PART.getId().equals(req.getMapSheetScope())) {
List<String> list = req.getMapSheetNum();
if (list == null || list.isEmpty()) {
@@ -604,6 +599,7 @@ public class MapSheetMngRepositoryImpl extends QuerydslRepositorySupport
if (prefix == null || prefix.isBlank()) {
continue;
}
// 50k 도엽번호로 Like 하여 5k 도엽번호 검색
likeBuilder.or(mapSheetMngHstEntity.mapSheetNum.like(prefix.trim() + "%"));
}
}

View File

@@ -1,9 +1,8 @@
package com.kamco.cd.kamcoback.scheduler.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kamco.cd.kamcoback.common.exception.CustomApiException;
import com.kamco.cd.kamcoback.common.inference.service.InferenceCommonService;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient;
import com.kamco.cd.kamcoback.config.resttemplate.ExternalHttpClient.ExternalCallResult;
import com.kamco.cd.kamcoback.inference.dto.InferenceDetailDto.InferenceBatchSheet;
@@ -19,7 +18,6 @@ import java.nio.file.Paths;
import java.time.ZonedDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
@@ -31,7 +29,6 @@ import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@@ -43,6 +40,7 @@ public class MapSheetInferenceJobService {
private final InferenceResultCoreService inferenceResultCoreService;
private final ShpPipelineService shpPipelineService;
private final InferenceCommonService inferenceCommonService;
private final ExternalHttpClient externalHttpClient;
private final ObjectMapper objectMapper;
@@ -357,7 +355,7 @@ public class MapSheetInferenceJobService {
m.setPriority(5d);
log.info("[BEFORE INFERENCE] BEFORE SendDto={}", m);
// 추론 실행 api 호출
Long batchId = ensureAccepted(m);
Long batchId = inferenceCommonService.ensureAccepted(m);
SaveInferenceAiDto saveInferenceAiDto = new SaveInferenceAiDto();
saveInferenceAiDto.setUuid(uuid);
@@ -369,73 +367,6 @@ public class MapSheetInferenceJobService {
inferenceResultCoreService.update(saveInferenceAiDto);
}
/**
* api 호출
*
* @param dto
* @return
*/
// 같은함수가 왜 두개지
private Long ensureAccepted(InferenceSendDto dto) {
if (dto == null) {
log.warn("not InferenceSendDto dto");
throw new CustomApiException("BAD_REQUEST", HttpStatus.BAD_REQUEST);
}
// 1) 요청 로그
log.info("");
log.info("========================================================");
log.info("[SEND INFERENCE] Inference request dto= {}", dto);
log.info("========================================================");
log.info("");
// 2) local 환경 임시 처리
// if ("local".equals(profile)) {
// if (dto.getPred_requests_areas() == null) {
// throw new IllegalStateException("pred_requests_areas is null");
// }
//
// dto.getPred_requests_areas().setInput1_scene_path("/kamco-nfs/requests/2023_local.geojson");
//
// dto.getPred_requests_areas().setInput2_scene_path("/kamco-nfs/requests/2024_local.geojson");
// }
// 3) HTTP 호출
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(List.of(MediaType.APPLICATION_JSON));
// TODO 어떤 URL로 어떤파리티러로 요청한 로딩해야지
ExternalCallResult<String> result =
externalHttpClient.call(inferenceUrl, HttpMethod.POST, dto, headers, String.class);
if (result.statusCode() < 200 || result.statusCode() >= 300) {
log.error("Inference API failed. status={}, body={}", result.statusCode(), result.body());
throw new CustomApiException("BAD_GATEWAY", HttpStatus.BAD_GATEWAY);
}
// 4) 응답 파싱
try {
List<Map<String, Object>> list =
objectMapper.readValue(result.body(), new TypeReference<>() {});
if (list.isEmpty()) {
// 어떤 URL로 어떤파리티러로 요청한 정보를 봐야 재현을 할듯하지요
throw new IllegalStateException("Inference response is empty");
}
Object batchIdObj = list.get(0).get("batch_id");
if (batchIdObj == null) {
throw new IllegalStateException("batch_id not found in response");
}
return Long.valueOf(batchIdObj.toString());
} catch (Exception e) {
log.error("Failed to parse inference response. body={}", result.body(), e);
throw new CustomApiException("INVALID_INFERENCE_RESPONSE", HttpStatus.BAD_GATEWAY);
}
}
/**
* 실행중인 profile
*