利用Streamlit前端框架开发Stable Diffusion模型图像生成网页应用(下篇)

今天介绍亚马逊云科技推出的国际前沿人工智能模型平台Amazon Bedrock上的Stability Diffusion模型开发生成式AI图像生成应用!本系列共有3篇,在上篇中我们学习了如何在亚马逊云科技控制台上体验该模型的每个特色功能,如文生图、图生图、图像修复等。中篇我们介绍了如何通过API代码实现以上功能。

接下来在下篇中我将带大家沉浸式实操,通过Stability Difussion模型API和Streamlit网页前端框架,沉浸式开发一个属于自己的图片生成式AI应用。大家可以通过本博客中的实操项目自己学习AI技能,并应用到日常工作中。

方案所需基础知识 

什么是Amazon Bedrock

Amazon Bedrock 是一项完全托管的服务,通过统一的 API 提供来自 AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI 和 Amazon 等领先 AI 公司的高性能基础模型(FMs),同时提供广泛的功能,让开发者能够在确保安全、隐私和负责任 AI 的前提下构建生成式 AI 应用。使用 Amazon Bedrock,开发者们可以:

轻松地测试、评估开发者的用例在不同基础模型下的表现;

  1. 使用微调和检索增强生成(RAG)等技术定制化开发应用程序;
  2. 构建可以使用开发者的企业系统和数据源自动执行任务的智能 Agents。
  3. 由于 Amazon Bedrock 是 Serverless 的服务,开发者无需管理任何基础设施,并且可以使用开发者已经熟悉其它的亚马逊云科技服务安全地集成和部署生成式 AI 功能到开发者的应用中。

什么是 Stability AI 模型? 

Stability AI 是一家致力于开发和提供生成式人工智能模型的公司,其模型被广泛应用于图像生成领域。Stability AI 的模型中最著名的莫非是 Stable Diffusion 生成模型,能够根据用户输入的描述,自动生成高度逼真的图像和文本。这些模型以其卓越的生成能力和灵活性,在应用开发中管饭应用和认可。

本实践包括的内容 

1. 学习Streamlit前端框架以及常用API、服务器启动命令等

2. 利用Streamlit前端框架和Stability Diffusion AI模型开发生成式AI图像生成网页应用。

功能实践具体步骤

模型参数

我们可以在访问Stability Diffusion API时配置如下参数,调整图片生成提示词、风格等配置生成多样化图片:

参数解释
height生成图像的高度
width生成图像的宽度
text_prompts数组形式的文本提示
cfg_scale控制扩散过程对提示文本的遵循程度
clip_guidance_preset采样的预设模式
sampler用于选择扩散过程使用的算法
seed随机噪声种子
steps扩散过程的运行次数
style_preset引导图像模型走向特定风格的预设
extras传递给引擎的其他实验性功能

接下来我们定义在我们的图像生成网页开发过程中会用到的Stable Diffusion模型参数:

DEBUG = os.getenv("DEBUG", False)
DEFAULT_SEED = os.getenv("DEFAULT_SEED", 12345)
MAX_SEED = 4294967295
MODEL_ID = "stability.stable-diffusion-xl-v1"
NEGATIVE_PROMPTS = [
    "bad anatomy", "distorted", "blurry",
    "pixelated", "dull", "unclear",
    "poorly rendered",
    "poorly Rendered face",
    "poorly drawn face",
    "poor facial details",
    "poorly drawn hands",
    "poorly rendered hands",
    "low resolution",
    "Images cut out at the top, left, right, bottom.",
    "bad composition",
    "mutated body parts",
    "blurry image",
    "disfigured",
    "oversaturated",
    "bad anatomy",
    "deformed body features",
]
STYLES_MAP = {
    "电影感(Cinematic)": "cinematic",
    "摄影(Photographic)": "photographic",
    "漫画(Comic Book)": "comic-book",
    "折纸(Origami)": "origami",
    "模拟胶片(Analog Film)": "analog-film",
    "幻想艺术(Fantasy Art)": "fantasy-art",
    "线条艺术(Line Art)": "line-art",
    "霓虹朋克粉(Neon Punk)": "neon-punk",
    "三维模型(3D Model)": "3d-model",
    "数码艺术(Digital Art)": "digital-art",
    "增强(Enhance)": "enhance",
    "像素艺术(Pixel Art)": "pixel-art",
    "瓷砖纹理(Tile Texture)": "tile-texture",
    "无(None)": "None",
}

 图片生成API调用函数代码段

1.编写调用 API 的等函数

bedrock_runtime = boto3.client('bedrock-runtime')

@st.cache_data(show_spinner=False)
def gen_img_from_bedrock(prompt, style, seed=DEFAULT_SEED,width=512,height=512):
    body = json.dumps({
        "text_prompts": [
            {
                "text": prompt
            }
        ],
        "cfg_scale": 10,
        "seed": seed,
        "steps": 50,
        "style_preset": style,
        "negative_prompts": NEGATIVE_PROMPTS,
        "width":width,
        "height":height
    })
    accept = "application/json"
    contentType = "application/json"
    response = bedrock_runtime.invoke_model(
        body=body, modelId=MODEL_ID, accept=accept, contentType=contentType
    )
    response_body = json.loads(response.get("body").read())
    image_bytes = response_body.get("artifacts")[0].get("base64")
    image_data = base64.b64decode(image_bytes.encode())
    st.session_state['image_data'] = image_data
    return image_data

其他Streamlit应用相关函数,主要用于管理用户界面组件(滑块、图片上传等)

def update_slider():
    st.session_state.slider = st.session_state.numeric


def update_numin():
    st.session_state.numeric = st.session_state.slider


@st.cache_data
def get_image(image_data):
    return Image.open(io.BytesIO(image_data))

 2. 主函数界面部分

if __name__ == '__main__':
    # Create the page title
    st.set_page_config(
        page_title='Amazon Bedrock Stable Diffusion', page_icon='./bedrock.png')
    st.title('Stable Diffusion Image Generator with Amazon Bedrock')
    # Create a sidebar with text examples
    with st.sidebar:
        # Selectbox
        style_key = st.sidebar.selectbox(
            "Choose image style",
            STYLES_MAP.keys(),
            index=0)

        seed_input = st.sidebar.number_input(
            "Seed", value=DEFAULT_SEED, placeholder=DEFAULT_SEED, key="numeric", on_change=update_slider)
        seed_slider = st.sidebar.slider(
            'Seed Slider', min_value=0, value=seed_input, max_value=MAX_SEED, step=1, key="slider",
            on_change=update_numin, label_visibility="hidden")
        seed = seed_input | seed_slider
        
           # 图片宽度
        width = st.sidebar.slider(
            'Width', min_value=256, value=512, max_value=1024, step=64, key="width_slider")
        
        # 图片高度
        height = st.sidebar.slider(
            'Height', min_value=256, value=512, max_value=1024, step=64, key="height_slider")

3.主函数调用Stable Diffusion API 部分 

    prompt = st.text_input('Input your prompt')
    if not prompt:
        st.warning("Please input a prompt")
        # Block the image generation if there is no input prompt
        st.stop()

    if st.button("Generate", type="primary"):
        if len(prompt) > 0:
            st.markdown(f"""
            This will show an image using **Stable Diffusion** with your desired prompt entered : {prompt}
            """)
            # Create a spinner to show the image is being generated
            with st.spinner('Generating image based on prompt'):
                if not DEBUG:
                    style = STYLES_MAP[style_key]
                    print("Generate image with Style:{} with Seed:{} and Width:{} and Height:{} and Prompt: {}".format(
                        style_key, seed, width , height  , prompt))
                    # Send request to Bedrock
                    
                    image_data = gen_img_from_bedrock(
                        prompt=prompt, style=style, seed=seed,width=width,height=height)
                    st.success('Generated stable diffusion image')

    if st.session_state.get("image_data", None):
        image = get_image(st.session_state.image_data)
        st.image(image)

    if DEBUG:
        st.write(st.session_state)

4. 启动streamlit服务器,加载网页应用

streamlit run intro_streaming.py --server.port 8080 

网页应用预览

5. 打开运行命令返回的"External URL"就可以进入到我们开发的网页应用前端了

6. 若想关停streamlit前端应用,在键盘点击Ctrl+C

以上就是沉浸式使用Amazon Bedrock上的Stability AI模型开发图像生成AI网页应用的下篇内容。欢迎大家关注小李哥的亚马逊云科技AI服务深入调研系列,未来获取更多国际前沿的AWS云开发/云架构方案。 

  • 23
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值