大家好,我是狂师!
今天给大家推荐一款开源的Python库:Gradio!
Gradio
是一个开源的Python库,用于创建机器学习和数据科学的交互式应用和演示。
项目地址:
https://github.com/gradio-app/gradio
Gradio
旨在简化展示和测试机器学习模型的过程,它允许用户通过构建漂亮的界面来展示其模型,而无需编写复杂的前端代码。通过Gradio,可以快速地为模型创建Web界面,并支持多种类型的输入和输出,如文本、图像和音频。这个库非常适合于快速迭代开发和用户反馈获取,以及在教学和展示中与观众互动。
通过提供简单的API,Gradio可以在几行代码中将任何Python函数转换为一个Web应用程序,无需前端开发经验。
Gradio的主要用途包括:
可以使用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.gradio.live
,可以将这个链接发给别人进行访问使用。当然你也可以选择将应用部署到云服务器。
示例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)
Gradio
通过提供一个简洁的API和直观的界面,降低了创建交互式机器学习应用的技术门槛,特别适合入门级开发者和初学者使用。它的设计理念在于让开发者能够专注于模型的功能和性能,而不是耗费大量时间在界面设计和代码复杂化上。因此,无论是教学、研究还是商业演示,Gradio都是一个非常有价值的工具。
总的来说,你可以不用,但是你不能不知道,脑海里多一个方案,在解题时就能多一种选择。