大家好,我是狂师!
今天给大家推荐一款开源的Python库:Gradio!
Gradio
是一个开源的Python库,用于创建机器学习和数据科学的交互式应用和演示。
项目地址:
https://github.com/gradio-app/gradio
1、项目介绍 Gradio
旨在简化展示和测试机器学习模型的过程,它允许用户通过构建漂亮的界面来展示其模型,而无需编写复杂的前端代码。通过Gradio,可以快速地为模型创建Web界面,并支持多种类型的输入和输出,如文本、图像和音频。这个库非常适合于快速迭代开发和用户反馈获取,以及在教学和展示中与观众互动。
通过提供简单的API,Gradio可以在几行代码中将任何Python函数转换为一个Web应用程序,无需前端开发经验。
2、工具用途 Gradio的主要用途包括:
展示和测试机器学习模型 :通过创建具有输入字段(如文本输入或图像上传)和输出字段(如模型预测结果)的界面,用户可以直接与模型进行交互,从而测试和验证模型的性能。演示机器学习模型 :Gradio可以帮助开发者向客户、合作者和学生展示机器学习模型的功能和应用场景。通过创建简单漂亮的用户界面,可以更好地展示模型的预测效果和可视化结果。快速部署模型 :通过自动共享链接,Gradio可以快速部署机器学习模型,并使其在互联网上可用。这使得开发者可以轻松地与团队成员、合作伙伴或用户共享模型,并收集他们对模型性能的反馈。交互式调试模型 :在开发过程中,Gradio提供了内置的操作和解释工具,允许开发者交互式地调试机器学习模型。3、安装、使用 可以使用pip进行安装,安装之前要确保python版本大于 3.8。
pip install gradio
示例1: 牛刀小试
import gradio as gr def greet(name, intensity): return "Hello " * intensity + name + "!" demo = gr.Interface( fn=greet, inputs=["text" , "slider" ], outputs=["text" ], ) demo.launch()
运行之后,在浏览器打开http://localhost:7860/
即可访问web程序
示例2:生成外网地址
import gradio as gr def greet(name): return "Hello " + name + "!" demo = gr.Interface(fn=greet, inputs="textbox" , outputs="textbox" ) demo.launch(share=True) # Share your demo with just 1 extra parameter 🚀
运行时候,就会自动生成一个URL链接,类似https://a23dsf231adb.
,可以将这个链接发给别人进行访问使用。当然你也可以选择将应用部署到云服务器。
示例3: 和FastAPI框架集成
from fastapi import FastAPI import gradio as gr CUSTOM_PATH = "/gradio" app = FastAPI() @app.get("/" ) def read_main(): return {"message" : "This is your main app" } io = gr.Interface(lambda x: "Hello, " + x + "!" , "textbox" , "textbox" ) app = gr.mount_gradio_app(app, io, path=CUSTOM_PATH)# Run this from the terminal as you would normally start a FastAPI app: `uvicorn run:app` # and navigate to http://localhost:8000/gradio in your browser.
示例4: 一个更为完整的示例
import os from authlib.integrations.starlette_client import OAuth, OAuthError from fastapi import FastAPI, Depends, Request from starlette.config import Config from starlette.responses import RedirectResponse from starlette.middleware.sessions import SessionMiddleware import uvicorn import gradio as gr app = FastAPI()# Replace these with your own OAuth settings GOOGLE_CLIENT_ID = "..." GOOGLE_CLIENT_SECRET = "..." SECRET_KEY = "..." config_data = {'GOOGLE_CLIENT_ID' : GOOGLE_CLIENT_ID, 'GOOGLE_CLIENT_SECRET' : GOOGLE_CLIENT_SECRET} starlette_config = Config(environ=config_data) oauth = OAuth(starlette_config) oauth.register( name='google' , server_metadata_url='https://accounts.google.com/.well-known/openid-configuration' , client_kwargs={'scope' : 'openid email profile' }, ) SECRET_KEY = os.environ.get('SECRET_KEY' ) or "a_very_secret_key" app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)# Dependency to get the current user def get_user(request: Request): user = request.session.get('user' ) if user: return user['name' ] return None @app.get('/' ) def public(user: dict = Depends(get_user)): if user: return RedirectResponse(url='/gradio' ) else : return RedirectResponse(url='/login-demo' ) @app.route('/logout' ) async def logout (request: Request): request.session.pop('user' , None) return RedirectResponse(url='/' ) @app.route('/login' ) async def login(request: Request): redirect_uri = request.url_for('auth' ) # If your app is running on https, you should ensure that the # `redirect_uri` is https, e.g. uncomment the following lines: # # from urllib.parse import urlparse, urlunparse # redirect_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https')) return await oauth.google.authorize_redirect(request, redirect_uri) @app.route('/auth' ) async def auth(request: Request): try: access_token = await oauth.google.authorize_access_token(request) except OAuthError: return RedirectResponse(url='/' ) request.session['user' ] = dict(access_token)["userinfo" ] return RedirectResponse(url='/' ) with gr.Blocks() as login_demo: gr.Button("Login" , link="/login" ) app = gr.mount_gradio_app(app, login_demo, path="/login-demo" ) def greet(request: gr.Request): return f"Welcome to Gradio, {request.username}" with gr.Blocks() as main_demo: m = gr.Markdown("Welcome to Gradio!" ) gr.Button("Logout" , link="/logout" ) main_demo.load(greet, None, m) app = gr.mount_gradio_app(app, main_demo, path="/gradio" , auth_dependency=get_user)if __name__ == '__main__' : uvicorn.run(app)
4、小结 Gradio
通过提供一个简洁的API和直观的界面,降低了创建交互式机器学习应用的技术门槛,特别适合入门级开发者和初学者使用。它的设计理念在于让开发者能够专注于模型的功能和性能,而不是耗费大量时间在界面设计和代码复杂化上。因此,无论是教学、研究还是商业演示,Gradio都是一个非常有价值的工具。
总的来说,你可以不用,但是你不能不知道,脑海里多一个方案,在解题时就能多一种选择。