|
import gradio as gr |
|
|
|
text_dict = {} |
|
|
|
def predict(text, url_params, room=None , msg=None, request: gr.Request =None): |
|
|
|
text_input = gr.Text(url_params['text_input']) |
|
msg_id = url_params['msg_id'] |
|
text_dict[msg_id] = url_params |
|
return [f"Hello {text}!!", url_params, text_input] |
|
|
|
def getState(text , url_params): |
|
msg_id = url_params['msg_id'] |
|
if text_dict.get(msg_id): |
|
data = text_dict[msg_id] |
|
text_input = gr.Text(data['text_input'], interactive=False) |
|
return [f"Hello {data['text_input']}" , url_params, text_input] |
|
return ["", url_params, ""] |
|
|
|
get_window_url_params = """ |
|
function(text_input, url_params) { |
|
console.log(text_input, url_params); |
|
const params = new URLSearchParams(window.location.search); |
|
url_params = Object.fromEntries(params); |
|
text_input = url_params['text_input']; |
|
document.getElementById('textbox').value = url_params['text_input']; |
|
return [text_input, url_params]; |
|
} |
|
""" |
|
|
|
get_space_data = """ |
|
function(text_input, url_params) { |
|
const params = new URLSearchParams(window.location.search); |
|
url_params = Object.fromEntries(params); |
|
text_input = url_params['text_input']; |
|
return [text_input, url_params] |
|
} |
|
""" |
|
|
|
set_window_url_params = """ |
|
function(text_input, url_params) { |
|
const params = new URLSearchParams(window.location.search); |
|
params.set("text_input", text_input); |
|
url_params = Object.fromEntries(params); |
|
const queryString = '?' + params.toString(); |
|
//window.history.replaceState(null, document.title, `${window.location.pathname}?${params.toString()}`); |
|
// this next line is only needed inside Spaces, so the child frame updates parent |
|
window.parent.postMessage({ queryString: queryString }, "*") |
|
return [text_input, url_params]; |
|
} |
|
""" |
|
with gr.Blocks() as block: |
|
url_params = gr.JSON({}, visible=True, label="URL Params") |
|
text_input = gr.Textbox("",label="Input", elem_id="textbox") |
|
text_output = gr.Text(label="Output", elem_id="output") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
example = gr.Examples([["adam"]], [text_input], text_output) |
|
|
|
btn2 = gr.Button("Submit") |
|
btn2.click(fn=predict, inputs=[text_input, url_params], |
|
outputs=[text_output, url_params], js=set_window_url_params) |
|
block.load( |
|
fn=getState, |
|
inputs=[text_input, url_params], |
|
outputs=[text_output, url_params, text_input], |
|
js=get_space_data |
|
) |
|
block.launch(debug=True) |