Ubuntu 20.04.3 LTS, streamlit 1.4 will not start

Question:
Hi,
I just started learning python programming. And to use Streamlit, more precisely to learn it.
I also managed to do a simple little program. Streamlit also runs nicely under 0.52. However, if I upgrade the version, no commands to Streamlit will start. The error message: Invalid instruction.
If I install the “Streamlit pages” pip package, the error will go away until version 0.84, but then unfortunately it will not start with this pip package, it will give the error message “It is no longer supported after version 0.84”. Please help me with a detailed description (I am a very beginner) of how I could make the newer versions work.
My system: Ubuntu 20.04.3 LTS Linux username 5.4.0-94-generic # 106-Ubuntu SMP Thu Jan 6 23:58:14 UTC 2022 x86_64 x86_64 x86_64 GNU / Linux
python version: 3.9.9
and I use Pycharm.
Sorry if my English isn’t really perfect.
And thank you in advance for all the help

Context:
Hi @CsorbaTomi, welcome to the Streamlit community!

 CsorbaTomi:

Streamlit also runs nicely under 0.52.

If you are going as far back as Streamlit 0.52, then you’re on the wrong track unfortunately. That is probably two years old at this point. The current version of Streamlit is 1.4, and a lot has changed between now and then.
Are you using a 64-bit version of Streamlit? Because of the talk of version 0.84 or so, I suspect you might be using a 32-bit version of Python, which Streamlit does not support since one of our key dependencies (Apache Arrow) does not support 32-bit versions of Python.
Best,
Randy


Question: I want to add the wordcloud to streamlit app to show thw related words in the tweets.

Context:
Great question and you absolutely can do this with st.pyplot() and wordcloud. Here’s a simple example:
import streamlit as st
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# Create some sample text
text = 'Fun, fun, awesome, awesome, tubular, astounding, superb, great, amazing, amazing, amazing, amazing'

# Create and generate a word cloud image:
wordcloud = WordCloud().generate(text)

# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()
st.pyplot()

Let me know if that works for you!


Question:
Hi.
After select some options on the sidebar of my app, I have a button to make the prediction.
I would like to know if is there a way to toggle/hide the sidebar?
On mobile, that gets in the way of usability.
Thanks.

Context:
Hi @SantiagoBF,
First welcome to the Streamlit community!
Currently, there is no built-in way to remove the “X” on the sidebar. But if this is a feature your looking for you can open a feature request on our github!

      GitHub

Issues · streamlit/streamlit 16

  Streamlit — The fastest way to build data apps in Python - Issues · streamlit/streamlit

Happy Streamlit-ing!
Marisa


Network URL not working on other computers

Question:
Summary
When I run streamlit run xxx.py, it works very well in my local browser. When I try to access the web app from another computer using the provided network URL, Streamlit shows:
Safari can’t open the page “http://192.168.1.100:8501 71”. because the server where this page is located isn’t responding.
Steps to reproduce

streamit run xxxx.py
Local URL: http://localhost:8501 50 works!
Network URL: http://192.168.1.100:8501 71 - works on local computer, but not on other computers.

config.toml
[global]

# By default, Streamlit checks if the Python watchdog module is available and, if not, prints a warning asking for you to install it. The watchdog module is not required, but highly recommended. It improves Streamlit's ability to detect changes to files in your filesystem.

# If you'd like to turn off this warning, set this to True.

# Default: false

disableWatchdogWarning = false

# Configure the ability to share apps to the cloud.

# Should be set to one of these values: - "off" : turn off sharing. - "s3" : share to S3, based on the settings under the [s3] section of this config file. - "file" : share to a directory on the local machine. This is meaningful only for debugging Streamlit itself, and shouldn't be used for production.

# Default: "off"

sharingMode = "off"

# If True, will show a warning when you run a Streamlit-enabled script via "python my_script.py".

# Default: true

showWarningOnDirectExecution = true

# Level of logging: 'error', 'warning', 'info', or 'debug'.

# Default: 'info'

logLevel = "info"

[client]

# Whether to enable st.cache.

# Default: true

caching = true

# If false, makes your Streamlit script not draw to a Streamlit app.

# Default: true

displayEnabled = true

[runner]

# Allows you to type a variable or string by itself in a single line of Python code to write it to the app.

# Default: true

magicEnabled = true

# Install a Python tracer to allow you to stop or pause your script at any point and introspect it. As a side-effect, this slows down your script's execution.

# Default: false

installTracer = false

# Sets the MPLBACKEND environment variable to Agg inside Streamlit to prevent Python crashing.

# Default: true

fixMatplotlib = true

[server]

# List of folders that should not be watched for changes. This impacts both "Run on Save" and @st.cache.

# Relative paths will be taken as relative to the current working directory.

# Example: ['/home/user1/env', 'relative/path/to/folder']

# Default: []

folderWatchBlacklist = []

# Change the type of file watcher used by Streamlit, or turn it off completely.

# Allowed values: * "auto" : Streamlit will attempt to use the watchdog module, and falls back to polling if watchdog is not available. * "watchdog" : Force Streamlit to use the watchdog module. * "poll" : Force Streamlit to always use polling. * "none" : Streamlit will not watch files.

# Default: "auto"

fileWatcherType = "auto"

# If false, will attempt to open a browser window on start.

# Default: false unless (1) we are on a Linux box where DISPLAY is unset, or (2) server.liveSave is set.

headless = false

# Immediately share the app in such a way that enables live monitoring, and post-run analysis.

# Default: false

liveSave = false

# Automatically rerun script when the file is modified on disk.

# Default: false

runOnSave = false

# The address where the server will listen for client and browser connections. Use this if you want to bind the server to a specific address. If set, the server will only be accessible from this address, and not from any aliases (like localhost).

# Default: (unset)

#address =

# The port where the server will listen for browser connections.

# Default: 8501

port = 8501

# The base path for the URL where Streamlit should be served from.

# Default: ""

baseUrlPath = ""

# Enables support for Cross-Origin Request Sharing, for added security.

# Default: true

enableCORS = false

# Max size, in megabytes, for files uploaded with the file_uploader.

# Default: 200

maxUploadSize = 200

[browser]

# Internet address where users should point their browsers in order to connect to the app. Can be IP address or DNS name and path.

# This is used to: - Set the correct URL for CORS purposes. - Show the URL on the terminal - Open the browser - Tell the browser where to connect to the server when in liveSave mode.

# Default: 'localhost'

serverAddress = "192.168.1.100"

# Whether to send usage statistics to Streamlit.

# Default: true

gatherUsageStats = true

# Port where users should point their browsers in order to connect to the app.

# This is used to: - Set the correct URL for CORS purposes. - Show the URL on the terminal - Open the browser - Tell the browser where to connect to the server when in liveSave mode.

# Default: whatever value is set in server.port.

serverPort = 8501

[mapbox]

# Configure Streamlit to use a custom Mapbox token for elements like st.deck_gl_chart and st.map. If you don't do this you'll be using Streamlit's own token, which has limitations and is not guaranteed to always work. To get a token for yourself, create an account at https://mapbox.com. It's free! (for moderate usage levels)

# Default: ""

token = ""

[s3]

# Name of the AWS S3 bucket to save apps.

# Default: (unset)

#bucket =

# URL root for external view of Streamlit apps.

# Default: (unset)

#url =

# Access key to write to the S3 bucket.

# Leave unset if you want to use an AWS profile.

# Default: (unset)

#accessKeyId =

# Secret access key to write to the S3 bucket.

# Leave unset if you want to use an AWS profile.

# Default: (unset)

#secretAccessKey =

# The "subdirectory" within the S3 bucket where to save apps.

# S3 calls paths "keys" which is why the keyPrefix is like a subdirectory. Use "" to mean the root directory.

# Default: ""

keyPrefix = ""

# AWS region where the bucket is located, e.g. "us-west-2".

# Default: (unset)

#region =

# AWS credentials profile to use.

# Leave unset to use your default profile.

# Default: (unset)

#profile =

Context:
Welcome to the community @TheClub4!
Usually an issue like this indicates a networking issue, not a Streamlit one. If there is a firewall on the computer you are trying to access over the network, temporarily disabling it completely will allow you to understand if that’s the issue.
If disabling the firewall works, then you can re-enable the firewall with a rule that allows access to port 8501. How this is done depends on which operating system you are using and your local network setup, so unfortunately I can’t give too much more detail than that.


Session State Variables are re-initialized to initial state going through pages

Question:
hi all,
I am having issues with my session state variables with the following code.

I instantiate the session state variables

In the sidebar, I can select the pages to which I want to navigate to

In each page, there is a widget that takes a value and saves it in the session state.

Problem: when going through different pages, the values that were given are being removed from the session state.
Here is my code:
# Instantiate the Session State Variables

if 'name' not in st.session_state:

    st.session_state.name = ''

if 'age' not in st.session_state:

    st.session_state.age = ''

if 'gender' not in st.session_state:

    st.session_state.gender = ''

# Sidebar Widgets

sidebar_Title = st.sidebar.markdown('# Streamlit')

sidebar_pages = st.sidebar.radio('Menu', ['Page 1', 'Page 2', 'Page 3'])

# Page 1

def page1():

    name = st.text_input('What is your name?', key = 'name' )

# Page 2

def page2():

    age = st.text_input('What is your age?', key = 'age')

# Page 3

def page3():

    gender = st.text_input('What is your gender?', key = 'gender')

# Navigate through pages

if sidebar_pages == 'Page 1':

    page1()

elif sidebar_pages == 'Page 2':

    page2()

else:

    page3()

st.write(st.session_state)

Context:
hello,
I have the same issue, and I don’t understand why.
The doc:
https://docs.streamlit.io/library/advanced-features/widget-semantics
seems to say that it should be the way to save widgets states through session.
An (ugly?) workaround found is to put the following lines somewhere in the page
for k in st.session_state.keys():
    st.session_state[k] = st.session_state[k]

but I am not clear if we should really do that… ?


Question:
Hello friends
Is it possible to create date picker for “date_input” widget(for example persian/jalali calendar) using component???
Do you think is there any example???

Context:
Hi @Mohammadseif, welcome back!
Yes, it would be a great example of a Streamlit Component. That would be an example of a bi-directional Streamlit Component 2, where you use a pre-existing JavaScript library to pass information back to Python.
Unfortunately, I’m not a JS developer nor familiar with the Persian calendar, but it’s definitely possible to implement.
Best,
Randy


Question:
Hi,
I am new to this - please bear with me if I have gravely missed something.
One feature I would love to see is multiple tabs so the app can host multiple windows. Is it available? I looked through the online documents as well as the community site, but could not find it.
Thanks!
-jc

Context:
Not at the moment. What you can do for now is to use radiobuttons like in the image below

image1144×626 57 KB

There are some feature requests related to this like

      github.com/streamlit/streamlit

      Feature request: Tabs 472

        opened

        Oct 2, 2019

          ines

  Problem
Sorry if this has been discussed before (couldn't find anything here on on the forum). While building my app, I thought...

    FR:Layout
    enhancement

      github.com/streamlit/streamlit

      Please add st.navigation widget 350

        opened

        Nov 21, 2019

          MarcSkovMadsen

  Problem
I would like to build multi page apps with a nice layout and style for use internally in an enterprise and...

    enhancement

It would be awesome if you casted a vote or added some comments in the issues on what you need.


Help with “UnpicklingError: invalid load key, ‘v’.”

Question:
Hi and happy new year,
May I ask for your help with the following upickling error on my Streamlit App:
Screen Shot 2021-01-07 at 2.42.50 PM1496×560 41.6 KB
These pickle files were uploaded to github using git-lfs, as they are large files–might that be involved in the error?
My python version is 3.7.4
My streamlit version is 0.72.0
My github repo is GitHub - amaze2/concordiensis: Concordiensis Project 11
I would really appreciate your help with this. Thank you in advance!

Context: Actually, I take that back…it looks like it could be in by end of January/early February, as it’s a pretty often requested feature.


AttributeError: ‘NoneType’ object has no attribute ‘update’ fastai and streamlit

Question:
Hello
I want to create an web app using streamlit that classify dogs but I can’t get it to work
I tried every trick in the book but I got nowhere, here is my code :
%%writefile app.py
from fastai.vision.widgets import *
from fastai.vision.all import *
from pathlib import Path
import streamlit as st

    class Predict:
        def __init__(self, filename):
            self.learn_inference = load_learner(Path()/filename)
            self.img = self.get_image_from_upload()
            if self.img is not None:
              self.display_output()
              self.get_prediction()

        @staticmethod
        def get_image_from_upload():
            uploaded_file = st.file_uploader("Upload Files",type=['png','jpeg', 'jpg'])
            if uploaded_file is not None:
              return PILImage.create((uploaded_file))
            return None
        def display_output(self):
            st.image(self.img.to_thumb(500,500), caption='Uploaded Image')
        def get_prediction(self):
            if st.button('Classify') :
              self.pred, self.pred_idx, self.probs=self.learn_inference.predict(self.img)
              st.write(f'Prediction: {self.pred}; Probability: {self.probs[pred_idx]:.04f}')
            else:
                return st.write(f'Click the button to classify')

    if __name__=='__main__':

        file_name='dog.pkl'

        predictor = Predict(file_name)

After I compile
!streamlit run app.py & npx localtunnel --port 8501
and I click on classify
I get :
AttributeError: 'NoneType' object has no attribute 'update'

Any help would be much appreciated.
Thanks

Context:
Traceback

<IPython.core.display.HTML object>
2022-01-18 18:17:18.723 Traceback (most recent call last):
File “/usr/local/lib/python3.7/dist-packages/streamlit/script_runner.py”, line 379, in run_script
exec(code, module.dict)
File “/content/app.py”, line 38, in
Predict(file_name)
File “/content/app.py”, line 14, in init
self.get_prediction()
File “/content/app.py”, line 26, in get_prediction
self.pred, self.pred_idx, self.probs=self.learn_inference.predict(self.img)
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 266, in predict
inp,preds,,dec_preds = self.get_preds(dl=dl, with_input=True, with_decoded=True)
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 253, in get_preds
self._do_epoch_validate(dl=dl)
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 203, in _do_epoch_validate
with torch.no_grad(): self._with_events(self.all_batches, ‘validate’, CancelValidException)
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 163, in with_events
try: self(f’before{event_type}’);  f()
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 141, in call
def call(self, event_name): L(event_name).map(self._call_one)
File “/usr/local/lib/python3.7/dist-packages/fastcore/foundation.py”, line 155, in map
def map(self, f, *args, gen=False, **kwargs): return self._new(map_ex(self, f, *args, gen=gen, **kwargs))
File “/usr/local/lib/python3.7/dist-packages/fastcore/basics.py”, line 698, in map_ex
return list(res)
File “/usr/local/lib/python3.7/dist-packages/fastcore/basics.py”, line 683, in call
return self.func(*fargs, **kwargs)
File “/usr/local/lib/python3.7/dist-packages/fastai/learner.py”, line 145, in _call_one
for cb in self.cbs.sorted(‘order’): cb(event_name)
File “/usr/local/lib/python3.7/dist-packages/fastai/callback/core.py”, line 45, in call
if self.run and _run: res = getattr(self, event_name, noop)()
File “/usr/local/lib/python3.7/dist-packages/fastai/callback/progress.py”, line 26, in before_validate
def before_validate(self): self._launch_pbar()
File “/usr/local/lib/python3.7/dist-packages/fastai/callback/progress.py”, line 35, in _launch_pbar
self.pbar.update(0)
File “/usr/local/lib/python3.7/dist-packages/fastprogress/fastprogress.py”, line 56, in update
self.update_bar(0)
File “/usr/local/lib/python3.7/dist-packages/fastprogress/fastprogress.py”, line 76, in update_bar
else: self.on_update(val, f’{100 * val/self.total:.2f}% [{val}/{self.total} {elapsed_t}<{remaining_t}{end}]’)
File “/usr/local/lib/python3.7/dist-packages/fastprogress/fastprogress.py”, line 125, in on_update
if self.display: self.out.update(HTML(self.progress))
AttributeError: ‘NoneType’ object has no attribute 'update


Question:
The session state initialization error shows up, even when the session state is properly initialized.
The code taken ‘as is’ from the Example 1 Streamlit Docs 1
import streamlit as st
st.title(‘Counter Example’)
if ‘count’ not in st.session_state:
st.session_state.count = 0
increment = st.button(‘Increment’)
if increment:
st.session_state.count += 1
st.write('Count = ', st.session_state.count)
Returns the following error
AttributeError: st.session_state has no attribute “count”. Did you forget to initialize it? More info: Add statefulness to apps - Streamlit Docs 1
The same is happening with my own code. I see similar questions in the forum, not yet addressed, so decided to raise a new one. Would appreciate any help… Thank you.
Streamlit ver. 1.4

Context:
I do:
if 'count' not in st.session_state:
   st.session_state['count'] = 0

Have you tried that?
Dinesh


Question:
Hi,
I am new to Streamlit. Was trying it out on my local machine, but ran into problems of streamlit not rerunning as per my understanding. Any help would be much appreciated. I am using Python 3.9. Following is the test case code that I run with the command:

streamlit run testcase.py
It opens the browser fine with the required forms and buttons. First time around the “Start” button works and it starts the program. But if I do any changes to the form values, it does not take effect when I again press the “Start” button. Also, when I press the “Stop” button, the program does not stop. I rolled back the streamlit to 0.86 version from the latest one, then also it does not work. Not sure what I am missing.

Regards.

testcase.py:
from time import sleep
import streamlit as st
bell = ‘ON’
form = st.sidebar.form(key=“myform”)
stop_loss_target_total = form.number_input(“SL Target”, value=int(600))
profit_target_total = form.number_input(“Profit Target”, value=int(800))
sleep_interval = form.number_input(“Sleep Interval”, value=int(3))
start = form.form_submit_button(“Start”)
stop = st.sidebar.button(“Stop”)
def print_parameter_values():
print(f’\tSleep Interval: {sleep_interval} Secs’)
print(f’\tProfit Target (per lot): {profit_target_total}’)
print(f’\tStop Loss (per lot): {stop_loss_target_total}’)
print(f’\tBell: {bell}’)
# print(f’\n’)
print(‘Waiting for connection…’)
print(“Connected…”)
if bell == ‘ON’:
print(f’Bell: {bell}’)
print(start, stop)
def run_strategy():
i = 0
while True:
print(i, start, stop)
print(f’Current Parameters For The Run:’)
print_parameter_values()
print(f’Hi2 {start}, {stop}’)
sleep(sleep_interval)
i = i+1
if start:
print(‘In start’)
print(start)
run_strategy()
if stop:
print(‘In stop’)
print(stop)
st.write(‘Exiting…’)

Context: It is working now… no longer an issue. This can be closed. Thanks.


Question:
Hi Team ,
The package looks great!. I wanted to know if there is a simple way to take a text input from the user and use the input to filter or create views on streamlit.  Since there are many millions of data points ,  i am unable to use the slider or dropdown option for this
Thanks and regards,
Aravind

Context:
Hi Aravind_K_R
There are two ways to get text input from users.
First, there’s st.text_input 1.1k for when you only need a single line of text:
user_input = st.text_input("label goes here", default_value_goes_here)

Then there’s st.text_area 323 for then you want multiple lines of text:
user_input = st.text_area("label goes here", default_value_goes_here)

In both cases, the default_value_goes_here argument is optional. You can find more about these in our API documentation 1.4k.
Let me know if this answers your question!


Move the cursor to the bottom after logging in st.text_area

Question:
Hi,
I am using st.text_area to display logs from my background process. i.e. every time some one clicks a refresh button, I read the log file and write it using st.text_area
The problem is that the cursor/scroll bar is at the top of the text_area. But in a log file we are most interested in what is at the end of the file (which is the most recent update). Is there some way to specify that the text_area scroll bar should scroll down to the bottom.
Thanks.

Context: Any pointers on this will be helpful. Thanks.


Disable reloading of image every time a widget is updated

Question:
Hi,
First of all big kudos to the Streamlit team for this awesome piece of software.
I have run into a mild annoyance. I am creating an app to do image labeling (with multiple label classes). The categories are binary, and each label category is represented by a checkbox. The labels are stored and the next image is shown when upon clicking a ‘Submit’ button.
The problem:
Whenever a checkbox is checked, the app makes a new call to st.image(picture) rerenders the (same) picture, which makes the app ‘fade’ for a moment. I would like to avoid this fading if possible, or at least minimize it. Right now, it seems that the caching isn’t really doing a lot for the speed. I see some approaches.
1: Somehow pause rerendering until submit button is hit. I.e. ability to change the value of the widget without impacting the state of the app before clicking a ‘submit’ button (preferred option).
2: Make the caching work properly so that the image does not rerender (perhaps I am making some mistake regarding how caching is used?)
Can any of you good people give me some pointers?
Minimal example:
from PIL import Image
from collections import OrderedDict
import streamlit as st

categories= ['a', 'b', 'c']
checkboxes = OrderedDict({category: st.sidebar.checkbox(category) for category in categories})

### Omitted code with submit button and writing labels to file ###

@st.cache
def load_image(img_id):
    image = Image.open(f"images/{img_id}.jpg")
    return image

image = load_image("example")
st.image(image, use_column_width=True)

Context:
Hey @PeterT, welcome to Streamlit, and thanks for the kind words!
As you’ve noted, this fade happens every time your app re-runs (and therefore re-renders), if it takes longer than 1 second to complete the re-render. There isn’t a real workaround for this right now, but we have an open GitHub issue 212 that you can follow. There have been a number of requests for “form-like” widget behavior, and it’s something we’re discussing internally!
In the meantime, there are several sub-optimal workarounds if this is a real show-stopper for you:

Make your app run faster. (This may not be possible! It looks like you’re already using caching. Are there other long-running operations that could be cached?)
Modify the .stale-element CSS selector in ReportView.scss 39, extending the duration of the opacity transition (or removing the opacity change altogether). This would require you to build your own Streamlit, which is more work, so I’d certainly not recommend it to most users, but it’s an escape hatch if needed.

Tim


Question:
Wassup Guys,
I am currently writing a transcriptor app. I’ve deployed it since a couple versions to my cloud.
However, I added a few files to Git LFS because they’re too big to be uploaded normally.
I store the logic for my models as .npy, .pth, .bin files.
Everythings works locally normally, but the cloud project seems to have issues cloning my stored files.
How can I solve this? I don’t want to use an ugly workaround.

Context:
Hi @fuccDebugging -
Streamlit Cloud supports using GitLFS, but if I’m not mistaken it does require credits to be purchased (from GitHub) over a certain size. How large are the files you are using?
Best,
Randy


Question: how do I solve this in streamlit where I don’t know how their js works or how do I make them load at the end of the file?

Context:
Hi @Kanjani_Kabir, welcome to the Streamlit community!
Are you actually experiencing an issue with Streamlit or did you see this in the developer console and it worried you?
In general, to make a package like Streamlit work, there has to be a lot of boilerplate JS code “just in case” new widgets show up. Meaning, the front-end code has to account for all of the widgets that might get passed from the Python backend.
The analysis tools in the browser is just highlighting that if the page always stayed the same there is JS that could be removed. But since the point of Streamlit is to make writing apps from Python possible, there really isn’t a way to remove the JS that makes all that possible.
Best,
Randy


Using step lower than 0.01 for slider with floats

Question:
Hello,
I am using a slider with float values, but it seems that choosing a step lower than 0.01, for example 0.001, is treated as if it was 0.01.
Any solution for fixing this?

Context:
Hi @HugoLaurencon, welcome to the Streamlit community!
You should be able to set the precision as shown by the following example:

    About number_input for very small number Using Streamlit

    Hi @Sunix_Liu -
Adding the format parameter worked for me:
import streamlit as st
temp = st.number_input(
    label="test",
    min_value=0.000000,
    step=0.000001,
    max_value=0.0005,
    value=0.0000045,
    format="%f",
)

 [image]

Best,
Randy

Best,
Randy


Question:
Hello,
My code and screen shot are below.
How can I format the numbers in columns to percentage or round a number ?
df_exc= pd.read_excel(yol)
  gb = GridOptionsBuilder.from_dataframe(df_exc)
  gb.configure_pagination()
  gb.configure_column("Env_Oran", cellStyle={'color': 'red'})
  gb.configure_selection(selection_mode="single", use_checkbox=True)

  gridOptions = gb.build()

  AgGrid(df_exc, gridOptions=gridOptions)

  #data = AgGrid(df_exc, gridOptions=gridOptions, enable_enterprise_modules=True, allow_unsafe_jscode=True, update_mode=GridUpdateMode.SELECTION_CHANGED)

image859×815 115 KB

Context:
I found such a solution using pandas round function and gb.configure_column
df_exc['Env_Oran']= df_exc['Env_Oran']*100
 #df_exc['Env_Oran']= df_exc['Env_Oran'].round(2)
 if os.path.exists(yol)==True:
  'Dosya Burda bir daha hesaplama'
 else:
  'Dosya yok'
 gb = GridOptionsBuilder.from_dataframe(df_exc)
 gb.configure_pagination()
 gb.configure_column("Env_Oran", type=["customCurrencyFormat"], custom_currency_symbol="%")


Question:
@whitphx  I am trying to convert my code from pyaudio to webrtc.
This is how I am currently consuming the audio input from Microphone. I see that Webrtc uses pydub instead of pyaudio. How can I convert this to webrtc?
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms
with MicrophoneStream(RATE, CHUNK, device=args.input_device) as stream:
        audio_generator = stream.generator()

class MicrophoneStream(object):
    """Opens a recording stream as a generator yielding the audio chunks."""

    def __init__(self, rate, chunk, device=None):
        self._rate = rate
        self._chunk = chunk
        self._device = device
        # Create a thread-safe buffer of audio data
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            input_device_index=self._device,
            channels=1,
            rate=self._rate,
            input=True,
            frames_per_buffer=self._chunk,
            stream_callback=self._fill_buffer,
        )
        self.closed = False
        return self

    def __exit__(self, type=None, value=None, traceback=None):
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)
        self._audio_interface.terminate()

    def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
        """Continuously collect data from the audio stream, into the buffer."""
        self._buff.put(in_data)
        return None, pyaudio.paContinue

    def generator(self):
        while not self.closed:
            chunk = self._buff.get()
            if chunk is None:
                return
            data = [chunk]
            while True:
                try:
                    chunk = self._buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break
            yield b''.join(data)

    def stop(self):
        self.__exit__()

Context:
I can’t help because I’m not familiar with PyAudio.
If there are anyone who have experiences with PyAudio, please answer this question.
What I can say is that pydub is not mandatory to deal with audio streams with streamlit-webrtc. I just used it in the sample app as an example, but it’s independent from WebRTC stuff.

Crossposted to

      github.com/whitphx/streamlit-webrtc

      Converting PortAudio to Webrtc

        opened

        Jan 19, 2022

          arunraman

    I am trying to convert my code from pyaudio to webrtc.

This is how I am curr…ently consuming the audio input from Microphone. I see that Webrtc uses pydub instead of pyaudio. How can I convert this to webrtc?

```
RATE = 16000
CHUNK = int(RATE / 10)  # 100ms
with MicrophoneStream(RATE, CHUNK, device=args.input_device) as stream:
        audio_generator = stream.generator()
```

```
class MicrophoneStream(object):
    """Opens a recording stream as a generator yielding the audio chunks."""

    def __init__(self, rate, chunk, device=None):
        self._rate = rate
        self._chunk = chunk
        self._device = device
        # Create a thread-safe buffer of audio data
        self._buff = queue.Queue()
        self.closed = True

    def __enter__(self):
        self._audio_interface = pyaudio.PyAudio()
        self._audio_stream = self._audio_interface.open(
            format=pyaudio.paInt16,
            input_device_index=self._device,
            channels=1,
            rate=self._rate,
            input=True,
            frames_per_buffer=self._chunk,
            stream_callback=self._fill_buffer,
        )
        self.closed = False
        return self

    def __exit__(self, type=None, value=None, traceback=None):
        self._audio_stream.stop_stream()
        self._audio_stream.close()
        self.closed = True
        # Signal the generator to terminate so that the client's
        # streaming_recognize method will not block the process termination.
        self._buff.put(None)
        self._audio_interface.terminate()

    def _fill_buffer(self, in_data, frame_count, time_info, status_flags):
        """Continuously collect data from the audio stream, into the buffer."""
        self._buff.put(in_data)
        return None, pyaudio.paContinue

    def generator(self):
        while not self.closed:
            chunk = self._buff.get()
            if chunk is None:
                return
            data = [chunk]
            while True:
                try:
                    chunk = self._buff.get(block=False)
                    if chunk is None:
                        return
                    data.append(chunk)
                except queue.Empty:
                    break
            yield b''.join(data)

    def stop(self):
        self.__exit__()
```


Selection is sometimes not returned from custom widgets

Question:
Hi,
I have a streamlit app which uses the AgGrid component to make rows in a table selectable and the plotly_events component to get feedback from clicked points in charts.
Both components show the same behaviour, that the feedback sometimes just doesn’t work and the return value is emtpy. It does however work sometimes, like 50% of the time, so I am not sure if this is a bug on the streamlit side since it happends for both components independently.
Has anybody obvserved similar issues?
streamlit version is 1.3.1

Context:
I managed to build a minimal example for this which has a quite interesting behaviour.
The selection feedback of AgGrid works in this code but if I remove the caching of the dataframe it breaks it.
I have seen somewhat similar issues with selection feedback with the plotly_events component as well so possibly it is a streamlit side bug.
How to reproduce:

start the app and select some rows
press submit, it will display the selected rows
now comment out the caching line in the code
reload the page and repeat the first two steps, for me the selection no longer works now

import streamlit as st
from st_aggrid import AgGrid, GridOptionsBuilder
import pandas as pd
import numpy as np

@st.experimental_memo # commenting this line out breaks the selection feedback for me as the "selected_rows" entry in the grid_response is always empty
def get_df():
    df = pd.DataFrame(columns=['foo','bar','baz'], data=np.random.choice(range(10), size=(100000,3)))
    return df

df = get_df()

gb = GridOptionsBuilder.from_dataframe(df)
gb.configure_default_column(value=True, enableRowGroup=True, aggFunc=None, editable=False)

gb.configure_selection(selection_mode="multiple", use_checkbox=True)

with st.form("table_form", clear_on_submit=False):
    grid_response = AgGrid(df, gridOptions=gb.build(), height=700, data_return_mode="AS_INPUT", update_mode="SELECTION_CHANGED")#, enable_enterprise_modules=True)#.style.apply(highlight_clusters, axis=1))

    st.write(f"grid_response {grid_response}")
    selected = grid_response['selected_rows']
    st.write(f"selected {selected}")
    if st.form_submit_button("Submit"):
        pass


Best (fastest) practice to display live 2D data

Question:
Dear all!
I have a detector which produces 2D images at video rates and higher. However, for live imaging rates in the range 10 Hz and more would be sufficient. Data comes as numpy arrays.
I face problems, when I want to display the data at the wanted rates.
The following code mocks up different ways to do this with streamlit. I am by no means a python - and especially no asyncio - expert, though.

display, get the data, rerun
get the data, display, rerun
do displaying and data taking asynchronously

The third option does not need a st.experimental_rerun(). Part of the communication is done via streamlit’s st.sessions_state which is not always mandatory, but keeps the examples as similar as possible.
Version 2 does not work well at all. I see only a grayed out image.
Versions 1&3 only work up to delays of about 0.25 secs, only
I am doing this out of my home office using a ssh tunnel to a server at work over 100 MBit/s connection.
I have no idea how to speed up this, but I guess that there is a way,  as for example watching youtube videos about streamlit is not a problem at all.
Perhaps streamlit is not the way to go for this type of application?
Thanks a lot for any thoughts on this!
Best wishes
Markus
import streamlit as st
import numpy as np
import time
import asyncio

# --------------------------------------------------------------

def ui():
    if 'image' in st.session_state:
        st.image(st.session_state['image'])

def work(delay):
    time.sleep(delay)
    st.session_state['image'] = np.random.random((512, 512))

# --------------------------------------------------------------
# --------------------------------------------------------------

async def async_ui():
    with st.session_state['placeholder']:
        ui()
    r = await asyncio.sleep(0.01)

async def async_work(delay):
    work(delay)
    r = await asyncio.sleep(0.01)

# --------------------------------------------------------------
# --------------------------------------------------------------

def work_before_display(delay=1):
    work(delay)
    ui()

# --------------------------------------------------------------

def display_before_work(delay=1):
    ui()
    work(delay)

# --------------------------------------------------------------

async def do_all_asynchronously(delay=1):

    if 'tasks' in st.session_state:
        for t in st.session_state['tasks']:
            t.cancel()
    coroutines = [async_work(delay), async_ui()]
    tasks = []
    for s in coroutines:
        tasks.append(asyncio.ensure_future(s))
    if tasks:
        st.session_state['tasks'] = tasks
        res = await asyncio.gather(*tasks)

if __name__ == '__main__':

    if 'placeholder' not in st.session_state:
        st.session_state['placeholder'] = st.empty()

    delay = 0.25
    #display_before_work(delay=delay)

    #work_before_display(delay=delay)

    asyncio.run(do_all_asynchronously(delay=delay))

    st.experimental_rerun()

see also

    Avoid fading output during longer background activity Using Streamlit

    following up on this:
what I did in my script was, that I separated calculation/data acquisition tasks, work(), from the stuff that does the displaying via streamlit, ui(). The script first runs ẁork() followed by ui(). What I observed, was that work() blocked part of streamlit activity which resulted in grayed-out widgets.
However, I now simply reversed the sequence, i.e. first ui() and than work(), which leads to better displaying performance. It might be necessary to do a st.experimental_re…

    Issue with asyncio run in streamlit Using Streamlit

    Hi guys !
I was trying to get something with a stream working in streamlit. ( no pun intended )
I tried a couple of approaches with threading and finished my search on asyncio.run with a small coroutine and for the most part it works really well. No need for any fancy code just a asyncio.run at the end. But there’s a small problem, I am seeing None printed at every run of loop.
Any idea what might be causing this ?
This is my script I am using to show a simple clock
import asyncio
import st…

Context:
an addition:
after some time variant 1 errors with
RecursionError: maximum recursion depth exceeded in comparison
  You can now view your Streamlit app in your browser.

  URL: http://127.0.0.1:8501

2021-12-10 09:50:02.755 InMemoryFileManager: Missing file 4f237411c238189ad04bff875b2cbae4ea5ef8e4c979c3413999b321.jpeg
2021-12-10 09:50:52.730 Traceback (most recent call last):
  File ".../lib/python3.8/site-packages/streamlit/script_runner.py", line 354, in _run_script
    exec(code, module.__dict__)
  File ".../test.py", line 55, in <module>
    display_before_work(delay=delay)
  File ".../test.py", line 39, in display_before_work
    ui()
  File ".../test.py", line 23, in ui
    st.image(st.session_state['image'])
  File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 120, in image
    marshall_images(
  File ".../python3.8/site-packages/streamlit/elements/image.py", line 370, in marshall_images
    proto_img.url = image_to_url(
  File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 272, in image_to_url
    data = _np_array_to_bytes(data, output_format=output_format)
  File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 181, in _np_array_to_bytes
    return _PIL_to_bytes(img, format)
  File ".../lib/python3.8/site-packages/streamlit/elements/image.py", line 167, in _PIL_to_bytes
    image.save(tmp, format=format, quality=quality)
  File ".../lib/python3.8/site-packages/PIL/Image.py", line 2240, in save
    save_handler(self, fp, filename)
  File ".../lib/python3.8/site-packages/PIL/JpegImagePlugin.py", line 745, in _save
    if isinstance(exif, Image.Exif):
  File ".../lib/python3.8/abc.py", line 98, in __instancecheck__
    return _abc_instancecheck(cls, instance)
RecursionError: maximum recursion depth exceeded in comparison


Question:
从官网拷贝下来的代码，为什么运行时报错呢，缺少什么文件吗？

image810×716 39.7 KB

image715×829 57.6 KB

Context:
可以试试Pymysql, 也可以关注微信公众号：Streamlit
里面有连接数据库的案例


Question:
Hi guys. Is there a way to display text in a justified way? Like we have in Microsoft Word?
e.g:

Context:
Hi @feliperoque -
It appears that you can do so using CSS, though this article suggests that maybe you shouldn’t:

      Design for Hackers – 14 Aug 14

Justify text with HTML/CSS? Don't do it! - Design for Hackers 1

  It’s 3 in the morning, and you’re putting the final touches on your layout. It looks clean, with everything in its place – lined up on the grid. You squint from afar. “The edges of these type blocks look uneven,” you say to yourself. You...

    Est. reading time: 4 minutes

How to add CSS to a Streamlit app using st.markdown is demonstrated here:

    Changing the default text "Choose an option" from a multiselect widget Using Streamlit

    Hi @NiklausBal, welcome to the Streamlit community!!
Streamlit does not expose the option to change the placeholder text for st.multiselect. As such, there is no native option to change the placeholder because it is hard-coded in the frontend.
However, here is an unofficial CSS hack. I used a CSS selector to first make the default placeholder invisible. Next, I use another CSS selector to set the value of the placeholder. This CSS is injected into the app with st.markdow…

Best,
Randy


Getting error:[manager] Error checking Streamlit healthz: Get “http://localhost:8501/healthz”:

Question:
Hello, I successfully deployed my app in streamlit
But when I try to run it more than 3 time, It crashes.
The log says
[manager] Error checking Streamlit healthz: Get "http://localhost:8501/healthz":  dial tcp 127.0.0.1:8501: connect: connection refused  [manager] Streamlit server consistently failed status checks
I understand the error is because of resource allocation,
but I am using st.cache here, so the file won’t be downloaded again
@st.cache
def download1(url1):
    url = url1
    filename = url.split('/')[-1]
    urllib.request.urlretrieve(url, filename)

download1(“https://github.com/Anubhav1107/streamlit/releases/download/fasterrcnn.pth/fasterrcnn.pth 1”)
The app is in
https://share.streamlit.io/anubhav1107/streamlit/streamlit.py 16
Thanks

Context:
Hi @Anubhav1107 -
In looking at your app, unfortunately I think this has to do with using Torch. As far as I can tell, your app doesn’t have any obvious flaws, but Torch is such a big dependency that running your app a few times then exhausts all available RAM, which causes the error you are seeing.
I’ll forward this thread on to our product and cloud teams, so they can have another example and possibly find a solution for this.
Best,
Randy


Unable to clear or delete columns from ‘beta_columns’

Question:
I’m trying to do a live interactive scorer of NBA games, but I’m having troubles at updating this scorer. To set this scorer I use the beta_columns component the way you can see in this function:
# Dado unos datos necesarios, muestra un cabecero de página con la información relevante sobre un encuentro de la NBA en directo
def show_live_match_header(home_score, away_score, home_team, away_team, date, hour, quarter, minutes_left):

	# Definimos 5 columnas para mostrar el resultado actual del partido en cada instante
	col1, col2, col3, col4, col5 = st.beta_columns([4, 3, 4, 3, 4])

	quarter_ending = "er"
	if quarter == 2:
		quarter_ending = "do"
	elif quarter == 1 or quarter == 3:
		quarter_ending = "er"
	elif quarter == 4:
		quarter_ending = "to"

	# Añadimos objetos a la primera columna relacionados con el equipo local
	with col1:
		st.markdown('', unsafe_allow_html=True)
		st.markdown("
" + home_team + "
", unsafe_allow_html=True)
		st.markdown("
 (Local)
", unsafe_allow_html=True)

	# Añadimos objetos a la segunda columna relacionados con la puntuación del equipo local en este instante
	with col2:
		st.write("")
		st.write("")
		st.write("")
		if home_score == -1 or away_score == -1:
			st.markdown("
" + "-" + "
", unsafe_allow_html=True)
		else:
			st.markdown("
" + str(home_score) + "
", unsafe_allow_html=True)
		st.write("")
		st.write("")
		st.write("")

	# Añadimos objetos a la tercera columna relacionados con información del partido como el minuto en el que está en este mismo instante
	with col3:
		st.write("")
		st.write("")
		st.write("")
		if home_score == -1 or away_score == -1:
			st.markdown("
" + "El partido no ha comenzado aún" + "
", unsafe_allow_html=True)
			st.markdown("
 Hora del comienzo del partido: " + hour + "
", unsafe_allow_html=True)
			st.markdown("
 (" + date + ")
", unsafe_allow_html=True)
		else:
			st.markdown("
 " + str(quarter) + quarter_ending + " Cuarto   " + str(minutes_left) + "'
", unsafe_allow_html=True)
			st.markdown("
 (" + date + ", " + hour + ")
", unsafe_allow_html=True)
		st.write("")
		st.write("")

	# Añadimos objetos a la cuarta columna relacionados con la puntuación del equipo visitante en este instante
	with col4:
		st.write("")
		st.write("")
		st.write("")
		if home_score == -1 or away_score == -1:
			st.markdown("
" + "-" + "
", unsafe_allow_html=True)
		else:
			st.markdown("
" + str(away_score) + "
", unsafe_allow_html=True)
		st.write("")
		st.write("")
		st.write("")

	# Añadimos objetos a la primera columna relacionados con el equipo local
	with col5:
		st.markdown('', unsafe_allow_html=True)
		st.markdown("
" + away_team + "
", unsafe_allow_html=True)
		st.markdown("
 (Visitante)
", unsafe_allow_html=True)

	col5 = st.empty()

	return [col1, col2, col3, col4, col5]

This way I obtain this results:

Example of using the method once1918×1004 75.2 KB

The problem comes when I try to remove the beta_columns returned in order to set new ones with each score updated. I tried to do this by this example code:
	# Definimos las estructuras que se mostrarán en la interfaz
	session_state.counter = -1
	match_header = None

	while session_state.counter < 5:
		if match_header is not None:
			for col in match_header:
				col.empty()

		home_score = away_score = session_state.counter
		match_header = show_live_match_header(home_score, away_score, session_state.home_team, session_state.away_team, session_state.date, session_state.hour, 1, 10)
		session_state.counter = session_state.counter + 1
		sleep(1)

Obtaining this awful result:

Awful Result :(1918×1006 151 KB

I tried a lot of things, but I can’t delete the previous columns before setting the new ones. Is there another way to do this update or a chance of deleting the previous columns?

Context:
Hi @Agustin_6199 ,
Do you solve this problem? because I have the same one
Tanks a lot


Change breakpoint of columns (for mobile)

Question:
I am developing an application that depicts various metrics on the same row, similar to the example in the documentation (Streamlit 1).
Similar to the example provided in the documentation, the columns stack on mobile. Eventhough, it  seems that two columns can easily fit on the same row on mobile. How can I prevent that the columns are stacked, when there is enough room for two or more columns on the same row? Is it possible to change the breakpoint?

Context:
Hi @remcoloof, welcome to the Streamlit community!
Unfortunately, no, setting the breakpoints isn’t a functionality that we currently expose. It may be the case that you could specify your own CSS, but that might lead to weird blinking artifacts. To see an example of how to write CSS using st.markdown, please see the link below:

    Changing the default text "Choose an option" from a multiselect widget Using Streamlit

    Hi @NiklausBal, welcome to the Streamlit community!!
Streamlit does not expose the option to change the placeholder text for st.multiselect. As such, there is no native option to change the placeholder because it is hard-coded in the frontend.
However, here is an unofficial CSS hack. I used a CSS selector to first make the default placeholder invisible. Next, I use another CSS selector to set the value of the placeholder. This CSS is injected into the app with st.markdow…

Best,
Randy


Question:
Hello guys ,
I would like to get an appending boolean button (it displays a STOP button and when I click on it , it becomes a START button) in the “Start/Stop of BOT”
coins_list = ['BTC','LTC','ETH'] #

@st.cache(allow_output_mutation=True)
def Input_Parameters():
	return []

coin = st.selectbox('Search COIN',coins_list)
st.write(coin)
X1 = st.number_input('Provide Value for X1', min_value = 000000.00000 , max_value = 99999.9999 , step = 1e-5)
st.write(X1)
Y1 = st.number_input('Provide Value for Y1', min_value = 000000.00000 , max_value = 99999.9999, step = 1e-5)
st.write(Y1)
Z1 = st.number_input('Quantity Z1', min_value = 000000.00000, max_value = 99999.9999, step = 1e-5)
st.write(Z1)
n_loop = st.number_input('Provide Value for N (Loop)',min_value = 1 ,max_value = 99999, step = 1)

current_price = web.DataReader(coin + "-USD","yahoo","2018-1-1",dt.now())["Close"][-1]
TradingTime = dt.now().strftime("%m-%d-%Y at %H:%M:%S")
st.write("current price of the coin : " + str(current_price))

col1, col2, col3,col4,col5 = st.columns(5)

with col3:
   	start = st.button("Start the Bot")

commission = 0 #current_price*(1/100)
profit = 0

df = pd.DataFrame(Input_Parameters())
session_state = SessionState.get(df=df)

if start :

	status = "Running"
	session_state.df = session_state.df.append(
		{"Trading Time" : TradingTime ,
		"coin pair" : coin,
		"Status": status,
		"Start/Stop of BOT": st.button("STOP"),
		"Current Price of the coin pair": current_price,
		"Comission Detected": commission,
		"profit made": profit
		},ignore_index=True
	)

Thanks for your help

Context: anyone guys ???


Load and Display Files from Local Storage

Question:
Hey Guys,
I have a file manager that lists all uploaded files from the upload section.
My question is, how can I retrieve my files from my tempDir and display them?
os.open just gives me a string than the actual data:

Bildschirmfoto 2022-01-14 um 11.46.202156×1380 202 KB

below is my code:
 # my files menu
    if (choice == menu[1]):
        col1, col2, col3 = st.columns([4, 1, 1])
        fileList = []
        filePaths = []
        fileId = 0

        for root, dirs, files in os.walk("tempDir"):
            for file in files:
                filePath = os.path.join(root, file)
                fileName = os.path.join(file)
                fileList.append(fileName)
                filePaths.append(filePath)
        for item in fileList:
            fileKey = "fileKey_{}".format(fileId)
            with st.expander(item):
                with open(filePaths[fileId], 'rb') as file:
                    agree = st.checkbox('Display Data 📊', key=fileKey)
                    if agree:
                        st.write(file)
                        st.download_button("Download", item, key=fileKey)
                fileId += 1

        st.selectbox("Select Item", fileList)
        with st.expander("Raw Output"):
            st.write(fileList)

Context:
Hi @fuccDebugging -
I’m not sure I understand your question. You are retrieving files from the local filesystem and open doesn’t work?
Best,
Randy


Performance Problems with many small dataframes

Question:
I have an streamlit app that I use as a labeling tool.
The user gets a list of many small dataframes with a checkbox each and a submit button at the end of the form to submit the labels.
When I use st.write to write the dataframes to the browser, the browser has serious performance issues (100% cpu usage on one core that does not go away). The server side script has no performance problems.
When I use the AgGrid Component instead of st.write to write the dataframes, then I don’t see this issue.
Just wanted to let you guys know about this.

Context:
Hi @thunderbug1 -
Do you have a code example that demonstrates this?
Best,
Randy


Is it possible to run a local script from my streamlit app with a button?

Question:
Hi there, in my app I have another script that updates data from yahoo finance. I am wondering if it is possible to run this script from my streamlit app.
Thank you,
J

Context:
Hi @jorgeggpool, welcome to the Streamlit community!
In general, the answer is almost always ‘yes’, it’s just a matter of figuring out the syntax. What have you tried so far?
Best,
Randy


File_uploader DuplicateWidgetID key error

Question:
I want to receive different data sheets from users.First, users need to click to determine their own data table type; Then upload the file; After that, the program performs a series of operations.
But the problem I encounter is that when the user changes the options, the previously uploaded files will not disappear.When the file is manually closed and uploaded again, an error will be reported.
The following is my code. In order to facilitate understanding, I simplified some programs, but the functions are consistent
def getFile():
    uploaded_file = st.file_uploader("Please")
    if uploaded_file is not None:
        df = pd.read_excel(uploaded_file)
        AgGrid(
            df.head(3),
            fit_columns_on_grid_load=False,
            height=120,
            editable=False,
        )

        return df

if __name__ == '__main__':
    a=input()
    if a=='a':
        data=getFile()
        # ... ...
    else:
        data=getFile()
        # ... ...

Context:
Hi @Dcclandbest, welcome to the Streamlit community!
When you place uploaded_file = st.file_uploader("Please") inside of a function that is called over and over again, you are creating a new instance of file_uploader each time rather than re-using the same one over and over. And because you create several instances of file_uploader, it’s yelling that you don’t have a key argument to make each of them have a unique identifier.
I suspect moving that line outside of the function will fix your issue.
Best,
Randy


What is the error with my project? This is my first time doing this

Question:
By the way this is my repository.
•SpeechEmoRec/sample.py at main · jonsarz16/SpeechEmoRec · GitHub 1
This is the response i get…[picture]

XRecorder_13012022_1734291080×1920 278 KB

Context:
Hi @jonsarz16, welcome to the Streamlit community!
In your screenshot, the black button “Manage app” shows the actual logs, which frequently shows the error. Can you open that panel and copy what you see there into this thread?
Best,
Randy


Question:
After I successfully install streamlit-1.3.1,an ImportError comes forth when I import streamlit (python version:3.7.11).I don’t know how to fix it.
Here is my code

image1289×596 108 KB

Context:
Hi @phoenix -
It looks like one of the packages you are trying to use requires zoneinfo, which if I’m reading the docs correctly only became available in Python 3.9 (you’re using Python 3.7).
Best,
Randy


Question: Whenever I try to plot the latitudes and longitudes spread all over the USA map using streamlit.map() function it works fine but, when the map pops up I have to hover over the desired location and zoom it in order to see the red points plotted. How can I make those points visible without zooming in the map?

Context:
Hi @ShivamBhirud welcome to the community and sorry this isn’t working for you. St.map is meant to be a very simple and straightforward function and unfortunately doesn’t allow a lot of customization like setting radius size (and obviously defaults to a too small size!). I went ahead and made a bug report for this that you can track here: https://github.com/streamlit/streamlit/issues/577 192
The good news is you can use deck.gl to make your map; st.deck_gl_chart is a little more code but a lot more customizable. Here’s an example of setting the zoom location, adding a radius, setting a minimum radius, and also changing the color of the dots to hot pink:
data = pd.DataFrame({
    'awesome cities' : ['Chicago', 'Minneapolis', 'Louisville', 'Topeka'],
    'lat' : [41.868171, 44.979840,  38.257972, 39.030575],
    'lon' : [-87.667458, -93.272474, -85.765187,  -95.702548]
})

# Adding code so we can have map default to the center of the data
midpoint = (np.average(data['lat']), np.average(data['lon']))

st.deck_gl_chart(
            viewport={
                'latitude': midpoint[0],
                'longitude':  midpoint[1],
                'zoom': 4
            },
            layers=[{
                'type': 'ScatterplotLayer',
                'data': data,
                'radiusScale': 250,
   'radiusMinPixels': 5,
                'getFillColor': [248, 24, 148],
            }]
        )

Let me know if there’s anything else I can help with!


Question:
Hi,
I’m getting a warning  - I’ve looked at other threads but still can’t figure it out on my use case.
Here is my code in it’s entirety:
import pandas as pd

from causalimpact import CausalImpact

import streamlit as st

df = pd.DataFrame({'date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06'],

                   'value': [1539, 1696, 1427, 1341, 1426, 1471]})

def get_pre_post(data, change):

    pre_start = min(data.index)

    pre_end = int(data[data['date'] == change].index.values)

    post_start = pre_end + 1

    post_end = max(data.index)

    pre_period = [pre_start, pre_end]

    post_period = [post_start, post_end]

    return pre_period, post_period

change = '2021-01-05'

pre_period, post_period = get_pre_post(df, change)

ci = CausalImpact(df.drop(['date'], axis=1), pre_period, post_period, prior_level_sd=None)

fig = ci.plot()

st.pyplot(fig)

Screenshot 2022-01-19 112623809×832 69.7 KB

Any help is much appreciated (I don’t want to just disable the warning)

Context:
Hi @Grainger,
This was a tricky one to figure out. I inspected the plotting source code of the pycausalimpact package and found that the ci.plot() method does not return any object. Instead, it calls plt.show().
What needs to be done is to use matplotlib get the current figure and current axes created when ci.plot() is called, and pass the resulting figure to st.pyplot(). Here’s how to do it:

Solution
import pandas as pd
import matplotlib.pyplot as plt # required later
from causalimpact import CausalImpact

import streamlit as st

df = pd.DataFrame({'date': ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', '2021-01-05', '2021-01-06'],

                   'value': [1539, 1696, 1427, 1341, 1426, 1471]})

@st.experimental_memo
def get_pre_post(data, change):
    pre_start = min(data.index)
    pre_end = int(data[data['date'] == change].index.values)
    post_start = pre_end + 1
    post_end = max(data.index)
    pre_period = [pre_start, pre_end]
    post_period = [post_start, post_end]

    return pre_period, post_period

change = '2021-01-05'

pre_period, post_period = get_pre_post(df, change)

ci = CausalImpact(df.drop(['date'], axis=1), pre_period, post_period, prior_level_sd=None)

ci.plot()

fig = plt.gcf() # to get current figure
ax = plt.gca() # to get current axes

st.pyplot(fig)

Output

image1182×1051 139 KB

Happy Streamlit-ing!
Snehan


How to reset the cache after a fixed frequency?

Question:
Hi ,
I have user case where dashboard base data gets updated in every 1 hour. For good response time I have used cache before data loading function. How I can make cache clear after say 1 hour so that user will see the refreshed data on dashboard.
Thanks,
Manoj Kumar

Context:
Can any one help on this?
Thanks


Question:
Hi everyone!
I have five checkboxes. When some of them are selected, I want my dataframe to be filtered on some specific condition. Additionally, values should be filtered with the AND logic. For example:
if filter1 & filter2:
   df = df .loc[(some condition of filter1) & (some condition of filter2)]

However, having five filters, I have to use a lot of different combinations to implement such logic (e.g. if filter1 & filter3, if filter1 & filter4, if filter1 & filter3 & filter4, and so on).
Is there is a more effective way to do it without going through all the filters combinations in if statements?
I checked this solution, however, it is applicable for sliders only as I understand it:

    Filter logic Using Streamlit

    Hi pvtaisne,
See below for an example with multiple filters for one dataframe. Let me know if it helps you
import streamlit as st
import pandas as pd
import numpy as np

np.random.seed(0)  # Seed so random arrays do not change on each rerun
n_rows = 1000
random_data = pd.DataFrame(
    {"A": np.random.random(size=n_rows), "B": np.random.random(size=n_rows)}
)

sliders = {
    "A": st.sidebar.slider(
        "Filter A", min_value=0.0, max_value=1.0, value=(0.0, 1.0), step=0.01
  …

I would highly appreciate any help!

Context:
Hi, you could try doing it this way:

Start with a blank string (Eg. querystr = ‘’)
Using your checkboxes, you can incrementally construct your combined filter, appending the result to querystr. (Eg. querystr = querystr + "Gender == ‘M’ "

Gender would be the dataframe field and ‘M’ could be check box value.
Similarly continue with your other checkboxes…
querystr = querystr + "Race == ‘White’ ") will make the resultant query string for Gender as well as Race… And so on…
Finally, you can use df.query
Refer internet help docs as needed.
Hope this helps,


Question:
Hi,
I am trying to link a JS library for 360 photo viewer with streamlit. The photo was loaded, but the it looks like the JS library wasn’t loaded properly with the photo not being able to be interacted with.
Anyone has experienced similar issues?
Cheers,
Will
import streamlit as st

def main():
    st.set_page_config(page_title='BKN 360 Photo App', initial_sidebar_state = 'auto')
    #page_icon = favicon,
    st.markdown(
            f"""
            <style>
                .reportview-container .main .block-container{{
                    max-width: 1200px;
                    padding-top: 1rem;
                    padding-right: 1rem;
                    padding-left: 1rem;
                    padding-bottom: 1rem;
                }}

            </style>
            """,
            unsafe_allow_html=True,
        )

    # main section
    st.subheader('Web 360 Photo App')
    st.markdown('<script src="https://aframe.io/releases/0.6.1/aframe.min.js"></script>', unsafe_allow_html=True)
    st.markdown("""
    <a-scene>
        <a-assets>
            <img id="panorama" src="https://c1.staticflickr.com/5/4302/35137573294_1287bfd0ae_k.jpg" crossorigin />
        </a-assets>
        <a-sky src="#panorama" rotation="0 -90 0"></a-sky>
    </a-scene>
    """, unsafe_allow_html=True)

if __name__ == "__main__":
    main()

Context:
st.markdown won’t work with js
you could use components.html from import streamlit.components.v1 as components


Only allow the data type str for the st.text_input widget

Question:
I saw a question on StackOverflow that I wanted to answer and I stumbled upon following problem.
Suppose you want to restrict the user input from the st.text_input widget. E.g. the user can only type in strings. How would you do that?
My attempt:
import streamlit as st

def main():
    st.title("Only allow text example")

    #only allow strings
    text = st.text_input('Type something', value=str)

    #conditional statement to check if the input is a string
    if type(text) == str:
        st.write(text + ' ' + ' ...works as its a string')

    else:
        type(text) != str
        st.write("Please enter a string")

if __name__ == "__main__":
    main()

If I type in 1234 as the input it outputs …1234… works as its a string.
I read the documentation for this widget
docs for st.input_text → st.text_input - Streamlit Docs
…and I know the type argument is good for hiding the text input but I don’t know what the value argument is doing. I feel like by default all that you type into the widget is a string.
Wrapping everything up into a str() is also not advisable.
text = str(st.text_input('Type something', value=str))

Context:
Okay I found a solution.
text.isaplha( ) works to check for the input.
import streamlit as st

def main():
    st.title("Only allow text example")

    #only allow strings
    text = str(st.text_input('Type something'))

    #conditional statement to check if the input is a string
    if text.isalpha():
        st.write(text, '...works as its a string', )
    else:
        st.write('Please type in a string ')

if __name__ == "__main__":
    main()

So a mixture of strings and integers doesn’t work for the input any more …
Input: 123abc
Output: Please, enter a string


Question:
Hi Guys,
First of all, I would like to appreciate the entire Streamlit team for creating such an amazing and simple to use framework for creating beautiful apps. It is simply amazing.
I work as an auditor in an ed-tech organization. Part of my work involves creating interactive reports of the audits conducted so far. For this purpose, I am using Google’s Data Studio to create an interactive report. A google sheet here works as the report’s data source, so whenever a new row is added in the google sheet, the report gets updated automatically.
Now, I am trying to take things to the next level by making an amazing app using Streamlit. I have some familiarity with Python already and would need some help to start creating this app. It would be great if you can point me in the right direction as to how we can connect google sheets to streamlit.
Thank you in advance!

Context:
Hi @aakash_chaudhry, welcome to the Streamlit community!
Here’s the official package for Google Sheets:

      Google Developers

Python Quickstart  |  Sheets API  |  Google Developers 104

There is also a package that will read Google Sheets into a pandas dataframe. Once you have a pandas dataframe, Streamlit supports pandas pretty seamlessly:

      PyPI

gspread-pandas 99

A package to easily open an instance of a Google spreadsheet and interact with worksheets through Pandas DataFrames.

Best,
Randy


Question:
My target:

Enter a key in text box, the App will run a query and return a list of options.
For each option, display a checkbox and check it by default.
The options from step 1 are likely to be the same among different runs but with small difference.
I don’t want to use multiselect drop down here.

The issue:

If I uncheck a checkbox, the state will be memorized even if the checkbox is regenerated.
Yes I tried to give the a unique id for each checkbox but it will keep resetting every checkbox.

A example code:
import streamlit as st
import numpy as np

def main():
    case_id = st.text_input("Please enter an ID")
    if case_id:
        options = sorted(np.random.choice([1,2,3,4,5], 4, replace=False))
        pathways_bool = [st.checkbox(str(_x),True) for _x in options]

if __name__ == "__main__":
    main()

Thanks for your help!

Context:
Hey @w-markus,
First, welcome to the Streamlit Community!
and @h3045,
With st.session_state you can have the checkbox un-check on a re-run using the on_change parameter. But as no one has posted a code example of how to reproduce this, or of the functionality you are trying to achieve it’s difficult to point you in the right direction.
Session State blog post and examples 40
Does anyone have an MVP they can post that I can try locally?
Happy Streamlit-ing!
Marisa


Format Integer With Comma Using Python Printf

Question:
I have built a slider that has integer values between, say, 0 and 2,000,000. I would like to display the numbers with thousands-commas-separator. The documentation states:
format (str or None) – A printf-style format string controlling how the interface should display numbers. This does not impact the return value. Valid formatters: %d %e %f %g %i

But it isn’t clear how I could accomplish this with the format argument.
Usually, in Python, this can be accomplished with:
x = 1000000
print(f"{x:,}")
# 1,000,000

Context:
Hey @Sean,
Welcome to the forum
We use the sprintf-js 53 library to handle string formatting in the client.
I don’t believe this is currently possible, after looking at their documentation.
Feel free to file a feature request for this functionality!
However I’m not sure we’ll get to it right away, given the diversity of formats that could possibly be requested.
Also, we’ve started development on plugins, so this is something you should be able to build yourself in the near future!


After the session state being introduced how do I create a reset button

Question:
I am now trying to create a reset button that allow the user to uncheck the boxes of all the checkboxes selected by user the Session state Example here streamlit reset app via button
is good but I am creating a reproducible app and hence need to use session state api but I am not able to do it.
What I tried was
if 'celcius' not in st.session_state:
    st.session_state.celsius = False

st.checkbox(
    "Temperature in Celsius",value=st.session_state.celsius
)
a=st.button('Reset')
if a:
    st.session_state.celsius=False

but the checkbox does not change until I clear cache which is the last resort all I want is to give the user a freedom to reselect columns if he want to create different query (the button are query and reset query brings a set columns selected by user through checkbox and reset allows user to nullify selection and select again for different query)

Context: no matter what I try like chaging it to true then false the or any combination even with callback does not reset the checkbox unless I clear cache


How to Create Wizard Style App (Step 1, Step 2, Etc)

Question:
I’m struggling with way to create a fixed number of steps a user can take to use the App.  I’ve landed on using st.empty() and works up to first  two steps, then resets back to beginning after trying to move to first step.  Looking for suggestions!  Thank you
def write():
    shown_page = 'intro'
    if shown_page == "intro":
        contIntro = st.empty()
        expIntro = contIntro.expander('What App Wizard Can Do', True)
        job_name = expIntro.text("Give this Job a Name")
        col1, col2 = expIntro.columns([9,1])
        col1.write("")
        exp1_button = col2.button('To Step 1')

        if exp1_button:
            contIntro.empty()
            shown_page = 'Step 1'

    if shown_page == 'Step 1':
        header_text = 'Step 1'
        cont1 = st.empty()
        exp1 = cont1.expander('Step 1 of 2', True)
        exp1.file_uploader('Upload Data', type=None, accept_multiple_files=False)
        col1, col2 = exp1.columns([9,1])
        col1.write("")
        exp1_back_button = col1.button('Back to Intro')
        exp1_next_button = col2.button('To Step 2')

        if exp1_back_button:
            cont1.empty()
            shown_page = 'Intro'

        if exp1_next_button:
            cont1.empty()
            shown_page = 'Step 2'

    if shown_page == 'Step 2':
        header_text = 'Step 2'
        cont2 = st.empty()
        exp2 = cont2.expander("Step 2 of 2", True)
        job_name = exp2.text_input("Some more info")
        col1, col2 = exp2.columns([9,1])
        exp2_back_button = col1.button("Back to Step 1")
        exp2_forward_button = col2.button('To Another Setp in Future')

        if exp2_back_button:
            upload_data.write()

        if exp2_back_button:
            cont2.empty()
            shown_page = 'Step 2'

        if exp2_forward_button:
            cont2.empty()

image1878×453 5.74 KB

Then moves to Step 1 when hit ‘To Step 1’

image1779×530 7.43 KB

Then I hit ‘To Step 2’ and it brings me back to Intro, when I’d expect to move to Step 2

Context:
Hi @saxon11 , take a look at stepperbar at this link.

      GitHub

GitHub - Mohamed-512/Extra-Streamlit-Components: An all in one place, to find... 7

  An all in one place, to find complex or just not available components by default on streamlit. - GitHub - Mohamed-512/Extra-Streamlit-Components: An all in one place, to find complex or just not av...

Cheers


How to get the file path from download_button?

Question:
Hello
I have a download button, that creates a file with suffix, depending on how many files of the same name exist - this the default functionality of the st.download_button.
How can I get the file path of the created/downloaded file?
Or how can I force download_button to overwrite existing file, not create a new one?

Context: Hi, the file will be saved under your defalut folder in explorer, you can check it through your explorer setting.


Question:
This error produces the TypeError: number_input() got an unexpected keyword argument 'disabled’ error:
# Indices of entries to extract

    idx = re.findall("\\d+", cols[0].text_input("Entries"))

    # Min. Entry and Max. Entries controls will be disabled if Entries are provided

    is_disabled = len(idx) > 0

    # Index of first FASTA to extract (starts from 1 on UI)

    min_idx = (

        cols[1].number_input("Min. Entry", min_value=1, value=1, disabled=is_disabled)

        - 1

    )

    # Number of entries to extract starting from min

    max_idx = cols[2].number_input(

        "Max. Entries", min_value=1, value=10, disabled=is_disabled

    )

According to documentation:

image734×89 8.57 KB

How can I fix that?

Context:
Hi @rlf037 @Svantevith ,
You can specify the version of Streamlit in the same manner you would for other Python dependencies in your app: App dependencies - Streamlit Docs
If you’re specifying Python dependencies via a requirements.txt file, you can pin a specific version of a package. For example, to install Streamlit 1.4.0, include the following line in requirements.txt:
streamlit==1.4.0

Happy Streamlit-ing!
Snehan


Question:
I am trying to

Take some user input
When a “Load” button (normal style button) is clicked, build a form from that input with N number of widgets
When form_submit_button is clicked, write the widgets’ values to a database.

I’ve noted the warnings in the docs about putting a button inside a form, but there is nothing about putting a form inside a button.
Here is a minimal example where the user enters a film director’s name and the form is populated with all of their films, each with a widget to provide a rating. When I click the form_submit_button, the app resets but the code inside the if submitted: block is not executed.
Any suggestions?
import streamlit as st

director = st.text_input("Director")
load_button = st.button("Load films")

# When the load_button clicked, the form is created and populated
if load_button:
    # (Some code to fetch the film data from a database)
    # films is a list of Film objects
    films = load_films(director=director)

    # Display each film along with a widget to provide a rating
    with st.form():
        # Catch each widget in a dictionary
        widget_dict = {}

        # Add a row to the form for every film
        for film in films:
            info_col, rating_col = st.beta_columns(2)
            # Put film info in left column
            with info_col:
                st.subheader(film.title)
                st.write(film.year)
            # Put a widget in the right column
            with rating_col:
                rating = st.slider(
                    label="Rating",
                    min_value=1,
                    max_value=10,
                    key=f"{director}_{film.title}",
                )
                # Add this widget to the dict
                widget_dict[film.title] = rating

        # When you submit the form, it loops through all
        # widget entries and updates an external database
        submitted = st.form_submit_button("Submit")
        if submitted:
            # THIS CODE IS NOT TRIGGERED ON CLICK
            print(f"Submitting ratings for {director}")
            for title, rating in widget_dict.items():
                write_rating_to_db(director, title, rating)

Context: Did you end up finding a solution to this? I am having the same issue


Display order of widgets when using callbacks

Question:
I’ve made a very simple app that:

Uses the file uploader widget to read in an Excel file
Gets the user to choose a worksheet they’re interested in previewing using a selectbox dropdown
Displays a preview of the worksheet

I’m using a callback from st.selectbox to display the preview, so that it only displays after the user has actively chosen a worksheet they’re interested in. But in order to do so I need to have defined my callback function before calling st.selectbox - and that’s leading the preview to appear above the file uploader and selectbox widgets in the app, rather than where I want it, below those widgets.
This is my code (Streamlit 1.3.1) and a screengrab of my output.
import streamlit as st
import pandas as pd

# CREATE APP
# Add file_uploader
uploaded_file = st.file_uploader(
    label='Upload a file', type=['xls', 'xlsx', 'xlsm'],
    key='file-uploader',
    help='''
        Upload an Excel file. The file must be
        closed in order for you to upload it.
    '''
)

# Define function that loads sheet preview
def load_sheet_preview():
    st.dataframe(df[st.session_state.selectbox_sheet])

# Add selectbox
if uploaded_file is not None:
    df = pd.read_excel(uploaded_file, sheet_name=None)      # sheet_name=None needs explicitly including - it isn't the default        # noqa: E501

    st.selectbox(
        key='selectbox_sheet',
        label='Select worksheet',
        options=df.keys(),
        on_change=load_sheet_preview
    )

Capture1920×1079 77.3 KB

I suspect I’ll kick myself when I hear the solution but I can’t think how to get around this. Wrapping the code that produces the file uploader and the selectbox in functions, ordered as I want them to appear in the app, doesn’t do it.
Thank you.

Context:
when you callback the load_sheet_preview function, you write to the page with st.dataframe. Since the callback function is written to the page before anything else during the streamlit reload, it means that the dataframe is written to the page before moving to the if uploaded_file is not None: statement.
I would need to thing about the solution some more, but maybe this helps you get there first.


Question:
Hi,
Inside a with st.form(‘my_form’), how to put 2 data entry columns on it?
From Date                       Time
date_input()                    time_input()
To Date                         Time
date_input()                    time_input()

Submit Button

Thanks!

Context:
Hi, you can do the following:
#After your with st.form statement… add
c1, c2 = st.columns(2)
With c1:
#Add controls you want to show in column 1
With c2:
#Add controls you want to show in column 2

add your submit button


Question:
I don’t know much about styling the streamlit app outside of page_config. Are there resources for me to learn how to maximize the customization of the app outside of the standard options supported by html. in general, what is the most effective way to do this, inject custom css? does JS come into play at all here?
One specific question I have is how would I customize button styling? but if i’m going to custom style buttons, I might as well know the full extent of what’s possible.
I’ve seen a few @dataprofessor videos. other suggestions?

Context:
I just did a video on this: 4 ways of styling Streamlit widgets | Streamlit tutorial - YouTube 4
Where I quickly skim through all the current ways to “hack” Streamlit design, with a lot of links in the video description  .
Hope it helps!
Fanilo


Question:
Hi there,
is there a way to force a new line in the label of the radio widget? This doesn’t work:
vis_outliers= st.radio(
   'Display outliers?\n(for data that might have errors only)',
   ['no', 'yes', 'hidden']
)

Thanks for your help.

Context:
Hi, how about doing this as an alternative:

st.text(‘Display outliers?\n(for data that might have errors only’)

OR

st.text(‘Display outliers?’)
st.text(‘for data that might have errors only’)

AND

vis_outliers= st.radio(’’,[‘no’, ‘yes’, ‘hidden’])


Question:
Hi all,
Is there a way to disable scrollbar?
I am building an one-page app where the content does not exceed screen height, the scrollbar appears anyways even when there is nothing below the main component.
I’d really like my page to be fixated. Is there an option to disable the scrollbar?
thanks in advance,
Don

Context:
I’m looking for this too.
I thought you could use the ‘overflow’ tag in CSS, but it doesn’t seem to work in Streamlit.
body {
  overflow: hidden; /* Hide scrollbars */
}


Question:
I want to change my theme using the command st.markdown(    “”"
     """, unsafe_allow_html=True,). My current custom theme is
 [theme]
base="dark"
primaryColor="#002b36"
backgroundColor="#002b36"
secondaryBackgroundColor="#586e75"
font="sans serif"
Can someone please help me to sort out  this problem?

Context:
Hi @udo

 udo:

My current custom theme is [theme] base=“dark” primaryColor="#002b36" backgroundColor="#002b36" secondaryBackgroundColor="#586e75" font=“sans serif”

Those edits are to be put inside a .streamlit/config.toml file (Theming - Streamlit Docs 1).
Edits done in st.markdown should be CSS Selectors + Properties only like
<style>
body {
    background-color: lightgoldenrodyellow;
}

div[role="listbox"] ul {
    background-color: red;
}
</style>

There are some tutorials wandering in this forum like

Can I change the color of the selectbox widget? - Using Streamlit - Streamlit
Creating a nicely formatted search field? - Using Streamlit - Streamlit
CSS hacks for the dumb? - #3 by andfanilo

to understand all the HTML blocks and CSS properties you can edit within the Streamlit app.
Have a nice day,
Fanilo


Changing background color of single number input and selectboxes

Question:
Hi,
I have a streamlit webApp and have several text input and selectbox widgets.
for example:
a = st.number_input(“value a”,value=0.5)
b = st.selectbox(‘choose value’,(‘b’,‘c’))
I want most of the widgets stay in standard gray but for some single ones I want to define the backgroudcolor by my self.
I found some ideas with st.markdown but could not realize it with my example.
Is it possible to change the backgroundcolor like this and do you have any ideas?
Thanks

Context:
Hey @Specht , welcome to the community
Let me preface this by saying the following is absolutely hard to maintain, even harder than the Markdown CSS Hack trick…
But yeah I’ve tried with CSS Selection alone but couldn’t find it out either. The only way of doing I found is by bypassing the components iframe:
import streamlit as st
import streamlit.components.v1 as components

a = st.number_input("value a", value=0.5)
b = st.number_input("value b", value=0.5)
c = st.number_input("value c", value=0.5)

components.html(
    """
<script>
const elements = window.parent.document.querySelectorAll('.stNumberInput div[data-baseweb="input"] > div')
console.log(elements)
elements[1].style.backgroundColor = 'red'
</script>
""",
    height=0,
    width=0,
)

image708×326 1.86 KB

I say unmaintainable because…well certain styles and events may break the moment you leave the iframe sandbox for components + well I think you can see from the code anytime you change the app, you’ll need to re-edit the code.
I don’t usually recommend this but just so you know there is this workaround…
Have a nice day!
Fanilo


Stop page from reloading after using downloader

Question:
Hi,
In my app a user uploads a file which is processed, the results of which are offered as a download.
Now when I press the download button on my webpage, it reloads and starts processing the uploaded file again. From what I gather this is the intended behaviour of Streamlit? Can I prevent  this reloading somehow, though? Seems like caching is an option, but that requires decorating a function? And I’m not really sure it would really solve my problem anyway.
Basically what I want is the user to be able to upload a file and having to option to download the results of the processing. If the user then wants to upload a new file, do the processing on the new file and offer the results as a new download.

Context: Hi Chiel, I ran into similar issue. Every time I click the download button, the whole app will refresh. May I know how you fixed it? Thanks!


How to use multiple columns in forms so that the input is side by side instead of below each

Question:
I have the following code, but the code doesn’t seem to work and its still showing one below the other
form = st.form(key="my-form")
c1, c2 = st.columns(2)
with c1:
    sel1= form.selectbox("Report Type", ("normal", "full"))
with c2:
    track= form.text_input("enter track no").upper()
submit = form.form_submit_button("Generate Report")

if submit:
    with st.spinner('Generating Report....'):

Context:
For anyone that is looking for the answer to my own question above, here is how I fixed it:
with st.form(key='columns_in_form'):
    c1, c2, c3, c4 = st.columns(4)
    with c1:
        initialInvestment = st.text_input("Starting capital",value=500)
    with c2:
        monthlyContribution = st.text_input("Monthly contribution (Optional)",value=100)
    with c3:
        annualRate = st.text_input("Annual increase rate in percentage",value="15")
    with c4:
        investingTimeYears = st.text_input("Duration in years:",value=10)

    submitButton = st.form_submit_button(label = 'Calculate')

This did the trick, one form with four inputs in four different columns:

Screenshot 2022-01-17 at 01.33.461779×201 11.1 KB


How to add Google Analytics or JS code in a Streamlit app?

Question:
Hi all,
I would like to monitor the traffic on my app using Google Analytics. What is the best way to achieve this?
I need to insert something like that
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-44444444-1"></script>
Also, what about Google Adsense code?
I hope there is a way to inject these in Steamlit somehow.
Thanks in advance for support.

Context: It is very proud to see Streamlit become so far  I believe this will go bigger and bigger


Question: Hello everyone, I would like to download a streamlit table to pdf. Once I click on a button the table will be downloaded automatically. I really need it so please help me out

Context:
Hi Loubna! And welcome to the Streamlit forum!
I’m not aware of any way to do this, but Devs may know!
Let me ask them and come back to you!
Best,
Charly


Question:
I have StreamLit working fine with some simple things like st.write and even st.table.
I have a CSV file with two columns, “Date” and “Profit/Loss”
Date,Profit/Loss
2022-01-14,-500.00

df =  pd.read_csv('profitloss.csv')

chart_data = pd.DataFrame(df)

st.bar_chart(chart_data)

this code just gives me this error:
**StreamlitAPIException** : ("Expected bytes, got a 'float' object", 'Conversion failed for column value with type object')
What am I doing wrong?

Context:
Hi @TheBigDuck
I suggest you replace the above code with the following code:

df =  pd.read_csv(‘profitloss.csv’)
df = df.set_index(‘Date’)
st.bar_chart(df)

Also suggest you take a look at other visualization libraries: Altair, etc.
Cheers


Problem: Streamlir shows source code, when dataframe is displayed

Question:
Dear all,
My code reads a file and then displays it in a data frame.
uploaded_file = st.file_uploader("Choose a KML file")

if uploaded_file is not None:

    df = gpd.read_file (uploaded_file, driver ='KML')

    st.write(df)

but for some reason it also displays part of the source code of the data frame.

streamlit_problem1518×1006 97.3 KB

Does anyone know how to solve this?
Thank you!

Context:
Hi @karina-castillo, welcome to the forum!
Have you tried using st.dataframe(df) or st.table(df) instead?
Happy Streamlit’ing!
Snehan


How to display animated loading while process run in background (preload page)

Question:
Hello, everyone.
First, i wanna thank you streamlit team for the amazing work they have been done so far.
So, I’m building an app that uses Pylinac Library 2 for automating radiotherapy QA.
I was trying to implement a loading gif while the analysis code run in background, but I’m facing a hard time in this task. Being clear, I basically want a pre-load page, that shows only the loading gif while the analysis is done in background and, when is completed, shows only the app page with the analysis without the gif.
I know st.spinner exist, but I can’t set to show only the loading, just how it is below:

SharedScreenshot1364×664 64.1 KB

Thank you in advance, community!

Context:
Almost 30 different loaders to choose from in any combination you like.

      GitHub

GitHub - TangleSpace/hydralit_components: A package of custom components for... 1

  A package of custom components for Streamlit and Hydralit. Can be used directly or in combination with the Hydralit package. - GitHub - TangleSpace/hydralit_components: A package of custom componen...

The example project also shows you how to create a full page loader that will run whenever your app is running/loading in the background, works with all the loaders in the components package or you can create your own.

      GitHub

GitHub - TangleSpace/hydralit-example: A sample project showing off the ease... 2

  A sample project showing off the ease and ability of the Hydralit multi-page Streamlit package. - GitHub - TangleSpace/hydralit-example: A sample project showing off the ease and ability of the Hyd...


Module not found pandas profiling error message

Question:
how do I resolve the following error message? ModuleNotFoundError: No module named ‘pandas_profiling’
Traceback:
File "/opt/anaconda3/envs/streamlit_model/lib/python3.9/site-packages/streamlit/script_runner.py", line 354, in _run_script
    exec(code, module.__dict__)File "/Users/bishopakolgo/Desktop/app.py", line 11, in <module>
    from pandas_profiling import ProfileReport

Context:
Hi i finally resolved this issue by just by simply installed pandas profiling.  However the new problem is the following;
module NotFound: No module named: “df_helper”
file “opt/anacoda3/envs/stream;it_model/lib/python3.9/dite-packages/streamlit exec(code, module. dic)
File”/users/bishopakolgo/desktop/app.py,line 16, in module import df_helper as helper # custom script


Streamlit working on web browser (not mobile)

Question:
Hello everyone!
Amazing tool! Love what you guys did.
After building and deploying my app to https://playground-ml.herokuapp.com/ 37 I came to notice that it doesn’t open on mobile browsers (specifically IPhone when using Safari and Chrome) : when you hit the link, you’re faced with a blank page (not even an error message)
Could this be related to Heroku?
It’s hard to debug on mobile. On desktop, everything works fine. Has anyone faced this issue?
Thanks for your help.

Context:
Hello @ahmedbesbes, welcome to the community! And what a nice app you have delpoyed there
On my side your link works perfectly on iPhone Chrome and Safari though, I’ve been able to change dataset and play with the sidebar parameters. Did you change anything in between?
Cheers,
Fanilo


Buttons running a on-click function during startup and runtime

Question:
Hi all,
I am making a Streamlit app for simple permission management of an SQL database.
In this app I have some functions doing SQL queries (adding and deleting rows in the database) when a button is pressed. Problem is these buttons execute my add/remove functions at startup and during runtime. This should only be done when performed by the user!
Example button and function.
userID is picked from a st.selectbox
df is generated from a st.multiselect list
def update_Usergroup(userID, df):
    eng = makeConnection() # sqlalchemy create engine function

    st.success('update_Usergroup is run')

    query = f"""DELETE FROM Users_Usergroups_Comb
    WHERE UserID = {userID};
    """
    eng.execute(sa_text(query).execution_options(autocommit=True))
    # write to Users_Usergroups_Comb table with no index and appending the dataframe to the DB
    df.to_sql('Users_Usergroups_Comb',con=eng, index = False, if_exists = 'append')

return

st.button('Save updated usersgroups', on_click = update_Usergroup(userID, membership))

How can I control the app such that on_click is not executed automatically?
Thanks in advance!

Context:
Hi @EBEN
Try replacing your st.button statement with the following code:
if st.button(‘Save updated usersgroups’):
update_Usergroup(userID, membership)


How to access uploaded video in streamlit by open cv?

Question:
Hi, I want to upload video through streamlit and want to access it with cv.VideoCapture()
function. So How can i do please help me.

Context:
Seems wasteful, but if OpenCV really requires a file, I wonder if this will be acceptable:
import streamlit as st
import cv2 as cv
import tempfile

f = st.file_uploader("Upload file")
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(f.read())
vf = cv.VideoCapture(tfile.name)


Question:
Hi all,
I was wondering if there was a way to have a user upload a file (ie a txt or csv file) to a Streamlit app? I didn’t see anything in the docs about this.
Tangent from this, is it possible to inject HTML into Streamlit to create new functionalities?

Context:
Hi Karl.
Great questions!

#1: How to create a file selector
Currently, there is no file picker, but I just added a feature request for one 845. Please feel free to follow this request on Github to follow its progress.
In the meantime, here’s an example of a janky ad-hoc file selector on the server:
import streamlit as st
import os

filename = st.text_input('Enter a file path:')
try:
    with open(filename) as input:
        st.text(input.read())
except FileNotFoundError:
    st.error('File not found.')

#2: How to inject custom HTML into Streamlit
What would you like to add? Streamlit already supports many different elements and we’re adding more each day. If you share some details we can help you achieve your aim.
In the long run, we plan to expose a plug-in architecture. I’ve created this tracking bug 55. Please feel free to add comments describing what you’d like to see here.
Summary
In general, please feel free to submit bug report or feature requests 13 at our repo 6.


Question:
Hi, I have built a streamlit app which visualizes some data, based on various settings the user can make in the sidebar.
The visualization itself can be switched between different modes (I built a form of multi page app with a select box on top of the page)
Now it is often interesting to compare different views of the same filter settings with each other. The best solution for this in my current setup is to open a new browser window and to carefully set all the filter settings on the sidebar to the same values as they are in the first window. Then one can select a different mode and compare both.
Since the visualization modes can be a bit complex, I would like to avoid having one giant compare mode with two visualizations on one page.
Copying of the settings is a bit tedious, so ideally this would be encoded into the url for example, which can then be copied to get a second session with the same input widget state.
I don’t think it is possible, but maybe somebody knows a way to get something like that?

Context:
ideally this would be encoded into the url for example

This is possible with st.experimental_get_query_params() and st.experimental_set_query_params()
See this example 2


Question:
Display pyGAM model summary into streamlit application.
Source: https://codeburst.io/pygam-getting-started-with-generalized-additive-models-in-python-457df5b4705f 1
    import pandas as pd
    from sklearn.datasets import load_boston
    from pygam import LinearGAM

    boston = load_boston()
    df = pd.DataFrame(boston.data, columns=boston.feature_names)
    target_df = pd.Series(boston.target)
    df.head()

    X = df
    y = target_df
    gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values)
    gam.summary()

image1012×742 100 KB
As shown in image the output of gam.summary is not displaying with any of the st.* (display functions)

Context:
Hi @Ahmad_Zia , welcome to the Streamlit community!
It’s unfortunate that the pyGAM summary method dumps the result using print() statements, but you can redirect the output using the following code:
import pandas as pd
from sklearn.datasets import load_boston
from pygam import LinearGAM
from io import StringIO
import sys
import streamlit as st

# redirect where stdout goes, write to 'mystdout'
# https://stackoverflow.com/a/1218951/2394542
old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
target_df = pd.Series(boston.target)
df.head()

X = df
y = target_df
gam = LinearGAM(n_splines=10).gridsearch(X.values, y.values)
gam.summary()

sys.stdout = old_stdout

# this is what writes to the streamlit app...read the value from the redirected out
st.text(mystdout.getvalue())

image1495×1462 104 KB
Best,
Randy