【腾讯云HAI域探秘】通过StableDiffusion实现个性化翻翻看游戏

image.png

前言

随着ChatGPT和Stable Diffusion等大模型的迅速发展,生成式AI备受瞩目。数字媒体、游戏、动画、电影、广告、社交、短视频、软件开发等各行各业都开始积极借助AIGC的能力提升生产效率。然而,对于如何实现独立部署和体验,仍然是一个值得探讨的话题。因为大模型需要处理的数据量巨大无比,整个处理过程可以分为训练(train)、微调(fine-tune)和推理(inference)。对于只是短期使用的场景,自己购买硬件资源显然是不划算的。
最近腾讯云推出了一款“高性能应用服务HAI”,它基于腾讯云GPU云服务器底层算力,提供即插即用的高性能云服务。以应用为中心,匹配GPU云算力资源,助力中小企业及开发者快速部署LLM、AI作画、数据科学等高性能应用,部署起来非常省心!!!博主这次也是亲自体验了一番,从0到1使用腾讯云高性能应用服务 HAI ,部署了StableDiffusion 模型来辅助我开发【翻翻看】的益智游戏,游戏的素材是基于StableDiffusion画图生成。整体开发下来发现自己完全不用担心素材的生成, 我们只需要准备好prompt的提示词就可以了,先来看下部分游戏效果截图吧

一、腾讯云HAI介绍

即插即用 · 轻松上手

基于腾讯云GPU云服务器底层算力,提供即插即用的高性能云服务。

image.png

横向对比 · 青出于蓝

大幅降低GPU云服务器使用门槛,多角度优化产品使用体验,开箱即用

image.png

应用场景

多种高性能应用部署场景,轻松拿捏

image.pngimage.pngimage.png

二、使用腾讯云HAI一键部署StableDiffusion

申请高性能应用服务 HAI

点击链接 高性能应用服务 HAI 申请资格
image.png

等待审核通过

等待审核通过后便可以 ** 前往体验HAI **了哦!!
image.png

三、Stable Diffusion 创建

选择应用

点击链接 进入产品页面

  1. 选择AI模型中的Stable Diffusion
  2. 地域选择广州
  3. 算力方案选择基础型即可
  4. 实例名称根据自己的喜好命名即可 , 这里我们命名为 “cardGame”
  5. 硬盘选择 80gb 即可
  6. 点击 立即购买

详细配置如下图所示:

buy.cloud.tencent.com_hai_applicationId=app-io484ryb&regionId=1&bundleId=XL&alias=cardGame&diskSize=80&rule=true.png

等待创建完成

实例创建大约需要 8~10 分钟左右

image.png

学术加速

选择需要加速的地域,单击右侧开关启动加速能力。

image.png

学术加速场景

当遇到部分资源平台访问、下载速度过慢或无法响应时,可尝试使用学术加速能力,提高部分资源平台的访问速度。

注意事项

  • 目前加速能力仅支持部分地域及部分资源平台。
  • 同地域下任一服务开启学术加速能力,将会同时开启同地域下所有服务的学术加速能力。
  • 学术加速能力限时免费,限免结束时间以腾讯云官网公告为准。

image.png

实例描述

创建完成后,我们对当前的实例简单的了解一下

image.png

详细信息查看

image.png

关机

关机的话是不会计费了哦!! 但是付费云盘会正常计费,这点要注意一下, 提示框写的比较详细

image.png

配置 StableDiffusion API 服务

本次项目我们需要对接的是 StableDiffusion 的api , 因此我们直接来进行配置即可

进入 jupyter_lab 操作界面

点击 算力链接 选择jupyter_lab
image.png

终端操作

jupyter_lab 中我们选择 Terminal 进行操作

image.png

运行launch.py 脚本

在命令行输入如下指令

cd /root/stable-diffusion-webui
python launch.py --nowebui --xformers --opt-split-attention  --listen --port 7862

image.png

命令讲解

命令描述
–nowebui以 API 模式启动
–xformers使用xformers库。极大地改善了内存消耗和速度。
–opt-split-attentionCross attention layer optimization 优化显着减少了内存使用,几乎没有成本(一些报告改进了性能)。黑魔法。默认情况下torch.cuda,包括 NVidia 和 AMD 卡。
–listen默认启动绑定的 ip 是 127.0.0.1,只能是你自己电脑可以访问 webui,如果你想让同个局域网的人都可以访问的话,可以配置该参数(会自动绑定 0.0.0.0 ip)。
–port默认端口是 7860,如果想换个端口,可以配置该参数,例如:–port 7862
–gradio-auth username:password如果你希望给 webui 设置登录密码,可以配置该参数,例如:–gradio-auth GitLqr:123456。
添加入站规则

查看端口配置中是否有 7862的协议,没有的话需要添加一个

image.png

启用 StableDiffusion API 接口

配置完成后输入 服务器IP地址:端口号/docs 可查看相关的 API 接口 swagger 使用指南

到此我们的接口配置就完成了

问题处理

点开swagger 会发现需要传的参数较多,如下图所示:
image.png

常用传参归纳

名称说明
prompt提示词
negative_prompt反向提示词
seed种子,随机数
batch_size每次张数
n_iter生成批次
steps生成步数
cfg_scale关键词相关性
width宽度
height高度
restore_faces脸部修复
tiling可平铺
sampler_index采样方法

json 格式

{
     "denoising_strength": 0,
     "prompt": "Generate a cute SAMURAI WARRIOR illustration, resolution, cartoon-sticker style with clear lines on a pure white background suitable for a children's coloring book.",
     "negative_prompt": "",
     "seed": -1,
     "batch_size": 2,
     "n_iter": 1,
     "steps": 50,
     "cfg_scale": 7,
     "width": 512,
     "height": 512,
     "restore_faces": false,
     "tiling": false,
     "sampler_index": "Euler" 
}

api测试

博主本人使用apifox 进行的接口测试, 当然也可以直接使用swagger 进行测试哈, 本人习惯而已

image.png
可以看到返回的结果是没问题的,接下来直接进行接口对接吧!!

四、项目开发

准备Prompt 提示词

promptList: [
        {
          label:
            "Create a portrait of Jin-ro, an Astral Elf with long pointed ears. His skin should shimmer faintly like the night sky, reflecting wisdom and centuries of knowledge. His eyes should twinkle with a star-like glow, and his silver hair should flow like the tail of a comet. Adorn him in elegant robes that are decorated with celestial patterns, showcasing his grace and the precision of an orbiting planet, His expression should be contemplative but with a hint of arrogance, a knowing smile that's both inviting and slightly condescending. In his hand, he should hold a delicate telescope, a symbol of his fascination with celestial alignments. Behind him, include astrolabes, star charts, and ancient tomes, indicative of his deep connection to the cosmos, capture the air of mystique and wisdom, the aura of a scholar who has unraveled secrets of the universe, yet maintains a distance due to his intellect and slight impatience with lesser minds. smooth, highly detailed, sharp focus, cinematic, 4k",
        },
        {
          label:
            "Generate a cute SAMURAI WARRIOR illustration, resolution, cartoon-sticker style with clear lines on a pure white background suitable for a children's coloring book.",
        },
        {
          label: "Disney Mulan in chibi style",
        },
        {
          label: "anime drawing. Beautiful girl. Anime reskin style",
        },
        {
          label: "anime drawing. Beautiful girl. Anime reskin style",
        },
        {
          label:
            "A beautiful obscure girl 25yo, dark eyes, white skin, wear a black clothes, ultra hd, vampire",
        },
      ]

使用py做本地代理

使用py 转发请求, 如果直接请求的话会出现跨域现象

from flask import Flask, request, jsonify
import json
import base64
import requests
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}}) 
your_ip = 'xxxx'  # HAI服务器IP地址
your_port = 7862  # SD api 监听的端口

def submit_post(url: str, data: dict):
    """
    Submit a POST request to the given URL with the given data.
    """
    return requests.post(url, data=json.dumps(data))

def save_encoded_image(b64_image: str, output_path: str):
    """
    Save the given image to the given output path.
    """
    with open(output_path, "wb") as image_file:
        image_file.write(base64.b64decode(b64_image))

@app.route('/generate_image', methods=['POST'])
def generate_image():
    txt2img_url = f'http://{your_ip}:{your_port}/sdapi/v1/txt2img'
    data = request.get_json()
    response = submit_post(txt2img_url, data)
    # image_path = 'cat.png'  # 保存图片的路径
    print(response.json())
    # save_encoded_image(response.json()['images'][0], image_path)
    return response.json()

if __name__ == '__main__':
    app.run(host="0.0.0.0",port="8083")

请求中。。。

image.png

服务端请求的日志

image.png

效果演示

image.pngimage.png
image.pngimage.png
image.pngimage.png

五、常见问题

整体开发过程中还是蛮顺利的, 唯一的缺点是api 接口在请求的时候需要自己做一下处理, 否则直接调用会出现跨域的问题, 其次请求的参数过多, 个人觉得可以精简一下 比如参数可以只有下面五个即可。

名称说明
prompt提示词
negative_prompt反向提示词
batch_size每次张数
width宽度
height高度

其他的参数如果想要配额可以换一个请求地址等等 , 将接口分为两种即:基础型进阶型

六、总结

腾讯云HAl这次给我的体验非常良好,后续会考虑探索腾讯云HAl更多的功能,为工作进行赋能~

  • 54
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 32
    评论
评论 32
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值