-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #67 from LlmKira/dev
feat: Director Tools / imagetools
- Loading branch information
Showing
40 changed files
with
1,608 additions
and
1,022 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
# -*- coding: utf-8 -*- | ||
# @Time : 2024/1/26 下午12:23 | ||
# @Author : sudoskys | ||
# @File : __init__.py.py | ||
# @Software: PyCharm | ||
import asyncio | ||
import os | ||
import pathlib | ||
|
||
from dotenv import load_dotenv | ||
from pydantic import SecretStr | ||
|
||
from novelai_python import APIError, LoginCredential, JwtCredential, ImageGenerateResp | ||
from novelai_python import AugmentImageInfer | ||
from novelai_python.sdk.ai.augment_image import ReqType | ||
|
||
|
||
async def generate( | ||
image, | ||
request_type: ReqType = ReqType.SKETCH, | ||
): | ||
jwt = os.getenv("NOVELAI_JWT", None) | ||
if jwt is None: | ||
raise ValueError("NOVELAI_JWT is not set in `.env` file, please create one and set it") | ||
credential = JwtCredential(jwt_token=SecretStr(jwt)) | ||
"""Or you can use the login credential to get the renewable jwt token""" | ||
_login_credential = LoginCredential( | ||
username=os.getenv("NOVELAI_USER"), | ||
password=SecretStr(os.getenv("NOVELAI_PASS")) | ||
) | ||
try: | ||
agent = AugmentImageInfer.build( | ||
req_type=request_type, | ||
image=image | ||
) | ||
# print(f"charge: {agent.calculate_cost(is_opus=True)} if you are vip3") | ||
# print(f"charge: {agent.calculate_cost(is_opus=False)} if you are not vip3") | ||
result = await agent.request( | ||
session=credential | ||
) | ||
except APIError as e: | ||
print(f"Error: {e.message}") | ||
return None | ||
else: | ||
print(f"Meta: {result.meta}") | ||
_res: ImageGenerateResp | ||
file = result.files[0] | ||
with open(f"{pathlib.Path(__file__).stem}.png", "wb") as f: | ||
f.write(file[1]) | ||
|
||
|
||
load_dotenv() | ||
loop = asyncio.new_event_loop() | ||
loop.run_until_complete( | ||
generate( | ||
image=pathlib.Path(__file__).parent / "static_image.png", | ||
request_type=ReqType.SKETCH | ||
) | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
import json | ||
|
||
import requests | ||
|
||
url = "https://image.novelai.net/ai/augment-image" | ||
|
||
payload = json.dumps({ | ||
"req_type": "bg-removal", | ||
"width": 1024, | ||
"height": 1024, | ||
"image": "iVBORw0" | ||
}) | ||
payload = json.dumps({ | ||
"req_type": "colorize", | ||
"prompt": "", | ||
"defry": 0, | ||
"width": 2252, | ||
"height": 465, | ||
"image": "iVBORw0KGgoAAA" | ||
}) | ||
payload = json.dumps({ | ||
"req_type": "lineart", | ||
"width": 2252, | ||
"height": 465, | ||
"image": "iVBO" | ||
}) | ||
payload = json.dumps({ | ||
"req_type": "sketch", | ||
"width": 2252, | ||
"height": 465, | ||
"image": "iVBOR" | ||
}) | ||
|
||
payload = json.dumps({ | ||
"req_type": "emotion", | ||
"prompt": "neutral;;123132", | ||
"defry": 0, | ||
"width": 2252, | ||
"height": 465, | ||
"image": "iVBORw0KG" | ||
}) | ||
payload = json.dumps({ | ||
"req_type": "declutter", | ||
"width": 2252, | ||
"height": 465, | ||
"image": "iVBORw0" | ||
}) | ||
APIKEY = "YOUR_API" | ||
|
||
headers = { | ||
'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36", | ||
'Accept-Encoding': "gzip, deflate, br, zstd", | ||
'Content-Type': "application/json", | ||
'authorization': f"Bearer {APIKEY}", | ||
'origin': "https://novelai.net", | ||
'priority': "u=1, i" | ||
} | ||
|
||
response = requests.post(url, data=payload, headers=headers) | ||
|
||
print(response.text) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
[project] | ||
name = "novelai-python" | ||
version = "0.4.11" | ||
version = "0.4.12" | ||
description = "NovelAI Python Binding With Pydantic" | ||
authors = [ | ||
{ name = "sudoskys", email = "[email protected]" }, | ||
|
Large diffs are not rendered by default.
Oops, something went wrong.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"req_type": "emotion", | ||
"prompt": "neutral;;", | ||
"defry": 0, | ||
"width": 1024, | ||
"height": 1024, | ||
"image": "Base64 Data" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
import base64 | ||
import json | ||
import pathlib | ||
from io import BytesIO | ||
|
||
from PIL import Image | ||
from loguru import logger | ||
|
||
|
||
def ignore(*args, **kwargs): | ||
pass | ||
|
||
|
||
def decode_base64_in_dict(data, current_path): | ||
if isinstance(data, dict): | ||
for k, v in data.items(): | ||
if isinstance(v, dict) or isinstance(v, list): | ||
decode_base64_in_dict(v, current_path) | ||
if isinstance(v, list): | ||
_new_list = [] | ||
for index, item in enumerate(v): | ||
if isinstance(item, str) and len(item) > 100: | ||
try: | ||
# Base64解码 | ||
image_bytes = base64.b64decode(item) | ||
image = Image.open(BytesIO(image_bytes)) | ||
except Exception as e: | ||
ignore(e) | ||
else: | ||
logger.info(f"Decoding Base64 data in {k}") | ||
img_name = f"{current_path}/{index}-{k}.png" | ||
image.save(img_name) | ||
_new_list.append('Base64 Data') | ||
if _new_list: | ||
data[k] = _new_list | ||
if isinstance(v, str) and len(v) > 100: | ||
try: | ||
# Base64解码 | ||
image_bytes = base64.b64decode(v) | ||
image = Image.open(BytesIO(image_bytes)) | ||
except Exception as e: | ||
ignore(e) | ||
else: | ||
logger.info(f"Decoding Base64 data in {k}") | ||
img_name = f"{current_path}/{k}.png" | ||
image.save(img_name) | ||
data[k] = 'Base64 Data' | ||
elif isinstance(data, list): | ||
for item in data: | ||
if isinstance(item, dict) or isinstance(item, list): | ||
decode_base64_in_dict(item, current_path) | ||
return data | ||
|
||
|
||
def handle_file(filename): | ||
filename_wo_ext = filename.stem | ||
pathlib.Path(filename_wo_ext).mkdir(parents=True, exist_ok=True) | ||
with open(filename, 'r') as file: | ||
json_data = json.load(file) | ||
# 取消 headers 里面 Authorization 字段,然后写回 | ||
if 'headers' in json_data: | ||
if 'Authorization' in json_data['headers']: | ||
json_data['headers']['Authorization'] = 'Secret' | ||
# 写回原文件 | ||
with open(filename, 'w') as file: | ||
json.dump(json_data, file, indent=2) | ||
if 'authorization' in json_data['headers']: | ||
json_data['headers']['authorization'] = 'Secret' | ||
# 写回原文件 | ||
with open(filename, 'w') as file: | ||
json.dump(json_data, file, indent=2) | ||
request_data = json.loads(json_data.get("body", "")) | ||
request_data = decode_base64_in_dict(request_data, filename_wo_ext) | ||
# 写出包含替换字段的 JSON 文件回同名的文件夹 | ||
with open(f"{filename_wo_ext}/schema.json", 'w') as jsonfile: | ||
json.dump(request_data, jsonfile, indent=2) | ||
|
||
|
||
def main(): | ||
# 列出当前文件夹内所有的 .json 文件 | ||
json_files = pathlib.Path('.').glob('*.json') | ||
for file in json_files: | ||
logger.info(f"Handling {file}") | ||
handle_file(file) | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.