docs
stringclasses
4 values
category
stringlengths
3
31
thread
stringlengths
7
255
href
stringlengths
42
278
question
stringlengths
0
30.3k
context
stringlengths
0
24.9k
marked
int64
0
1
streamlit
Using Streamlit
Nested Buttons with Session State
https://discuss.streamlit.io/t/nested-buttons-with-session-state/20031
Hi, I haven’t been able to follow the developments with ‘session state’ but I think I know that we can use that to solve my problem. How can I reach the successful part with these nested buttons? import streamlit as st a = st.button("Button 1") if a: b = st.button("Button 2") if b: st.write("Successful.")
Hi @Berk_Demir, My advice would be to put a key in st.session_state that changes once button 1 is pressed. Then the if statement that creates the second button, would depend on the value assigned to that key in the session state and not on the return value from the button. You can learn the syntax of this through our example in the docs on making a counter (It works on the same principle, you probably just want your value to be True or False and not an integer)! docs.streamlit.io Add statefulness to apps - Streamlit Docs 2 Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Any way to hide or remove default numbers in st.table()
https://discuss.streamlit.io/t/any-way-to-hide-or-remove-default-numbers-in-st-table/9663
Trying to remove the numbers on the left side of the table. Thanks! Screen Shot 2021-02-08 at 5.39.55 PM292×600 7.09 KB
Hi @pavan_kumar The solution can be found in the following knowledge base article in Streamlit’s documentation: Hide row indices when displaying a dataframe - Streamlit Docs 64 Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
How to save graphviz_char into a picture file?
https://discuss.streamlit.io/t/how-to-save-graphviz-char-into-a-picture-file/20026
I’m using st.graphviz_chart(graph) to display the graph, and how to save the graph into one JPG picture file ?
Hi @diao, welcome to the Streamlit community! Please note that st.graphviz_chart on the Streamlit side is display only, so it won’t have any methods for saving. However, whatever library that is creating graph should have a method for exporting the graph. Best, Randy
0
streamlit
Using Streamlit
Simplest way to deploy a streamlit app in Windows server 2012
https://discuss.streamlit.io/t/simplest-way-to-deploy-a-streamlit-app-in-windows-server-2012/1835
How can an Streamlit app be deployed in windows server to share it with other users? Can we deploy Streamlit app using a windows service?
I also want to publish the app to my windows2012 server. Because our data is internal confidential data of the enterprise, it cannot be published to internet web service providers. But we have our own internal server, what kind of environment the server needs to be configured to run this.
0
streamlit
Using Streamlit
Streamlit rerun
https://discuss.streamlit.io/t/streamlit-rerun/10701
Hi, I would like to rerun my app from a python script, I tried some thing like: from streamlit.ScriptRunner import RerunException raise RerunException I got the following error ModuleNotFoundError: No module named ‘streamlit.ScriptRunner’, I guess that this module was depreciated. is there any alternative to rerun my app from my script.
Hey @khalidbouziane, There is actually, but it is in our experimental area (see the docs on caveats to using experimental commands 263). You can use st.experimental_rerun() at the point where you would like your code to rerun from the top! Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Line_charts are slow, even with low amount of data points
https://discuss.streamlit.io/t/line-charts-are-slow-even-with-low-amount-of-data-points/20022
I’m reading data from sensors, which I understand might not be the best use case for Streamlit. Nonetheless, I like all the other features so much that I am willing to use Streamlit. I’m wondering if there’s a way to speed up how fast line_charts take. Here is an example: import time import random import streamlit as st data1 = deque([0]*5) data2 = deque([0]*5) graph1 = st.empty() graph2 = st.empty() while True: data1.popleft() data1.append(5 + random.randint(-5, 5)) data2.popleft() data2.append(4 + random.randint(3, 9)) graph1.line_chart(list(data1)) graph2.line_chart(list(data2)) time.sleep(1) I expect the two graphs to update at around the same time every second, but instead the first one updates, a brief half second pause, and then the second one updates, and then there’s the 1 second delay. I don’t believe it’s because of the various deque operations as there is only 5 elements in these lists. Also, because this is simulating sensor data, data is random and caching will be pretty much impossible.
Hi @kevinlinxc - I suspect the issue you are running into is the Streamlit processing model, not that line_charts themselves are particularly slow. There’s another thread going on right now about trying to display data with high frame rates, perhaps you could modify that approach: Best (fastest) practice to display live 2D data Using Streamlit Dear all! I have a detector which produces 2D images at video rates and higher. However, for live imaging rates in the range 10 Hz and more would be sufficient. Data comes as numpy arrays. I face problems, when I want to display the data at the wanted rates. The following code mocks up different ways to do this with streamlit. I am by no means a python - and especially no asyncio - expert, though. display, get the data, rerun get the data, display, rerun do displaying and data taking asynch… Best, Randy
0
streamlit
Using Streamlit
How to hide streamlit.text_input after input
https://discuss.streamlit.io/t/how-to-hide-streamlit-text-input-after-input/10832
Hello, I have st.text_input But i want to hide it or make it invisible after i input something and enter How to do it? Thank you
Hello @arri, welcome to the community! Check out the documentation for st.empty 45 which should fit your need by destroying the text_input after pressing “Enter”! : import streamlit as st text_input_container = st.empty() t = text_input_container.text_input("Enter something") if t != "": text_input_container.empty() st.info(t) test793×177 36.9 KB Have a nice day! Fanilo
1
streamlit
Using Streamlit
Streamlit not getting AWS public IP
https://discuss.streamlit.io/t/streamlit-not-getting-aws-public-ip/5802
The following lines were my first testing program using AWS EC2 (Window Sever 2019) and streamlit. The “Network URL” I got was AWS’ Private IPs 172.31.71.27, which can’t be access from outside! My question is how can Streamlit set the “Network URL” to AWS’ IPv4 Public IP 3.235.195.213, so that everyone can access from the world? Thank you so much! (After googling, I am so desperately!) (base) C:\Users\Administrator>streamlit run test.py Hello, World! You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 3 Network URL: http://172.31.71.27:8501 3
Steve_Chen: streamlit run test.py Thank you so much Randy. It worked!!! This is what I have done to solve the issue: Connect to EC2 instance Login to Windows VM In the bottom-left corner of the window, Just right next to the Windows Start icon, there is a search icon, click it. Type firewall Click check firewall status Click the advanced setting Scroll down and click the inbound rule On the left panel, right click the Inbound Rules Click new rule Create an inbound rule by filling in the protocol type with TCP, port numer: 8501… Find my public IP in EC2 console: 3.235.195.213 In the browser, type 3.235.195.213:8501 And it connected to the streamlit app that I ran in the server. It worked!!!
1
streamlit
Using Streamlit
Selectbox BUG on “chaining” forms!
https://discuss.streamlit.io/t/selectbox-bug-on-chaining-forms/19927
@Jessica_Smith @andfanilo @thiago @okld @vdonato @kmcgrady @Charly_Wargnier @asehmi import streamlit as st from streamlit_pandas_profiling import st_profile_report from streamlit import session_state as session import numpy as np import pandas as pd from pandas_profiling import ProfileReport def cluster_duplicates(df, col_name, dis_num, dis_non_alphanum, sim, aff): st.write(col_name) st.write(df.head()) st.write(df[col_name].unique()) def profiler(file, delim): file = st.session_state.upload delimiter = st.session_state.delim.split(" ")[1][1:-1] df = pd.read_csv(file, sep=delimiter, engine="python") file_info = {"Filename": file.name, "FileType": file.type, "FileSize": file.size} st.write(file_info) pr = ProfileReport(df, explorative=True) st_profile_report(pr) with st.form(key="cluster_duplicates"): cols = [val for val in df.columns] col_name = st.selectbox("Select column for clustering", cols, key="col_name") dis_num = st.checkbox("discard_numeric", key="dis_num") dis_non_alphanum = st.checkbox("discard_nonalpha_numeric", key="dis_non_alphanum") similarity = st.radio(label="Select Similarity Measure", options=["levenshtein (recommended)", "cosine", "jaro_winkler", "trigram", "levenshtein_partial"], key="similarity") affinity = st.radio(label="Select Distance Measure", options=["euclidean", "l1", "l2", "manhattan", "cosine", "precomputed"], key="affinity") method_args = (df, session.col_name, session.dis_num, session.dis_non_alphanum, session.similarity, session.affinity) submit_btn = st.form_submit_button(label = "Cluster Duplicates", on_click=cluster_duplicates, args=method_args) def data_uploader_form(): with st.form(key="file_upload"): data_file = st.file_uploader("Upload File", type=['csv', 'xlsx'], key="upload") delim_list = ["pipe (|)", r"tab (\t)", "comma (,)", "semicolon (;)"] delim = st.selectbox("Select File Seperator/Delimiter", delim_list, key="delim") submit_file_btn = st.form_submit_button(label='Profile Data', on_click=profiler, args=(session.upload, session.delim)) if __name__ =="__main__": #st.set_page_config(layout="wide") st.write("Data Profiler :wave:") data_uploader_form() After submitting the 2nd form (key = “cluster_duplicates”)–it always fetches the first argument in the 2nd selectbox even when I select another one See gif below-- I selected “Variety” in the 2nd selectbox but it still selects “Review #”
in the method_args variable, i’m “accessing” the session_state value BEFORE the button is clicked rather than then AFTER. My problem at the “base-level” has been chaining forms/callbacks Read these two issues for the “full-story”:– github.com/streamlit/streamlit selectbox not functioning properly when chaining forms opened Dec 11, 2021 closed Dec 12, 2021 kart2k15 bug needs triage ### Summary ```python import streamlit as st from streamlit_pandas_profilin…g import st_profile_report from streamlit import session_state as session import numpy as np import pandas as pd from pandas_profiling import ProfileReport def cluster_duplicates(df, col_name): st.write(col_name) st.write(df.head()) st.write(df[col_name].unique()) def profiler(file, delim): with st.form(key="cluster_duplicates"): cols = [val for val in df.columns] #st.session_state.col_name always contains the 1st value ONLY, even though I select a different one--see forums for details col_name = st.selectbox("Select column for clustering", cols, key="col_name") method_args = (df, session.col_name) submit_btn = st.form_submit_button(label = "Cluster Duplicates", on_click=cluster_duplicates, args=method_args) def data_uploader_form(): with st.form(key="file_upload"): data_file = st.file_uploader("Upload File", type=['csv', 'xlsx'], key="upload") delim_list = ["pipe (|)", r"tab (\t)", "comma (,)", "semicolon (;)"] delim = st.selectbox("Select File Seperator/Delimiter", delim_list, key="delim") submit_file_btn = st.form_submit_button(label='Profile Data', on_click=profiler, args=(session.upload, session.delim)) if __name__ =="__main__": #st.set_page_config(layout="wide") st.write("Data Profiler :wave:") data_uploader_form() ``` I've posted on the forums too-- [https://discuss.streamlit.io/t/selectbox-bug-on-chaining-forms/19927](https://discuss.streamlit.io/t/selectbox-bug-on-chaining-forms/19927) After submitting the 2nd form (key = "cluster_duplicates")--it always fetches the first argument in the 2nd selectbox even when I select another one ### Debug info - Streamlit version: 1.0 - Python version: 3.8.7 - Using pip3 (pip 20.0) - OS version: mac - Browser version: chrome github.com/streamlit/streamlit Forms/callback "chaining" not working:-- opened Dec 12, 2021 closed Dec 12, 2021 kart2k15 bug needs triage I need to chain callbacks for 2 forms: As long as I access session values for …the input widgets for either forms the "chain" **does not break**. For instance:-- ```python import pandas as pd import streamlit as st from streamlit import session_state as session def cluster_duplicates(): st.write(session.col_name)#prints the column passed in the 2nd form GOOD def profiler(): df = pd.read_csv(session.upload, sep=session.delim, engine="python") file_info = {"Filename": session.upload.name, "FileType": session.upload.type, "FileSize": session.upload.size} st.write(file_info) st.write(df.head()) with st.form(key="cluster_duplicates"): cols = list(df.columns) col_name = st.selectbox('Enter Column Name', cols, key="col_name") submit_btn = st.form_submit_button(label = "Cluster Duplicates", on_click=cluster_duplicates) def data_uploader_form(): with st.form(key="file_upload"): data_file = st.file_uploader("Upload File", type=['csv', 'xlsx'], key="upload") delim_list = ["|", r"\t", ",", ";"] delim = st.selectbox("Select File Seperator/Delimiter", delim_list, key="delim") submit_file_btn = st.form_submit_button(label='Profile Data', on_click=profiler) if __name__ =="__main__": #st.set_page_config(layout="wide") st.write("Data Profiler :wave:") data_uploader_form() ``` Now, if I try to pass the output caused from one form--i.e. the variable df here--then I get a session value error (error screenhshot below) ```python import pandas as pd import streamlit as st from streamlit import session_state as session def cluster_duplicates(df): #this whole function throws an error--DOES NOT RUN st.write(session.col_name)#DOES NOT PRINT column value anymore st.write(df)#throws ERROR def profiler(): df = pd.read_csv(session.upload, sep=session.delim, engine="python") file_info = {"Filename": session.upload.name, "FileType": session.upload.type, "FileSize": session.upload.size} st.write(file_info) st.write(df.head()) with st.form(key="cluster_duplicates"): cols = list(df.columns) col_name = st.selectbox('Enter Column Name', cols, key="col_name") #passing df throws an error!! submit_btn = st.form_submit_button(label = "Cluster Duplicates", on_click=cluster_duplicates, args=(df)) def data_uploader_form(): with st.form(key="file_upload"): data_file = st.file_uploader("Upload File", type=['csv', 'xlsx'], key="upload") delim_list = ["|", r"\t", ",", ";"] delim = st.selectbox("Select File Seperator/Delimiter", delim_list, key="delim") submit_file_btn = st.form_submit_button(label='Profile Data', on_click=profiler) if __name__ =="__main__": #st.set_page_config(layout="wide") st.write("Data Profiler :wave:") data_uploader_form() ``` <img width="897" alt="error" src="https://user-images.githubusercontent.com/17420426/145694021-990bb277-59f8-4466-a03f-987178312780.png"> The “correct” solution is:– import pandas as pd import streamlit as st from streamlit import session_state as session def cluster_duplicates(df): st.write(session.col_name)#prints the column passed in the 2nd form GOOD st.write(df) def profiler(): df = pd.read_csv(session.upload, sep=session.delim, engine="python") if 'dataframe' not in session: session['dataframe']=df file_info = {"Filename": session.upload.name, "FileType": session.upload.type, "FileSize": session.upload.size} st.write(file_info) st.write(df.head()) with st.form(key="cluster_duplicates"): cols = list(df.columns) col_name = st.selectbox('Enter Column Name', cols, key="col_name") #if one passes args=(df) ==> args =df, when args should be a TUPLE thus args = (df,) submit_btn = st.form_submit_button(label = "Cluster Duplicates", on_click=cluster_duplicates, args=(df,)) def data_uploader_form(): with st.form(key="file_upload"): data_file = st.file_uploader("Upload File", type=['csv', 'xlsx'], key="upload") delim_list = ["|", r"\t", ",", ";"] delim = st.selectbox("Select File Seperator/Delimiter", delim_list, key="delim") submit_file_btn = st.form_submit_button(label='Profile Data', on_click=profiler) if __name__ =="__main__": #st.set_page_config(layout="wide") st.write("Data Profiler :wave:") data_uploader_form() “cluster_duplicates” is chained AFTER “profiler”. Also, profiler has no “args”, but “cluster_duplicates” has one–which NEEDS to be passed like this (df,), I passed it as args=(df) and it threw an error–because it evaluated to args=df
1
streamlit
Using Streamlit
How to share custom files through my Streamlit app?
https://discuss.streamlit.io/t/how-to-share-custom-files-through-my-streamlit-app/19875
Hello guys, my goals is to share custom files through my Streamlit app such as jupyter notebook file (.ipynb) or GeoJson (.geojson). I know Streamlit provide a download button which I can use to share file. Let’s me share with you an example: import streamlit as st import nbformat as nbf # build my notebook notebook = nbf.v4.new_notebook() # enriched my notebook notebook["cells"] = [nbf.v4.new_markdown_cell("Blablabla"), ...] # create my download button st.download_button("Download the notebook", notebook, mime="application/vnd.jupyter") This is not working ! I am not sure if I made a mistake in my choice for the parameters “mime” or I need to format the notebook to an other format You can overpass the problem by formating the notebook in an html file : html_exporter = HTMLExporter() html_data, _ = html_exporter.from_notebook_node(notebook) st.download_button("Download the notebook", notebook, mime="text/html") But I feel more confortable with a notebook file ! Any idea guys ? (:
Hi @axelearning, welcome to the Streamlit community! I would try application/octet-stream as the mime-type, which is the generic type for any sort of bytes. Best, Randy
0
streamlit
Using Streamlit
FileNotFoundError: [Errno 2] No such file or directory: ‘gender_submission.csv’
https://discuss.streamlit.io/t/filenotfounderror-errno-2-no-such-file-or-directory-gender-submission-csv/19958
Hello, When i tried the host my streamlit app, I’m facing this issue FileNotFoundError: [Errno 2] No such file or directory: ‘gender_submission.csv’. Where should I place the CSV file for the application to read. image857×766 27.3 KB
Hey @lokesh_balaji! First, welcome to the Streamlit forum! The most basic answer to this is in the same directory/folder as your project, ideally the same one as your app python file. If your csv file is in a subdirectory of that folder/directory you have to pass the path that the script has to follow to find the csv. Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Feature idea, Pyodide JupyterLite like Streamlit
https://discuss.streamlit.io/t/feature-idea-pyodide-jupyterlite-like-streamlit/19919
So it’s a bit “out there” but the JupyterLab notebook is currently able to be completely “hosted” on a static web page using Pyodide kernels using web assembly. This is Python running directly within the user’s browser. No application server needed: GitHub GitHub - jupyterlite/jupyterlite: Wasm powered Jupyter running in the browser 💡 8 Wasm powered Jupyter running in the browser 💡. Contribute to jupyterlite/jupyterlite development by creating an account on GitHub. JupyterLite also has a really easy way to bundle up notebooks and python environments all within a nice reproducible archive. I can see this model being absolutely awesome for Streamlit. Imagine being able to share a local version of a Streamlit app just by sending someone an archive that opens up the web browser and all of the Python runs within the user’s browser, without needing any Python installed. Self hosting Streamlit would be multiple orders of magnitude easier, one could host a Streamlit app with GitHub pages. Anyway, here’s my proposal, support a Pyodide backend for Streamlit allowing Streamlit apps to run completely within the browser
This idea also crossed my mind and actually I recall multiple Creators have toyed with the idea: @whitphx @asehmi if you want to pop in the conversation with your experiences. It will probably run through the same issues as Install with pyodide · Issue #7764 · dask/dask · GitHub : tornado install with micropip still is experimental from memory, Streamlit runs python code from ReportContext in a thread, which I don’t know how WASM manages yet since its threading model is supposedly in proposal mode. I also wanted to do the smaller thing, load ipywidgets into Streamlit through Pyodide ipywidgets support (or any object with _repr_html_) · Issue #1598 · pyodide/pyodide · GitHub but it is still a little bit hard. Yuichiro I think managed to do a PoC of streamlit webrtc client-side But yeah we are definitely very interested in the idea!
0
streamlit
Using Streamlit
URGENT : Please HELP
https://discuss.streamlit.io/t/urgent-please-help/19196
Greetings Folks , I have a problem with this APP community1363×632 9.24 KB I want that each time that Click on START button , I save those selected parameters in a new table or in a csv file that I can check each time in the sidebar (I wanted being updated of course each time I select my parameters and click On START button) Also , I want that once I click that Start Button a new Line appears in the table that it was displayed (I have used plotly) but as you can see , it is poorly displayed and a new line is not added after selecting the parameters and click on the START button. Thanks a lot for your help To make it easy for you , here is the code : import streamlit as st import pandas as pd import numpy as np from datetime import datetime as dt import plotly.graph_objects as go coins_list = [‘LTC’,‘ETH’,‘BTC’] FIXED = 1e5 coin = st.selectbox(‘Search COIN’ ,coins_list) X1 = st.number_input(‘Select your X1’, min_value = 1e-5 , max_value = 999999999.999999 , step = 1e-5) Y1 = st.number_input(‘Select your Y1’, min_value = 1e-5 , max_value = 999999999.999999 , step = 1e-5) Z1 = st.number_input(‘Select your Quantity’, min_value = 1e-5, max_value = 9999999999.9999 , step = 1e-5) I want each time that I select these parameters to SAVE them in a new table (A time component wil be interesting maybe) col1,col2,col3,col4,col5 = st.columns(5) with col3 : st.button(“START”) # I want that each time a press the START Button there is a line which is added with the coin selected previously if coin : # I want to the figure to be displayed correctly , taking all the width for example than I can adjust font and cells size by myself (please add them as arguments to try them out) fig2 = go.Figure(data=[go.Table( header=dict(values=['','','',['BOT - Status'],'',''], fill_color = 'green', line_color = 'green', align = 'center', font=dict(color='black', family="Lato", size=15) ), cells = dict(values=[ ["Name of the BOT (as per the coin pair selected)",coin], ["Status"], ["Start/Stop of BOT"], ["Purchased Price",], ["Current Price of the coin pair"], ["Completed Loop"], ["Comission Dedected"], ["Profit made"]], line_color = 'darkslategray', fill_color = 'white', align = ['center'], font=dict(color='black', family="Lato", size=15)) )] ) fig2.update_layout(margin=dict(l=20, r=20, t=20, b=20), width=1200, height=300) st.write(fig2)
Thanks for your asnwer import streamlit as st import pandas as pd import numpy as np from datetime import datetime as dt import plotly.graph_objects as go coins_list = [‘LTC’,‘ETH’,‘BTC’] FIXED = 1e5 coin = st.selectbox(‘Search COIN’ ,coins_list) X1 = st.number_input(‘Select your X1’, min_value = 1e-5 , max_value = 999999999.999999 , step = 1e-5) Y1 = st.number_input(‘Select your Y1’, min_value = 1e-5 , max_value = 999999999.999999 , step = 1e-5) Z1 = st.number_input(‘Select your Quantity’, min_value = 1e-5, max_value = 9999999999.9999 , step = 1e-5) I want each time that I select these parameters to SAVE them in a new table (A time component wil be interesting maybe) col1,col2,col3,col4,col5 = st.columns(5) with col3 : st.button(“START”) # I want that each time a press the START Button there is a line which is added with the coin selected previously if coin : # I want to the figure to be displayed correctly , taking all the width for example than I can adjust font and cells size by myself (please add them as arguments to try them out) fig2 = go.Figure(data=[go.Table( header=dict(values=['','','',['BOT - Status'],'',''], fill_color = 'green', line_color = 'green', align = 'center', font=dict(color='black', family="Lato", size=15) ), cells = dict(values=[ ["Name of the BOT (as per the coin pair selected)",coin], ["Status"], ["Start/Stop of BOT"], ["Purchased Price",], ["Current Price of the coin pair"], ["Completed Loop"], ["Comission Dedected"], ["Profit made"]], line_color = 'darkslategray', fill_color = 'white', align = ['center'], font=dict(color='black', family="Lato", size=15)) )] ) fig2.update_layout(margin=dict(l=20, r=20, t=20, b=20), width=1200, height=300) st.plotly_chart(fig2,use_container_width=True) Here is what I get if I put under the “if coin :” after the fig2 , that way I create a connection … Also , I have figured out that if I find a way with the dictionary , it’s easy but didn’t find a solution is as the following : if I put this “fig2[‘data’][0][“cells”][“values”][0]” , I will as an output the following : which means if I find a way to put that “complex” code in the place of “coin” here [“Name of the BOT (as per the coin pair selected)”,coin], A line will be added , it’s the only way that I founded … can you try to find a solution for me for this ? Also , what’s the story of Table , what’s the diffrence with Figure ?..
0
streamlit
Using Streamlit
Twitch embedding
https://discuss.streamlit.io/t/twitch-embedding/19735
Hi everyone, I am currently trying to use streamlit-player to embed twitch videos and lives on my app. Using this package allowed me to do so, but only on my local version. Everything is working fine on local, but I get a message error from Twitch once I deploy the app (“player.twitch.tv doesn’t allow the connection”) I get from the documentation that I need a SSL connection. When I add “&parent=mywebsite.streamlit.io”, I get a black screen in the player, but no error. Is there a way to embed Twitch in streamlit? Thanks ! ps: here’s the code that works on local : link = st.text_input(label= "Link of the video") play = st.button("play the video") if play: st_player(f"{link}&parent=share.streamlit.io&parent=mywebsite.streamlit.io")
Well as a “solution” : I deployed on heroku. I couldn’t manage to make the “&parent” parameter work on streamlit cloud (where the domain is .io), but it worked nicely on heroku where I just added “&parent=myappname.heroku.com” to the url (as explained on the twitch documentation) in a st.markdown. Hope it might help someone !
1
streamlit
Using Streamlit
Root cause of running speed difference between in the local and in the Streamlit Cloud
https://discuss.streamlit.io/t/root-cause-of-running-speed-difference-between-in-the-local-and-in-the-streamlit-cloud/19903
Hi everyone, I’ve developed an app but I see that it works in local slowly. I guess, root cause of this problem is the code runs after every single action in the app throughly. I think that it is a common case for streamliters (You know, there is a “running…” text in the upper right corner of the screen and it makes you wait for a while.). Anyway, I’ve noticed that when I deploy my app in the Streamlit Cloud, the speed issue is gone. Why did I face this problem and how can I fix it in my local? Here is my app and its source code: https://share.streamlit.io/baligoyem/dataqtor/main/home.py 3 GitHub - baligoyem/dataqtor: 🔍Your Data Quality Detector / Gain insight into your data and get it ready for use before you start working with it 💡📊🛠💎 2 Thanks in advance for your responses.
I have the similar problem, it could be great if we could learn why it happens.
0
streamlit
Using Streamlit
St.dataframe coodinates
https://discuss.streamlit.io/t/st-dataframe-coodinates/19921
Hi, if I use st.dataframe to view a data frame, and I click on a cell, is there a way to get the row and column coordinates of the clicked cell? Eg. If I click on the 3rd row and 2nd column, can I get a return of values: 3, 2? Use case: specifically change the data in a cell that a user clicks at run time. Thanks in advance.
I think the AgGrid component will help you. GitHub - PablocFonseca/streamlit-aggrid: Implementation of Ag-Grid component for Streamlit 6
0
streamlit
Using Streamlit
Is it possible plot 3D Mesh file or to add the VTK/ Pyvista window inline streamlit?
https://discuss.streamlit.io/t/is-it-possible-plot-3d-mesh-file-or-to-add-the-vtk-pyvista-window-inline-streamlit/4164
I find Streamlit impressive. Outstanding work! I have a 3d mesh file. I am able to plot the 3d mesh file using pyvista library, ITK widgets, and see it in the notebook interactively. I would like to show this 3D plot in Streamlit interactively. Is it possible to do it? If there is an example, it would be very helpful. Kind regards, Hemanand
Hello @Hems, welcome to the community. With Components 26 coming really soon, which will enable you to run arbitrary HTML/JS code in Streamlit, we should be able to replicate part of ITKWidget’s code, which is passing a JS representation or file upload of your mesh read through Pyvista into itk-vtk-viewer 40 / vtk.js 17 to visualize it in Streamlit. I believe that’s an excellent example off custom component where you can have a quick prototype working, if you want to try it out when it’s live Fanilo
0
streamlit
Using Streamlit
Cannot print the terminal output in Streamlit?
https://discuss.streamlit.io/t/cannot-print-the-terminal-output-in-streamlit/6602
Hi guys, I’m trying to get a terminal output to be printed in Streamlit. I tried various codes including this one import searchconsole account = searchconsole.authenticate(client_config="GSCTatieLouCredentials.json", serialize='credentials.json', flow="console") st.write(account) but nothing seems to work - See screenshot below: image1317×356 71.4 KB Any idea on how to print in Streamlit? Thanks, Charly
Alright, new version. Tell me if it works in your case EDIT: removed output = st.empty(). Now you just have to put streamlit’s function name as parameter. from contextlib import contextmanager from io import StringIO from streamlit.report_thread import REPORT_CONTEXT_ATTR_NAME from threading import current_thread import streamlit as st import sys @contextmanager def st_redirect(src, dst): placeholder = st.empty() output_func = getattr(placeholder, dst) with StringIO() as buffer: old_write = src.write def new_write(b): if getattr(current_thread(), REPORT_CONTEXT_ATTR_NAME, None): buffer.write(b) output_func(buffer.getvalue()) else: old_write(b) try: src.write = new_write yield finally: src.write = old_write @contextmanager def st_stdout(dst): with st_redirect(sys.stdout, dst): yield @contextmanager def st_stderr(dst): with st_redirect(sys.stderr, dst): yield with st_stdout("code"): print("Prints as st.code()") with st_stdout("info"): print("Prints as st.info()") with st_stdout("markdown"): print("Prints as st.markdown()") with st_stdout("success"), st_stderr("error"): print("You can print regular success messages") print("And you can redirect errors as well at the same time", file=sys.stderr) image731×363 4.9 KB
1
streamlit
Using Streamlit
Part of page is getting refreshed on dropdown selection
https://discuss.streamlit.io/t/part-of-page-is-getting-refreshed-on-dropdown-selection/3336
I am trying to build a simple app where user will enter data & give feedback based on predicted result. Code: import streamlit as st def main(): st.title("Data Categorization") txt = st.text_area("Paste your data here..") if st.button("Find Category"): try: if txt != '': value = st.selectbox("Agree with result", ["Yes, I agree..", "Nah!! I don't"]) if st.button("Submit report"): if value == "Yes, I agree..": #st.write(value) print('Do this ...') elif value != "Nah!! I don't agree": print('Do that ...') st.write("Thank You..") else: st.write('No content found') except: st.write('Looks like I am having problem connecting my backend') if __name__ == '__main__': main() image948×561 14.5 KB But when I select any value from dropdown: image946×610 16.7 KB The rendered elements getting disappears : image959×340 9.42 KB Don’t know where I am going wrong. Need help here…
Hey @deepankar27 welcome to the forums What happens here is when you press the second button "Submit report" the script is rerun, and the first button hit "Find category" will go back to None since you hit the second one. So Streamlit won’t go inside the code block from the first button. You need to maintain the info that you pressed the first button somewhere to force Streamlit to go into the code block. There’s a way to preserve this information inside a state that is preserved between runs, with the State hack 172. So if you put the State script near your file, you can then do the following : import streamlit as st import st_state_patch def main(): st.title("Data Categorization") txt = st.text_area("Paste your data here..") s = st.State() if not s: s.pressed_first_button = False if st.button("Find Category") or s.pressed_first_button: s.pressed_first_button = True # preserve the info that you hit a button between runs try: if txt != '': value = st.selectbox("Agree with result", ["Yes, I agree..", "Nah!! I don't"]) if st.button("Submit report"): if value == "Yes, I agree..": st.write('Do this ...') elif value != "Nah!! I don't agree": st.write('Do that ...') else: st.write('No content found') except: st.write('Looks like I am having problem connecting my backend') if __name__ == '__main__': main()
1
streamlit
Using Streamlit
Is there a way to have multiple pages like flask?
https://discuss.streamlit.io/t/is-there-a-way-to-have-multiple-pages-like-flask/16823
Hi, I just finished streamlit tutorial and I was wondering if there is a way to have a multiple page like flask. Maybe code would look like this from flask import Flask import streamlit as st app = Flask(__name__) @app.route('/') def home(): return 'this is home' @app.route('/page1') def page1(): st.button('this is page1') if __name__ == '__main__': app.run() I’ve tried making multi page after watching data professors video on youtube, but it’s not quite what I’m looking for.
Hi 2asy, you can try my Multipage framework for this streamlit-multipage/MultiPage.py at main · akshanshkmr/streamlit-multipage (github.com) 34 from MultiPage import MultiPage from apps import first_app, second_app, third_app app = MultiPage() app.add_app('App1',first_app.app) app.add_app('App2',second_app.app) app.add_app('App3',third_app.app) app.run() This should fulfill your usecase Thanks
0
streamlit
Using Streamlit
My app stuck is stuck in the oven
https://discuss.streamlit.io/t/my-app-stuck-is-stuck-in-the-oven/19842
Hello, I am using github lfs to handle large files related to Questgen.ai library. I managed to get the streamlit app working locally on my machine but I cant get it to start on streamlit servers. Could you please advise or check if some files causing some issues ? link to app:https://share.streamlit.io/nalhamzy/clustering-project/main/main.py 3
Hey @dvlp, Welcome to the Streamlit community! I see you have created 2 threads about the same issue, since Randy has replied to you in your other thread I will post the link to that one here for anyone who comes across this in the future so that can see the solutions and conversation there! Deploying large sized app stuck in the oven Streamlit Cloud Hello, I am using github lfs to handle large files related to Questgen.ai library (vectors folder > 100MB). I managed to get the streamlit app working locally on my machine but I cant get it to start on streamlit servers. Could you please advise or check if some files causing some issues ? link to app:https://share.streamlit.io/nalhamzy/clustering-project/main/main.py Happy Streamlit-ing Marisa
1
streamlit
Using Streamlit
Numexpr.utils: NumExpr defaulting to 8 threads
https://discuss.streamlit.io/t/numexpr-utils-numexpr-defaulting-to-8-threads/19804
Hi i deployed streamlab webapp in anaconda docker container. I dont see the application its not showing in the browser. even running gives similar issue with numexpr.utils image1006×403 87.2 KB
I got the same error
0
streamlit
Using Streamlit
Using custom fonts
https://discuss.streamlit.io/t/using-custom-fonts/14005
Hi, I was wondering if I can use a custom font instead of the predefined three in the Edit Theme menu in setting? There I only see three options in the font family menu: sans serif, serif and monospace. I have some tff font files I downloaded and I would like to use them instead. I am new to streamlit and not that experienced with css. I would appreciate some examples and references. I see that it is possible to override using st.markdown as given here 9 . and this guide 25 DigitalOcean How To Define Custom Fonts in CSS with @font-face and font-display |... 25 The font-face at-rule gives a lot of flexibility to define custom fonts using CSS. Plus, the font-display property allows to control even the font loading. But it doesn’t seem to work. def style(): css = """ <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <style> @font-face { font-family: 'My Font'; font-style: normal; src: url(assets/fonts/myfont.tff) format('truetype');; } .sidebar-text{ font-family: 'Roboto', sans-serif; } .standard-text{ font-family: 'My Font'; } </style> """ st.markdown(css,unsafe_allow_html=True) style()
This works import streamlit as st t = st.radio("Toggle to see font change", [True, False]) if t: st.markdown( """ <style> @font-face { font-family: 'Tangerine'; font-style: normal; font-weight: 400; src: url(https://fonts.gstatic.com/s/tangerine/v12/IurY6Y5j_oScZZow4VOxCZZM.woff2) format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } html, body, [class*="css"] { font-family: 'Tangerine'; font-size: 48px; } </style> """, unsafe_allow_html=True, ) "# Hello" """This font will look different, based on your choice of radio button""" image1085×1391 33.2 KB image988×710 10.9 KB Best, Randy
1
streamlit
Using Streamlit
MultiSelect without closing
https://discuss.streamlit.io/t/multiselect-without-closing/19897
Hi, When you are using multiselect, user has to select, click to multi select again and select again. I think, for best user experience, multi-select dropdown menu should be open unless user clicks somewhere else. Imagine you have to select 10 options, it is 20 click (10 options + 10 for opening the menu) instead of 11 click (one for opening the menu and 10 options). Is there an option to do this that I am not aware of?
If you have a few number of options, you could try using a collection of check boxes instead. Cheers
0
streamlit
Using Streamlit
Avoid fading output during longer background activity
https://discuss.streamlit.io/t/avoid-fading-output-during-longer-background-activity/17950
Dear all! I wrote an app to display images from a 2D detector. I use the st.experimental_rerun() function to this continuously. When using longer exposure times (seconds) the image displayed from the previous run fades as do some of the other components (I added for setting up acquisition parameters). Is there a way to avoid this, i.e. at least the image remains displayed with the original contrasts until being replaced by the new one? Thanks a lot in advance and for the great streamlit! Markus
Issue with asyncio run in streamlit Using Streamlit Aww yeah in my case it was the very last widget I remember Unfortunately the code is buried into company internal code. I’ll have to dig into it… While I will continue following your debugging for an asyncio solution (too much FastAPI recently, so getting to learn asyncio too ), I think this has a solution using Threading and injecting the ReportContext info in the new thread here and here. Maybe we have a kinda similar issue with asyncio, where t has 2 references, … Digging further through the discussions here, I found that above topic can help me, by making components of my streamlit app be run as co-routines controlled(?) by asyncio. Still, I shall appreciate any comment on my initial post. Thank you! Markus
0
streamlit
Using Streamlit
Is it possile to let streamlit app run under windows IIS web server?
https://discuss.streamlit.io/t/is-it-possile-to-let-streamlit-app-run-under-windows-iis-web-server/19890
I built over 15 apps through streamlit and use themin my job. Thanks streamlit develop, support team and our powerful commuity, it make our job become more and more convenient. With more and more apps be built, I have to open more and more windows of cmd to run new streamlit apps through command So, if there have some way to let streamlit app can run under windows IIS server, it will provide more stable way to keep streamlit app online.
Great question, I tried to follow the instruction on Deployment Guide 11 but without success. please share some light on this topic if anyone have done it. Thanks in advance
0
streamlit
Using Streamlit
PDF Download button error
https://discuss.streamlit.io/t/pdf-download-button-error/19639
Hi This code for a generated PDF download link works: b64 = base64.b64encode(pdf.output(dest=“S”)) html = f’Download file’ st.markdown(html, unsafe_allow_html=True) But this link for a download button does not work: b64 = base64.b64encode(pdf.output(dest=“S”)).decode() st.download_button(“Download Report”, data=b64, file_name=f"{oflnme}", mime=“application/octet-stream”) Any idea why this is happening? Thanks in advance
@Shawn_Pereira, Here’s a working example with st.download_button(). import streamlit as st from fpdf import FPDF import base64 pdf = FPDF() # pdf object pdf = FPDF(orientation="P", unit="mm", format="A4") pdf.add_page() pdf.set_font("Times", "B", 18) pdf.set_xy(10.0, 20) pdf.cell(w=75.0, h=5.0, align="L", txt="This is my sample text") st.download_button( "Download Report", data=pdf.output(dest='S').encode('latin-1'), file_name="Output.pdf", ) Note how I used .encode('latin-1') . The fpfd source code says “manage binary data as latin1 until PEP461 or similar is implemented”. pdf.output(dest='S') outputs a binary string that must be encoded as latin1. Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
Streamlit Components, Wrap around React Three Fiber?
https://discuss.streamlit.io/t/streamlit-components-wrap-around-react-three-fiber/4749
Any thoughts on whether it would be possible to use streamlit components to selectively wrap around React Three Fiber to expose a simple way to render 3D visualizations, permit orbiting view, and allow basic interaction like clicking on objects?
ref: GitHub react-spring/react-three-fiber 28 🇨🇭 A React renderer for Three.js (web and react-native) - react-spring/react-three-fiber Something like this should be possible, the biggest thing is defining how the Python side would interact with the React portion. There’s also the question if you can re-use an existing Python wrapper of threejs, which would make the component even easier: https://pythreejs.readthedocs.io/en/stable/ 33
0
streamlit
Using Streamlit
Beta_expander: how to execute code only when expanded
https://discuss.streamlit.io/t/beta-expander-how-to-execute-code-only-when-expanded/14150
Hello, I would like the use the beta_expander. Naïvely, I would like to have the code “inside” the beta_expander to be executed only when the beta_expander is expanded. I would also like to check is some beta_expander is collapsed. And I would also like to collapse/expand a beta_expander programmatically. What can be done from my dreams? Most important to me is the first dream. Thanks for your suggestions, Michel
Hey @maajdl I’m pretty sure I saw this request multiple times so let’s try to focus all those demands in one place the closest issue I could find is this one: github.com/streamlit/streamlit beta_expander expanded/collapsed state 35 opened Dec 1, 2020 LeoTafti enhancement layout ### Problem I'd like to be able to know whether a `beta_expander` is expanded… or collapsed (e.g. to show something on the main layout only when an expander in the sidebar is in expanded state). ### Solution **MVP:** Something like `beta_expander().expanded` as a `bool` would be nice. Could you maybe drop your full usecase there so we can start coordinating work for this on Github? Thanks a lot Fanilo
0
streamlit
Using Streamlit
Hide Fullscreen Option when displaying images using st.image
https://discuss.streamlit.io/t/hide-fullscreen-option-when-displaying-images-using-st-image/19792
Hi, I would like to remove the full screen option from displaying images. I’m visualizing images from a URL using streamlit columns. I create my four columns and display images as so cols = st.columns(4) cols[0].image(image['url'], use_column_width = True) However, for each image I end up with this full screen option on the top right of the image, is there a way to get rid of it?
Hi @AditSanghvi94 , Here’s an example, using the CSS part, you can hide the full screen option within the image. import streamlit as st url = "https://badgen.net/badge/icon/GitHub?icon=github&label" st.image(url) hide_img_fs = ''' <style> button[title="View fullscreen"]{ visibility: hidden;} </style> ''' st.markdown(hide_img_fs, unsafe_allow_html=True) Will this help ? Best, Avra
1
streamlit
Using Streamlit
Saving user data from a live intake form
https://discuss.streamlit.io/t/saving-user-data-from-a-live-intake-form/11460
Hi! My app is a book catalog + recommendation system for books, and I want to give the option for users to submit a form with additional books or authors that are not currently featured in the project. Some parts of the form works, but every time a new user submits a new response the csv file overwrites that entry, so I only have 1 row of data. This is the code I use: # submit button clickSubmit = st.button(‘Submit’) d = {‘Book Name(s)’: [newBookName], ‘Book Author(s)’: [newBookAuthor], ‘Feedback’: [newFeedback], ‘Name’: [emailName], ‘Email’: [emailAddress]} df = pd.DataFrame(data=d) if clickSubmit == True: st.markdown('<h3>Thank you for your feedback!</h3>', unsafe_allow_html=True) st.markdown('Submitted responses:') st.write(df) open('df.csv', 'w').write(df.to_csv()) else: st.markdown("Click submit to save form responses.") And this is my app 71 if you want to check out the current form (go to the ‘Add Books or Authors’ section). Any thoughts on how to get around this issue?
@vclugoar hey! Still working on the book app! That’s great Seriously, your app is looking AWESOME! and the rows of recommended book covers seems to work perfectly! Love the styling and all the visuals! (hey did you see that you can now make your own theme with custom theming?! That might be right up your alley for this. You just need to upgrade to the newest Streamlit version, check out the post here: Announcing Theming for Streamlit apps! 🎨 6) Ok enough of my chit chat and lets get your question answered So this is an easy fix, and is actually a pandas issue, your line here: vclugoar: df = pd.DataFrame(data=d) This is actually overwriting your pandas dataframe each time someone does this, its not appending the data at the end of the database. To append is a super quick fix though. You should just be able to directly append that new data on to your df. (Note: I believe you will need to create df as a pandas data frame before you run this, so if you run into an error that could be why) df = df.append(pd.DataFrame(data=d)) here is the pandas docs if you needed more info on this: pandas.DataFrame.append — pandas 1.2.3 documentation 1 Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Is adding github icon possible in markdown?
https://discuss.streamlit.io/t/is-adding-github-icon-possible-in-markdown/8593
Went through API reference — Streamlit 0.74.0 documentation 18 - but no fonts like font-awesome mentioned there. But I remember seeing an example somewhere.
If you use st.markdown, you can specify the HTML syntax for images and links.
0
streamlit
Using Streamlit
Icon with links
https://discuss.streamlit.io/t/icon-with-links/19818
Hey is there a way to insert .ico files and embed them with links like github repo or linkedin.
Hi @Varun_Nayyar , Yes it’s possible using, st.markdown syntax . # Add Link to your repo ''' [![Repo](https://badgen.net/badge/icon/GitHub?icon=github&label)](https://github.com/AvratanuBiswas/PubLit) ''' st.markdown("<br>",unsafe_allow_html=True) Does this code work for you ? Best Avra
0
streamlit
Using Streamlit
Changing the default text “Choose an option” from a multiselect widget
https://discuss.streamlit.io/t/changing-the-default-text-choose-an-option-from-a-multiselect-widget/19812
Is there a simple solution to change the default text (“Choose an option”) from the multiselect widget? I would like to translate the default text to German. Thanks!
Hi @NiklausBal, welcome to the Streamlit community!! Streamlit does not expose the option to change the placeholder text for st.multiselect. As such, there is no native option to change the placeholder because it is hard-coded in the frontend. However, here is an unofficial CSS hack. I used a CSS selector to first make the default placeholder invisible. Next, I use another CSS selector to set the value of the placeholder. This CSS is injected into the app with st.markdown 1. Solution 1 Insert the following snippet into your app: import streamlit as st change_text = """ <style> div.st-cs.st-c5.st-bc.st-ct.st-cu {visibility: hidden;} div.st-cs.st-c5.st-bc.st-ct.st-cu:before {content: "Wähle eine Option"; visibility: visible;} </style> """ st.markdown(change_text, unsafe_allow_html=True) 2 Replace the German text Wähle eine Option with the text of your choice. Here’s an example app and the corresponding output: Code import streamlit as st change_text = """ <style> div.st-cs.st-c5.st-bc.st-ct.st-cu {visibility: hidden;} div.st-cs.st-c5.st-bc.st-ct.st-cu:before {content: "Wähle eine Option"; visibility: visible;} </style> """ st.markdown(change_text, unsafe_allow_html=True) options = st.multiselect( 'What are your favorite colors', ['Green', 'Yellow', 'Red', 'Blue'],) st.write('You selected:', options) Output image961×803 21.9 KB Are you able to reproduce this behavior? Happy Streamlit-ing! Snehan Inspiration: How can I replace text with CSS? 1
1
streamlit
Using Streamlit
Light mode by default
https://discuss.streamlit.io/t/light-mode-by-default/19816
Hello ! How can I set my dashboard to the Light Mode by default ? Currently, it looks like the “Use system setting” is setting by default. May you advise please ? Thanks in advance !
Hi @miranarkt, welcome to the Streamlit community!! I would suggest reading our documentation on Theming. To use the light theme by default, create a .streamlit/config.toml file in your app folder with the following lines: [theme] base="light" Once you create a .streamlit/ folder containing the above config.toml file, restart your app. Your app should now be using your custom (light) theme. To verify, click on the hamburger menu on the top-right corner of your app and click on Settings. Under the Theme section, you should see “Custom Theme” as the selected option: image1372×1047 41.3 KB Does this help? Happy Streamlit-ing! Snehan
0
streamlit
Using Streamlit
Is it possible to add link?
https://discuss.streamlit.io/t/is-it-possible-to-add-link/1027
I was trying to add links to my picture shown using streamlit. But when I click those buttons, the page automatically refresh. Is it possible to jumping to another page and could return to current page continuously when press return on the new page?
Hey @Jing_Xu and welcome to the community ! Just to clarify - are you looking for a selectbox that switches “apps” or are you looking to add a clickable link to your app? Also anything else you can tell me about the app and use case would help so I can help you figure out the best way to do what you want!
0
streamlit
Using Streamlit
Display text inside text box of a particular color
https://discuss.streamlit.io/t/display-text-inside-text-box-of-a-particular-color/19788
Hey Community members I have a teeny doubt but I can’t find its solution. I have a string object and i am willing to display it inside a box of black color due to my background. Kindly provide the code for it pls
Hey @Varun_Nayyar, I posted an answer to someone a while ago about how to change the colour of just one text element. You can use the same code to change your text colour, and just hardcode the colour you want: Traffic light for values Using Streamlit Hey @jgodoy, First Welcome to the Streamlit Community! I have a solution on how to do this! If you use st.markdown with the unsafe_allow_html=True, then you can pass css code to st.markdown to change text colour! I made an example for you that will change text color based on a slider value of 0-100 (the 0% to 100% in your example). This code used the color package which you can install in your environment with … Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
St.text_input shows “None” when input value from Dataframe is None
https://discuss.streamlit.io/t/st-text-input-shows-none-when-input-value-from-dataframe-is-none/19771
st.text_input shows “None” when input value from Dataframe is None. Is there any way to show “” instead of None when the input value is None or null or any other type of na? I’m having a form to show and fill, so there’re lots of st.text_input to use. I’m now trying “if pd.notna(value): xxx else: xxx” but with lots of st.text_input components, it’s way too complicated.
Did you try adding value="" within your text input?
0
streamlit
Using Streamlit
Hide titles link
https://discuss.streamlit.io/t/hide-titles-link/19783
image735×128 8.61 KB Good day. First of all, I want to thank all for the magnificent tool that Streamlit is. I was wondering if there is a way to hide the little clip symbol that appears next to the titles. The reason for this is that when someone clicks its, it changes the http direction of the app Example: -before clicking: https://share.streamlit.io/tylerjrichards/streamlit_goodreads_app/books.py 2 -after clicking: https://share.streamlit.io/tylerjrichards/streamlit_goodreads_app/books.py#analyzing-your-goodreads-reading-habits 2 I need to turn this off because I have styled my app with lot of css code and this feature is interfering with the global behavior. Thanks in advance for you help!
Hi Randy, thank you very much for your prompt response. Indeed I could achieve it with CSS. If anyone wants to hide that link button you just need to include the following in your script: st.markdown(""" .css-m70y {display:none} “”", unsafe_allow_html=True)
1
streamlit
Using Streamlit
Support for CytoscapeJS
https://discuss.streamlit.io/t/support-for-cytoscapejs/872
Hi Streamlit Team, I am about to finish my master thesis in Bioinformatics and stumbled above Streamlit on Medium - Not sure if I should ask here or on Github: Is there any integration with CytoscapeJS planned in the near future? Right now my web app is Plotly-Dash based + utilizing the Dash-Cytoscape Plugin but I would love to rewrite it in Streamlit.
Hi @IvoLeist - welcome to the community and congrats on finishing your thesis! Just looking at Cytoscape.js and that is a really interesting library. We do have support for GraphViz 25 but I get you don’t necessarily want to change all of your chart types. While Cytoscape.js is not in the near future, I’m adding it as a feature request 19 so you can track when it is integrated. Also we are thinking about our plugin architecture 13 to make it possible for users to create their own plugins, so you could weigh in there as well. Best of luck on the masters and your app - would love to see it if you do end up making it in Streamlit!
0
streamlit
Using Streamlit
Issue with displaying dict type cell values using st.dataframe
https://discuss.streamlit.io/t/issue-with-displaying-dict-type-cell-values-using-st-dataframe/19781
Hello Everyone, I am new to Streamlit and facing issues while working with dataframes. Use-case : I need to store dict as cell values in dataframe ‘df’ for column ‘a’ and string for column ‘b’. Normally, my code outputs the result as required but somehow when I use the same code on Streamlit using st.dataframe, It merges cell values for the columns that has value type dict. I have attached the example code below for your reference. df = pd.DataFrame([[{‘1’:‘2’}, ‘abc’], [{‘6’:‘3’}, 'def]], columns= [‘a’,‘b’]) Expected output: Output using st.dataframe(): output21093×287 6.99 KB Could someone help me out on this?. Thanks in advance.
Hey @nikita, I am able to reproduce this exact error on my computer too! Can you please file a GitHub issue on this and add your code line in? GitHub Issues · streamlit/streamlit 3 Streamlit — The fastest way to build data apps in Python - Issues · streamlit/streamlit Thanks for the catch! Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
St.multiselect
https://discuss.streamlit.io/t/st-multiselect/19722
How to add “All” and “None” option in st.multiselect so that if I click “All” then it select all options and if I select “None” then it select no options. I will be grateful if anyone solve this problem or if the solution is already exists then kindly provide me the link.
Hi @udo , Here’s a list of neat workarounds, provided by @Marisa_Smith . 'Select All' on a Streamlit Multiselect Using Streamlit Hi all, I’ve been trying to get a “Select All” checkbox to work on a multiselect widget by doing the following: if st.checkbox('Select all'): selected_options = st.multiselect("Select one or more options:", ['A', 'B', 'C'], ['A', 'B', 'C']) else: selected_options = st.multiselect("Select one or more options:", … Does this help ? Best, Avra
0
streamlit
Using Streamlit
Interdependent Forms
https://discuss.streamlit.io/t/interdependent-forms/19121
@Jessica_Smith @andfanilo @thiago @okld @vdonato @kmcgrady @Charly_Wargnier from pandas_profiling import ProfileReport import streamlit as st from streamlit_pandas_profiling import st_profile_report import pandas as pd def describe_col(df, col): print(df[col].unique()) def get_summary_stats(df): with st.form(key="describe-df"): col = st.selectbox("Select column for summary stats", df.columns) #on clicking the stats_btn the WHOLE APP RUNS again! FIX THIS PLEASE stats_btn = st.form_submit_button(label="Get Summary Statistics", on_click = describe_col, args=(df, col)) def file_handler(): def profiler(): file = st.session_state.upload delim = st.session_state.choice.split(" ")[1][1:-1] df = pd.read_csv(file, sep=delim, engine="python") file_info = {"Filename": file.name, "FileType": file.type, "FileSize": file.size} pr = ProfileReport(df, explorative=True) st.write(file_info) st_profile_report(pr) get_summary_stats(df) with st.form(key="file_upload"): data_file = st.file_uploader("Upload CSV File", type=['csv'], key="upload") seperators = [" ", "pipe (|)", r"tab (\t)", "comma (,)", "semicolon (;)"] choice = st.selectbox("Select File Seperator", seperators, key="choice") submit_file_btn = st.form_submit_button(label='Submit', on_click=profiler) if __name__ =="__main__": file_handler() On clicking the stats_btn the whole app runs again. I don’t want to do that Furthermore, the profiler method does not work outside file handler method. i.e. the form could be inside one function & could contain some inputs. But those inputs are locally restricted to the scope of the said function I cannot access st.session_state.upload outside file_handler
Hi, The reason this isn’t working as expected is that you’re chaining the second form’s rendering via the first form’s callback. Also you’re calling functions within the form’s lifecycle, in those callbacks. I think best practice is to use forms to collect field values (in a way that doesn’t cause Streamlit to rerun as you make adjustments to the field value widgets) and then after hitting the form submit button to run operations with those values. E.g. the profiler function should be called after the form is submitted and has bound its field values. Since pandas profiler is quite heavyweight, I recommend holding its profile report state in session state whilst interacting with the data frame that is used to generate the report, otherwise you’ll lose the report state between Streamlit reruns and it would need to be regenerated each time, which takes a while. Here’s a complete rewrite of your example demonstrating the way that I’d write it: pandas_profiler.py import streamlit as st import pandas_profiling from streamlit_pandas_profiling import st_profile_report import pandas as pd st.set_page_config( page_title='Data Profiler', layout='wide', page_icon='🔍' ) state = st.session_state if 'profile_report' not in state: state['profile_report'] = None def generate_profile_report(data_file, delimiter, minimal): file_info = {"Filename": data_file.name, "FileType": data_file.type, "FileSize": data_file.size} st.write(file_info) df = pd.read_csv(data_file, sep=delimiter, engine="python") pr = df.profile_report(lazy=True, minimal=minimal) state.profile_report = {'data': df, 'pr': pr} def file_handler(): seperators = {" ": " ", "pipe (|)": "|", r"tab (\t)": "\t", "comma (,)":",", "semicolon (;)":";"} file_upload_form = st.form(key="file_upload") with file_upload_form: data_file = st.file_uploader("Upload CSV File", type=['csv'], key="upload") delimiter = seperators[st.selectbox("Select delimiter", seperators.keys(), key="delims")] minimal = st.checkbox('Minimal report', value=True) if file_upload_form.form_submit_button(label='Submit') and data_file: generate_profile_report(data_file, delimiter, minimal) if (data_file and delimiter and state.profile_report): data = st.session_state.profile_report['data'] pr = st.session_state.profile_report['pr'] col = st.selectbox("Select column for summary stats", options=['']+list(data.columns)) if col != '': st.write(pd.DataFrame(data[col].unique(), columns=[col]).T) st_profile_report(pr) else: st.info('Please upload a CSV data file, select a delimiter and hit submit.') state.profile_report = None if __name__ =="__main__": file_handler() Demo See gist 1 for the downloadable source file. HTH, Arvindra
0
streamlit
Using Streamlit
Can I Use Streamlit and Folium to filter out a specific number of data and display it?
https://discuss.streamlit.io/t/can-i-use-streamlit-and-folium-to-filter-out-a-specific-number-of-data-and-display-it/19705
I’m developing a web mapping application using Python Folium and I came across Streamlit and I was impressed. So I decided I will use it especially since it has an amazing design for developing a dashboard. I wanted to create a filter dashboard, and this is where I wanted to inquire if there is a way to do so. My data is about schools, I wanted to find which schools would require more financial aid than others, kind of a rank. I would like to create a filter that would display the chosen number of schools, say top 100, or 50, depending on the number selected in the filter. Also, if i can be able to create a filter to apply different weights (some columns get generated by applying weights to existing columns) and display the results. Thanks! Regards, Evans.
Hey @Steel, First, welcome to the Streamlit community!!! This is a pretty open-ended question, there are many ways to make a filtered dashboard in Streamlit! do you have an MWE of code you can post to help explain how you want to filter and what you want to be displayed? This post outlines tips and trick on how to structure your questions on our forum to give you the best chance of getting an answer: Welcome ! Some suggestions for your first Streamlit question Using Streamlit Welcome to the Questions category, the place to be if you’re having issues with your code, want to chat on Streamlit best practices or share some exotic code snippets with other users Don’t hesitate to post any problem you’re having with Streamlit there, so other people can discuss it with you ! If you have trouble writing about your issue, from our experience the following details help a lot : A quick description of what you are trying to achieve and the roadb… I would suggest starting with st.form, and putting all your filtering parameters in there, that way Streamlit refreshes only after all the filter parameters have been applied. docs.streamlit.io st.form - Streamlit Docs 2 st.form creates a form that batches elements together with a “Submit” button. Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Hyperlink in streamlit without markdown
https://discuss.streamlit.io/t/hyperlink-in-streamlit-without-markdown/7046
I would like to know is there any updates for streamlit where we could use hyperlink without markdown? I need it for one of my application where the user would login and on clicking the link the app opens. Is this possible?
Hey @harish_natarajan, I believe that we already have the feature your looking for, you can definitely put hyperlinks in a Streamlit app import streamlit as st st.write("check out this [link](https://share.streamlit.io/mesmith027/streamlit_webapps/main/MC_pi/streamlit_app.py)") will produce: check out this link 231 Cheers! Marisa
1
streamlit
Using Streamlit
Autocomplete Option for st.text_input()
https://discuss.streamlit.io/t/autocomplete-option-for-st-text-input/7371
Is there any way to have the text_input autocomplete from a column of strings in a DataFrame?
Hey @chefnewman! For the text_input there currently isn’t a way to have it auto complete. BUT if you’re looking to select a string from a column of strings in a DataFrame, where they can only use those specific strings, maybe select box or multi select will work for you? They allow you to populate a list of preselected options, and when you type into the field, they show options matching what you have typed so far. They also allow a dropdown box for people to look through all available options. Screen Shot 2020-11-23 at 10.28.11 AM1334×710 26.8 KB Here is when you start typing in the field: Screen Shot 2020-11-23 at 10.28.26 AM1334×608 23.1 KB Both of these widgets have this behaviour, the select box simply allows only one choice and multi select allows multiple selections! Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Language Translator app is throwing up an error regarding JSONDecode
https://discuss.streamlit.io/t/language-translator-app-is-throwing-up-an-error-regarding-jsondecode/14620
Hello all, A few days ago, I deployed a Language Translator app. The Language Translator app was going fine those days. When I checked this morning, It is showing a json.JSONDecode error. ERROR: json.decoder.JSONDecodeError: Extra data: line 1 column 798 (char 797) Uncaught app exception Traceback (most recent call last): File “/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py”, line 338, in _run_script exec(code, module.dict) File “/app/languagetranslator/main.py”, line 35, in translate = translator.translate(text,lang_src=value1,lang_tgt=value2) File “/home/appuser/venv/lib/python3.7/site-packages/google_trans_new/google_trans_new.py”, line 188, in translate raise e File “/home/appuser/venv/lib/python3.7/site-packages/google_trans_new/google_trans_new.py”, line 152, in translate response = json.loads(response) File “/usr/local/lib/python3.7/json/init.py”, line 348, in loads return _default_decoder.decode(s) File “/usr/local/lib/python3.7/json/decoder.py”, line 340, in decode raise JSONDecodeError(“Extra data”, s, end) Github repo: GitHub - HarisankarSNair/LanguageTranslator: A web app for translating from one language to another.Almost all languages are available.App also generates an audio file of the translation and lets you download the audio file. 4 Live App: https://share.streamlit.io/harisankarsnair/languagetranslator/main/main.py 8 I don’t know why this JSON error is being shown up suddenly. Can anyone help me solve this problem? Any help will be much appreciated. Regards, Harisankar.
Hi all, It is coming from a JSON issue at google_trans_new.py. I fixed at my local by making some changes at this file. For further information to fix at your local you may read this article. Its working properly on local: Python google-trans-new translate raises error: JSONDecodeError: Extra data: - Stack Overflow 16 But I could not find a way to work this on Streamlit host. Could somebody fix this issue? Kind Regards, Cagdas
1
streamlit
Using Streamlit
Download XLSX file with multiple sheets in Streamlit
https://discuss.streamlit.io/t/download-xlsx-file-with-multiple-sheets-in-streamlit/11509
Hi there ! I’ve been experimenting with streamlit for a few days and trying to convert some scripts into apps. It’s been interesting so far but I’ve hit a roadblock : I can’t find a way to download XLSX file from the app. My script is based on pandas and is pretty easy : Import CSV file Clean/analyze data/create new dataframes Export in a clean XLSX file with multiple sheets @Charly_Wargnier showed me a way to download a CSV file from the app but I can’t figure the way to download my “export_keywords.xlsx” file : export780×213 41.1 KB Is there a way to do it ? Thank you in advance.
Hey Michael! Welcome to the forum! I think this download_button function from @jrieke would do what you need. github.com jrieke/traingenerator/blob/main/app/utils.py#L73 85 # From: https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661/3 if new_tab: js = f"window.open('{url}')" # New tab or window else: js = f"window.location.href = '{url}'" # Current tab html = '<img src onerror="{}">'.format(js) div = Div(text=html) st.bokeh_chart(div) def download_button( object_to_download, download_filename, button_text # , pickle_it=False ): """ Generates a link to download the given object_to_download. From: https://discuss.streamlit.io/t/a-download-button-with-custom-css/4220 Params: ------ object_to_download: The object to be downloaded. Thanks Charly
0
streamlit
Using Streamlit
Selectbox too slow when too many options
https://discuss.streamlit.io/t/selectbox-too-slow-when-too-many-options/19687
Hello! I have a selectbox with 100k+ options and it takes a bit too long to interact with it. Is there any way I can reduce the delay? Maybe somehow reduce the number of visible options from the dropdown, or none at all? Thamks
You could try caching the function that loads options into the selectbox. Check the Streamlit documentation about optimizing performance.
0
streamlit
Using Streamlit
Sending email through the outlook app of the user, not the server
https://discuss.streamlit.io/t/sending-email-through-the-outlook-app-of-the-user-not-the-server/19678
Hello everyone, i am trying to build an application that on a click of a button opens the outlook application of the user and sends an email with attachments etc etc. When i run this app on my pc, everything works fine, when i put it on the server machine and access the app through that, i get an error suggesting that outlook is not installed. So i believe the app is trying to open outlook from the server machine, not the user. Is there a way to solve this? Thank you in advance!
You could probably try one of the following: Load outlook on the server and send an email through that account, just as you are doing from a local machine. Use mail protocol to send an email through Gmail (where you will have an account for this purpose) Have an internal email server accessible to the server (where your application is stored) that you can send your email from.
0
streamlit
Using Streamlit
Graphviz graph with different engine/layout (e.g., neato, circo) are not rendered correspondingly in the streamlit 0.78.0/0.79.0
https://discuss.streamlit.io/t/graphviz-graph-with-different-engine-layout-e-g-neato-circo-are-not-rendered-correspondingly-in-the-streamlit-0-78-0-0-79-0/10982
When I try different layout/engine of the graphviz graph (e.g., neato, circo, see here: https://graphviz.org/ 2), the streamlit seems not render the graph correspondingly. Any suggestions?
Hey @Jiangang_Hao, can you please provide a small example with minimum code to to reproduce the error? Also some screenshots would be helpful. Thanks for your bug report. Best regards Chris
0
streamlit
Using Streamlit
Run app only after users enters all inputs
https://discuss.streamlit.io/t/run-app-only-after-users-enters-all-inputs/8998
I have a python app that takes multiple inputs from the user and then runs the program. But on Streamlut the app seems to run after each input is added… I want the program to run only after the user has submitted all inputs and hits the “Submit” button. Also, the program seems to self execute each time the page is reloaded. How do I prevent this?
Hi @Ajay_Chakravarthy - Yes, it is possible to have the results gated based on clicking a submit button. If I’m not mistaken (I can’t find it as this exact moment), @okld has created an example of this along with using our shared state workaround. Ajay_Chakravarthy: Also, the program seems to self execute each time the page is reloaded. How do I prevent this? This is a fundamental property of the Streamlit architecture, so it’s not something that can be turned off. In this post, I briefly discuss the design decision for having the refresh model vs. the callback model: Streamlit vs. Other Apps Using Streamlit Hi @Bryson_Cale, welcome to the Streamlit community! Our launch article covers some of your questions: https://towardsdatascience.com/coding-ml-tools-like-you-code-ml-models-ddba3357eace?source=friends_link&sk=f7774c54571148b33cde3ba6c6310086 In short, the top-down model vs. the callback model of interaction really depends on the user’s background. As you mention, you’ve experienced the event-driven experience first, so it makes sense to you. In contrast, Streamlit hypothesized that “data sci… Best, Randy
0
streamlit
Using Streamlit
Drop down list in Table
https://discuss.streamlit.io/t/drop-down-list-in-table/19662
HI , I am new to streamlit (and Python for that matter) . I am looking to create a table which has a drop down selection box within it like that pictured below image886×251 11.2 KB Is this possible within Streamlit? all guidance appreciated
If you want to follow your logic path, the way to do it is: Create 3 columns using st.columns Write the headers for each columns For the data rows (in each column), you can use st.selectbox in a loop for the number of rows you want. However, I suggest this method: Create a 1 row x 3 columns using st.columns in a form. In each column, put your st.selectbox with its related options Create an empty pandas dataframe with 3 columns below this row (mentioned in the above point) Every time you update the form with new data, you can programmatically add the data to a new pandas row Cheers
0
streamlit
Using Streamlit
St.text_input & st.text_area have an issue for expecting an argument “placeholder”
https://discuss.streamlit.io/t/st-text-input-st-text-area-have-an-issue-for-expecting-an-argument-placeholder/19637
An argument “placeholder” seems to be updated new via ver.1.2.0. even though the current version 1.2.0 of streamlit is in my labtop, st.text_input & st.text_area doesn’t get that argument. is there anything else I can do?
the function of argument “value” in st.text_input and st.text_area is equal to “placeholder” st.text_input(label, value="placeholder information put here", max_chars=None, key=None, type="default", help=None, autocomplete=None, on_change=None, args=None, kwargs=None, *, placeholder=None) st.text_area(label, value="placeholder information put here", height=None, max_chars=None, key=None, help=None, on_change=None, args=None, kwargs=None, *, placeholder=None)
0
streamlit
Using Streamlit
[plotly] Problem using latex in titles and axis labels
https://discuss.streamlit.io/t/plotly-problem-using-latex-in-titles-and-axis-labels/4766
Hi! I’m trying to use latex on a plotly figure (yaxis) but streamlit doesn’t recognize it and shows the raw code, but when I visualize in jupyter lab the latex code shows fine image1252×741 50.6 KB image2020×1402 192 KB
Same experience here. I can only get latex to show in figures using matplotlib.
0
streamlit
Using Streamlit
Radio button “lock”
https://discuss.streamlit.io/t/radio-button-lock/19623
Hi guys, How can I lock the state of a radio button after it has been selected? That is, how can I avoid the user to change his answer? Thank in advance
Hi @Bojan_Martinovic , Welcome to the Streamlit Community Forum. Unfortunately, I’m not aware of locking the radio button option. But would this workaround help you ? import streamlit as st empty = st.empty() options = ['None','A','B'] choice = empty.radio(label = "Your one time selection",options = options) if not (choice == 'None') : st.write("You selected : " + choice) empty.empty() Best Avra
1
streamlit
Using Streamlit
Toggle hide/show sidebar from Python
https://discuss.streamlit.io/t/toggle-hide-show-sidebar-from-python/5805
Is there a way to hide/show (toggle) the sidebar from Python? I am aware that there is initial_sidebar_state in set_page_config (currently beta_set_page_config), but what I would like to do is different. I want to hide the sidebar from users initially and only show it when “necessary” for the app. My overarching goal is to hide unnecessary complexity from end users (and also nudge the ones who might want / need the complexity about where to find it). Thanks!
im looking for the Answer
0
streamlit
Using Streamlit
St_aggrid does not update when user inputs editable property
https://discuss.streamlit.io/t/st-aggrid-does-not-update-when-user-inputs-editable-property/19626
@PablocFonseca Thanks a lot for the component. See code below. I would like to have the user select whether he wants to modify a column (“editable”) or not (“not editable”). However, the user selection has no effect on how the component behaves. In the case below, at the first execution, “editable” returns true and the AgGrid component continues to allow to edit data in the column no matter what the user select successively. Is there a way to make this work? Thanks! import streamlit as st from st_aggrid import AgGrid, GridOptionsBuilder import pandas as pd df = pd.DataFrame([['1','2',''],['d','e',''],['','','']], columns=['first','second','modified_data']) options = ('editable', 'not editable') selected_option = st.selectbox('Do you want allow edits?', options) edit_data = selected_option == 'editable' gb = GridOptionsBuilder.from_dataframe(df) gb.configure_column('modified_data', editable=edit_data) go = gb.build() response = AgGrid( df, gridOptions=go, reload_data=False, key='Ag_1' )
Hi @gaetanoe , Welcome to the Streamlit Community Forum! Please, try this code below, it seems to work. import streamlit as st from st_aggrid import AgGrid, GridOptionsBuilder , GridUpdateMode import pandas as pd df = pd.DataFrame([['1','2',''],['d','e',''],['','','']], columns=['first','second','modified_data']) options = ("True", "False") selected_option = st.selectbox('Do you want allow edits?', options) #gb.configure_column('modified_data', editable = selected_option) # Doesnot work gb = GridOptionsBuilder.from_dataframe(df) if selected_option == 'True': gb.configure_column('modified_data', editable = True) else: gb.configure_column('modified_data', editable = False) go = gb.build() #st.write(go) # Check the Grid Options response = AgGrid( df, gridOptions=go, reload_data=False, update_mode=GridUpdateMode.MODEL_CHANGED ) Best Avra
0
streamlit
Using Streamlit
Updating only certain content on page
https://discuss.streamlit.io/t/updating-only-certain-content-on-page/19648
Hey everybody, i have this problem: i am facing toghether with some schoolmates a Data Science project where we made a market analysis tool; available to see here: https://geocompetitortracker.herokuapp.com/ 4 the problem is that once you, for example, select a different vendor to be displayed of the map down below, all the statistics from the previous search disappear. The only case i’d like that to happen is indeed when pressing search once more. the code is 548 lines i don’t know if it’d be appropriate to paste here. Thanks in advance for the help!
Hi @castoldie , Welcome to the Streamlit Community Forum ! Thank you for sharing the app here, it’s really a nice app and wish you guys the best! castoldie: the problem is that once you, for example, select a different vendor to be displayed of the map down below, all the statistics from the previous search disappear. Best possible guess would be, since Streamlit runs linearly from the very top, the app reruns and therefore all your stats disappears, unless you click the search button again. An easy (not ideal) quick fix would be, to change your submit button to a checkbox st.checkbox. Which will maintain the checked ‘ON’ state for the app. Other possible workaround can be, to control the state of the search button using SessionState, [ st.session_state ] Otherwise, wrapping up the computing part of your code, within a single function may do the trick with usage of st.experimental_memo or st.cache syntax. Do refer to the doc. The above workarounds may not be valid, if it’s not the case within your app. You can always share the link of your code or link of your repo, if it’s fine for you to be public. Let me know. Best, Avra
0
streamlit
Using Streamlit
Something wrong happen when I execute the command “streamlit run my_script.py”
https://discuss.streamlit.io/t/something-wrong-happen-when-i-execute-the-command-streamlit-run-my-script-py/19520
When I execute the command “streamlit run my_script.py”,a fatal error in launcher happen.I have no idea what makes this error happen image1799×51 45.9 KB
Have you checked the obvious things like python version, streamlit version, and both are 64-bit. Does streamlit hello work? If you are able, please post a minimal sample app to reproduce this error? Thanks, Arvindra
0
streamlit
Using Streamlit
Google Drive API: How to read the secrets.toml file as a json file?
https://discuss.streamlit.io/t/google-drive-api-how-to-read-the-secrets-toml-file-as-a-json-file/19528
I’m using the Google Drive API for a project, which now I want to move to Streamlit. I was using a client_secrets.json to create the API service using a function provided by Google: CLIENT_SECRET_FILE = 'client_secrets.json' # 👈 JSON File with the API KEY and other config stuff API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] #This function expects a json file/route as the "CLIENT_SECRET_FILE" parameter 👇 service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) I know about the secrets.toml and already created it using the content of the client_secrets.json. Now, when I declare CLIENT_SECRET_FILE = st.secrets['something'] #or CLIENT_SECRET_FILE = st.secrets I get this error: with open(client_secrets_file, "r") as json_file: TypeError: expected str, bytes or os.PathLike object, not Secrets How can I use the Create_Service() function using TOML instead of JSON? Thanks for your help!!!
Hi @gmepscon, welcome to the Streamlit community! In this case, when you are using the secrets functionality, you often need to change the authentication method. For example, in this example where we show how to connect Streamlit to a private Google Sheet 3, there is a method service_account.Credentials.from_service_account_info where you can pass the values in, rather than a JSON file. If you can post the code or the library you are using, I can quickly look at the Google library documentation and suggest what function it might be. Best, Randy
0
streamlit
Using Streamlit
Navigating through dataframe records
https://discuss.streamlit.io/t/navigating-through-dataframe-records/19605
Hi there, I would like to create an app that navigates through the record of a dataframe. Basically, I would the first record of the dataframe to be displayed, then the user clicks a “next” button and the second record is now displayed etc. Is there already an existing component/element to do that? I hope my question is clear. I just started using Streamlit Thanks!
Hi @MrnRbn , Welcome to the Streamlit Community Forum. would you like to navigate through each rows of the data frame ? Here’s a code snippet below. Refer to Streamlit Session State demo apps import streamlit as st import pandas as pd # initialize list of lists data = {'col1': [1, 2, 3, 4], 'col2': [300, 400, 500, 600]} # Create the pandas DataFrame df = pd.DataFrame(data) # print dataframe. st.dataframe(df) # Using Session State for pagination # from example - https://github.com/streamlit/release-demos/blob/0.84/0.84/demos/pagination.py if "row" not in st.session_state: st.session_state.row = 0 def next_row(): st.session_state.row += 1 def prev_row(): st.session_state.row -= 1 col1, col2, _, _ = st.columns([0.1, 0.17, 0.1, 0.63]) if st.session_state.row < len(df.index)-1: col2.button(">", on_click=next_row) else: col2.write("") if st.session_state.row > 0: col1.button("<", on_click=prev_row) else: col1.write("") st.write(df.iloc[st.session_state.row]) Otherwise, you can also implement the component , Streamlit-AgGrid 7 - an user-interactive table. Hope this helps. Best, Avra
1
streamlit
Using Streamlit
How do i align st.title?
https://discuss.streamlit.io/t/how-do-i-align-st-title/1668
how do i align st.title ?
Hi @qxlsz. I would like to help. But I need more info to be able to help. Please be a bit more specific. What do you mean by align? Horizonally, vertically or… The best approach is to provide a small code example and a screenshot that shows how it looks and indicates how it should look. Thanks.
0
streamlit
Using Streamlit
St.session_state deletes on refresh
https://discuss.streamlit.io/t/st-session-state-deletes-on-refresh/19170
Hey guys, I am trying to build a login wall with Google OAuth. When logging the user for the first time I store the OAuth token in st.session_state.token. However, every time I refresh the page, the session_state gets erased and throws the client out of the page. Here is the code I am using streamlit-google-oauth/app.py at main · uiucanh/streamlit-google-oauth · GitHub 5. There is also a problem with write_access_token() function in the code because it always returns an “malformed auth code” error. But still, even if it worked it would refresh the session_state anyway. Is there a way to set an expiration time for session_state? How do you keep your users logged in after they refresh the page? Thanks
@ScottZhang So, what I ended up doing is setting a param in the url everytime the user logs in and only deleting it when he logs out. Url params remain the same on page refresh. Login: st.experimental_set_query_params(code=“logged_in”) everytime the user logs in. Check Login: st.experimental_get_query_params()[‘code’][0] Logout: st.experimental_set_query_params(code=“logged_out”) Here is my code. main.py def main(user: object): st.write(f"You're logged in as {st.session_state['user']['email']}") set_code(code=user['refreshToken']) st.write("Hello World") app.py if __name__ == '__main__': # firebase configuration firebaseConfig = { "apiKey": os.environ['APIKEY'], "authDomain": os.environ['AUTHDOMAIN'], "databaseURL": os.environ['DATABASEURL'], "projectId": os.environ['PROJECTID'], "storageBucket": os.environ['STORAGEBUCKET'], } firebase = pyrebase.initialize_app(firebaseConfig) auth = firebase.auth() # authentification if "user" not in st.session_state: st.session_state['user'] = None if st.session_state['user'] is None: try: code = st.experimental_get_query_params()['code'][0] refreshToken = refresh_session_token(auth=auth, code=code) if refreshToken == 'fail to refresh': raise(ValueError) user = get_user_token(auth, refreshToken=refreshToken) main(user=user) except: st.title("Login") login_form(auth) else: main(user=st.session_state['user']) auth.py import streamlit as st import requests def set_code(code: str): st.experimental_set_query_params(code=code) def login_form(auth): email = st.text_input( label="email", placeholder="fullname@gmail.com") password = st.text_input( label="password", placeholder="password", type="password") if st.button("login"): try: user = auth.sign_in_with_email_and_password(email, password) st.session_state['user'] = user st.experimental_rerun() except requests.HTTPError as exception: st.write(exception) def logout(): del st.session_state['user'] st.experimental_set_query_params(code="/logout") def get_user_token(auth, refreshToken: object): user = auth.get_account_info(refreshToken['idToken']) user = { "email": user['users'][0]['email'], "refreshToken": refreshToken['refreshToken'], "idToken": refreshToken['idToken'] } st.session_state['user'] = user return user def refresh_session_token(auth, code: str): try: return auth.refresh(code) except: return "fail to refresh" Its not ideal. But works for the time being. Points for improvement. check if token expired.
1
streamlit
Using Streamlit
Deployment Error Secrets file not found. Expected at:
https://discuss.streamlit.io/t/deployment-error-secrets-file-not-found-expected-at/19594
Hello everyone I’m trying to deploy my app into streamlit cloud but always appears this error: Secrets file not found. Expected at: and my repo link… This issue is driving me crazy. I already delete, reboot and nothing seems to work. Could someone help me with this? Repo link: LU_Public/Formulario at main · TPPDeyanira/LU_Public · GitHub 3 requirements773×570 32.3 KB credentials2152×1363 152 KB
@Kazz - Apparently this was a regression in the cloud codebase, and should be resolved now. You may need to delete and re-deploy your app for the fix to take hold. If this doesn’t resolve your issue, please let us know! Best, Randy
1
streamlit
Using Streamlit
St.map() error
https://discuss.streamlit.io/t/st-map-error/19615
Capture845×631 24.3 KB I get this error whenever I try to use st.map() on a dataframe
Hi @akinolaa, and welcome to the Streamlit community! This error seems to indicate that Pandas cannot find what you’re looking for. Are you sure that warnings is in that dataframe? (check out possible spaces, as it would need to be an exact match to work More info on how to handle this issue here: KeyError Pandas - How To Fix - Data Independent 2 Hope that helps Best, Charly
0
streamlit
Using Streamlit
Having Navigation tabs in Streamlit
https://discuss.streamlit.io/t/having-navigation-tabs-in-streamlit/19607
Hi Team, I am trying to deploy my project on streamlit. I have few questions which I couldn’t find it in the documentation. Is there any way we can have a navigation bar with tabs on streamlit, instead of like radio buttons on the side? Can you please help us with this? Regards, Vineeth
Hi @Vineeth_Reddy , There are few possible workaround which can help you implement it . Check out this Streamlit components - New Component: `st_btn_select` - Selectbox alternative with buttons 12 New Release Hydralit: Multi-page apps even nicer 20 Otherwise, you can check out @dataprofessor 's Youtube video 1 on st.markdown function to embed HTML code for Bootstrap’s Navbar. I hope this helps. Best, Avra
0
streamlit
Using Streamlit
Multiselect reinitializing the page
https://discuss.streamlit.io/t/multiselect-reinitializing-the-page/19578
Hello community, I have encountered several times now this behavior but this time with specifically with the multiselect object. Scenario: I have a button, once clicked it will show me a text and a multiselect object. Weird behavior: Once I select the options I want the page reinitialize without printing anything. Here is two methods I tried, they gave me the same behavior Method 1: import streamlit as st btn= st.button ('Start') dates = ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', ] if btn : st.write('123') output = st.multiselect('Test', options = dates) if output != []: st.write(output) else: st.write('haha') Method 2 import streamlit as st btn= st.button ('Start') dates = ['2021-01-01', '2021-01-02', '2021-01-03', '2021-01-04', ] if btn : st.write('123') #option 2 with st.form(key='rand'): selected_dates = st.multiselect('Test 123', options = dates) submit_button = st.form_submit_button(label='Validate') if submit_button: stcol_load.write(selected_dates) Any idea what I am doing wrong? Ideas are appreciated. Thank you,
Hi @Rima , If I understood you correctly, you would like to get the selected date as output, but instead your app returns to the initial state, right ? This is because of Streamlit’s behaviour of running the app linearly from the very top. Hence, it gets stuck at st.button syntax, and you see no output. A quick workaround, (not ideal) using st.checkbox option. So instead of Rima: btn= st.button ('Start') Use, check_state = st.checkbox("Start") One of other possibilities, is to use st.session_state and storing the button’s state. I hope this helps. Best, Avra
0
streamlit
Using Streamlit
Download Plotly plot as html
https://discuss.streamlit.io/t/download-plotly-plot-as-html/4426
I would like to allow the user to download a plotly plot as a .html file. This is well supported by plotly. I can’t get it to work though. I am trying from io import StringIO, BytesIO import base64 import streamlit as st import plotly.express as px df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species") st.plotly_chart(fig) mybuff = StringIO() fig.write_html(mybuff, include_plotlyjs='cdn') mybuff = BytesIO(mybuff.read().encode('utf8')) href = f'<a href="data:file/txt;base64, {base64.b64encode(mybuff.read())}" download="plot.html">Downlo\ ad plot</a>' st.markdown(href, unsafe_allow_html=True) I confirm that fig.write_html("myplot.html") outputs the proper thing.
Solved! mybuff = StringIO() fig.write_html(mybuff, include_plotlyjs='cdn') mybuff = BytesIO(mybuff.getvalue().encode()) b64 = base64.b64encode(mybuff.read()).decode() href = f'<a href="data:text/html;charset=utf-8;base64, {b64}" download="plot.html">Download plot</a>' st.markdown(href, unsafe_allow_html=True) and the user gets a portable self-contained plotly plot!
1
streamlit
Using Streamlit
Form submit button does get latest values on click
https://discuss.streamlit.io/t/form-submit-button-does-get-latest-values-on-click/19558
I have a form and I want to submit its values on submit button click. However when I click on it, it will not pick up latest changes but previous values. If I do something like: if submitted: on_submit_click(**payload) it will get the latest values, however that re-renders the same annotation task which I don’t want. Ideally I want to render a next task after clicking submit. def on_submit_click(**kwargs): resp = send_update(**kwargs) st.success('Task submitted') def render_annotation_task(task_data: Dict): """ create a submit form with pre-filled values """ annotation_config = LABEL_CONF['annotation'] with st.form('annotation_task', clear_on_submit=True): st.video(str(PROJECT_DIR / task_data['local_path'])) title = st.text_input('title', value=task_data.get('title', "")) description = st.text_area('description', value=task_data.get('description', "")) language = st.selectbox('language', options=annotation_config['language'], index=_get_lang_index(annotation_config['language'], task_data.get('language', "ru"))) emoji = st.text_input('emoji', value=task_data.get('emoji', "")) tags = st.multiselect('tags', options=annotation_config['tags'], default=task_data.get('video_tags' ,[])) payload = dict(title=title, description=description, language=language, emoji=emoji, tags=tags, _id=task_data['_id'], verified=True) submitted = st.form_submit_button('Submit', on_click=on_submit_click, kwargs=payload)
Oh i’ve got to use session state in the callback section as described here: Add statefulness to apps - Streamlit Docs 4
1
streamlit
Using Streamlit
Couldn’t deploy the app, Please HELP
https://discuss.streamlit.io/t/couldnt-deploy-the-app-please-help/19539
Hi, I tried to deploy the app, but it stuck on the page “Your app is in the oven”. Here’s the repo of my project-- GitHub - yishan575757/lit2 5 Any help is appreciated, thank you in advance! Below are the logs [client] Provisioning machine... [client] Preparing system... [client] Spinning up manager process... [client] Inflating balloons... [client] Unpacking Comic Sans RAR files... [client] Loading "Under construction" GIF... [client] Compiling <blink> tags... [client] Initializing Java applet... [client] Please wait...
Hi @ylylyl, welcome to the Streamlit community! There was a bit of a hiccup last night, which I’m told is resolved by our engineers. Since this is resolved, I’ll mark it answered for now, but if this happens again please (continue) to let us know! Best, Randy
1
streamlit
Using Streamlit
Host Streamlit on Apache Webserver
https://discuss.streamlit.io/t/host-streamlit-on-apache-webserver/6479
I have a sample Streamlit Application to be hosted on Apache Webserver version 2.4. The application is hosted on default port 8501. I want that to be hosted on Apache Webserver which i have already installed. Since iam new to this Hosting Application topic, can somebody help me how do i setup using Apache webserver and what changes to do in Apache Webserver’s configuration file?
Hi @Harshith_Subramanya, welcome to the Streamlit community! We have a Streamlit Deployment Guide (wiki) 616 that has an entry for setting up Apache webserver, that might be a good place to get started. Best, Randy
0
streamlit
Using Streamlit
How to use Dlib with streamlit-webrtc ?!
https://discuss.streamlit.io/t/how-to-use-dlib-with-streamlit-webrtc/19582
any one can help me, how use dlib with streamlit-webrtc
Hi @AbdoShahat, welcome to the Streamlit community! It would be more helpful if you posted the code you already have, and what issues you’ve encountered, so that others can help. “How do I do this?” is a pretty broad question. Best, Randy
0
streamlit
Using Streamlit
Need help with threading in function (ibapi)
https://discuss.streamlit.io/t/need-help-with-threading-in-function-ibapi/19454
Hi, i try to use streamlit with the ibapi library to get some stock quotes. This is my function: def tws_hist(stock): class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) self.cols = ['date', 'open', 'high', 'low', 'close', 'volume'] self.df = pd.DataFrame(columns=self.cols) self.data = [] def historicalData(self, reqId:int, bar: BarData): self.data.append([bar.date, bar.open, bar.high, bar.low, bar.close, bar.volume]) def error(self, reqId, errorCode, errorString): print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString) def run_loop(): app.run() app = IBapi() today = dt.datetime.today().strftime("%Y%m%d %H:%M:%S") app.connect('127.0.0.1', 7496, 12) #Start the socket in a thread api_thread = threading.Thread(target=run_loop)#daemon=True) api_thread.start() time.sleep(1) #Sleep interval to allow time for connection to server #Create contract object contract = Contract() contract.symbol = stock contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' #Request Market Data app.reqMarketDataType(1) app.reqHistoricalData(1, contract, today, "6 M", "1 day", "TRADES", 0, 1, False, []) #time.sleep(1) #Sleep interval to allow time for incoming price data df = pd.DataFrame(app.data, columns=['Date', 'open', 'high', 'low', 'close', 'volume']) df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d') app.disconnect() return df How do I get the dataframe out of the function? At the moment it contains only the column names without values. Thank you
Any ideas?
0
streamlit
Using Streamlit
Don’t allow keyboard at st.selectbox()
https://discuss.streamlit.io/t/dont-allow-keyboard-at-st-selectbox/13365
Hello everyone! Is there any way to not allow keyboard insertion when open a selectbox() ? My list is in alphabetical order and considering that the app is made to use almost exclusively in mobiles when the keyboard is opened, it disturbs the user. Thank you!
Did you find a solution/hack for this problem? It is the only things stopping me to use Streamlit. Not usuable on mobile.
0
streamlit
Using Streamlit
How to let streamlit support table kinds inside pandas to show in explorer?
https://discuss.streamlit.io/t/how-to-let-streamlit-support-table-kinds-inside-pandas-to-show-in-explorer/19489
we can see that pandas has serial tables inside itself as below: image340×619 35.1 KB https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html?highlight=plot#pandas.DataFrame.plot I had tried, but the table will not showed in explorer, how can we make it?
Hi @BeyondMyself - If I’m not mistaken, those methods are built on matplotlib; have you tried calling st.pyplot() with the result of the function call? Best, Randy
0
streamlit
Using Streamlit
Annotated_text in Streamlit
https://discuss.streamlit.io/t/annotated-text-in-streamlit/9260
Hi, I am using the package st-annotated-text to highlight some words in texts on my streamlit app. However, I noticed that when the text is too long, the app shows a truncated text. Someone had the same problem ? Is there anyway to solve this problem ? Thanks, PyPI st-annotated-text 113 A simple component to display annotated text in Streamlit apps.
Hi @syo, welcome to the Streamlit community! @thiago wrote this package, maybe he has some suggestions. Tagging him here for the next time he comes to the forum. Best, Randy
0
streamlit
Using Streamlit
Annotations in header / in list, with Markdown and st-annotated-text
https://discuss.streamlit.io/t/annotations-in-header-in-list-with-markdown-and-st-annotated-text/12307
I’m using annotation from st-annotated-text and tried something like that: st.markdown("### " + text + str(annotation("apple", "fruit")), unsafe_allow_html=True) While the HTML seems perfectly fine, st.markdown struggled with parsing it (see image). What can I do? image1608×430 38.8 KB
Also, when using annotated_text it produces large, unreasonable margins (see image). annotated_text(("annotated", "adj", "#faa")) Is it possible to use annotations in a heading / in a list (possibly in conjunction with Markdown)? Can you help, @thiago, since you’re the maintainer of the project? image1570×505 9.15 KB
0
streamlit
Using Streamlit
How to show like a table: a data item and a button in one row
https://discuss.streamlit.io/t/how-to-show-like-a-table-a-data-item-and-a-button-in-one-row/19476
Please help! I hope to list some data items in a format as in each row, show a data (a job name) and a button. With clicking the button, the user can select to show the corresponding result. Tried to put buttons into a Dataframe but failed. Please kindly help address this UI function. Thanks a lot! Yongjin
You can use Streamlit columns instead, and put your text in one column and your button widgets in another.
0
streamlit
Using Streamlit
Reduce whitespace from Top of the page in Sidebar as well as place two elements next to each other
https://discuss.streamlit.io/t/reduce-whitespace-from-top-of-the-page-in-sidebar-as-well-as-place-two-elements-next-to-each-other/19495
image754×271 3.25 KB . Here is the code that i tried. import streamlit as st col1,col2=st.sidebar.columns([1,10]) with col1: st.write(‘Logo’) with col2: st.sidebar.markdown( Report- OCT’21 ,unsafe_allow_html=True). Appreciate if i can have a solution
try to add this to your code st.markdown( f''' <style> .reportview-container .sidebar-content {{ padding-top: {1}rem; }} .reportview-container .main .block-container {{ padding-top: {1}rem; }} </style> ''',unsafe_allow_html=True)
0
streamlit
Using Streamlit
State Management on custom components
https://discuss.streamlit.io/t/state-management-on-custom-components/19362
I was thinking about state management when using custom components. I have uploaded a gist 1 with a sample app that uses ace editor to edit, validate and download an yaml file. The problem is that when the component key is not fixed, the compoenent reloads between page refreshs causing a bad user experience Video 4. With fixed keys this doesn’t happen. This issue is not related only to ace editor, I noticed the same happen with streamlit-aggrid or any custom component that holds state. In my projects I’m fixing the keys using a random value stored in session_state and changing this value whenever I need the compoenent to reset. One use case is when I want to clear the file uploaded in file_upload component after processing. Have anyone faced the same situation? Any other ideas on how to manage that? Pablo
I encountered the same problem and gave it up. My streamlit-webrtc component defines its key argument as a required, non-optional argument. github.com whitphx/streamlit-webrtc/blob/5376edd28239ad44ed96de712c90daab928d371c/streamlit_webrtc/component.py#L185 def generate_frontend_component_key(original_key: str) -> str: return ( original_key + r':frontend 6)r])0Gea7e#2E#{y^i*_UzwU"@RJP<z' ) # Random string to avoid conflicts. # XXX: Any other cleaner way to ensure the key does not conflict? @overload def webrtc_streamer( key: str, mode: WebRtcMode = WebRtcMode.SENDRECV, rtc_configuration: Optional[Union[Dict, RTCConfiguration]] = None, media_stream_constraints: Optional[Union[Dict, MediaStreamConstraints]] = None, desired_playing_state: Optional[bool] = None, player_factory: Optional[MediaPlayerFactory] = None, in_recorder_factory: Optional[MediaRecorderFactory] = None, out_recorder_factory: Optional[MediaRecorderFactory] = None, video_processor_factory: None = None, audio_processor_factory: None = None, async_processing: bool = True, I think it’s unavoidable with the current Streamlit mechanism which tracks the identity of each component instance by checking its arguments unless key is provided. In such cases, when the input changes, Streamlit considers the component identity has changed and re-renders the component.
0
streamlit
Using Streamlit
St.form showing old results even when input is cleared. 2nd form is updating based on input in 1st form
https://discuss.streamlit.io/t/st-form-showing-old-results-even-when-input-is-cleared-2nd-form-is-updating-based-on-input-in-1st-form/16591
Hi, I have a function that recommends 3 random but similar cities, based on an input of the users current city. And another function that recommends 3 random, non-similar cities. I am using st.form, st.text_input and submit_button for each function. I am new to Streamlit and have 2 problems: When clearing out the input city, the results from the previous input still remain. Even when refreshing the page. Is there are way for the form to reset after the input is cleared out? When submitting an input for my first st.form (similar city), the 2nd st.form (non-similar city) populates based on the input in the first form. And vice versa. This is the code I am using to put my function on streamlit: #take user city as input with st.form(key=‘my_cities’): my_city = st.text_input(label=“Enter your current city (City, Country):”) submit_button = st.form_submit_button(label=‘Get my next living destination!’) similar_city_recommendations(city_country = my_city) image724×638 10 KB I would like the results to clear once the text box is cleared. I am making a demo video and I can’t have the previous results shown in the demo. Again, both forms update based on input from just 1 form. Any guidance would be appreciated!! Using Streamlit version 0.87.0 and python version 3.8.8
Just signed up but I think the clear_on_submit = True should work for this issue. docs.streamlit.io st.form - Streamlit Docs 5
0
streamlit
Using Streamlit
Hiw to print latex equation in png format
https://discuss.streamlit.io/t/hiw-to-print-latex-equation-in-png-format/19038
How to print st.latex in png format
Welcome to the Streamlit community @Harshal_Thulkar! Given Streamlit’s focus on helping people create web apps, we render the latex equations using a JavaScript library. What is your aim for having a PNG? Best, Randy
0
streamlit
Using Streamlit
My streamlit app keep showing connecting
https://discuss.streamlit.io/t/my-streamlit-app-keep-showing-connecting/17787
My streamlit app kept showing connecting after deployment without loading the content of the page. what could be the reason for this. The app works fine on my local I am running streamlit on my laptop Streamlit, version 0.89.0 Python, version 3.9.7 windows 10 I have taken the below step but still not able to solve the issue. Deployed app to streamlit cloud and heroku tried various versions of streamlit 0.8.0 to 1.0.0 link to my repo app link new11329×617 18.2 KB The app works fine on my local new21350×623 32.2 KB @andfanilo , @asehmi , @thiago , @snehankekre
I think the fault is from my chrome browser. I just tried another browser and it displayed my app
1
streamlit
Using Streamlit
St-annotated-text is out of maintence?
https://discuss.streamlit.io/t/st-annotated-text-is-out-of-maintence/16852
pip install st-annotated-text is not work any more, we can not download this package @Thiago Teixeira
@thiago I had solved this problem. to solve this problem, step1: I have to download htbuilder from here: https://github.com/tvst/htbuilder 1 and overwrite the line 3 into: with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() in the htbuilder directory, run python setup.py install step2: download st-annotated-text from github: GitHub - tvst/st-annotated-text: A simple component to display annotated text in Streamlit apps. also need to overwrite the line 3 in setup.py with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() in the st-annotated-text directory, run python setup.py install finally, I can run the st-annotated-text app import streamlit as st from annotated_text import annotated_text, annotation annotated_text( "I ", ("Love", "", "#8ef"), " our ", ("Great", "", "#faa"), ("and", "", "#afa"), " Useful ", ("Streamlit", "", "#fea"), ("Community", "", "#8ef"), ("!", "", "#afa"), ) image960×311 17.6 KB Is it possible to cancel the second argument in annotated_text function like this? annotated_text( "I ", ("Love","#8ef"), " our ", ("Great", "#faa"), ("and", "#afa"), " Useful ", ("Streamlit", "#fea"), ("Community", "#8ef"), ("!", "#afa"), )
1
streamlit
Using Streamlit
SessionState, selectbox, avoid rerun
https://discuss.streamlit.io/t/sessionstate-selectbox-avoid-rerun/19460
Dear all, I got inspired by this post python 3.x - Script rerun when i change selectbox in Streamlit - Stack Overflow 3 , trying to do the following: I have 2 selectbox located in 2 different columns. Once I click on ‘Calculate’, the selectbox in column 1 gets overriden by a certain value. But I would like my script not to reset this value (rerun) and replace it by a new selectbox, when I use the other selectbox located in column 2 … I didn’t manage to avoid the streamlit rerun when using the second selectbox after I clicked on ‘Calculate’. I’m having hard time using SessionState. This is my code: import streamlit as st import pandas as pd import SessionState df = pd.DataFrame({‘name’: [‘steve’, ‘joe’, ‘paul’], ‘position’: [1, 2, 3]}) with st.sidebar.form(“my_form”): calculate = st.form_submit_button(‘Calculate’) session_state = SessionState.get(col1=False, col2=False) col1, col2 = st.columns(2) placeholder = placeholder = col1.empty() col1_one = placeholder.selectbox(‘box1’, df[‘name’].unique()) col2_one = col2.selectbox(‘box2’, df[‘name’].unique()) if col1_one or session_state.col1: session_state.col1 = True session_state.col2 = False col1.write(col1_one) if col2_one or session_state.col2: session_state.col1 = False session_state.col2 = True col2.write(col2_one) if calculate: st.sidebar.write(‘Algo is running’) placeholder.write(‘overriden value’) session_state.col1 = False session_state.col2 = True
Any thoughts about this ? SessionState is really a great tool, but not easy to handle.
0
streamlit
Using Streamlit
FileNotFoundError on streamlit’s app online but not in local
https://discuss.streamlit.io/t/filenotfounderror-on-streamlits-app-online-but-not-in-local/19479
Hey, I am trying to deploy my first little app. In same directory of the app i have a data directory with some csv file. When I click on link I have error : FileNotFoundError: [Errno 2] No such file or directory: ‘data/file.csv’ But in local there are functioning so I don’t understand how can I connect the data to my app the error are in this part of code: “”" Championshipchoice = st.sidebar.selectbox(“which Championship do you want ?”,(“Tirs_Bundesliga.csv”,“Tirs_PL.csv”,“Tirs_liga.csv”,“Tirs_SerieA.csv”,“Tirs_L1.csv”) ) choice = “data/” + Championshipchoice TableChoice = pd.read_csv(choice) “”" So pd.read_csv function don’t find files. I verifying all libraries are in requirements.txt files.
You will probably need to add a path before each filename. Example ./data directory/filename
0
streamlit
Using Streamlit
How to add records to a dataframe using python and streamlit
https://discuss.streamlit.io/t/how-to-add-records-to-a-dataframe-using-python-and-streamlit/19164
I have a python code that allow user to read dataframe and add new records by enter data in the text input and on the click event the system append the new record to the datafarme The problem is that when user click on the add button the system add the values in new column where each value is a considerate as new record. while what i want is to consider all entered value are in the same record on different columns. 2 code: import pandas as pd import streamlit as st df = pd.read_csv(iris.csv) num_new_rows = st.sidebar.number_input("Add Rows",1,50) with st.form(key='add_record_form',clear_on_submit= True): st.subheader("Add Record") ncol = len(df.columns) cols = st.columns(int(ncol)) for i, x in enumerate(cols): for j, y in enumerate(range(int(num_new_rows))): records_val = x.text_input(f"{df.columns[i]}", key=j) records_val_list.append(records_val) newrow = pd.DataFrame(records_val_list) if st.form_submit_button("Add"): df = pd.concat([newrow,df],ignore_index=True) st.write(df)
You could use: df.loc[len(df.index)] = [“df col heading1”, “df col heading2”…]
0
streamlit
Using Streamlit
Web Geolocation API to Get User’s Location
https://discuss.streamlit.io/t/web-geolocation-api-to-get-users-location/9493
Hi, Is there a way to use, or a plan to implement the web Geolocation API 9 for asking the user’s location and continue processing based on that? Thanks
Hey @aghasemi , Yep, just use streamlit-bokeh-events with this bunch of code and it works pretty well github.com ash2shukla/streamlit-bokeh-events/blob/master/example/custom_js.py 50 import streamlit as st from bokeh.models.widgets import Button from bokeh.models import CustomJS from streamlit_bokeh_events import streamlit_bokeh_events loc_button = Button(label="Get Location") loc_button.js_on_event("button_click", CustomJS(code=""" navigator.geolocation.getCurrentPosition( (loc) => { document.dispatchEvent(new CustomEvent("GET_LOCATION", {detail: {lat: loc.coords.latitude, lon: loc.coords.longitude}})) } ) """)) result = streamlit_bokeh_events( loc_button, events="GET_LOCATION", key="get_location", refresh_on_update=False, override_height=75, debounce_time=0) This file has been truncated. show original PS. you can execute any custom js this way on a event and get the value in the callback without writting a full component Hope it helps !
1
streamlit
Using Streamlit
Interactively editable data table in streamlit
https://discuss.streamlit.io/t/interactively-editable-data-table-in-streamlit/5200
Hi everyone, firstly I would like to say that Streamlit is great. For my application, through streamlit I am trying to import an excel file as a data table and trying to make it interactively editable. Is there any way through which I can make the data table editable interactively? If not, is there any workaround for it? Any suggestions/ comments are very much appreciated. Thank you
Hey I think the use case is great! Right now I think there’s no direct way of doing it with streamlit. However, it’d be interesting to create a new Streamlit component using this react component https://nadbm.github.io/react-datasheet/ 305 If that works, I imagine you can load your excel using Pandas and send it to the component as a Json object and work with it interactively. Here’s the doc for creating new components https://docs.streamlit.io/en/stable/streamlit_components.html 238 Let me know if that helps!
0
streamlit
Using Streamlit
Altair time transforms are off?
https://discuss.streamlit.io/t/altair-time-transforms-are-off/19453
I am getting wait times across a variety of geographic locations. The times are stored in a mongodb collection as a UTC timestamp, and when it comes time to present them, I convert them to local time. The dataframes come out ok, as in the data makes sense. However, the graphs seem offset by 2 hours. Example of the graph I am illustrating image1010×836 28.8 KB Example of the dataframe that feeds it: image1082×490 61.5 KB Specific example of the offset error: image1054×1283 78.7 KB My code: hist = pd.DataFrame(mongo_queries.get_hist_data(f)) # get the data hist['local_time'] = hist.apply(get_local,axis=1) # convert UTC to local time alt_color = {'Maximum':'max(wait):Q', 'Average':'average(wait):Q','Median':'median(wait):Q'} hist st.write('### Schedule View') scatter = alt.Chart(hist).mark_rect().encode( alt.Y('hours(local_time):O', title='hour of day',), alt.X('day(local_time):O', title='Weekday'), alt.Tooltip(['hours(local_time):O','day(local_time):O',alt_color[metric]]), color=alt_color[metric], ).interactive() st.altair_chart(scatter, use_container_width=True) As you can see in the data, you would expect that the latest times (within the 7th hour AM) would bin together and average to 17.75. The average is correct, but it is being illustrated on the 9AM block… After some googling it seemed that the date format was causing this issue, so I converted the local_time column to an ISOFORMAT which was apparently the fix, but it is not fixing it. Upon further investigation, it seems that altair is converting it to MY local time, regardless. I put the UTC time as the input to the graph(alt.Y and alt.X above) and its still binning them to the 9th hour, which is what I am in currently… I guess the question is, how do I stop Altair(I think that's the culprit) from converting times and letting them be on the specified local times. I am expecting each location to follow the same generic trends throughout the day, respective of their local times. With locations across the continent, if they are all mashed together in my timezone, it’s not going to work… Another weird thing is, my UTC time seems to be the right time, but the wrong timezone offset. The local time is correct. I am confused… image1126×334 45.2 KB
More info: the data is stored as a utc, here’s a screenshot from mongo compass: I loaded up the same data in a notebook, and it doesn’t seem to come with my local timezone, so maybe it is a streamlit dataframe issue? image855×766 56.4 KB
0
streamlit
Using Streamlit
Disable opacity?
https://discuss.streamlit.io/t/disable-opacity/10345
Hi! Is there a way to disable the Opacity going down when the script is runnig? I’ve changed the CSS of the app, so now I have a custom CSS, but when the widgets are changing, most of the app changes into low opacity, untill they are done running. Is there a way to disable this behavior? Thanks!
Any solution from anyone?
0
streamlit
Using Streamlit
Selectable Image Grid for Data Explorer Application
https://discuss.streamlit.io/t/selectable-image-grid-for-data-explorer-application/19442
Hi, I am working on a image based data explorer and want to show the images in a grid like layout with filters in side bar, so user can apply filters and traverse through images and select one/multiple images by clicking on them. I tried to show images with st.columns() but also want to implement selection of images. Based on selected images, I need to create a list of them to process further so would need some ID also for each image. I am new to streamlit so I may not aware of all functionalities/features, kindly suggest a way to achieve above requirements. Thanks in advance!!
See if these 2 links help: Grid of images with the same height? Using Streamlit Hi! I’m working on a book recommendation system based on a LDA model and want to show the book options on one page. Right now I’m using st.image() and passing the list of images which comes from a column in the dataframe, and it looks like this: st.image(filteredImages, width=150, caption=caption) [Screen Shot 2021-03-10 at 1.13.59 PM] I’m able to set the width but not the height, so all of them have different heights. I tried using the pillow library to resize each image but the run time in… PyPI streamlit-imagegrid 5 Streamlit imagegrid
0
streamlit
Using Streamlit
Center button st.button
https://discuss.streamlit.io/t/center-button-st-button/9751
How to center the button ? thanks
Thanks @Marisa_Smith. It’s really useful to me. Just putting it in a way easier to copy import streamlit as st import cv2 img = cv2.imread('photo.jpeg') st.image(img, use_column_width=True, caption='Random image for sizing') st.title("Off center :(") col1, col2, col3 = st.beta_columns([1,1,1]) col2.title("Centered! :)") col2.image(img, use_column_width=True) Screenshot 74
1
streamlit
Using Streamlit
How do i hide/ remove the menu in production?
https://discuss.streamlit.io/t/how-do-i-hide-remove-the-menu-in-production/362
Hi I would like to be able to remove the menu bar when shipping to production. Is that possible? I would think it natural to remove. The user does not need to understand that this is a Streamlit app as far as I can see. Maybe they would still need to be able to recalculate? Or clear the cache? But so far I only see the use case for that in development. Thanks
Or even better. At some stage someone would ask for a menu for navigation. Could the existing menu be extended to that so that I as a developer i could configure which of the existing items to enable and disable. Add my own items that if clicked would trigger an update enable a tree structure of subitems of items. choose between the existing minimized layout or a maximized, expanded top menubar layout ?
0
streamlit
Using Streamlit
Image read error
https://discuss.streamlit.io/t/image-read-error/19396
I need to load an image as a numpy array, manipulate it and display the results. But it doesn’t work. Displaying static image like below works st.image('./data/gallery/AI_generated_meal.jpg') However, when I try to have an image in a variable, and then display it, it raises an error ‘OSError: encoder error -2 when writing image file’. I tried reading with PIL, skimage, cv2, matplotlib… Streamlit version 1.2.0 Tried both already existed file and st.file_uploader() Tried launching with sudo as well. Some samples of non-working code: img = cv2.imread('./data/gallery/AI_generated_meal.jpg') st.image(img) img = np.array(Image.open('./data/gallery/AI_generated_meal.jpg')).astype(np.float64) st.image(img) img = np.array(plt.imread('./data/gallery/AI_generated_meal.jpg')) st.image(img) Full Traceback: OSError: encoder error -2 when writing image file Traceback: File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/script_runner.py", line 354, in _run_script exec(code, module.__dict__) File "/home/sergey/Projects/streamlit-image-editor/main.py", line 32, in <module> st.image(img) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/elements/image.py", line 128, in image output_format, File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/elements/image.py", line 371, in marshall_images image, width, clamp, channels, output_format, image_id File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/elements/image.py", line 272, in image_to_url data = _np_array_to_bytes(data, output_format=output_format) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/elements/image.py", line 181, in _np_array_to_bytes return _PIL_to_bytes(img, format) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/streamlit/elements/image.py", line 167, in _PIL_to_bytes image.save(tmp, format=format, quality=quality) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/PIL/Image.py", line 2240, in save save_handler(self, fp, filename) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/PIL/JpegImagePlugin.py", line 782, in _save ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)], bufsize) File "/home/sergey/Projects/streamlit-image-editor/venv/lib/python3.7/site-packages/PIL/ImageFile.py", line 523, in _save raise OSError(f"encoder error {s} when writing image file") from exc I also noticed that using st.write(img) I get [[[0 0 0] [0 0 0] [0 0 0] ... [0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0] ... While the same code in jupyter notebook works properly [[[255, 255, 255], [255, 255, 255], [255, 255, 255], ..., [218, 222, 223], [218, 222, 223], [218, 222, 223]], [[255, 255, 255], [255, 255, 255], [255, 255, 255], ..., [218, 222, 223], [218, 222, 223], [218, 222, 223]], [[255, 255, 255], [255, 255, 255], [255, 255, 255], ..., [218, 222, 223], [218, 222, 223], [218, 222, 223]], ...,
So, downgrading to version 1.0.0 works. I didn’t find other solution
0
streamlit
Using Streamlit
Caching Sqlite DB connection resulting in glitchy rendering of the page
https://discuss.streamlit.io/t/caching-sqlite-db-connection-resulting-in-glitchy-rendering-of-the-page/19017
Hello, I am trying to build a multipage app. I have a login page and one other page that is accessible only after a valid user logs in. I am using sqlite db for authentication. Without caching the sqlite db connection, the login page renders seamlessly. However, on caching the db connection, I notice glitchy rendering only on the very first interaction with all the widgets. It gets stable from the second time onwards. The code is as follows: app.py import streamlit as st from page import login_page, species_search_page from auth import init_db def app_title(): st.title("Multipage App") st.write("An Experimental Multipage App") def main(): init_db() app_title() menu = ['Login', 'Species Search'] menu_selection = st.sidebar.radio("Menu", menu, key='menu_selection') if menu_selection == 'Login': if 'login' not in st.session_state or not st.session_state['login']: login_page() elif 'login' in st.session_state and st.session_state['login']: st.success( f"\n You are successfully logged in as user '{st.session_state.username}'") elif menu_selection == 'Species Search': if 'login' in st.session_state and st.session_state['login']: species_search_page() else: st.warning("\n Please Login before you proceed \n") if __name__ == "__main__": main() page.py import streamlit as st from callback import login_callback def login_page(): login = st.container() with login: st.subheader("Login") username = st.text_input("Username") password = st.text_input("Password", type="password") st.button("Login", on_click=login_callback, args=(login, username, password,)) def species_search_page(): return callback.py import streamlit as st from auth import is_valid_user def login_callback(placeholder, username, password): if is_valid_user(username, password): st.session_state['username'] = username st.session_state['password'] = password st.session_state['login'] = True else: placeholder.error("Please Enter Valid Username and Password") auth.py import sqlite3 from config import URI_SQLITE_DB, ADMIN_USERNAME, ADMIN_PWD, USERS_TABLE import streamlit as st # @st.cache(allow_output_mutation=True) def get_connection(path: str): conn = sqlite3.connect(path, check_same_thread=False) # st.session_state.sqlite_conn = conn return conn def init_db(): conn = get_connection(URI_SQLITE_DB) conn.execute( f"""CREATE TABLE IF NOT EXISTS {USERS_TABLE} ( USERNAME TEXT, PASSWORD TEXT, IS_ADMIN INTEGER );""" ) cur = conn.execute("SELECT * FROM USERS WHERE USERNAME = ? AND PASSWORD = ?", (ADMIN_USERNAME, ADMIN_PWD)) if cur.fetchone() == None: conn.execute( f"INSERT INTO {USERS_TABLE} VALUES (?, ?, ?)", (ADMIN_USERNAME, ADMIN_PWD, 1)) conn.commit() conn.close() def is_valid_user(username, password): conn = get_connection(URI_SQLITE_DB) # conn = st.session_state.sqlite_conn cur = conn.execute(f"SELECT * FROM {USERS_TABLE} WHERE USERNAME = ? AND PASSWORD = ?", (username, password)) if cur.fetchone() == None: return False else: return True conn.close() config.py URI_SQLITE_DB = "auth.db" ADMIN_USERNAME = "admin" ADMIN_PWD = "admin" USERS_TABLE = "USERS" With Caching: Without: Tried storing the db connection in the session state and used it in the is_user_valid function instead of doing a cache hit, and even that seems to work fine. But I wonder which is the best practice. Appreciate any help!
Hey @puzzled-cognition, So I tried out snippets of your code and I was having that double button push error whether or not I was using @st.experimental_singleton. I suspected this was due to some funny interaction between using the callback function and using the return values of the text inputs and not storing them in state themselves. I edited your code and now I have this working seamlessly on my machine. upgrade streamlit >=1.1.0 I changed your login to be a form, that way the script only runs when you hit the submit button and not as you enter each values into the text_inputs I changed the logic around the login key:value pair in session state 'login' not in st.session_state and not st.session_state['login'] are the same thing, so I removed the duplicates of each (just 2 different ways of accessing the key login from session state) added returns to all of the functions you made, its best practice and you want to make sure that you explicitly tell python to always return to the main function import streamlit as st import time # this is the function to connect with the database since I am not # connecting i just put a progress bar here and a time delay to mimick that @st.experimental_singleton(suppress_st_warning=True) def init_db(): start_up = st.empty() with start_up: bar = st.progress(0) for complete in range(100): time.sleep(0.01) bar.progress(complete+1) start_up.empty() return def app_title(): st.title("Multipage App") st.write("An Experimental Multipage App") return # turned this into a form to keep your script from running without actually # pressing the "login" button. Because I added a form user and pass will only # be put in the state one time (when the form returns True), so when the user # logs in with the correct password I transfer these values to your username # and password, as well as setting login to True def login_page(): st.subheader("Login") login = st.form("enter_form") with login: username = st.text_input("Username", key="user") password = st.text_input("Password", key="pass") st.form_submit_button("Login", on_click=login_callback) return # i removed your function call in a callback, the things you were doing # in them seemed simple and sort enough that having to move to # another python module to see the code seemed more work than its worth def login_callback(): # me mimicking opening the connection to your DB and checking the credentials if (st.session_state.user == "me")and(st.session_state["pass"] =="123"): st.session_state["login"] = True st.session_state.username = st.session_state.user #assign to diff key st.session_state.password = st.session_state["pass"] elif (st.session_state.user == "me")and(st.session_state["pass"] !="123"): st.error("Wrong Password") elif (st.session_state.user != "me")and(st.session_state["pass"] =="123"): st.error("Wrong username") else: st.error("Incorrect login info") return def species_search_page(): return def main(): init_db() app_title() menu = ['Login', 'Species Search'] menu_selection = st.sidebar.radio("Menu", menu, key='menu_selection') # best practice is to add your key value pairs to session state and then work from there if menu_selection == 'Login': if 'login' not in st.session_state: st.session_state.login = False #shortened this to use only one condition as mentioned above if not st.session_state.login: login_page() else: st.success( f"\n You are successfully logged in as user '{st.session_state.username}'") elif menu_selection == 'Species Search': if 'login' in st.session_state: species_search_page() else: st.warning("\n Please Login before you proceed \n") if __name__ == "__main__": main() Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
How can I clear a specific cache only?
https://discuss.streamlit.io/t/how-can-i-clear-a-specific-cache-only/1963
I run a script with a few caches. When I use the following code it clears all the caches: from streamlit import caching caching.clear_cache() I would like to clear only a specific cache. How can I do this?
Hey @theletz, welcome to Streamlit! This isn’t currently (easily) doable. Can you give some context for what you’re trying to achieve? We have some caching improvements in the pipeline, but it may also be the case that there’s an easier workaround for your use case. Thanks!
0
streamlit
Using Streamlit
Download PDF option
https://discuss.streamlit.io/t/download-pdf-option/19386
Hi Community, I am trying to create a download option for a pdf file for the end-user. The goal is to enable the user to download the PDF file that is located in the same server where the app is hosted. I am able to download the file, but the file is not opening after download. The PDFs size varies between 6-12 pages here. I have tweaked the code a bit from this post 3. Please help. import streamlit as st from fpdf import FPDF import base64 def create_download_link(val, filename): b64 = base64.b64encode(val) hreflink = f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}.pdf">Download file</a>' return hreflink def main(): menu = ["Home", "PDF", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": pass if choice == "PDF": with open("dummy2.pdf", "rb") as pdf_file: PDFbyteText = base64.b64encode(pdf_file.read()) export_as_pdf = st.button("Export Report") st.text(type(PDFbyteText)) if export_as_pdf: html = create_download_link(PDFbyteText, "test") st.markdown(html, unsafe_allow_html=True) if choice == "About": pass if __name__ == '__main__': main() Upon opening the downloaded PDF, it throws the below error: error1337×572 14.7 KB
Hello @cs.sabya There is an official Download Button 8, did you try to use it with the pdf_file variable? Have a nice day, Fanilo
1
streamlit
Using Streamlit
URGENT : store a table in a database
https://discuss.streamlit.io/t/urgent-store-a-table-in-a-database/19358
Hello guys , I want to save this table into a database , how to do that please ? @st.cache(allow_output_mutation=True) def Input_Parameters(): return X1 = st.number_input(’ X1’, min_value = 0, max_value =10 , step = 1) X2 = st.number_input(‘X2’, min_value = 0 , max_value = 10 , step = 1) X3= st.number_input(‘X3’, min_value = 0, max_value = 10 , step = 1) if start_bot: Input_Parameters().append( {"X1":X1, "Y1":Y1, "Z1":Z1 } ) st.table(Input_Parameters()) I want the table stored in a database , Thanks for your help
I never understand why I never get any answers
0