Gradio的学习

1、fastapi +gradio

在这里插入图片描述

from fastapi import FastAPI
from fastapi.responses import HTMLResponse
import gradio as gr

app = FastAPI()

HELLO_ROUTE = "/hello"
GOODBYE_ROUTE = "/goodbye"
iframe_dimensions = "height=300px width=1000px"

index_html = f'''
<h1>Put header here</h1>

<h3>
You can mount multiple gradio apps on a single FastAPI object for a multi-page app.
However if you mount a gradio app downstream of another gradio app, the downstream
apps will be stuck loading. 
</h3>

<h3>
So in particular if you mount a gradio app at the index route "/", then all your 
other mounted gradio apps will be stuck loading. But don't worry, you can still embed
your downstream gradio apps into the index route using iframes like I do here. In fact,
you probably want to do this anyway since its your index page, which you want to detail 
more fully with a jinja template. 
For a full example, you can see my <a href=https://yfu.one/>generative avatar webapp</a>
</h3>

<div>
<iframe src={HELLO_ROUTE} {iframe_dimensions}></iframe>
</div>

<div>
<iframe src={GOODBYE_ROUTE} {iframe_dimensions}></iframe>
</div>

'''

@app.get("/", response_class=HTMLResponse)
def index():
    return index_html


hello_app = gr.Interface(lambda x: "Hello, " + x + "!", "textbox", "textbox")
goodbye_app = gr.Interface(lambda x: "Goodbye, " + x + "!", "textbox", "textbox")


app = gr.mount_gradio_app(app, hello_app, path=HELLO_ROUTE)
app = gr.mount_gradio_app(app, goodbye_app, path=GOODBYE_ROUTE)

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

2、隐藏下面的图标


import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(
    fn=greet,
    inputs="text",
    outputs="text",
    css="footer {visibility: hidden}"
)

demo.launch()

3、竖向多个页面

参考链接:https://github.com/gradio-app/gradio/issues/2654#issuecomment-2212506888
在这里插入图片描述

import gradio as gr

session_states = {}

#
# 页面可以放在外部文件中
#
def get_not_found_page(local_state):
    with gr.Column() as result:
        gr.Markdown("## 404 - 页面未找到")
        gr.Label(f"404 页面 {type(local_state)}: {local_state.get('page')}")
    return result


def get_landing_page(local_state):
    with gr.Column() as result:
        gr.Markdown("## 首页")

        if local_state:
            gr.Label(f"首页 {type(local_state)}")
            gr.Label(f"页面: {local_state.get('page')}")
    return result


def get_home_page(local_state):
    with gr.Column() as result:
        gr.Markdown("## 首页")

        gr.Label(f"首页 {type(local_state)}")
        gr.Label(f"页面: {local_state.get('page')}")
    return result


def get_faq_page(local_state):
    with gr.Column() as result:
        gr.Markdown("## 常见问题")

        gr.Label(f"常见问题页面 {type(local_state)}")
        gr.Label(f"页面: {local_state.get('page')}")
    return result


#
# 应用外壳 - 用于多个页面
#
with gr.Blocks() as demo:

    def init_state(request: gr.Request):
        # 获取 session_id
        session_id = request.cookies.get("session", "")

        # 如果 session_id 为空,则使用一个默认的 session_id
        if not session_id:
            session_id = "default_session_id"  # 使用默认值避免空字符串
            print(f"** 生成默认 session_id: {session_id}")

        # 如果 session_id 不在 session_states 中,初始化该 session
        if session_id not in session_states:
            session_states[session_id] = {
                "user": "jdoe123",
                "session_id": session_id,
                "tasks": [],
                "page": "",
            }

        result = session_states[session_id]

        # 获取 URL 参数
        result["page"] = request.query_params.get("page", "")  # 如果没有 page 参数,默认为空
        return result  # 返回填充后的状态

    state = gr.State()

    #
    # 用请求数据填充用户的 "state"
    #
    demo.load(
        fn=init_state,
        inputs=None,
        outputs=state,
        queue=True,
        show_progress=False,
    )

    content = gr.HTML("...")

    @gr.render(inputs=[state], triggers=[state.change])
    def page_content(local_state):
        # 使用 gr.Row 创建一个横向的布局
        with gr.Row(variant="panel") as result:
            # 创建一个包含图标的列,设置最小宽度为50,比例为0
            with gr.Column(scale=0, min_width=100):
                # 在该列中添加一个HTML组件,显示🏠图标
                anchor = gr.HTML("<h1>🏠</h1>")

                #
                # 页面导航按钮
                #
                # 在新的 gr.Column 中放置多个按钮,用于页面跳转
                with gr.Row() as result:
                # with gr.Column() as result:

                    # 创建一个按钮,点击后跳转到首页("/")
                    gr.Button("👥", link="/")
                    # 创建一个按钮,点击后跳转到主页(/?page=home)
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("人脸识别", link="/?page=home")
                    gr.Button("人工智能", link="/?page=faq")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    # 创建一个按钮,点击后跳转到主页(/?page=home)
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("人脸识别", link="/?page=home")
                    gr.Button("人工智能", link="/?page=faq")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    # 创建一个按钮,点击后跳转到主页(/?page=home)
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("人脸识别", link="/?page=home")
                    gr.Button("人工智能", link="/?page=faq")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")
                    gr.Button("👥", link="/")
                    gr.Button("🏠", link="/?page=home")
                    gr.Button("💼", link="/?page=faq")



            with gr.Column(scale=12):
                #
                # 页面路由处理
                #
                if (
                    local_state is None
                    or local_state.get("page") is None
                    or len(local_state["page"]) < 1
                ):
                    return get_landing_page(local_state), local_state
                elif local_state["page"] == "home":
                    return get_home_page(local_state), local_state
                elif local_state["page"] == "faq":
                    return get_faq_page(local_state), local_state
                else:
                    return (
                        get_not_found_page(local_state),
                        local_state,
                    )

    #
    # 临时解决方案:最好延迟渲染直到 state 被填充
    #
    def page_content_update(local_state):
        return gr.HTML("...", visible=False)

    state.change(fn=page_content_update, inputs=state, outputs=content)

demo.launch()

3、横向多个页面

参考链接:https://www.gradio.app/guides/controlling-layout
在这里插入图片描述

import numpy as np
import gradio as gr

def flip_text(x):
    return x[::-1]

def flip_image(x):
    return np.fliplr(x)

with gr.Blocks() as demo:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tab("Flip Text"):
        text_input = gr.Textbox()
        text_output = gr.Textbox()
        text_button = gr.Button("Flip")
    with gr.Tab("Flip Image"):
        with gr.Row():
            image_input = gr.Image()
            image_output = gr.Image()
        image_button = gr.Button("Flip")

    with gr.Accordion("Open for More!", open=False):
        gr.Markdown("Look at me...")
        temp_slider = gr.Slider(
            0, 1,
            value=0.1,
            step=0.1,
            interactive=True,
            label="Slide me",
        )

    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)

demo.launch()

5、修改ip和端口号

demo.launch(server_name=“192.168.192.67”,server_port=8909)
访问方法:http://192.168.192.67:8909

03-14
### Gradio 的简介与使用教程 #### 什么是 GradioGradio 是一种用于快速创建机器学习模型交互界面的开源 Python 库。它允许开发者通过简单的几行代码将复杂的模型部署为直观易用的应用程序,支持多种输入和输出组件。 --- #### 安装 Gradio 要开始使用 Gradio,首先需要安装该库。可以通过 pip 命令轻松完成安装: ```bash pip install gradio ``` --- #### 创建第一个 Gradio 应用 以下是基于 Gradio 构建应用程序的基本流程: 1. **导入 Gradio** 需要在脚本中引入 `gradio` 模块以便访问其功能[^1]。 2. **定义核心函数 (fn 参数)** 这里的 fn 可以是你自己编写的任何函数或者封装好的机器学习模型预测逻辑。此函数接收来自用户的输入数据作为参数,并返回处理后的结果给用户查看[^2]。 3. **指定输入组件 (inputs 参数)** 输入可以是多种形式的数据类型比如文本字符串、图片文件等。每种类型的输入都有对应的预设组件可供选择如 text、image 或 mic 表示语音录入设备等等。 4. **设定输出形式 (outputs 参数)** 同样地,在展示最终计算成果的时候也需要明确告知系统应该采用何种方式呈现这些信息——这便是所谓的“output”。同样存在丰富的选项来满足不同场景下的需求,像 image 显示图像;label 展现分类标签名称之类的功能都是可以直接调用出来的。 5. **启动服务** 当所有的配置都完成后就可以运行 launch 方法让整个项目上线啦! 下面给出一段完整的例子演示如何利用上述提到的知识点搭建起一个简易版的文字长度统计工具: ```python import gradio as gr def greet(name): return f"Hello {name}! Your name has {len(name)} letters." demo = gr.Interface( fn=greet, inputs="text", outputs="text" ) demo.launch() ``` 在这个案例里我们先自定了一个名为greet的小方法用来接受外部传入的名字变量再经过加工形成一句带有字数统计的话句反馈回去。接着按照前面所讲过的理论框架依次指派好相应的input/output类别最后激活launch()命令使得网页端口能够正常开启从而实现预期效果。 --- ### 总结 综上所述,借助于Gradio强大的灵活性以及简洁明了的操作步骤即使是没有太多前端开发经验的新手也能够在短时间内学会怎样把自己的研究成果转换成可视化的互动体验分享给别人欣赏[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值