使用 gradio 创建 图文任务 App

该代码示例展示了如何利用HuggingFace的模型(如Muge-Image-Caption和DiffusionPipeline)结合gradio创建交互式应用,分别实现为图片添加标题和根据文本提示生成图片的功能。用户可以输入图片或文本,自定义参数,以直观体验AI生成内容的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

learn from https://learn.deeplearning.ai/huggingface-gradio

1. 给图片起标题

import pathlib
from PIL import Image
from transformers import pipeline
import gradio as gr

get_completion = pipe = pipeline("image-to-text", model="D:\huggingface\hub\Maciel\Muge-Image-Caption")


def summarize(input):
    output = get_completion(input)
    return output[0]['generated_text']




if __name__ == '__main__':
    image = pathlib.Path(__file__).parent / 'Andrew.jpg'
    img = Image.open(image)
    # img.show()
    print(get_completion(img))
    # [{'generated_text': '高颜值电脑桌,让你的生活更有情调'}]

    gr.close_all()
    demo = gr.Interface(fn=summarize,
                        inputs=[gr.Image(label="上传图片", type="pil")],
                        outputs=[gr.Textbox(label="标题")],
                        title="为图像添加标题",
                        description="使用 BLIP 模型为图像添加标题",
                        allow_flagging="never",
                        examples=[image])

    demo.launch(share=True)

在这里插入图片描述

2. 文生图

以下,本地电脑资源不够,就直接在 官网上操作了

from diffusers import DiffusionPipeline

pipeline = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")

def get_completion(prompt):
    return pipeline(prompt).images[0] 
prompt = "a train in hill"

result = get_completion(prompt)
IPython.display.HTML(f'<img src="data:image/png;base64,{result}" />')

在这里插入图片描述

import gradio as gr 

#A helper function to convert the PIL image to base64
#so you can send it to the API
def base64_to_pil(img_base64):
    base64_decoded = base64.b64decode(img_base64)
    byte_stream = io.BytesIO(base64_decoded)
    pil_image = Image.open(byte_stream)
    return pil_image

def generate(prompt):
    output = get_completion(prompt)
    result_image = base64_to_pil(output)
    return result_image

gr.close_all()
demo = gr.Interface(fn=generate,
                    inputs=[gr.Textbox(label="提示词")],
                    outputs=[gr.Image(label="输出图片")],
                    title="文本生成图片",
                    description="输入提示词,使用SD模型生成图片",
                    allow_flagging="never",
                    examples=["中国古风建筑","a mecha robot in a favela"])

demo.launch(share=True, server_port=int(os.environ['PORT1']))

在这里插入图片描述

添加高级选项

import gradio as gr 

#A helper function to convert the PIL image to base64 
# so you can send it to the API
def base64_to_pil(img_base64):
    base64_decoded = base64.b64decode(img_base64)
    byte_stream = io.BytesIO(base64_decoded)
    pil_image = Image.open(byte_stream)
    return pil_image

def generate(prompt, negative_prompt, steps, guidance, width, height):
    params = {
        "negative_prompt": negative_prompt,
        "num_inference_steps": steps,
        "guidance_scale": guidance,
        "width": width,
        "height": height
    }
    
    output = get_completion(prompt, params)
    pil_image = base64_to_pil(output)
    return pil_image

gr.close_all()
demo = gr.Interface(fn=generate,
                    inputs=[
                        gr.Textbox(label="提示词"),
                        gr.Textbox(label="反向提示词"),
                        gr.Slider(label="推理步数", minimum=1, maximum=100, value=25,
                                 info="模型迭代多少步生成图片"),
                        gr.Slider(label="提示指导程度", minimum=1, maximum=20, value=7, 
                                  info="提示词影响结果的重要程度"),
                        gr.Slider(label="宽", minimum=64, maximum=512, step=64, value=512),
                        gr.Slider(label="高", minimum=64, maximum=512, step=64, value=512),
                    ],
                    outputs=[gr.Image(label="输出图片")],
                    title="文本生成图片",
                    description="输入提示词,使用SD模型生成图片",
                    allow_flagging="never"
                    )

demo.launch(share=True, server_port=int(os.environ['PORT2']))

在这里插入图片描述

gr.Blocks

使用这个模块写起来更优雅,可以自由的排版

with gr.Blocks() as demo:
    gr.Markdown("# 文本生成图片")
    prompt = gr.Textbox(label="提示词")
    with gr.Row():
        with gr.Column():
            negative_prompt = gr.Textbox(label="负向提示词")
            steps = gr.Slider(label="推理步数", minimum=1, maximum=100, value=25,
                      info="模型迭代多少步生成图片")
            guidance = gr.Slider(label="提示指导程度", minimum=1, maximum=20, value=7,
                      info="提示词影响结果的重要程度")
            width = gr.Slider(label="宽", minimum=64, maximum=512, step=64, value=512)
            height = gr.Slider(label="高", minimum=64, maximum=512, step=64, value=512)
            btn = gr.Button("提交")
        with gr.Column():
            output = gr.Image(label="输出")

    btn.click(fn=generate, inputs=[prompt,negative_prompt,steps,guidance,width,height], outputs=[output])
gr.close_all()
demo.launch(share=True, server_port=36790)

在这里插入图片描述

  • 调整布局
with gr.Blocks() as demo:
    gr.Markdown("# 文本生成图片")
    with gr.Row():
        with gr.Column(scale=4):
            prompt = gr.Textbox(label="提示词") #Give prompt some real estate
        with gr.Column(scale=1, min_width=50):
            btn = gr.Button("提交") #Submit button side by side!
    with gr.Accordion("高级选项", open=False): #Let's hide the advanced options!
            negative_prompt = gr.Textbox(label="负向提示词")
            with gr.Row():
                with gr.Column():
                    steps = gr.Slider(label="推理步数", minimum=1, maximum=100, value=25,
                      info="模型迭代多少步生成图片")
                    guidance = gr.Slider(label="提示指导程度", minimum=1, maximum=20, value=7,
                      info="提示词影响结果的重要程度")
                with gr.Column():
                    width = gr.Slider(label="宽", minimum=64, maximum=512, step=64, value=512)
                    height = gr.Slider(label="高", minimum=64, maximum=512, step=64, value=512)
    output = gr.Image(label="输出") #Move the output up too
            
    btn.click(fn=generate, inputs=[prompt,negative_prompt,steps,guidance,width,height], outputs=[output])

gr.close_all()
demo.launch(share=True, server_port=41010)

提交按钮放在上面,减少鼠标移动距离
在这里插入图片描述

高级选项默认折叠,看起来简洁在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Michael阿明

如果可以,请点赞留言支持我哦!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值