import gradio as gr def f(message: str): return message.upper() demo = gr.Interface(f, inputs="text", outputs="text") demo.launch()
import numpy as np import gradio as gr def sepia(input_img): sepia_filter = np.array( [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]) sepia_img = input_img.dot(sepia_filter.T) return sepia_img / sepia_img.max() demo = gr.Interface(sepia, "image", "image") demo.launch()
import gradio as gr with gr.Blocks() as demo: inn = gr.Textbox(label="這是個輸入") out = gr.Textbox(label="這是個輸出") btn = gr.Button("大寫!") def f(s: str): return s.upper() btn.click(f, inn, out) demo.launch()
import gradio as gr with gr.Blocks() as demo: bot = gr.Chatbot().style(height=600) msg = gr.Textbox() def SendMessage(msg: str, history: list): resp = "喵喵喵" history.append([msg, resp]) return None, history msg.submit(SendMessage, [msg, bot], [msg, bot]) demo.launch()
使用 Session State 控制每個使用者獨立的狀態
import gradio as gr with gr.Blocks() as demo: cart = gr.State([]) def add_item(cart, item): cart.append(item) return cart, ", ".join(cart) inn = gr.Textbox() out = gr.Textbox() inn.submit(add_item, [cart, inn], [cart, out]) demo.launch()
可以自訂主題、字體、標題、圖示和 CSS 控制
import gradio as gr title = "Meow Meow Meow" css = "#input_text {padding: 50px !important}" font = [gr.themes.GoogleFont("Pacifico")] theme = gr.themes.Soft(font=font) with gr.Blocks(theme=theme, title=title, css=css) as demo: chatbot = gr.Chatbot().style(height=600) message = gr.Textbox(elem_id="input_text") def SendMessage(msg: str, history: list): resp = "**Meow Meow Meow**" # 支援 Markdown history.append([msg, resp]) return None, history message.submit(SendMessage, [message, chatbot], [message, chatbot]) demo.launch(favicon_path="Data/Duck.png")
Demo Time!