Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
WooilJeong committed Jan 13, 2023
1 parent acc46b6 commit eb52ac0
Show file tree
Hide file tree
Showing 29 changed files with 12,867 additions and 1,800 deletions.
12 changes: 10 additions & 2 deletions PyKakao/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@
from .config.info import __project__, __version__, __author__, __contact__, __github__

__all__ = [
"__project__", "__version__", "__author__", "__contact__", "__github__",
"__project__",
"__version__",
"__author__",
"__contact__",
"__github__",
"KakaoLocal",
"Local", "DaumSearch", "KoGPT", "Message",
"Local",
"DaumSearch",
"KoGPT",
"Karlo",
"Message",
]
155 changes: 155 additions & 0 deletions PyKakao/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import io
import json
import base64
import requests
import pandas as pd
from PIL import Image


class Message:
Expand Down Expand Up @@ -312,6 +315,158 @@ def generate(self, prompt, max_tokens, **kwargs):
return response.json


class Karlo:
"""
카카오 Karlo API 클래스
Parameters
----------
service_key : str
카카오 개발자 센터에서 발급받은 애플리케이션의 REST API 키
"""

def __init__(self, service_key=None):
self.service_key = service_key
self.headers = {"Authorization": f"KakaoAK {self.service_key}",
"Content-Type": "application/json"}

def text_to_image(self, text, batch_size=1):
"""
이미지 생성하기 API
Parameters
----------
text : str
생성할 이미지를 묘사하는 제시어, 영문만 지원(최대: 256자)
참고:
- 활용 가이드(https://developers.kakao.com/docs/latest/ko/karlo/how-to-use)
batch_size : int, optional
생성할 이미지 수(기본값: 1, 최대: 8)
Returns
-------
dict
생성된 이미지의 정보
"""
_url = "https://api.kakaobrain.com/v1/inference/karlo/t2i"
_json = {
"prompt": {
"text": text,
"batch_size": batch_size,
}
}
return requests.post(_url, json=_json, headers=self.headers).json()

def transform_image(self, image, batch_size=1):
"""
이미지 변환하기
Parameters
----------
image : str
변환할 원본 이미지를 Base64 인코딩한 값
참고:
- 이미지 파일 규격(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-image-requirement)
- 이미지 인코딩 및 디코딩(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-encode-and-decode)
batch_size : int, optional
생성할 이미지 수(기본값: 1, 최대: 8)
Returns
-------
dict
생성된 이미지의 정보
"""
_url = "https://api.kakaobrain.com/v1/inference/karlo/variations"
_json = {
"prompt": {
"image": image,
"batch_size": batch_size,
}
}
return requests.post(_url, json=_json, headers=self.headers).json()

def inpaint_image(self, image, mask, text="", batch_size=1):
"""
이미지 편집하기
Parameters
----------
image : str
원본 이미지를 Base64 인코딩한 값
참고:
- 이미지 파일 규격(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-image-requirement)
- 이미지 인코딩 및 디코딩(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-encode-and-decode)
mask : str
편집할 부분을 표시한 원본 이미지를 Base64 인코딩한 값
편집할 부분을 검은색(Grayscale, RGB 기준 0)으로 가려서 표시
이미지의 여러 곳 마스킹 가능
참고:
- 이미지 파일 규격(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-image-requirement)
- 이미지 인코딩 및 디코딩(https://developers.kakao.com/docs/latest/ko/karlo/rest-api#before-you-begin-encode-and-decode)
text : str, optional
편집해 넣을 이미지를 묘사하는 제시어, 영문만 지원(최대: 256자)
text 값이 설정되지 않으면 편집할 부분의 주변과 어울리도록 사물을 삭제하거나 대체함
(기본값: "", 빈 문자열)
참고:
- 활용 가이드(https://developers.kakao.com/docs/latest/ko/karlo/how-to-use)
batch_size : int, optional
생성할 이미지 수(기본값: 1, 최대: 8)
Returns
-------
dict
생성된 이미지의 정보
"""
_url = "https://api.kakaobrain.com/v1/inference/karlo/inpainting"
_json = {
"prompt": {
"image": image,
"mask": mask,
"text": text,
"batch_size": batch_size,
}
}
return requests.post(_url, json=_json, headers=self.headers).json()

def string_to_image(self, base64_string, mode='RGBA'):
"""
base64 string을 이미지로 변환
Parameters
----------
base64_string : str
base64 string
mode : str, optional
이미지 모드(기본값: RGBA)
Returns
-------
PIL.Image
이미지
"""
return Image.open(io.BytesIO(base64.b64decode(str(base64_string)))).convert(mode)

def image_to_string(self, img):
"""
이미지를 base64 string으로 변환
Parameters
----------
img : PIL.Image
이미지
Returns
-------
str
base64 string
"""
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format='PNG')
my_encoded_img = base64.encodebytes(
img_byte_arr.getvalue()).decode('ascii')
return my_encoded_img


class DaumSearch:
"""
카카오 다음 검색 API 클래스
Expand Down
4 changes: 2 additions & 2 deletions PyKakao/config/info.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__project__ = "PyKakao"
__version__ = "0.0.3"
__version__ = "0.0.4"
__author__ = "정우일(Wooil Jeong)"
__contact__ = "wooil@kakao.com"
__github__ = "https://github.com/WooilJeong/PyKakao"
__github__ = "https://github.com/WooilJeong/PyKakao"
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,56 @@ result = GPT.generate(prompt, max_tokens, temperature=0.7, top_p=0.8)

<br>

### Karlo API

Karlo API는 사용자가 입력한 문장과 이미지를 기반으로 새로운 이미지를 만드는 기능을 제공합니다. 생성형 인공지능(AI) Karlo는 1억 8천만 장 규모의 이미지-텍스트 학습을 통해 사용자가 묘사한 내용을 이해하고, 픽셀 단위로 완전히 새로운 이미지를 생성합니다. 또한 사용자가 원하는 콘셉트에 맞춰 창작 활동을 할 수 있도록 사물, 배경, 조명, 구도, 다양한 화풍을 지원합니다.

```python
from PyKakao import Karlo

# Karlo API 인스턴스 생성
api = Karlo(service_key)

## 이미지 생성하기

# 프롬프트에 사용할 제시어
text = "A white Christmas tree in a public square by Claude Monet, Christmas season, snowy night, light tone"
# 이미지 생성하기 REST API 호출
img_dict = api.text_to_image(text, 1)
# 생성된 이미지 정보
img_str = img_dict.get("images")[0].get('image')
# base64 string을 이미지로 변환
img = api.string_to_image(base64_string = img_str, mode = 'RGBA')

## 이미지 변환하기

# 이미지 파일 불러오기
img = Image.open('./original.png')
# 이미지를 Base64 인코딩하기
img_base64 = api.image_to_string(img)
# 이미지 변환하기 REST API 호출
response = api.transform_image(image = img_base64, batch_size=1)
# 응답의 첫 번째 이미지 생성 결과 출력하기
result = api.string_to_image(response.get("images")[0].get("image"), mode = 'RGB')

## 이미지 편집하기

# 이미지 파일 불러오기
img = Image.open('./original.png')
mask = Image.open('./mask.png')
# 이미지를 Base64 인코딩하기
img_base64 = api.image_to_string(img)
mask_base64 = api.image_to_string(mask)
# 프롬프트에 사용할 제시어
text = "Flowers"
# 이미지 변환하기 REST API 호출
response = api.inpaint_image(image = img_base64, mask = mask_base64, text = text, batch_size = 1)
# 응답의 첫 번째 이미지 생성 결과 출력하기
result = api.string_to_image(response.get("images")[0].get("image"), mode = 'RGB')
```

<br>

### 메시지 API

메시지 API는 사용자가 카카오톡 친구에게 카카오톡 메시지를 보내는 기능을 제공합니다. PyKakao의 최신 버전에서는 '나에게 보내기' 기능만 이용할 수 있습니다.
Expand Down
2 changes: 1 addition & 1 deletion docs/.buildinfo
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Sphinx build info version 1
# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
config: bf9301a534d5344c3bdb1a65f42172fe
config: 375a4ba3693f1be99c2fe546e8e69115
tags: 645f666f9bcd5a90fca523b33c5a78b7
18 changes: 10 additions & 8 deletions docs/PyKakao.config.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
<script data-url_root="./" id="documentation_options" src="_static/documentation_options.js"></script>
<script src="_static/jquery.js"></script>
<script src="_static/underscore.js"></script>
<script src="_static/_sphinx_javascript_frameworks_compat.js"></script>
<script src="_static/doctools.js"></script>
<script src="_static/sphinx_highlight.js"></script>
<script src="_static/translations.js"></script>
<script src="_static/js/theme.js"></script>
<link rel="index" title="색인" href="genindex.html" />
Expand Down Expand Up @@ -67,10 +69,10 @@
<div class="rst-content">
<div role="navigation" aria-label="Page navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html" class="icon icon-home"></a></li>
<li class="breadcrumb-item"><a href="modules.html">PyKakao</a></li>
<li class="breadcrumb-item"><a href="PyKakao.html">PyKakao package</a></li>
<li class="breadcrumb-item active">PyKakao.config package</li>
<li><a href="index.html" class="icon icon-home"></a> &raquo;</li>
<li><a href="modules.html">PyKakao</a> &raquo;</li>
<li><a href="PyKakao.html">PyKakao package</a> &raquo;</li>
<li>PyKakao.config package</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/PyKakao.config.rst.txt" rel="nofollow"> View page source</a>
</li>
Expand All @@ -81,15 +83,15 @@
<div itemprop="articleBody">

<section id="pykakao-config-package">
<h1>PyKakao.config package<a class="headerlink" href="#pykakao-config-package" title="표제에 대한 퍼머링크"></a></h1>
<h1>PyKakao.config package<a class="headerlink" href="#pykakao-config-package" title="제목에 대한 퍼머링크"></a></h1>
<section id="submodules">
<h2>Submodules<a class="headerlink" href="#submodules" title="표제에 대한 퍼머링크"></a></h2>
<h2>Submodules<a class="headerlink" href="#submodules" title="제목에 대한 퍼머링크"></a></h2>
</section>
<section id="module-PyKakao.config.info">
<span id="pykakao-config-info-module"></span><h2>PyKakao.config.info module<a class="headerlink" href="#module-PyKakao.config.info" title="표제에 대한 퍼머링크"></a></h2>
<span id="pykakao-config-info-module"></span><h2>PyKakao.config.info module<a class="headerlink" href="#module-PyKakao.config.info" title="제목에 대한 퍼머링크"></a></h2>
</section>
<section id="module-PyKakao.config">
<span id="module-contents"></span><h2>Module contents<a class="headerlink" href="#module-PyKakao.config" title="표제에 대한 퍼머링크"></a></h2>
<span id="module-contents"></span><h2>Module contents<a class="headerlink" href="#module-PyKakao.config" title="제목에 대한 퍼머링크"></a></h2>
</section>
</section>

Expand Down
Loading

0 comments on commit eb52ac0

Please sign in to comment.