Stable Diffusion 이 무엇인지는 대부분 알기 때문에 이 글을 보고 계신다고 생각하니, 일단 Stable Diffusion 에 대한 소개는 건너뛰고 가보겠습니다. 이 부분은 나중에 아주 자세히 글을 한번 올려보겠습니다.

 

Colab 은 무엇인가

 Google Colab은 구글이 제공하는 클라우드 기반의 무료 Jupyter Notebook 환경입니다. 주로 파이썬 라이브러리를 사용하여 데이터 분석 및 머신러닝 모델링 등 다양한 작업을 할 수 있습니다.

사용자가 자신의 브라우저에서 코드를 실행하고 실행 결과를 확인할 있으며 사용자는 Google Drive에 데이터를 업로드하고, 해당 데이터를 Colab에서 로드하여 분석에 활용할 수 있습니다. 또한, Colab은 GPU나 TPU와 같은 하드웨어 가속기를 제공하여, 대용량 데이터셋의 학습을 더 빠르게 처리할 수 있습니다.

또한 Colab 의 Notebook 은 마크다운과 코드 셀 등 다양한 셀 유형을 지원하며, 코드 셀에서는 파이썬 코드를 실행할 수 있고, 다양한 라이브러리와 모듈이 많이 설치되어있습니다.

중요한것은 이러한 환경이 무료로 제공되며, 구글 계정으로 로그인만 하면 바로 사용할 수 있습니다. 이래서 Google Colab 은 저처럼 가난한 GPU 서버 없는 사용자가 AI Model 을 테스트 하거나 하기에 Google신이 내려준 축복같은 선물이라고 보면 되겠습니다.

 

어떻게 Colab 에 설치해야 하나

 네 Colab 에 "설치" 한다는 개념은 사실 딱 맞는 개념은 아니고요, Colab 에 Jupyter 노트북을 만들어서 그 노트북에서 Shell Script 및 Python Script를 실행시켜 필요한 File 들을 VM 에 설치하게 하고 (VM 은 Command Shell 로 접근이 안됩니다) Python 으로 개발된 Web UI 가 실행되어 Browser 로 Web UI 서버를 접근하게 하는 형태입니다.

 일단은 아래 URL 로 접근해봅니다.

https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Online-Services

Web UI 를 개발한 AUTOMATIC1111 이라는 개발자의 Github 내의 Wiki 인데, 여기에 보면 Google Colab, Paperspace, SageMaker 용 Jupyter 노트북용 스크립트들의 Link 가 있습니다

이 중 밑줄의 camenduru 라는 사람의 노트북을 써보기로 하겠습니다. camenduru 의 Github README 아랫쪽으로 스크롤 하다보면 아래와 같은 Link 들이 있습니다.

여러 Model 들이 preset 된 Jupyter script 들이 있는데요,

이중 저걸 설치해보겠습니다. 

링크를 클릭하면 CIVITAI (AI 생성 모델 과 모델로 부터 생성한 이미지들을 공유하는 사이트) 나 Huggin Face 커뮤니티 사이트(딥러닝 모델 및 데이터셋 공유 커뮤니티)로 연결 되니 대략 어떤 모델인지를 확인해볼 수 있습니다.

대략 확인했으면, 파란색 Link 가 아닌 좌측의 "stable" 이라고 되어있는 이미지 버튼을 누릅니다.

그러면, 실제 Colab 용 Jupyter 노트북으로 이동합니다. 저 노트북을 공유한 사람의 노트북인것이죠.

그리고 저 박스 안의 "Drive로 복사" 버튼을 눌러 나의 Google Drive 로 복사를 해줍니다. 

그러면 이제 복사가 완료되었을 것이고 바로 나의 Colab 으로 오게 됩니다.

 

이제 이 노트북을 실행시킬 VM 을 연결해주는 작업을 합니다. 아래 처럼 화면 우측 상단의 "연결" 을 눌러봅니다.

아래 처럼 할당된 리소스가 나오거나, 만약 연결한적이 없다면 런타임 유형을 선택하라고 나오는데 여기에서 "GPU" 를 선택하시면 됩니다.

만약 런타임 유형 선택 화면이 안나오면, 화면 하단의 "런타임 유형 변경" 을 누르시면 됩니다.

이제 Script 의 좌측 Play 버튼을 눌러서 실행시키면 됩니다

 

설치 후 첫 실행

 좀전에 실행시킨 스크립트창 하단에 보면 아래와 같은데 보일겁니다.

저 링크들이 Colab 에서 실행된 Web UI 서버로 접근할 수 있는 URL 입니다. 이중 클릭 해서 접속 되는 URL 로 들어가보시면 됩니다

접속이 잘 되었다면, 

prompt 란에 대략 내가 생성하고 싶은 이미지의 키워드들을 떠올려 넣어보시고, 필요하다면 바로 아래의 Nagative Prompt 에도 포함되면 안되는 요소의 키워드들을 넣어봅니다. 

그리고 저 빨간색 Generate 버튼을 누르면 시간이 흘러 image 가 생성 되고,  

하단의 Save 버튼을 누르면, 파일 이름이 그 밑의 목록에 추가 되고 "Download" 버튼을 통해 해당 이미지를 다운로드 받을 수 있습니다.

만약 Batch 로 생성(다음에 더 설명 예정입니다)하거나 하여 여러 이미지가 나왔다면 "Zip" 을 선택하여 모든 이미지들을 Zip 으로 묶어 다운로드 받을 수도 있습니다.

 

결론

 집에 사양 좋은 Windows Notebook 이 있어서 (NVIDIA 칩 GPU 있는) Local 에서 설치해서 사용하려 했으나 역시나 요구사양대로 4GB 이상의 VRAM 이 아닌 1GB 의 VRAM 노트북이라 실행이 불가했기에 Colab 에서 설치하고 실행하는 방법만 우선 올려봅니다.

 앞으로 여러 모델을 활용하고 다양한 파라미터들을 조작해서 내가 원하는 이미지들에 최대한 근접한 이미지를 만들어가는 방법도 올려보겠습니다. 

 또 다른 기술들과 접목을 하거나 유튜버들이 이야기하는 돈벌기 부업이 정말 되는지도 검증해보고, 다른 Generative AI 서비스나 도구들도 사용해보면서 다양한 컨텐츠를 만들어볼까 생각합니다. 응원 플리즈~

... 

그나저나 camenduru 의 README 를 보다보니 좀 암울한 얘기가 있네요.. 조만간 Stable Diffusion Web UI 사용이 Colab 에서 불가능할수도 있겠네요. Colab 팀이 Stable Diffusion Web UI 를 사람들이 너무 많이 돌려서 GPU 가 터질것 같은데 팀에 예산이 없어.. 조만간 뭔가 조치가 취해질 수 있다는 얘기네요.. 

반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

Colab 으로 띄우는게 너무 시간도 오래 걸리고 이것저것 만져보고싶은 생각에 Windows PC 에 설치를 하려 했으나 실패했다.

설치는 매우 간단하지만, 설치 후 SD(Stable Diffusion) 실행 시 VRAM 에 Model 을 올리는것 같은데 VRAM 이 1GB 인 내 노트북이 역시나 실행 최소환경 요건에 맞지 않았다.ㅠㅠ

OutOfMemoryError.. 이럴수가.. OTL

어쩔 수 없이 Colab 으로 가야하는가보다

반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

 Spring Security 에 OAuth 2 모듈이 있는걸 알고 있지만 OAuth 로 SSO 서버를 구현해보지는 않았기에 chatGPT 에게 물어봤다


Q > Springboot 의 OAuth 를 활용해 SSO 구현 가능하니?

A > ChatGPT 는 당근 가능하다고 하며 TMI 로 아래처럼 얘기를 붙여준다

 

OAuth 정의 

OAuth는 사용자 자격 증명을 공개하지 않고 보호된 서버에서 사용자 자원에 대한 제3자 응용 프로그램의 액세스를 허용하는 인증 프레임 워크입니다. 최신 웹 애플리케이션 및 API에서 인증 및 권한 부여에 자주 사용됩니다.

Spring Boot는 웹 애플리케이션 및 API를 구축하기위한 인기있는 Java 기반 프레임 워크로서 OAuth를 지원하기 위한 다양한 도구 및 라이브러리를 제공합니다.

Spring Boot를 사용하여 OAuth를 이용한 SSO를 구현하려면 Spring Security 프레임 워크를 사용할 수 있습니다. Spring Security는 OAuth 인증 및 권한 부여를 지원하는 내장 기능을 제공합니다. Spring Security를 구성하여 Google이나 Facebook과 같은 OAuth 공급자를 신원 공급자로 사용하도록 설정할 수 있습니다.

다음은 Spring Boot를 사용하여 OAuth를 이용한 SSO를 구현하는 일반적인 단계입니다.

  1. 새로운 Spring Boot 애플리케이션을 만들거나 기존 애플리케이션을 수정하여 Spring Security를 사용합니다.
  2. Google이나 Facebook과 같은 OAuth 공급자를 선택하고 클라이언트 ID 및 클라이언트 비밀번호를 얻기 위해 공급자에 애플리케이션을 등록합니다.
  3. Spring Security를 구성하여 OAuth 공급자를 신원 공급자로 사용하도록 설정합니다.
  4. OAuth 인증 흐름을 처리하는 필요한 컨트롤러 엔드 포인트 및 사용자 인터페이스를 구현합니다.
  5. 사용자가 인증되면 세션 또는 토큰에 사용자 자격 증명을 저장하여 여러 애플리케이션에서 SSO를 활성화합니다.

Spring Boot를 사용하여 OAuth를 이용한 SSO를 구현하는 방법에 대한 자습서, 가이드 및 샘플 코드를 포함한 많은 온라인 자료가 있습니다. Spring Security 문서는 OAuth 인증 및 권한 부여를 구성하는 방법에 대한 자세한 정보를 제공하는 좋은 출발점입니다.


추가질문

이번에도 나의 질문이 조금 부족했음을 느낀다 나는 SSO Server 를 구현하는 방법을 물어보고 싶었는데, SSO 구현방법을 물어봤다.

다시 수정해서 물어보고 Springboot 기반의 Sample Code 도 달라고 요청했다

 

Q >  역시나 친절하게도 아래처럼 대답해준다 

 

First, you would need to add the necessary dependencies to your pom.xml file:

<dependencies>
    <!-- Spring Security OAuth2 dependencies -->
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.4.0</version>
    </dependency>
    
    <!-- Spring Boot dependencies -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.6.2</version>
    </dependency>
</dependencies>

Next, you would need to configure the OAuth2 server in your Spring Boot application. Here is an example configuration class:

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
 
    @Autowired
    private AuthenticationManager authenticationManager;
 
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
            .withClient("client1")
            .secret("secret1")
            .authorizedGrantTypes("authorization_code")
            .scopes("read")
            .redirectUris("http://localhost:8081/login/oauth2/code/client1")
            .and()
            .withClient("client2")
            .secret("secret2")
            .authorizedGrantTypes("authorization_code")
            .scopes("read")
            .redirectUris("http://localhost:8082/login/oauth2/code/client2");
    }
 
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
    }
 
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.checkTokenAccess("isAuthenticated()");
    }
}

In this example configuration class, we are configuring two clients ("client1" and "client2") with different credentials and redirect URIs. We are also specifying that the clients are authorized to use the "authorization_code" grant type with the "read" scope. Finally, we are specifying that the AuthenticationManager should be used to authenticate clients and users.

You would also need to configure your Spring Boot application to use Spring Security for authentication. Here is an example WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/oauth/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic()
            .and()
            .csrf().disable();
    }
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("user1")
            .password("{noop}password1")
            .roles("USER")
            .and()
            .withUser("user2")
            .password("{noop}password2")
            .roles("USER");
    }
 
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
 
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

In this example WebSecurityConfigurerAdapter, we are configuring Spring Security to permit all requests to the "/oauth" endpoint and to require authentication for all other requests. We are also configuring an in-memory UserDetailsService with two users and their passwords,

 

반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,

오늘 열심히 새로운 프로젝트를 위한 분석설계 작업을 하던 중 옆 동료들과 잠시 머리도 식힐겸 이야기를 하다가 연동 시스템에서 HTTP 요청 시 Spring Boot 기반의 Multi Instance 서버들이 해당 요청을 Broadcast 받은 것 처럼 각 Instance 의 State 들을 업데이트 해야 하는 요건이 생겨 논의하고 있다는걸 알게 되었다.

머리 식히러 왔어서 자리를 피하고 싶었으나.. 최소한의 Effort 로 구현하고 싶고, Message Broker 나 Redis 같은 IMDB, Zookeper 등을 사용하지 않았으면 좋겠다 하고, NoSQL DB 로 MongoDB 를 사용하고 있으나 DB Polling 으로 인해 부하를 주고싶지 않다고 하고..

잠시 생각하던 중 MongoDB 에서 Collection 의 변경이 일어나면 이 이벤트를 Listen 할 수 있는 기능이 생각나서 해당 기능을 사용해서 구현해보는게 어떤가 이야기 했다.

말이 나온김에 ChatGPT 를 통해 Sample Code 를 만들어 보라 시켜봤다.

GPT write a pub sub example springboot java code using mongodb


ChatGPT 놈의 조언

Here is an example of a basic implementation of the publish-subscribe pattern in a Spring Boot application using MongoDB as the message broker:

@Service
public class PublisherService {
    private final MongoTemplate mongoTemplate;

    @Autowired
    public PublisherService(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    public void publishMessage(String message) {
        mongoTemplate.save(new Message(message));
    }
}

@Document
class Message {
    private String message;

    public Message(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

@Service
public class SubscriberService {
    private final MongoTemplate mongoTemplate;

    @Autowired
    public SubscriberService(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    @PostConstruct
    public void subscribe() {
        mongoTemplate.getDb().getCollection("message").watch().forEach((Consumer<ChangeStreamDocument<Document>>) changeStreamDocument -> {
            Message message = mongoTemplate.getConverter().read(Message.class, changeStreamDocument.getFullDocument());
            System.out.println("Received message: " + message.getMessage());
        });
    }
}

이녀석 초반에는 무늬만 pub sub 같은 코드를 내놓더니만 몇번 심도있는(?) 대화를 해주고 난 이후에는 Collection 의 watch() 로 ChangeStreamDocument 를 사용해 Event 를 Listen 하는 제대로 되어보이는 코드를 내어준다. 한번 테스트 해보자.

 

테스트 코드

package mongo.account;

import lombok.Getter;
import lombok.Setter;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Getter
@Setter
@Document(collection = "account")
public class Account {
    @Id
    private String id;
    private String userName;
    private String email;
}
@Repository
public interface AccountRepository extends MongoRepository<Account, String> {
    Account findAccountByUserName(String userName);
    List<Account> findAccountsByUserName(String userName);

    @Query(value = "distinct('userName')", fields = "userName")
    List<String> findDistinct();
}
@Service
@RequiredArgsConstructor
@Slf4j
public class AccountSubscriber {
    private final MongoTemplate mongoTemplate;

    @PostConstruct
    public void subscribe() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                log.info("Registering Subscriber");
                mongoTemplate.getDb().getCollection("account").watch()
                        .forEach((Consumer<ChangeStreamDocument<Document>>) changeStreamDocument -> {
                            Account account = mongoTemplate.getConverter().read(Account.class, changeStreamDocument.getFullDocument());
                            log.info("[{}] userName : {}", changeStreamDocument.getOperationType(), account!=null?account.getUserName():null);
                        });
                log.info("Subscriber Registered");
            }
        });
        t.start();
    }
}
@Bean
    @Order(1)
    public ApplicationRunner applicationRunner() {
        return args -> {
            Account account = new Account();
            account.setUserName("joon");
            account.setEmail("abcdef@naver.com");

            accountRepository.insert(account);
            log.info("Done");

            List<Account> result = accountRepository.findAccountsByUserName("joon");
            log.info("result 1 : {}", result.size());


            // .... 생략 ...

            accountRepository.deleteAll();

        };
    }

 

실행결과

 

오늘도 chatGPT 가 나름 참고할만한 코드를 잘 만들어주었다. 

물론 그대로 갖다 붙여넣는다고 원하는 동작을 하지는 못한다 (뭐 이러면 개발자 죽어야지..). watch() 에서 blocking 되기땜에 thread 로 빼주는 코드를 추가해주는 센스까지는 아직 chatGPT 가 못내주기는 하다마는 그래도 이게 어디냐..

구글링 해서 찾을수도 있지만 chatGPT 를 썼을 때에는 좀더 "덜 읽어도" 된다는게 좋은것 같다

반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,
요즘 ChatGPT 와 시간내서 노는게 참 재미있다. 이제야 SF 영화에서 보던 AI 라고 할 수 있을만한게 나온것 같다는 생각이 든다.

 작년부터 회사에서 AICC 솔루션 얘기가 나오고 있었다. SWA 시절 부터 Aka*** 회사에서의 Solutions Architect 시절 등 나야 솔루션을 만들거나 거대한 솔루션을 각종 업무 도메인과 각색의 아키텍쳐를 갖는 시스템들과 연계하던 경험이 있으나 현재 소속해있는 우리 팀은 사실 솔루션에 대한 경험이 있는 사람이 적고 그나마 이번 프로젝트에 involve 된 사람은 전무한 상황이다.

 나도 서비스 개발을 지속하다 보니 예전 솔루션 개발 방법론까지 Tailoring 해가며 개발해왔던 경험도 기억이 가물한 상황에서 술한잔 먹고 chatGPT 와 대화를 해봤다.

 우리회사에 AI 기술은 있으나, 이걸 AICC 솔루션으로 만들기 위해 우리에게 필요한게 뭐가 있을까?  기특한 GPT 가 답을 해준다.


If you and your team have experience with AI technologies but have not built an AI-powered contact center solution before, there are a few things you may need to consider:

  1. Domain expertise: Having a deep understanding of the domain of contact center operations will be important to ensure that your solution addresses the specific needs of your customers and meets the requirements of your business.
  2. Business understanding: A good understanding of the business side of contact center operations will be important to ensure that your solution is cost-effective, scalable, and able to integrate with existing systems and processes.
  3. Project management skills: Building an AI-powered contact center solution will likely be a complex and time-consuming project, so it will be important to have project management skills and experience to ensure that the project stays on track and meets its deadlines.
  4. Data expertise: Having experience working with large datasets and data science tools will be important for collecting, cleaning, and preparing data for training your models.
  5. Software development skills: Experience in software development will be important for designing and implementing the system, including the integration with existing systems, and creating an API to access the AI models.
  6. Support and maintenance: Building a robust and maintainable system is important, and that means having the capacity to support and maintain the system after it's deployed, this includes monitoring and fine-tuning the system to improve its performance and adapt it to new requirements.
  7. Legal and ethical considerations: As mentioned before, AI-based contact center solutions may raise legal and ethical concerns, such as data privacy and bias. It's important to consider these issues and take appropriate measures to mitigate them.
  8. User experience design: having a good understanding of user experience design will be important to make sure that the system is easy to use and understand, this will help to improve customer satisfaction.

Building an AI-powered contact center solution is not an easy task and will require a combination of skills and expertise from different areas. Depending on the specific needs of your solution, you may need to bring in additional experts or resources to help with the development.


이쁜녀석.. 이렇게 체계적으로 말을 잘 만들어서 대답을 해주니 얼마나 좋은가? 내가 CEO 이고 의사결정자라면 이녀석 참 쓸데가 많을것 같다.

1. 도메인 전문지식

솔루션이 고객의 특정 요구 사항을 해결하고 비즈니스 요구 사항을 충족하는지 확인하려면 컨택 센터 운영 도메인을 깊이 이해하는 것이 중요합니다.

2. 비즈니스 이해

솔루션이 비용 효율적이고 확장 가능하며 기존 시스템 및 프로세스와 통합될 수 있도록 하려면 컨택 센터 운영의 비즈니스 측면을 잘 이해하는 것이 중요합니다.

3. 프로젝트 관리 스킬

AI 기반 컨택 센터 솔루션을 구축하는 것은 복잡하고 시간이 많이 소요되는 프로젝트일 가능성이 높으므로 프로젝트가 순조롭게 진행되고 기한을 맞추도록 프로젝트 관리 기술과 경험을 갖추는 것이 중요합니다.

4. 데이터 전문성

대규모 데이터 세트 및 데이터 과학 도구로 작업한 경험이 있으면 모델 교육을 위해 데이터를 수집, 정리 및 준비하는 데 중요합니다.

5. Software 개발 스킬

소프트웨어 개발 경험은 기존 시스템과의 통합을 포함하여 시스템을 설계 및 구현하고 AI 모델에 액세스하기 위한 API를 만드는 데 중요합니다.

6. 지원과 유지보수

강력하고 유지 관리 가능한 시스템을 구축하는 것이 중요합니다. 즉, 배포 후 시스템을 지원하고 유지 관리할 수 있는 능력을 갖추는 것입니다. 여기에는 성능을 개선하고 새로운 요구 사항에 맞게 조정하기 위한 시스템 모니터링 및 미세 조정이 포함됩니다.

7. 법과 윤리 고려

앞서 언급한 바와 같이 AI 기반 컨택 센터 솔루션은 데이터 프라이버시 및 편견과 같은 법적 및 윤리적 문제를 제기할 수 있습니다. 이러한 문제를 고려하고 이를 완화하기 위한 적절한 조치를 취하는 것이 중요합니다.

8. UX 디자인

사용자 경험 디자인을 잘 이해하는 것은 시스템이 사용하기 쉽고 이해하기 쉬운지 확인하는 데 중요하며 이는 고객 만족도를 향상시키는 데 도움이 됩니다.

AI 기반 컨택 센터 솔루션을 구축하는 것은 쉬운 일이 아니며 다양한 분야의 기술과 전문 지식의 조합이 필요합니다. 솔루션의 특정 요구 사항에 따라 개발을 돕기 위해 추가 전문가 또는 리소스를 가져와야 할 수 있습니다.


딱 보면 일을 시작하기 전에 어떤 측면의 중요성을 상기하고 있어야 하는지 잘 짚어주었다. 물론 일반론적 이야기이긴 하겠지만 개발하기 전 설계나 솔루션 개발 및 이행 단계에서 고려해야 할 요소들을 정확히 짚어주지 않았나 싶다.

앞으로 OpenAI 의 GPT 가 상당히 기대된다!

반응형
블로그 이미지

Good Joon

IT Professionalist Since 1999

,