안녕하세요. 스프링 부트 기반으로 karlo를 사용해보려고하는데
다음과같은 에러가 뜹니다.
{“code”:-401,“msg”:“kapi: invalid token”}"
해결방법을 알수 있을까요? 감사합니다.
package com.emiary.service;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import javax.imageio.ImageIO;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class ImageGenerationService {
private final String REST_API_KEY = "${api키는 이곳에 넣음}";
private final String T2I_URL = "https://api.kakaobrain.com/v1/inference/karlo/t2i";
public BufferedImage generateImage(String text) throws IOException {
log.debug("이미지 서비스 들어옴 {}",text);
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "KakaoAK " + REST_API_KEY);
headers.setContentType(MediaType.APPLICATION_JSON);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(Collections.singletonMap("prompt",
Collections.singletonMap("text", text)));
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(T2I_URL, HttpMethod.POST, requestEntity, String.class);
String responseJson = responseEntity.getBody();
ObjectMapper mapper = new ObjectMapper();
ImageResponse response = mapper.readValue(responseJson, ImageResponse.class);
String base64ImageString = response.getImages().get(0).getImage();
byte[] decodedBytes = Base64.getDecoder().decode(base64ImageString);
ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes);
return ImageIO.read(bis);
}
private static class ImageResponse {
private java.util.List<ImageData> images;
public java.util.List<ImageData> getImages() {
return images;
}
public void setImages(java.util.List<ImageData> images) {
this.images = images;
}
}
private static class ImageData {
private String image;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
}