edit : bing art 추가
This commit is contained in:
@@ -13,12 +13,10 @@ RESTful API Server
|
|||||||
```
|
```
|
||||||
https://cloud.google.com/sdk/docs/install?hl=ko#linux
|
https://cloud.google.com/sdk/docs/install?hl=ko#linux
|
||||||
```
|
```
|
||||||
### bing image creator
|
### cookie
|
||||||
쿠키정보 get
|
|
||||||
```
|
```
|
||||||
https://github.com/acheong08/BingImageCreator
|
https://github.com/acheong08/BingImageCreator
|
||||||
```
|
```
|
||||||
|
|
||||||
### notice
|
### notice
|
||||||
const.py 에 지정한 OUTPUT_FOLDER 하위에
|
const.py 에 지정한 OUTPUT_FOLDER 하위폴더에 이미지 저장됨.
|
||||||
imagen, dalle 폴더가 있어야함.
|
|
||||||
2
const.py
2
const.py
@@ -1,3 +1,3 @@
|
|||||||
OUTPUT_FOLDER = "/home/fermat/project/fermat_test/FM_TEST_REST_SERVER/output"
|
OUTPUT_FOLDER = "./output"
|
||||||
|
|
||||||
ILLEGAL_FILE_NAME = ['<', '>', ':', '"', '/', '\ ', '|', '?', '*']
|
ILLEGAL_FILE_NAME = ['<', '>', ':', '"', '/', '\ ', '|', '?', '*']
|
||||||
81
custom_apps/bingart/bingart.py
Normal file
81
custom_apps/bingart/bingart.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
import urllib.request
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
from bingart import BingArt
|
||||||
|
|
||||||
|
from custom_apps.utils import cookie_manager
|
||||||
|
from rest.app.utils.parsing_utils import prompt_to_filenames
|
||||||
|
from rest.app.utils.date_utils import D
|
||||||
|
from const import OUTPUT_FOLDER
|
||||||
|
|
||||||
|
|
||||||
|
class BingArtGenerator:
|
||||||
|
|
||||||
|
model = 'dalle3'
|
||||||
|
detail = 'art'
|
||||||
|
output_folder = os.path.join(OUTPUT_FOLDER,"dalle","art")
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.bing_art = BingArt(auth_cookie_U=cookie_manager.get_cookie())
|
||||||
|
self.prompt = ''
|
||||||
|
self.datetime = D.date_file_name()
|
||||||
|
Path(self.output_folder).mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
def get_image_links(self, prompt, image_len:int):
|
||||||
|
"""
|
||||||
|
이미지 url값 생성
|
||||||
|
"""
|
||||||
|
results = None
|
||||||
|
try:
|
||||||
|
self.prompt = prompt_to_filenames(prompt)
|
||||||
|
results = self.bing_art.generate_images(prompt)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
self.bing_art.close_session()
|
||||||
|
|
||||||
|
if results == None:
|
||||||
|
raise Exception("result is null")
|
||||||
|
|
||||||
|
images = results.get("images")
|
||||||
|
|
||||||
|
if images != None:
|
||||||
|
_temp = []
|
||||||
|
for i in images:
|
||||||
|
_temp.append(i.get('url'))
|
||||||
|
images = _temp
|
||||||
|
|
||||||
|
#중복제거
|
||||||
|
images = list(set(_temp))
|
||||||
|
|
||||||
|
if len(images) < image_len:
|
||||||
|
return images[0:len(images)]
|
||||||
|
else:
|
||||||
|
return images[0:image_len]
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def link_to_img(self, img_links:list):
|
||||||
|
"""
|
||||||
|
이미지 링크로 이미지 파일 저장
|
||||||
|
"""
|
||||||
|
jpeg_index = 1
|
||||||
|
|
||||||
|
if img_links == None:
|
||||||
|
raise Exception("result is null")
|
||||||
|
|
||||||
|
for i in img_links:
|
||||||
|
path= f"{self.model}_{self.detail}_{self.prompt}_{jpeg_index}_{self.datetime}.png"
|
||||||
|
|
||||||
|
urllib.request.urlretrieve(i, os.path.join(self.output_folder,path))
|
||||||
|
jpeg_index += 1
|
||||||
|
|
||||||
|
def get_images(self, prompt, image_len):
|
||||||
|
image_links = self.get_image_links(prompt,image_len)
|
||||||
|
|
||||||
|
if image_links == None:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
else:
|
||||||
|
self.link_to_img(img_links=image_links)
|
||||||
|
return len(image_links)
|
||||||
|
|
||||||
@@ -1,28 +1,11 @@
|
|||||||
import nest_asyncio
|
import nest_asyncio
|
||||||
import os
|
import os
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from custom_apps.dalle3.BingImageCreator import *
|
from custom_apps.bingimagecreator.BingImageCreator import *
|
||||||
from const import OUTPUT_FOLDER
|
from const import OUTPUT_FOLDER
|
||||||
|
from custom_apps.utils import cookie_manager
|
||||||
|
|
||||||
class CookieManager:
|
|
||||||
|
|
||||||
DEFAULT_COOKIE = "15yugVy08XGWEWtpv2SW7-mG_0HsBxbDyBFQDdnKEEK6c-XkjYt4HOk6G_5wY4npT0yKB9yEbl76i7RB5CM_HocUZ-nIOIseVMFVPkg-aTeA82BrEjVSh6ohZaz3rUk9Lw0NpDCV60Mn8s4nyQo8vSZJDlsqVEYXklSyKbEbnrtLPNcXUY5gl9Fmjz5Lxr1CMiBr8ogt3UvmWUBYDA-b4-6SEranbD_2wY_KSVN0djJg"
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.cookie = self.DEFAULT_COOKIE
|
|
||||||
|
|
||||||
def get_cookie(self):
|
|
||||||
if not self.cookie:
|
|
||||||
raise
|
|
||||||
else:
|
|
||||||
return self.cookie
|
|
||||||
|
|
||||||
def set_cookie(self,new_cookie):
|
|
||||||
self.cookie = new_cookie
|
|
||||||
|
|
||||||
cookie_manager = CookieManager()
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -41,7 +24,7 @@ class DallEArgument:
|
|||||||
U = cookie_manager.get_cookie()
|
U = cookie_manager.get_cookie()
|
||||||
prompt: str
|
prompt: str
|
||||||
cookie_file: str|None = None
|
cookie_file: str|None = None
|
||||||
output_dir: str = os.path.join(OUTPUT_FOLDER,"dalle")
|
output_dir: str = os.path.join(OUTPUT_FOLDER,"dalle","img")
|
||||||
download_count: int = 1
|
download_count: int = 1
|
||||||
debug_file: str|None = None
|
debug_file: str|None = None
|
||||||
quiet: bool = False
|
quiet: bool = False
|
||||||
@@ -81,8 +64,7 @@ def dalle3_generate_image(args):
|
|||||||
|
|
||||||
counter = Counter()
|
counter = Counter()
|
||||||
|
|
||||||
if not os.path.isdir(args.output_dir):
|
Path(args.output_dir).mkdir(parents=True, exist_ok=True)
|
||||||
raise FileExistsError(f"FileExistsError: {args.output_dir}")
|
|
||||||
|
|
||||||
if args.version:
|
if args.version:
|
||||||
print(pkg_resources.get_distribution("BingImageCreator").version)
|
print(pkg_resources.get_distribution("BingImageCreator").version)
|
||||||
1
custom_apps/dalle3/const.py
Normal file
1
custom_apps/dalle3/const.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
API_KEY = "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"
|
||||||
20
custom_apps/dalle3/main.py
Normal file
20
custom_apps/dalle3/main.py
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import os
|
||||||
|
from openai import OpenAI
|
||||||
|
# from custom_apps.dalle3.const import API_KEY
|
||||||
|
|
||||||
|
#set api key
|
||||||
|
# os.environ['OPENAI_API_KEY'] = "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"
|
||||||
|
|
||||||
|
os.environ['OPENAI_API_KEY'] = "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"
|
||||||
|
|
||||||
|
client = OpenAI()
|
||||||
|
|
||||||
|
response = client.images.generate(
|
||||||
|
model="dall-e-2",
|
||||||
|
prompt="a white siamese cat",
|
||||||
|
size="512x512",
|
||||||
|
quality="standard",
|
||||||
|
n=1,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(response.data[0].url)
|
||||||
17
custom_apps/utils.py
Normal file
17
custom_apps/utils.py
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
class CookieManager:
|
||||||
|
|
||||||
|
DEFAULT_COOKIE = "19S_ux18UhHzxHMsY5gTYwqk2YjYahwxssgJyx0AybuAjDa_kZKWFauqMSrtb1a80s89VjmLwKWIGhvpZxLOzkwcMXAuShkgFwGSVlD8ayI7qgQiCabE9-UFByw4QJ_ZSAnOnskn5iPydk4vaZZEayTR--u7-mVglsaANK6rGOQPeu8q-Sa6cjVCUQR9kkjEtz-J4wf2MQ6inXuC41IbCi8QwmZyHkwxOy6U6CqPiREg"
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.cookie = self.DEFAULT_COOKIE
|
||||||
|
|
||||||
|
def get_cookie(self):
|
||||||
|
if not self.cookie:
|
||||||
|
raise
|
||||||
|
else:
|
||||||
|
return self.cookie
|
||||||
|
|
||||||
|
def set_cookie(self,new_cookie):
|
||||||
|
self.cookie = new_cookie
|
||||||
|
|
||||||
|
cookie_manager = CookieManager()
|
||||||
@@ -17,9 +17,15 @@ email-validator
|
|||||||
google-cloud-aiplatform
|
google-cloud-aiplatform
|
||||||
Pillow
|
Pillow
|
||||||
|
|
||||||
#DALL-E 3
|
#bing img
|
||||||
aiohttp
|
aiohttp
|
||||||
regex
|
regex
|
||||||
requests
|
requests
|
||||||
httpx
|
httpx
|
||||||
nest_asyncio
|
nest_asyncio
|
||||||
|
|
||||||
|
#bing art
|
||||||
|
bingart==1.10
|
||||||
|
|
||||||
|
#DALL-E 3
|
||||||
|
# openai
|
||||||
@@ -573,6 +573,13 @@ class ImageGenerateReq(BaseModel):
|
|||||||
prompt : str = Field(description='프롬프트', example='검은색 안경')
|
prompt : str = Field(description='프롬프트', example='검은색 안경')
|
||||||
downloadCount : int = Field(1, description='이미지 생성 갯수', example=1)
|
downloadCount : int = Field(1, description='이미지 생성 갯수', example=1)
|
||||||
|
|
||||||
|
|
||||||
|
class BingCookieSetReq(BaseModel):
|
||||||
|
"""
|
||||||
|
### [Request] bing cookie set
|
||||||
|
"""
|
||||||
|
cookie : str = Field('',description='쿠키 데이터', example='')
|
||||||
|
|
||||||
|
|
||||||
#===============================================================================
|
#===============================================================================
|
||||||
#===============================================================================
|
#===============================================================================
|
||||||
@@ -598,4 +605,26 @@ class ImageGenerateRes(ResponseBase):
|
|||||||
ImageGenerateRes.result = True
|
ImageGenerateRes.result = True
|
||||||
ImageGenerateRes.error = None
|
ImageGenerateRes.error = None
|
||||||
ImageGenerateRes.imageLen = img_len
|
ImageGenerateRes.imageLen = img_len
|
||||||
return ImageGenerateRes
|
return ImageGenerateRes
|
||||||
|
|
||||||
|
|
||||||
|
class BingCookieSetRes(ResponseBase):
|
||||||
|
"""
|
||||||
|
### bing cookie set response
|
||||||
|
"""
|
||||||
|
currentCookie : str = Field('',description='현재 사용중인 쿠키 정보', example='')
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def set_error(error,current_cookie=''):
|
||||||
|
BingCookieSetRes.result = False
|
||||||
|
BingCookieSetRes.error = str(error)
|
||||||
|
BingCookieSetRes.currentCookie = current_cookie
|
||||||
|
|
||||||
|
return BingCookieSetRes
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def set_message(current_cookie):
|
||||||
|
BingCookieSetRes.result = True
|
||||||
|
BingCookieSetRes.error = None
|
||||||
|
BingCookieSetRes.currentCookie = current_cookie
|
||||||
|
return BingCookieSetRes
|
||||||
@@ -19,26 +19,51 @@ from rest.app import models as M
|
|||||||
from rest.app.utils.date_utils import D
|
from rest.app.utils.date_utils import D
|
||||||
from custom_logger.custom_log import custom_logger as LOG
|
from custom_logger.custom_log import custom_logger as LOG
|
||||||
|
|
||||||
from custom_apps.dalle3.custom_dalle import DallEArgument,dalle3_generate_image
|
from custom_apps.bingimagecreator.utils import DallEArgument,dalle3_generate_image
|
||||||
|
from custom_apps.bingart.bingart import BingArtGenerator
|
||||||
from custom_apps.imagen.custom_imagen import imagen_generate_image
|
from custom_apps.imagen.custom_imagen import imagen_generate_image
|
||||||
from rest.app.utils.parsing_utils import download_range
|
from rest.app.utils.parsing_utils import download_range
|
||||||
|
from custom_apps.utils import cookie_manager
|
||||||
|
|
||||||
router = APIRouter(prefix="/services")
|
router = APIRouter(prefix="/services")
|
||||||
|
|
||||||
|
@router.post("/bing/cookie/set", summary="bing 관련 쿠키 set", response_model=M.BingCookieSetRes)
|
||||||
@router.post("/imageGenerate/dalle3", summary="이미지 생성(AI) - DALL-E 3", response_model=M.ImageGenerateRes)
|
async def bing_cookie_set(request: Request, request_body_info: M.BingCookieSetReq):
|
||||||
async def dalle3(request: Request, request_body_info: M.ImageGenerateReq):
|
|
||||||
"""
|
"""
|
||||||
## 이미지 생성(AI) - DALL-E 3
|
## Bing cookie set
|
||||||
> DALL-E 3 AI를 이용하여 이미지 생성
|
> 쿠키정보 set
|
||||||
|
|
||||||
|
## 정보
|
||||||
|
> cookie 값이 빈 값일경우 쿠키정보를 set 하지 않고 현재 쿠키값 return 함
|
||||||
|
> cookie 값이 정상 쿠키 인지는 확인안함
|
||||||
|
|
||||||
|
"""
|
||||||
|
response = M.BingCookieSetRes()
|
||||||
|
try:
|
||||||
|
if len(request_body_info.cookie) == 0:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
cookie_manager.set_cookie(request_body_info.cookie)
|
||||||
|
|
||||||
|
return response.set_message(current_cookie=cookie_manager.get_cookie())
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
LOG.error(traceback.format_exc())
|
||||||
|
return response.set_error(e,current_cookie=cookie_manager.get_cookie())
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/imageGenerate/bingimg", summary="이미지 생성(AI) - bing image generator (DALL-E 3)", response_model=M.ImageGenerateRes)
|
||||||
|
async def bing_img_generate(request: Request, request_body_info: M.ImageGenerateReq):
|
||||||
|
"""
|
||||||
|
## 이미지 생성(AI) - bing image generator (DALL-E 3)
|
||||||
|
> bing image generator를 이용하여 이미지 생성
|
||||||
|
|
||||||
### Requriements
|
### Requriements
|
||||||
> - 쿠키 정보 설정(https://github.com/acheong08/BingImageCreator) 추후 set api 추가 예정 -> 현재 고정값
|
|
||||||
> - const.py 에 지정한 OUTPUT_FOLDER 하위에 dalle 폴더가 있어야함.
|
|
||||||
|
|
||||||
## 정보
|
## 정보
|
||||||
> 오류 발생시 오류 발생한 파일은 에러 메세지에만 남기고 저장은 안함
|
> 오류 발생시 오류 발생한 파일은 에러 메세지에만 남기고 저장은 안함
|
||||||
|
> *동작 안함.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
response = M.ImageGenerateRes()
|
response = M.ImageGenerateRes()
|
||||||
@@ -66,6 +91,36 @@ async def dalle3(request: Request, request_body_info: M.ImageGenerateReq):
|
|||||||
return response.set_error(e)
|
return response.set_error(e)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/imageGenerate/bingart", summary="이미지 생성(AI) - bing art (DALL-E 3)", response_model=M.ImageGenerateRes)
|
||||||
|
async def bing_art(request: Request, request_body_info: M.ImageGenerateReq):
|
||||||
|
"""
|
||||||
|
## 이미지 생성(AI) - bing art (DALL-E 3)
|
||||||
|
> bing art를 이용하여 이미지 생성
|
||||||
|
|
||||||
|
### Requriements
|
||||||
|
|
||||||
|
|
||||||
|
## 정보
|
||||||
|
> 오류 발생시 오류 발생한 파일은 에러 메세지에만 남기고 저장은 안함
|
||||||
|
> *동작 안함.
|
||||||
|
|
||||||
|
"""
|
||||||
|
response = M.ImageGenerateRes()
|
||||||
|
try:
|
||||||
|
if not download_range(request_body_info.downloadCount):
|
||||||
|
raise Exception(f"downloadCount is 1~4 (current value = {request_body_info.downloadCount})")
|
||||||
|
|
||||||
|
bing_art = BingArtGenerator()
|
||||||
|
|
||||||
|
info = bing_art.get_images(prompt=request_body_info.prompt,image_len=request_body_info.downloadCount)
|
||||||
|
|
||||||
|
return response.set_message(img_len=info)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
LOG.error(traceback.format_exc())
|
||||||
|
return response.set_error(e)
|
||||||
|
|
||||||
|
|
||||||
@router.post("/imageGenerate/imagen", summary="이미지 생성(AI) - imagen", response_model=M.ImageGenerateRes)
|
@router.post("/imageGenerate/imagen", summary="이미지 생성(AI) - imagen", response_model=M.ImageGenerateRes)
|
||||||
async def imagen(request: Request, request_body_info: M.ImageGenerateReq):
|
async def imagen(request: Request, request_body_info: M.ImageGenerateReq):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ def prompt_to_filenames(prompt):
|
|||||||
return filename
|
return filename
|
||||||
|
|
||||||
|
|
||||||
def download_range(download_count:int):
|
def download_range(download_count:int,max=4):
|
||||||
_min = 1
|
_min = 1
|
||||||
_max = 4
|
_max = max
|
||||||
|
|
||||||
if _min <= download_count and download_count <= _max:
|
if _min <= download_count and download_count <= _max:
|
||||||
return True
|
return True
|
||||||
|
|||||||
Reference in New Issue
Block a user