ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Gradio介绍安装与使用

Gradio介绍安装与使用 Gradio是什么Hugging Face发布的开源Python包可以为机器学习模型、API或任意Python函数快速构建demo或web应用并且通过Gradio的内置共享功能可以快速生成对应的链接而无需任何编程基础官方网站: https://www.gradio.app/ - 官方文档 - 快速开始: https://www.gradio.app/guides/quickstart为什么要学习Gradio1.直观演示你的模型、API、函数: 需要图形化的界面但又不太需要过多关心界面2.快速部署和分享: 只需要多添加一个参数shareTrue就会生成一个公共URL(72小时后过期)世界各地的人都可以访问3.公共URL格式示例: https://a23dsf231adb.gradio.liveve快速入门python import gradio as grdef reverse_text(text):return text[::-1] #字符串反转demo gr.Interface(fnreverse_text, inputstext, outputstext)demo.launch(shareTrue)参数作用示例fn要包装的 Python 函数界面的 “逻辑核心”fnreverse_textinputs界面的输入组件指定用户怎么给函数传参inputstext或gr.Textbox()outputs界面的输出组件指定函数返回值怎么展示outputstext或gr.Textbox()1.fn必须是一个可调用的 Python 函数函数的参数个数要和inputs的组件数量一一对应函数的返回值个数要和outputs的组件数量一一对应例pythondef add(a, b): # 两个参数 → inputs 要给两个组件 return a b # 一个返回值 → outputs 给一个组件 demo gr.Interface(fnadd, inputs[number, number], outputsnumber)2.inputs可以是字符串简写也可以是组件对象简写text/number/image/audio/file等组件对象gr.Textbox()/gr.Slider()/gr.Image()等多个输入用列表inputs[text, number]例python# 简写 gr.Interface(fn..., inputs[text, image], outputs...) # 组件对象可自定义配置 gr.Interface( fn..., inputs[gr.Textbox(label请输入文本), gr.Image(typepil, label上传图片)], outputs... )3.outputs用法和inputs完全一样用来展示函数的返回值简写text/image/label/json等组件对象gr.Textbox()/gr.Label()/gr.Image()等多个输出用列表outputs[text, image]例pythondef process(text, img): return text.upper(), img demo gr.Interface( fnprocess, inputs[text, image], outputs[text, image] )三、常用进阶参数表格参数作用示例title页面标题显示在界面顶部title文本反转工具description简短说明显示在标题下方description输入文本返回反转后的结果examples给用户提供预设示例一键填充输入examples[[hello], [你好]]allow_flagging是否允许用户标记结果比如 “好 / 不好”allow_flaggingnever关闭theme设置界面主题themegr.themes.Soft()完整示例pythonimport gradio as gr def reverse_text(text): return text[::-1] demo gr.Interface( fnreverse_text, inputsgr.Textbox(label输入文本), outputsgr.Textbox(label反转结果), title文本反转工具, description输入任意文本一键反转, examples[[hello world], [Gradio真好用]], ) demo.launch( shareTrue, themegr.themes.Glass()四、launch()里的关键参数参数作用示例share是否生成公网链接72 小时有效shareTrueserver_name绑定到 0.0.0.0方便局域网访问server_name0.0.0.0server_port指定端口默认是 7860server_port7861debug开启调试模式报错会显示完整堆栈debugTrue
返回列表