카테고리 없음

[👀 Owing] FLUX.1 AI로 이미지 생성하기

ming412 2024. 11. 8. 18:52

FLUX.1 AI란?

FLUX.1 AI는 FalAI에서 개발한 차세대 AI 이미지 생성 엔진으로, 텍스트를 기반으로 한 고품질 이미지 생성에 특화된 모델이다.

 

https://docs.fal.ai/

 

Documentation

Comprehensive documentation, examples, and guides for using fal.ai's AI infrastructure and client libraries.

docs.fal.ai

 

FLUX.1 AI 모델 특징

1) FLUX.1 Pro

FLUX.1 Pro는 FLUX의 최상위 모델로, 최첨단 성능의 이미지 생성과 뛰어난 프롬프트 처리를 제공한다. 시각적 품질이 우수하며, 이미지 세부 사항과 출력의 다양성 면에서도 탁월한 성능을 제공한다. FLUX.1 Pro 모델은 유료로 제공되며, 고품질의 결과물이 필요한 상용 프로젝트에 적합하다.

 

2) FLUX.1 Dev

FLUX.1 Dev는 비상업적 연구 및 개발을 위해 제공되는 오픈 가중치 모델이다. FLUX.1 Pro 모델을 증류하여 만든 버전으로, 유사한 품질과 프롬프트 처리 기능을 제공한다. 공식 사이트와 오픈 소스로 제공되며 모델 가중치는 HuggingFace에서 다운로드할 수 있다. 다만, 공식 사이트에서 모델을 사용하는 경우 유료 결제가 필요하며, 상업적 용도로의 사용은 제한된다.

 

3) FLUX.1 Schnell

FLUX.1 Schnell은 로컬 개발과 개인 사용을 위해 설계된 가장 빠른 모델이다. 고속 처리 성능을 갖추고 있어, 빠르게 반복 작업을 수행하거나 이미지 생성 기능을 테스트하고자 할 때 유용하다.

이번 프로젝트에서는 Schnell 모델을 선택했다. 그 이유는, 프로젝트에서 이미지 생성이 주로 작품의 표지 이미지나 세계관 이미지 제작에 사용되기 때문이다. 이러한 경우, 고품질보다는 빠른 속도가 더욱 중요하다고 판단했기 때문이다.

 

코드

공식문서를 참고해 구현했다.

 

`FalAiImageGenerator.java`

상황에 따라 OpenAi를 사용하기 위해 추상화하여 사용 (OpenAiImageGenerator도 있다.)

@Component("falAiImageGenerator")
@RequiredArgsConstructor
public class FalAiImageGenerator implements ImageGenerator {

	private final FalAiImageProperties falAiImageProperties;
	private FalClient falClient; // FalClient 인스턴스 선언

	// API 키 설정 및 FalClient 초기화
	@PostConstruct
	public void init() {
		this.falClient = FalClient.withConfig(
			ClientConfig.withCredentials(CredentialsResolver.fromApiKey(falAiImageProperties.apiKey()))
		);
	}
    
	public String generateImage(String prompt) {
		var input = Map.of(
			"prompt", prompt,
			"seed", 6252023,
			"image_size", "landscape_4_3",
			"num_images", 4
		);

		var result = falClient.subscribe(falAiImageProperties.model(),
			SubscribeOptions.<JsonObject>builder()
				.input(input)
				.logs(true)
				.resultType(JsonObject.class)
				.onQueueUpdate(update -> {
					if (update instanceof QueueStatus.InProgress) {
						System.out.println(((QueueStatus.InProgress)update).getLogs());
					}
				})
				.build()
		);
		return result.getData().toString();
	}
}

`ImageGeneratorConfig.java`

`imageGeneratorType` 필드는 기본적으로 `falAI`를 사용하도록 초기화되어 있고, 필요에 따라 이미지 생성기를 유연하게 사용할 수 있도록 작성했다.

@Configuration
public class ImageGeneratorConfig {

	private String imageGeneratorType = "falAI";

	@Bean
	public ImageGenerator imageGenerator(
		@Qualifier("openAiImageGenerator") ImageGenerator openAIImageGenerator,
		@Qualifier("falAiImageGenerator") ImageGenerator falAIImageGenerator) {

		if ("openAI".equalsIgnoreCase(imageGeneratorType)) {
			return openAIImageGenerator;
		} else if ("falAI".equalsIgnoreCase(imageGeneratorType)) {
			return falAIImageGenerator;
		} else {
			throw new IllegalArgumentException("지원되지 않는 이미지 생성 서비스: " + imageGeneratorType);
		}
	}
}

`application.yml`

발급받은 API KEY를 환경변수에 등록한다. 

spring:
  ai:
    fal:
      api-key: ${FAL_AI_KEY}
      model: fal-ai/flux/schnell

`FalAiImageProperties.java`

@ConfigurationProperties(prefix = "spring.ai.fal")
public record FalAiImageProperties(
	String apiKey,
	String model
) {
}

`UniverseService.java`

@Service
@RequiredArgsConstructor
public class UniverseService {

private final ImageGenerator imageGenerator;

	/**
	 * FalAI API 를 이용해 세계관 이미지를 생성하는 메서드
	 *
	 * @param universeSaveRequest 파일 생성 요청을 담은 DTO
	 * @return 생성된 이미지의 URL 을 ResponseEntity 로 반환
	 */
	@Transactional
	public ResponseEntity<ImageGenerateResponse> generateUniverseImage(UniverseSaveRequest universeSaveRequest) {

		String prompt = PromptUtils.createPrompt(universeSaveRequest);
		String url = imageGenerator.generateImage(prompt);

		ImageGenerateResponse response = ImageGenerateResponse.builder()
			.url(url)
			.build();

		return ResponseEntity.ok(response);
	}
}

 

호출 결과

동일한 프롬프트를 사용하여 Dev 모델과 Schnell 모델을 비교한 결과이다. Dev 모델은 약 9~10초의 시간이 소요되었고, Schnell 모델은 약 2~3초의 시간이 소요되었다.

 

프롬프트

A lively and playful scene of a cheerful golden retriever puppy and a mischievous tabby kitten playing together in a sunny backyard. 
The puppy is mid-pounce, with its floppy ears bouncing and a joyful expression on its face, while the kitten leaps gracefully, swiping a paw toward the puppy's wagging tail. 
The grass is lush and dotted with colorful flowers, and a few fallen leaves add an autumnal touch. In the background, there’s a wooden fence, a small garden bench, and a few scattered toys like a rubber ball and a yarn ball. 
The sunlight creates soft, warm highlights on the animals' fur, and their dynamic poses capture the energy of their playful interaction. 
The style is vibrant and realistic, emphasizing their fur textures and the motion of the scene.

 

FLUX.1 Dev 모델

생성 시간: 약 9~10초

 

FLUX.1 Schnell 모델

생성 시간: 약 2~3초

 

 

+ ) 241113 추가

OpenAI