pythonnamed-parametersgradio

How can I have the value of a Gradio block be passed to a function's named parameter?


Example:

import gradio as gr

def dummy(a, b='Hello', c='!'):
    return '{0} {1} {2}'.format(b, a, c)

with gr.Blocks() as demo:
    txt = gr.Textbox(value="test", label="Query", lines=1)
    txt2 = gr.Textbox(value="test2", label="Query2", lines=1)
    answer = gr.Textbox(value="", label="Answer")
    btn = gr.Button(value="Submit")
    btn.click(dummy, inputs=[txt], outputs=[answer])
    gr.ClearButton([answer])

demo.launch()

enter image description here

How can I have the value of txt2 be given to the dummy()'s named parameter c?


Solution

  • As far as I know, Gradio doesn't directly allow it. I.e., it doesn't allow something like this:

    btn.click(fn=dummy, inputs={"a": txt, "c": txt2}, outputs=answer)
    

    In this specific case, if you can't modify the dummy function then I would rearrange the parameters with the following function:

    def rearrange_args(func):
        def wrapper(*args):
            a, c = args
            return func(a, c=c)
        return wrapper
    

    Now, you just need to modify your example as follows:

    btn.click(rearrange_args(dummy), inputs=[txt, txt2], outputs=[answer])