Gradio is an open-source Python package that allows you to quickly build a demo or web application for your machine learning model, API, or any arbitary Python function.
gr.Blocks - кастомное приложение: базовый класс;gr.Interface - input-output интерфейс;gr.ChatInterface - чат-интерфейс;gr.TabbedInterface - приложение, разделённое на несколько tab-секций. То есть несколько приложений внутри одного;Запуск любого приложения: gradio <filename.py> или python <filename.py>
gr.Interface — input-output приложение, позволяющее в интерактивном режиме взаимодействовать с пользователем.
import gradio as gr
import pandas as pd
df = pd.read_csv("examples/data/sales.csv")
def get_sample_dataframe(
sample_size,
):
return df.sample(sample_size)
demo = gr.Interface(
fn=get_sample_dataframe,
inputs=["number"], # inputs=[gr.Number()],
outputs=["dataframe"], # outputs=[gr.DataFrame()],
)
demo.launch()input —>
—> output
Например gr.Image может быть картинкой (np.ndarray), путём до файла с картинкой (str), списком путей до файлов (list[str]).
gr.ChatInterface - приложение-чат
strlist[tuple[str, str]]strgr.BlocksНаконец рассмотрим более общий класс, который позволяет создать практически сколь угодно сложное приложение, подобно тому как мы строили приложения с помощью Streamlit.
import gradio as gr
def update(name):
return f"Welcome to Gradio, {name}!"
with gr.Blocks() as demo:
# Отформатированный текст
gr.Markdown("Start typing _below_ and then click **Run** to see the output.")
# Вёрстка: компоновка элементов в строку
with gr.Row():
# текстовое поле
inp = gr.Textbox(placeholder="What is your name?")
# текстовый ввод
out = gr.Textbox()
# Кнопка
btn = gr.Button("Run")
# действие при нажатии на кнопку
btn.click(fn=update, inputs=inp, outputs=out)
demo.launch()gr.Blocks - Data Flowкнопочка к которой прикреплено событие
real-time change
интерактивность
Label, DataFrame, Code, Chatbot, Image, Video, BarPlot, etcRadio, Slider, UploadButton, etcAnnotatedImage: картинки с аннотациями объектов
MultimodalTextbox - поле ввода, в которое можно загружать мульти-медиа Model3D - 3D модель в формате .obj, .glb, .stl, .gltf, .splat, .ply Определение в глобальной области видимости.
Синглтон для всех пользователей.
Пример
Session State — переменные сессии.
gr.State().Blocks — сколько угодноgr.Interface (history — обращение к singleton)import gradio as gr
def store_message(message: str, history: list[str]):
output = {
"Current messages": message,
"Previous messages": history[::-1]
}
history.append(message)
return output, history
demo = gr.Interface(
fn=store_message,
inputs=["textbox", gr.State(value=[])],
outputs=["json", gr.State()]
)
demo.launch()Пример для gr.Blocks
with gr.Blocks() as demo:
words_singleton = gr.State(set()) # переменная сессии
with gr.Row() as row:
with gr.Column():
input_letter = gr.Textbox(label="Enter word")
btn = gr.Button("Add word")
with gr.Column():
session_words_box = gr.Textbox(label="Current words")
def add_word(word, session_words):
session_words.add(word)
return [
session_words, # присвоится синглтон-переменной `words_singleton`
", ".join(session_words),
]
btn.click(
add_word,
[input_letter, words_singleton],
[
words_singleton, # обновляем синглтон-переменную через первый retval функции
session_words_box
],
)
demo.launch()Вместо функции в интерфейсе используется генератор.
Тогда значение будет перезаписываться по мере того как будут поступать новые yield-values
Например: можно стримить вывод ML-модели.
Некоторые компоненты могут работать в “интерактивном режиме”
Реактивный интерфейс - интерфейс который реагирует на изменение пользовательского ввода и позволяет “на лету” обновлять приложение и генерировать вывод не по нажатию кнопки “Submit”, а при изменении input.
live=True
Пример: Automatic Speech Recognition (тут больше примеров).
# libs are required: numpy, torch, torchaudio, transformers
import gradio as gr
import numpy as np
from transformers import pipeline
transcriber = pipeline("automatic-speech-recognition", model="openai/whisper-base.en")
def transcribe(stream, new_chunk):
sr, y = new_chunk
left_ch = y[:, 0].astype(np.float32) # костыль для получения одноканального аудио
left_ch /= np.max(np.abs(left_ch))
if stream is not None:
stream = np.concatenate([stream, left_ch])
else:
stream = left_ch
return stream, transcriber({"sampling_rate": sr, "raw": stream})["text"]
demo = gr.Interface(
transcribe,
[gr.State(), gr.Audio(sources=[gr.Microphone()], streaming=True)],
[gr.State(), gr.Textbox()],
live=True,
)
demo.launch()Что можно делать с gr.Interface кроме launch?
gr.Interface.load — позволяет триггерить блок кода при запуске приложения
gr.load — позволяет загружать hugging-face модели из Serverless Inference API
gr.Interface.from_pipeline — конструирует интерфейс на основе transformers.Pipeline или diffusers.DiffusionPipeline. Подробнее
gr.Interface.integrate - позволяет интегрироваться со сторонними ML-сервисами
HuggingFace, transformers.pipeline, MlFlow и т.д.Gradio