《Python Gradio》(四)常用效果

1. 进度条

import gradio as gr
import time

def response1(number):
    # 创建进度条
    progress = gr.Progress()
    result = 0.0
    for i in range(1, number + 1):
        # 设置进度条的进度
        # progress((i, number), desc="准备计算")
        progress(i / number, desc="准备计算")
        result += i
        time.sleep(0.1)

    return result

def response2(number):
    progress = gr.Progress()
    # 创建 tqdm 进度条,并让 progress 跟踪其进度
    pbar = progress.tqdm(iterable=range(number), desc='正在计算')
    result = 0.0
    for i in pbar:
        result += i
        time.sleep(0.1)

    return result


def test():
    app = gr.Interface(fn=response1, inputs='number', outputs='number')
    app.launch()


if __name__ == '__main__':
    test();

2. 会话保持

Gradio 会话保持(Session State)是指在用户会话过程中,保存用户请求的数据。这对于需要跟踪用户状态、或在用户交互中保留上下文的应用程序非常有用。

  • 全局会话保持:用户共享历史信息
  • 用户会话保持:用户独享历史信息

import gradio as gr


# 全局记录
def test01():
    states = []

    def response(content):
        states.append(content)
        return content, '\n'.join(states)

    app = gr.Interface(fn=response, inputs='text', outputs=['text', 'text'])
    app.launch()


# 用户记录
def test02():

    def response(content, history):
        history.append(content)
        return content, '\n'.join(history), history

    # 输入和输出必须有且只有 gr.State()
    # 临时记忆,刷新浏览器后信息丢失
    history = gr.State([])
    app = gr.Interface(fn=response,
                       inputs=['text', history],
                       outputs=['text', 'text', history])
    app.launch()

if __name__ == '__main__':
    test02()

3. 提示信息

import gradio as gr

def response(text):

    if text in ['i', 'I']:
        gr.Info('这是普通消息', duration=1)
        return 'no'

    if text in ['w', 'W']:
        gr.Warning('这是警告消息', duration=1)
        return 'no'

    if text in ['e', 'E']:
        raise gr.Error('这是错误消息', duration=3)

    return 'OK'


def test():
    demo = gr.Interface(response, inputs='text', outputs='text')
    demo.launch(show_error=True, debug=True)


if __name__ == "__main__":
    test()

4. 迭代输出

import gradio as gr
import time

def test():

    # 注意:只需将 fn 函数修改为 yield 生成器
    def response(message, history):
        data = '风起时,叶子轻轻摇,无声地诉说着秋的寂寥。云在天边低语,柔和轻飘,像是在远方寻找着归巢。'
        output = ''
        for index in range(len(data)):
            time.sleep(0.2)
            output += data[index]
            yield output

    gr.ChatInterface(fn=response, type='messages').launch()

if __name__ == '__main__':
    test()

5. 选项卡

import gradio as gr
import random


def test():

    def respond1(message, history):
        return random.choice(['Hello', '你好'])
    interface1 = gr.ChatInterface(fn=respond1, type='messages')

    def respond2(num):
        return num + 100
    interface2 = gr.Interface(respond2, inputs='number', outputs='number')

    # 创建标签页
    gr.TabbedInterface(interface_list=[interface1, interface2],
                       tab_names=['聊天界面', '传统界面'],
                       title='交互式界面').launch()


if __name__ == '__main__':
    test()

未经允许不得转载:一亩三分地 » 《Python Gradio》(四)常用效果
评论 (0)

7 + 4 =