Commit 0c6fc21c by wangfa

增加接口生成图片

parent d970d710
......@@ -8,4 +8,5 @@
/build
*.spec
*.zip
\ No newline at end of file
*.zip
salai/env.ini
\ No newline at end of file
import time
import uvicorn
from fastapi import FastAPI, Query, Body
from fastapi.middleware.cors import CORSMiddleware
from salai.mid_journey import MidJourney
from salai.helper import *
from loguru import logger
# logger.remove(handler_id=None)
# logger.add(sink='app.log', rotation="1 MB", retention='1 days', compression='zip', encoding='utf-8',
# enqueue=True)
app = FastAPI()
origins = [
"*"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
async def success(data=None, message: str = "success", time: float = 0):
data = {
"code": "200",
"message": message,
"data": data,
"time": time,
}
return data
async def error(data: dict = None, message: str = "error", time: float = 0):
data = {
"code": "400",
"message": message,
"data": data,
"time": time
}
return data
@app.post("/api/imagine")
async def imagine(data=Body(None)):
"""
获取用户资产
:param api_key:
:param api_secret:
:return:
"""
start_time = time.time()
data = data['data']
mid_journey = MidJourney(data['token'])
guild_id = data['guild_id']
channel_id = data['channel_id']
prompt = data['prompt']
error_message = ""
try:
response = await mid_journey.imagine(guild_id, channel_id, prompt)
if response.status >= 400:
error_message = "请求失败;请稍后再试"
else:
response = {
"message": "您的图像正在准备中,请稍等片刻..."
}
except Exception as e:
response = {}
use_time = time.time() - start_time
if response:
return await success(response, time=use_time)
else:
return await error(time=use_time, message=error_message)
@app.post("/api/download-image")
async def download_images(data=Body(None)):
start_time = time.time()
data = data['data']
url = data['url']
name = data['name']
error_message = ""
try:
response = await download_image(url, name)
except Exception as e:
print(e)
response = {}
use_time = time.time() - start_time
if response:
return await success(response, time=use_time)
else:
return await error(time=use_time, message=error_message)
if __name__ == '__main__':
uvicorn.run(host="0.0.0.0", app='app:app', port=9001, workers=5, reload=True)
import configparser
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
config.read(os.path.join(BASE_DIR, 'env.ini'))
DOWNLOAD_IMAGE_PATH = config.get('download', 'DOWNLOAD_IMAGE_PATH')
# oss配置
ACCESS_KEY_ID = config.get('oss', 'ACCESS_KEY_ID')
ACCESS_KEY_SECRET = config.get('oss', 'ACCESS_KEY_SECRET')
ENDPOINT = config.get('oss', 'ENDPOINT')
BUCKET_NAME = config.get('oss', 'BUCKET_NAME')
SAVE_PATH = config.get('oss', 'SAVE_PATH')
\ No newline at end of file
[download]
DOWNLOAD_IMAGE_PATH=
[oss]
ENDPOINT=
ACCESS_KEY_ID=
ACCESS_KEY_SECRET=
BUCKET_NAME=
SAVE_PATH=
\ No newline at end of file
from PIL import Image
import requests
import os
from salai.common_config import DOWNLOAD_IMAGE_PATH, ACCESS_KEY_ID, ACCESS_KEY_SECRET, ENDPOINT, BUCKET_NAME, SAVE_PATH
import hashlib
from oss2 import Auth, Bucket
def split_image(image_file):
"""
切割图片
"""
with Image.open(image_file) as im:
# Get the width and height of the original image
width, height = im.size
# Calculate the middle points along the horizontal and vertical axes
mid_x = width // 2
mid_y = height // 2
# Split the image into four equal parts
top_left = im.crop((0, 0, mid_x, mid_y))
top_right = im.crop((mid_x, 0, width, mid_y))
bottom_left = im.crop((0, mid_y, mid_x, height))
bottom_right = im.crop((mid_x, mid_y, width, height))
return top_left, top_right, bottom_left, bottom_right
def get_hash(name):
"""
获取图片的hash值
"""
md5 = hashlib.md5()
md5.update(name.encode('utf-8'))
return md5.hexdigest()
async def oss_upload(file_name, file_path):
"""
上传图片到阿里云oss
"""
auth = Auth(ACCESS_KEY_ID, ACCESS_KEY_SECRET)
bucket = Bucket(auth, ENDPOINT, BUCKET_NAME)
return bucket.put_object_from_file(file_name, file_path)
async def download_image(url, filename):
"""
下载图片
"""
r = requests.get(url)
r.raise_for_status()
# 打开一个文件作为文件对象
filename = get_hash(filename) + ".png"
path = f"{DOWNLOAD_IMAGE_PATH}{filename}"
with open(path, 'wb') as f:
f.write(r.content)
f.close()
top_left, top_right, bottom_left, bottom_right = split_image(path)
image_list = [top_left, top_right, bottom_left, bottom_right]
save_image_list = list()
number = 1
for image in image_list:
new_file_name = os.path.join(f"{DOWNLOAD_IMAGE_PATH}/{number}_{filename}")
image.save(new_file_name)
temp = {
"name": f"{number}_{filename}",
"path": new_file_name
}
save_image_list.append(temp)
number += 1
result = list()
for file in save_image_list:
save_name = f"{SAVE_PATH}/{file['name']}"
await oss_upload(save_name, file['path'])
save_name = "https://{}.{}/{}".format(BUCKET_NAME, ENDPOINT, save_name)
result.append(save_name)
return result
import aiohttp
class MidJourney:
def __init__(self, token):
self.token = token
self.headers = {
"authorization": self.token
}
async def imagine(self, guild_id: str, chanel_id: str, prompt: str):
"""
生成图片
:param guild_id: 服务器ID
:param chanel_id 频道ID
:param prompt 内容
:return:
"""
payload = {"type": 2, "application_id": "936929561302675456", "guild_id": guild_id,
"channel_id": chanel_id, "session_id": "2fb980f65e5c9a77c96ca01f2c242cf6",
"data": {"version": "1077969938624553050", "id": "938956540159881230", "name": "imagine", "type": 1,
"options": [{"type": 3, "name": "prompt", "value": prompt}],
"application_command": {"id": "938956540159881230",
"application_id": "936929561302675456",
"version": "1077969938624553050",
"default_permission": True,
"default_member_permissions": None,
"type": 1, "nsfw": False, "name": "imagine",
"description": "Create images with Midjourney",
"dm_permission": True,
"options": [{"type": 3, "name": "prompt",
"description": "The prompt to imagine",
"required": True}]},
"attachments": []}}
async with aiohttp.ClientSession() as session:
async with session.post(
"https://discord.com/api/v9/interactions",
headers=self.headers,
json=payload,
timeout=5,
allow_redirects=True
) as resp:
response = resp
return response
if __name__ == '__main__':
token = "MTA0MDkxMDY4NzgzODQyMTA2Mw.Gj2fzk.SvEdsuifUw9deKCbQaWGFs4j6alq3KTTsXGP3w"
mid_journey = MidJourney(token)
mid_journey.imagine('1095628793860857957', '1095628793860857960', 'this is a picture')
import discord
from discord.ext import commands
from loguru import logger
intents = discord.Intents.default()
intents.messages = True
client = commands.Bot(command_prefix='>', intents=intents)
DIRECTORY = "/www/wwwroot/salai"
INPUT_FOLDER = "input"
OUTPUT_FOLDER = "output"
@client.event
async def on_message(message):
message_data = {
"message_id": message.id,
"message_content": message.content,
"channel_id": message.channel.id,
"author_id": message.author.id,
"author_name": message.author.name,
"author_discriminator": message.author.discriminator,
"guild_id": message.guild.id,
"guild_name": message.guild.name,
}
logger.info(message_data)
for attachment in message.attachments:
if attachment.filename.lower().endswith((".png", ".jpg", ".jpeg", ".gif")):
message_data["attachment_url"] = attachment.url
message_data["attachment_filename"] = attachment.filename
logger.info(f"message 参数: {message_data}")
client.run("MTA5NTg4MzI5MzkyNjM3MTQ0OA.GUjqoM.8tFZ1phIIV-NO9l9sJqNPYuCbY8kjmZfyi48HA")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment