Guest User

streamlit-caching-multithreading

a guest
Oct 19th, 2020
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import numpy as np
  3. import requests
  4. import streamlit as st
  5. from concurrent.futures import ThreadPoolExecutor
  6.  
  7. @st.cache(suppress_st_warning=True, allow_output_mutation=True)
  8. def make_image(id, opacity, column_index):
  9.     print('requesting image from api')
  10.     print(f'id:{id} oppacity:{opacity}, column:{column_index}')
  11.     # image get request, normally we would load the image from disk
  12.     img = requests.get(url='https://picsum.photos/100/100')
  13.     return img.content
  14.  
  15.  
  16. # standard caching without specifiying the hash func gives: UnhashableTypeError: Cannot hash object of type streamlit.delta_generator.DeltaGenerator, found in the arguments of show_image().
  17. # @st.cache(suppress_st_warning=True,allow_output_mutation=True)
  18. def show_image(id, column, column_index):
  19.     print('showing image')
  20.     with column:
  21.         category = st.selectbox('category', ['base', 'ground truth', 'prediction'], key=str(column_index)+ 'cat' + str(id))
  22.  
  23.         print(f'cat: {category}')
  24.  
  25.         oppacity = st.select_slider(
  26.             "Oppacity",
  27.             [round(i, 2) for i in np.linspace(0, 1, 21).tolist()],  # dat_filtered["x1"].tolist()
  28.             value=0.5,
  29.             key=str(column_index) + 'op' + str(id)
  30.         )
  31.  
  32.         st.image(
  33.             make_image(id=id, opacity=oppacity, column_index=column_index),
  34.             # make_caption(d),
  35.             use_column_width=False,
  36.             output_format="PNG",
  37.             channels="RGB",
  38.         )
  39.  
  40.  
  41. def show_image_threadpool_test(id, column, column_index):
  42.     print(f'threadpool: id: {id}, column: {column}, column_index: {column_index}')
  43.  
  44. ######################################
  45. ######################################
  46. st.beta_set_page_config(layout="wide")
  47.  
  48. column1, column2 = st.beta_columns(2)
  49.  
  50. #Regular FOR loop
  51. for i in range(0, 200):
  52.     show_image(i, column1, column_index=0)
  53.     show_image(i, column2, column_index=1)
  54.  
  55. #ThreadPoolExecutor
  56. #with ThreadPoolExecutor(max_workers=20) as exec:
  57. #    for i in range(0, 200):
  58. #        #this needs some work to sync both images, so they display next to each other
  59. #        #as completed could help
  60. #        exec.submit(show_image_threadpool_test, i, column1, 0)
  61. #        exec.submit(show_image_threadpool_test, i, column2, 1)
  62.  
Add Comment
Please, Sign In to add comment