Does Streamlit have a default vega-lite specification?

Question:
Hi, I am new to using vega-lite for graphing, but I prefer it to matplotlib because the plots look sexier.
First, I have a confusion about the vega-lite specification json. If I don’t specify something like
"mark": {"opacity": 0.3, "type": "area", "color": "#85C5A6"},

For my plot, will it default to something?
Second,if it does not default to something, does Streamlit have some defaults for how it handles coloring line charts?

Context:
Hey @kevinlinxc
You’ll definitely be better using Altair, it mirrors all of the vega-lite spec and gives you autocompletion on the spec
Streamlit does not interact with your vegalite/altair spec and does not provide a default, it just passes the spec directly to the vegalite parser so, so yeah you have to actually learn the language which takes some time, trial and error  . I think Streamlit does not provide a default because merging your Altair spec with Streamlit’s default option would mess things up given the sheer number of available options you would have to override.
For me the best way to learn Altair and its spec is to understand each example of the Altair gallery 3 and its vega-lige counterpart 1, that way you will understand how Altair maps back to vega-lite and slowly be able to express your plot. I did not find a tutorial that can speed you through Altair, this is something you’ll have to dig into  but honestly it’s worth it.

There a vegalite editor if you want to build out your JSON, or test out the JSON output of Altair (using this tip to output the vegalite chart from Altair)
There is a Slack group Join Vega on Slack | Slack 1  with an official Altair channel

Good luck!
Fanilo


Streamlit webapp with sidebar refreshes everytime when some action is performed

Question:
My code:
import streamlit as st
import pandas as pd

def main():
    st.markdown("
My Streamlit App
", unsafe_allow_html=True)

    menu = ["Admin","Manager","Employee"]
    choice = st.sidebar.selectbox("User",menu)

    if choice == "Admin":
        admid = st.sidebar.text_input("Admin ID")
        passw = st.sidebar.text_input("Password",type='password')

        if st.sidebar.button("Login"):
            result = 1
            if result:
                user = st.selectbox("Select User",["Admin","Manager","Employee"])
                if user == "Admin":
                    task = st.selectbox("Manage Admin",["View","Add","Delete"])
                    if task == "View":
                        st.subheader("Admins")
                    if task == "Add":
                        st.subheader("Add admin")
                    if task == "Delete":
                        st.subheader("Delete admin")
                elif user == "Manager":
                    task = st.selectbox("Manage Manager",["View","Add","Delete"])
                    if task == "View":
                        st.subheader("Managers")
                    if task == "Add":
                        st.subheader("Add manager")
                    if task == "Delete":
                        st.subheader("Delete manager")
                else:
                    task = st.selectbox("Manage Employee",["View","Add","Delete"])
                    if task == "View":
                        st.subheader("Employees")
                    if task == "Add":
                        st.subheader("Add employee")
                    if task == "Delete":
                        st.subheader("Delete employee")
            else:
                st.warning("Incorrect Admin ID/Password")

    elif choice == "Manager":
        manid = st.sidebar.text_input("Manager ID")
        passw = st.sidebar.text_input("Password",type='password')
        if st.sidebar.button("Login"):
            result = 1
            if result:
                st.success("Logged In as Admin")
            else:
                st.warning("Incorrect Manager ID/Password")

    else:
        empid = st.sidebar.text_input("Employee ID")
        passw = st.sidebar.text_input("Password",type='password')
        if st.sidebar.button("Login"):
            result = 1
            if result:
                st.success("Logged In as Admin")
            else:
                st.warning("Incorrect Employee ID/Password")

main()

After I run this app and login as admin / manager / employee using sidebar , doing any further action ( using any selectbox ) refreshes the entire app, making the whole app useless. I’ve read many posts that suggest using session state to overcome this problem. But I couldn’t understand how to implement session state. I’ve read about it and watched YouTube videos, still I’m not able to implement it on my own problem. So if anyone could implement any technique to retain all actions for each run on this code, that’d be easy for me to understand session state.
I’ve gone through many Streamlit posts that discuss the same problem, But I couldn’t understand them.

Context:
Hello @MainamarbuSav, welcome to the forum!
This is due to st.button not retaining any state. Like other posts on this matter, your example assume that st.button toggles some state automatically, like a checkbox would do. In practice, st.button returns True for one run only.
Instead of displaying your user views if the login button is clicked, display them if some session state tells you that your user is logged in. Your login button will be used to change that session state.
import streamlit as st
import pandas as pd

def main():
    st.markdown("
My Streamlit App
", unsafe_allow_html=True)

    # Initializes session state
    if "user" not in st.session_state:
        # Will store the currently logged user
        st.session_state.user = None

    # Case where user is not logged
    menu = ["Admin","Manager","Employee"]
    choice = st.sidebar.selectbox("User",menu)

    if choice == "Admin":
        admid = st.sidebar.text_input("Admin ID")
        passw = st.sidebar.text_input("Password",type='password')

        if st.sidebar.button("Login"):
            result = 1
            if result:
                st.success("Logged In as Admin")
                st.session_state.user = "Admin"
            else:
                st.warning("Incorrect Admin ID/Password")

    elif choice == "Manager":
        manid = st.sidebar.text_input("Manager ID")
        passw = st.sidebar.text_input("Password",type='password')

        if st.sidebar.button("Login"):
            result = 1
            if result:
                st.success("Logged In as Manager")
                st.session_state.user = "Manager"
            else:
                st.warning("Incorrect Manager ID/Password")

    else:
        empid = st.sidebar.text_input("Employee ID")
        passw = st.sidebar.text_input("Password",type='password')

        if st.sidebar.button("Login"):
            result = 1
            if result:
                st.success("Logged In as Employee")
                st.session_state.user = "Employee"
            else:
                st.warning("Incorrect Employee ID/Password")

    # Case where Admin is logged
    if st.session_state.user == "Admin":
        user = st.selectbox("Select User",["Admin","Manager","Employee"])

        if user == "Admin":
            task = st.selectbox("Manage Admin",["View","Add","Delete"])
            if task == "View":
                st.subheader("Admins")
            if task == "Add":
                st.subheader("Add admin")
            if task == "Delete":
                st.subheader("Delete admin")
        elif user == "Manager":
            task = st.selectbox("Manage Manager",["View","Add","Delete"])
            if task == "View":
                st.subheader("Managers")
            if task == "Add":
                st.subheader("Add manager")
            if task == "Delete":
                st.subheader("Delete manager")
        else:
            task = st.selectbox("Manage Employee",["View","Add","Delete"])
            if task == "View":
                st.subheader("Employees")
            if task == "Add":
                st.subheader("Add employee")
            if task == "Delete":
                st.subheader("Delete employee")

    elif st.session_state.user == "Manager":
        st.write("Manager dashboard")

    elif st.session_state.user == "Employee":
        st.write("Employee dashboard")

main()


How to make placeholder for components.iframe?

Question:
How to make a placeholder for components.iframe()? For everything else I have seen that there is st.empty(). I looked everywhere couldn’t find the way to do the same for components.iframe()
I have 3 elements in a column and the 3rd (iframe) one depends on the input for the first two, but I want to place the 3rd one as first. Hence I thought placeholder could be a way but am unable to find a way of producing the same for components.iframe.
Ps: with components, I mean import streamlit.components.v1 as components
Used st.markdown("") instead, which worked. But would still love to know if something can be possible with components.iframe.

Context:
Hello @mac1,
You can use st.container(). You can even add multiple widgets inside it, including components. Check out the second code example shown there: st.container - Streamlit Docs 3


Question:
When I executed the following script
import streamlit as st
import pandas as pd

df = pd.read.csv('path\to\a random.csv')
df_types =  pd.DataFrame(df.dtypes, columns=['Data Type'])

where my csv file had 3 columns: Text (object), Date-Time (object), Number (float64).
However, I got this error message
StreamlitAPIException: Unable to convert numpy.dtype to pyarrow.DataType.
This is likely due to a bug in Arrow (see https://issues.apache.org/jira/browse/ARROW-14087).
As a temporary workaround, you can convert the DataFrame cells to strings with df.astype(str).

Could someone please explain why:

df_types is a dataframe but why it couldn’t be displayed?
what numpy.dtype did the error message refer to?
why was numpy.dtype needed to convert to pyarrow.DataType?

Thanks in advance

Context:
I also had the same issue on my function. I resolved it by converting my df_types Dataframe to df_types.astype(str) and Steamlit was able to render the Dataframe without issues
def explore(data):
df_types = pd.DataFrame(data.dtypes, columns=['Data Type'])
numerical_cols = df_types[~df_types['Data Type'].isin(['object',
               'bool'])].index.values
df_types['Count'] = data.count()
df_types['Unique Values'] = data.nunique()
df_types['Min'] = data[numerical_cols].min()
df_types['Max'] = data[numerical_cols].max()
df_types['Average'] = data[numerical_cols].mean()
df_types['Median'] = data[numerical_cols].median()
df_types['St. Dev.'] = data[numerical_cols].std()
return df_types.astype(str)


Question:
Ask the community or our support engineers for answers to questions.
is that a way to overwrite or clear user input value by click a button?
image905×202 2.99 KB
for example, by click the button, clear the text input value.

Context:
Yes, you can store the value of the click and if its true, set the value of the text input to blank.
import streamlit as st

placeholder = st.empty()

input = placeholder.text_input('text')
click_clear = st.button('clear text input', key=1)
if click_clear:
    input = placeholder.text_input('text', value='', key=1)

This works for me. Does it answer your q?
Dinesh


Question:
Is it possible?
The last time I installed something with pip it broke my anaconda installation… Thus if the package could be installed through something similar to “conda install streamlit” it would be great!

Context:
Found the solution in Conda User’s Guide 820.
A short sum up:
conda activate base
pip install streamlit
Then check the install by doing:
conda list | grep streamlit
If it doesn’t appear, read the guide, there’s a solution there.


Upgraded to 1.0. What happened to `st.caching.clear_cache()?`

Question:
Hi!
In version 0.88, I had in my code a place where I wanted to force a cache reset. I did this with st.caching.clear_cache().
I’ve since upgraded to 1.0 and changed my @st.cache decorators to @st.experimental_memo decorators and st.caching.clear_cache() no longer works. is this because of upgrade to 1.0 or change to experimental_memo?
Any help to force cache clear in 1.0?

Context:
Hi @ryanlampkin,
st.caching.clear_cache() no longer works because of both the reasons you cite. To force a cache reset with v.1.1.0, use st.legacy_caching.clear_cache().
I’ve verified that it clears both disk cache and memory cache created by @st.experimental_memo.
Best,
Snehan


App concept: Asking for help with a bit of direction

Question:
Hi all,
I am developing a concept for an app in my head and I was hoping for a bit of advice on how to approach this. I have used Streamlit for 6 months, mostly for dynamic plotting of data, so I know the basics.
The concept is this:
a) I will have a number of photos stored somewhere (like github). Each photo contains a number of items (cats, dogs, etc).
b) The user opens the streamlit app and a random image is shown. The user is asked how many cats are in this image and they can input this value.
c) Part b) repeats 10 times (i.e. a different image loads with a different number of cats), until there is 10 user inputs.
d) After 10 user inputs, the app calculates the users score and displays results.
I know I can create a place for my images using st.empty() and update the image after each input. That seems like it should be OK.
The thing I am a little confused about is how I can collate the user inputs, since every time the user enters their answer, wont the app reset?
Maybe it is easier than I am thinking, but any advice or help, or things I have not thought of yet, would all be appreciated.
Thank you for taking the time to read

Context:
Hey @LukeF,
Don’t know how much time you have been spending on the forum in the last few months but I think the easiest way to do this is using session state.
You can easily store each of the user’s answers in st.session_state, and then compare them with the “correct” values once they are finished! here are some links for you to get started:

    Version 0.84.0 Official Announcements

    I am excited to announce the release of version 0.84.0 of Streamlit, which includes the long-awaited Session State feature!
Release date: Jul 1, 2021
Highlights

Introducing st.session_state and widget callbacks to allow you to add statefulness to your apps. Check out the blog post

Notable Changes

st.text_input now has an autocomplete parameter to allow password managers to be used

Other Changes

Using st.set_page_config to assign the page title no longer appends “Streamlit” to that ti…

      Streamlit – 1 Jul 21

Store Information Across App Interactions | Session State 1

  You can now store information across app interactions and reruns!

      docs.streamlit.io

Session State - Streamlit Docs

  st.session_state is a way to share variables between reruns, for each user session.

Happy Streamlit-ing!
Marisa


Question:
I’m wondering how I can download a model that was trained within the app. I know that you can download a csv file using the following code:
    csv = output_df.to_csv(index=False)
    b64 = base64.b64encode(csv.encode()).decode()  # some strings <-> bytes conversions necessary here
    href = f'Download Test Set Predictions CSV File (right-click and save as <some_name>.csv)'
    st.markdown(href, unsafe_allow_html=True)

How could I apply something similar using pickle?

Context:
Figured it out. Here’s the code if anyone else is wondering:
def download_model(model):
    output_model = pickle.dumps(model)
    b64 = base64.b64encode(output_model).decode()
    href = f'Download Trained Model .pkl File (right-click and save as <some_name>.pkl)'
    st.markdown(href, unsafe_allow_html=True)


Uploading multiple files with file uploader

Question:
Good job with the st.file_uploader(). I spent some time playing with it but could not figure out how to upload multiple files.
In my case I would like the user to upload multiple images (in a batch or one-by-one), and then run an ML model on them. Is this somehow possible with the current release?

Context:
I tried but it turns out that I cannot easily use the file_uploader.

You can only upload one file at the time.
You get no additional information on the file like name, size, upload time, type etc. So you cannot distinguish the files without reading the content.
every time you interact with any widget, the script is rerun and you risk processing or storing the file again!
The file uploader widget is not cleared when you clear the cache and there is no way to clear the file uploader widget programmatically.

But here is something that feels like multiple file upload.
I will be adding it to the gallery at awesome-streamlit.org 197.

file_uploader_multiple_files1755×1194 1.77 MB

# pylint: disable=line-too-long
"""This is example shows how to **upload multiple files** via the
[File Uploader Widget](https://streamlit.io/docs/api.html?highlight=file%20upload#streamlit.file_uploader)

As far as I can see you can only upload one file at a time. So if you need multiple files in your
app, you need to store them in a static List or Dictionary. Alternatively they should be uploaded
as one .zip file.

Please note that file uploader is a **bit problematic** because
- You can only upload one file at the time.
- You get no additional information on the file like name, size, upload time, type etc. So you
cannot distinguish the files without reading the content.
- every time you interact with any widget, the script is rerun and you risk processing or storing
the file again!
- The file uploader widget is not cleared when you clear the cache and there is no way to clear the
file uploader widget programmatically.

Based on the above list I created [Issue 897](https://github.com/streamlit/streamlit/issues/897)

This example was based on
[Discuss 1445](https://discuss.streamlit.io/t/uploading-multiple-files-with-file-uploader/1445)
"""
# pylint: enable=line-too-long
from typing import Dict

import streamlit as st

@st.cache(allow_output_mutation=True)
def get_static_store() -> Dict:
    """This dictionary is initialized once and can be used to store the files uploaded"""
    return {}

def main():
    """Run this function to run the app"""
    static_store = get_static_store()

    st.info(__doc__)
    result = st.file_uploader("Upload", type="py")
    if result:
        # Process you file here
        value = result.getvalue()

        # And add it to the static_store if not already in
        if not value in static_store.values():
            static_store[result] = value
    else:
        static_store.clear()  # Hack to clear list if the user clears the cache and reloads the page
        st.info("Upload one or more `.py` files.")

    if st.button("Clear file list"):
        static_store.clear()
    if st.checkbox("Show file list?", True):
        st.write(list(static_store.keys()))
    if st.checkbox("Show content of files?"):
        for value in static_store.values():
            st.code(value)

main()


Question:
I use subprocess all the time as the ‘correct’ way to call shell commands in python. Always works fine.
In streamlit its a total fail nothing works most things return ‘0’ not the result of the command.
Or the server seems to lock up.
a simple test:
import streamlit as st
import subprocess
res = subprocess.call('ls l', shell=True)
st.write(res)

Context:
When I run this, I get the following message in the terminal: ls: cannot access 'l': No such file or directory
You can run this to get the output:
import streamlit as st
import subprocess
res = subprocess.check_output(['ls', '-l'])
st.write(res)

What are you actually trying to do with your code, outside of this trivial example?
Best,
Randy


Question:
Hello there! Is there a way I can set the value of a selectbox on the press of a button?
Thamkss
cols = st.columns([1, 2])
search = cols[0].selectbox('', options, key='search_1')
if cols[1].button('set'):
     # ? set selectbox value to (say) options[0]

Context:
Hey @elwyn,
Oops! Sorry! I was coding from my phone and I mixed up the order of those
It should look like this:
cols = st.columns([1, 2])

if cols[1].button('set'):
     # call search_1 in session state and set it
     st.session_state.search_1 = options[2]

# when you create the selectbox with a key it automatically tracks it in the session state
search = cols[0].selectbox('', options, key='search_1')

You shouldn’t need to initialize search_1 unless you intend to access it or change its state before its first render!
Happy Streamlit-ing!
Marisa


Question:
Hello! I am trying to use multi select as a way to choose which functions to run. Below is some sample code. When the code is run, you’re unable to select an option. According to the docs, it sounds like I just need to pass in a Sequence for options, so I’m not sure if I’m doing something wrong or if there is another workaround for what I’m trying to achieve. Ideally, this would return a list of functions that I could then iterate through. Thanks for the help!
import streamlit as st

def first():
    pass

def second():
    pass

st.multiselect(label="Example", options=[first, second])

Context:
I would do it like this:
import streamlit as st

def first():
    pass

def second():
    pass

res = st.multiselect(label="Example", options=["first", "second"])

if res == "first":
    first()
elif res == "second":
    second()

It’s important to realize that Streamlit is returning a value from st.multiselect, which I define as res. I would assume that the way your original code is written, you are returning the definition of first or second (literally the interpreted Python code) instead of executing it.
Best,
Randy


How can I cache outputs when parameters inside a widget change?

Question:
Say you have this:

My goal is to change input in X (e.g., to 3) and have it say:

Current result: 9
Previous result: 6

Then, when I change X to 4, it will say:

Current result: 12
Previous result: 9

Does anyone know how to do this please?

Context:
HI @mogortevo ,
If I understood you correctly, probably session-state 1 will do the trick.Try to store your variable Previous result using session_state.
Best,
Avra


Urgent help on getting value of input box

Question:
good day guys. i have just started learning and practicing streamlit and i must say it is cool to use and simple. i have been making use of tkinter for basic desktop apps but now i intend learning streamlit to convert most of my tkinter apps to web app but the issue i am facing is that, some of the simple functions to get the values from input boxes on tkinter are not present on streamlit. stuffs like
insert to insert value into a text_area or text_input,
delete to clear the text_area or text_input box. i was thinking streamlit has such function maybe
box1 = st.text_area(“enter text”)
box1.get() to get the value that is inside the box
box1.insert(“string”) to insert anything inside the text_area or text_input box. stuffs like this would be a great features to add to streamlit because it will make things easy to do with functions. i am currently having issues implementing such flow with streamlit. with tkinter, i have no issue doing this, but with streamlit, how do i get the value of a text_area, text_input when it is inserted after a function is being run. for example, check code below
import streamlit as st

import clipboard

import time

box2 = st.text_area("enter your age")

labels = [1, 2, 3, 4, 5]

box1 = st.text_area('Generated From function', value='type here')

box4 = st.empty()

def MAINFUNCTION(tojoin):

    JOINLIST = "\n".join(str(i) for i in tojoin)

    return JOINLIST

if st.button("Submit"):

    runapp = MAINFUNCTION(labels)

    with box4.beta_container():

        st.text_area("Generated", runapp)

    box1 = st.text_area("Generated From function", runapp)

    box3 = st.text_area('enter your name', runapp)

    #st.success(box1)

if st.button('copy'):

    st.success(f'box1 to be copied: {box1}')

    clipboard.copy(str(box1))

    clipboard.paste()

    st.success("copied successfully")

    st.success(f'box4 to be copied: {box4}')

    st.success(f'box1 to be copied: {box3}')

from the code above, i inserted the value from running the mainfunction after clicking the button. this works well and inserted the value. now i tried to copy the value from the box which was added when i run after clicking the button. but i got an error as nothing is being printed out and copied except this
box1 to be copied: type here
box4 to be copied: <streamlit.delta_generator.DeltaGenerator object at 0x0000021A28263CC8>
why is it not copying the actual content from the box instead of the above.  how do i actually get the value inside a box regardless because if i remove the value and manually type anything in box1. it works but why doesn’t it get the value that is generated from the function when the submit button is clicked since it was inserted automatically. also, even after clicking the copy button, the other text_area boxes disappears.
so my question is, how do i get the value regardless .

Context:
Hi @carty,
Welcome to the Streamlit community. If you look at the API documentation 33, the return value from the st.text_area()is the current value inside the widget. So you don’t need to convert it into a string. You need to capture the result of text_area in box4 by saving the return from the call into a variable, the way you’re doing with box1, for example.
The way streamlit works is that reruns the entire code from start to the end (or hits st.stop()).
Does this help?
Dinesh


Question:
Hi, I’m trying to add an interactive map to my dashboard.
The idea is to be able to click on points in the map and update some other plots depending on what I selected. I didn’t find how to capture these events (or any other map events) on Streamlit.
Is there some way of doing this?
I’m using plotly mapbox maps but I’m ok if I have to use other kind of map.

Context:
Hi @nvaras,
Currently, it is not possible to have any interaction with the map … The react-map-gl component used is a StaticMap, therefore it is not possible to capture any interaction with the map.
So far the only interactivity you add to your map might be with setting
'pickable':True,
'autoHighlight':True

I hope it helped.
Best,


Question:
Hi everybody,
I want to pass two values, a min and a max, as variables for my code. I have used for this, st.select_slider , st.number_input, and the problem I have is the same, when I put the minimum value this is automatically launched, and what I want is to put the minimum value, then the maximum and then pass these variables with my “submit” button. How can I stop the automatic launching of these values and only be able to send them with the submit button?
my code:
      number = st.slider('Insert your min and max value',value=[0.0,1.0])

        if(st.button('Submit')):
            st.write('Your interval is ', number[0],'-',number[1])

Thanks!
Karina

Context:
Hi @karina-castillo -
If you need to bundle inputs together in such a way that they all need to be finished before submitting, you can use st.form
https://docs.streamlit.io/library/api-reference/control-flow/st.form 3
Best,
Randy


How to centre and resize gifs in streamlit

Question: Hi everyone, I would like to know how i could centre and resize gifs in streamlit. Thanks

Context:
I’d suggest using the width param in st.image. st.columns can be used to place the image in the center of the page. (For finer-grained control of the image size, etc., use the image module from the PIL library.)
See: st.columns - Streamlit Docs 1, which includes an example using st.image.
_left, mid, _right = st.columns(3)
with mid:
   st.image("./images/logo.gif")

HTH,
Arvindra


Question:
Hi, I have both cert and key file. But i dont know how to add them to streamlit. I am using a window server.
I am running simple snippet to access camera.
from streamlit_webrtc import webrtc_streamer
import av
class VideoProcessor:
    def recv(self, frame):
        img = frame.to_ndarray(format="bgr24")
        flipped = img[::-1,:,:]
        return av.VideoFrame.from_ndarray(flipped, format="bgr24")
webrtc_streamer(key="example", video_processor_factory=VideoProcessor)

Context: Streamlit doesnt come with SSL support out of the box. So my understanding is you cant use them with streamlit. You might need something like nginx in front of streamlit for SSL termination


Question: So I had just installed streamlit yesterday and it working all fine. All of sudden it doesn’t work now. streamlit hello throws some error which I am unable to understand. Please help!streamlit_error1097×615 25.7 KB

Context:
Hmm, I thought I’d find a € in it, but it’s not the case
You didn’t have any other match while running dir /s ...? If not, try running streamlit run hello again, and if you’re still encountering the same exception, rename the configuration file to something like backup.toml and run streamlit run hello again.


How to fix DuplicateWidgetID: There are multiple identical st.button widgets when there are no duplicate keys in Streamlit

Question:
I am trying to Implement a pause and resume button in my program.
But I get the error:  DuplicateWidgetID: There are multiple identical st.button widgets with key='pause_button' . How do I fix this when there are no duplicate keys?
Here is a snipnet of my code:
while st.sidebar.button(label="Pause", key='pause_button'):
    if st.sidebar.button(label="Resume", key='resume_buton'):
        continue
    time.sleep(10)

Or what is best way to implement a pause button in my simulation program?

Context:
Hello John,
I’m having the same issue, did you happen to find a solution for this?


Question:
I am trying to move a small Excel macro app to a new app using streamlit, here is what I have done so far
https://xerviewer.herokuapp.com/ 15 , First I have to say what you guys have build is amazing, I am not a dev and managed to make  a web app
the app just read an xer file (it is just a csv file with a lot of tables) and parse it and loaded it to an in memory sqlite DB, I am using st.cache too, the app is hosted in heroku.
my question is : is the data deleted or save it in the server, ideally I want people to use it and feel confident that I can’t read there data ?
thanks

Context:
Hi @mim,
By default the cache is stored in memory until the server process is killed. There are some flags you can use to alter this behavior.
    persist : boolean
        Whether to persist the cache on disk.

    max_entries : int or None
        The maximum number of entries to keep in the cache, or None
        for an unbounded cache. (When a new entry is added to a full cache,
        the oldest cached entry will be removed.) The default is None.

    ttl : float or None
        The maximum number of seconds to keep an entry in the cache, or
        None if cache entries should not expire. The default is None.


Is it possible to import Shared Components when creating a Streamlit Component?

Question:
Is it possible to use a Shared Components when creating a Streamlit Component?
My use case if the following: I would like to create an “info alert” (st.sidebar.info("some text")) with a little tweak. The little tweak consists in adding a little icon to “copy” the text of the info alert when clicked.
Instead of recreating the JS and CSS from scratch, I wanted to import the shared component AlertContainer inside my MyComponent.tsx file and start from there.
But I failed to do so. It looks like the said Container is not in the streamlit-component-lib module.
Is there a way to do what I just described?

Context:
Hey,
Can you just use st.sidebar.code(“Some text”)
To achieve the same?
Thanks,
Akshansh


Can’t get columns to go horizontally in loop

Question:
Hey, I’m pretty knew to using streamlit and i’m trying to generate a loop of columns with multiselect tool, but they end going to a lower line, as shown:
labels = [‘label1’, ‘label2’, ‘label3’, ‘label4’, ‘label5’]
for i in labels:
cols = st.columns(len(labels))
cols[labels.index(i)].multiselect(f"""{i}""", [‘Green’, ‘Yellow’, ‘Red’, ‘Blue’])

Sem título1212×470 5.1 KB

Searched for few solutions, but couldn’t get anything conclusive.

Context:
Hi @Elio_Daniel_Mota_Soa, welcome to the Streamlit community!
Try moving cols = st.columns(len(labels)) outside of the loop. With it in the loop, each time it’s creating a new row of 5 columns. Outside, it will only define one row of 5 columns.
Best,
Randy


How to keep track of who is logging into Deployed app?

Question:
Hi everyone,
My questions involves a publicly deployed app (via heroku) with individual user logins. I want to keep track of exactly when (and preferably where but not as important) each user is logging in. And then have a way to access this information.
I found the best way to do so in a pinch as to log into Gmail API, and send myself an email saying “Person A just logged in”. I would continue to do so, but it has become more and more frequent that Google flags these logins for security reasons and my whole app gets bugged out because it won’t log in.
I would really prefer a way to keep track of who is logging in and when without having to send myself emails. Is there a way to do this that can circumvent the whole process of having to login to my email and possibly (likely) bug the whole app?
Thank you.

Context:
Would this recent announcement help? New Component: auth0_component, a simple way to authenticate a user - #4 by asehmi 10
Also, this sounds a lot like a request for analytics. There is a streamlit analytics extension – GitHub - jrieke/streamlit-analytics: 👀 Track & visualize user interactions with your streamlit app 18.


Clear uploaded files with button not working well

Question:
I have the for following code:
if 'key' not in st.session_state:           st.session_state.key = str(randint(1000, 100000000))
…
upload_files = st.file_uploader("Choose files", accept_multiple_files=True, type=['pdf'], key=st.session_state.key, help="Rerun if cache error")
…
if st.button('Clear Uploaded File(s)', help='click twice to clear ALL'):     for key in st.session_state.keys():          del st.session_state[key]
When I press the Clear… button, have to press twice to clear the uploaded listed files to be removed. And when I try adding new files, initial upload fails but repeat holds.  Would love to get this fix if someone could tell me how.

Context:
Hi @philsgu ,
Welcome to the community. You can try this:
import streamlit as st
if st.button('Clear Uploaded File(s)') and 'key' in st.session_state.keys():
    st.session_state.pop('key')
    st.experimental_rerun()

Thanks,
Akshansh


How to reduce the top blank area height of streamlit app?

Question:
When we start a streamlit app, after open explorer, we will see a huge blank area at the top.
How can we control the blank height with some argument and where we can do this?
Thank you.

Context:
I adapted this from @Marc’s Awesome Streamlit Resources 3 app.

BACKGROUND_COLOR = 'white'
COLOR = 'black'

def set_page_container_style(
        max_width: int = 1100, max_width_100_percent: bool = False,
        padding_top: int = 1, padding_right: int = 10, padding_left: int = 1, padding_bottom: int = 10,
        color: str = COLOR, background_color: str = BACKGROUND_COLOR,
    ):
        if max_width_100_percent:
            max_width_str = f'max-width: 100%;'
        else:
            max_width_str = f'max-width: {max_width}px;'
        st.markdown(
            f'''
            <style>
                .reportview-container .sidebar-content {{
                    padding-top: {padding_top}rem;
                }}
                .reportview-container .main .block-container {{
                    {max_width_str}
                    padding-top: {padding_top}rem;
                    padding-right: {padding_right}rem;
                    padding-left: {padding_left}rem;
                    padding-bottom: {padding_bottom}rem;
                }}
                .reportview-container .main {{
                    color: {color};
                    background-color: {background_color};
                }}
            </style>
            ''',
            unsafe_allow_html=True,
        )


ModuleNotFoundError: No module named ‘cv2’ Streamlit

Question:
Hi All,
I am trying to deploy an app that uses opencv. I have tried all the permutations so far by adding “opencv-python-headless” / “opencv-python” or “opencv-contrib-python”. I have also added packages.txt to remove the error “libGL.so.1: cannot open shared object file: No such file or directory”.
But still below error exists no matter what I try .
Traceback (most recent call last):
  File "detect.py", line 14, in <module>
ModuleNotFoundError: No module named 'cv2'

Contents of requirements.txt:
numpy
opencv-python
easyocr==1.4.1
matplotlib==3.4.3
matplotlib-inline==0.1.3
pandas==1.3.4
pandocfilters==1.5.0
Pillow==8.2.0
requests==2.26.0
scikit-image==0.18.3
scipy==1.7.1
seaborn==0.11.2
streamlit==1.0.0
torch==1.9.1
torchvision==0.10.1
tqdm==4.62.3

contents of packages.txt:
freeglut3-dev
libgtk2.0-dev
libgl1-mesa-glx

Kindly assist me in resolving the issue so that this error does not occur. Also, I have followed through other similar issues.

Context:
Hi @Shubham_Singh, welcome to the community!
The error is caused by line 137 of your app, where you run a Python script in a subprocess.

The packages in your requirements file are installed in a virtual environment. The Python binary used in this virtual env is found at /home/appuser/venv/bin/python

In line 137 of your app, you run python detect.py --weights ... via a subprocess. This Python binary is not the one used in the virtual env where your packages, including opencv-python-headless , are installed.
Change line 137 to the following:

detectCommand = "/home/appuser/venv/bin/python detect.py --weights ./resources/weights/best.pt --source ./resources/test_image/businessCard/ --img 512 --conf 0.6 --save-crop --save-conf --line-thickness 2 --iou-thres 0.5 --save-txt --name results"

Replace opencv-python in your requirements file with opencv-python-headless

Delete packages.txt

Reboot your app

Once you make the above changes, your detection script will run fine

image1703×1055 158 KB

Happy Streamlit-ing!
Snehan


Fetch data from sql database using Pypdbc package

Question:
I have a streamlit app that retrieve data from sql server database where i am using pyodbc.
I have an select  query where i try to select data based on user input using wild card inside the sql query.
The problem is that when the user search on any field beside the ID it does not return anything.

database:
CREATE TABLE [dbo].[t1](
	[ID] [int] IDENTITY(1,1) NOT NULL,
	[first] [nvarchar](50) NULL,
	[last] [nchar](50) NULL,
	[Rating] [int] NULL,
 CONSTRAINT [PK_t1] PRIMARY KEY CLUSTERED
(
	[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

python code:
import pandas as pd
import streamlit as st

advanced_search_term_list = []

if len(advanced_search_term_list)>0:

   sql="select * from testDB.dbo.t1 where (ID = ? OR ID is null) and (first LIKE  ? OR first is null) and (last LIKE ? or last is null) and (Rating = ? or Rating is null) "

   param0=advanced_search_term_list[0]

   param1=f'%{advanced_search_term_list[1]}%'

   param2=f'%{advanced_search_term_list[2]}%'

   param3=advanced_search_term_list[3]

   rows = cursor.execute(sql,param0,param1,param2,param3).fetchall()

the query just return data of the param0
where is the error in my code ??

Context:
It appears this is being answered here:

      stackoverflow.com

  Fetch data from sql database using Pyodbc package 9

  python, sql-server, wildcard, pyodbc

  answered by

    Zhorov

  on 01:48PM - 19 Oct 21 UTC


Question:
I just deployed my first streamlit application to Heroku using my GitHub repo as the method of deployment. When I tested the app using streamlit run, the app was running fine. However, I received a file not found error once I deployed it. I checked my GitHub and all the files were in the repo so I do not know why it does not recognize the .csv files. My application is simple: read .csv files and do some data analysis simple as that. I can provide screenshots if it will be useful.
screenshot of tested application (streamlit run):
image1920×1080 137 KB
Github repo that contains the file I am reading:
image1920×1080 227 KB
The error I got after deployment:
image1920×1080 220 KB

Context:
Hi @OmarEltouny78, welcome to the Streamlit community!
This is appears to be a simple issue of a relative filepath. If you’re sure that the file exists in your GitHub, then the next thing would be to try and specify the filepath more precisely than PL/PL2021_keepers.csv. pathlib seems to be the commonly-accepted package to use to avoid issues  like these:
https://docs.python.org/3/library/pathlib.html 79
Best,
Randy


Question:
Hello,
Please I have a concern with the Folium.Marker.
I am using streamlit to map our data. However when I try to use folium.Marker to display the Lat Long data of my dataFrame, although it displays them but in different maps.
I don’t know if it’s my rope that is causing the problem.
Please help me. Regards
Here is the problem in question in screenshot

image1589×782 258 KB

image525×855 123 KB

Context:
Hi @oberlin28, welcome to the Streamlit community!
Moving line 232 out of the loop should solve this. You want to loop over to add the points, but not call folium_static each time. Moving out of the loop will call it once, displaying the map once.
Best,
Randy


Why does my text input not focus with script in component.html when sessionstore is unchanged?

Question:
Hello,
I came across this topic when I was trying to find a way to .focus() a text input when the script is rerun

    NO WAY to set focus at top of screen on page reload. Really? Using Streamlit

    Hello @bilbo,
As you said, components.html encapsulates its code inside an iframe, but you can access the rest of the page with window.parent. That said, to scroll to the top, you’d do something like this:

There’s a little catch though. Passing this line directly to components.html may work only once, as it will render (and thus execute that javascript line) only once if no parameter was changed between two …

The approach shown there works fine, but I would like to know why it only
works when st.session_state['counter'] changes. It the line where it is incremented is commented the text box will not focus. If the counter increases, the text box
is focused when the button is clicked, the text input is sent via Enter or the select box changes (every time the callback is triggered).
This is the code:
import streamlit.components.v1 as components
import streamlit as st

def cbk():
    st.session_state['delete_line'] = True
    # st.session_state['counter'] += 1

option = st.selectbox('', [1,2,3],
                              index=1,
                              key='id_combo',
                              on_change=cbk)

if 'delete_line' not in st.session_state:
    st.session_state['delete_line'] = True

if 'counter' not in st.session_state:
    st.session_state['counter'] = 0

if st.session_state['delete_line']:

    st.session_state['id_answer'] = ''
    st.session_state['delete_line'] = False

y = st.text_input(f'', key='id_answer', on_change=cbk)

components.html(
    f"""

some hidden container

{st.session_state.counter}

    """,
    height=150
)

st.write(f'the submitted answer was {y}')

if st.button('Check', on_click=cbk):
    st.session_state['delete_line'] = True

Context:
Hello @solarjoe,
When your script reruns, Streamlit does not re-render HTML components that don’t change. And if they don’t change, javascript code included in them won’t be executed again.
So, to force Streamlit to re-render the component and execute its javascript code multiple times, we need to apply some change to it, hence the st.session_state.counter.


Can we integrate our HTML CSS UI with streamlit?

Question: I have UI designed for my web app using HTML and CSS. Can I use it as a layout for my streamlit web app ?

Context:
Hi Vansh,
Sure, you can use html and css components with streamlit. Just use components.html or components.iframe
https://docs.streamlit.io/library/components/components-api#streamlitcomponentsv1html 6
Thanks,
Akshansh


Handling button events while receiving data from a background thread

Question:
I’m new to using Streamlit and am hoping that it can work for my use-case.  I have a background thread that receives data from a process that I’m monitoring.  By using a loop I’m able to periodically update streamlit with updated state information.  I also have a button to interact with the background process.
The problem I face is that for the button’s press event to be captured, it needs to be inside the update loop.  However, once the button is pressed it remains in the pressed state until the script returns.  The work around has been to have the script return when the button is pressed and include a “restart” button that will re-run the script.  I’ve included an example below that re-creates this flow.
Is there a cleaner way to make this work?  I.e. is there a way to tell Streamlit to re-run the script programatically?
import streamlit as st
import time
import threading

class DataGenerator:
    def __init__(self):
        self.counter = 0

    def run(self):
        thread = threading.Thread(target=self._run, args=(), daemon=True)
        thread.start()

    def _run(self):
        while True:
            time.sleep(0.01)
            self.counter += 1

    def run_task(self):
        print(f"Do the thing once {self.counter}")

@st.cache(allow_output_mutation=True)
def generate_data():
    gen = DataGenerator()
    gen.run()
    return gen

# Declare UI Elements
running_time = st.empty()
generated_data = st.empty()
task_button = st.button("Do the thing")
kick_button = st.button("Restart")

# Start data generation
my_data = generate_data()

# Continually update the UI as data arrives from the background thread
while True:
    time.sleep(0.1)

    running_time.write(time.time())
    generated_data.write(my_data.counter)

    if task_button:
        my_data.run_task()
        break

Context:
Hi @Joseph_Moster
I have your same problem. Did you find a solution?
Thanks
Alessia


Question:
Hello guys. I have several ‘code’ elements on a row which I want to clear on the press of a button. Any ideas how I can do this? Thanks alot in advance
cols = st.beta_columns(3)
cols[0].code('id', language="markdown")
cols[1].code('name', language="markdown")
if cols[2].button('Clear'):
     # clear

Context:
st.code does not support session_state->widget_state interaction directly, so had to improvise a solution
import streamlit as st

if 'id' not in st.session_state.keys():
    st.session_state['id']='1'
if 'name' not in st.session_state.keys():
    st.session_state['name'] = 'name'

cols = st.columns(3)
cols[0].code(st.session_state['id'], language="markdown")
cols[1].code(st.session_state['name'], language="markdown")
if cols[2].button('Clear'):
    st.session_state['id']=''
    st.session_state['name']=''
    st.experimental_rerun()


How to save the uploaded rar, zip, 7z file through st.file_uploader and save them to specific directory of server?

Question:
If we upload picture, we can use PIL to save them to server.
If we upload csv or excel, we can use dataframe.to_csv or dataframe.to_excel to finish save task.
How about we upload rar, zip, 7z file, how should we save them to server?
Thank you.

Context:
For any arbitrary file type being passed to file_uploader, you can take the BytesIO buffer and write it to disk:

      stackoverflow.com

  Convert BytesIO into File 4

  python

  answered by

    Reid Ballard

  on 04:52AM - 23 Jun 16 UTC

Best,
Randy


Question:
Hi,
For a simple “Change Password” form, I want the user to be able to tab between the consecutive text_input fields.
Also, I want to be able to default the “show input” (eye icon) to “show”.
How can I do these things?

Context:
Hi @fredzannarbor ,
I think tab to switch to different text_input fields is supported by default.
As far as changing the default behaviour of the eye-icon, i don’t think that is supported yet.
Thanks,
Akshansh


Question:
When I ran this script
s = (full_name, birth_date, gender_)
'string:', s

Because streamlit got confused with the trailing underscore of gender_, it then displayed the string like this:
string: fullname, birth_date, gender
Is there a workaround to make streamlit display the string correctly, that is:
string: full_name, birth_date, gender_
Thanks

Context:
Hello @jaseuts, welcome to the forum!
Streamlit magic displays your string as a markdown text, and if you wrap some markdown text between _two underscores_, it is generally displayed in italic.
You can either add a backslash before gender’s underscore…
s = "(full_name, birth_date, gender\_)"

…wrap your string with backquotes (which will render with a monospaced font)…
s = "`(full_name, birth_date, gender_)`"

…or use st.text to display your whole string (renders with a monospaced font as well):
s = "(full_name, birth_date, gender_)"
st.text("string: " + s)


Question:
Hi guys,
I’m wondering if it is possible  to check text input values via a callback function.e.g.:
ip = st.text_input(‘IP for  system one’, value=‘192.168. …’, max_chars=18, on_change=my_callback)
my_callback should check if the input is a valid ipaddress. However I don’t know how streamlit hands
the input over to the callback function and how to reference it in the function
Is it possible to do that  during input or do I have to use  a form_submit_button on_click callback and provide the inputs as arguments to the on_click function?
Thanks

Context:
That would be great If someone could answer this quesiton.
I searched everywhere but couldn’t find the solution.


Question:
I’m trying to deploy a Streamlit app to Windows. I managed to set up all the environment and dependencies and get it start (for the details on how I deploy the app, refer to this question 2). But it immediately blocks asking for credentials.
This is the log:
  Welcome to Streamlit!

  If you're one of our development partners or you're interested in getting
  personal technical support or Streamlit updates, please enter your email
  address below. Otherwise, you may leave the field blank.

  Email:
2021-10-11 20:56:53.202 WARNING streamlit.config:
Warning: the config option 'server.enableCORS=false' is not compatible with 'server.enableXsrfProtection=true'.
As a result, 'server.enableCORS' is being overridden to 'true'.

More information:
In order to protect against CSRF attacks, we send a cookie with each request.
To do so, we must specify allowable origins, which places a restriction on
cross-origin resource sharing.

If cross origin resource sharing is required, please disable server.enableXsrfProtection.

2021-10-11 20:56:53.202 DEBUG   streamlit.logger: Initialized tornado logs
2021-10-11 20:56:53.202 ERROR   streamlit.credentials:

It seems that the execution of the app is stopped becuase it is waiting for some credentials. I found here 1 that a .streamlit/credentials.toml can be added, but I’m not sure on the exact location on windows. I’ve also tried to explicitly add --server.headless=false while launching streamlit, but again with no effect.
Why the app doesn’t start automatically like on Linux, showing the address where the app can be reached? Is there a way to start the app without additional configurations by the user?

Context:
Problem overcome, I mistakenly set to false the --server.headless configuration. Instead, it must be true. Another argument is required to make the deploy work properly: --global.developmentMode=false.
Full anwser here 2.


Interference/Crosstalk using python libraries across sessions

Question:
Hello,
We notice there is interference while using standard libraries across sessions. We noticed this in the random and matplotlib libraries in our project.
We reproduce this error with this snippet of code :
Please run two sessions (open two windows or browsers with the same app) and click on start such that both apps run simultaneously.
import streamlit as st
import random

button1 = st.button("Start")
if button1:
    random.seed(1)
    for i in range(100000000):
        random.random()
    st.write(random.random())

When we run them independently, the apps run as expected. But, when there is overlap or while the app is run on both sessions simultaneously, there is interference. This can be seen in the changed value of the write. Even Matplotlib library has a similar issue while trying to plot.
This is a workaround for the code discussed above such that even with overlapping computation or simultaneous run, the returned answer is identical.
import streamlit as st
import random

button1 = st.button("Start")
if button1:
    i=0
    for i in range(500000):
        random.seed(i)
        random.random()
    random.seed(i)
    st.write(random.random())

This workaround involves constant re-setting of the seed value. Please advise.

Context:
An example for the interference with the Matplotlib library is as follows :
With two sessions opened, click on button 2 on one of the sessions and immediately click on button 1 in the other session.
import matplotlib.pyplot as plt
import streamlit as st
import time

one = st.button("1")
two = st.button("2")

if one:
    x = [0,1,2,3,4]
    y = x
    plt.title("Hello 1")
    plt.plot(x,y)
    st.pyplot(plt)

if two:
    plt.title("Hello 2")
    x = [0,1,2,3,4]
    y = x
    plt.plot(x,y)
    plt.title("Hello 1")

    time.sleep(5)

    x = [4,3,2,1,0]
    plt.plot(x,y)
    st.pyplot(plt)

Notice that while both buttons are pressed with overlap, the plot in button 2 changes.
Screenshots -
Running button 2 independently -

Screenshot 2021-10-18 at 6.46.20 PM1302×1266 90.9 KB

Running button 2 overlapping with running button 1 on another session -

Screenshot 2021-10-18 at 6.46.08 PM1302×1224 68.8 KB


Question:
Hi,
it may have already been answered, but I would like to ask if the Network URL can accommodate for multiple runs from multiple users.
For example, the same Network URL is shared to 3 different users. Can they use the application in an independent manner or each time a new event is triggered the app will restart for all of them.
Thanks

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

 greek_quant:

Can they use the application in an independent manner or each time a new event is triggered the app will restart for all of them.

Yes, Streamlit supports multiple users.


Question: Hi, I’m having some trouble loading a textfile with the fileuploader method. When I reduce the amount of data in the file it works fine. So unless i remove something from the content of the file that is causing issues (seems unlikely?), it might be caused by the filesize (102 mb). The errormessage seems to be “405: Method Not Allowed”. Changeing filename does not alter the result. Is there a known limit to the size of the file being uploaded?

Context:
Hi @Tobe, welcome to the Streamlit community!
The first thing to check is whether you have the latest version of Streamlit (0.62.1). A few releases ago, we moved the file upload limit from 100MB to 200MB by default. If you want to upload larger files, you can, you just need to increase the max limit in a config.toml file:
# Max size, in megabytes, for files uploaded with the file_uploader.
# Default: 200
maxUploadSize = 200

https://docs.streamlit.io/en/stable/cli.html#view-all-config-options 121


Clearing all selected items (check box, radio buttons & selectbox)

Question:
Hello Team,
I’m trying to reset my selection by deleting each element in streamlit.session.state.
But not able to do so.
Reproducible Code -
import streamlit as st
from streamlit import caching

st.set_page_config(layout="wide")

columns = st.columns(4)

columns[0].header("Session State Start")
columns[0].write(st.session_state)

n_check_box = 3
columns[1].header("Sample CheckBox")
for i in range(n_check_box):
    label = "check_box_" + str(i + 1)
    columns[1].checkbox(label=label, value=False, key=label)

n_radio_button = 2
columns[2].header("Sample Radio Button")
for i in range(n_radio_button):
    key = "radio_button_" + str(i + 1)
    label = "Radio Selection " + str(i + 1)
    values = ["Radio " + str(n) for n in range(n_radio_button)]
    columns[2].radio(label, values, key=key)

columns[3].header("Session State End")
columns[3].write(st.session_state)

if st.button("Clear Selection", key="clear_selection_button"):
    st.subheader("Executing code")
    code_clear_session_state = """
    for key in st.session_state.keys():
        del st.session_state[key]
    caching.clear_cache()"""
    st.code(code_clear_session_state, language="python")

    for key in st.session_state.keys():
        del st.session_state[key]
    caching.clear_cache()

Context:
Github issue

      github.com/streamlit/streamlit

      Can't reset selected items (check box, radio buttons) by clearing session.state 5

        opened

        Sep 24, 2021

          sachinpatel248

          bug

          needs triage

    ### Summary

Can not clear existing selected items from **check box, radio but…tons**.
Tried to reset my selection by deleting each element in `streamlit.session.state`

> **Is there any workaround to achieve this?**

### Steps to reproduce

Code snippet:

```
import streamlit as st
from streamlit import caching

st.set_page_config(layout="wide")

columns = st.columns(4)

columns[0].header("Session State Start")
columns[0].write(st.session_state)

n_check_box = 3
columns[1].header("Sample CheckBox")
for i in range(n_check_box):
    label = "check_box_" + str(i + 1)
    columns[1].checkbox(label=label, value=False, key=label)

n_radio_button = 2
columns[2].header("Sample Radio Button")
for i in range(n_radio_button):
    key = "radio_button_" + str(i + 1)
    label = "Radio Selection " + str(i + 1)
    values = ["Radio " + str(n) for n in range(n_radio_button)]
    columns[2].radio(label, values, key=key)

columns[3].header("Session State End")
columns[3].write(st.session_state)

if st.button("Clear Selection", key="clear_selection_button"):
    st.subheader("Executing code")
    code_clear_session_state = """
    for key in st.session_state.keys():
        del st.session_state[key]
    caching.clear_cache()"""
    st.code(code_clear_session_state, language="python")

    for key in st.session_state.keys():
        del st.session_state[key]
    caching.clear_cache()

```

**Steps :**

1. Select any option/(s) from radio button & checkbox.
2. Click on `Clear Selection` button

**Expected behavior:**

On clicking Clear Selection all selected items should get clear/reset.

**Actual behavior:**

Selected data persists

![streamlit-sessio-state-issue](https://user-images.githubusercontent.com/8427202/134623033-3bed70a8-d312-46aa-86ec-c2ea401313ed.gif)

### Is this a regression?

Not sure

### Debug info

- Streamlit version: 0.86.0
- Python version: 3.8.8
- Using: PipEnv
- OS version: Windows 10
- Browser version: Chrome 93

### Additional information

Had asked this in streamlit forum https://discuss.streamlit.io/t/clearing-all-selected-items-check-box-radio-buttons-selectbox/16605


Bypassing the 200MB size limit for multi-file uploads?

Question:
Hello!
I’d like to build a utility via Streamlit for server log files. One of the challenges is that the files I need to concatenate are ~500MB each (that is, above the 200MB file size limit).
Is there a way to increase that cap?
No worries if not, I can build a connector to my google cloud buckets, but I thought it may be a handy thing to have
Thanks,
Charly

Context: You can update the 200MB file size limit with server.maxUploadSize. The value is in MB and defaults to 200. If you have problems, let me know!


Question: Hi! I need some help with my streamlit app. I have a local zip file and want to add a link to download in my app. Can someone help me with this?, i found some codes but none is working to me, Thanks in advance!

Context:
Hi @diegovct and @BeyondMyself
With Streamlit version 0.88.0, you can use st.download_button 3
If your zip file, say myfile.zip, is in the same location as your app:
import streamlit as st

with open("myfile.zip", "rb") as fp:
    btn = st.download_button(
        label="Download ZIP",
        data=fp,
        file_name="myfile.zip",
        mime="application/zip"
    )

If it’s in a folder, say dir/myfile.zip, you can download from a file pointer:
import streamlit as st

with open("dir/myfile.zip", "rb") as fp:
    btn = st.download_button(
        label="Download ZIP",
        data=fp,
        file_name="myfile.zip",
        mime="application/zip"
    )

Happy Streamlit’ing!
Snehan


How i can display dataprep on my app need help please

Question:
i want to display this code on my app streamlit but nothink happend se please need help
from dataprep.eda import *

if st.checkbox('Create a rapport'):
    rapport=create_report(df)
    st.write(rapport)
    st.pyplot()

Context:
Hi @sammarisalah, welcome to the Streamlit community!
What does the create_report function do?


No such file or directory error: streamlit cloud

Question:
Hi all
I’ve been struggling to deploy a simple app from a private GitHub repo via streamlit cloud for some time. The app works when running it locally.
My repo structure looks like this. The streamlit .py app and a .xlsx spreadsheet are in the same folder.

image1017×133 7.23 KB

I’ve tried various approaches to get this to work, but have settled on using pathlib so streamlit can find the root directory (see line 12). Based on what I’ve read from others who have had similar issues, this should work.

image741×472 20.9 KB

However when I go to deploy the app, it keeps returning back this error (even after trying various combinations of relative and absolute directory paths)

image922×28 2.12 KB

Any advice would be great, as I’m sure there’s an obvious solution which I can then take forward!

Context: OK, I’ve changed the import data from Excel (.XLSX) to multiple CSVs and the app now works as expected. Pretty strange to be honest, but at least the app is deployed now.


Question:
Hi,
This is my first shared app and everything works fine except when you click on st.button which invokes to pyperclip module.
It appears the following error:Captura de pantalla 2020-10-20 a las 12.21.221458×530 58.2 KB
I assume I have to install xclip or something similar but I don’t know from where I can do that.
Any help much appreciated.

Context:
Hi @VerbisAnimae, welcome to the Streamlit community!
In order to install system packages on Streamlit sharing, you can create a packages.txt file:

      docs.streamlit.io

Deploy an app — Streamlit 0.69.2 documentation 9

Best,
Randy


Question:
Hi, I have a voice assistant in my project, It works fine in my local system while deploying it throws an error, I am new to this, If any help is appreciated.
Pyaudio error
fatal error: portaudio

screenshot of my error

Screenshot (44)1818×918 97.7 KB

Context:
Hello @Jaiharish-passion07
I think we had this issue before here: PortAudio Library Not Found 5

PortAudio Library Not Found

so my guess would be you need to install libportaudio2 this when creating the Heroku worker, maybe someone here knows how to but otherwise the Heroku community is your best bet.

Depending on where you are deploying there should be an intermediate step to instapp apt packages, this is where you’d want to install PortAudio. Hope that clears some things up!
EDIT: ah wait this is on Streamlit Share, let me check real quick.
EDIT2: so I “think” I got this working using this 6. Did not fully test but it doesn’t err anymore at the install.
Add a packages.txt file at the root of your project with the following contents:
build-essential
libasound-dev
portaudio19-dev
python3-pyaudio

You can check this repo 10 for a working example.
Have a nice day,
Fanilo


Secrets management unhashable in @st.cache

Question:
I am using the st.secrets() feature to supply my Streamlit app with a login token for an on-demand Dask Cluster via Coiled.io 1
The script runs fine before including the st.secrets() line but fails when I include it with the following message in the app terminal, copied below.
I’m not familiar enough with hashing to understand what this actually means  – any help here would be very much appreciated!
streamlit.hashing.UnhashableTypeError: Cannot hash object of type `_thread.RLock`, found in the body of `get_client()`.

While caching the body of `get_client()`, Streamlit encountered an
object of type `_thread.RLock`, which it does not know how to hash.
To address this, please try helping Streamlit understand how to hash that type
by passing the `hash_funcs` argument into `@st.cache`. For example:

@st.cache(hash_funcs={_thread.RLock: my_hash_func})
def my_func(...):
    ...

If you don't know where the object of type `_thread.RLock` is coming
from, try looking at the hash chain below for an object that you do recognize,
then pass that to `hash_funcs` instead:

Object of type _thread.RLock: <unlocked _thread.RLock object owner=0 count=0 at 0x7f2b088cedb0>

Object of type builtins.tuple: ('_lock', <unlocked _thread.RLock object owner=0 count=0 at 0x7f2b088cedb0>)

Object of type builtins.dict: {'_secrets': {'coiled_token': '<hidden>', 'coiled_account': '<hidden>'}, '_lock': <unlocked _thread.RLock object owner=0 count=0 at 0x7f2b088cedb0>, '_file_watcher_installed': True, '_file_path': '/app/streamlit/.streamlit/secrets.toml'}

Object of type streamlit.secrets.Secrets: {'coiled_token': '<hidden>', 'coiled_account': '<hidden>'}

Object of type builtins.function: <function get_client at 0x7f2b5b4e6ca0>

Context:
rrpelgrim:

st.secrets("coiled_account")

Use square brackets instead of parenthesis
st.secrets["coiled_account"]

Best,
Snehan


How to get something printed from a function

Question:
def movie_edit1(moive, inp):
		inp_alpha = []
		inp_alpha = inp
		movie_list = []
		movie = ""
		movie_list[:0] = movie

		for i in range(0, len(movie)):
			if(movie_list[i] not in inp_alpha):
				movie_list[i] = "_"
			if(movie[i] == ''):
				movie_list[i] = ' '
		movie_new = ""

		for x in movie_list:
			if(x == "_"):
				movie_new += '-'
			else:
				movie_new += x
		return movie_new

     h_list=['Avengers','Charlie And The Chocolate Factory','The Lion King','Inception','Harry Potter',
	'Suicide Squad','Bird Box','Annabelle','The Ring','The Amazing Spiderman']

	b_list=['Welcome','Ready','Happy New Year','My Name Is Khan','Highway','Student Of The Year',
	'Dear Zindagi','Kahaani','Talaash','Bhaag Milkha Bhaag']

	input_alpha=["a","i","e","o","u","A","E","I","O","U"]

st.write(f"{movie_edit1(h_list[n], input_alpha)}")
		x = movie_edit1 (h_list[n], input_alpha)
		st.write(f"{x}")

I am trying to get this above line printed but for some reason, it shows a blank space instead whenever I run it.

Context: I don’t know if it’s just a typo in this post or if it’s in your code, but in your post, your parameter for movie_edit1 is misspelled as moive rather than movie.


How to output matplotlib chart built by module function?

Question: I’m using a module that has a function that outputs a chart, but calling the function in st.write() returns “none”. Any ideas on how to display a chart generated by a module function?

Context: Have you tried using st.pyplot()?


Deploy an app - This file does not exist

Question:
Dear Streamlit,

Screen Shot 2022-01-03 at 10.08.09 PM909×668 31.3 KB

Im trying to deploy the app, I’ve got everything on GitHub (link below)

      github.com

    GitHub - deterius/OnlineMetrics_streamlit at onlineMetrics_git 3

  onlineMetrics_git

  Contribute to deterius/OnlineMetrics_streamlit development by creating an account on GitHub.

But I can’t seem to find the main app file (OnlineMetrics.py), see screenshot attached.
Any help would be appreciated!

Context: Have you tried checking which branch you are using? It looks like the OnlineMetrics.py file is on a branch named onlineMetrics_git rather than main.


How to run a scheduler, one process per app?

Question:
I’m looking to run a scheduler or some kind that will pull data from a source every now and then and display it but how to do this since I only want it to process once per the whole app and not user sessions.
Related, it would nice if we could get terminal access or run tmux ?

Context:
Hi @rlf037 -

 rlf037:

I’m looking to run a scheduler or some kind that will pull data from a source every now and then and display it but how to do this since I only want it to process once per the whole app and not user sessions.

The scheduler piece isn’t currently possible, though it’s probably possible to mock up something using a combination of the ttl parameter with caching and streamlit-autorefresh.

 rlf037:

Related, it would nice if we could get terminal access or run tmux ?

It’s unlikely that in the near-term we’ll be providing this access, as we’re focusing on making Streamlit Cloud the fastest way to get started with Streamlit, not making a generalized container service.
Best,
Randy


No module named ‘matplotlib’ when deploying app

Question:
image1920×1080 128 KB

this is my .txt file
beautifulsoup4==4.10.0
gensim==3.8.3
Keras==2.4.3
matplotlib==3.3.2
nltk==3.5
numpy==1.19.2
pandas==1.1.3
Pillow==9.0.0
requests==2.24.0
Sastrawi==1.0.1
scikit_learn==1.0.2
seaborn==0.11.0
selenium==4.1.0
snscrape==0.4.3.20220106
streamlit==1.4.0
tensorflow==2.4.1
textblob==0.17.1
webdriver_manager==3.5.2
wordcloud==1.6.0
i manage to build the App on local host, but when deploy it seems streamlit doesn’t ‘have’ the matplot package

Context:
Hi @ahengg, welcome to the Streamlit community!
Can you post a link to your GitHub repo?
Best,
Randy


App Stuck in the Oven but working Locally?

Question:
Hello!
I created an uploaded an app and it seems to be stuck in the oven!

image2560×1400 176 KB

Here is a photo of it as of now.
The link is https://share.streamlit.io/crodriguezm2016/spotifywrapped/main/spotifyapp.py 2
My Github Repo is GitHub - crodriguezm2016/SpotifyWrapped 2
I’m not too sure why it isn’t working on the site though. When I run it locally, it works fine…

Context: Deleting and relaunching fixed it! Thanks!


Server error [A15]: Error creating workspace What does this mean?

Question:
I’ve been trying to deploy my app in streamlit sharing but keep getting the error Server error [A15]: Error creating workspace. I’m not sure but I recently changed my github username but I have revoked and reauthorized streamlit’s access to my repository.
Wondering if anyone else has any experience with fixing this error code? Thanks!

Context:
Hi @chisantos, and welcome to the Streamlit community!
I’m not familiar with this issue, not something I ever come across.
It seems to me like a temporary issue. Have you tried to:

delete your app
reconnect it to Github

Best,
Charly


FileNotFoundError: [Errno 2] No such file or directory: ‘C:/Users/Utilisateur/OneDrive/Bureau/PROJET7/data_train.csv’

Question:
I am trying to deploy my app on streamlit cloud, and I am having a problem with paths.
Here is my repo https://github.com/SaidMANAM/Application-IA-scoring_CREDIT

Screenshot 2022-01-25 at 17-45-21 File Finder · SaidMANAM Application-IA-scoring_CREDIT1196×806 17.3 KB

Thanks in advance for the help !

Context:
Hi @SaidMANAM, welcome to the Streamlit community!
It’s important to note that absolute paths to your local computer directory mapping  is unlikely to work on another computer, irrespective of using Streamlit Cloud or another hosting service. You need to use relative references 2 to the files for your code to work.
Best,
Randy


Question:
When I run streamlit run, I can upload images without error and they are displayed as I wrote them,
But when I upload to streamlit sharing, I get the error below
OSError: This app has encountered an error. The original error message is redacted to prevent data leaks. Full error details have been recorded in the logs (if you're on Streamlit Cloud, click on 'Manage app' in the lower right of your app).
Traceback:

File "/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 379, in _run_script
    exec(code, module.__dict__)
File "/app/face_api_streamlit/main.py", line 74, in <module>
    draw_text(result)
File "/app/face_api_streamlit/main.py", line 44, in draw_text
    text, font = get_draw_text(faceDictionary)
File "/app/face_api_streamlit/main.py", line 34, in get_draw_text
    font = ImageFont.truetype('Arial', font_size)
File "/home/appuser/venv/lib/python3.7/site-packages/PIL/ImageFont.py", line 855, in truetype
    return freetype(font)
File "/home/appuser/venv/lib/python3.7/site-packages/PIL/ImageFont.py", line 852, in freetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
File "/home/appuser/venv/lib/python3.7/site-packages/PIL/ImageFont.py", line 212, in __init__
    font, size, index, encoding, layout_engine=layout_engine

スクリーンショット 2022-01-24 12.03.181820×516 69.8 KB

What I did for fixing.
I changed the codes like below and run it but not resolved yet…

font = ImageFont.truetype(font='/System/Library/Fonts/Arial', size=20, index=0, encoding='', layout_engine=None)

font_path = '/System/Library/Fonts/Arial'

font = ImageFont.truetype(font=font_path, size=20, index=0, encoding='', layout_engine=None)

Mac OS
Python 3.9.2
Streamlit 1.4.0

Context:
Hi @01mayo, welcome to the Streamlit community!
It’s important to note that you are using a Mac for local development, and the Streamlit Cloud image is based on Debian. So specifying an exact file directory isn’t going to work.
According to this snippet, it looks like fonts are installed at /usr/share/fonts, but I would suggest trying to find a programmatic way to set that in your app so that you don’t need to switch the reference based on where the app is running.

      superuser.com

  Location of truetype fonts

  linux, fonts

  asked by

    StackedCrooked

  on 01:55PM - 05 May 10 UTC

Best,
Randy


Bypassing the 200MB size limit for multi-file uploads? how to change in streamlit sharing cloud

Question: Hey, Can anyone please guide to change the limit in streamlit sharing with proper steps. Thanks in advance,

Context:
Hi @Akshay_Aksh, welcome to the Streamlit community! You can find the steps in the following article:

      docs.streamlit.io

How do I increase the upload limit of st.file_uploader on Streamlit Cloud? -... 3

Best,
Randy


How to add an ODBC driver to streamlit cloud?

Question:
Hi,
I have an app that works locally fine, but requires ‘ODBC Driver 17 for SQL Server’ to be installed to retrieve data using pyodbc when deployed. I have tried using a requires.txt file with combinations of the below (as per other posts) but it comes up with a could not be located message (I guess because Linux based).
What does everyone else do to get around this? As there must be a way to do this, any help massively appreciated.
unixodbc-dev
msodbcsql17
mssql-tools

[This is the link to the microsoft documentation.]
Thanks

Context:
I think you have to delete your app and re-deploy, so that the new version of the container gets used. Could you try that @Mark_Von_Oven and @Andy_J?
The driver should be the official MS SQL driver.


App in Streamlit Cloud not running in the same way as on local host

Question:
hi …
I managed , for most part, deployed my app to Streamlit cloud and ended with the following message.
2022-01-14 08:52:14.477940: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2 FMA. To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
I wasn’t sure what to do with it, and ran my application ( GitHub - Ipomoeabatatas/TiHar 1 ).
The app was suppose to identify changing human action in a video clip with labels constantly over it.
As I run it, I get the error below.
2022-01-14 08:53:01.702 InMemoryFileManager: Missing file c8badebc9f2aac3c6482116046c4fb4d6747832688fbfbff4ee59767.jpeg
I suspect it has something to do with the tensorflow installation error message.
Any hints to resolve this will be tremendously appreciated.

Context:
It is not related with tensorflow but with with the rendering of the image. I assume you have somewhere a st.image(some_numpy_image) which is causing the InMemoryFileManager error. How did you deploy it? I deployed a streamlit app to Google Cloud Run (serverless) and was having the exact same problem that you are having, unfortunately couldn’t manage to solve it. It seems that (at least with Cloud run) different machines can be spawn so the image is generated in one machine and other tries to serve it, see this same issue: MediaFileManager: Missing file on Google App Engine · Issue #3334 · streamlit/streamlit · GitHub 1
I manage to solve it by deploying it to just a single machine.
After a lot of trying it was also solved in Cloud Run by setting Maximum requests per container to a high value and vCPU=1
Another ugly option it worked for me before finding the other solution was by uploading the image you want to render to a persistent storage (like GCP Cloud storage) and return the URL to it instead of the numpy array.


Unable to open video camera in streamlit cloud

Question:
logs1896×923 55.1 KB

Here is the image of the logs after deploying my streamlit app on streamlit cloud.
I am building an app for realtime emotion recognition using webcam.
The app works fine when i run it locally. But the webcam is unable to open when running the app on streamlit cloud.
If anybody can please help me in solving the issue… it would be really appreciated…
I am using streamlit == 1.4.0 and streamlit webrtc == 0.34.1
Here is the link of the code for the app deployed - fer-app/app.py at branch-1 · SuhasTantri/fer-app · GitHub
Here is the streamlit cloud link - https://share.streamlit.io/suhastantri/fer-app/branch-1/app.py
Thanks in advance!
@whitphx

Context: streamlit webrtc works well on your local setup but has issues when deploying on the cloud try using heroku to deploy your app and see if the problem still persist, which i think the error may still occur.


Deploying in Streamlit Share gives error. I am using Python 3.8

Question:
Hi, I am using Streamlit share to deploy my app.  I get the following error. And I found somewhere that Python 3.8 will not work for streamlit share. Is it true?
Last few lines of my log given below
Collecting ipykernel==6.7.0

  Downloading ipykernel-6.7.0-py3-none-any.whl (127 kB)

ERROR: Could not find a version that satisfies the requirement ipython==8.0.1 (from versions: 0.10, 0.10.1, 0.10.2, 0.11, 0.12, 0.12.1, 0.13, 0.13.1, 0.13.2, 1.0.0, 1.1.0, 1.2.0, 1.2.1, 2.0.0, 2.1.0, 2.2.0, 2.3.0, 2.3.1, 2.4.0, 2.4.1, 3.0.0, 3.1.0, 3.2.0, 3.2.1, 3.2.2, 3.2.3, 4.0.0b1, 4.0.0, 4.0.1, 4.0.2, 4.0.3, 4.1.0rc1, 4.1.0rc2, 4.1.0, 4.1.1, 4.1.2, 4.2.0, 4.2.1, 5.0.0b1, 5.0.0b2, 5.0.0b3, 5.0.0b4, 5.0.0rc1, 5.0.0, 5.1.0, 5.2.0, 5.2.1, 5.2.2, 5.3.0, 5.4.0, 5.4.1, 5.5.0, 5.6.0, 5.7.0, 5.8.0, 5.9.0, 5.10.0, 6.0.0rc1, 6.0.0, 6.1.0, 6.2.0, 6.2.1, 6.3.0, 6.3.1, 6.4.0, 6.5.0, 7.0.0b1, 7.0.0rc1, 7.0.0, 7.0.1, 7.1.0, 7.1.1, 7.2.0, 7.3.0, 7.4.0, 7.5.0, 7.6.0, 7.6.1, 7.7.0, 7.8.0, 7.9.0, 7.10.0, 7.10.1, 7.10.2, 7.11.0, 7.11.1, 7.12.0, 7.13.0, 7.14.0, 7.15.0, 7.16.0, 7.16.1, 7.16.2, 7.16.3, 7.17.0, 7.18.0, 7.18.1, 7.19.0, 7.20.0, 7.21.0, 7.22.0, 7.23.0, 7.23.1, 7.24.0, 7.24.1, 7.25.0, 7.26.0, 7.27.0, 7.28.0, 7.29.0, 7.30.0, 7.30.1, 7.31.0, 7.31.1)

ERROR: No matching distribution found for ipython==8.0.1

WARNING: You are using pip version 21.1.1; however, version 21.3.1 is available.

You should consider upgrading via the '/home/appuser/venv/bin/python -m pip install --upgrade pip' command.

[manager] installer returned a non-zero exit code

  Stopping...

[manager] Streamlit server consistently failed status checks

[manager] Please fix the errors, push an update to th

Context: I found the solution friends. You can change the version of Python in your app (Advanced settings). You can choose from 3.7, 3.8, and 3.9. I am not sure if it can be done after creating the app. I deleted and created a new app again since I am just beginning with mine.


Issues displaying a PDF in Streamlit App

Question:
Hello!
Around a month ago, I believe my app was working in displaying a PDF from my desktop. At the moment, I’m attempting to read a file in, save it to my desktop, then read the file from my desktop and show it as a PDF. (Perhaps there is an easier way to do this, but that’s the best I could find!)
The code that is doing this is below:
elif choice == ‘MAP’:
#outdir = st.text_input("Please enter the pathway to you documents folder, in order to generate KEGG file",value="/Users/hellpark/Desktop/",help='Ex: /Users/hellpark/Desktop/')
outdir = "/Users/hellpark/Desktop/"
pathinput = st.text_input("To generate Halomonas map of genes in KEGG, please enter pathway of interest",value='hel00010',help='type pathway like, hel00010 after the path:')
img_filename = "%s.pdf" % pathinput
draw_kegg_map(pathinput,outdir)

with open(os.path.join(outdir, img_filename),"rb") as f:
     base64_pdf = base64.b64encode(f.read()).decode('utf-8')
     pdf_display = F'<iframe src="data:application/pdf;base64,{base64_pdf}" width="900" height="700" type="application/pdf"></iframe>'
     st.markdown(pdf_display, unsafe_allow_html=True)

Also, here is the link to my GitHub and the app:
https://share.streamlit.io/helloftroy/omics_td1.0/main/Streamlit.py 1 (select ‘MAP’)
Omics_TD1.0/Streamlit.py at main · helloftroy/Omics_TD1.0 · GitHub 1
And, my issue is in the screenshot below!

Screen Shot 2022-01-18 at 1.42.48 PM750×636 73.8 KB

If you can help at all that would be amazing! It did used to work, and I haven’t changed the code!
Helen

Context:
Hi @Helen_Park -
It’s important to remember that once an app is published on Streamlit Cloud or any other deployment platform, the file paths now refer to where the Python code is running, not the browser where the user is sitting. So this line in your code won’t work:

      github.com

    helloftroy/Omics_TD1.0/blob/main/Streamlit.py#L198

elif choice == 'KEGG':
                kegginput = st.text_input("Seach KEGG Halomonas Database", value="Porin",max_chars=200,help='Type + between the words you are searching for')
                st.write(to_df(kegg_find('hel', kegginput).read()))

elif choice == 'MAP':
                st.write("### List of Halo KEGG pathways")
                st.write(to_df(kegg_list('pathway', 'hel').read()))

                #outdir = st.text_input("Please enter the pathway to you documents folder, in order to generate KEGG file",value="/Users/hellpark/Desktop/",help='Ex: /Users/hellpark/Desktop/')
                outdir = "/Users/hellpark/Desktop/"
                pathinput = st.text_input("To generate Halomonas map of genes in KEGG, please enter pathway of interest",value='hel00010',help='type pathway like, hel00010 after the path:')
                #str = to_df2(kegg_get(pathinput).read())
                img_filename = "%s.pdf" % pathinput
                #st.write(img_filename, pathinput, outdir)
                draw_kegg_map(pathinput,outdir)

    st.write("### KEGG Pathway with Halomonas TD1.0 genes highlighted")
                with open(os.path.join(outdir, img_filename),"rb") as f:
                     base64_pdf = base64.b64encode(f.read()).decode('utf-8')

You would need to have that directory in your GitHub repo and refer to it by a path reference to make this app work on Streamlit Cloud.
Best,
Randy


When deployed I get the following two errors involving script_runner.py and import pyPDF2

Question:
I’m running into two problems. I working on a file uploader and during the build I get the following error “‘NoneType’ object has no attribute ‘seek’”, but my code works and I get the output I am looking for.
The second error I get when I deploy the app File “/home/appuser/venv/lib/python3.7/sitepackages/streamlit/script_runner.py”, line 354, in _run_script exec(code, module.dict)
and
File “/app/293pending_cases/pending_cases.py”, line 4, in
import docx2txt
however, I have removed the docx2txt import and still getting this error. When it does clear its followed by import pyPDF not found…I am not sure where I am going wrong. Any advice is greatly appreciated.

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

ModuleNotFoundError: No module named ‘PyPDF2’

The issue is that your repository does not contain a requirements file with your Python dependencies. As such, Streamlit Cloud has not installed packages like PyPDF2, docx2txt, gspread, etc, that your app uses.
Read our documentation on App dependencies and a knowledge base article on the ModuleNotFoundError.
You have the option of manually creating a requirements.txt file and including a Python package on each line. Take care to use the package name as it appears on PyPI. E.g. scikit-learn, not sklearn.
Alternatively, you can automate the creation of a requirements.txt using pipreqs. Run:
pipreqs /path/to/293rd_pendening_cases/

It will create a requirements.txt file for you that you can upload to GitHub.
When I run the above command upon cloning your repo, it creates a requirements file with the following entries:
gspread==5.1.1
streamlit==1.4.0
docx2txt==0.8
df2gspread==1.0.4
pandas==1.2.5
PyPDF2==1.26.0

Hope this helps!
Best,
Snehan

Resources

App dependencies - Streamlit Docs
ModuleNotFoundError No module named - Streamlit Docs


Pytube Issue / bug : https://github.com/pytube/pytube/issues/1199#issuecomment-1017372476

Question:
Dear Streamlit team,
There is recent bug with pytube library and I have an app running on Streamlit Cloud using pytube.
To solve the problem locally I changed the line 30 in pytube/cipher.py :
from var_regex = re.compile(r"^\w+\W")
to
var_regex = re.compile(r"^\$*\w+\W")
But you would probably need to fix this on your side so that apps - deployed on Streamlit Cloud - using pytube can run properly.
The issue was open on Github 19 hours ago → [BUG] RegexMatchError ? · Issue #1199 · pytube/pytube · GitHub 1
Thank you, Reda Merzouki (from Paris France).

Context:
Hi @rmerzouki, welcome to the Streamlit community!
This isn’t something we can “fix on our side”. It looks like pytube is in the process of pushing out a new version of the package; when that happens, you can update your Streamlit app dependencies to have that new version and upon making that commit in your repo, the app will re-build.
Best,
Randy


“ModuleNotFoundError” but the module is correctly installed

Question:
I get this error:
File "/app/trial-aid/streamlit_app.py", line 2, in <module>
    import plotly.express as px

However plotly is correctly installed through conda env .yml file (version=5.5.0), moreover before I pushed to the repository and updated the app it was perfectly working (and I didn’t change the plotly import).
The repository can be found at: https://github.com/voidpunk/Trial-AId 1
I also tried to delete and re-build the app, but it keeps the environment and only reboot it, which isn’t really helpful…

Context:
Yes, sorry, I forgot to post the solution.
It was only due to some sort of conflict between libraries, I deleted the environment and recreates a new one,  then I reinstalled the needed libraries and exported the yml, it worked. I installed some libraries to get some data in the same environment which weren’t needed for the final app, I suspect that one of them may be the cause of the environment not working on deploying (on local, Streamlit app was still working perfectly even in the “broken” environment)


Question:
I tried deploying a machine learning model that I built using h2o. However, java needs to be installed for the model to work on your cloud. Is there any workaround on this? It gave me this error
h2o.exceptions.H2OStartupError: Cannot find Java.

Can anyone guide me on how to solve this issue? Thank you

Context:
Hi @Chuka_Obi, welcome to the Streamlit community!
This post highlights how to install java on Streamlit cloud:

    How to install Java 8 via packages.txt? Streamlit Cloud

    Hi! Adding default-jre to packages.txt works for me perfectly.

Best,
Randy


Question:
Hello Streamlit Community,
I have built a lipidomics app using streamlit and deployed it on streamlit shares. However, sometimes the app does not load. I receive the following error message:

Screen Shot 2022-01-17 at 11.01.04 AM1278×570 19.9 KB

Then, I am forced to re-deploy the app. Is there a way to avoid this situation?
Thank you for being awesome!
Hamed

Context:
Hi @haabdii, welcome back!
If your app is frequently over resources, then you’ll see this message. One quick fix is to upgrade to newer versions of Streamlit (> 1.1) and see if this fixes it, as we’ve made a lot of memory improvements recently.
If that doesn’t fix it, then post your repo here and maybe something else obvious will stand out.
Best,
Randy


How to deploy an app when my files are very large

Question:
Hi,
I created an app that I would like to deploy. But my code use several csv files that are larger than 1GB.
How could I deal with this problem ?
Many thanks for the help,
Maxime

Context:
Hi @Maxime_tut -
Streamlit Cloud supports Git LFS, which is our usual recommendation to users:

      docs.streamlit.io

Troubleshooting - Streamlit Docs 1

      Git Large File Storage

Git Large File Storage

  Git Large File Storage (LFS) replaces large files such as audio samples, videos, datasets, and graphics with text pointers inside Git, while storing the file contents on a remote server like GitHub.com or GitHub Enterprise.

Alternatively, you could first try to compress the CSV files and see if that helps.
Best,
Randy


Question:
I got an email my app is about to go to sleep… and that it’d take a minute or two to wake after sleep.
What does a viewer see if they come to a sleeping app?
If they see a spinner with no explanation, that’s not great.
If they see a nice note about it being warmed up, I’ll feel fine about it.

Context:
Hi @Dan_Becker -
The app will show the user a button so they can awaken the app:

      docs.streamlit.io

Manage your app - Streamlit Docs 3

Best,
Randy


Error while running the application on streamlit_sharing

Question:
I have created a streamlit app that is able to detect the emotions from live video then when shared on cloud platforms receiving some errors and today when I deployed it on streamlit sharing I got the below error. If anyone has some solution to it please let me know. Thanks to you. Source code at Repo 4
[client] Connecting...

2021-07-21 14:22:12.043 Track audio received

2021-07-21 14:22:12.043 Track video received

2021-07-21 14:22:12.043 Add a input video track <aiortc.rtcrtpreceiver.RemoteStreamTrack object at 0x7fbd4f9ebe50> to output track with video_transformer <class 'streamlit_webrtc.transform.AsyncVideoTransformTrack'>

2021-07-21 14:22:12.044 Add the video track with transfomer to <aiortc.rtcpeerconnection.RTCPeerConnection object at 0x7fbd4fa66a30>

2021-07-21 14:22:12.082 Connection(0) Check CandidatePair(('10.12.107.163', 56240) -> ('192.168.68.108', 51094)) State.FROZEN -> State.WAITING

2021-07-21 14:22:12.082 ICE connection state is checking

2021-07-21 14:22:12.082 Connection(0) Check CandidatePair(('10.12.107.163', 56240) -> ('192.168.68.108', 51094)) State.WAITING -> State.IN_PROGRESS

2021-07-21 14:23:15.827 Connection(0) Check CandidatePair(('10.12.107.163', 56240) -> ('192.168.68.108', 51094)) State.IN_PROGRESS -> State.FAILED

2021-07-21 14:23:15.827 Connection(0) ICE failed

2021-07-21 14:23:15.849 ICE connection state is failed

2021-07-21 14:23:15.850 ICE connection state is closed

@whitphx

Context:
I am also facing the same issue… If you have resolved it…
Can you please tell me how did you resolve the issue.
Thanks in advance


Question:
My app (https://share.streamlit.io/alalalalaki/econ-paper-search/main/Code/app.py 1) used to work well but now suddenly does not connect to Streamlit server. It says “Failed to process a Websocket message (RangeError: index out of range: 54 + 10 > 54)”.
Update: I reboot the app and it now works again. But I am afraid that this problem will occur again after a while. Can anyone give some response on this?
Also I find a correlated problem is that each time when there is some problem about the app and then fixed, the user would need to clean their cookie to make the app work again. Is there any way to circumvent this?
Update2: This happens again after I update the app.

Context: @Alalalalaki  Your streamlit app loaded for me. I didn’t test out the widgets though. Try clearing your cash and reloading your browser and/or restarting your computer.


Question:
Hello,
I am trying to plot a combination of scatter plot and time series, where each time series curve belongs to its corresponding point in the scatter plot. I want to have an interactive plot and I use altair for that purpose. I use exactly the same code that is shared in altair (here: Selection Detail Example — Altair 4.2.0 documentation 3) to create such interactive plot. When I run this code on my local computer, everything works very well. However, when I deploy the code and show it in share.streamlit.io 1, the time series are not synched with the scatterplot anymore. In fact, when all the points are selected, the time series is shown well for all points. However, as soon as I choose one specific point in the scatterplot, the time series disappear totally.
This problem is shown in the attached figures. I appreciate any hints/ comments about this problem.

image865×430 85.1 KB

image851×420 21.8 KB

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

When I run this code on my local computer, everything works very well.

What version of Streamlit are you using? I tried all versions from 0.85.0, 0.86.0, …, to 1.3.1 and wasn’t able to reproduce the behavior where it “works well”. Clicking on any point in the scatterplot, locally and on Streamlit Cloud, causes the time series to disappear.
Strange that the following example works as expected, but not the one you linked: Interactive Scatter Plot and Linked Layered Histogram — Altair 4.2.0 documentation 3
Best,
Snehan


ModuleNotFoundError: No module named ‘streamlit.report_thread’

Question:
I’m trying to deploy an object detection web app on streamlit cloud but it’s throwing me this error
File “/home/appuser/venv/lib/python3.7/site-packages/streamlit_webrtc/session_info.py”, line 1, in
import streamlit.report_thread as ReportThread
the app runs fine on my local setup
here is the github repo of the project

      GitHub

GitHub - adityachache/final-year-project 3

  Contribute to adityachache/final-year-project development by creating an account on GitHub.

here is the piece of code from the file which i think throws the error
import pandas as pd
import PIL.Image as Image
import tensorflow as tf
import tensorflow_hub as hub
import cv2
import urllib

import asyncio
import logging
import queue
import threading
import urllib.request
from pathlib import Path
from typing import List, NamedTuple

try:
    from typing import Literal
except ImportError:
    from typing_extensions import Literal  # type: ignore

import av
import matplotlib.pyplot as plt
import numpy as np
import pydub
import streamlit as st
from aiortc.contrib.media import MediaPlayer

from streamlit_webrtc import (
    AudioProcessorBase,
    RTCConfiguration,
    VideoProcessorBase,
    WebRtcMode,
    webrtc_streamer,
)

Context:
Hello @Aditya_Chache, welcome to the community!
We’ve seen the issue appear this morning with the new 1.4.0 release, for now if you are in a hurry you can downgrade back to streamlit==1.3.1.
Do you use any old Session State code or external Streamlit package aside from streamlit-webrtc ? That will help the team diagnose the problem.
PS: wait, I think, @whitphx are you calling streamlit.report_thread in streamlit-webrtc ? I submitted an issue ModuleNotFoundError: No module named 'streamlit.report_thread' on Streamlit 1.4.0 · Issue #598 · whitphx/streamlit-webrtc · GitHub 28
Have a nice day,
Fanilo


“RuntimeError: Ninja is required to load C++ extension” BUT Ninja is successfully installed!

Question:
As the title suggest, I get this error when the Streamlit app calls a function which uses a library dependent on PyTorch. However, everything works smoothly locally, and I successfully installed all the dependency on he cloud through a conda environment .yml file, included Ninja (see the following pictures).

The repository I’m trying to deploy can be found here: https://github.com/voidpunk/Trial-AId 1

Context:
Just solved! LOL
SOLUTION:
I just added a packages.txt file with the following dependencies:
ninja-build
build-essential


Question:
Hi! I’m having trouble debugging this error and installing my packages using my yml file. Note that I have a dlib dependency so I’m currently using the conda installation method.

Screen Shot 2021-08-01 at 5.23.54 PM1912×420 94.2 KB

My github repo 1

Context:
wesleykwong:

ng this error and insta

Hi @wesleykwong welcome to Streamlit!
I had a similar problem with conda. Have a look at this thread Managing your Streamlit dependencies using conda 22
Give it a try with pipenv / pip.


Issue with dependencies for poetry lock file and streamlit cloud

Question:
I’m having issues deploying my app to streamlit cloud
below I the issue in the logs
 The current project's Python requirement (3.7.12) is not compatible with some of the required packages Python requirement:

    - numpy requires Python >=3.8, so it will not be satisfied for Python 3.7.12

  Because no versions of pandas match >=1.3.3,<1.3.5 || >1.3.5,<2.0.0

   and pandas (1.3.5) depends on numpy (>=1.17.3), pandas (>=1.3.3,<2.0.0) requires numpy (>=1.17.3).

  Because numpy (1.22.0) requires Python >=3.8

   and no versions of numpy match >=1.17.3,<1.22.0 || >1.22.0, numpy is forbidden.

  Thus, pandas is forbidden.

  So, because yt-comments depends on pandas (^1.3.3), version solving failed.

  at ~/.poetry/lib/poetry/puzzle/solver.py:241 in _solve

      237│             packages = result.packages

      238│         except OverrideNeeded as e:

      239│             return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)

      240│         except SolveFailure as e:

    → 241│             raise SolverProblemError(e)

      242│

      243│         results = dict(

      244│             depth_first_search(

      245│                 PackageNode(self._package, packages), aggregate_package_nodes

  • Check your dependencies Python requirement: The Python requirement can be specified via the `python` or `markers` properties

    For numpy, a possible solution would be to set the `python` property to "<empty>"

    https://python-poetry.org/docs/dependency-specification/#python-restricted-dependencies,

    https://python-poetry.org/docs/dependency-specification/#using-environment-markers

I’ve been trying to solve this for the past hour so any help is greatly appreciated.
Here is the link to my github repo GitHub - benthecoder/yt-comments-mongodb-search

Context:
If your packages really require Python 3.8, you can set the package version through the deployment menu:

      docs.streamlit.io

Deploy an app - Streamlit Docs 3

Best,
Randy