기존 서비스의 문제점
- 프로젝트 초기 DALLE3선택 이유
여행 일정기반 AI코디북 생성 기능을 제공하는 웹 서비스를 진행했었다. 하지만 해당 기능의 문제점은 과도한 옵션과 시간을 잡아먹는 점이다. 싸피에서 프로젝트 진행시 제공받은 gpt key를 이용해 API를 사용했고 DALLE2와 3고민중 2가 프롬프트 내용을 적용을 잘 못시키고 매번 결과물이 이상하게 나왔기 때문에 DALLE3을 선택했었다. 문제는 DALLE3는 cfg_scale, steps와 같은 해상도 직접 조정 불가능하다. 따라서 OpenAI가 미리 정의한 최적의 설정에 의존한다.
- 과도한 시간 소비
해당 여행 일정 날씨 + 코디북 이미지 + 여행 준비물이 나오는 시간은 무려 27~28초. 사용자가 열받기 충분한 시간이다. 따라서 다른 이미지 AI모델을 찾아봤다.
Stable Diffusion 도입기
Stable Diffsuion 소개
텍스트나 이미지를 기반으로 새로운 이미지를 생성하는 기술, 로컬 환경 또는 클라우드 API를 통해 활용할 수 있다.
- Local 설치 방식 vs API 사용 방식 차이
1. Local 특징
- 커스터마이징 가능: cfg_scale, steps, seed등 세부 옵션 조정 가능
- 서버 비용이 무료라면 서비스도 무료! 아 물론 본인 서버 아니면 비용듬
- 하드웨어 제약: GPU가 없는 경우 속도 느림
2. 클라우드 API 특징
- 초기 설치 없이 API 호출만으로 사용 가능
- GPU, 서버와 같은 하드웨어 부담없음
- 비용 문제: API 호출 수와 생성 이미지에 따라 증가
- 선택한 방식: Stability AI API
- 소규모 프로젝트 서비스에 AWS에서 GPU 인스턴스를 사용하는 EC2 비용을 지불하기에는 과도한 예산
- Spring AI와의 연결성
Local 설치 및 테스트
- 본 API를 사용하기 전에 프롬프트 무료로 연습겸 Local에 별도로 설치 및 테스트 진행
- 2개 사이트 선택 및 진행
Stable Diffusion: Automatic 1111 설치 및 활용 가이드
Stable Diffusion: Automatic 1111 설치 및 활용 가이드
서론Stable Diffusion은 텍스트에서 이미지를 생성하는 강력한 도구로, 창의적 프로젝트에 널리 사용되고 있습니다. 이 가이드에서는 Windows, Mac, Ubuntu 환경에서 Stable Diffusion을 설치하고 활용하는 방
pointer81.tistory.com
GitHub - AUTOMATIC1111/stable-diffusion-webui: Stable Diffusion web UI
GitHub - AUTOMATIC1111/stable-diffusion-webui: Stable Diffusion web UI
Stable Diffusion web UI. Contribute to AUTOMATIC1111/stable-diffusion-webui development by creating an account on GitHub.
github.com
- 설치 및 실행
- 일단은 해당 링크로 들어가서 다운로드 받은 후 실행하면 된다
- 참고로 python 라이브러리 버전 하나하나에 영향을 많이 받는것 같아 requirements.txt의 버전을 참고해서 업데이트 하면 된다.
python --version #python 버전 확인
cd path/to/stable-diffusion-webui
python -m venv venv
venv\Scripts\activate #가상환경 돌입
pip install -r requirements.txt #의존성 설치
deactivate #가상환경 빠져나오기
테스트 결과
1. 높은 옵션을 줄 경우(약 2분 소요)
2. 낮은 옵션 줄경우, 장당 5초내 생성
3. 프롬프트 수정 및 결과물
A high-resolution image divided into three equal vertical rectangles, each representing a day of a trip. Each section contains a flat-lay arrangement of clothing and accessories based on weather and location. No text or unnecessary background, only neatly arranged clothing and accessories for each day.
- Day 1: Clothing and accessories for cloudy weather at 10°C / 5°C with 2mm precipitation. Includes a waterproof jacket, thermal pants, hiking boots, lightweight scarf, gloves, and a small umbrella. Representing the activities at 광안리 SUP Zone, 미포, 해동 용궁사.
- Day 2: Clothing and accessories for sunny weather at 12°C / 6°C with no precipitation. Includes casual wear: jeans, a light sweater, sneakers, sunglasses, and a small backpack. Representing the activities at 태종사, 국제시장, 송도용궁구름다리.
- Day 3: Clothing and accessories for cloudy weather at 11°C / 7°C with 3mm precipitation. Includes a raincoat, a warm sweater, comfortable walking shoes, and a crossbody bag. Representing the activities at 감천문화마을, 자갈치시장, 부산타워.
Minimalistic flat-lay style with no background or human figures. Clean and modern design.
Stable Diffusion API 사용 및 연결 테스트 코드 작성
Springboot AI로 진행
properties
# Stability AI image model configuration, key는 추후 secret으로 이전해서 commit
spring.ai.stabilityai.api-key=
spring.ai.stabilityai.base-url=https://api.stability.ai/v1
spring.ai.stabilityai.image.enabled=true
spring.ai.stabilityai.image.option.n=1
spring.ai.stabilityai.image.option.width=512
spring.ai.stabilityai.image.option.height=512
spring.ai.stabilityai.image.option.model=stable-diffusion-v1-6
spring.ai.stabilityai.image.option.responseFormat=image/png
AIController
@RestController
@RequiredArgsConstructor
@RequestMapping("/ai")
public class AIController {
private final StabilityAiImageModel stabilityAiImageModel;
@GetMapping("/image")
public ResponseEntity<byte[]> generateImage(
@RequestParam(value = "prompt", defaultValue = "You are an AI stylist helping a user plan a trip wardrobe. Create outfits suitable for a 2-day trip to Busan. Day 1: Rainy, 20°C, visiting a market. Day 2: Sunny, 17°C, visiting a beach. Focus on clothing only. Backgrounds are not required.") String prompt) {
ImageResponse response = stabilityAiImageModel.call(
new ImagePrompt(prompt,
StabilityAiImageOptions.builder()
.withSamples(1) // 생성 image 개수
.withHeight(512)
.withWidth(512)
.withCfgScale(9f)
.withSteps(20)
.withResponseFormat("image/png") // Response format
.build()));
//이미지 데이터 가져오기
Image image = response.getResult().getOutput();
if (image == null) {
return ResponseEntity.badRequest().body(null);
}
byte[] imageBytes;
if (image.getB64Json() != null) {
// Base64 데이터를 디코딩 -> 여기서 s3 또는 redis를 통한 이미지 관리가 필요할듯함
imageBytes = Base64.getDecoder().decode(image.getB64Json());
} else if (image.getUrl() != null) {
// URL이 제공된 경우 에러 또는 별도 처리 (예: URL로부터 데이터를 다운로드)
return ResponseEntity.badRequest()
.body(null); // URL 기반 처리는 필요에 따라 구현
} else {
return ResponseEntity.badRequest().body(null); // 유효한 이미지 데이터가 없음
}
// 반환된 이미지를 클라이언트로 전달
return ResponseEntity.ok()
.header("Content-Type", "image/png")
.body(imageBytes);
}
}
Test API 작성 및 결과
- 1.6버전 사용(legacy버전이지만 장당 0.9credit, 즉 10원)
- stability api: prompt 영어만 사용가능(한국어 → 영어 변경 필요), 관련 내용은 타 게시물에 등록
https://developerjisu.tistory.com/133
[API] 번역 API: DeepL 사용 및 Java 코드를 통한 적용
번역 API 도입 및 사용번역 API 사용 및 선정 이유(DeepL API 사용)번역 API 종류1. DeepL API Free특징:REST API 형식으로 제공되며, 한 달에 최대 500,000자 무료 번역 가능.고품질 번역을 제공하며, JSON
developerjisu.tistory.com
코드에 적용 및 결과(28초 -> 8초)
- 초기 dalle3 테스트, 약 28초
- Stable Diffusion 적용, 약 11초
- 비동기 적용, 약 8초
실제 페이지 결과물
출처
Stable Diffusion: Automatic 1111 설치 및 활용 가이드
GitHub - AUTOMATIC1111/stable-diffusion-webui: Stable Diffusion web UI
'스프링' 카테고리의 다른 글
AWS S3와 IAM 생성: 스프링과의 연동 방법 및 이미지 저장 (0) | 2024.03.20 |
---|---|
[Spring] Validation 종류 및 적용 (0) | 2024.03.15 |
[스프링] 스프링 3.1이후에 디버그 로그가 안뜰경우, 로그레벨 조정 방법 (0) | 2024.01.29 |
[스프링] 혼자 구현하는 웹 서비스1: 프로젝트 세팅 (0) | 2024.01.08 |
Google Drive API를 활용한 이미지 업로드 및 Url반환(스프링 서비스단계 구현) (0) | 2023.08.26 |