save code

This commit is contained in:
colomi
2025-07-11 22:10:56 +08:00
parent 8de064f43e
commit 4ca55230e8
6 changed files with 1758 additions and 55 deletions
+168 -18
View File
@@ -5,6 +5,13 @@ from flask import Flask, request, jsonify
from urllib.parse import urlparse
from volcenginesdkarkruntime import Ark
import json
import base64
import time
from PIL import Image
from datetime import datetime
APP_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_FOLDER = os.path.join(APP_ROOT, 'static')
app = Flask(__name__)
@@ -102,6 +109,48 @@ def save_image_from_url(image_url):
print(f"Error saving image from URL: {e}")
return None
def change(human_name, cloth_name, c_width, c_height):
with open('/home/szlc/code/ComfyUI/change_cloth/change_new.json', 'r', encoding='utf-8') as file:
prompt_text = file.read()
prompt = json.loads(prompt_text)
prompt["99"]["inputs"]["width"] = int((c_width/c_height) * 1024)
#input cloth img
prompt["22"]["inputs"]["image"] = cloth_name
#input human img
prompt["61"]["inputs"]["image"] = human_name
#out put name
out_img_name = str(uuid.uuid4())[:8]
prompt["102"]["inputs"]["filename_prefix"] = out_img_name
p = {"prompt": prompt}
data = json.dumps(p).encode('utf-8')
response = requests.post("http://localhost:8188/prompt", data=data)
prompt_id = response.json()["prompt_id"]
# 2. 轮询队列,直到任务完成
while True:
queue = requests.get("http://localhost:8188/queue").json()
# print(queue)
if not queue["queue_running"] and not queue["queue_pending"]:
break # 队列为空,任务已完成
time.sleep(0.5) # 避免频繁请求
# 3. 从历史记录中获取结果
history = requests.get("http://localhost:8188/history").json()
print("History:", history)
outputs = history[prompt_id]["outputs"]
for out in outputs:
if out_img_name in out:
return out
@app.route('/change_cloth', methods=['POST'])
def change_cloth():
"""从 URL 下载图片"""
@@ -128,27 +177,128 @@ def change_cloth():
return jsonify({"filename": cloth_filename})
@app.route('/upload_image', methods=['POST'])
def upload_image():
"""直接上传图片(保留原始格式)"""
if 'file' not in request.files:
return jsonify({"error": "No file uploaded"}), 400
def save_base64_image(base64_str, prefix):
"""
将base64字符串保存为图片文件
:param base64_str: 带有类型标识的base64字符串
:param prefix: 文件名前缀
:return: 保存的文件路径
"""
try:
# 分离base64头部和实际数据
header, data = base64_str.split(',', 1)
# 从头部获取文件扩展名
file_ext = ''
if 'image/png' in header:
file_ext = '.png'
elif 'image/jpeg' in header:
file_ext = '.jpg'
elif 'image/jpg' in header:
file_ext = '.jpg'
elif 'image/gif' in header:
file_ext = '.gif'
else:
file_ext = '.png' # 默认使用png
# 生成唯一文件名
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
unique_id = str(uuid.uuid4())[:8]
filename = f"{prefix}_{timestamp}_{unique_id}{file_ext}"
filepath = os.path.join('/home/szlc/code/ComfyUI/change_cloth/static', filename)
# 解码并保存图片
with open(filepath, 'wb') as f:
f.write(base64.b64decode(data))
file = request.files['file']
if file.filename == '':
return jsonify({"error": "Empty filename"}), 400
input_filepath = os.path.join('/home/szlc/code/ComfyUI/input', filename)
# 解码并保存图片
with open(input_filepath, 'wb') as f:
f.write(base64.b64decode(data))
return filename
except Exception as e:
print(f"Error saving image: {str(e)}")
return None
def get_image_dimensions(image_path):
try:
with Image.open(image_path) as img:
width, height = img.size
return width, height
except Exception as e:
print(f"Error: {e}")
return None
def image_to_base64(file_path, mime_type=None):
if mime_type is None:
extension = file_path.split('.')[-1].lower()
mime_types = {
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'png': 'image/png',
'gif': 'image/gif',
'webp': 'image/webp',
'bmp': 'image/bmp'
}
mime_type = mime_types.get(extension, 'application/octet-stream')
# 读取文件内容并编码为Base64
with open(file_path, 'rb') as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
# 组合成Data URI格式
return f"data:{mime_type};base64,{encoded_string}"
# 获取原始文件扩展名
ext = os.path.splitext(file.filename)[1].lower()
if not ext: # 如果无扩展名,默认 PNG
ext = '.png'
@app.route('/change_cloth_base64', methods=['POST'])
def change_cloth_base64():
# 获取参数
data = request.get_json()
if not data:
return jsonify({"ret":-1,'msg': 'No JSON data provided'}), 400
human_img = data.get('human_img')
cloth_img = data.get('cloth_img')
output_format = data.get('output_format')
if not human_img or not cloth_img:
return jsonify({"ret":-1, 'msg': 'Both human_img and cloth_img are required'}), 400
try:
# 保存人像图片
human_filename = save_base64_image(human_img, 'human')
if not human_filename:
return jsonify({"ret":-1, 'msg': 'Failed to save human image'}), 500
# 保存服装图片
cloth_filename = save_base64_image(cloth_img, 'cloth')
if not cloth_filename:
return jsonify({"ret":-1, 'msg': 'Failed to save cloth image'}), 500
w,h = get_image_dimensions(f'/home/szlc/code/ComfyUI/input/{human_filename}')
# 生成唯一文件名(保留原始格式)
filename = f"{uuid.uuid4()}{ext}"
save_path = os.path.join(COMFYUI_INPUT_DIR, filename)
out_put_name = change(human_filename, cloth_filename, w, h)
image = Image.open(f'/home/szlc/code/ComfyUI/output/{out_put_name}')
jpg_name = out_put_name.replace(".png", ".jpg")
jpg_path_name = f'/home/szlc/code/ComfyUI/change_cloth/static/{jpg_name}'
image.save(jpg_path_name, quality=95)
file.save(save_path)
return jsonify({"filename": filename})
if 'base64' in output_format:
return jsonify({
"ret":0,
"msg":"success",
"data":image_to_base64(jpg_path_name)
})
else:
return jsonify({
"ret":0,
"msg":"success",
"url":f"http://112.126.94.241:18018/static/{jpg_name}"
})
except Exception as e:
return jsonify({"ret":-1, 'error': str(e)}), 500
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000, debug=True)
app.run(host="0.0.0.0", port=8018, debug=True)