当前位置: 首页 > news >正文

使用fastapi部署stable diffusion模型

使用vscode运行stable diffusion模型,每次加载模型都需要10+分钟,为算法及prompt调试带来了极大麻烦。使用jupyter解决自然是一个比较好的方案,但如果jupyter由于种种原因不能使用时,fastapi无疑成为了一个很好的选择。
参考github链接:https://github.com/jarvislabsai/fastapi-sd-template

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from typing import List
from PIL import Image
import torch
from diffusers import StableDiffusionPipeline
from torch import autocast
from pydantic import BaseModel
from typing import List, Optional
from utils import save_image

device = torch.device("cuda:5")


model_id = "/your_file_path/stable-diffusion-v1-5"
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, revision="fp16")
pipe = pipe.to(device)

app = FastAPI(root_path="/your_file_path/fastapiImage")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"]
)

class GenImage(BaseModel):
    prompt: str
    guidance_scale: Optional[float] = 7.5

@app.post("/genimage")
def gen_image(req:GenImage):
    with autocast("cuda"):
        img = pipe(req.prompt,guidance_scale=req.guidance_scale).images[0]
        img_url,fname = save_image(img)
    return{'url':img_url}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host = "0.0.0.0", port=9008)

搭配命令行命令

curl -X POST "http://localhost:9008/genimage" -H "Content-Type: application/json" -d '{"prompt": "a beautiful woman", "guidance_scale": 7.5}

utils.py脚本

import io
from datetime import datetime, timezone
import uuid
from PIL import Image

def save_image(img):
    # 获取当前时间戳
    dt = datetime.now()
    # 生成唯一的文件名
    file_name = str(uuid.uuid4()) + '-' + str(int(dt.replace(tzinfo=timezone.utc).timestamp()))
    # 定义本地保存路径,这里假设保存到当前目录下的 images 文件夹
    local_path = f'images/{file_name}.png'
    try:
        # 保存图像到本地路径
        img.save(local_path)
        return local_path, file_name
    except Exception as e:
        print(f"保存图像时出错: {e}")
        return None, None

相关库参考

fastapi==0.85.0
uvicorn==0.18.3
diffusers==0.6.0
gunicorn==20.1.0
boto3==1.24.90
transformers==4.23.1
ftfy==6.1.1

相关文章:

  • 如何记录Matlab程序运行过程中所占用的最大内存(续)
  • 天梯赛 L2-005 集合相似度
  • 配置 VSCode 的 C# 开发环境
  • 山寨币ETF的叙事,不灵了?
  • 【css酷炫效果】纯CSS实现全屏粒子连线
  • sparksql的Transformation与 Action操作
  • 解决git init 命令不显示.git
  • 3.1 在VisionPro脚本中添加CogGraphicLabel
  • LeetCode 热题 100_跳跃游戏(78_55_中等_C++)(贪心算法)
  • 技术路线图ppt模板_流程图ppt图表_PPT架构图
  • 购物车全选功能
  • Api架构设计--- HTTP + RESTful
  • C++和标准库速成(八)——指针、动态数组、const、constexpr和consteval
  • dataframe数据形式操作中的diff和shift函数区别与对比
  • 自交互学习:计算病理学中用于分子特征预测的多尺度组织形态学特征的融合与演化|文献速递-医学影像人工智能进展
  • 3.git操作:git init说明
  • macOS 安装 LibreOffice
  • QPS和TPS 的区别是什么?QPS 大了会有什么问题,怎么解决?
  • 数据库设计实验(4)—— 数据更新实验
  • MySQL数据高效同步到Elasticsearch的四大方案
  • 海南机场拟超23亿元收购美兰空港控股权,进一步聚焦机场主业
  • 首开股份:一季度净利润亏损约10.79亿元,签约金额63.9亿元
  • 锦江酒店:第一季度营业收入约29.42亿元,境内酒店出租率同比增长
  • 广西干旱程度有所缓解,未来一周旱情偏重地区降水量仍不足
  • “五一”假期全国口岸日均出入境人员将达215万人次
  • 国家统计局:一季度规模以上工业企业利润延续持续恢复态势