change to url

This commit is contained in:
Your Name
2026-03-13 02:53:16 +00:00
parent 80404217aa
commit b04797fc2e
9 changed files with 139 additions and 27 deletions
+47 -8
View File
@@ -10,11 +10,14 @@ import asyncio
import base64
import io
import json
import os
import tempfile
import time
import uuid
from pathlib import Path
import httpx
import oss2
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
@@ -41,6 +44,28 @@ app.add_middleware(
)
def upload_to_oss(image_path, object_name=None):
access_key_id = 'LTAI5tGp1sLzedqxihcNC1eb'
access_key_secret = 'IFZE1b8YYreCP6zfA6GaZ9uBT678qO'
endpoint = 'oss-cn-beijing.aliyuncs.com'
bucket_name = 'xiangsilian'
auth = oss2.Auth(access_key_id, access_key_secret)
bucket = oss2.Bucket(auth, endpoint, bucket_name)
if object_name is None:
object_name = image_path.split('/')[-1]
try:
bucket.put_object_from_file(object_name, image_path)
url = bucket.sign_url('GET', object_name, 3600 * 24 * 365 * 10)
print(f"文件上传成功,URL: {url}")
return url
except Exception as e:
print(f"上传失败: {str(e)}")
return None
class TryOnRequest(BaseModel):
model_image: str # base64 模特图片
shirt_image: str # base64 上衣图片
@@ -48,7 +73,7 @@ class TryOnRequest(BaseModel):
class TryOnResponse(BaseModel):
result_image: str # base64 结果图片
result_url: str # OSS 图片 URL
def decode_base64_image(b64_str: str) -> bytes:
@@ -97,14 +122,12 @@ async def wait_for_result(client: httpx.AsyncClient, prompt_id: str, timeout: in
raise HTTPException(status_code=504, detail="等待 ComfyUI 超时(300秒)")
async def fetch_image_as_base64(client: httpx.AsyncClient, filename: str, subfolder: str = "", type_: str = "output") -> str:
"""从 ComfyUI 下载图片并编码为 base64"""
async def fetch_image_bytes(client: httpx.AsyncClient, filename: str, subfolder: str = "", type_: str = "output") -> bytes:
"""从 ComfyUI 下载图片,返回原始字节"""
params = {"filename": filename, "subfolder": subfolder, "type": type_}
resp = await client.get(f"{COMFYUI_URL}/view", params=params)
resp.raise_for_status()
content_type = resp.headers.get("content-type", "image/png")
b64 = base64.b64encode(resp.content).decode()
return f"data:{content_type};base64,{b64}"
return resp.content
@app.post("/try-on", response_model=TryOnResponse)
@@ -116,6 +139,7 @@ async def try_on(req: TryOnRequest):
- pants_image: 裤子图片 base64
返回 result_image: 换装结果 base64
"""
print(f"接收到换装请求,正在处理...")
# 加载工作流模板
workflow = json.loads(WORKFLOW_PATH.read_text(encoding="utf-8"))
@@ -175,9 +199,24 @@ async def try_on(req: TryOnRequest):
# 下载结果图片
async with httpx.AsyncClient(timeout=30.0) as dl_client:
result_b64 = await fetch_image_as_base64(dl_client, filename, subfolder, type_)
result_bytes = await fetch_image_bytes(dl_client, filename, subfolder, type_)
return TryOnResponse(result_image=result_b64)
# 将图片保存到临时文件,上传到 OSS
suffix = Path(filename).suffix or ".png"
object_name = f"tryon/{uuid.uuid4().hex}{suffix}"
with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
tmp.write(result_bytes)
tmp_path = tmp.name
try:
result_url = upload_to_oss(tmp_path, object_name)
finally:
os.unlink(tmp_path)
if not result_url:
raise HTTPException(status_code=500, detail="上传结果图片到 OSS 失败")
return TryOnResponse(result_url=result_url)
@app.get("/health")