docs
stringclasses
4 values
category
stringlengths
3
31
thread
stringlengths
7
255
href
stringlengths
42
278
question
stringlengths
0
30.3k
context
stringlengths
0
24.9k
marked
int64
0
1
streamlit
Using Streamlit
Load Time and JavaScript
https://discuss.streamlit.io/t/load-time-and-javascript/21164
how do I solve this in streamlit where I don’t know how their js works or how do I make them load at the end of the file?
Hi @Kanjani_Kabir, welcome to the Streamlit community! Are you actually experiencing an issue with Streamlit or did you see this in the developer console and it worried you? In general, to make a package like Streamlit work, there has to be a lot of boilerplate JS code “just in case” new widgets show up. Meaning, the front-end code has to account for all of the widgets that might get passed from the Python backend. The analysis tools in the browser is just highlighting that if the page always stayed the same there is JS that could be removed. But since the point of Streamlit is to make writing apps from Python possible, there really isn’t a way to remove the JS that makes all that possible. Best, Randy
0
streamlit
Using Streamlit
Using step lower than 0.01 for slider with floats
https://discuss.streamlit.io/t/using-step-lower-than-0-01-for-slider-with-floats/21211
Hello, I am using a slider with float values, but it seems that choosing a step lower than 0.01, for example 0.001, is treated as if it was 0.01. Any solution for fixing this?
Hi @HugoLaurencon, welcome to the Streamlit community! You should be able to set the precision as shown by the following example: About number_input for very small number Using Streamlit Hi @Sunix_Liu - Adding the format parameter worked for me: import streamlit as st temp = st.number_input( label="test", min_value=0.000000, step=0.000001, max_value=0.0005, value=0.0000045, format="%f", ) [image] Best, Randy Best, Randy
1
streamlit
Using Streamlit
Formatting Numbers with AgGrid
https://discuss.streamlit.io/t/formatting-numbers-with-aggrid/21232
Hello, My code and screen shot are below. How can I format the numbers in columns to percentage or round a number ? df_exc= pd.read_excel(yol) gb = GridOptionsBuilder.from_dataframe(df_exc) gb.configure_pagination() gb.configure_column("Env_Oran", cellStyle={'color': 'red'}) gb.configure_selection(selection_mode="single", use_checkbox=True) gridOptions = gb.build() AgGrid(df_exc, gridOptions=gridOptions) #data = AgGrid(df_exc, gridOptions=gridOptions, enable_enterprise_modules=True, allow_unsafe_jscode=True, update_mode=GridUpdateMode.SELECTION_CHANGED) image859×815 115 KB
I found such a solution using pandas round function and gb.configure_column df_exc['Env_Oran']= df_exc['Env_Oran']*100 #df_exc['Env_Oran']= df_exc['Env_Oran'].round(2) if os.path.exists(yol)==True: 'Dosya Burda bir daha hesaplama' else: 'Dosya yok' gb = GridOptionsBuilder.from_dataframe(df_exc) gb.configure_pagination() gb.configure_column("Env_Oran", type=["customCurrencyFormat"], custom_currency_symbol="%")
0
streamlit
Using Streamlit
Converting PortAudio to Webrtc
https://discuss.streamlit.io/t/converting-portaudio-to-webrtc/21147
@whitphx I am trying to convert my code from pyaudio to webrtc. This is how I am currently consuming the audio input from Microphone. I see that Webrtc uses pydub instead of pyaudio. How can I convert this to webrtc? RATE = 16000 CHUNK = int(RATE / 10) # 100ms with MicrophoneStream(RATE, CHUNK, device=args.input_device) as stream: audio_generator = stream.generator() class MicrophoneStream(object): """Opens a recording stream as a generator yielding the audio chunks.""" def __init__(self, rate, chunk, device=None): self._rate = rate self._chunk = chunk self._device = device # Create a thread-safe buffer of audio data self._buff = queue.Queue() self.closed = True def __enter__(self): self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, input_device_index=self._device, channels=1, rate=self._rate, input=True, frames_per_buffer=self._chunk, stream_callback=self._fill_buffer, ) self.closed = False return self def __exit__(self, type=None, value=None, traceback=None): self._audio_stream.stop_stream() self._audio_stream.close() self.closed = True # Signal the generator to terminate so that the client's # streaming_recognize method will not block the process termination. self._buff.put(None) self._audio_interface.terminate() def _fill_buffer(self, in_data, frame_count, time_info, status_flags): """Continuously collect data from the audio stream, into the buffer.""" self._buff.put(in_data) return None, pyaudio.paContinue def generator(self): while not self.closed: chunk = self._buff.get() if chunk is None: return data = [chunk] while True: try: chunk = self._buff.get(block=False) if chunk is None: return data.append(chunk) except queue.Empty: break yield b''.join(data) def stop(self): self.__exit__()
I can’t help because I’m not familiar with PyAudio. If there are anyone who have experiences with PyAudio, please answer this question. What I can say is that pydub is not mandatory to deal with audio streams with streamlit-webrtc. I just used it in the sample app as an example, but it’s independent from WebRTC stuff. Crossposted to github.com/whitphx/streamlit-webrtc Converting PortAudio to Webrtc opened Jan 19, 2022 arunraman I am trying to convert my code from pyaudio to webrtc. This is how I am curr…ently consuming the audio input from Microphone. I see that Webrtc uses pydub instead of pyaudio. How can I convert this to webrtc? ``` RATE = 16000 CHUNK = int(RATE / 10) # 100ms with MicrophoneStream(RATE, CHUNK, device=args.input_device) as stream: audio_generator = stream.generator() ``` ``` class MicrophoneStream(object): """Opens a recording stream as a generator yielding the audio chunks.""" def __init__(self, rate, chunk, device=None): self._rate = rate self._chunk = chunk self._device = device # Create a thread-safe buffer of audio data self._buff = queue.Queue() self.closed = True def __enter__(self): self._audio_interface = pyaudio.PyAudio() self._audio_stream = self._audio_interface.open( format=pyaudio.paInt16, input_device_index=self._device, channels=1, rate=self._rate, input=True, frames_per_buffer=self._chunk, stream_callback=self._fill_buffer, ) self.closed = False return self def __exit__(self, type=None, value=None, traceback=None): self._audio_stream.stop_stream() self._audio_stream.close() self.closed = True # Signal the generator to terminate so that the client's # streaming_recognize method will not block the process termination. self._buff.put(None) self._audio_interface.terminate() def _fill_buffer(self, in_data, frame_count, time_info, status_flags): """Continuously collect data from the audio stream, into the buffer.""" self._buff.put(in_data) return None, pyaudio.paContinue def generator(self): while not self.closed: chunk = self._buff.get() if chunk is None: return data = [chunk] while True: try: chunk = self._buff.get(block=False) if chunk is None: return data.append(chunk) except queue.Empty: break yield b''.join(data) def stop(self): self.__exit__() ```
0
streamlit
Using Streamlit
Selection is sometimes not returned from custom widgets
https://discuss.streamlit.io/t/selection-is-sometimes-not-returned-from-custom-widgets/21202
Hi, I have a streamlit app which uses the AgGrid component to make rows in a table selectable and the plotly_events component to get feedback from clicked points in charts. Both components show the same behaviour, that the feedback sometimes just doesn’t work and the return value is emtpy. It does however work sometimes, like 50% of the time, so I am not sure if this is a bug on the streamlit side since it happends for both components independently. Has anybody obvserved similar issues? streamlit version is 1.3.1
I managed to build a minimal example for this which has a quite interesting behaviour. The selection feedback of AgGrid works in this code but if I remove the caching of the dataframe it breaks it. I have seen somewhat similar issues with selection feedback with the plotly_events component as well so possibly it is a streamlit side bug. How to reproduce: start the app and select some rows press submit, it will display the selected rows now comment out the caching line in the code reload the page and repeat the first two steps, for me the selection no longer works now import streamlit as st from st_aggrid import AgGrid, GridOptionsBuilder import pandas as pd import numpy as np @st.experimental_memo # commenting this line out breaks the selection feedback for me as the "selected_rows" entry in the grid_response is always empty def get_df(): df = pd.DataFrame(columns=['foo','bar','baz'], data=np.random.choice(range(10), size=(100000,3))) return df df = get_df() gb = GridOptionsBuilder.from_dataframe(df) gb.configure_default_column(value=True, enableRowGroup=True, aggFunc=None, editable=False) gb.configure_selection(selection_mode="multiple", use_checkbox=True) with st.form("table_form", clear_on_submit=False): grid_response = AgGrid(df, gridOptions=gb.build(), height=700, data_return_mode="AS_INPUT", update_mode="SELECTION_CHANGED")#, enable_enterprise_modules=True)#.style.apply(highlight_clusters, axis=1)) st.write(f"grid_response {grid_response}") selected = grid_response['selected_rows'] st.write(f"selected {selected}") if st.form_submit_button("Submit"): pass
0
streamlit
Using Streamlit
Best (fastest) practice to display live 2D data
https://discuss.streamlit.io/t/best-fastest-practice-to-display-live-2d-data/19895
Dear all! I have a detector which produces 2D images at video rates and higher. However, for live imaging rates in the range 10 Hz and more would be sufficient. Data comes as numpy arrays. I face problems, when I want to display the data at the wanted rates. The following code mocks up different ways to do this with streamlit. I am by no means a python - and especially no asyncio - expert, though. display, get the data, rerun get the data, display, rerun do displaying and data taking asynchronously The third option does not need a st.experimental_rerun(). Part of the communication is done via streamlit’s st.sessions_state which is not always mandatory, but keeps the examples as similar as possible. Version 2 does not work well at all. I see only a grayed out image. Versions 1&3 only work up to delays of about 0.25 secs, only I am doing this out of my home office using a ssh tunnel to a server at work over 100 MBit/s connection. I have no idea how to speed up this, but I guess that there is a way, as for example watching youtube videos about streamlit is not a problem at all. Perhaps streamlit is not the way to go for this type of application? Thanks a lot for any thoughts on this! Best wishes Markus import streamlit as st import numpy as np import time import asyncio # -------------------------------------------------------------- def ui(): if 'image' in st.session_state: st.image(st.session_state['image']) def work(delay): time.sleep(delay) st.session_state['image'] = np.random.random((512, 512)) # -------------------------------------------------------------- # -------------------------------------------------------------- async def async_ui(): with st.session_state['placeholder']: ui() r = await asyncio.sleep(0.01) async def async_work(delay): work(delay) r = await asyncio.sleep(0.01) # -------------------------------------------------------------- # -------------------------------------------------------------- def work_before_display(delay=1): work(delay) ui() # -------------------------------------------------------------- def display_before_work(delay=1): ui() work(delay) # -------------------------------------------------------------- async def do_all_asynchronously(delay=1): if 'tasks' in st.session_state: for t in st.session_state['tasks']: t.cancel() coroutines = [async_work(delay), async_ui()] tasks = [] for s in coroutines: tasks.append(asyncio.ensure_future(s)) if tasks: st.session_state['tasks'] = tasks res = await asyncio.gather(*tasks) if __name__ == '__main__': if 'placeholder' not in st.session_state: st.session_state['placeholder'] = st.empty() delay = 0.25 #display_before_work(delay=delay) #work_before_display(delay=delay) asyncio.run(do_all_asynchronously(delay=delay)) st.experimental_rerun() see also Avoid fading output during longer background activity Using Streamlit following up on this: what I did in my script was, that I separated calculation/data acquisition tasks, work(), from the stuff that does the displaying via streamlit, ui(). The script first runs ẁork() followed by ui(). What I observed, was that work() blocked part of streamlit activity which resulted in grayed-out widgets. However, I now simply reversed the sequence, i.e. first ui() and than work(), which leads to better displaying performance. It might be necessary to do a st.experimental_re… Issue with asyncio run in streamlit Using Streamlit Hi guys ! I was trying to get something with a stream working in streamlit. ( no pun intended ) I tried a couple of approaches with threading and finished my search on asyncio.run with a small coroutine and for the most part it works really well. No need for any fancy code just a asyncio.run at the end. But there’s a small problem, I am seeing None printed at every run of loop. Any idea what might be causing this ? This is my script I am using to show a simple clock import asyncio import st…
an addition: after some time variant 1 errors with RecursionError: maximum recursion depth exceeded in comparison You can now view your Streamlit app in your browser. URL: http://127.0.0.1:8501 2021-12-10 09:50:02.755 InMemoryFileManager: Missing file 4f237411c238189ad04bff875b2cbae4ea5ef8e4c979c3413999b321.jpeg 2021-12-10 09:50:52.730 Traceback (most recent call last): File ".../lib/python3.8/site-packages/streamlit/script_runner.py", line 354, in _run_script exec(code, module.__dict__) File ".../test.py", line 55, in <module> display_before_work(delay=delay) File ".../test.py", line 39, in display_before_work ui() File ".../test.py", line 23, in ui st.image(st.session_state['image']) File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 120, in image marshall_images( File ".../python3.8/site-packages/streamlit/elements/image.py", line 370, in marshall_images proto_img.url = image_to_url( File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 272, in image_to_url data = _np_array_to_bytes(data, output_format=output_format) File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 181, in _np_array_to_bytes return _PIL_to_bytes(img, format) File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 167, in _PIL_to_bytes image.save(tmp, format=format, quality=quality) File ".../lib/python3.8/site-packages/PIL/Image.py", line 2240, in save save_handler(self, fp, filename) File ".../lib/python3.8/site-packages/PIL/JpegImagePlugin.py", line 745, in _save if isinstance(exif, Image.Exif): File ".../lib/python3.8/abc.py", line 98, in __instancecheck__ return _abc_instancecheck(cls, instance) RecursionError: maximum recursion depth exceeded in comparison
0
streamlit
Using Streamlit
连接数据库报错?
https://discuss.streamlit.io/t/topic/21097
从官网拷贝下来的代码,为什么运行时报错呢,缺少什么文件吗? image810×716 39.7 KB image715×829 57.6 KB
可以试试Pymysql, 也可以关注微信公众号:Streamlit 里面有连接数据库的案例
0
streamlit
Using Streamlit
Streamlit justified text
https://discuss.streamlit.io/t/streamlit-justified-text/21043
Hi guys. Is there a way to display text in a justified way? Like we have in Microsoft Word? e.g:
Hi @feliperoque - It appears that you can do so using CSS, though this article suggests that maybe you shouldn’t: Design for Hackers – 14 Aug 14 Justify text with HTML/CSS? Don't do it! - Design for Hackers 1 It’s 3 in the morning, and you’re putting the final touches on your layout. It looks clean, with everything in its place – lined up on the grid. You squint from afar. “The edges of these type blocks look uneven,” you say to yourself. You... Est. reading time: 4 minutes How to add CSS to a Streamlit app using st.markdown is demonstrated here: Changing the default text "Choose an option" from a multiselect widget Using Streamlit Hi @NiklausBal, welcome to the Streamlit community!! Streamlit does not expose the option to change the placeholder text for st.multiselect. As such, there is no native option to change the placeholder because it is hard-coded in the frontend. However, here is an unofficial CSS hack. I used a CSS selector to first make the default placeholder invisible. Next, I use another CSS selector to set the value of the placeholder. This CSS is injected into the app with st.markdow… Best, Randy
1
streamlit
Using Streamlit
Getting error:[manager] Error checking Streamlit healthz: Get “http://localhost:8501/healthz”:
https://discuss.streamlit.io/t/getting-error-manager-error-checking-streamlit-healthz-get-http-localhost-8501-healthz/8882
Hello, I successfully deployed my app in streamlit But when I try to run it more than 3 time, It crashes. The log says [manager] Error checking Streamlit healthz: Get "http://localhost:8501/healthz": dial tcp 127.0.0.1:8501: connect: connection refused [manager] Streamlit server consistently failed status checks I understand the error is because of resource allocation, but I am using st.cache here, so the file won’t be downloaded again @st.cache def download1(url1): url = url1 filename = url.split('/')[-1] urllib.request.urlretrieve(url, filename) download1(“https://github.com/Anubhav1107/streamlit/releases/download/fasterrcnn.pth/fasterrcnn.pth 1”) The app is in https://share.streamlit.io/anubhav1107/streamlit/streamlit.py 16 Thanks
Hi @Anubhav1107 - In looking at your app, unfortunately I think this has to do with using Torch. As far as I can tell, your app doesn’t have any obvious flaws, but Torch is such a big dependency that running your app a few times then exhausts all available RAM, which causes the error you are seeing. I’ll forward this thread on to our product and cloud teams, so they can have another example and possibly find a solution for this. Best, Randy
0
streamlit
Using Streamlit
Unable to clear or delete columns from ‘beta_columns’
https://discuss.streamlit.io/t/unable-to-clear-or-delete-columns-from-beta-columns/12639
I’m trying to do a live interactive scorer of NBA games, but I’m having troubles at updating this scorer. To set this scorer I use the beta_columns component the way you can see in this function: # Dado unos datos necesarios, muestra un cabecero de página con la información relevante sobre un encuentro de la NBA en directo def show_live_match_header(home_score, away_score, home_team, away_team, date, hour, quarter, minutes_left): # Definimos 5 columnas para mostrar el resultado actual del partido en cada instante col1, col2, col3, col4, col5 = st.beta_columns([4, 3, 4, 3, 4]) quarter_ending = "er" if quarter == 2: quarter_ending = "do" elif quarter == 1 or quarter == 3: quarter_ending = "er" elif quarter == 4: quarter_ending = "to" # Añadimos objetos a la primera columna relacionados con el equipo local with col1: st.markdown('<center><img src=' + TEAM_ICONS_DICT[home_team] + '></center>', unsafe_allow_html=True) st.markdown("<h3 style='text-align: center; color: black;'><b>" + home_team + "</b></h3>", unsafe_allow_html=True) st.markdown("<h5 style='text-align: center; color: gray;'> (Local) </h5>", unsafe_allow_html=True) # Añadimos objetos a la segunda columna relacionados con la puntuación del equipo local en este instante with col2: st.write("") st.write("") st.write("") if home_score == -1 or away_score == -1: st.markdown("<h1 style='text-align: center; color: black;'><b>" + "-" + "</b></h1>", unsafe_allow_html=True) else: st.markdown("<h1 style='text-align: center; color: black;'><b>" + str(home_score) + "</b></h1>", unsafe_allow_html=True) st.write("") st.write("") st.write("") # Añadimos objetos a la tercera columna relacionados con información del partido como el minuto en el que está en este mismo instante with col3: st.write("") st.write("") st.write("") if home_score == -1 or away_score == -1: st.markdown("<h3 style='text-align: center; color: red;'><b>" + "El partido no ha comenzado aún" + "</b></h3>", unsafe_allow_html=True) st.markdown("<h5 style='text-align: center; color: grey;'> Hora del comienzo del partido: " + hour + " </h5>", unsafe_allow_html=True) st.markdown("<h5 style='text-align: center; color: grey;'> (" + date + ") </h5>", unsafe_allow_html=True) else: st.markdown("<h3 style='text-align: center; color: red;'><b> " + str(quarter) + quarter_ending + " Cuarto " + str(minutes_left) + "' </b></h3>", unsafe_allow_html=True) st.markdown("<h5 style='text-align: center; color: grey;'> (" + date + ", " + hour + ") </h5>", unsafe_allow_html=True) st.write("") st.write("") # Añadimos objetos a la cuarta columna relacionados con la puntuación del equipo visitante en este instante with col4: st.write("") st.write("") st.write("") if home_score == -1 or away_score == -1: st.markdown("<h1 style='text-align: center; color: black;'><b>" + "-" + "</b></h1>", unsafe_allow_html=True) else: st.markdown("<h1 style='text-align: center; color: black;'><b>" + str(away_score) + "</b></h1>", unsafe_allow_html=True) st.write("") st.write("") st.write("") # Añadimos objetos a la primera columna relacionados con el equipo local with col5: st.markdown('<center><img src=' + TEAM_ICONS_DICT[away_team] + '></center>', unsafe_allow_html=True) st.markdown("<h3 style='text-align: center; color: black;'><b>" + away_team + "</b></h3>", unsafe_allow_html=True) st.markdown("<h5 style='text-align: center; color: gray;'> (Visitante) </h5>", unsafe_allow_html=True) col5 = st.empty() return [col1, col2, col3, col4, col5] This way I obtain this results: Example of using the method once1918×1004 75.2 KB The problem comes when I try to remove the beta_columns returned in order to set new ones with each score updated. I tried to do this by this example code: # Definimos las estructuras que se mostrarán en la interfaz session_state.counter = -1 match_header = None while session_state.counter < 5: if match_header is not None: for col in match_header: col.empty() home_score = away_score = session_state.counter match_header = show_live_match_header(home_score, away_score, session_state.home_team, session_state.away_team, session_state.date, session_state.hour, 1, 10) session_state.counter = session_state.counter + 1 sleep(1) Obtaining this awful result: Awful Result :(1918×1006 151 KB I tried a lot of things, but I can’t delete the previous columns before setting the new ones. Is there another way to do this update or a chance of deleting the previous columns?
Hi @Agustin_6199 , Do you solve this problem? because I have the same one Tanks a lot
0
streamlit
Using Streamlit
Change breakpoint of columns (for mobile)
https://discuss.streamlit.io/t/change-breakpoint-of-columns-for-mobile/21058
I am developing an application that depicts various metrics on the same row, similar to the example in the documentation (Streamlit 1). Similar to the example provided in the documentation, the columns stack on mobile. Eventhough, it seems that two columns can easily fit on the same row on mobile. How can I prevent that the columns are stacked, when there is enough room for two or more columns on the same row? Is it possible to change the breakpoint?
Hi @remcoloof, welcome to the Streamlit community! Unfortunately, no, setting the breakpoints isn’t a functionality that we currently expose. It may be the case that you could specify your own CSS, but that might lead to weird blinking artifacts. To see an example of how to write CSS using st.markdown, please see the link below: Changing the default text "Choose an option" from a multiselect widget Using Streamlit Hi @NiklausBal, welcome to the Streamlit community!! Streamlit does not expose the option to change the placeholder text for st.multiselect. As such, there is no native option to change the placeholder because it is hard-coded in the frontend. However, here is an unofficial CSS hack. I used a CSS selector to first make the default placeholder invisible. Next, I use another CSS selector to set the value of the placeholder. This CSS is injected into the app with st.markdow… Best, Randy
1
streamlit
Using Streamlit
URGENT : appending boolean buttons
https://discuss.streamlit.io/t/urgent-appending-boolean-buttons/20740
Hello guys , I would like to get an appending boolean button (it displays a STOP button and when I click on it , it becomes a START button) in the “Start/Stop of BOT” coins_list = ['BTC','LTC','ETH'] # @st.cache(allow_output_mutation=True) def Input_Parameters(): return [] coin = st.selectbox('Search COIN',coins_list) st.write(coin) X1 = st.number_input('Provide Value for X1', min_value = 000000.00000 , max_value = 99999.9999 , step = 1e-5) st.write(X1) Y1 = st.number_input('Provide Value for Y1', min_value = 000000.00000 , max_value = 99999.9999, step = 1e-5) st.write(Y1) Z1 = st.number_input('Quantity Z1', min_value = 000000.00000, max_value = 99999.9999, step = 1e-5) st.write(Z1) n_loop = st.number_input('Provide Value for N (Loop)',min_value = 1 ,max_value = 99999, step = 1) current_price = web.DataReader(coin + "-USD","yahoo","2018-1-1",dt.now())["Close"][-1] TradingTime = dt.now().strftime("%m-%d-%Y at %H:%M:%S") st.write("current price of the coin : " + str(current_price)) col1, col2, col3,col4,col5 = st.columns(5) with col3: start = st.button("Start the Bot") commission = 0 #current_price*(1/100) profit = 0 df = pd.DataFrame(Input_Parameters()) session_state = SessionState.get(df=df) if start : status = "Running" session_state.df = session_state.df.append( {"Trading Time" : TradingTime , "coin pair" : coin, "Status": status, "Start/Stop of BOT": st.button("STOP"), "Current Price of the coin pair": current_price, "Comission Detected": commission, "profit made": profit },ignore_index=True ) Thanks for your help
anyone guys ???
0
streamlit
Using Streamlit
Load and Display Files from Local Storage
https://discuss.streamlit.io/t/load-and-display-files-from-local-storage/20972
Hey Guys, I have a file manager that lists all uploaded files from the upload section. My question is, how can I retrieve my files from my tempDir and display them? os.open just gives me a string than the actual data: Bildschirmfoto 2022-01-14 um 11.46.202156×1380 202 KB below is my code: # my files menu if (choice == menu[1]): col1, col2, col3 = st.columns([4, 1, 1]) fileList = [] filePaths = [] fileId = 0 for root, dirs, files in os.walk("tempDir"): for file in files: filePath = os.path.join(root, file) fileName = os.path.join(file) fileList.append(fileName) filePaths.append(filePath) for item in fileList: fileKey = "fileKey_{}".format(fileId) with st.expander(item): with open(filePaths[fileId], 'rb') as file: agree = st.checkbox('Display Data 📊', key=fileKey) if agree: st.write(file) st.download_button("Download", item, key=fileKey) fileId += 1 st.selectbox("Select Item", fileList) with st.expander("Raw Output"): st.write(fileList)
Hi @fuccDebugging - I’m not sure I understand your question. You are retrieving files from the local filesystem and open doesn’t work? Best, Randy
0
streamlit
Using Streamlit
Performance Problems with many small dataframes
https://discuss.streamlit.io/t/performance-problems-with-many-small-dataframes/20875
I have an streamlit app that I use as a labeling tool. The user gets a list of many small dataframes with a checkbox each and a submit button at the end of the form to submit the labels. When I use st.write to write the dataframes to the browser, the browser has serious performance issues (100% cpu usage on one core that does not go away). The server side script has no performance problems. When I use the AgGrid Component instead of st.write to write the dataframes, then I don’t see this issue. Just wanted to let you guys know about this.
Hi @thunderbug1 - Do you have a code example that demonstrates this? Best, Randy
0
streamlit
Using Streamlit
Is it possible to run a local script from my streamlit app with a button?
https://discuss.streamlit.io/t/is-it-possible-to-run-a-local-script-from-my-streamlit-app-with-a-button/20921
Hi there, in my app I have another script that updates data from yahoo finance. I am wondering if it is possible to run this script from my streamlit app. Thank you, J
Hi @jorgeggpool, welcome to the Streamlit community! In general, the answer is almost always ‘yes’, it’s just a matter of figuring out the syntax. What have you tried so far? Best, Randy
0
streamlit
Using Streamlit
File_uploader DuplicateWidgetID key error
https://discuss.streamlit.io/t/file-uploader-duplicatewidgetid-key-error/20919
I want to receive different data sheets from users.First, users need to click to determine their own data table type; Then upload the file; After that, the program performs a series of operations. But the problem I encounter is that when the user changes the options, the previously uploaded files will not disappear.When the file is manually closed and uploaded again, an error will be reported. The following is my code. In order to facilitate understanding, I simplified some programs, but the functions are consistent def getFile(): uploaded_file = st.file_uploader("Please") if uploaded_file is not None: df = pd.read_excel(uploaded_file) AgGrid( df.head(3), fit_columns_on_grid_load=False, height=120, editable=False, ) return df if __name__ == '__main__': a=input() if a=='a': data=getFile() # ... ... else: data=getFile() # ... ...
Hi @Dcclandbest, welcome to the Streamlit community! When you place uploaded_file = st.file_uploader("Please") inside of a function that is called over and over again, you are creating a new instance of file_uploader each time rather than re-using the same one over and over. And because you create several instances of file_uploader, it’s yelling that you don’t have a key argument to make each of them have a unique identifier. I suspect moving that line outside of the function will fix your issue. Best, Randy
0
streamlit
Using Streamlit
What is the error with my project? This is my first time doing this
https://discuss.streamlit.io/t/what-is-the-error-with-my-project-this-is-my-first-time-doing-this/20918
By the way this is my repository. •SpeechEmoRec/sample.py at main · jonsarz16/SpeechEmoRec · GitHub 1 This is the response i get…[picture] XRecorder_13012022_1734291080×1920 278 KB
Hi @jonsarz16, welcome to the Streamlit community! In your screenshot, the black button “Manage app” shows the actual logs, which frequently shows the error. Can you open that panel and copy what you see there into this thread? Best, Randy
0
streamlit
Using Streamlit
ImportError in linux
https://discuss.streamlit.io/t/importerror-in-linux/20905
After I successfully install streamlit-1.3.1,an ImportError comes forth when I import streamlit (python version:3.7.11).I don’t know how to fix it. Here is my code image1289×596 108 KB
Hi @phoenix - It looks like one of the packages you are trying to use requires zoneinfo, which if I’m reading the docs correctly only became available in Python 3.9 (you’re using Python 3.7). Best, Randy
0
streamlit
Using Streamlit
Map Plotting using streamlit.map()
https://discuss.streamlit.io/t/map-plotting-using-streamlit-map/765
Whenever I try to plot the latitudes and longitudes spread all over the USA map using streamlit.map() function it works fine but, when the map pops up I have to hover over the desired location and zoom it in order to see the red points plotted. How can I make those points visible without zooming in the map?
Hi @ShivamBhirud welcome to the community and sorry this isn’t working for you. St.map is meant to be a very simple and straightforward function and unfortunately doesn’t allow a lot of customization like setting radius size (and obviously defaults to a too small size!). I went ahead and made a bug report for this that you can track here: https://github.com/streamlit/streamlit/issues/577 192 The good news is you can use deck.gl to make your map; st.deck_gl_chart is a little more code but a lot more customizable. Here’s an example of setting the zoom location, adding a radius, setting a minimum radius, and also changing the color of the dots to hot pink: data = pd.DataFrame({ 'awesome cities' : ['Chicago', 'Minneapolis', 'Louisville', 'Topeka'], 'lat' : [41.868171, 44.979840, 38.257972, 39.030575], 'lon' : [-87.667458, -93.272474, -85.765187, -95.702548] }) # Adding code so we can have map default to the center of the data midpoint = (np.average(data['lat']), np.average(data['lon'])) st.deck_gl_chart( viewport={ 'latitude': midpoint[0], 'longitude': midpoint[1], 'zoom': 4 }, layers=[{ 'type': 'ScatterplotLayer', 'data': data, 'radiusScale': 250, 'radiusMinPixels': 5, 'getFillColor': [248, 24, 148], }] ) Let me know if there’s anything else I can help with!
0
streamlit
Using Streamlit
PyplotGlobalUseWarning - CauseImpact
https://discuss.streamlit.io/t/pyplotglobalusewarning-causeimpact/21156
Hi, I’m getting a warning - I’ve looked at other threads but still can’t figure it out on my use case. Here is my code in it’s entirety: import pandas as pd from causalimpact import CausalImpact import streamlit as st df = pd.DataFrame({'date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06'], 'value': [1539, 1696, 1427, 1341, 1426, 1471]}) def get_pre_post(data, change): pre_start = min(data.index) pre_end = int(data[data['date'] == change].index.values) post_start = pre_end + 1 post_end = max(data.index) pre_period = [pre_start, pre_end] post_period = [post_start, post_end] return pre_period, post_period change = '2021-01-05' pre_period, post_period = get_pre_post(df, change) ci = CausalImpact(df.drop(['date'], axis=1), pre_period, post_period, prior_level_sd=None) fig = ci.plot() st.pyplot(fig) Screenshot 2022-01-19 112623809×832 69.7 KB Any help is much appreciated (I don’t want to just disable the warning)
Hi @Grainger, This was a tricky one to figure out. I inspected the plotting source code of the pycausalimpact package and found that the ci.plot() method does not return any object. Instead, it calls plt.show(). What needs to be done is to use matplotlib get the current figure and current axes created when ci.plot() is called, and pass the resulting figure to st.pyplot(). Here’s how to do it: Solution import pandas as pd import matplotlib.pyplot as plt # required later from causalimpact import CausalImpact import streamlit as st df = pd.DataFrame({'date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06'], 'value': [1539, 1696, 1427, 1341, 1426, 1471]}) @st.experimental_memo def get_pre_post(data, change): pre_start = min(data.index) pre_end = int(data[data['date'] == change].index.values) post_start = pre_end + 1 post_end = max(data.index) pre_period = [pre_start, pre_end] post_period = [post_start, post_end] return pre_period, post_period change = '2021-01-05' pre_period, post_period = get_pre_post(df, change) ci = CausalImpact(df.drop(['date'], axis=1), pre_period, post_period, prior_level_sd=None) ci.plot() fig = plt.gcf() # to get current figure ax = plt.gca() # to get current axes st.pyplot(fig) Output image1182×1051 139 KB Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
How to reset the cache after a fixed frequency?
https://discuss.streamlit.io/t/how-to-reset-the-cache-after-a-fixed-frequency/21149
Hi , I have user case where dashboard base data gets updated in every 1 hour. For good response time I have used cache before data loading function. How I can make cache clear after say 1 hour so that user will see the refreshed data on dashboard. Thanks, Manoj Kumar
Can any one help on this? Thanks
0
streamlit
Using Streamlit
Multiple filters based on checkboxes
https://discuss.streamlit.io/t/multiple-filters-based-on-checkboxes/20920
Hi everyone! I have five checkboxes. When some of them are selected, I want my dataframe to be filtered on some specific condition. Additionally, values should be filtered with the AND logic. For example: if filter1 & filter2: df = df .loc[(some condition of filter1) & (some condition of filter2)] However, having five filters, I have to use a lot of different combinations to implement such logic (e.g. if filter1 & filter3, if filter1 & filter4, if filter1 & filter3 & filter4, and so on). Is there is a more effective way to do it without going through all the filters combinations in if statements? I checked this solution, however, it is applicable for sliders only as I understand it: Filter logic Using Streamlit Hi pvtaisne, See below for an example with multiple filters for one dataframe. Let me know if it helps you import streamlit as st import pandas as pd import numpy as np np.random.seed(0) # Seed so random arrays do not change on each rerun n_rows = 1000 random_data = pd.DataFrame( {"A": np.random.random(size=n_rows), "B": np.random.random(size=n_rows)} ) sliders = { "A": st.sidebar.slider( "Filter A", min_value=0.0, max_value=1.0, value=(0.0, 1.0), step=0.01 … I would highly appreciate any help!
Hi, you could try doing it this way: Start with a blank string (Eg. querystr = ‘’) Using your checkboxes, you can incrementally construct your combined filter, appending the result to querystr. (Eg. querystr = querystr + "Gender == ‘M’ " Gender would be the dataframe field and ‘M’ could be check box value. Similarly continue with your other checkboxes… querystr = querystr + "Race == ‘White’ ") will make the resultant query string for Gender as well as Race… And so on… Finally, you can use df.query Refer internet help docs as needed. Hope this helps,
1
streamlit
Using Streamlit
Link 360 JS library in markdown
https://discuss.streamlit.io/t/link-360-js-library-in-markdown/19825
Hi, I am trying to link a JS library for 360 photo viewer with streamlit. The photo was loaded, but the it looks like the JS library wasn’t loaded properly with the photo not being able to be interacted with. Anyone has experienced similar issues? Cheers, Will import streamlit as st def main(): st.set_page_config(page_title='BKN 360 Photo App', initial_sidebar_state = 'auto') #page_icon = favicon, st.markdown( f""" <style> .reportview-container .main .block-container{{ max-width: 1200px; padding-top: 1rem; padding-right: 1rem; padding-left: 1rem; padding-bottom: 1rem; }} </style> """, unsafe_allow_html=True, ) # main section st.subheader('Web 360 Photo App') st.markdown('<script src="https://aframe.io/releases/0.6.1/aframe.min.js"></script>', unsafe_allow_html=True) st.markdown(""" <a-scene> <a-assets> <img id="panorama" src="https://c1.staticflickr.com/5/4302/35137573294_1287bfd0ae_k.jpg" crossorigin /> </a-assets> <a-sky src="#panorama" rotation="0 -90 0"></a-sky> </a-scene> """, unsafe_allow_html=True) if __name__ == "__main__": main()
st.markdown won’t work with js you could use components.html from import streamlit.components.v1 as components
0
streamlit
Using Streamlit
Only allow the data type str for the st.text_input widget
https://discuss.streamlit.io/t/only-allow-the-data-type-str-for-the-st-text-input-widget/21157
I saw a question on StackOverflow that I wanted to answer and I stumbled upon following problem. Suppose you want to restrict the user input from the st.text_input widget. E.g. the user can only type in strings. How would you do that? My attempt: import streamlit as st def main(): st.title("Only allow text example") #only allow strings text = st.text_input('Type something', value=str) #conditional statement to check if the input is a string if type(text) == str: st.write(text + ' ' + ' ...works as its a string') else: type(text) != str st.write("Please enter a string") if __name__ == "__main__": main() If I type in 1234 as the input it outputs …1234… works as its a string. I read the documentation for this widget docs for st.input_text → st.text_input - Streamlit Docs …and I know the type argument is good for hiding the text input but I don’t know what the value argument is doing. I feel like by default all that you type into the widget is a string. Wrapping everything up into a str() is also not advisable. text = str(st.text_input('Type something', value=str))
Okay I found a solution. text.isaplha( ) works to check for the input. import streamlit as st def main(): st.title("Only allow text example") #only allow strings text = str(st.text_input('Type something')) #conditional statement to check if the input is a string if text.isalpha(): st.write(text, '...works as its a string', ) else: st.write('Please type in a string ') if __name__ == "__main__": main() So a mixture of strings and integers doesn’t work for the input any more … Input: 123abc Output: Please, enter a string
1
streamlit
Using Streamlit
Reading data from google sheets
https://discuss.streamlit.io/t/reading-data-from-google-sheets/5736
Hi Guys, First of all, I would like to appreciate the entire Streamlit team for creating such an amazing and simple to use framework for creating beautiful apps. It is simply amazing. I work as an auditor in an ed-tech organization. Part of my work involves creating interactive reports of the audits conducted so far. For this purpose, I am using Google’s Data Studio to create an interactive report. A google sheet here works as the report’s data source, so whenever a new row is added in the google sheet, the report gets updated automatically. Now, I am trying to take things to the next level by making an amazing app using Streamlit. I have some familiarity with Python already and would need some help to start creating this app. It would be great if you can point me in the right direction as to how we can connect google sheets to streamlit. Thank you in advance!
Hi @aakash_chaudhry, welcome to the Streamlit community! Here’s the official package for Google Sheets: Google Developers Python Quickstart  |  Sheets API  |  Google Developers 104 There is also a package that will read Google Sheets into a pandas dataframe. Once you have a pandas dataframe, Streamlit supports pandas pretty seamlessly: PyPI gspread-pandas 99 A package to easily open an instance of a Google spreadsheet and interact with worksheets through Pandas DataFrames. Best, Randy
0
streamlit
Using Streamlit
How to reset checkbox
https://discuss.streamlit.io/t/how-to-reset-checkbox/6441
My target: Enter a key in text box, the App will run a query and return a list of options. For each option, display a checkbox and check it by default. The options from step 1 are likely to be the same among different runs but with small difference. I don’t want to use multiselect drop down here. The issue: If I uncheck a checkbox, the state will be memorized even if the checkbox is regenerated. Yes I tried to give the a unique id for each checkbox but it will keep resetting every checkbox. A example code: import streamlit as st import numpy as np def main(): case_id = st.text_input("Please enter an ID") if case_id: options = sorted(np.random.choice([1,2,3,4,5], 4, replace=False)) pathways_bool = [st.checkbox(str(_x),True) for _x in options] if __name__ == "__main__": main() Thanks for your help!
Hey @w-markus, First, welcome to the Streamlit Community! and @h3045, With st.session_state you can have the checkbox un-check on a re-run using the on_change parameter. But as no one has posted a code example of how to reproduce this, or of the functionality you are trying to achieve it’s difficult to point you in the right direction. Session State blog post and examples 40 Does anyone have an MVP they can post that I can try locally? Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Format Integer With Comma Using Python Printf
https://discuss.streamlit.io/t/format-integer-with-comma-using-python-printf/2344
I have built a slider that has integer values between, say, 0 and 2,000,000. I would like to display the numbers with thousands-commas-separator. The documentation states: format (str or None) – A printf-style format string controlling how the interface should display numbers. This does not impact the return value. Valid formatters: %d %e %f %g %i But it isn’t clear how I could accomplish this with the format argument. Usually, in Python, this can be accomplished with: x = 1000000 print(f"{x:,}") # 1,000,000
Hey @Sean, Welcome to the forum We use the sprintf-js 53 library to handle string formatting in the client. I don’t believe this is currently possible, after looking at their documentation. Feel free to file a feature request for this functionality! However I’m not sure we’ll get to it right away, given the diversity of formats that could possibly be requested. Also, we’ve started development on plugins, so this is something you should be able to build yourself in the near future!
0
streamlit
Using Streamlit
After the session state being introduced how do I create a reset button
https://discuss.streamlit.io/t/after-the-session-state-being-introduced-how-do-i-create-a-reset-button/21124
I am now trying to create a reset button that allow the user to uncheck the boxes of all the checkboxes selected by user the Session state Example here streamlit reset app via button is good but I am creating a reproducible app and hence need to use session state api but I am not able to do it. What I tried was if 'celcius' not in st.session_state: st.session_state.celsius = False st.checkbox( "Temperature in Celsius",value=st.session_state.celsius ) a=st.button('Reset') if a: st.session_state.celsius=False but the checkbox does not change until I clear cache which is the last resort all I want is to give the user a freedom to reselect columns if he want to create different query (the button are query and reset query brings a set columns selected by user through checkbox and reset allows user to nullify selection and select again for different query)
no matter what I try like chaging it to true then false the or any combination even with callback does not reset the checkbox unless I clear cache
0
streamlit
Using Streamlit
How to Create Wizard Style App (Step 1, Step 2, Etc)
https://discuss.streamlit.io/t/how-to-create-wizard-style-app-step-1-step-2-etc/21111
I’m struggling with way to create a fixed number of steps a user can take to use the App. I’ve landed on using st.empty() and works up to first two steps, then resets back to beginning after trying to move to first step. Looking for suggestions! Thank you def write(): shown_page = 'intro' if shown_page == "intro": contIntro = st.empty() expIntro = contIntro.expander('What App Wizard Can Do', True) job_name = expIntro.text("Give this Job a Name") col1, col2 = expIntro.columns([9,1]) col1.write("") exp1_button = col2.button('To Step 1') if exp1_button: contIntro.empty() shown_page = 'Step 1' if shown_page == 'Step 1': header_text = 'Step 1' cont1 = st.empty() exp1 = cont1.expander('Step 1 of 2', True) exp1.file_uploader('Upload Data', type=None, accept_multiple_files=False) col1, col2 = exp1.columns([9,1]) col1.write("") exp1_back_button = col1.button('Back to Intro') exp1_next_button = col2.button('To Step 2') if exp1_back_button: cont1.empty() shown_page = 'Intro' if exp1_next_button: cont1.empty() shown_page = 'Step 2' if shown_page == 'Step 2': header_text = 'Step 2' cont2 = st.empty() exp2 = cont2.expander("Step 2 of 2", True) job_name = exp2.text_input("Some more info") col1, col2 = exp2.columns([9,1]) exp2_back_button = col1.button("Back to Step 1") exp2_forward_button = col2.button('To Another Setp in Future') if exp2_back_button: upload_data.write() if exp2_back_button: cont2.empty() shown_page = 'Step 2' if exp2_forward_button: cont2.empty() image1878×453 5.74 KB Then moves to Step 1 when hit ‘To Step 1’ image1779×530 7.43 KB Then I hit ‘To Step 2’ and it brings me back to Intro, when I’d expect to move to Step 2
Hi @saxon11 , take a look at stepperbar at this link. GitHub GitHub - Mohamed-512/Extra-Streamlit-Components: An all in one place, to find... 7 An all in one place, to find complex or just not available components by default on streamlit. - GitHub - Mohamed-512/Extra-Streamlit-Components: An all in one place, to find complex or just not av... Cheers
0
streamlit
Using Streamlit
How to get the file path from download_button?
https://discuss.streamlit.io/t/how-to-get-the-file-path-from-download-button/21017
Hello I have a download button, that creates a file with suffix, depending on how many files of the same name exist - this the default functionality of the st.download_button. How can I get the file path of the created/downloaded file? Or how can I force download_button to overwrite existing file, not create a new one?
Hi, the file will be saved under your defalut folder in explorer, you can check it through your explorer setting.
0
streamlit
Using Streamlit
Disabled parameter not working
https://discuss.streamlit.io/t/disabled-parameter-not-working/21090
This error produces the TypeError: number_input() got an unexpected keyword argument 'disabled’ error: # Indices of entries to extract idx = re.findall("\\d+", cols[0].text_input("Entries")) # Min. Entry and Max. Entries controls will be disabled if Entries are provided is_disabled = len(idx) > 0 # Index of first FASTA to extract (starts from 1 on UI) min_idx = ( cols[1].number_input("Min. Entry", min_value=1, value=1, disabled=is_disabled) - 1 ) # Number of entries to extract starting from min max_idx = cols[2].number_input( "Max. Entries", min_value=1, value=10, disabled=is_disabled ) According to documentation: image734×89 8.57 KB How can I fix that?
Hi @rlf037 @Svantevith , You can specify the version of Streamlit in the same manner you would for other Python dependencies in your app: App dependencies - Streamlit Docs If you’re specifying Python dependencies via a requirements.txt file, you can pin a specific version of a package. For example, to install Streamlit 1.4.0, include the following line in requirements.txt: streamlit==1.4.0 Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
Nest form inside regular button
https://discuss.streamlit.io/t/nest-form-inside-regular-button/13758
I am trying to Take some user input When a “Load” button (normal style button) is clicked, build a form from that input with N number of widgets When form_submit_button is clicked, write the widgets’ values to a database. I’ve noted the warnings in the docs about putting a button inside a form, but there is nothing about putting a form inside a button. Here is a minimal example where the user enters a film director’s name and the form is populated with all of their films, each with a widget to provide a rating. When I click the form_submit_button, the app resets but the code inside the if submitted: block is not executed. Any suggestions? import streamlit as st director = st.text_input("Director") load_button = st.button("Load films") # When the load_button clicked, the form is created and populated if load_button: # (Some code to fetch the film data from a database) # films is a list of Film objects films = load_films(director=director) # Display each film along with a widget to provide a rating with st.form(): # Catch each widget in a dictionary widget_dict = {} # Add a row to the form for every film for film in films: info_col, rating_col = st.beta_columns(2) # Put film info in left column with info_col: st.subheader(film.title) st.write(film.year) # Put a widget in the right column with rating_col: rating = st.slider( label="Rating", min_value=1, max_value=10, key=f"{director}_{film.title}", ) # Add this widget to the dict widget_dict[film.title] = rating # When you submit the form, it loops through all # widget entries and updates an external database submitted = st.form_submit_button("Submit") if submitted: # THIS CODE IS NOT TRIGGERED ON CLICK print(f"Submitting ratings for {director}") for title, rating in widget_dict.items(): write_rating_to_db(director, title, rating)
Did you end up finding a solution to this? I am having the same issue
0
streamlit
Using Streamlit
Display order of widgets when using callbacks
https://discuss.streamlit.io/t/display-order-of-widgets-when-using-callbacks/20993
I’ve made a very simple app that: Uses the file uploader widget to read in an Excel file Gets the user to choose a worksheet they’re interested in previewing using a selectbox dropdown Displays a preview of the worksheet I’m using a callback from st.selectbox to display the preview, so that it only displays after the user has actively chosen a worksheet they’re interested in. But in order to do so I need to have defined my callback function before calling st.selectbox - and that’s leading the preview to appear above the file uploader and selectbox widgets in the app, rather than where I want it, below those widgets. This is my code (Streamlit 1.3.1) and a screengrab of my output. import streamlit as st import pandas as pd # CREATE APP # Add file_uploader uploaded_file = st.file_uploader( label='Upload a file', type=['xls', 'xlsx', 'xlsm'], key='file-uploader', help=''' Upload an Excel file. The file must be closed in order for you to upload it. ''' ) # Define function that loads sheet preview def load_sheet_preview(): st.dataframe(df[st.session_state.selectbox_sheet]) # Add selectbox if uploaded_file is not None: df = pd.read_excel(uploaded_file, sheet_name=None) # sheet_name=None needs explicitly including - it isn't the default # noqa: E501 st.selectbox( key='selectbox_sheet', label='Select worksheet', options=df.keys(), on_change=load_sheet_preview ) Capture1920×1079 77.3 KB I suspect I’ll kick myself when I hear the solution but I can’t think how to get around this. Wrapping the code that produces the file uploader and the selectbox in functions, ordered as I want them to appear in the app, doesn’t do it. Thank you.
when you callback the load_sheet_preview function, you write to the page with st.dataframe. Since the callback function is written to the page before anything else during the streamlit reload, it means that the dataframe is written to the page before moving to the if uploaded_file is not None: statement. I would need to thing about the solution some more, but maybe this helps you get there first.
0
streamlit
Using Streamlit
How to have 2 columns on a form
https://discuss.streamlit.io/t/how-to-have-2-columns-on-a-form/20997
Hi, Inside a with st.form(‘my_form’), how to put 2 data entry columns on it? From Date Time date_input() time_input() To Date Time date_input() time_input() Submit Button Thanks!
Hi, you can do the following: #After your with st.form statement… add c1, c2 = st.columns(2) With c1: #Add controls you want to show in column 1 With c2: #Add controls you want to show in column 2 add your submit button
0
streamlit
Using Streamlit
General question on custom styling
https://discuss.streamlit.io/t/general-question-on-custom-styling/20999
I don’t know much about styling the streamlit app outside of page_config. Are there resources for me to learn how to maximize the customization of the app outside of the standard options supported by html. in general, what is the most effective way to do this, inject custom css? does JS come into play at all here? One specific question I have is how would I customize button styling? but if i’m going to custom style buttons, I might as well know the full extent of what’s possible. I’ve seen a few @dataprofessor videos. other suggestions?
I just did a video on this: 4 ways of styling Streamlit widgets | Streamlit tutorial - YouTube 4 Where I quickly skim through all the current ways to “hack” Streamlit design, with a lot of links in the video description . Hope it helps! Fanilo
1
streamlit
Using Streamlit
Multiline label for radio widget
https://discuss.streamlit.io/t/multiline-label-for-radio-widget/20916
Hi there, is there a way to force a new line in the label of the radio widget? This doesn’t work: vis_outliers= st.radio( 'Display outliers?\n(for data that might have errors only)', ['no', 'yes', 'hidden'] ) Thanks for your help.
Hi, how about doing this as an alternative: st.text(‘Display outliers?\n(for data that might have errors only’) OR st.text(‘Display outliers?’) st.text(‘for data that might have errors only’) AND vis_outliers= st.radio(’’,[‘no’, ‘yes’, ‘hidden’])
0
streamlit
Using Streamlit
Disable scrollbar
https://discuss.streamlit.io/t/disable-scrollbar/17485
Hi all, Is there a way to disable scrollbar? I am building an one-page app where the content does not exceed screen height, the scrollbar appears anyways even when there is nothing below the main component. I’d really like my page to be fixated. Is there an option to disable the scrollbar? thanks in advance, Don
I’m looking for this too. I thought you could use the ‘overflow’ tag in CSS, but it doesn’t seem to work in Streamlit. body { overflow: hidden; /* Hide scrollbars */ }
0
streamlit
Using Streamlit
Theme Change using st.markdown
https://discuss.streamlit.io/t/theme-change-using-st-markdown/20907
I want to change my theme using the command st.markdown( “”" """, unsafe_allow_html=True,). My current custom theme is [theme] base="dark" primaryColor="#002b36" backgroundColor="#002b36" secondaryBackgroundColor="#586e75" font="sans serif" Can someone please help me to sort out this problem?
Hi @udo udo: My current custom theme is [theme] base=“dark” primaryColor="#002b36" backgroundColor="#002b36" secondaryBackgroundColor="#586e75" font=“sans serif” Those edits are to be put inside a .streamlit/config.toml file (Theming - Streamlit Docs 1). Edits done in st.markdown should be CSS Selectors + Properties only like <style> body { background-color: lightgoldenrodyellow; } div[role="listbox"] ul { background-color: red; } </style> There are some tutorials wandering in this forum like Can I change the color of the selectbox widget? - Using Streamlit - Streamlit Creating a nicely formatted search field? - Using Streamlit - Streamlit CSS hacks for the dumb? - #3 by andfanilo to understand all the HTML blocks and CSS properties you can edit within the Streamlit app. Have a nice day, Fanilo
1
streamlit
Using Streamlit
Changing background color of single number input and selectboxes
https://discuss.streamlit.io/t/changing-background-color-of-single-number-input-and-selectboxes/20974
Hi, I have a streamlit webApp and have several text input and selectbox widgets. for example: a = st.number_input(“value a”,value=0.5) b = st.selectbox(‘choose value’,(‘b’,‘c’)) I want most of the widgets stay in standard gray but for some single ones I want to define the backgroudcolor by my self. I found some ideas with st.markdown but could not realize it with my example. Is it possible to change the backgroundcolor like this and do you have any ideas? Thanks
Hey @Specht , welcome to the community Let me preface this by saying the following is absolutely hard to maintain, even harder than the Markdown CSS Hack trick… But yeah I’ve tried with CSS Selection alone but couldn’t find it out either. The only way of doing I found is by bypassing the components iframe: import streamlit as st import streamlit.components.v1 as components a = st.number_input("value a", value=0.5) b = st.number_input("value b", value=0.5) c = st.number_input("value c", value=0.5) components.html( """ <script> const elements = window.parent.document.querySelectorAll('.stNumberInput div[data-baseweb="input"] > div') console.log(elements) elements[1].style.backgroundColor = 'red' </script> """, height=0, width=0, ) image708×326 1.86 KB I say unmaintainable because…well certain styles and events may break the moment you leave the iframe sandbox for components + well I think you can see from the code anytime you change the app, you’ll need to re-edit the code. I don’t usually recommend this but just so you know there is this workaround… Have a nice day! Fanilo
0
streamlit
Using Streamlit
Stop page from reloading after using downloader
https://discuss.streamlit.io/t/stop-page-from-reloading-after-using-downloader/18744
Hi, In my app a user uploads a file which is processed, the results of which are offered as a download. Now when I press the download button on my webpage, it reloads and starts processing the uploaded file again. From what I gather this is the intended behaviour of Streamlit? Can I prevent this reloading somehow, though? Seems like caching is an option, but that requires decorating a function? And I’m not really sure it would really solve my problem anyway. Basically what I want is the user to be able to upload a file and having to option to download the results of the processing. If the user then wants to upload a new file, do the processing on the new file and offer the results as a new download.
Hi Chiel, I ran into similar issue. Every time I click the download button, the whole app will refresh. May I know how you fixed it? Thanks!
0
streamlit
Using Streamlit
How to use multiple columns in forms so that the input is side by side instead of below each
https://discuss.streamlit.io/t/how-to-use-multiple-columns-in-forms-so-that-the-input-is-side-by-side-instead-of-below-each/21035
I have the following code, but the code doesn’t seem to work and its still showing one below the other form = st.form(key="my-form") c1, c2 = st.columns(2) with c1: sel1= form.selectbox("Report Type", ("normal", "full")) with c2: track= form.text_input("enter track no").upper() submit = form.form_submit_button("Generate Report") if submit: with st.spinner('Generating Report....'):
For anyone that is looking for the answer to my own question above, here is how I fixed it: with st.form(key='columns_in_form'): c1, c2, c3, c4 = st.columns(4) with c1: initialInvestment = st.text_input("Starting capital",value=500) with c2: monthlyContribution = st.text_input("Monthly contribution (Optional)",value=100) with c3: annualRate = st.text_input("Annual increase rate in percentage",value="15") with c4: investingTimeYears = st.text_input("Duration in years:",value=10) submitButton = st.form_submit_button(label = 'Calculate') This did the trick, one form with four inputs in four different columns: Screenshot 2022-01-17 at 01.33.461779×201 11.1 KB
1
streamlit
Using Streamlit
How to add Google Analytics or JS code in a Streamlit app?
https://discuss.streamlit.io/t/how-to-add-google-analytics-or-js-code-in-a-streamlit-app/1610
Hi all, I would like to monitor the traffic on my app using Google Analytics. What is the best way to achieve this? I need to insert something like that <script async src="https://www.googletagmanager.com/gtag/js?id=UA-44444444-1"></script> Also, what about Google Adsense code? I hope there is a way to inject these in Steamlit somehow. Thanks in advance for support.
It is very proud to see Streamlit become so far I believe this will go bigger and bigger
0
streamlit
Using Streamlit
Download an streamlit table to pdf
https://discuss.streamlit.io/t/download-an-streamlit-table-to-pdf/15546
Hello everyone, I would like to download a streamlit table to pdf. Once I click on a button the table will be downloaded automatically. I really need it so please help me out
Hi Loubna! And welcome to the Streamlit forum! I’m not aware of any way to do this, but Devs may know! Let me ask them and come back to you! Best, Charly
0
streamlit
Using Streamlit
I just want a SIMPLE bar chart
https://discuss.streamlit.io/t/i-just-want-a-simple-bar-chart/20995
I have StreamLit working fine with some simple things like st.write and even st.table. I have a CSV file with two columns, “Date” and “Profit/Loss” Date,Profit/Loss 2022-01-14,-500.00 df = pd.read_csv('profitloss.csv') chart_data = pd.DataFrame(df) st.bar_chart(chart_data) this code just gives me this error: **StreamlitAPIException** : ("Expected bytes, got a 'float' object", 'Conversion failed for column value with type object') What am I doing wrong?
Hi @TheBigDuck I suggest you replace the above code with the following code: df = pd.read_csv(‘profitloss.csv’) df = df.set_index(‘Date’) st.bar_chart(df) Also suggest you take a look at other visualization libraries: Altair, etc. Cheers
1
streamlit
Using Streamlit
Problem: Streamlir shows source code, when dataframe is displayed
https://discuss.streamlit.io/t/problem-streamlir-shows-source-code-when-dataframe-is-displayed/18272
Dear all, My code reads a file and then displays it in a data frame. uploaded_file = st.file_uploader("Choose a KML file") if uploaded_file is not None: df = gpd.read_file (uploaded_file, driver ='KML') st.write(df) but for some reason it also displays part of the source code of the data frame. streamlit_problem1518×1006 97.3 KB Does anyone know how to solve this? Thank you!
Hi @karina-castillo, welcome to the forum! Have you tried using st.dataframe(df) or st.table(df) instead? Happy Streamlit’ing! Snehan
0
streamlit
Using Streamlit
How to display animated loading while process run in background (preload page)
https://discuss.streamlit.io/t/how-to-display-animated-loading-while-process-run-in-background-preload-page/20944
Hello, everyone. First, i wanna thank you streamlit team for the amazing work they have been done so far. So, I’m building an app that uses Pylinac Library 2 for automating radiotherapy QA. I was trying to implement a loading gif while the analysis code run in background, but I’m facing a hard time in this task. Being clear, I basically want a pre-load page, that shows only the loading gif while the analysis is done in background and, when is completed, shows only the app page with the analysis without the gif. I know st.spinner exist, but I can’t set to show only the loading, just how it is below: SharedScreenshot1364×664 64.1 KB Thank you in advance, community!
Almost 30 different loaders to choose from in any combination you like. GitHub GitHub - TangleSpace/hydralit_components: A package of custom components for... 1 A package of custom components for Streamlit and Hydralit. Can be used directly or in combination with the Hydralit package. - GitHub - TangleSpace/hydralit_components: A package of custom componen... The example project also shows you how to create a full page loader that will run whenever your app is running/loading in the background, works with all the loaders in the components package or you can create your own. GitHub GitHub - TangleSpace/hydralit-example: A sample project showing off the ease... 2 A sample project showing off the ease and ability of the Hydralit multi-page Streamlit package. - GitHub - TangleSpace/hydralit-example: A sample project showing off the ease and ability of the Hyd...
0
streamlit
Using Streamlit
Module not found pandas profiling error message
https://discuss.streamlit.io/t/module-not-found-pandas-profiling-error-message/20940
how do I resolve the following error message? ModuleNotFoundError: No module named ‘pandas_profiling’ Traceback: File "/opt/anaconda3/envs/streamlit_model/lib/python3.9/site-packages/streamlit/script_runner.py", line 354, in _run_script exec(code, module.__dict__)File "/Users/bishopakolgo/Desktop/app.py", line 11, in <module> from pandas_profiling import ProfileReport
Hi i finally resolved this issue by just by simply installed pandas profiling. However the new problem is the following; module NotFound: No module named: “df_helper” file “opt/anacoda3/envs/stream;it_model/lib/python3.9/dite-packages/streamlit exec(code, module. dic) File”/users/bishopakolgo/desktop/app.py,line 16, in module import df_helper as helper # custom script
0
streamlit
Using Streamlit
Streamlit working on web browser (not mobile)
https://discuss.streamlit.io/t/streamlit-working-on-web-browser-not-mobile/11479
Hello everyone! Amazing tool! Love what you guys did. After building and deploying my app to https://playground-ml.herokuapp.com/ 37 I came to notice that it doesn’t open on mobile browsers (specifically IPhone when using Safari and Chrome) : when you hit the link, you’re faced with a blank page (not even an error message) Could this be related to Heroku? It’s hard to debug on mobile. On desktop, everything works fine. Has anyone faced this issue? Thanks for your help.
Hello @ahmedbesbes, welcome to the community! And what a nice app you have delpoyed there On my side your link works perfectly on iPhone Chrome and Safari though, I’ve been able to change dataset and play with the sidebar parameters. Did you change anything in between? Cheers, Fanilo
0
streamlit
Using Streamlit
Buttons running a on-click function during startup and runtime
https://discuss.streamlit.io/t/buttons-running-a-on-click-function-during-startup-and-runtime/20964
Hi all, I am making a Streamlit app for simple permission management of an SQL database. In this app I have some functions doing SQL queries (adding and deleting rows in the database) when a button is pressed. Problem is these buttons execute my add/remove functions at startup and during runtime. This should only be done when performed by the user! Example button and function. userID is picked from a st.selectbox df is generated from a st.multiselect list def update_Usergroup(userID, df): eng = makeConnection() # sqlalchemy create engine function st.success('update_Usergroup is run') query = f"""DELETE FROM Users_Usergroups_Comb WHERE UserID = {userID}; """ eng.execute(sa_text(query).execution_options(autocommit=True)) # write to Users_Usergroups_Comb table with no index and appending the dataframe to the DB df.to_sql('Users_Usergroups_Comb',con=eng, index = False, if_exists = 'append') return st.button('Save updated usersgroups', on_click = update_Usergroup(userID, membership)) How can I control the app such that on_click is not executed automatically? Thanks in advance!
Hi @EBEN Try replacing your st.button statement with the following code: if st.button(‘Save updated usersgroups’): update_Usergroup(userID, membership)
0
streamlit
Using Streamlit
How to access uploaded video in streamlit by open cv?
https://discuss.streamlit.io/t/how-to-access-uploaded-video-in-streamlit-by-open-cv/5831
Hi, I want to upload video through streamlit and want to access it with cv.VideoCapture() function. So How can i do please help me.
Seems wasteful, but if OpenCV really requires a file, I wonder if this will be acceptable: import streamlit as st import cv2 as cv import tempfile f = st.file_uploader("Upload file") tfile = tempfile.NamedTemporaryFile(delete=False) tfile.write(f.read()) vf = cv.VideoCapture(tfile.name)
1
streamlit
Using Streamlit
Upload Files to Streamlit App
https://discuss.streamlit.io/t/upload-files-to-streamlit-app/80
Hi all, I was wondering if there was a way to have a user upload a file (ie a txt or csv file) to a Streamlit app? I didn’t see anything in the docs about this. Tangent from this, is it possible to inject HTML into Streamlit to create new functionalities?
Hi Karl. Great questions! #1: How to create a file selector Currently, there is no file picker, but I just added a feature request for one 845. Please feel free to follow this request on Github to follow its progress. In the meantime, here’s an example of a janky ad-hoc file selector on the server: import streamlit as st import os filename = st.text_input('Enter a file path:') try: with open(filename) as input: st.text(input.read()) except FileNotFoundError: st.error('File not found.') #2: How to inject custom HTML into Streamlit What would you like to add? Streamlit already supports many different elements and we’re adding more each day. If you share some details we can help you achieve your aim. In the long run, we plan to expose a plug-in architecture. I’ve created this tracking bug 55. Please feel free to add comments describing what you’d like to see here. Summary In general, please feel free to submit bug report or feature requests 13 at our repo 6.
0
streamlit
Using Streamlit
Encoding state of input widgets in url
https://discuss.streamlit.io/t/encoding-state-of-input-widgets-in-url/20804
Hi, I have built a streamlit app which visualizes some data, based on various settings the user can make in the sidebar. The visualization itself can be switched between different modes (I built a form of multi page app with a select box on top of the page) Now it is often interesting to compare different views of the same filter settings with each other. The best solution for this in my current setup is to open a new browser window and to carefully set all the filter settings on the sidebar to the same values as they are in the first window. Then one can select a different mode and compare both. Since the visualization modes can be a bit complex, I would like to avoid having one giant compare mode with two visualizations on one page. Copying of the settings is a bit tedious, so ideally this would be encoded into the url for example, which can then be copied to get a second session with the same input widget state. I don’t think it is possible, but maybe somebody knows a way to get something like that?
ideally this would be encoded into the url for example This is possible with st.experimental_get_query_params() and st.experimental_set_query_params() See this example 2
1
streamlit
Using Streamlit
Display pyGAM model summary
https://discuss.streamlit.io/t/display-pygam-model-summary/9254
Display pyGAM model summary into streamlit application. Source: https://codeburst.io/pygam-getting-started-with-generalized-additive-models-in-python-457df5b4705f 1 import pandas as pd from sklearn.datasets import load_boston from pygam import LinearGAM boston = load_boston() df = pd.DataFrame(boston.data, columns=boston.feature_names) target_df = pd.Series(boston.target) df.head() X = df y = target_df gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values) gam.summary() image1012×742 100 KB As shown in image the output of gam.summary is not displaying with any of the st.* (display functions)
Hi @Ahmad_Zia , welcome to the Streamlit community! It’s unfortunate that the pyGAM summary method dumps the result using print() statements, but you can redirect the output using the following code: import pandas as pd from sklearn.datasets import load_boston from pygam import LinearGAM from io import StringIO import sys import streamlit as st # redirect where stdout goes, write to 'mystdout' # https://stackoverflow.com/a/1218951/2394542 old_stdout = sys.stdout sys.stdout = mystdout = StringIO() boston = load_boston() df = pd.DataFrame(boston.data, columns=boston.feature_names) target_df = pd.Series(boston.target) df.head() X = df y = target_df gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values) gam.summary() sys.stdout = old_stdout # this is what writes to the streamlit app...read the value from the redirected out st.text(mystdout.getvalue()) image1495×1462 104 KB Best, Randy
1
streamlit
Using Streamlit
Prediction analysis and creating a database
https://discuss.streamlit.io/t/prediction-analysis-and-creating-a-database/3504
Hi, I’m in a project where I have an algorithm already built the works as a calculator, so what I want to know is if there is any simple way that I can create the input variables on the left, save them in a database and use them to calculate with the algorithm the final result. Thank you very much in advance!
Hi @Pedro_Freire, welcome to the forum Here’s a quick snippet to make you started import pandas as pd from pathlib import Path import sqlite3 from sqlite3 import Connection import streamlit as st URI_SQLITE_DB = "test.db" def main(): st.title("My Super Calculator") st.markdown("Enter data in database from sidebar, then run the **mighty** calculator") conn = get_connection(URI_SQLITE_DB) init_db(conn) build_sidebar(conn) display_data(conn) run_calculator(conn) def init_db(conn: Connection): conn.execute( """CREATE TABLE IF NOT EXISTS test ( INPUT1 INT, INPUT2 INT );""" ) conn.commit() def build_sidebar(conn: Connection): st.sidebar.header("Configuration") input1 = st.sidebar.slider("Input 1", 0, 100) input2 = st.sidebar.slider("Input 2", 0, 100) if st.sidebar.button("Save to database"): conn.execute(f"INSERT INTO test (INPUT1, INPUT2) VALUES ({input1}, {input2})") conn.commit() def display_data(conn: Connection): if st.checkbox("Display data in sqlite databse"): st.dataframe(get_data(conn)) def run_calculator(conn: Connection): if st.button("Run calculator"): st.info("Run your function") df = get_data(conn) st.write(df.sum()) def get_data(conn: Connection): df = pd.read_sql("SELECT * FROM test", con=conn) return df @st.cache(hash_funcs={Connection: id}) def get_connection(path: str): """Put the connection in cache to reuse if path does not change between Streamlit reruns. NB : https://stackoverflow.com/questions/48218065/programmingerror-sqlite-objects-created-in-a-thread-can-only-be-used-in-that-sa """ return sqlite3.connect(path, check_same_thread=False) if __name__ == "__main__": main() (could have put conn=get_connection(URI_SQLITE_DB) in each function where you need it since it’s in cache anyway, you can reorganize as you will) image1035×491 18.8 KB
0
streamlit
Using Streamlit
Creating a PDF file generator
https://discuss.streamlit.io/t/creating-a-pdf-file-generator/7613
Hi, I do data analysis work, so I generate different plots. Now i want to create a tool which helps to visualize and as well as export chats into pdf file. Is it possible with streamlit to create that kind of app.
Hi @Pavan_Cheyutha, You sure can ! Though streamlit doesnt support PDF generation out of the box for obvious reasons but you can look into PyFPDF and coupled with streamlit it can do the job. Adding a snippet that I just tried for reference. import streamlit as st from fpdf import FPDF import base64 report_text = st.text_input("Report Text") export_as_pdf = st.button("Export Report") def create_download_link(val, filename): b64 = base64.b64encode(val) # val looks like b'...' return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}.pdf">Download file</a>' if export_as_pdf: pdf = FPDF() pdf.add_page() pdf.set_font('Arial', 'B', 16) pdf.cell(40, 10, report_text) html = create_download_link(pdf.output(dest="S").encode("latin-1"), "test") st.markdown(html, unsafe_allow_html=True) Will give you this. snippet1399×879 139 KB
1
streamlit
Using Streamlit
Folium/leaflet maps not loading or taking too long to load
https://discuss.streamlit.io/t/folium-leaflet-maps-not-loading-or-taking-too-long-to-load/20882
I made an application using folium maps and specifically using the streamlit_folium component to render my maps. I’ve noticed for a couple of months now that the maps will often take too long to render(around 1 minute) and sometimes not render at all. (shows the message ‘Make this Notebook Truste to load map’) What’s baffling is that this problem happens to apps that I didn’t create, apps that I host on Streamlit Cloud and apps that I run locally. But somehow this problem doesn’t occur in one of the laptops that I have. Any idea what’s going on and if anyone else has encountered it. Leaving some links to where I encountered this problem. My application and the streamlit_folium demo app https://share.streamlit.io/randyzwitch/streamlit-folium/examples/streamlit_app.py 3 https://share.streamlit.io/nabilersyad/train-stations-isochrones/webapp/webapp.py 2
Hi @nabilersyad, welcome to the Streamlit community! What browser/OS are you trying to view from? The streamlit-folium app loads for me in about a second in Chrome, and your train app loads quickly as well. Best, Randy
0
streamlit
Using Streamlit
St_camera_input
https://discuss.streamlit.io/t/st-camera-input/20950
Hello! Maybe too soon, but i was testing the new method for obtaining an image directly from a webcam (st.camera_input). It is quite easy to display the picture back into the app. But i’m trying to read it or as an image, or as bytes. The class returned is: “<class ‘streamlit.uploaded_file_manager.UploadedFile’>”. Do you know how to properly return (and possibly save this image)? Thanks!
In the docs, we do the example if you want to show it, which uses st.write(): docs.streamlit.io st.camera_input - Streamlit Docs 2 st.camera_input displays a widget to upload images from a camera However, the st.file_uploader example shows how to do different things with the bytes: if uploaded_file is not None: # To read file as bytes: bytes_data = uploaded_file.getvalue() st.write(bytes_data) # To convert to a string based IO: stringio = StringIO(uploaded_file.getvalue().decode("utf-8")) st.write(stringio) # To read file as string: string_data = stringio.read() st.write(string_data) # Can be used wherever a "file-like" object is accepted: dataframe = pd.read_csv(uploaded_file) st.write(dataframe) docs.streamlit.io st.file_uploader - Streamlit Docs 1 st.file_uploader displays a file uploader widget.
1
streamlit
Using Streamlit
Centre widget horizontally within column
https://discuss.streamlit.io/t/centre-widget-horizontally-within-column/20571
Hi, is there a way to centre a widget (eg. st.button) horizontally within a column? Thanks in advance.
Hi @Shawn_Pereira Thanks for your question. Would you be able to provide a quick mock-up of what you are after? Many thanks, Charly
0
streamlit
Using Streamlit
NameError: name ‘pydub’ is not defined
https://discuss.streamlit.io/t/nameerror-name-pydub-is-not-defined/20889
Wassup Guys, I try to create a document file uploader that also supports audio files (wav, mp3). (Want to save uploaded file temporarily locally so I can use them in later in order to transcript them as text). However, my code is below, everything needed is installed. I get the follwing error from my application: NameError: name ‘pydub’ is not defined I checked my local system for installed packages (including virtualenv) and everything needed should be installed (using pip freeze) a) local: altair==4.1.0 appnope==0.1.2 argon2-cffi==21.3.0 argon2-cffi-bindings==21.2.0 astor==0.8.1 async-generator==1.10 attrs==21.4.0 backcall==0.2.0 backports.zoneinfo==0.2.1 base58==2.1.1 bleach==4.1.0 blinker==1.4 cachetools==4.2.4 certifi==2021.10.8 cffi==1.15.0 chardet==4.0.0 charset-normalizer==2.0.10 click==7.1.2 cryptography==36.0.1 dataclasses==0.8 decorator==5.1.1 defusedxml==0.7.1 distlib==0.3.4 docx2txt==0.8 entrypoints==0.3 filelock==3.4.1 gitdb==4.0.9 GitPython==3.1.18 google-api-core==2.3.2 google-auth==2.3.3 google-cloud-texttospeech==2.9.0 googleapis-common-protos==1.54.0 grpcio==1.43.0 grpcio-status==1.43.0 huggingface-hub==0.4.0 idna==3.3 importlib-metadata==4.8.3 importlib-resources==5.4.0 ipykernel==5.5.6 ipython==7.16.2 ipython-genutils==0.2.0 ipywidgets==7.6.5 jedi==0.17.2 Jinja2==3.0.3 joblib==1.1.0 jsonschema==3.2.0 jupyter-client==7.1.0 jupyter-core==4.9.1 jupyterlab-pygments==0.1.2 jupyterlab-widgets==1.0.2 MarkupSafe==2.0.1 mistune==0.8.4 nbclient==0.5.9 nbconvert==6.0.7 nbformat==5.1.3 nest-asyncio==1.5.4 notebook==6.4.6 numpy==1.19.5 packaging==21.3 pandas==1.1.5 pandocfilters==1.5.0 parso==0.7.1 pdfminer.six==20211012 pdfplumber==0.6.0 pexpect==4.8.0 pi==0.1.2 pickleshare==0.7.5 Pillow==8.4.0 platformdirs==2.4.0 prometheus-client==0.12.0 prompt-toolkit==3.0.24 proto-plus==1.19.8 protobuf==3.19.3 ptyprocess==0.7.0 pyarrow==6.0.1 pyasn1==0.4.8 pyasn1-modules==0.2.8 pycparser==2.21 pydeck==0.6.2 pydub==0.25.1 Pygments==2.11.2 Pympler==1.0.1 pyparsing==3.0.6 PyPDF2==1.26.0 pyrsistent==0.18.0 python-dateutil==2.8.2 pytz==2021.3 pytz-deprecation-shim==0.1.0.post0 PyYAML==6.0 pyzmq==22.3.0 regex==2021.11.10 requests==2.27.1 rsa==4.8 sacremoses==0.0.47 Send2Trash==1.8.0 simpleaudio==1.0.4 six==1.16.0 smmap==5.0.0 SpeechRecognition==3.8.1 streamlit==1.3.1 terminado==0.12.1 testpath==0.5.0 tokenizers==0.10.3 toml==0.10.2 toolz==0.11.2 torch==1.10.1 tornado==6.1 tqdm==4.62.3 traitlets==4.3.3 transformers==4.15.0 typing_extensions==4.0.1 tzdata==2021.5 tzlocal==4.1 urllib3==1.26.8 validators==0.18.2 virtualenv==20.13.0 Wand==0.6.7 wcwidth==0.2.5 webencodings==0.5.1 widgetsnbextension==3.5.2 zipp==3.6.0 b) virtualenv env: pydub==0.25.1 What did I miss? Below is my code: import speech_recognition as sr import streamlit as st import pandas as pd import numpy as np from pydub import AudioSegment from io import StringIO import streamlit.components.v1 as stc import docx2txt from PIL import Image from PyPDF2 import PdfFileReader import pdfplumber # example sound filename = "sound.wav" # initialize the recognizer r = sr.Recognizer() def handle_uploaded_audio_file(uploaded_file): a = pydub.AudioSegment.from_wav(uploaded_file) st.write(a.sample_width) samples = a.get_array_of_samples() fp_arr = np.array(samples).T.astype(np.float32) fp_arr /= np.iinfo(samples.typecode).max st.write(fp_arr.shape) return fp_arr, 22050 def read_pdf(file): pdfReader = PdfFileReader(file) count = pdfReader.numPages all_page_text = "" for i in range(count): page = pdfReader.getPage(i) all_page_text += page.extractText() return all_page_text def read_pdf_with_pdfplumber(file): with pdfplumber.open(file) as pdf: page = pdf.pages[0] return page.extract_text() # import fitz # this is pymupdf # def read_pdf_with_fitz(file): # with fitz.open(file) as doc: # text = "" # for page in doc: # text += page.getText() # return text # Fxn @st.cache def load_image(image_file): img = Image.open(image_file) return img def main(): st.title("File Upload Tutorial") menu = ["Home", "Dataset", "DocumentFiles", "Audio", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Home") image_file = st.file_uploader( "Upload Image", type=['png', 'jpeg', 'jpg']) if image_file is not None: # To See Details # st.write(type(image_file)) # st.write(dir(image_file)) file_details = {"Filename": image_file.name, "FileType": image_file.type, "FileSize": image_file.size} st.write(file_details) img = load_image(image_file) st.image(img, width=250, height=250) elif choice == "Dataset": st.subheader("Dataset") data_file = st.file_uploader("Upload CSV", type=['csv']) if st.button("Process"): if data_file is not None: file_details = {"Filename": data_file.name, "FileType": data_file.type, "FileSize": data_file.size} st.write(file_details) df = pd.read_csv(data_file) st.dataframe(df) elif choice == "DocumentFiles": st.subheader("DocumentFiles") docx_file = st.file_uploader( "Upload File", type=['txt', 'docx', 'pdf']) if st.button("Process"): if docx_file is not None: file_details = {"Filename": docx_file.name, "FileType": docx_file.type, "FileSize": docx_file.size} st.write(file_details) # Check File Type if docx_file.type == "text/plain": # raw_text = docx_file.read() # read as bytes # st.write(raw_text) # st.text(raw_text) # fails st.text(str(docx_file.read(), "utf-8")) # empty # works with st.text and st.write,used for futher processing raw_text = str(docx_file.read(), "utf-8") # st.text(raw_text) # Works st.write(raw_text) # works elif docx_file.type == "application/pdf": # raw_text = read_pdf(docx_file) # st.write(raw_text) try: with pdfplumber.open(docx_file) as pdf: page = pdf.pages[0] st.write(page.extract_text()) except: st.write("None") elif docx_file.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document": # Use the right file processor ( Docx,Docx2Text,etc) # Parse in the uploadFile Class directory raw_text = docx2txt.process(docx_file) st.write(raw_text) elif choice == "Audio": st.subheader("Audio") fileObject = st.file_uploader( "Please upload your file ", type=['wav', 'mp3']) if fileObject is not None: id = fileObject.id name = fileObject.name type = fileObject.type size = fileObject.size handle_uploaded_audio_file(fileObject) if (type == 'mp3'): print('mp3') st.write(id, name, type, size) """ sound = AudioSegment.from_mp3("/path/to/file.mp3") sound.export("/output/path/file.wav", format="wav") """ else: st.subheader("About") st.info("Built with Streamlit") st.info("Jesus Saves @JCharisTech") st.text("Jesse E.Agbe(JCharis)") if __name__ == '__main__': main() Bildschirmfoto 2022-01-12 um 19.04.372880×1800 378 KB Bildschirmfoto 2022-01-12 um 19.13.301620×520 64.3 KB
It looks like you’re using VSCode…in the bottom left of the screen, it will tell you which environment you are pointing to to execute the code. It doesn’t necessarily have to be the same as the Terminal where you are running Streamlit: In this picture, VSCode will use environment st39 to look for packages/code linting. Running streamlit run file.py will execute in the base environment. Best, Randy
1
streamlit
Using Streamlit
Button to clear cache and rerun
https://discuss.streamlit.io/t/button-to-clear-cache-and-rerun/3928
Is there a way to create a button on my page that does the following (a) clear cache and (b) rerun?
Thanks! That is what I looking to automate in my script based on certain conditions. Are there commands for this in the API?
0
streamlit
Using Streamlit
Quick restart problem
https://discuss.streamlit.io/t/quick-restart-problem/10085
Welcome, everyone. I’m facing an important problem, and I want to know a quick solution to it, please. I’m working on a project where the user inserts some data and then a prediction occurs. But when I run the program, when I enter the first value, the program automatically restarts. Which erases the data again. SharedScreenshot1234×556 38.2 KB I hope you can help me. Because my project re-delivery is approaching.
Hi, I do not know if this question is live for you. But if you use the form object, you can submit the information all at once and it does not reload. docs.streamlit.io st.form - Streamlit Docs st.form creates a form that batches elements together with a “Submit” button.
0
streamlit
Using Streamlit
Conflict with Plotly 5.5 and Dask 2021.12.0
https://discuss.streamlit.io/t/conflict-with-plotly-5-5-and-dask-2021-12-0/20266
Hi guys. I use Streamlit 1.3 and Plotly 5.5 and Dask 2021.12.0, when I run a example like: from collections import namedtuple import altair as alt import math import pandas as pd import streamlit as st import plotly.express as px """ # Welcome to Streamlit! Edit `/streamlit_app.py` to customize this app to your heart's desire :heart: If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community forums](https://discuss.streamlit.io). In the meantime, below is an example of what you can do with just a few lines of code: """ with st.echo(code_location='below'): total_points = st.slider("Number of points in spiral", 1, 5000, 2000) num_turns = st.slider("Number of turns in spiral", 1, 100, 9) Point = namedtuple('Point', 'x y') data = [] points_per_turn = total_points / num_turns for curr_point_num in range(total_points): curr_turn, i = divmod(curr_point_num, points_per_turn) angle = (curr_turn + 1) * 2 * math.pi * i / points_per_turn radius = curr_point_num / total_points x = radius * math.cos(angle) y = radius * math.sin(angle) data.append(Point(x, y)) st.altair_chart(alt.Chart(pd.DataFrame(data), height=500, width=500) .mark_circle(color='#0068c9', opacity=0.5) .encode(x='x:Q', y='y:Q')) I get the following errors: 2021-12-22 18:50:20.089 INFO numexpr.utils: Note: NumExpr detected 36 cores but "NUMEXPR_MAX_THREADS" not set, so enforcing safe limit of 8. 2021-12-22 18:50:20.089 INFO numexpr.utils: NumExpr defaulting to 8 threads. You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://192.168.1.12:8501 2021-12-22 18:50:21.603 Traceback (most recent call last): File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/streamlit/script_runner.py", line 354, in _run_script exec(code, module.__dict__) File "/media/kan-dai/workspace/workcode/miscellaneous/collections/streamlit/Capital-Bike-Share-Data-Streamlit-Web-Application/app.py", line 8, in <module> import plotly.express as px File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/plotly/express/__init__.py", line 15, in <module> from ._imshow import imshow File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/plotly/express/_imshow.py", line 11, in <module> import xarray File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/xarray/__init__.py", line 1, in <module> from . import testing, tutorial, ufuncs File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/xarray/tutorial.py", line 13, in <module> from .backends.api import open_dataset as _open_dataset File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/xarray/backends/__init__.py", line 6, in <module> from .cfgrib_ import CfGribDataStore File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/xarray/backends/cfgrib_.py", line 16, in <module> from .locks import SerializableLock, ensure_lock File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/xarray/backends/locks.py", line 13, in <module> from dask.distributed import Lock as DistributedLock File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/dask/distributed.py", line 11, in <module> from distributed import * File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/__init__.py", line 7, in <module> from .actor import Actor, ActorFuture File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/actor.py", line 5, in <module> from .client import Future File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/client.py", line 59, in <module> from .batched import BatchedSend File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/batched.py", line 10, in <module> from .core import CommClosedError File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/core.py", line 28, in <module> from .comm import ( File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/comm/__init__.py", line 25, in <module> _register_transports() File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/comm/__init__.py", line 17, in _register_transports from . import inproc, tcp, ws File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/comm/tcp.py", line 387, in <module> class BaseTCPConnector(Connector, RequireEncryptionMixin): File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/distributed/comm/tcp.py", line 389, in BaseTCPConnector _resolver = netutil.ExecutorResolver(close_executor=False, executor=_executor) File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/tornado/util.py", line 288, in __new__ instance.initialize(*args, **init_kwargs) File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/tornado/netutil.py", line 427, in initialize self.io_loop = IOLoop.current() File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/site-packages/tornado/ioloop.py", line 263, in current loop = asyncio.get_event_loop() File "/home/kan-dai/miniconda3/envs/MET/lib/python3.9/asyncio/events.py", line 642, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' RuntimeError: There is no current event loop in thread 'ScriptRunner.scriptThread'. When I change Dask from 2021.12.0 to 2021.11.2, no errors happen. So, how can I solve this? Thanks very much.
Hi @kan - I’m not sure I’m understanding…in your example, you aren’t importing Dask, but changing installed versions of Dask changes whether the plotly package plots? Best, Randy
0
streamlit
Using Streamlit
Change the slider selected region shown by the color
https://discuss.streamlit.io/t/change-the-slider-selected-region-shown-by-the-color/20862
In my project, I have used sliders for data filtering purposes. These sliders have textual values, therefore the left extreme is undesired value while the right extreme is the desired value. Therefore, when such sliders are moved, the expectation is to color the region between the knob and right extreme. However, the default behavior is reversed. Any ideas how to do it? image1756×828 41 KB
@thiago any leads?
0
streamlit
Using Streamlit
Theme change
https://discuss.streamlit.io/t/theme-change/20873
How to change theme in streamlit using codes? I want dark theme. Can someone please tell me how to do that?
Check the section “Creating a theme using config.toml directly” in the documentation. The page link is https://www.google.com/amp/s/blog.streamlit.io/introducing-theming/amp/ 7 Cheers
1
streamlit
Using Streamlit
How to pause a simulation app and resume from where you stopped
https://discuss.streamlit.io/t/how-to-pause-a-simulation-app-and-resume-from-where-you-stopped/5693
I am trying to add full functionality to program. M app runs a simulation. I would like to be to pause the simulation and resume the simulation from the last point. I stumbled on this post: Stop or Cancel button 20 How can I implement a pause button that pauses my simulation at the last point and resumes from th last point when I click the resume button? Additionally, I get the following error: ModuleNotFoundError: No module named 'SessionState' when using he SessionState. I tried to install it but no successs Kindly advise please Thanks
Hi @JohnAnih, Do you have SessionState module in your path ? I usually put the session state in a utils module and import it from there. You can take reference from this repo, https://github.com/ash2shukla/streamlit-heroku 15 Here the _SessionState class resides in utils.py and I import it from there in main.py. Hope it helps ! PS. the repo is compatible with streamlit 0.63.1 for latest version change the import in utils.py like following, from streamlit.ReportThread import get_report_ctx # change that 👆 to this 👇 from streamlit.report_thread import get_report_ctx from streamlit.server.Server import Server # change that 👆 to this 👇 from streamlit.server.server import Server
0
streamlit
Using Streamlit
How to hide the first column in dataframe
https://discuss.streamlit.io/t/how-to-hide-the-first-column-in-dataframe/20892
Hi, I tried to drop, but df.drop seems to work only on the “regular” columns. Also tried df.style.hide_index(), but no effect. Want to hide that incrementing number first column when you do st.write(). How to do that? Thanks!
Hi! I think this documentation covers your question: Hide row indices when displaying a dataframe - Streamlit Docs 3 Hope it helps!
0
streamlit
Using Streamlit
App Reruns upon User Input
https://discuss.streamlit.io/t/app-reruns-upon-user-input/20639
Hi, I have a problem with my app, So its an NLP app that accepts files in pdf format, the app fits on the document the takes user input and I have to grab the text and query the Pre-trained bert model , but upon the user pressing the predict button after writing the query the app reruns all over again, here is my code import streamlit as st import pandas as pd import joblib import cdqa import tabula import docx2txt from PyPDF2 import PdfFileReader import os import pandas as pd from ast import literal_eval import urllib.request from cdqa.utils.converters import pdf_converter from cdqa.utils.filters import filter_paragraphs from cdqa.pipeline import QAPipeline from cdqa.utils.download import download_model def read_pdf(directory_path='./tempDir/'): df = pdf_converter(directory_path) return df #def load model def load_model(): model = joblib.load('models/bert_qa.joblib') cdqa_pipeline = QAPipeline(reader=model, max_df=1.0, ) return cdqa_pipeline st.subheader("Home") docx_file = st.file_uploader("Upload Document",type=["pdf"]) if st.button("Process"): # text = st.text_input("input your query") if docx_file is not None: #see details of the file file_details = {"filename":docx_file.name, "filetype":docx_file.type, "filesize":docx_file.size} st.json(file_details) with open(os.path.join("tempDir",docx_file.name),"wb") as f: f.write(docx_file.getbuffer()) df = read_pdf() with st.spinner("fitting the model...."): pipeline = load_model() pipeline.fit_retriever(df=df) st.write(type(docx_file)) st.success("model has been fitted") text = st.text_input("Query Model",placeholder="Type your query") if st.button("Predict"): if text is not None: prediction = pipeline.predict(text) res = { "Query" : text, "Answer": prediction[0], "Title" : prediction[1], "Paragraph":prediction[2]} st.write(res) st.json(res) else: st.warning("you have not typed your query")
Hi @Brainiac , Could you resolve this using SessionState as @Marisa_Smith suggested ? If not, a quick fix can be using a st.checkbox() instead of st.button() Brainiac: st.button("Process"): In this way you can keep your app in an active state. You can also use SessionState for the active state of your button. I have referred to this before, here’s a link to this workaround mentioned in my blog post / Youtube video, indeed it’s a very common user issue in the forum. Best, Avra
1
streamlit
Using Streamlit
Event Handling of pydeck_chart map in streamlit
https://discuss.streamlit.io/t/event-handling-of-pydeck-chart-map-in-streamlit/10842
Hello, I was able to plot GPS points containing latitude and longitude information from a pandas dataframe into a pydeck_chart Scatterplot Layer. I included custom tooltips and finally wrapped all into a small streamlit app. Bildschirmfoto 2021-03-16 um 14.24.393122×1748 519 KB I was wondering if someone of you knows how to handle interactivity such as event handling/picking using PyDeck charts with Streamlit? In my example I would like to be able to extract the PointID of a clicked point and reuse it (e.g. as a variable) with further streamlit components. This would allow the output of an on_click event to be reused further in streamlit (e.g. for a plot or subsetting/filtering a dataframe). I tried to include a minimal working example below. import streamlit as st import pydeck as pdk import pandas as pd import ssl # get rid of ssl connection error (certificates) try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context st.header("Map data") `# read in data` df = pd.read_csv(r'https://gist.githubusercontent.com/bafu-DF/f60bd9ac9579d9f830f1f52ce7e79c86/raw/af16f3bb04d5150cc0e139d25d9c706ccbb80215/sampledata.csv', sep=',') layer = pdk.Layer( "ScatterplotLayer", df, pickable=True, opacity=0.8, filled=True, radius_scale=2, radius_min_pixels=10, radius_max_pixels=500, line_width_min_pixels=0.01, get_position='[Longitude, Latitude]', get_fill_color=[255, 0, 0], get_line_color=[0, 0, 0], ) # Set the viewport location view_state = pdk.ViewState(latitude=df['Latitude'].iloc[-1], longitude=df['Longitude'].iloc[-1], zoom=13, min_zoom= 10, max_zoom=30) # Render r = pdk.Deck(layers=[layer], map_style='mapbox://styles/mapbox/satellite-v9', initial_view_state=view_state, tooltip={"html": "<b>Point ID: </b> {PointID} <br /> " "<b>Longitude: </b> {Longitude} <br /> " "<b>Latitude: </b>{Latitude} <br /> " "<b> Value: </b>{Value}"}) r # output of clicked point should be input to a reusable list selectedID = st.selectbox("Choose point ID", df['PointID']) Thank you so much streamlit team for all your work and developing this awesome framework!
Hi @bafu-DF, welcome to the Streamlit community! Your use case makes perfect sense. Because of the many variations on how this could go (not just with pydeck, but any JavaScript-based library), we created the Streamlit components framework: https://docs.streamlit.io/en/stable/publish_streamlit_components.html#prepare-your-component 137 It may be in the future that we add the functionality you are imagining to Streamlit, but in the meantime, using the Components framework is the quickest way to accomplish this. Best, Randy
0
streamlit
Using Streamlit
Another error running app question
https://discuss.streamlit.io/t/another-error-running-app-question/20855
Hi, I have a question similar to I can't delete my own App I am unable to delete my app and I am receiving an error message when I try to launch it. The previous replies suggest that this is due to a name change, but the name of the repository has been unchanged. It did, however, switch owners. It is a private repo under an organization, and was transferred to another account owned by the organization, which is when this error began. I had initially forked the repo from the organization account, and no other errors occurred on github or elsewhere when the transfer occurred. I’ve tried re-forking the repo to no avail and I am unable to transfer the repo back. Is there any other way to delete it and restart? Any other suggestions? Perhaps I also mis-identified the problem since the name of the repository itself has not changed, e.g. it remained user/repo-name after the transfer. Just the account that it was forked from changed. I’m really at a loss of what this could be. I hope this makes sense. Thank you! Anna
Hi @Anna_Wuest, First, welcome to the Streamlit community! I actually think this might be a question for our support team. I have let them know that they should expect you to contact them soon. When you email them, include your: GitHub username email associated with your account any relevant details about this issue (you couple probably copy-paste your first post in this thread!) You can reach out to them with this email: support@streamlit.io Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Rendering PDF on UI
https://discuss.streamlit.io/t/rendering-pdf-on-ui/13505
Currently, on my local, I’m able to successfully render PDF files onto my UI. However, as I’m trying to deploy the app I’m running into the PDF file not being shown on the UI. As you can see through the inspect tools, the file’s component is being generated. Local: image2880×1564 500 KB Deployed: image2880×1568 404 KB Code: def displayPDF(file): # Opening file from file path with open(file, "rb") as f: base64_pdf = base64.b64encode(f.read()).decode('utf-8') # Embedding PDF in HTML pdf_display = F'<embed src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf">' # Displaying File st.markdown(pdf_display, unsafe_allow_html=True)
Using iframe instead of embed worked like a charm. pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf"></iframe>'
1
streamlit
Using Streamlit
Session expires on page reload
https://discuss.streamlit.io/t/session-expires-on-page-reload/4651
Like on any website, can we have the same Session State on Page Reload or Duplicate Tab?
Related: Persisting device fingerprint specific states specific to a client Using Streamlit Though there are ways to store a single session’s states (like this), there currently seems to be no way to persist them across refreshes for a single user/client. (Something roughly like a browser cookie or local storage) Not to be confused with a global persistent states (like this or this). It would be great if we could use the device fingerprint of the client to store a state object specific to that client. Would that be possible?
0
streamlit
Using Streamlit
Streamlit file explorer
https://discuss.streamlit.io/t/streamlit-file-explorer/16031
Hello! I am currently working on a streamlit site in Python, but I have no idea how to add a file explorer display into the site. Is there any way where I can identify a directory and I can add code that will allow users to view the files through folders and categories (similar to that of github project file explorer).
import os import streamlit as st filelist=[] for root, dirs, files in os.walk("your folder directory"): for file in files: filename=os.path.join(root, file) filelist.append(filename) st.write(filelist)
0
streamlit
Using Streamlit
Multi-page apps
https://discuss.streamlit.io/t/multi-page-apps/266
Is there any support for apps that have multiple pages? My use case is a 3-part workflow that I’d like to separate into three separate views with state carried across them. Stages generally are: 1- overview of data and category specification, 2- model refinement with active learning, and 3- overview of trained model results). Is this use case out of scope for streamlit, something that’s possible now, or something that’s planned? Thanks
Sounds interesting for me as well.
0
streamlit
Using Streamlit
User authentication
https://discuss.streamlit.io/t/user-authentication/612
Is it possible to add an authentication step to access streamlit? I want to control so that only users who can provide a correct username/password can access the content. Example: https://dash.plot.ly/authentication 1.8k
Welcome to the community, @fogel! Unfortunately I don’t have a good solution for you right now. We are working on this as part of the Streamlit for Teams 1.0k offering which is in limited beta right now and will be rolling out in early 2020. If you don’t need true authentication, you could just set up a passphrase using st.text_input and only show the app if the answer matches the passphrase you set. It’s not ideal, but if you are just trying to gate access that would work. A related feature request we’re tracking will also enable password text_inputs 637. Thank you for using Streamlit and we apologize for the delay. We’ve been a bit overwhelmed with the amount of questions coming in since launch.
0
streamlit
Using Streamlit
Working with Jupyter Notebooks
https://discuss.streamlit.io/t/working-with-jupyter-notebooks/368
My workflow often involves analyzing data and creating plots from within a Jupyter notebook (via matplotlib, plotly, seaborn, pandas). Most of the time, that involves a fig.show() command to render the figure I created within the notebook. What is the suggested workflow to get from a Jupyter notebook to a working streamlit script? Right now I need to: Change all fig.show() calls to st.show(fig) in the notebook. Export the Notebook to a .py file Strip out any Jupyter magic commands Run streamlit on the exported .py file Is it possible to use streamlit natively from within a notebook so that I don’t have to go through that process when moving from a notebook? Or is there an alternate suggested workflow for rapid/interactive development and analysis?
Hi @Tom If you prefer to use Jupyter when first analyzing data, then I think the steps you described above are indeed the right ones. Although I’d flip the order of (1) and (2), so you could write a script that processes the converted .py file with regexes to replace fig.show with st.show and remove %magic commands. Let me know if you need help putting together a script like that — it sounds like a fun project That said, I suggest you try doing your initial analysis in Streamlit too . It will require a bit more care in how you structure your code, but in my experience it works quite well!
0
streamlit
Using Streamlit
Is it possible to switch conda environments while Streamlit is running?
https://discuss.streamlit.io/t/is-it-possible-to-switch-conda-environments-while-streamlit-is-running/4440
Hi there, I’m a new user to Streamlit and have been playing around from past couple of weeks. I’m trying to create a application for Word embedding. Part of my models use libraries/code base that is dependent on Tensorflow 1.X and part of them use Tensorflow 2.X and also multiple pytorch dependencies. I have two separate anaconda environments for either of them to avoid dependency issues. I want to have just one application file which will show/run all models and results irrespective of the environments (or hiding all environment details from user). Is there a simple/dynamic way to switch conda environments while the Streamlit app is running. Was hoping advanced users might have some good insights on this ? Thanks! Mohammed Ayub
Hi @mohammed_ayub, welcome to the Streamlit community! In general, no, you can’t switch conda environments from the same Python session (this is a Python limitation, not a Streamlit one). Once you load a module one time, trying to reload it again won’t do anything: stackoverflow.com What happens when a module is imported twice? python, module answered by Thomas Orozco on 11:14AM - 29 Sep 13 UTC So once Tensorflow 1.x is loaded, that’s what you have. Additionally, with conda, the Python interpreter is part of the environment…trying to “switch” the interpreter is essentially stopping the code and starting a different executable, which means Streamlit would no longer be running. In industry, when people want to serve the results of a model, they wrap it up in their own process as an API, then call the API. You could do this in your case…depending on a drop-down or radio button in streamlit, you could call the different API endpoints for your model results.
1
streamlit
Using Streamlit
Download Button with Excel File
https://discuss.streamlit.io/t/download-button-with-excel-file/20794
I’m working on an app that allows for information to be downloaded to a Microsoft Excel file. I use XLSXWriter (https://xlsxwriter.readthedocs.io/) to create a file. Using inputs from Streamlit, the app I have created then downloads (or at least I am hoping it will) the excel file for the user. XLSXWriter returns a: <class ‘xlsxwriter.workbook.Workbook’> I am using the download button with the following code: st.download_button(label=‘Export to Excel’ , data = excel_file # excel file is the name of the downloaded <class ‘xlsxwriter.workbook.Workbook’> , file_name= ‘df_test.xlsx’ , mime = ‘application/vnd.openxmlformats-officedocument.spreadsheetml.sheet’) Any help on how to make this work would be greatly appreciated.
Hi @user-3135 Here’s a reproducible example that uses st.download_button to download an Excel workbook written to an in-memory string with BytesIO: import streamlit as st import xlsxwriter from io import BytesIO output = BytesIO() # Write files to in-memory strings using BytesIO # See: https://xlsxwriter.readthedocs.io/workbook.html?highlight=BytesIO#constructor workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet() worksheet.write('A1', 'Hello') workbook.close() st.download_button( label="Download Excel workbook", data=output.getvalue(), file_name="workbook.xlsx", mime="application/vnd.ms-excel" ) You should be able to adapt this example to your use-case. Let us know if you run into roadblocks! Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
Enter key press to submit st.form
https://discuss.streamlit.io/t/enter-key-press-to-submit-st-form/16939
Hi again (starting to feel like a local here! got too many annoying questions ), Just wondering why pressing the enter/return key in a Streamlit form doesn’t automatically submit the form. I’ve done some tests and pressing enter on a text_input in a form doesn’t seem to trigger a re-run of the script so it seems it’s not being used for that. Could it be that it’s because the <form> tags are omitted in the rendered html? It would be epic if the input widget that currently has focus is seen as part of that specific form and the corresponding submit button so that it’s possible to have multiple forms too that won’t get in the way with the enter key press since it will just grab the submit button that’s part of that form where the focus is at. There’s a good case to be made for accessibility too! (The Enter Key should Submit Forms, Stop Suppressing it 2) Thanks and have an awesome Streamlitty-bitty day!
Hey @Fhireman! You’re correct that we don’t use the <form> tag in the rendered HTML, and we don’t currently support enter-to-submit - and we should! I’ve added a feature request here: github.com/streamlit/streamlit st.form should create proper <form> element (with "enter to submit" support) 5 opened Sep 14, 2021 tconkling enhancement needs triage From a user request here: https://discuss.streamlit.io/t/enter-key-press-to-subm…it-st-form/16939 The request is correct: we don't currently use `<form>` tags in `st.form` HTML output. We should consider it!
1
streamlit
Using Streamlit
How to make a PWA with streamlit
https://discuss.streamlit.io/t/how-to-make-a-pwa-with-streamlit/10369
Hello! I wanna make a PWA using streamlit. So i make a manifest.json and try to add <link rel=‘manifest’…> in html header tag. But i dont know how to add. Please teach me how to add… Thank you
Hi @Soogle44, welcome to the Streamlit community! Could you be more specific about what you are trying to do? From the context, it looks like you are trying to pass manifest.json and want Streamlit to do something with it? Best, Randy
0
streamlit
Using Streamlit
Streamlit App (after initial loading) starts in the middle of the page instead of the top
https://discuss.streamlit.io/t/streamlit-app-after-initial-loading-starts-in-the-middle-of-the-page-instead-of-the-top/13165
Hello, I want my streamlit app to start at the top of the page after it is loaded, but for some reason it just jumps to the middle of the page. Is there anyway I can configure my app so it start at the top of the page every time it’s loaded?
Hi @corsilt, welcome to the Streamlit community! Without seeing your code, it’s pretty hard to make any suggestions. Do you have a code snippet that demonstrates this behavior? Best, Randy
0
streamlit
Using Streamlit
Delete/reset widgets in the main page on changing selections in the radio button on sidebar
https://discuss.streamlit.io/t/delete-reset-widgets-in-the-main-page-on-changing-selections-in-the-radio-button-on-sidebar/20554
One week back started using Streamlit. The docs are self-understandable and helped to quickly go prepare an app for my project. However, I ran into one critical issue as follows: My app is consists of: Two radio buttons on the sidebar Based on these selections, a different number of checkboxes, sliders, and dropdown appears on the main page. While changing the radio buttons selections, I receive the error: IndexError: list index out of range After debugging, I came to know this issue is because in st.session_state the earlier widgets are still present i.e. two checkboxes to be true, etc. My expectation here is that when a change of selection from radio button is noticed by app during rerun, all the widgets should be deleted or reset because the number of widgets and their values/names will change.
I have solved the problem by using the radio buttons selection in the key name and deleting the previously selected widgets using del st.session_state[key]
1
streamlit
Using Streamlit
Expander expanded=False not working
https://discuss.streamlit.io/t/expander-expanded-false-not-working/20786
two buttons. one expander in each button. both expanders are collapsed by default. expanding one expander under one button automatically leads to another expander expanding. Am I missing something here or is this a bug? here’s the live demo Streamlit 6 import streamlit as st b0 = st.button("b0") b1 = st.button("b1") if b0: with st.expander("b0_expander", expanded=False): st.write("b0_write") if b1: with st.expander("b1_expander", expanded=False): st.write("b1_write") maybe something related: Expander does not keep its state if something is displayed above it Using Streamlit I am having some troubles with st.expander. In the example below, if the second expander is opened and then the button is clicked, on the next run, the first expander is opened while the second one is closed. Any idea what is causing that? import streamlit as st # Load the data button = st.button('Click me') # Display message container = st.container() if button: with container: st.markdown('Data loaded') # Expanders with st.expander('Expander 1'): st.markdown('Expander 1X') … clearing cache doesn’t help github.com/streamlit/streamlit Is there a way to clear the cache from python script ? 1 opened Nov 21, 2019 closed Dec 4, 2019 amineHY I would like to create a button to manually free the cache, e.g. at the end of p…rocessing all frames. This option will help me to create a workaround to the conflict that occurs when caching cap object (from cv.VideoCapture) and cap.release()
Hey @kimehta, First, welcome to the Stereamlit community! Thanks so much for your detailed explanation and especially for the super helpful app and the exact steps to reproduce what you’re seeing. The same thing happens when I try and I have sent this onto the team to check out! I will let you know once I hear more from them! Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
https://discuss.streamlit.io/t/oserror-winerror-10013-an-attempt-was-made-to-access-a-socket-in-a-way-forbidden-by-its-access-permissions/1545
(stream) C:\Users\Ajinkya>streamlit hello Traceback (most recent call last): File "c:\users\ajinkya\miniconda3\envs\stream\lib\runpy.py", line 192, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\ajinkya\miniconda3\envs\stream\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Ajinkya\Miniconda3\envs\stream\Scripts\streamlit.exe\__main__.py", line 7, in <module> File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\click\core.py", line 717, in main rv = self.invoke(ctx) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\streamlit\cli.py", line 193, in main_hello _main_run(filename) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\streamlit\cli.py", line 251, in _main_run bootstrap.run(file, command_line, args) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\streamlit\bootstrap.py", line 181, in run server.start(_on_server_start) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\streamlit\server\Server.py", line 213, in start start_listening(app) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\streamlit\server\Server.py", line 122, in start_listening app.listen(port) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\tornado\web.py", line 2042, in listen server.listen(port, address) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\tornado\tcpserver.py", line 143, in listen sockets = bind_sockets(port, address=address) File "c:\users\ajinkya\miniconda3\envs\stream\lib\site-packages\tornado\netutil.py", line 168, in bind_sockets sock.bind(sockaddr) OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Hi @aidlml — and welcome to the forum! I found similar issues that might help: https://superuser.com/questions/635498/socket-error-errno-10013-port-forbidden-access-permissions 391 https://appuals.com/fix-an-attempt-was-made-to-access-a-socket-in-a-way-forbidden-by-its-access-permissions/ 240 It looks like Windows (or some other software) is blocking socket access to the provided port. Please let me know if the issue persists!
1
streamlit
Using Streamlit
Unique key for every items in radio button
https://discuss.streamlit.io/t/unique-key-for-every-items-in-radio-button/20654
Hi, Have do you assign a key for each item in a radio box? choices = st.sidebar.radio('Filter', ('United States', 'Canada')) selected = 'US' if choices == 'United States' else 'CA' I hope not to use a dictionary or function or the like to return the code assigned to the radio item. TIA!
The point was that your example only showed ('United States', 'Canada'), so that writing out the two combinations wouldn’t be that much work to do. If the list can be really long, then you can use the format_func argument: import streamlit as st mapping = {"US": "United States", "CA": "Canada"} choices = st.sidebar.radio("Filter", ("US", "CA"), format_func=lambda x: mapping[x]) choices # will show "United States" in radio button widget, return "US" to variable 'choices' I hope not to use a dictionary or function or the like to return the code assigned to the radio item. Not sure there is a different solution than the one I provide above. Best, Randy
1
streamlit
Using Streamlit
Is it possible to have example input values where user can select for st.form?
https://discuss.streamlit.io/t/is-it-possible-to-have-example-input-values-where-user-can-select-for-st-form/20768
Hi, just wanted to know how I can add example input values so user can click and it will fill up the form for st.form. Thank you
Well, st.text_input and st.text_area have a parameter called placeholder which should do what you want. You can review the docs as needed. For other widgets, you could probably use st.markdown to show example text (to serve the same functionality). Or you can put instructions in the help= parameter. Cheers
0
streamlit
Using Streamlit
Conda not activate in cmd
https://discuss.streamlit.io/t/conda-not-activate-in-cmd/20598
Hi all, I have question I can not install conda enviro. and with streamlit run myapp.py is not working at all. Thanks for your help
Hey @Phon_Oudom, Did you follow the instructions on Conda’s website to install it on a windows machine? https://docs.conda.io/projects/conda/en/latest/user-guide/install/windows.html#installing-on-windows Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Change font size and font color
https://discuss.streamlit.io/t/change-font-size-and-font-color/12377
I want to change the font color and size of the text written in cv2.imshow. Please tell the code… how to tackle this problem asap. @randyzwitch
@randyzwitch please reply to my query asap !!!
0
streamlit
Using Streamlit
How to have 2 rows of columns using st.beta_columns()
https://discuss.streamlit.io/t/how-to-have-2-rows-of-columns-using-st-beta-columns/11699
Hello! Loving the st.beta_columns function so far! In order to present a better layout, instead of having a row of 4 columns (1x4), I’d like to break up the columns into two rows of two columns (2x2). Sample code for 1x4: col1, col2, col3, col4 = st.beta_columns(4) with col1: selected_col1 = st.multiselect(…) with col2: selected_col2 = st.multiselect(…) with col3: selected_col3 = st.multiselect(…) with col4: selected_col4 = st.multiselect(…) I cannot make two consecutive calls of (to get 2x2): col1, col2 = st.beta_columns(2) col3, col4 = st.beta_columns(2) Can someone please advise me on how to make multiple rows of columns possible? Thank you very much!
Hi @dashboard I think you only need 2 columns for what you want, but with two calls, something like this: col1,col2=st.beta_columns(2) with col1: something in row1.. with col2: something in row1.. with col1: something in row2.. with col2: something in row2..
1
streamlit
Using Streamlit
Has anyone implemented a social sharing widget
https://discuss.streamlit.io/t/has-anyone-implemented-a-social-sharing-widget/20778
Hi, I want to add a “share this page” widget to my Streamlit app with “share to facebook, twitter, Linkedin” buttons. Has anyone done this? What’s a good way?
Hi @fredzannarbor , I’ve tried this in case of Twitter. Here’s the code. import streamlit as st import streamlit.components.v1 as components components.html( """ <a href="https://twitter.com/share?ref_src=twsrc%5Etfw" class="twitter-share-button" data-text="Check my cool Streamlit Web-App🎈" data-url="https://streamlit.io" data-show-count="false"> data-size="Large" data-hashtags="streamlit,python" Tweet </a> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script> """ ) You can tweak the code further, and make it as you want it. Refer to Tweet Button, for more information. Here’s how it looks when you click the tweet button image1196×1372 120 KB Probably, if you don’t use the parameter data-url="https://streamlit.io" , will be auto-populated. Does this help ? Best, Avra
0
streamlit
Using Streamlit
Ag-Grid
https://discuss.streamlit.io/t/ag-grid/20545
Firstly Happy New Year to all the members of Streamlit Community. How to add “Select All” option in Ag-Grid? I will be highly obliged if you give me a solution.
Please someone help me. Or if there are any resources please forward it to me.
0
streamlit
Using Streamlit
How to embed javascript into streamlit?
https://discuss.streamlit.io/t/how-to-embed-javascript-into-streamlit/20152
have a streamlit app that i want to embed into it javascript i already add html tags by using st.markdown() and i was able to add some bootstrap but when i tried to add javascript code above the html tags it crashes. So how this can be done within streamlit ?
Hi - Use components.html 7.
0
streamlit
Using Streamlit
Streamlit not recognizing module from same package
https://discuss.streamlit.io/t/streamlit-not-recognizing-module-from-same-package/4572
Hi. I’m new to streamlit, and attempting to build a dashboard with it. I have problems importing a class from the same package. My code: import streamlit as st from dashboard_layer.freq_enums import frequency_enum if __name__ == '__main__': print(frequency_enum.freqsAll_mt.value) In the console I see “hi” In the app I see: I would appreciate any help you can give. Thank you!
Bump?
0
streamlit
Using Streamlit
File Uploader File to OpenCV imread
https://discuss.streamlit.io/t/file-uploader-file-to-opencv-imread/8479
How can I pass image file from file_uploader() to opencv’s imread()?
file_uploader does not store the uploaded file on the webserver but keeps it in memory. It returns a ‘stream’ class variable to access it. I came across this situation as well but honestly I dont have THE answer yet. Fact seems to be that some python modules dont care whether you throw a pathname or a stream at them , but many other do. To me the python ‘stream’ classes appear as a relatively relatively complex matter. You may try to give imread the stream but if this doesnt work you may save the stream to a file and then read like usual. However it might be difficult with streamlit to find the right point in time to delete the quasi temporary file. I dont know if the webserver does this by it itself, does it? Same issue with files you create for downloading. AT the moment I am completely ignoring this issue on my streamlit apps because there are only very few users that work with them. code fragment to save the file: fs = st.file_uploader('upload a file') if fs is not None: with open(fs.name,'wb') as f: f.write(fs.read())
1
streamlit
Using Streamlit
Aggrid: Is there a way to color a row based on a column value?
https://discuss.streamlit.io/t/aggrid-is-there-a-way-to-color-a-row-based-on-a-column-value/20750
Hi. I’m using streamlit-aggrid custom component to display dataframes. I’d like to color an entire row based on a specific column’s value. I’m not sure how to do it as there are no examples provided for this. Please help. Best wishes, Dinesh
I figured out how to do it, thanks to code to enable other functionality not directly supported that a user posted on the Aggrid thread in Show the Community channel. The following snippet should help (I’m assuming the dataframe has a column called state, and you know about using Aggrid otherwise including imports): jscode = JsCode(""" function(params) { if (params.data.state === 'failed') { return { 'color': 'white', 'backgroundColor': 'red' } } }; """) gridOptions = gb.build() gridOptions['getRowStyle'] = jscode grid_response = AgGrid( df, gridOptions=gridOptions, allow_unsafe_jscode=True, ) Hope this helps others searching for a similar answer, Dinesh
0
streamlit
Using Streamlit
Embedding a terminal
https://discuss.streamlit.io/t/embedding-a-terminal/9339
Hello, I wondered if there’s a way to embed a python terminal in streamlit? I’ve got a CLI (using pyinquirer) that I don’t really want to part with, but would like to have it embedded so that I can also display some charts around it too.
Hi @B_W, welcome to the Streamlit community! Not sure if there’s a current solution, but it looks like if someone wrote a Streamlit Component for xterm.js 33, that might work? Best, Randy
0
streamlit
Using Streamlit
Wordcloud
https://discuss.streamlit.io/t/wordcloud/5714
Hey, How can I create Wordcloud in Streamlit?
Hi @theamitbhardwaj Welcome to the community, Creating wordclouds is not something that streamlit supports out of the box but you can create wordclouds convert them to an array and use st.image to show it, You can use this library for generating word clouds https://github.com/amueller/word_cloud 43 import streamlit as st from wordcloud import WordCloud wc = WordCloud().fit_words({"A": 2, "B": 2, "C": 3}) st.image(wc.to_array()) Hope it helps!
1
streamlit
Using Streamlit
Filtering data with pandas
https://discuss.streamlit.io/t/filtering-data-with-pandas/20724
Hi everybody, i have a Excel files with dataframe and i want filtering it with multiselect input widget. Code is following: import streamlit as st import pandas as pd import openpyxl as oxl from PIL import Image import numpy as np import plotly.express as px st.set_page_config(page_title="Spazio Italia Ordinato", layout="wide") immagine = "/home/andrea/Documenti/VsCode/StreamLit/spazio.png" st.sidebar.image(immagine) @st.cache(persist =True) def get_data_from_excel(): data = pd.read_excel( "Ordinato.xlsx", sheet_name="dettaglio", usecols="A:H", header=0, converters={'Anno':int, "Valore":int} ) return data df = get_data_from_excel() st.markdown("<h1 style='text-align: center; color: white;'>Dashboard Ordinato</h1>", unsafe_allow_html=True) # st.title(':bar_chart: Dashboard Ordinato') st.markdown("""---""") # --------SIDERBAR----------- st.sidebar.header("Filtri:") azienda = st.sidebar.multiselect('Scegliere una o piu Aziende:', options=df["Azienda"].unique(), default="OLDLINE") anno = st.sidebar.multiselect('Scegliere uno o piu Anni:', options=df["Anno"].unique()) manager = st.sidebar.multiselect('Scegliere uno o piu manager:', options=df["Manager"].unique()) citta = st.sidebar.multiselect('Scegliere una o piu Città:', options=df["Citta"].unique()) #-----FILTRI------ df_selection = df.query( "Azienda == @azienda & Anno == @anno & Manager == @manager & Citta == @citta" ) st.dataframe(df_selection) #----MAIN PAGE -------- st.markdown("""---""") st.markdown("##") total_order = len(df_selection) total_sales = int(df_selection["Valore"].sum()) mean_sales = int(df_selection["Valore"].mean()) left_column, middle_column, right_column = st.columns(3) with left_column: st.subheader(":baggage_claim: Numero di Ordini:") st.subheader(f"{total_order}") with middle_column: st.subheader(":euro: Totale Ordini:") st.subheader(f"€ {total_sales:,}") with right_column: st.subheader(":chart: Media ordini:") st.subheader(f"€ {mean_sales:,}") st.markdown("""---""") # SALES BY YEARS [BAR CHART] sales_by_years = df_selection.groupby(by=["Anno"]).sum()[["Valore"]] fig_years_sales = px.bar( sales_by_years, x=sales_by_years.index, y="Valore", title="<b>Vendite per Anno</b>", color_discrete_sequence=["#0083B8"] * len(sales_by_years), template="plotly_white", ) fig_years_sales.update_layout( xaxis=dict(tickmode="linear"), plot_bgcolor="rgba(0,0,0,0)", yaxis=(dict(showgrid=False)), ) # SALES BY MANAGER [BAR CHART] sales_by_manager = df_selection.groupby(by=["Manager"]).sum()[["Valore"]] fig_manager_sales = px.bar( sales_by_manager, x=sales_by_manager.index, y="Valore", title="<b>Vendite Azienda/Manager</b>", color_discrete_sequence=["#0083B8"] * len(sales_by_manager), template="plotly_white", ) fig_manager_sales.update_layout( xaxis=dict(tickmode="linear"), plot_bgcolor="rgba(0,0,0,0)", yaxis=(dict(showgrid=False)), ) left_column, right_column = st.columns(2) left_column.plotly_chart(fig_years_sales, use_container_width=True) right_column.plotly_chart(fig_manager_sales, use_container_width=True) my problem is that i would like filter columns ANNO (years), azienda (company), Manager and città (city) and i try to do that with pandas query. But if is use AND bitwise operatore &, i got filtered dataframe just with first filter used. If i use OR bitwise operator | the same problem. How i can get filtered data with all conditions i need? Thanks for the help! Andrea
I use and and or in df.query all the time, not the & and |. That works.Have you tried that? I also use parentheses to keep the conditions clear. Dinesh
0
streamlit
Using Streamlit
St.file_uploader keeps calling the callback function passed into the ‘on_change’ parameter on every other widget change
https://discuss.streamlit.io/t/st-file-uploader-keeps-calling-the-callback-function-passed-into-the-on-change-parameter-on-every-other-widget-change/20293
Streamlit v1.3.0 I only want the file_uploader to run the callback function when I remove any file or upload any new file to the file_uploader widget. But now I’m having this issue where it keeps calling the ‘on_change’ callback function even though I didn’t remove or upload any file. The way to trigger this is just to change any other widget’s value (e.g. the st.radio button in the example code below). But I know I’m actually changing it’s value when I tried to access it to copy the file to a temporary folder to use it to do something. So I tried to use video_file.seek(0) and also deepcopy(video_file) to try to avoid changing the value of the file_uploader, but still in vain. Please help. import streamlit as st import shutil import os from copy import deepcopy from pathlib import Path TEMP_DIR = Path('tmp/extracted') def dummy_cb(): print("DUMMY CALLBACK FOR FILE UPLOADER") video_file = st.sidebar.file_uploader( "Upload a video", type=['mp4', 'mov', 'avi', 'asf', 'm4v'], key='video_file_uploader', on_change=dummy_cb) if video_file is None: st.stop() # use this to avoid keep calling the file_uploader's callback # NOTE: still not helping... uploaded_video = deepcopy(video_file) video_path = str(TEMP_DIR / uploaded_video.name) print("Copying file") if TEMP_DIR.exists(): shutil.rmtree(TEMP_DIR) os.makedirs(TEMP_DIR) print(f"{video_path = }") with open(video_path, 'wb') as f: f.write(uploaded_video.getvalue()) # seeking is also not helping uploaded_video.seek(0) video_file.seek(0) st.radio("options", (1, 2), key='dummy_options') st.stop()
I settled with a workaround by performing all the necessary callbacks within the if video_file is None statement. This works well for accepting a single upload but probably not multiple files. if video_file is None: logger.info("Resetting states for uploaded video") # reset and remove the TEMP_DIR if there's no uploaded file # to ensure the app only reads the new uploaded file reset_cb() if TEMP_DIR.exists(): shutil.rmtree(TEMP_DIR) os.makedirs(TEMP_DIR) st.stop() # using str to ensure readable by st.video and cv2 video_path = str(TEMP_DIR / video_file.name) if not os.path.exists(video_path): # only creates it if not exists, to speed up the process when # there is any widget changes besides the st.file_uploader logger.debug(f"{video_path = }") with st.spinner("Copying video to a temporary directory ..."): with open(video_path, 'wb') as f: f.write(video_file.getvalue())
0
streamlit
Using Streamlit
Error during installation
https://discuss.streamlit.io/t/error-during-installation/20669
Dear Team, Getting the following error while installing streamlit. Please help "ERROR: Could not build wheels for backports.zoneinfo which use PEP 517 and cannot be installed directly" ---Full error: Using cached tzdata-2021.5-py2.py3-none-any.whl (339 kB) Building wheels for collected packages: backports.zoneinfo Building wheel for backports.zoneinfo (PEP 517) ... error ERROR: Command errored out with exit status 1: command: /opt/anaconda3/envs/st/bin/python /opt/anaconda3/envs/st/lib/python3.6/site-packages/pip/_vendor/pep517/in_process/_in_process.py build_wheel /var/folders/nl/83xqjm8x18z2ymb3nm8x1qcw0000gn/T/tmp6sxxkwg4 cwd: /private/var/folders/nl/83xqjm8x18z2ymb3nm8x1qcw0000gn/T/pip-install-1bxuhs8t/backports-zoneinfo_bf635f132515425cad8867f2f29c99da Complete output (36 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-x86_64-3.6 creating build/lib.macosx-10.9-x86_64-3.6/backports copying src/backports/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/backports creating build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/_version.py -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/_common.py -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/__init__.py -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/_zoneinfo.py -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/_tzpath.py -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo running egg_info writing src/backports.zoneinfo.egg-info/PKG-INFO writing dependency_links to src/backports.zoneinfo.egg-info/dependency_links.txt writing requirements to src/backports.zoneinfo.egg-info/requires.txt writing top-level names to src/backports.zoneinfo.egg-info/top_level.txt reading manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no files found matching '*.png' under directory 'docs' warning: no files found matching '*.svg' under directory 'docs' no previously-included directories found matching 'docs/_build' no previously-included directories found matching 'docs/_output' adding license file 'LICENSE' adding license file 'licenses/LICENSE_APACHE' writing manifest file 'src/backports.zoneinfo.egg-info/SOURCES.txt' copying src/backports/zoneinfo/__init__.pyi -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo copying src/backports/zoneinfo/py.typed -> build/lib.macosx-10.9-x86_64-3.6/backports/zoneinfo running build_ext building 'backports.zoneinfo._czoneinfo' extension creating build/temp.macosx-10.9-x86_64-3.6 creating build/temp.macosx-10.9-x86_64-3.6/lib gcc -Wno-unused-result -Wsign-compare -Wunreachable-code -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/opt/anaconda3/envs/st/include -arch x86_64 -I/opt/anaconda3/envs/st/include -arch x86_64 -I/opt/anaconda3/envs/st/include/python3.6m -c lib/zoneinfo_module.c -o build/temp.macosx-10.9-x86_64-3.6/lib/zoneinfo_module.o -std=c99 xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: command 'gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for backports.zoneinfo Failed to build backports.zoneinfo ERROR: Could not build wheels for backports.zoneinfo which use PEP 517 and cannot be installed directly
Hi @Prabhat, welcome to the Streamlit community! What version of OSX, Python and Streamlit are you trying to use? Best, Randy
0
streamlit
Using Streamlit
“Server error [A10]: Unable to create app”
https://discuss.streamlit.io/t/server-error-a10-unable-to-create-app/9312
,I cannot able to create and deploy my app.Please help me out here. image1094×518 25.8 KB Thank you
I suspect the spaces in the directory name Flight fare prediction are causing the error. I would suggest renaming the directory in your repo to remove the spaces and/or replace them with another character like a hyphen or underscore.
1