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 | Text_input refreshes whole script | https://discuss.streamlit.io/t/text-input-refreshes-whole-script/19385 | I have created a search engine and want to use streamlit for it. Now my script loads a model which takes quite some time and then asks user to put query in the text_input field. The problem is whenever I press enter after putting query, it refreshes the whole script and my model loads again. I tried to use on_change callback, but this function does not receive any input from the text_input field. How to solve this issue? | Hi @pritam-dey3, welcome to the Streamlit community!!
I would suggest decorating the function that loads your model with @st.experimental_singleton. This will ensure that your model is cached after the first call to load the model, and will prevent your app from loading the same model with every widget interaction.
We’re developing new cache primitives that are easier to use and much faster than @st.cache.
Use @st.experimental_singleton to cache functions that return non-data objects like TensorFlow/Torch/Keras sessions/models and/or database connections.
Use st.experimental_memo to cache functions that return data like dataframe computation (pandas, numpy, etc), storing downloaded data, etc.
Read more here: Experimental cache primitives - Streamlit Docs
Here’s pseudocode to cache your ML model:
import streamlit as st
import favmodellibrary
# Decorator to cache non-data objects
@st.experimental_singleton
def load_model():
# Load large model
model = favmodellibrary.create_model()
return model
# Model is now cached
model = load_model()
# On subsequent interactions, the cached model will be used
# When the input changes, the cached model will be used
text = st.text_input("Enter some text", value="Classify this")
if text:
output = model.classify(text)
st.write("Prediction: ", output)
Does this help?
Happy Streamlit-ing!
Snehan | 1 |
streamlit | Using Streamlit | How to download file in streamlit | https://discuss.streamlit.io/t/how-to-download-file-in-streamlit/1806 | There are some files generate by my program, I need a button when I press files will be download by my browser, but I don’t know how to do that. could streamlit provide this function? | Adding the ‘download’ tag attribute as shown below allows you to provide a file name and extension.
f'<a href="data:file/csv;base64,{b64}" download="myfilename.csv">Download csv file</a>' | 1 |
streamlit | Using Streamlit | Can streamlit application access servers over the web using REST APIs? | https://discuss.streamlit.io/t/can-streamlit-application-access-servers-over-the-web-using-rest-apis/19400 | Hi.
I’m new with streamlit
Can a streamlit-applications access servers over the web using REST APIs?
should there be any issue with that?
Thanks | Yes, I do it all the time | 0 |
streamlit | Using Streamlit | Any workaround for placeholder of interactive widget? | https://discuss.streamlit.io/t/any-workaround-for-placeholder-of-interactive-widget/19397 | Hi,
I’m trying to find any workaround to the problem that one can’t use a placeholder for interactive widgets.
for example: st.number_input
When I press a button widget, I want the option to clear the widget from the screen.
Blockquote
import streamlit as st
import numpy as np
if ‘flag’ not in st.session_state:
st.session_state.flag = 0
if st.session_state.flag ==0:
n = st.number_input(“enter number:”,1,10,4)
if st.button(“random plot”):
st.session_state.flag =1
st.bar_chart(np.random.randn(50, 3))
Blockquote
image741×268 1.38 KB
So, when I hit the ‘random plot’ button, I want to remove the input widget from the UI.
I understand that this is a problem, but I was wondering if anyone knew of a workaround or had any ideas on how to solve it.
Thanks in advance | ori:
one can’t use a placeholder for interactive widgets
Hi @ori,
You can actually use st.empty() to create a placeholder for the number input widget, which you can then clear after a button click.
Here’s how:
import streamlit as st
import numpy as np
# Function to clear the number input widget
def clear_number_widget(widget):
widget.empty()
# Insert a single element container
placeholder = st.empty()
if 'flag' not in st.session_state:
st.session_state.flag = 0
if st.session_state.flag ==0:
# Use the placeholder container to hold a number input widget
n = placeholder.number_input("enter number:",1,10,4)
if st.button("random plot"):
st.session_state.flag =1
# Clear the number input widget
clear_number_widget(placeholder)
st.bar_chart(np.random.randn(50, 3))
Output:
Does this help?
Happy Streamlit-ing!
Snehan | 1 |
streamlit | Using Streamlit | St.table() does not match the documentation | https://discuss.streamlit.io/t/st-table-does-not-match-the-documentation/19270 | I just recently upgraded to streamlit version 1.2 and the visual representation of st.table() is totally new and does not match with the visuals on the documentation page:
Here is the output when I run the following test app (taken directly from the docs page)
#!/usr/bin/env python
import streamlit as st
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 5), columns=('col %d' % i for i in range(5)))
st.table(df)
Screen Shot 2021-11-18 at 3.54.17 PM1944×1040 177 KB
You can see it looks very different (not as cool) as the visual on the docs page.
Any help? | Hi @lklein,
Thank you for bringing this to our attention. The visual in the documentation is outdated and does not account for the fairly recent design updates to st.table. I will make the change.
Happy Streamlit-ing!
Snehan | 1 |
streamlit | Using Streamlit | How to download profile_report() from Pandas Profiling? | https://discuss.streamlit.io/t/how-to-download-profile-report-from-pandas-profiling/19277 | Greetings,
I am working on a mini project wherein I ask the users to upload a CSV file. I performed some basic EDA and visuals, I also made use of the Pandas Profiling in order to generate the profile report. I want to create a download button which on clicking allows the users to download the profile report.
The code I have tried is :
if dataset is not None:
df = pd.read_csv(dataset , delimiter = ",")
st.dataframe(df)
pr = df.profile_report()
st_profile_report(pr)
export=pr.to_file(b"Analysis.html")
st.download_button(label="Download Full Report", data=export,file_name='Profile Report')
Sadly I don’t find this working ( I am using Streamlit version 1.2.0). Requesting help from the community to find a workaround to achieve the above.
Thanks in advance. | Hello @Sai_Ram_k, welcome to the community!
The st.download_button expects data but I think the pr.to_file() only creates the file and does not return any html data back to Python. There’s a .to_html() that does the trick though:
export=pr.to_html()
st.download_button(label="Download Full Report", data=export, file_name='report.html')
Happy Streamlitin’
Fanilo | 1 |
streamlit | Using Streamlit | Tooltip for Metric | https://discuss.streamlit.io/t/tooltip-for-metric/19380 | Hi everyone,
I would like to add a tooltip to my “st.metric”, so that when the user hover the metric or its title he can see more details about the calculations.
I can’t use the “help” argument that already exists for the radio feature. I thaught about using an empty st.markdown (with unsafe_allow_html paramater), but I was wondering if someone had a more elegant solution!
Anyway, great framework ! | Hello @Gu1g-Z, welcome to the community
You’re right, this is an issue that has been spotted here:
github.com/streamlit/streamlit
Add tooltip to st.metric(0 to provide more information on a KPI 2
opened
Sep 29, 2021
knorthover
enhancement
### Problem
It would help our business users to have a bit more description a…vailable on KPIs.
### Solution
**MVP:** Could we add a tooltip to the _st.metric()_ function? That would provide a lot of drill down flexibility, background description and the ability to use f-strings to include more detailed information
Could you bump that issue by putting a comment to it? That should help reprioritize
Have a nice day,
Fanilo | 0 |
streamlit | Using Streamlit | Plotly templates don’t work properly | https://discuss.streamlit.io/t/plotly-templates-dont-work-properly/17593 | It seems that plotly’s templates don’t render properly in streamlit. The graphs change, but only the default template seems to work properly. Try running the below code, taken from plotly’s documentation: Theming and templates | Python | Plotly 1
import streamlit as st
import plotly.express as px
df = px.data.gapminder()
df_2007 = df.query("year==2007")
for template in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white", "none"]:
fig = px.scatter(df_2007,
x="gdpPercap", y="lifeExp", size="pop", color="continent",
log_x=True, size_max=60,
template=template, title="Gapminder 2007: '%s' theme" % template)
st.plotly_chart(fig)
I’m happy to look into this but don’t know where to start! | Ditto. Exact same code. | 0 |
streamlit | Using Streamlit | Copy dataframe to clipboard | https://discuss.streamlit.io/t/copy-dataframe-to-clipboard/2633 | Is it possible to copy the data displayed by st.dataframe to the clipboard? The current implementation allows a partial copy paste for single column dataframes, but doesn’t work at all for multi column.
Thanks,
Kieran | Hi @kierancondon, welcome to the Streamlit community!
Can you be more specific of the behavior you are desiring? For a multi-column dataframe, is your desire to be able to still highlight just a single column?
Best,
Randy | 0 |
streamlit | Using Streamlit | Styling Streamlit’s Dataframe Index & Header | https://discuss.streamlit.io/t/styling-streamlits-dataframe-index-header/9115 | Hey! I love streamlit’s built-in dataframe for many obvious reasons:
Responsive for desktop & mobile
You can always see column names & index names even when scrolling around
Allows me to display my fancy dataframes with minimal headache
Background: I work in an industry that’s super opinionated on formatting its tables. Using pandas built-in styling, I’m able to achieve 99% of my needs (highlighting subtotals, formatting negatives with parentheses, all that jazz). However, all this pandas styling only applies to the values of the dataframe and not the index/column headers.
Request: Has anyone figured out a way to style the index & column header as well? Perhaps the below example highlights my issue. I’d like to make “Total UCF” dark grey as I’ve already done with pandas styling. And I’d also like to make the headers “Entry, 2018, 2019,” etc. dark blue & bold with white font. Any ideas?! (actual figures hidden b/c confidential)
df example809×311 13.6 KB
I can (& have) achieved this with plotly tables. But they’re a little less ideal because they’re effectively static images without the magic of keeping the header & index in-place as the user scrolls around the dataframe. Any clue how to do this with the native st.dataframe()? Or something that behaves similarly (i.e. can do the three things bulleted above). I’m open to hacks and other libraries you may know, but the ideal would be Streamlit-native (but beggars can’t be choosers). | I have the same issue. I would especially like to format the table header. I remember reading a post saying this was not possible. Any positive update would be most welcome. | 0 |
streamlit | Using Streamlit | ValueError: Unknown graph. Aborting | https://discuss.streamlit.io/t/valueerror-unknown-graph-aborting/4991 | This happens as soon as I try to load my Keras-retinanet model & can only be resolved after clearing the cache and reloading the page.
This happens every time I run my first prediction.
ValueError: Unknown graph. Aborting.
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/streamlit/script_runner.py”, line 324, in _run_script
exec(code, module.dict)
File “/home/linus/Desktop/GitHub/Automatic-License-Plate-Recognition/app.py”, line 562, in
annotated_image, score, draw, b, crop_list = detector(IMAGE_PATH)
File “/home/linus/Desktop/GitHub/Automatic-License-Plate-Recognition/app.py”, line 226, in detector
boxes, scores, labels = inference(model, image, scale) # session
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/streamlit/caching.py”, line 593, in wrapped_func
return get_or_create_cached_value()
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/streamlit/caching.py”, line 573, in get_or_create_cached_value
return_value = func(*args, **kwargs)
File “/home/linus/Desktop/GitHub/Automatic-License-Plate-Recognition/app.py”, line 177, in inference
boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/keras/engine/training.py”, line 1579, in predict_on_batch
self._make_predict_function()
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/keras/engine/training.py”, line 378, in _make_predict_function
**kwargs)
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/keras/backend/tensorflow_backend.py”, line 3009, in function
**kwargs)
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/tensorflow/python/keras/backend.py”, line 3825, in function
return EagerExecutionFunction(inputs, outputs, updates=updates, name=name)
File “/home/linus/miniconda3/envs/license_plate/lib/python3.7/site-packages/tensorflow/python/keras/backend.py”, line 3709, in init
raise ValueError(‘Unknown graph. Aborting.’) | Instead of loading the model globally, it’s only loading when a sub-page is entered. This solved my problem. | 1 |
streamlit | Using Streamlit | Closeing Images | https://discuss.streamlit.io/t/closeing-images/19360 | I have a loop that is displaying a video frame by frame.
My issue is, I was expecting the images to display frame by frame…like flipping through a set of index cards; however, I’m getting the frames to display underneath each other one by one in a cascading fashion (if that makes sense).
Is there a way I can close an image in my streamlit app?
Here is my code
cap = cv2.VideoCapture('/content/video.mp4')
while cap.isOpened():
ret, image = cap.read()
st.image(Image.open(image), width=1200) | Hi @Andre_Williams,
Thank you for describing the expected and actual behavior, and providing a code snippet!
I would recommend using st.empty() to create a container for the image outside the while loop. In the while loop, call the .image() function on the container to draw the image, instead of st.image().
For every iteration i of the while loop, image_i-1 will be replaced by image_i:
import streamlit as st
import cv2
import time
cap = cv2.VideoCapture("/content/video.mp4")
# Create a single-element container
image_container = st.empty()
while cap.isOpened():
ret, frame = cap.read()
if ret:
# Display the frame in the container and
# Replace contents of the container with next frame on the next iteration
image_container.image(frame, width=800)
time.sleep(0.05) # Optional delay
else:
break
Does this help?
Happy Streamlit-ing!
Snehan | 0 |
streamlit | Using Streamlit | HELP - Have to press the login form submit twice | https://discuss.streamlit.io/t/help-have-to-press-the-login-form-submit-twice/19349 | Hello
Have a login form for which I have to press the submit button twice for anything to happen. I have a callback function set on the button which apparently doesn’t seem to get called on button press the first time around. | Hi @puzzled-cognition,
Could you share a minimal code example? That will allow us reproduce this behavior on our end to help with debugging.
Best,
Snehan | 0 |
streamlit | Using Streamlit | How can I change the position of the columns? | https://discuss.streamlit.io/t/how-can-i-change-the-position-of-the-columns/19265 | Hi guys, I’m new on streamlit and would like to know how I can change the positions of the columns generated from st.columns().
I’m collaborating on developing an app using streamlit and I need two “floating” columns on the left and right sides of the page.
In the documentation, I can’t find any modification options for st.columns().
Something like this example:
WhatsApp Image 2021-11-16 at 16.57.181280×615 95.4 KB | Hi @renanrodm, welcome to the Streamlit community!
Instead of viewing them as two floating columns, you could think of this as a 3-column layout. In that case, you could use st.columns to create 3 columns, re-sizing the center column to be however much wider you desire it to be.
Best,
Randy | 0 |
streamlit | Using Streamlit | Data frame error of the same code | https://discuss.streamlit.io/t/data-frame-error-of-the-same-code/19348 | Data frames are imported intermittently through Pandas data readers. I separated two pages through navigation, but an error occurs only in the same place.
error1841×887 117 KB
this is error meseege and code. There are times when data frames come out and times when they don’t.
nomal908×651 26.2 KB
This code and page are normally printed pages.
Streamlit
This is my distributed application.
LEEGIYEONG/StockPrediction: 2021년 LSTM, NeuralProphet 주가지수예측 (github.com)
This is my repo
Why is this error coming out when it’s the same chord? Please | Try the following:
Step #1: Check if you first externally installed the datareader with the command:
pip install pandas_datareader
Step #2: Check if you then initialized it in your program with the command:
import pandas_datareader.data as web
Step #3: Change 4th line of your function from:
df = data.DataReader(
To:
df = web.DataReader( | 0 |
streamlit | Using Streamlit | Remove, avoid empty array,list being viewed | https://discuss.streamlit.io/t/remove-avoid-empty-array-list-being-viewed/4498 | Hi,
I’m new using nice tool - streamlit and I would like to know how to avoid empty array or list be viewed.
I’m creating some pandas tables wich I can show without any problem with st.write() …
however, before the table, I see "empty " list with null values.
I have 12 like:
[…]
[
0:NULL
1:NULL
2:NULL
3:NULL
4:NULL
5:NULL
6:NULL
7:NULL
8:NULL
]
No idea why it appears if I do not have any st.func() for example.
Any help or guide is very appreciated - Thanks | Hi @Dicast, welcome to the Streamlit community!
I’m not sure I understand your question, could you be more specific? Maybe if you post a code snippet we can see what the issue is.
Best,
Randy | 0 |
streamlit | Using Streamlit | How to handle dummy variables | https://discuss.streamlit.io/t/how-to-handle-dummy-variables/19204 | Please how do you handle variables that have been converted to dummies in the streamlit app creation?
For example; when creating a scorecard, the optBinning library will convert all variables to dummies. How do you implement such variables when creating the app?
Thank you | Hi @Elijah_Nkuah -
Can you share a code snippet that demonstrates this behavior?
Best,
Randy | 0 |
streamlit | Using Streamlit | Clear the cache for file uploder on streamlit | https://discuss.streamlit.io/t/clear-the-cache-for-file-uploder-on-streamlit/14304 | Hello, I have a big issue when I try to upload a batch of images using file uploader for the first batch is upload but I need to clear the list of file uploader to classify the other batches because if I don’t the second, third,… just append How can I fix this issue??? | Hey @safae_belkyr,
First, welcome to the Streamlit community!!!
The only way to clear files from the uploader is to hit the ‘x’ button, there is no official programmatic way to clear them.
BUT with the introduction of forms and the clear_on_submit, you might be able to get the behaviour your looking for!
Take this example:
with st.form("my-form", clear_on_submit=True):
file = st.file_uploader("FILE UPLOADER")
submitted = st.form_submit_button("UPLOAD!")
if submitted and file is not None:
st.write("UPLOADED!")
# do stuff with your uploaded file
This will allow you to upload a file and hit the UPLOAD! button. When Streamlit re-runs, the file will be uploaded and run through any process you have in the if submitted and file is not None statement, and the file_uploader at the top will be cleared and ready for the next file or “batch”!
Happy Streamlit-ing!
Marisa | 1 |
streamlit | Using Streamlit | Pd.read_excel(nrows=) | https://discuss.streamlit.io/t/pd-read-excel-nrows/19299 | Only when I am specifying nrows with pd.read_excel Streamlit accepts the dataframe
df = pd.read_excel(io=uploaded_file, engine=“openpyxl”, sheet_name=“data”, skiprows=3,
usecols=[0, 1, 2, 3, 7], names=[‘year’, ‘month’, ‘day’, ‘hour’, ‘Hm0’], nrows=8767)
When nrows is omitted I get an error message, the excel sheet is clean and filled with proper data
What could this error be and how can I read in any Excel sheet with a certain given rows?
When running the code in jupyter notebook or other code editor there are no errors. | Hi @M_LUY
Would you mind pasting the exact error message you’re getting?
Best,
Snehan | 0 |
streamlit | Using Streamlit | Pay wall for streamlit content | https://discuss.streamlit.io/t/pay-wall-for-streamlit-content/19156 | I want to build a proof of concept for a streamlit app where some of the charts require users to first pay/subscribe.
Simple scenario:
non authenticated users can see content A
Authenticated subscribed users can see content B
I have a small budget for this, if anyone is interested hit me up and we can build together!
Thanks! | I don’t have time but would love to see how it turns out (or already turned out)! | 0 |
streamlit | Using Streamlit | Using mplfinance with streamlit? | https://discuss.streamlit.io/t/using-mplfinance-with-streamlit/19322 | Hi,
is it possible to use mplfinance 3 with streamlit?
With my code:
fig = mpf.figure(style='yahoo', figsize=(8,6))
mpf.plot(hist)
st.pyplot(fig)
i only see a white window.
Thank you | Thanks for posting a more complete example. A couple of things I discovered browsing the mplfinance source code:
Streamlit st.pyplot requires a matplotlib fig object (which it can save to disk to render the plot)
It’s possible to have mpf.plot return fig and ax, but only if returnfig=True is given
See the source code (line 778) here 1
Once you have a handle on fig, you’re in business!
Here’s a fully functioning solution I wrote (since I happen to be doing some financial technical analysis myself at the moment ):
Demo
https://user-images.githubusercontent.com/138668/142746621-5e6884a9-be52-4b40-8f2d-0fed175a1f0d.gif(image larger than 4 MB) 6
Code
from datetime import date, datetime
import streamlit as st
import pandas as pd
import mplfinance as mpf
from pandas_datareader import data as pdr
st.experimental_memo(persist='disk')
def get_historical_data(symbol, start_date = None):
df = pdr.get_data_yahoo(symbol, start=start_date, end=datetime.now())
df = df.rename(columns = {'Open': 'open', 'High': 'high', 'Low': 'low', 'Close': 'close', 'Adj Close': 'adj close', 'Volume': 'volume'})
for i in df.columns:
df[i] = df[i].astype(float)
df.index = pd.to_datetime(df.index)
if start_date:
df = df[df.index >= start_date]
return df
st.title('mplfinance demo')
c1, c2, c3 = st.columns([1,1,1])
with c1:
symbol = st.selectbox('Choose stock symbol', options=['AAPL', 'MSFT', 'GOOG', 'AMZN'], index=1)
with c2:
date_from = st.date_input('Show data from', date(2021, 10, 1))
with c3:
st.markdown(' ')
show_data = st.checkbox('Show data table', False)
st.markdown('---')
st.sidebar.subheader('Settings')
st.sidebar.caption('Adjust charts settings and then press apply')
with st.sidebar.form('settings_form'):
show_nontrading_days = st.checkbox('Show non-trading days', True)
# https://github.com/matplotlib/mplfinance/blob/master/examples/styles.ipynb
chart_styles = [
'default', 'binance', 'blueskies', 'brasil',
'charles', 'checkers', 'classic', 'yahoo',
'mike', 'nightclouds', 'sas', 'starsandstripes'
]
chart_style = st.selectbox('Chart style', options=chart_styles, index=chart_styles.index('starsandstripes'))
chart_types = [
'candle', 'ohlc', 'line', 'renko', 'pnf'
]
chart_type = st.selectbox('Chart type', options=chart_types, index=chart_types.index('candle'))
mav1 = st.number_input('Mav 1', min_value=3, max_value=30, value=3, step=1)
mav2 = st.number_input('Mav 2', min_value=3, max_value=30, value=6, step=1)
mav3 = st.number_input('Mav 3', min_value=3, max_value=30, value=9, step=1)
st.form_submit_button('Apply')
data = get_historical_data(symbol, str(date_from))
fig, ax = mpf.plot(
data,
title=f'{symbol}, {date_from}',
type=chart_type,
show_nontrading=show_nontrading_days,
mav=(int(mav1),int(mav2),int(mav3)),
volume=True,
style=chart_style,
figsize=(15,10),
# Need this setting for Streamlit, see source code (line 778) here:
# https://github.com/matplotlib/mplfinance/blob/master/src/mplfinance/plotting.py
returnfig=True
)
st.pyplot(fig)
if show_data:
st.markdown('---')
st.dataframe(data)
GitHub gist 1
Have fun!
Arvindra | 1 |
streamlit | Using Streamlit | File Upload Limitation? | https://discuss.streamlit.io/t/file-upload-limitation/19283 | I have a Streamlit application running on a windows server. I am accessing it from a remote / local machine. If I try to upload a file, streamlit does not find it, even if I specify my local path (ref statements containing ‘npth’). Only if I save the file on the server and upload the same file from the local machine, will streamlit continue processing as intended.
dtafl = st.file_uploader("Upload template", type = "xlsx", accept_multiple_files = False)
npth = os.path.dirname(__file__) + "\\"
npth = st.text_input("Template File network path (should end with a '\\')", help="For files residing on a different network, please specify entire file path as per the example", value = npth, placeholder=f"Eg. {npth}")
npth = npth.replace("\\", "/")
sbtn = st.button("Import File")
if sbtn:
if dtafl is not None and tproj != "":
try:
tdf = pd.read_excel(npth + dtafl.name, sheet_name = 'S1')
Is there a suitable remedy?
Thanks in advance. | The file is being uploaded into the app, not being saved on the server per se. It exists as a StringIO or BytesIO object, which you can then use to physically create and save a file. See API docs.
app.py
import os
import time
from random import randint
import streamlit as st
from data import csv_to_df, excel_to_df
# Important: This folder must exist!
SAVE_PATH = os.path.join(os.getcwd(), 'uploads')
state = st.session_state
if 'FILE_UPLOADER_KEY' not in state:
state.FILE_UPLOADER_KEY = str(randint(1000,9999))
st.markdown('## \U0001F4C2 Upload data files')
st.write('Upload one or more Excel data files. Duplicate files will be ignored.')
excel_files = st.file_uploader('', type=['xlsx', 'csv'], accept_multiple_files=True, key=state.FILE_UPLOADER_KEY)
save = st.checkbox(f'Save files in {SAVE_PATH}?')
if len(excel_files) > 0 and st.button('\U00002716 Clear all'):
state.FILE_UPLOADER_KEY = str(randint(1000,9999))
st.experimental_rerun()
# This will remove duplicate files
excel_files_dict = {}
for excel_file in excel_files:
excel_files_dict[excel_file.name] = excel_file
message = st.empty()
for _, excel_file in excel_files_dict.items():
message.info(f'Loading {excel_file.name}...')
if excel_file.type in ['application/vnd.ms-excel', 'application/octet-stream']:
df = csv_to_df(excel_file)
if save:
message.info(f'Saving: {os.path.join(SAVE_PATH, excel_file.name)}')
df.to_csv(os.path.join(SAVE_PATH, excel_file.name))
else: # 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
df = excel_to_df(excel_file)
if save:
message.info(f'Saving: {os.path.join(SAVE_PATH, excel_file.name)}')
df.to_excel(os.path.join(SAVE_PATH, excel_file.name))
st.subheader(excel_file.name)
st.dataframe(df)
if save:
message.info('Your files have been saved.')
else:
message.info('Upload complete.')
time.sleep(2)
message.write('')
data.py
import streamlit as st
import pandas as pd
@st.experimental_memo(persist='disk')
def csv_to_df(excel_file):
df = pd.read_csv(excel_file)
return df
@st.experimental_memo(persist='disk')
def excel_to_df(excel_file):
# https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
# New in Pandas version 1.3.0.
# The engine xlrd now only supports old-style .xls files. When engine=None, the following logic will be used to determine the engine:
# If path_or_buffer is an OpenDocument format (.odf, .ods, .odt), then odf will be used.
# Otherwise if path_or_buffer is an xls format, xlrd will be used.
# Otherwise if path_or_buffer is in xlsb format, pyxlsb will be used.
# Otherwise openpyxl will be used.
#
# import openpyxl
# df = pd.read_excel(excel_file, engine=openpyxl)
#
# Therefore... do not need to provide "engine" when using a "path_or_buffer"
df = pd.read_excel(excel_file)
return df
Screenshot
image756×813 36.4 KB
This solution has been adapted from code I wrote here.
Create APIs from data files within seconds, using FastAPI, SQLite and Streamlit Show the Community!
Hi Community!
I’ve released APINESS - an app motivated by the work of jrieke on fastapi-csv.
fastapi-wrapper is a Python package and Streamlit application to create APIs from data files (Excel XLSX and CSV only), using a lightweight & fully customizable wrapper around FastAPI. Endpoints and query parameters are auto-generated based on the column names and data types in the data file. Its contents is written to either a temporary in-memory or persistent SQLite database, so the API can be blazin… | 0 |
streamlit | Using Streamlit | Text_input : how to disable “Press Enter to Apply” | https://discuss.streamlit.io/t/text-input-how-to-disable-press-enter-to-apply/14457 | I am using 12 short text_input in a row.
In this situation, the suggestion “Press Enter to Apply” is scrambled.
I would like to avoid having this appearing on the screen.
Is it possible to disable this?
Thanks,
Michel | +1
same problem here, can one edit/disable/customize that piece of text in the st.text_input components?
image697×81 2 KB | 0 |
streamlit | Using Streamlit | How to label each point on Streamlit map | https://discuss.streamlit.io/t/how-to-label-each-point-on-streamlit-map/7356 | Hello, all.
I was building an app to visualize weather patterns with a geospatial map. After I have coordinates for a point, how can I put labels over each point? I need it to encode the temperature for that particular location and I want it to be visible without hovering over or doing anything extra. Is there such functionality? Or can anyone suggest another option for doing this? | Hi, thanks for your reply. I already found a good alternative for the task. I am using the plotly scatter_mapbox. Though it does not display each point’s label, I can hover over to see them.
Actually, the app I had in mind is ready and I wanted to deploy it. I already shared it in the Show Community section. You can see it on this 28 GitHub too.
I wanted to write a Medium article for TDS explaining my app but I cannot show it because I have not received my reply from Streamlit Sharing.
It would be great if you could extend an invite beforehand, @randyzwitch. Thanks! | 1 |
streamlit | Using Streamlit | How to install streamlit in termux | https://discuss.streamlit.io/t/how-to-install-streamlit-in-termux/19303 | I using python in termux by andorid phone. i try to install streamlit in termux ,but failed.
pip install streamlit
ERROR: Failed building wheel for pyzmq
Failed to build pillow pyarrow pyzmq
ERROR: Could not build wheels for pyarrow, pyzmq, which is required to install pyproject.toml-based projects
how to fix it? | Hi,
I solved this problem by following steps
1 - Install app Andronix from Google Market.
2 - install fedora from Andronix.
3 - run. /start-fedora.sh to run fedora on Termux.
4 - install python 3.6 or 3.9 by dnf
5 - install streamlit by using pip
Enjoy.
IMG_20211121_0648451080×2246 304 KB | 0 |
streamlit | Using Streamlit | How to retrieve dates from user input of a future date | https://discuss.streamlit.io/t/how-to-retrieve-dates-from-user-input-of-a-future-date/19321 | The following code allows me to select dates to visualise and predict stock prices in a defined date range
start = '2010-01-01'
end = '2021-11-20'
st.title('Stock Prediction')
ticker_input = st.sidebar.text_input('Enter Stock Ticker', 'AAPL')
df = data.DataReader(ticker_input, 'yahoo', start, end)
st.subheader(ticker_input)
The code works as intended when I change the end variable to a future date within the IDE by changing end to '2022-01-01' and then run it in streamlit. My prediction chart would also change to reflect the end date. How can I change the end variable so the user can select dates in the future themselves? The tutorial I followed doesn’t show this and I’ve tried to look at examples where datetime lets users select dates in the future and they all seem to just go up to present day.
start = st.date_input('Start', value = pd.to_datetime('2010-01-01'))
end = st.date_input('End', value = pd.to_datetime('2024-01-01'))
I tried using pd.to_datetime and st.date_input like this to see if the user can change it from the dropdown calendar but it doesn’t work. | You could try the following:
import streamlit as st
from datetime import datetime as dt
start = dt.strptime(‘2010-01-01’, ‘%Y-%m-%d’) # set default value
end = dt.strptime(‘2021-11-20’, ‘%Y-%m-%d’) # set default value
st.title(‘Stock Prediction’)
ticker_input = st.sidebar.text_input(‘Enter Stock Ticker’, ‘AAPL’)
start = st.date_input(“Enter Start Date”, value = start)
end = st.date_input(“Enter Start Date”, value = end)
add code to check if end date is >= start date + any other processing code. | 0 |
streamlit | Using Streamlit | Render Custom HTML from the Directory | https://discuss.streamlit.io/t/render-custom-html-from-the-directory/19292 | I am trying to use a hyperlink in my streamlit webapp. On clicking the same, it should load the html file (from the local directory) in a new tab. I have attached a code snippet depicting the same.
I am not well conversant with HTML, I am trying to figure out a simple way.
Kindly suggest…
Streamlit Code
import streamlit as st
legend= """<html>
<body>
<h2>Terms & Condition</h2>
<p><a href=TnC.html>My Custom Webpage</a></p>
</h1>
</body>
</html>"""
st.markdown(legend, unsafe_allow_html=True)
TnC HTML Code
<html>
<head></head>
<body>
<p>Terms & Conditions</p>
</body>
</html>
Output | TnC.html needs to be served from a webserver to be rendered in a bowser. Double clicking an html file on your filesystem and seeing it open is just convenient voodoo of the operating system shell that isn’t a web native concept.
You can fake opening static HTML files using a blank/empty component, by taking advantage of its frontend folder. See the trick I used here: This is how to use Sweetviz with Streamlit 3
HTH,
Arvindra | 0 |
streamlit | Using Streamlit | Use Shapash library in Streamlit | https://discuss.streamlit.io/t/use-shapash-library-in-streamlit/19289 | Hello, i want to use Shapash in Streamlit to display Feature Importance, contribution, compare plot. Shapash is a library built with the base of shap but it’s better . The understanding of models are more intuitive and bettrer than shap.
Can you help me please to inser shapash plot in Streamlit ?
Thank you in advance | Looks like Shapash is a web app which compiles your model and runs Shap, etc. then displays the results. The web app would need to be run separately from Streamlit and the front end iframed into Streamlit. (Deduced from the docs of how it runs in Jupyter.) | 1 |
streamlit | Using Streamlit | Clear cache gone? | https://discuss.streamlit.io/t/clear-cache-gone/19301 | Just today, I noticed I can’t clear the cache with “c” or with the hamburger anymore. I don’t see it in the changelog - what happened? | Ah I see that it’s a developer option now - I need it to be available to users too, is there a flag I can set somehow? | 0 |
streamlit | Using Streamlit | STreamlit how to implement a stateful ML app that doesnt rerun after every widget interaction | https://discuss.streamlit.io/t/streamlit-how-to-implement-a-stateful-ml-app-that-doesnt-rerun-after-every-widget-interaction/19247 | I would like to implement a stateful ML app that doesnt rerun for every intreaction with a widget.
Flow of app: Step 1: Enter filepath and upload data onto dataframe on click of a button. Step 2: Show sample data Step 3: Show descriptive stats Step 4: Plot histogram for selected feature dynamically on selection from selectbox.
When I select a new variable apart from the default selection for step 4 plot, the entire script reruns. How do I save state information such that when I am at step 4, everything above this doesnt get rerun i.e step1,2,3 shouldnt be called again. Only what I am interacting with in step 4. Kindly help me out.
import numpy as np
import pandas as pd
import sklearn as sk
import matplotlib.pyplot as plt
import streamlit as st
import pyspark
from pyspark import *
from PIL import Image
from io import StringIO
import st_state_patch
def load_data(ss,uploaded_file):
df = ss.read.format('csv').option('header','true').load(uploaded_file)
return df
def sample_data(df,widget):
df_sample = pd.DataFrame(df.head(5))
df_sample.columns = df.columns
widget.dataframe(df_sample)
def descriptive_stats(df,widget):
df_desc = df.summary().toPandas()
widget.dataframe(df_desc)
def hist_plot(df,col,widget):
df_plot = df.select(col).toPandas().iloc[:,0]
fig, ax = plt.subplots()
ax.hist(df_plot,density = False, bins = 50)
widget.pyplot(fig)
def main():
sparkapp = pyspark.sql.SparkSession.builder.master('local[4]').appName('No-code Spark Pipeline').getOrCreate()
df = pd.DataFrame()
st.title("No-Code ML Spark Pipeline")
st.subheader('1. Upload file (csv)')
uploaded_file = st.text_input("Provide local file path")
upload_button1 = st.button('Upload')
st.caption('Sample data')
upload_cont1 = st.empty()
white_background = Image.open('C:/Users/hp/Desktop/white_600_240.png')
upload_cont1.image(white_background)
# Call load data
if upload_button1:
df = load_data(sparkapp,uploaded_file)
sample_data(df, upload_cont1)
# Call sample data
st.subheader('2. Exploratory Data Analytics')
st.caption('Descriptive statistics')
eda_cont1 = st.empty()
eda_cont1.image(white_background,use_column_width=True)
# Call descriptive stats
if upload_button1:
descriptive_stats(df, eda_cont1)
st.caption('Histogram / Frequency plot')
eda_sel_feat = st.selectbox('Select feature to be displayed', options = df.columns)
eda_cont2 = st.empty()
eda_cont2.image(white_background,use_column_width=True)
# Call hist plot
if upload_button1:
hist_plot(df,eda_sel_feat,eda_cont2)
if __name__ == '__main__':
main() | Hi @bhargavbn, welcome to the Streamlit community!
bhargavbn:
How do I save state information such that when I am step 4, everything above this doesnt get rerun.
This re-running is fundamental to how Streamlit is designed. By re-running from top-down each time, you never get into an uncertain state of the app.
However, for cases like you describe, where the above steps can take considerable time, we have a handful of caching functions. The following documentation describes how to use them:
docs.streamlit.io
Experimental cache primitives - Streamlit Docs 4
By using cache or memo or singleton, you effectively skip the re-running of steps by saving the results of those steps in memory. This makes it feel as if the steps aren’t re-run.
Best,
Randy | 0 |
streamlit | Using Streamlit | Read particular cells values from an Excel file | https://discuss.streamlit.io/t/read-particular-cells-values-from-an-excel-file/18590 | Hello , I tried to import openpyxl in order to load an excel file and then read a couple of cell values in but that appears not to work in Streamlit. I am using file = st.file_uploader(“Choose an excel file”, type=“xlsx”) What would be the best way to achieve reading in a couple of stand alone cells that act as variables in the code?
I did find some work arounds with pandas but thats not very efficient.
Thanks
Michiel | Hi Randy,
I dont know what went wrong last time, but its working fine indeed now
import openpyxl
import streamlit as st
wb = openpyxl.load_workbook(‘workbook.xlsx’)
sheet = wb[‘data’]
C1 = sheet[‘C1’] # read direct value in cell C1
st.write (C1.value) | 1 |
streamlit | Using Streamlit | Referencing Streamlit | https://discuss.streamlit.io/t/referencing-streamlit/11287 | Hi Streamlit staff and thanks for the amazing work that you do!
I am using Streamlit to build 2 apps for my Master’s thesis and I would like to reference it.
Is there any preferred way?
Best! | Hi @picchio18, glad to hear you’re making such good use of Streamlit for your academics!
We historically haven’t focused on academic things such as citations, since we’re a for-profit company in addition to the open-source library. So we don’t have a registered DOI number or anything to cite.
Best,
Randy | 0 |
streamlit | Using Streamlit | How to make smaller gaps between horizontal line and text | https://discuss.streamlit.io/t/how-to-make-smaller-gaps-between-horizontal-line-and-text/18715 | I was trying to put text under and above horizontal line, but it makes too big gaps between elements. I was trying to do it in this way
st.markdown("""Something
---
Something
""")
Also, I did set up margins and tried components.html() but without success. I can create h. line but with big gaps like this
line972×188 1.32 KB
I was wondering, is there a way how to make it more “squeezed”?, also to set up linewidth would be great option. | You could probably try using emoji:
st.write("" * 34) # horizontal separator line.
Just change 34 as needed.
Cheers | 0 |
streamlit | Using Streamlit | Update options of multiselect widget | https://discuss.streamlit.io/t/update-options-of-multiselect-widget/18493 | I use multiselect widgets to select python functions that I use later in my program. When I select a function, I like to add another one to the options of the multislider. So that I can select the new function in the next “rerun” of the application and chain them together.
Here is a simplified example that does not work like expected. Is there a way to update the multiselect options?
import streamlit as st
if "options" not in st.session_state:
st.session_state.options = ["a1", "a2", "a3"]
def update_options():
st.session_state.options.append("a4")
st.multiselect("", st.session_state.options, key="selected", on_change=update_options)
st.write(st.session_state) | Is this what you are looking for?
import streamlit as st
if "options" not in st.session_state:
st.session_state.options = ["a1", "a2", "a3"]
ti = st.text_input("Enter Function to be added to multiselect")
if ti != "":
if ti not in st.session_state.options: # prevent duplicates
st.session_state.options.append(ti)
st.multiselect("", st.session_state.options, key="selected")
st.write(st.session_state.options) | 0 |
streamlit | Using Streamlit | How to create multiple selectbox with different key? | https://discuss.streamlit.io/t/how-to-create-multiple-selectbox-with-different-key/18870 | how to create multiple select box inside a for loop using different key .
When i tried to create it crash and display the below error:
But when i try to use st.text_input it works and display it.
raise ValueError("{} is not in iterable".format(str(x)))
code:
for i , old_val in enumerate(range(5))):
old_val = st.selectbox(" ",old_values,key=i) | You could modify the following code for your use:
import streamlit as st
old_values = [“A”, “B”, “C”, “D”, “E”]
for i in range(len(old_values)):
old_val = st.selectbox(" “,old_values,key=f"MyKey{i}”) | 0 |
streamlit | Using Streamlit | Interface of streamlit | https://discuss.streamlit.io/t/interface-of-streamlit/18979 | I have a dataset having 50 dealers. Now I used check box to select them. But in my Streamlit interface all 50 names are shown and it looked very clumsy. Can anyone guide me how to modify that interface so that it is very eye catching? | can you share your code here? | 0 |
streamlit | Using Streamlit | Awkward dataframe style in 0.89.0 | https://discuss.streamlit.io/t/awkward-dataframe-style-in-0-89-0/19063 | In 0.86.0 st.dataframe() gave me something nice and neat:
old st.dataframe()719×205 3.76 KB
Now when I have upgraded to 0.89.0 st.dataframe() gives me something like this:
st.dataframe()728×203 4.3 KB
Probably I might have used some configs that have no support anymore? Or is this expected dataframe representation? | kind of solution for me:
div[class="ReactVirtualized__Grid table-bottom-left"],
div[class="ReactVirtualized__Grid table-top-right"],
div[class="ReactVirtualized__Grid"] {
background-color: #1f2229;
}
.stDataFrame div {
border-color: #222222;
font-family: "Source Sans Pro", sans-serif;
}
.stDataFrame {
border: 5px solid #1f2229;
} | 0 |
streamlit | Using Streamlit | Issue with asyncio run in streamlit | https://discuss.streamlit.io/t/issue-with-asyncio-run-in-streamlit/7745 | 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 streamlit as st
from datetime import datetime
st.set_page_config(layout="wide")
st.markdown(
"""
<style>
.time {
font-size: 130px !important;
font-weight: 700 !important;
color: #ec5953 !important;
}
</style>
""",
unsafe_allow_html=True
)
async def watch(test):
while True:
test.markdown(
f"""
<p class="time">
{str(datetime.now())}
</p>
""", unsafe_allow_html=True)
await asyncio.sleep(1)
test = st.empty()
if st.button("Click me."):
st.image("https://cdn11.bigcommerce.com/s-7va6f0fjxr/images/stencil/1280x1280/products/40655/56894/Jdm-Decals-Like-A-Boss-Meme-Jdm-Decal-Sticker-Vinyl-Decal-Sticker__31547.1506197439.jpg?c=2", width=200)
asyncio.run(watch(test))
The output looks like this,
snippet1909×779 233 KB
Thanks in advance ! | …so I guess the None is actually the result of await asyncio.sleep(0) which Streamlit naturally writes in Streamlit like when you just write "Hello World" in a Python script.
import asyncio
import streamlit as st
async def periodic():
while True:
st.write("Hello world")
r = await asyncio.sleep(1)
st.write(f"asyncio sleep ? {r}")
asyncio.run(periodic())
So back to your code
import asyncio
import streamlit as st
from datetime import datetime
st.set_page_config(layout="wide")
st.markdown(
"""
<style>
.time {
font-size: 130px !important;
font-weight: 700 !important;
color: #ec5953 !important;
}
</style>
""",
unsafe_allow_html=True
)
async def watch(test):
while True:
test.markdown(
f"""
<p class="time">
{str(datetime.now())}
</p>
""", unsafe_allow_html=True)
r = await asyncio.sleep(1)
test = st.empty()
if st.button("Click me."):
st.image("https://cdn11.bigcommerce.com/s-7va6f0fjxr/images/stencil/1280x1280/products/40655/56894/Jdm-Decals-Like-A-Boss-Meme-Jdm-Decal-Sticker-Vinyl-Decal-Sticker__31547.1506197439.jpg?c=2", width=200)
asyncio.run(watch(test))
test1103×528 88.2 KB
And now we have almost perfect 1 second timing too! | 1 |
streamlit | Using Streamlit | Change font size or width of selectbox | https://discuss.streamlit.io/t/change-font-size-or-width-of-selectbox/8095 | I wonder if there is any ways to change the font size of selectbox options?
All of my options are long string and can not display whole when dropdown the selectbox.
Or increase the width of selectbox might also works. | Hey @ChiHangChen,
Welcome to the Streamlit community!!!
You can’t currently change the font size on the selectbox options. The width of the selectbox is the full width of the page, or column its in. Which means that you can make it wider by putting the selectbox in a wider column.
If you need to make the page layout wider to achieve this you can use the st.set_page_config(layout="wide") as the first Streamlit call to use all the available space in your app!
Happy Streamlit-ing!
Marisa | 0 |
streamlit | Using Streamlit | Interact with Widgets and Forms | https://discuss.streamlit.io/t/interact-with-widgets-and-forms/19252 | Hi all !
I am currently writing a Streamlit dashboard, where I first want to fetch data from different sources and afterwards want to interactively analyze it. For the data downloading part I use st.from so that my dashboard does not get refreshed on every change. However, combining the form with other interactive widgets seem to reset the dashboard every time. Is there a way around this? Here is some example snippet of my current approach:
import streamlit as st
DATA_SOURCES = {
'Postgres': [1, 2, 3, 4, 5],
'MySQL': [4, 2, 4, 2],
'Snowflake': [5, 4, 3, 2, 1]
}
def download():
with st.sidebar.form('download_form'):
source = st.selectbox('Select Data Source', ['Postgres', 'MySQL', 'Snowflake'])
if st.form_submit_button('Download Data'):
return DATA_SOURCES[source]
def multiplicator(vals):
multiplicator = st.radio('Select sampling', list(range(1, 5)))
return [val*multiplicator for val in vals]
if __name__=='__main__':
st.sidebar.header('Config Zone')
data = download()
st.header('Analyzing Zone')
if data:
new_data = multiplicator(data)
st.write(f'Initial data: {data}')
st.write(f'Multiplied data: {new_data}')
This is the current behaviour: | Hi again !
After a bit more research, code refactoring and and playing around with st.experimental_memo and st.session_state, I found a working solution for me. Here is the code:
import streamlit as st
DATA_SOURCES = {
'Postgres': [1, 2, 3, 4, 5],
'MySQL': [4, 2, 4, 2],
'Snowflake': [5, 4, 3, 2, 1]
}
def select_source():
with st.sidebar.form('download_form'):
source = st.selectbox('Select Data Source', ['Postgres', 'MySQL', 'Snowflake'])
if st.form_submit_button('Download Data'):
return source
@st.experimental_memo
def download(source):
return DATA_SOURCES[source]
def multiplicator(vals):
multiplicator = st.radio('Select sampling', list(range(1, 5)))
return [val*multiplicator for val in vals]
if __name__=='__main__':
st.sidebar.header('Config Zone')
source = select_source()
if not source and 'source' in st.session_state:
source = st.session_state['source']
if source:
st.session_state['source'] = source
data = download(source)
st.header('Analyzing Zone')
new_data = multiplicator(data)
st.write(f'Initial data: {data}')
st.write(f'Multiplied data: {new_data}') | 0 |
streamlit | Using Streamlit | StateSession | https://discuss.streamlit.io/t/statesession/19227 | Hi guys ,
I have seen this code in a post
import streamlit as st
import pandas as pd
import numpy as np
import SessionState
# https://gist.githubusercontent.com/tvst/036da038ab3e999a64497f42de966a92/raw/f0db274dd4d295ee173b4d52939be5ad55ae058d/SessionState.py
# Create an empty dataframe
data = pd.DataFrame(columns=["Random"])
st.text("Original dataframe")
# with every interaction, the script runs from top to bottom
# resulting in the empty dataframe
st.dataframe(data)
# persist state of dataframe
session_state = SessionState.get(df=data)
# random value to append; could be a num_input widget if you want
random_value = np.random.randn()
if st.button("Append random value"):
# update dataframe state
session_state.df = session_state.df.append({'Random': random_value}, ignore_index=True)
st.text("Updated dataframe")
st.dataframe(session_state.df)
# still empty as state is not persisted
st.text("Original dataframe")
st.dataframe(data)
I would like to know if I have had multiple columns apart “Random” , how would I have dealed with this line
session_state.df = session_state.df.append({'Random': random_value}, ignore_index=True)
taking into account all columns : example “col1” and “col2”
Thanks for your help | Problems, questions, code snippets are usually discussed in the streamlit category “Using streamlit”.
“Show the community” is meant to show case finished projects you did. | 0 |
streamlit | Using Streamlit | Parsing dictionary to Streamlit component | https://discuss.streamlit.io/t/parsing-dictionary-to-streamlit-component/19213 | I am trying to build my own custom component using React. I am not very familiar with React framework so I might need a little help here. I have also tried my best to search online but to no avail.
So I have a dictionary from my python file:
dic = {'key1':['value1_1','value1_2'],
'key2':['value2_1','value2_2'],}
and I want to parse this to the frontend and render two forms with radio button labeled with the list (eg. value1_1, value1_2 for first form)
I am using material ui and here is the code I run into problem:
{Object.entries(myObject).map(([key,values])=>(
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
defaultValue="female"
name={key}
>
{Object.entries(values).map(val => {
return <FormControlLabel value={val.toString()} control={<Radio />} label={val.toString()} />
})}
</RadioGroup>
</FormControl>
))}
Here is the returned error:
Overload 1 of 2, ‘(o: { [s: string]: unknown; } | ArrayLike): [string, unknown]’, gave the following error.
Argument of type ‘unknown’ is not assignable to parameter of type ‘{ [s: string]: unknown; } | ArrayLike’.
Type ‘unknown’ is not assignable to type ‘ArrayLike’.
Overload 2 of 2, ‘(o: {}): [string, any]’, gave the following error.
Argument of type ‘unknown’ is not assignable to parameter of type ‘{}’. TS2769
Hope to get some help here! Thanks so much in advance. | Hi,
Thanks so much for your reply. I think I have found the solution.
{Object.keys(greet).map((key)=>(
<FormControl component="fieldset">
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
defaultValue="female"
name={key}
>
{greet[key] && greet[key].map((i:string)=>
<FormControlLabel value={i} control={<Radio />} label={i}></FormControlLabel>
)}
</RadioGroup>
</FormControl>
))} | 1 |
streamlit | Using Streamlit | Adding a new row to a dataframe with each button click (persistent dataframe) | https://discuss.streamlit.io/t/adding-a-new-row-to-a-dataframe-with-each-button-click-persistent-dataframe/12799 | Is there anyway to append a new value to a single column dataframe each time a button is clicked? I have tried to implement it using st.cache but the cached values are those every time the script reruns and not every time the button is pressed. The dataframe is empty initially. | Hi @Yashvin_Jagarlamudi, welcome to the Streamlit community!!
Your question sort of sounds like maintaining session state. Maybe take a look at this post 16 or our session-state 20 tag to see if it helps with this problem.
Here’s a simple working example that shows how to grow a dataframe a single row at a time using SessionState 38 and clicking a button:
import streamlit as st
import pandas as pd
import numpy as np
import SessionState
# https://gist.githubusercontent.com/tvst/036da038ab3e999a64497f42de966a92/raw/f0db274dd4d295ee173b4d52939be5ad55ae058d/SessionState.py
# Create an empty dataframe
data = pd.DataFrame(columns=["Random"])
st.text("Original dataframe")
# with every interaction, the script runs from top to bottom
# resulting in the empty dataframe
st.dataframe(data)
# persist state of dataframe
session_state = SessionState.get(df=data)
# random value to append; could be a num_input widget if you want
random_value = np.random.randn()
if st.button("Append random value"):
# update dataframe state
session_state.df = session_state.df.append({'Random': random_value}, ignore_index=True)
st.text("Updated dataframe")
st.dataframe(session_state.df)
# still empty as state is not persisted
st.text("Original dataframe")
st.dataframe(data)
Happy Streamlit-ing!
Snehan | 1 |
streamlit | Using Streamlit | About number_input for very small number | https://discuss.streamlit.io/t/about-number-input-for-very-small-number/19056 | Hi team, I need to input some very small number like: 0.0000045, but when I’m trying to use st.number_input, it seems it doesn’t support this, it could only show number like 0.00.
temp = st.number_input(label=‘test’,min_value=0.000000,step=0.000001,max_value=0.0005,value=0.0000045)
Is there any way to resolve this? | 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",
)
image939×238 2.01 KB
docs.streamlit.io
st.number_input - Streamlit Docs 1
Best,
Randy | 1 |
streamlit | Using Streamlit | Select an item from multiselect on the sidebar | https://discuss.streamlit.io/t/select-an-item-from-multiselect-on-the-sidebar/1276 | Hello Guys, please help me on this. I need streamlit to perform an operation when i select an item from multiselect on the sidebar without adding a feature like checkbox or button.
Let’s say the item am selecting is country and i have list of countries to select from, so once i click on that particular country say Algeria, then i get its information that are within my csv file. | Hi Wilson,
I’ve done something similar at work and since I only need a subset of the whole dataframe at any given time I filter my data based on the value of the multiselect menu.
import streamlit as st
import pandas as pd
data = pd.read_csv("example.csv")
# Create a list of possible values and multiselect menu with them in it.
COUNTRIES = data['country'].unique()
COUNTRIES_SELECTED = st.multiselect('Select countries', COUNTRIES)
# Mask to filter dataframe
mask_countries = data['country'].isin(COUNTRIES_SELECTED)
data = data[mask_countries]
Hopefully this works for you! | 1 |
streamlit | Using Streamlit | URL redirect inside a button | https://discuss.streamlit.io/t/url-redirect-inside-a-button/19112 | Hey! How can I open the url in the same tab of the browser? webbrowser didn’t help, it always opens a new tab and google search confirmed it’s not possible I used to have a hyperlink which opened the url in the same window
st.write(f'''<h1>
Please login via <a target="_self"
href="{authorization_url}">Google</a></h1>''',
unsafe_allow_html=True)
But I want a button that triggers URL redirect
login = st.button('Log in')
if login:
webbrowser.open(authorization_url)
I guess I could extract that redirect function from st.write above but I have no experience in html and this code isn’t mine haha
I need this to run google auth inside the app. | You can create a button manually. Unfortunately I couldn’t find a way to style the button persistently across Streamlit versions (class hashes change each version).
import streamlit as st
st.write(f'''
<a target="_self" href="https://eox.at">
<button>
Please login via Google
</button>
</a>
''',
unsafe_allow_html=True
) | 0 |
streamlit | Using Streamlit | How to move fullscreen-enter icon | https://discuss.streamlit.io/t/how-to-move-fullscreen-enter-icon/2303 | Dear team, users,
How could I decide the place where the ‘fullscreen-enter’ icon appears in the charts? I am having trouble with this when plotting with plotly, as follows:
Alternatively, moving the plotly bar options would be valid also.
Thanks in advance!
Germán | Hi @GermanCM and welcome to the forum ,
Currently that’s not supported, but we are working on Customizable Layout for Streamlit 51.
In the meantime you can hack your way around a solution by using st.markdown. Try styling .overlayBtn of the plotly .element-container.
Let me know if you need any help.
And thanks for using Streamlit! | 0 |
streamlit | Using Streamlit | How to create streamlit app with pagination | https://discuss.streamlit.io/t/how-to-create-streamlit-app-with-pagination/19172 | I am trying to create a streamlit app that uses pagination to display data. I have written the example code below. My issue is that clicking either button does not change the page. It only changes once I manually refresh the app ( by pressing ‘R’). Am I doing something wrong here or is this a bug?
import streamlit as st
if "page" not in st.session_state:
st.session_state.page = 1
st.title("Test")
if st.session_state.page == 1:
st.write("Page 1")
elif st.session_state.page == 2:
st.write("Page 2")
else:
st.write("No page")
if st.button("Next"):
st.session_state.page = 2
if st.button("Previous"):
st.session_state.page = 1 | Its because you check for the session state before the button, this should work
import streamlit as st
if "page" not in st.session_state:
st.session_state["page"] = 1
st.title("Test")
empty = st.empty()
if st.button("Next"):
st.session_state["page"] = 2
if st.button("Previous"):
st.session_state["page"] = 1
if st.session_state["page"] == 1:
empty.write("Page 1")
elif st.session_state["page"] == 2:
empty.write("Page 2")
else:
empty.write("No page")
Hope it helps! | 0 |
streamlit | Using Streamlit | How to update streamlit app? | https://discuss.streamlit.io/t/how-to-update-streamlit-app/19091 | Hello,
I am beginner, willing to learn streamlit. I have a question, after converting jupyter notebook (.ipynb) file to python source file (.py), we run the streamlit app from terminal. After an attempt to run the file, Lets say i Have to update the jupyter notebook file with source code. For this i have to close the terminal again, then again open the jupyter notebook to modify the code, then again export it to (.py) file, then again reopen the terminal to run the streamlit app. This something messy for me which i am doing. My question is, is there anyway to modify the source code and update the streamlit app in a singe attempt, with closing and reopening the terminal and jupyter notebook. | Run the app by pasting it into vsc instead of converting the ipynb file from Jupiter’s laptop. Then, if you modify the code in vsc, it will be automatically modified. | 0 |
streamlit | Using Streamlit | TypeError:”Module” Object is not callable | https://discuss.streamlit.io/t/typeerror-module-object-is-not-callable/8658 | How to fix this issue?Screenshot 2021-01-09 at 9.27.04 PM1366×768 59.8 KB | Per the yfinance docs 3, this is the proper syntax:
import yfinance as yf
msft = yf.Ticker("MSFT")
Your cell has yf.ticker, which is not correct capitalization.
Best,
Randy | 1 |
streamlit | Using Streamlit | Horizontal Separator Line? | https://discuss.streamlit.io/t/horizontal-separator-line/11788 | Is there a command to draw a horizotnal black line to separate parts of the app?
Or, is there a way to automatically put horizontal black lines between container objects. | You can do this with html components.
Something like
components.html("""<hr style="height:10px;border:none;color:#333;background-color:#333;" /> """) | 0 |
streamlit | Using Streamlit | A callback with Custom Components? | https://discuss.streamlit.io/t/a-callback-with-custom-components/18388 | Are there any way to implement the on_change callback with Custom Components? | I understood it is currently impossible then I created a feature request:
github.com/streamlit/streamlit
A callback on a custom component 6
opened
Oct 27, 2021
whitphx
enhancement
### Problem
I am a developer of a custom component, [streamlit-webrtc](https:…//github.com/whitphx/streamlit-webrtc), which manages its state in Python code, and there is [a request](https://github.com/whitphx/streamlit-webrtc/issues/470) to make it possible to detect state changes through the `on_change` callback.
However, currently a callback on a custom component is not supported.
### Solution
* To introduce a mechanism to allow component developers to register and trigger a callback from a custom component.
* It must not be an "automatic" trigger reacting to the changes of the frontend component state or session_state, such as a callback automatically invoked when the return value of `_component_func` or `session_state[key]` changes.
* As stated above, my component manages the state on Python side and the component value differs from the returned value from the frontend component. Additionally, a value stored in the session state of its key is a mutable object so that it cannot be used to detect changes. So, I want a way to manually invoke the callback.
* Ideally, it might be the best if we have a way to set arbitrary values to `WidgetMetadata.callback`, `WidgetMetadata.callback_args`, `WidgetMetadata.callback_kwargs`, and to forcefully call `call_callback(wid)` for a specific component.
### Additional context
* Related feature request to my component: https://github.com/whitphx/streamlit-webrtc/issues/470 | 0 |
streamlit | Using Streamlit | How to link a button to a webpage? | https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661 | I want to create a button and upon clicking, it should open desired webpage. Not sure how I can about it | May be use button to show up a hyperlink using markdown ? | 0 |
streamlit | Using Streamlit | Streamlit and visualization of network(x) structures | https://discuss.streamlit.io/t/streamlit-and-visualization-of-network-x-structures/19023 | Hi,
Q 1)
I am entirely new to actual use of Streamlit. The functionality looks very promising to me.
Right now I am in the process of creating mockup in python. Yet looking into the various chart options ( Chart elements - Streamlit Docs 1), and following Streamlit, I do not seem to spot a visualisation rendering a network(x) infrastructure.
Is that because:
I am lacking imagination? …use e.g. plotly to display?
There is no option available?
Q 2)
I am a bit in doubt when using Streamlit. I did create my app.py file using the command prompt and things do seem to work, somehow. Still, trying to visualize (and maybe this points back to Q 1, above) I am not able to make the structures appear, e.g. using the below code (‘stolen’ from a tutorial elsewhere on the internet). Basically, this code ONLY provides plotly bars, representing the input provides by user, i.e. NO network structure comes from below code. It is merely intended for me to see, how I can make things happen with Streamlit (…and network(x)), In conclusion: Executing my app.py works fine, presenting charts doesn’t.
def nodes_and_edges():
a = int(input("Enter counter value 1: "))
b = int(input("Enter counter value 2: "))
c = int(input("Enter counter value 3: "))
test_a, test_b, test_c = , ,
# test_b =
# test_c =
i, j, k = 0, 0, 0
# j=0
# k=0
while i < a:
pl = int(input(“Enter item value 1:”))
test_a.append(pl)
i += 1
# print(list(test_a))
while j < b:
p2 = int(input("Enter item value 2: "))
test_b.append(p2)
j += 1
# print(list(test_b))
while k < c:
try:
p3 = int(input("Enter item value 3: "))
test_c.append(p3)
k += 1
except ValueError:
print(“Please input int only…”)
one = nodes_and_edges()
print("\none")
print(one)
user_input = tuple(one.itertuples(index=False, name=None))
interactions = user_input
G=nx.Graph(name=‘xxx Interaction Test Graph’)
interactions = np.array(interactions)
for i in range(len(interactions)):
interaction = interactions[i]
a = interaction[0] # source node
b = interaction[1] # destination node
w = float(interaction[2]) # score as weighted edge where high scores = low weight
G.add_weighted_edges_from([(a,b,w)]) # add weighted edge to graph
x1 = G.nodes(interactions[0])
x2 = G.nodes(interactions[1])
x3 = G.nodes(interactions[2])
Group data together
hist_data = [x1, x2, x3]
group_labels = [‘Value 1’, ‘value 2’, ‘Value 3’]
Create distplot with custom bin_size
fig = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])
Plot!
st.plotly_chart(fig, use_container_width=True)
Looking very much forward to learning your reply.
BR
Jens Steenfos, Copenhagen, Denmark
The Newbie | Hi @projectfreak, welcome to the Streamlit community!
projectfreak:
, I do not seem to spot a visualisation rendering a network(x) infrastructure.
It’s not currently in the documentation, but please see this article how to use Networkx and Streamlit:
Medium – 10 Jan 21
Making network graphs interactive with Python and Pyvis. 67
The easy way to superb graphs.
Reading time: 5 min read
Best,
Randy | 0 |
streamlit | Using Streamlit | Implement user login and multi-page view using Pyrebase | https://discuss.streamlit.io/t/implement-user-login-and-multi-page-view-using-pyrebase/18888 | Hello everyone
Am getting stumped on trying to implement a multi-user login solution using Pyrebase.
I have a working copy of the code for a single-user password-protected login, unfortunately am unable to implement a multi-user password-protected login using Pyrebase.
I organized my code as follows:
main.py: A list of Streamlit apps/pages in the sidebar for users to navigate
import streams
import streamlit as st
def main():
PAGES = {
"Stream One": streams.one,
"Stream Two": streams.two,
"Stream Three": streams.three
}
st.sidebar.title("My Streamlit App")
selection = st.sidebar.radio("Go to", list(PAGES.keys()))
PAGES[selection].write()
streams.one,two,three are .py files that contain a .write() method that are stand-alone Streamlit scripts.
multi_user_auth.py: Authenticates the user before allowing view access to the pages in main.py
import streams
import pyrebase
import streamlit as st
from streams.main import main
def authenticate():
# Configuration Key
firebaseConfig = {
...
};
# Firebase Authentication
firebase = pyrebase.initialize_app(firebaseConfig)
auth = firebase.auth()
# Database
db = firebase.database()
storage = firebase.storage()
# Authentication
choice_block = st.empty()
choice = choice_block.radio('Login / Signup', ['Login', 'Sign up'])
# E-mail input
email_block = st.empty()
email = email_block.text_input('Please enter your email address')
# Password input
password_block = st.empty()
password = password_block.text_input('Please enter your password',type = 'password')
# Sign up block
if choice == 'Sign up':
username_block = st.empty()
username = username_block.text_input('Please input your app user name', value='Default')
sign_up_block = st.empty()
sign_up = sign_up_block.button('Sign Up')
if sign_up:
try:
user = auth.create_user_with_email_and_password(email, password)
st.success('Your account was created successfully!')
# Sign in
user = auth.sign_in_with_email_and_password(email, password)
db.child(user['localId']).child("Username").set(username)
db.child(user['localId']).child("ID").set(user['localId'])
st.info(f"Welcome {username}, you can now login to the system.")
sign_up_block.empty()
except:
st.error('Account already exists!')
# Login block
elif choice == 'Login':
# Login button
login_block = st.empty()
login = login_block.button('Login')
if login:
user = auth.sign_in_with_email_and_password(email,password)
while user:
username = db.child(user['localId']).child("Username").get().val()
st.sidebar.title(f"Welcome {username}!")
# Delete all placeholders
choice_block.empty()
email_block.empty()
password_block.empty()
login_block.empty()
# Display all pages to the user for navigation
main()
if __name__ == "__main__":
authenticate()
After the user signs up and logs in, all pages defined in main.py display successfully in the sidebar.
However, if the user clicks on any of the other pages in the sidebar, instead of calling the write() method on that particular page, Streamlit re-directs to the login page again, forcing the user to re-input their login details.
Is there any way to preserve / persist session state such that the user can navigate through the multiple pages in the sidebar once logged in?
I managed to get this behavior working using st.session_state and a single password input (script below), but this does not cater to the desired outcome of multi-user password login.
single_password_auth.py: Controls access to pages using a single password, but cannot cater to multi-user login
import streamlit as st
from streams.main import main
def authenticate():
# Initialize an empty session state variable
if 'password' not in st.session_state:
st.session_state['password'] = ''
# Check if password matches input
if st.session_state.password != 'SuperSecretPassword!':
login_block = st.empty()
password = login_block.text_input('Please enter the password:', value='', type='password')
st.session_state.password = password
if st.session_state.password == 'SuperSecretPassword!':
# Remove title after user has logged in
login_block.empty()
title.empty()
main()
elif password:
st.error("Please enter a valid password")
else:
title.empty()
main()
if __name__ == "__main__":
authenticate(main) | In case anyone is looking for a multi-page app with multi-user authentication, can try out hydralit 23
If you are not using hydralit, to keep the user logged in, use checbox instead of button for the login component. | 0 |
streamlit | Using Streamlit | Embedding BI tool in Streamlit | https://discuss.streamlit.io/t/embedding-bi-tool-in-streamlit/19030 | Hello,
I have been following Streamlit and want to know if anyone has tried to embed a report/dashboard from a BI tool like Looker, Metabase, Power BI, etc in Streamlit.
We want to make our reports available to our customers without having to design & create a whole new app just to display our reports from Looker. I feel that Streamlit can be a great solution (use case) for this.
What do you all think?
-Tim | Hi @Tim_Suh
See this: PowerBI dashboards and streamlit - #3 by Salma_Brahem 21
HTH,
Arvindra | 0 |
streamlit | Using Streamlit | TypeError: Can’t convert object of type ‘UploadedFile’ to ‘str’ for ‘filename’ | https://discuss.streamlit.io/t/typeerror-cant-convert-object-of-type-uploadedfile-to-str-for-filename/19154 | Hello Streamlit community,
So I’m applying the JPEG standard for image compression, and I want to take an input image from user and convert it to YCrCb image.
The problem is cv2.imread() doesn’t take the input image variable as argument, giving the following error: TypeError: Can’t convert object of type ‘UploadedFile’ to ‘str’ for 'filename’
Here’s my code:
import streamlit as st
import cv2
image = st.file_uploader("Upload an image", type=["JPEG", "JPG", "PNG"])
if image:
# YCbCr
img = cv2.imread(image, cv2.COLOR_RGB2YCrCb)
# Display YCbCr image
st.image(img, caption="YCbCr image")
What can you suggest to solve this problem?
Thanks in advance. | Hi @nainiayoub -
Please see the docs for file_uploader, which has varying methods of reading the UploadedFile class, depending on the output you require. I would guess that you need to do the bytes method:
bytes_data = uploaded_file.getvalue()
docs.streamlit.io
st.file_uploader - Streamlit Docs 1
Best,
Randy | 0 |
streamlit | Using Streamlit | Freemium streamlit app - how to approach | https://discuss.streamlit.io/t/freemium-streamlit-app-how-to-approach/14625 | I’m interested in a simple user flow:
User can explore standard data analytics content. More advanced and premium content is available only after payment.
To gain access, users go into a payment page, with minimal integration cost, similar to stripe or similar.
Upon successful payment, user is sent an access token or similar, which allows it access to the premium content.
At a high level, how would you approach this flow, in particular the user access and verification piece? | Bump! Any ideas? | 0 |
streamlit | Using Streamlit | No module named ‘xgboost’ when using pickle | https://discuss.streamlit.io/t/no-module-named-xgboost-when-using-pickle/12512 | Hi, I am trying to deploy a xgboost classifier using streamlit. I have the model trained in a jupyter notebook file in a different folder. in the folder that has the streamlit python script, i have installed venv and im running the app through the virtual environment. streamlit works perfectly but when I try to predict using the loaded pickle file, i get an error ‘no module named xgboost’ in it. so i did install xgboost inside the virtual environment, and when i try to run again i get the error ‘super object has no attribute get_params’.
and the code used to import the pickled model
data = np.array(inputs)
ser = pd.Series(data)
with open(‘xgb_classifier_model.pickle’,‘rb’) as modelFile:
model = pickle.load(modelFile)
prediction = model.predict(ser.to_frame().transpose())
my first question is - do i necessarily need to install xgboost and import it in the main app.py script? (ive used the trained model in a jupyter notebook, different than the one in which it was trained, by using pickle and it ran perfectly)
my second question is - even if i install xgboost, i get the new error. is there a way to fix it?
any help would be really appreciated. i have attached the github repo link - GitHub - rohithandique/maverick-web-app 20 | Hello, I had the second issue you mentioned, where ‘super’ object has no attribute ‘get_params’.
I was trying to predict from a model (made in the env using xgboost v1.3.3) loaded from pickle when xgboost (v1.5.0) is installed on the environment. I then made sure to use xgboost v1.3.3 for predicting and it’s not throwing any errors! | 0 |
streamlit | Using Streamlit | Persisting Settings | https://discuss.streamlit.io/t/persisting-settings/13496 | Hey, I wanted to ask what’s the recommended coding pattern for persistent streamlit settings.
Currently, I am using shelve to pickle/dill python objects that contain a collection of my settings.
Of course, I could also write the values directly to a DB. Though, saving snapshots of singleton objects allows me to version instances of different settings.
I just wonder if am thinking too complicated here. Maybe there’s a way to store the whole session as is, and reload it later.
I do it like this:
class Setting:
X = 10
def options(self):
self.X = st.number_input("my value", value=self.X)
config = get_last_setting()
config.options()
if st.button("Save new Setting"):
save_setting(config)
get_active_setting and save_setting would be database functions that retrieve a shelve object of Setting. It somehow works conveniently to have the class variable as default and once we call options, it becomes an instance bound variable, which can be persisted. But it all feels hacky and complicated.
A much more convenient approach would be to just snapshot the current session object so that all UI Elements entries are persisted.
if st.button("Load last session"):
load_last_session()
#This number input will be automatically set to the value which we used in the last session
config.X = st.number_input("My Value")
if st.button("Save session"):
save_session()
Do you think there could be any way to implement that? | Hey, did you make any progress. I was playing with useing pickle on the session state but without much sucesses. | 0 |
streamlit | Using Streamlit | ModuleNotFoundError: Module named ‘torch’ not found | https://discuss.streamlit.io/t/modulenotfounderror-module-named-torch-not-found/19065 | Actually I’m not deploying to cloud, Just trying it in the local machine. The package Torch is already installed in the system. But when I run streamlit, it raises the module not found error. I even included a requirements.txt file with my directory.
import streamlit as st
import glob
import pandas as pd
from utils.AudioUtils import AudioUtils
from utils.build_model import CNN14_mod
import torch
aud_util = AudioUtils()
model = CNN14_mod()
model.load_state_dict(torch.load("Fold0_0.7930.pth"))
evals = pd.read_csv("eval.csv")
model.eval()
model.cuda()
Labels = ['Baby','Conversation','Doorbell','Rain','Overflow','Object Falling','Cooker']
folder_name = st.selectbox("Category",Labels)
wav_files = glob.glob(f"Test/{folder_name}/*.wav")
def pipeline(filename,folder_name,start,dur):
#read audio file to tensor using torchaudio function
audio = aud_util.read_audio(filename=filename,foldername=folder_name,offset=start,duration=dur)
audio = aud_util.rechannel(audio)
audio = aud_util.resample(audio)
audio = aud_util.pad_audio(audio)
#converted to melspectrogram
audio = aud_util.melspectro(audio)
if wav_files is not None:
filename = st.selectbox("select the audio file plz",wav_files)
e = evals[evals.foldername==folder_name]
e = e[e.filename == filename]
start,dur = e.start_time,e.duration
pre_btn = st.button("Preprocess")
The image below is the output of streamlit run of above code
Screenshot from 2021-11-12 16-37-131920×1080 127 KB | Hi @ThiruRJST, and welcome to the Streamlit community!
You may need to add torchvision to your requirements.txt file. Is it something you’ve done?
Best,
Charly | 0 |
streamlit | Using Streamlit | Drag-and-drop in Streamlit? | https://discuss.streamlit.io/t/drag-and-drop-in-streamlit/986 | I am working on an app that takes an input file, does some calculations, visualizes them (using Streamlit) and then writes out a report. All of this works perfectly fine, except for the input file part.
On my local machine, I can use a text-box to specify the path (not very elegant though), but once deployed in the cloud even this hack will not be possible.
Are there any file upload/drag-and-drop options built into streamlit?
Thanks! | Hi @RichardOberdieck. Welcome to the community !
This feature is on the way 607 and is actively being implemented. Please follow that pull request for the latest updates!
Thank you for using Streamlit! | 0 |
streamlit | Using Streamlit | Form Submission vs SessionState | https://discuss.streamlit.io/t/form-submission-vs-sessionstate/17670 | Is it possible to have dynamic changing of inputs within a form? The blog post on forms says
“Also by definition, interdependent widgets within a form are unlikely to be particularly useful. If you pass the output of widget1 into the input for widget2 inside a form, then widget2 will only update to widget1 's value when the form is submitted.”
Consider the following app example that has a toggle button for the checkboxes and updates days based on month. I implemented the usage I want using st.session_state. My understanding is that this functionality in forms is not yet possible. Is that true? Would definitely make for cleaner code if it is possible. Thank you!
import streamlit as st
## Form Submission
st.header('Form Based Submission')
with st.form(key = 'Form Based Submission'):
birth_month = st.selectbox('Your Birth Month',['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'])
last_day = 31 if birth_month in ['Jan','Mar','May','Jul','Aug','Oct','Dec'] else 30
last_day = 29 if birth_month == 'Feb' else last_day
birth_day = st.selectbox('Your Birth Day', reversed(range(1,last_day+1)))
toggle = st.checkbox('Toggle All')
vanilla = st.checkbox('Do you like vanilla iceacream?', value = toggle)
chocolate = st.checkbox('Do you like chocolate icecream?', value = toggle)
mint = st.checkbox('Do you like mint icecream?', value = toggle)
output = {'Month':birth_month,'Day':birth_day,'Vanilla':vanilla,'Chocolate':chocolate,'Mint':mint}
submit = st.form_submit_button(label = 'Submit')
if submit:
st.write('You Form Submitted!')
st.write(output)
## Session State Based Submission
if 'output' not in st.session_state:
st.session_state['output'] = {}
if 'submitted' not in st.session_state:
st.session_state['submitted'] = False
st.header('Session State Based Submission')
birth_month = st.selectbox('Your Birth Month',['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],key='0')
last_day = 31 if birth_month in ['Jan','Mar','May','Jul','Aug','Oct','Dec'] else 30
last_day = 29 if birth_month == 'Feb' else last_day
birth_day = st.selectbox('Your Birth Day', reversed(range(1,last_day+1)),key='1')
toggle = st.checkbox('Toggle All',key = '5')
vanilla = st.checkbox('Do you like vanilla iceacream?', value = toggle, key='2')
chocolate = st.checkbox('Do you like chocolate icecream?', value = toggle, key='3')
mint = st.checkbox('Do you like mint icecream?', value = toggle, key =' 4')
submit = st.button('Submit', key = '6')
if submit:
st.session_state['submitted'] = True
st.session_state['output'] = {'Month':birth_month,'Day':birth_day,'Vanilla':vanilla,'Chocolate':chocolate,'Mint':mint}
if st.session_state['submitted']:
st.write('You Session State Submitted!')
st.write(st.session_state['output']) | @andfanilo
I need to redirect the output of one form to another?
My usecase:
User upload a dataset using st.file_uploader, selects a delimiter using a dropdown i.e. st.selectbox, I set a custom function for submission (i.e. set func for “on_click” parameter , inside st.form_submit_button)
The custom function needs to compute and display the data profile—using pandas profiling
i.e. st_profile_report(profile)
So far so good. But this function should also output a st.selectbox— with values as the column names of the uploaded dataset!
i.e. Once a form submit which contains a file uploader. I need another form that outputs a selectbox based that contains the column names of the uploaded dataset | 0 |
streamlit | Using Streamlit | How can I enable Google Adsense inside streamlit | https://discuss.streamlit.io/t/how-can-i-enable-google-adsense-inside-streamlit/4482 | Hello,
Thanks for the newest version of Streamlit 0.63 with the new feature of components, now I can insert javascript by components.html. However, After I insert the Google Adsense code using components.html, it only shows the blank at the position without loading any ads.
WeChat Screenshot_202007241340351596×493 36.9 KB
I tried just adding the code directly to the streamlit static page (index.html inside the package), and the ads showed up. So I think there should be a way to insert by component.
Any ideas?
Thanks,
Vincent | I would guess you’re running into this issue:
https://searchengineland.com/google-bans-iframes-for-adsense-though-says-it-will-grant-exceptions-81174#:~:text=Google%20has%20tweaked%20its%20policies,granted%20an%20exception%20by%20Google 49.
Streamlit Components each run in their own iframe, to keep them sandboxed from other components. Taking a step back, this is effectively this feature request, which I hope we can find a solution for in the near future
github.com/streamlit/streamlit
Allow arbitrary Javascript code blocks (e.g. Google Analytics) 62
opened
Jan 15, 2020
nthmost
Problem
Currently, Streamlit provides no vector for injection of arbitrary chunks of Javascript like Google Analytics, Adsense, LimeExplainer, and so on.
Solution
MVP: Perhaps...
enhancement | 0 |
streamlit | Using Streamlit | Option to remove padding/box for expanders in the sidebar | https://discuss.streamlit.io/t/option-to-remove-padding-box-for-expanders-in-the-sidebar/18660 | When an expander is added to the sidebar, it looks like this
I personally don’t like that there is padding on the sides, as the sidebar is already kind of compact so having these nested lines make the interior components squished. I’m wondering if there could be an option added like fill_container=False that I could set to True | kevinlinxc:
I could se
+1 for that request. | 0 |
streamlit | Using Streamlit | Sorting Plost bar chart | https://discuss.streamlit.io/t/sorting-plost-bar-chart/19100 | Hi Guys,
I have a bar chart with multiple input values (as a list).
I want to sort the bars by the first value in the list or alternatively by the total size of the bar.
Also, my bar chart uses the horizontal direction:
plost.bar_chart(
data=datasets['stocks'],
bar='company',
value=['q2', 'q3'],
direction='horizontal'
)
Anyone an idea how i could solve that? | Hey Chris, could you provide some sample data for this?? | 0 |
streamlit | Using Streamlit | Plotly draw shape, cannot delete shape | https://discuss.streamlit.io/t/plotly-draw-shape-cannot-delete-shape/14554 | Hi,
I can draw shapes on my plot, which i plan on using for allowing annotations.
Usually with Plotly, you can shift+left mouse click, select the shape and erase the shape.
However, if it’s plotted via Streamlit I can move and resize the shape but I cannot ‘select’ it to erase it.
Streamlit App
image1591×678 27.4 KB
https://plotly.com/python/configuration-options/
image1272×517 30.5 KB | Hi @seanbf ,
It took me a while to figure it out, but the effort payed off.
The 'editable' : True config option is the reason you’re unable to select the shape. If you comment out line 25 and uncomment the remaining options, you should be able to left click the shape to select it! You can then click on the erase button to get rid of the shape
Here’s an example:
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="petal_width", y="sepal_length", color="species")
fig.update_layout(
dragmode="drawopenpath",
newshape_line_color="cyan",
title_text="Draw a path to separate versicolor and virginica",
)
config = dict(
{
"scrollZoom": True,
"displayModeBar": True,
# 'editable' : True,
"modeBarButtonsToAdd": [
"drawline",
"drawopenpath",
"drawclosedpath",
"drawcircle",
"drawrect",
"eraseshape",
],
"toImageButtonOptions": {"format": "svg"},
}
)
st.plotly_chart(fig, config=config)
Output:
Happy Streamlit’ing!
Snehan | 1 |
streamlit | Using Streamlit | How to make nice circled step numbers | https://discuss.streamlit.io/t/how-to-make-nice-circled-step-numbers/18708 | Looking for a way to put some nice big circled step numbers to provide the user with a foretaste of the struxcture of the page, e.g.
1. Upload data
2. Process data
3. Download data
I guess I could create some columns and put image icons in the far left of each row. Any other approaches come to mind? A component? | Check StepperBar at link extra-streamlit-components · PyPI 9
Is this what you are looking for? | 0 |
streamlit | Using Streamlit | Label and values in in selectbox | https://discuss.streamlit.io/t/label-and-values-in-in-selectbox/1436 | hello
is it possible to have lookup values in a selectbox. I want the selectbox to display e.g. “dataset a”, “dataset b”, “dataset c” but associate a numeric value (1,2,3) with each of them so if selected, the selectbox returns a number. in html this would be: dataset a. in case this is not possible, would you want me to add it to the requested features in git? Thanks and happy Xmas everyone. | Hi @godot63,
Happy holidays to you as well!
It’s not possible to do so at this time.
There is a format_func attribute that allows you to format the display value separately from the return value, but I’m not seeing a way to use it to achieve exactly what you want.
Feel free to file a feature request on Github issues! Please include your use case as well to illustrate what you’re trying to do and why the current API isn’t suitable.
We had actually initially designed the API to work as you described then switched it to how it is now, based on user feedback. | 0 |
streamlit | Using Streamlit | Google Analytics component | https://discuss.streamlit.io/t/google-analytics-component/13878 | I am trying to make a simple component to enable google analytics, and I can’t seem to get it to work.
import streamlit.components.v1 as components
def google_analytics(google_analytics_id):
components.html(
"""
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src=f"https://www.googletagmanager.com/gtag/js?id={google_analytics_id}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', google_analytics_id);
</script>
""",
height=1,
scrolling=False,
)
Then in my app.py sidebar menu page, I have call the component. But I do not see the script loaded. | Try statcounter 41, simpler to use and works. Same implementation as the above, but it works. Also, this 15 seems relatively straight forward. I wouldn’t waste any further time on google analytics. But if you can get it to work like he 14 did, then be my guest. | 0 |
streamlit | Using Streamlit | Streamlit stats (weekly?) | https://discuss.streamlit.io/t/streamlit-stats-weekly/18100 | Hi,
Is there a way to receive weekly stats of apps views rather than monthly?
Thanks
E | Hey @emmanuel!
For the emails, we want to stick to a monthly format so it’s not too much spam. But we want to surface some more detailed analytics numbers in the app settings on Streamlit Cloud in the future. Can’t really give you a concrete date for when this will be launched but I’d guess sometime in spring next year.
If you have any input on which numbers (besides weekly views) you’d love to see, please reply here and I’ll add it to our roadmap
Happy Streamlit-ing!
Johannes | 0 |
streamlit | Using Streamlit | Matplolib animation not updating | https://discuss.streamlit.io/t/matplolib-animation-not-updating/13044 | Hi everyone !
I am trying to develop an app that computes and displays animations of satellite images , based upon acquisition parameters specified by the user.
I have been able to generate these animations and display them with a kind of “hacky” procedure : by using matplotlib.Animation.to_html5_video() and putting the resulting html in a st.markdown(html_video, unsafe_allow_html = True). I know I could have used streamlit.components.v1 according to this topic 1, but then I would have not been able to adapt the size and layout of the video generated.
Either way, I have several questions :
I have the user submit a time (with a slider in a form) at which the animations should be starting. When I submit a new timestamp, the content updates correctly (the titles and static images) except for the animations, which remain the same (see screencast below). I feel like they are cached or something. Can I somehow force the app to actually recalculate everything again ?
I am struggling to make the videos play all at once. I have tried to modified the HTML autoplay attribute of the generated videos and tried to add a custom javascript to the app as well, with no success.
Bonus question: Is it possible to zoom dynamically on an image in streamlit ?
Link to the screencast on google drive 1
Thanks for your help !
Specs:
Streamlit 0.82
Python 3.9.1, using conda
Ubuntu 20.04
Firefox 88.0.1 (64 bits) | I am closing this topic with these conclusions :
Using streamlit.components.v1 ensures that the animations get updated but I couldn’t find a way to adjust dynamically the size of the figures.
Here below you can find the javascript that I use to detect the created iframes for each animation, then fetch the video objects, stopping them and re-playing them from scratch all at once. This works well when the app is loaded once, but the script is not executed again upon reload.
Still not feasable.
<script>
function detect(){
console.log('Launching video script')
// Get all videos.
var iframes = parent.document.querySelectorAll("iframe")
var videos = [];
iframes.forEach(function(frame){
var video_list = frame.contentDocument.querySelectorAll('video');
if (video_list.length != 0){
var video = video_list[0]
console.log('Pausing and reloading videos')
video.autoplay = false
video.pause()
video.load()
// Add video to the detected videos list
videos.push(video)
}
});
return {iframes: iframes, videos: videos};
}
// Get the videos from the page
var res = detect()
var iframes = res.iframes
var videos = res.videos
iframes.forEach(function(iframe){
// Add an event listener to ensure that the detection gets reexecuted even on page reload
iframe.addEventListener('load', function(){
console.log('load')
console.log(iframe)
});
iframe.addEventListener('error', function(){
console.log('error')
});
});
// Create a promise to wait all videos to be loaded at the same time.
// When all of the videos are ready, call resolve().
var promise = new Promise(function(resolve) {
var loaded = 0;
console.log('Waiting for all videos to be loaded')
videos.forEach(function(v) {
v.addEventListener('loadedmetadata', function() {
loaded++;
if (loaded === videos.length) {
resolve();
}
});
});
});
// Play all videos one by one only when all videos are ready to be played.
promise.then(function() {
videos.forEach(function(v) {
v.play();
console.log('Playing video')
});
});
async function test(iframes){
while (true){
await new Promise(r => setTimeout(r, 5000));
console.log('Script is executing')
console.log(iframes)
}
}
test(iframes);
</script> | 1 |
streamlit | Using Streamlit | Sharing App Views via URL’s - Tricky? | https://discuss.streamlit.io/t/sharing-app-views-via-urls-tricky/18958 | We have developers frequently endeavouring to embed page parameters in the URLs so others can share a URL to get to their current view of the app (which can be quite different from the default view).
It’s rather non-trivial getting that to work though, especially for app developers who are not hardcore programmers. It requires identifying the required parameters, managing them on the session state and handling the URL query string. Frequently they’ll run into problems (e.g. Erratic behavior in selectbox when the index parameter is not a constant · Issue #1532 · streamlit/streamlit · GitHub) and always their app code gets messy. More often than we’d like - they’ll avoid the effort of getting parameters to the URL entirely → no sharing capability.
Wondering how y’all handle this?
Some example code and a demo - with a class we’ve started putting together to hide/consolidate some of this machinery.
Github - streamlit_parameters 4
Code - Parameters Module 1
Code - Parameters Usage 1
Streamlit Cloud - Parameters Demo 6 | I just dealt with this issue and it was indeed a struggle. This is heading in the right direction. Is this a third party effort or something that would be part of streamlit core? Adopting any third party effort for something this fundamental is bound to be risky. | 0 |
streamlit | Using Streamlit | filePath in streamlit app: If filePath exist on the computer deploying the app, can other computer use this app | https://discuss.streamlit.io/t/filepath-in-streamlit-app-if-filepath-exist-on-the-computer-deploying-the-app-can-other-computer-use-this-app/18931 | Hi everyone, first message here, sorry in advance if you find my question trivial.
I have been developing a local streamlit app for our data analysis in my team. I am looking to see if it is possible to deploy this app. Problem is that I need to access the path of where my datas sit (on a research server).
Can I deploy my app if my paths are defined locally in the computer that deploy the app? Or a device that is not connected to the server won’t see the data ?
I’m quite sure it doesn’t work that way but it would be super cool if the computer deploying the app could host the “run”, and other devices using the link just interacting with the interface. | Hi @Antoine_Roland, welcome to the Streamlit community!
When you define paths in your Streamlit app, it’s relative to the computer the app is being served from, not relative to the user’s computer. Which means, if where you deploy from has the same paths as you’re trying to access, then it would work.
However, if you’re doing something like in Windows where you map D:/ to a network drive, then try to host the app somewhere else, it won’t necessarily have the same drive mapping. In that case, you would need to specify the exact server address.
Best,
Randy | 0 |
streamlit | Using Streamlit | Reloading data from Database | https://discuss.streamlit.io/t/reloading-data-from-database/18994 | Hi everyone!
I’m newbie here in the Streamlit world! And i was wondering if there’s any posibility to create a button to ‘clear cache’ and bring the new information from my database connection.
I don’t wanna make my cache expire in some time,. Just want to upload my info, make some filters and visalizations, and if the users wants to reload the info without losing the filters, just need to click some button and it’s done!
I know this option exist in the hamburguer menu, but when i publish my app, this option dissapears. And also for UX is easier to visualize the button in the main screen.
Thanks! | Hi @Camilojaravila, welcome to the Streamlit community!
Using a combination of session state and cache, you should be able to accomplish what you want. Because of the way st.cache works, if you add an argument to your function definition, such as rerun_counter, then any new combination of arguments to that function will cause it to run again.
As pseudocode:
import streamlit as st
if 'key' not in st.session_state:
st.session_state['rerun_counter'] = 0
@st.cache
def dbfunction(conn, sql, rerun_counter):
....
return df
df = dbfunction(conn, sql, st.session_state['rerun_counter']
if st.button("re-run database"):
st.session_state['rerun_counter'] += 1
Effectively, when your app starts, the counter would be zero. So the same connection, same query, same counter value will be cached. When the person hits the button, the counter is now incremented, and that combination of arguments won’t exist in cache. So the function gets run again, gets cached, until the next time someone hits the button.
Best,
Randy | 1 |
streamlit | Using Streamlit | SQL Connection not available..Connecting to MySQL from streamlit | https://discuss.streamlit.io/t/sql-connection-not-available-connecting-to-mysql-from-streamlit/18923 | Hi,
From my streamlit UI application, Im trying to connect to MYSql database. Below is the code snippet for fetching the connection.
@st.cache(allow_output_mutation=True, hash_funcs={"_thread.RLock": lambda _: None})
def init_connection():
database = config[“database”]
return mysql.connector.connect(**config)
conn = init_connection()
Not sure what is the issue, but sometimes Im seeing SQL Connection not available. When I redeploy the application, able to get the connection.
Below is the code snippet how Im using this connection
def run_query():
with conn.cursor() as cur:
query = f"SELECT * FROM {database}.employee"
cur.execute(query)
return cur.fetchall() | Hey @lakshmi_mrudula,
First, welcome tot he Streamlit community!
Actually @st.cache is being phased out and replaced with better alternatives. In this case, you’re connecting to a database and opening that connection only needs to happen one time so I would suggest using st.experimental_singleton. But you can find all the optimization options here:
docs.streamlit.io
Optimize performance - Streamlit Docs 3
Happy Streamlit-ing!
Marisa | 0 |
streamlit | Using Streamlit | Information on three cards | https://discuss.streamlit.io/t/information-on-three-cards/18986 | Hello.
I’m a new streamlit user. I am developing an IOT application. Development was done on the Jupyter notebook, however I would like to provide a preview page for users to see the information.
The application has 3 output information (machine on/off, number of parts produced and % productivity percentage). I would like to show these three pieces of information in card format as used in power BI. I managed to do some things in streamlit, but I couldn’t find a way to show this information on the card. Could you help me please?
I’m inserting an example image.
Thanks | Hey @Rafael_Araujo,
Fisrt, welcome to the Streamlit community!
I think st.metric will do what you are looking for if you follow the 2nd example with columns:
Screen Shot 2021-11-10 at 9.46.04 AM1400×226 17.3 KB
docs.streamlit.io
st.metric - Streamlit Docs 5
Happy Streamlit-ing!
Marisa | 1 |
streamlit | Using Streamlit | Expander does not keep its state if something is displayed above it | https://discuss.streamlit.io/t/expander-does-not-keep-its-state-if-something-is-displayed-above-it/18959 | 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')
with st.expander('Expander 2'):
st.markdown('Exander 2X')
with st.expander('Expander 3'):
st.markdown('Exander 3X')
I’ve recorded a quick video to explain the problem
Emmanuel | It seems that setting container as st.empty first and then calling container() solve my problem. Hopefully that helps people with the same problem.
import streamlit as st
# Load the data
button = st.button('Click me')
# Display message
container = st.empty()
if button:
with container.container():
st.write('Data loaded')
# Expanders
with st.expander('Expander 1'):
st.markdown('Expander 1X')
with st.expander('Expander 2'):
st.markdown('Exander 2X')
with st.expander('Expander 3'):
st.markdown('Exander 3X') | 0 |
streamlit | Using Streamlit | Embed streamlit app | https://discuss.streamlit.io/t/embed-streamlit-app/3307 | We need to embed an existing Streamlit app (site A) to another website (site B) in order to get the company’s header, footer, traffic analysis, and so on. iframe is not allowed to use.
We tried to prepare a js script for site B
obtain HTML (site A) via a DOMParser XMLHttpRequest
query select css and js links and append to the HTML (site B)
query select app root and append to the HTML (site B)
but it gives some error as below. In Streamlit js, it failed as the endpoint has been changed.
main.d83a2e9b.chunk.js:1 WebSocket connection to 'ws://localhost:8000/stream' failed: Error during WebSocket handshake: Unexpected response code: 404
10.3ed0fb7a.chunk.js:1 GET http://localhost:8000/healthz 404 (File not found)
My question is
am I in a right direction to embed the Streamlit app?
is there any other more straightforward methods?
Thanks | Hi @kwunlyou, welcome to the Streamlit community!
If you’re not allowed to use iframes, then I’m not sure this is possible. How would your embed communicate with the Streamlit backend, without itself being a Streamlit app? | 0 |
streamlit | Using Streamlit | How to disable dark theme option? | https://discuss.streamlit.io/t/how-to-disable-dark-theme-option/11735 | Hello. I’m developing an app using plotly, and am having a very hard time making things work with both light and dark themes. I can’t get the plotly plots to look good in dark theme. I therefore would like to disable the dark theme option, and enforce that the app only uses the light theme. How can this be done? I have tried everything that I can think of and can’t seem to do it. The dark theme option is always there. Anyone know how to restrict the theme?
Alternatively, does anyone have any suggestions on how to make a plotly plot work well with both light and dark themes? I don’t want to use any of the default plotly themes because I don’t think any of them look particularly good, and I can’t get my plot customizations to work with them.
Thanks! | It might be sufficient if I can force the plotly plot to not change it’s them if the streamlit theme changes. | 0 |
streamlit | Using Streamlit | Removing and Reseting Cache | https://discuss.streamlit.io/t/removing-and-reseting-cache/69 | How do you reset the cache and can I remove only a specific object from the cache, but leave others? | To answer your first question, there are two ways to reset the cache:
Via the UI: click on the ☰ menu, then “Clear cache”. Or just press c as a shortcut.
Via the command line: type streamlit cache clear
In both cases, we clear the entire cache for you. This includes all objects stored in the memory cache as well as the disk cache (if any).
As for your second question: we don’t currently have a way to selectively remove items for the cache. It’s something we’ve been considering for a while, but have yet to find the best interface for it. | 0 |
streamlit | Using Streamlit | How to disable clear cache shortcut | https://discuss.streamlit.io/t/how-to-disable-clear-cache-shortcut/9160 | Hi everyone,
I’ve developed a Streamlit app where users usually copy data from a table cell using ‘Cmd+C’ or ‘Ctrl+C’ shortcut and paste it in a text input widget, in order to have details information about the data point selected.
Everything worked fine on Streamlit v0.61.0.
Now on Streamlit v0.74.0 issue is that when users used ‘Cmd+C’ or ‘Ctrl+C’ shortcut, it triggers the Streamlit clear cache shortcut. It seems that on v0.74.0 Streamlit is not able to see a difference between ‘Cmd+C’ and solo ‘C’ shortcut.
Is there any known solution for that issue ?
If not is there any way to disable the ‘C’ shortcut to clear cache ?
Thanks for your help. | Hi @doublemojo, welcome to the Streamlit community!
This is a known regression that was fixed in 0.74.1. If you upgrade your Streamlit version, it should be resolved.
github.com/streamlit/streamlit
Patch 0.74.1 3
streamlit:develop ← karriebear:release
opened
Jan 8, 2021
karriebear
+208
-168
Best,
Randy | 1 |
streamlit | Using Streamlit | Put the cursor in a certain component by default | https://discuss.streamlit.io/t/put-the-cursor-in-a-certain-component-by-default/18974 | Hello,
I was wondering if it would be possible to place the cursor by default into a component such as a st.text_input so that when the app starts one could just start typing instead of selecting which component to change.
I am writing an application which should accept inputs from a qr code scanner which should translate to a set of key strokes. I’d like those keystrokes to be entered into a specific st.text_input since I wouldn’t be able to mouse or tab over to the correct component with the qrcode scanner. | I believe that Scrolling to an element · Issue #636 · streamlit/streamlit · GitHub 5 would solve my issue. | 0 |
streamlit | Using Streamlit | St.file_uploader cannot transfer the file to the second object | https://discuss.streamlit.io/t/st-file-uploader-cannot-transfer-the-file-to-the-second-object/18946 | Hello, everyone. I need your help.
I found that st.file_uploader cannot transfer the file to the second object. My codes are like the following:
uploaded_file = st.file_uploader(“Choose a file”)
dom = minidom.parse(uploaded_file)
per = ET.parse(uploaded_file)
per cannot get anything. XML file has no error. And if I change the sequence to “per, dom”, dom can not get the file.
error: xml.etree.ElementTree.ParseError: no element found: line 1, column 0
Does anyone have some solutions? I appreciate it so much. | I tried, if you upload one file and read it will two function, second function will report error.
one solution is you copy the original file and rename the new file.
and set your code like this:
uploaded_file = st.file_uploader(“Choose a file”, accept_multiple_files=True) | 0 |
streamlit | Using Streamlit | Dataframe not refreshing | https://discuss.streamlit.io/t/dataframe-not-refreshing/18817 | Hello Streamlit community,
Currently writing Streamlit app to retrieve options setup on a specific Oracle database hosted on a target platform.
The user selects the folder containing the audit data
Folder name is composed by <server_name>_<Database_name>
Start_analyze button performing logical treatments and display informations for each option in a dataframe from a csv file generated dynamically
So far all Streamlit behavior fine but …Correct options used in the database displayed
Above title is correct (global python variable)
Next attempts (analyzing a different folder name ) retrieve correct data in title but related dataframe is never refreshed and still display data of initial analyze …
Did -with our without setting allow_output_mutation=True
@st.cache (suppress_st_warning=True, allow_output_mutation=True)
def load_data():
cols = columns=['Server' , 'Instance' ,'Option' , 'Usage_option_count' , 'Thales_subscribed' ,'Date_analysis']
data_ora = pd.read_csv(config.df_summary, usecols = cols)
return data_or
I checked config.df_summary value used (target .csv file name) is correct in load_data function, but dataframe never refreshed and still display data with server_name / database_name
values of first analysis … - like on image below example
Also tried of using st.empty() but with no effect
Capture_streamlit_dataframe1238×368 42.3 KB
Please advise !
Dominique | Iniitial issue solved (global variable not well reset)
Related dataframe correctly refreshed
Thanks again for your support | 1 |
streamlit | Using Streamlit | Why my app just keep running forever without any output even locally | https://discuss.streamlit.io/t/why-my-app-just-keep-running-forever-without-any-output-even-locally/18943 | why my streamlit app just keep running forever without any output even locally?
image1920×983 59.7 KB | Finally,I konw what happend.It is those number_input that make my app keep rerunning.Now I rewrite my code and the problem solved.Thanks for your help and here is part of my new code
if page == '所需资源预测':
st.write('# 所需资源预测')
st.write('***')
column1,column2=st.columns(2)
with column1:
st.write('### 输入')
ExportVolume=st.number_input('出库量',min_value=0,value=1,help='请输入一个整数作为出库量')
if not ExportVolume:
st.stop() #stop the app to rerun
ImportVolume=st.number_input('入库量',min_value=0,value=1,help='请输入一个整数作为入库量')
if not ImportVolume:
st.stop()
num_of_position=st.number_input('收发货位总数',min_value=1,value=1,help='请输入一个整数作为收发货位总数')
if not num_of_position:
st.stop()
t_in=st.number_input('单箱入库时间(分钟)',min_value=0.0,value=2.0,help='请输入一个浮点数作为单箱入库时间(单个箱头的入库用时)')
if not t_in:
st.stop()
t_out=st.number_input('单箱出库时间(分钟)',min_value=0.0,value=2.0,help='请输入一个浮点数作为单箱出库时间(单个箱头的出库用时)')
if not t_out:
st.stop()
T_Consuming=st.number_input('作业耗时(分钟)',min_value=0.0,value=60.0,help='请输入一个浮点数作为作业耗时')
if not T_Consuming:
st.stop()
num_of_ccs,position_for_export,position_for_import=ResourceRequired(ExportVolume,ImportVolume,num_of_position,t_in,t_out,T_Consuming)
with column2:
st.write('### 输出')
st.metric("所需叉车手",str(num_of_ccs))
st.metric('所需发货位',str(position_for_export))
st.metric('所需收货位',str(position_for_import)) | 1 |
streamlit | Using Streamlit | Changing each progress bar to different colors | https://discuss.streamlit.io/t/changing-each-progress-bar-to-different-colors/18827 | Hello everyone!
Below is the example of current status, but I want each bar to show different colors.
Is there way to achieve this in Streamlit?
Thank you! | I am facing a similar problem. Is there a way to style individual instances of a component? | 0 |
streamlit | Using Streamlit | Is it possible to process click events on charts? | https://discuss.streamlit.io/t/is-it-possible-to-process-click-events-on-charts/1258 | I am eager to rewrite a dash app I develop using streamlit. The only bit I am missing is the ability to react to click or select events on a chart, like updating another chart base on the click coordinates. Is it possible to do things like this in streamlit? | Hi @Alex_ml
It’s currently not directly supported in Streamlit. But you might figure an indirect way using the interactivity of some of the plotting libraries supported like Vega, Plotly or Bokeh. For inspiration see https://vega.github.io/vega-lite/examples/#interactive 419 | 0 |
streamlit | Using Streamlit | Download Button | https://discuss.streamlit.io/t/download-button/18841 | I have an excel file with multiple sheets and I want to add that excel file in the download button. I don’t know how to do that. I will be very grateful if anyone help me. | Hi, download excel, you can do like this:
with open("example.xlsx", "rb") as file:
btn = st.download_button(
label="click me to download excel",
data=file,
file_name="new.xlsx",
mime="application/octet-stream"
) | 1 |
streamlit | Using Streamlit | St.form_submit_button to update Postgres database | https://discuss.streamlit.io/t/st-form-submit-button-to-update-postgres-database/18052 | Started using Streamlit last week, instant fan. The app I’ve developed is very simple. I am collaborating with a group of scientists (app users) and need to have a simple platform for them to perform quality assessment (QA) review on some data. I use st.form that has some select boxes that lets users select a measurement from the project database for review. Once these options are selected, I have a st.form_submit_button that triggers the app to go get the data from the database based on the user input. It then writes out the data and makes a couple charts for them to look at, and then 2 drop down menus and a text box are provided to allow them to provide their input. A second st.form_submit_button is used to commit their input to the database.
Here’s the issue. This works perfectly in local development using an SQLite database. I updated the app to point to a Postgres database rather than my local test SQLite database. Everything still works perfectly except the second st.form_submit_button. It behaves totally differently now and does not commit anything to the database. Just to check, I put the database commit before the submit button and it commits, but only commits blanks (as if no input). For example, when put before the second submit button this successfully commits blank text ("") to the Postgres database even when there is user input:
CUR.execute("UPDATE table SET euid = ‘userinput1’ WHERE hashid = ‘userinput2’)
DBCON.commit()
While this does not commit anything to the Postgres database, clears the form (with clear_on_submit = False), and starts over without doing anything or raising any errors:
commitbutton = st.form_submit_button(label = ‘Click here to commit changes to database’)
if commitbutton:
CUR.execute("UPDATE table SET euid = ‘userinput1’ WHERE hashid = ‘userinput2’)
DBCON.commit()
Only the second st.form_submit_button is in question here. I haven’t changed anything else about the app except the database that it points to. | Have you had any luck figuring this out as I have exactly the same issue.
I have the following form code and writing to a SQLite db:
def FaddCase():
with st.form(key = "addData"):
FcaseName = st.text_input ("Case Ref...")
Fcris = st.text_input ("CRIS Number...")
FclientName = st.text_input ("Client Name...")
Ftrt = st.text_input ("TRT...")
FagreedHours = st.number_input ("Agreed Hours...")
FactualHours = st.number_input ("Actual Hours...")
FcostCode = st.text_input ("Cost Code...")
FoffType = st.text_input ("Offence Type...")
Fstatus = st.text_input ("Status...")
Foic = st.text_input ("OIC...")
_returnedData = [FcaseName, Fcris, FclientName, Ftrt, FagreedHours, FactualHours, FcostCode, FoffType, Fstatus, Foic]
curs.execute("INSERT INTO Tcases VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", _returnedData)
conn.commit()
_submitForm = st.form_submit_button("Commit to Database")
It merely puts in a blank record to the db
Any help/update would be appreciated.
Thanks. | 0 |
streamlit | Using Streamlit | NO WAY to set focus at top of screen on page reload. Really? | https://discuss.streamlit.io/t/no-way-to-set-focus-at-top-of-screen-on-page-reload-really/15474 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Hyperlink to an expander somewhere in app | https://discuss.streamlit.io/t/hyperlink-to-an-expander-somewhere-in-app/18881 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Wordcloud error | https://discuss.streamlit.io/t/wordcloud-error/18672 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Different button types/sizes in Streamlit | https://discuss.streamlit.io/t/different-button-types-sizes-in-streamlit/18883 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Convert stri() to int() | https://discuss.streamlit.io/t/convert-stri-to-int/18879 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | streamlit.legacy_caching.hashing.UserHashError | https://discuss.streamlit.io/t/streamlit-legacy-caching-hashing-userhasherror/18874 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | __conform__() not a valid streamlit command | https://discuss.streamlit.io/t/conform-not-a-valid-streamlit-command/18867 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Problem with Plotly figure update! | https://discuss.streamlit.io/t/problem-with-plotly-figure-update/18829 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | Create nested columns | https://discuss.streamlit.io/t/create-nested-columns/18807 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
streamlit | Using Streamlit | How to avoid refreshing the whole page everytime when the value of a text_input has been changed? | https://discuss.streamlit.io/t/how-to-avoid-refreshing-the-whole-page-everytime-when-the-value-of-a-text-input-has-been-changed/18845 | My latest failed attempt below (4 days since I asked the original question).
Imagine scrolling to the bottom of a long chart set on your phone and tap “Load Next Dataset” . Now you have to manually scroll all the way to the top to see the new data in order. Now imagine you need to do this 60 times in a row…
The following doesn’t work in Streamlit even though the script is firing and the console logs print both times.
Note: After reading more of the manual it appears that components.html encapsulates what it can affect to itself so there is no way the following code could affect the rest of the page.
def market_scan(exchange):
components.html(
"""
<script>
console.log("Will it run this?")
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
} else {
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
}
console.log("It ran but completely ingnores the javascript in between")
</script>
"""
) | Thank you so much @okid
I got your latest working with one slight change. The page would not refocus at the top of the page (in Brave anyway) with the session state counter embedded in the comment, but, it works fine inside a couple of paragraph tags. This works fine since the height is set to zero and can’t been seen anyway.
This is a good solution.
Working code here:
import streamlit as st
import streamlit.components.v1 as components
if "counter" not in st.session_state:
st.session_state.counter = 1
st.header("Set Focus Here on Page Reload")
st.write("Please click button at bottom of page.")
for x in range(20):
text_field = st.write("Field "+str(x))
if st.button("Load New Page"):
st.session_state.counter += 1
components.html(
f"""
<p>{st.session_state.counter}</p>
<script>
window.parent.document.querySelector('section.main').scrollTo(0, 0);
</script>
""",
height=0
)
st.write(f"Page load: {st.session_state.counter}") | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.