[英]How to process data before downloading using st.download_button with on_click callback?
I have an app running where my model gives result a np.ndarray
and I'm showing the results as st.image(result_matrix)
.我有一个运行的应用程序,我的 model 给出结果np.ndarray
并且我将结果显示为st.image(result_matrix)
。 I want to add a functionality where I want to give my users the ability to download this image but the problem is that I have to convert to that to PIL.Image
and send the buffer.getvalue()
as input to this button.我想添加一个功能,让我的用户能够下载此图像,但问题是我必须将其转换为PIL.Image
并将buffer.getvalue()
作为输入发送到此按钮。 I can do this too but my users don't download very often and to save the computation power and load, I'm not converting EVERY result to PIL.Image
.我也可以这样做,但我的用户并不经常下载,为了节省计算能力和负载,我不会将每个结果PIL.Image
。
Is there any functionality where you can download the data, after processing it, on demand?是否有任何功能可以让您在处理数据后按需下载数据?
I tried doing the below but gave me obvious error that it doesn't accept numpy
array:我尝试执行以下操作,但给了我明显的错误,它不接受numpy
数组:
import streamlit as st
from PIL import Image
import numpy as np
from io import BytesIO
st.session_state['result'] = some_numpy_RGB_array
def process_image():
img = Image.fromarray(st.session_state['result'])
buffer = BytesIO()
img.save(buffer, format="jpeg")
st.session_state['result'] = buffer.getvalue()
_ = st.download_button(label="Download",data=st.session_state['result'],file_name="image.jpeg",mime="image/jpeg",on_click=process_image)
I'm only aware of the workaround given here :我只知道这里给出的解决方法:
import streamlit as st
def generate_report(repfn):
with open(repfn, 'w') as f:
f.write('Report')
st.write('done report generation')
if st.button('generate report'):
repfn = 'report.pdf'
generate_report(repfn)
with open(repfn, "rb") as f:
st.download_button(
label="Download report",
data=f,
file_name=repfn)
It's not ideal, because the user has to click two buttons: one to generate the (in your case) image, and a second one to actually download it.这并不理想,因为用户必须单击两个按钮:一个用于生成(在您的情况下)图像,第二个用于实际下载它。 But I guess it's better than nothing.但我想总比没有好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.