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
Change the display position of an html file on a webpage in Streamlit
https://discuss.streamlit.io/t/change-the-display-position-of-an-html-file-on-a-webpage-in-streamlit/7779
I am using Streamlit to build an app. I have no front-end experience or expertise. I have an use case where I want to display a sample pdf file on the left hand side and an html file having a sample extraction from the pdf on the right hand side. Presently it’s coming one below the other. My html file reads like this: <body style="background-color:White ;"> <div class="ui form"> <div class="fields"> <div class="field"> <label>Student Name</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size="63" placeholder="Roger"> <p> </div> <div class="field"> <label>Branch</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size='15' placeholder="Section B"> <p> </div> <div class="field"> <div class="field"> <label>Subject</label> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size='15' placeholder="Physics"> <p> </div> <div class="field"> <label>Grade</label> &nbsp;&nbsp;&nbsp;&nbsp;<input type="text" size='15' placeholder="A"> <p> </div> and my code reads like: import streamlit as st import streamlit.components.v1 as components import base64 st.header("test html import") HtmlFile = open("test.html", 'r', encoding='utf-8') source_code = HtmlFile.read() print(source_code) components.html(source_code, height= 1600, width=1600) with open("Datafile.pdf", "rb") as pdf_file: base64_pdf = base64.b64encode(pdf_file.read()).decode('utf-8') pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf">' st.markdown(pdf_display, unsafe_allow_html=True) I just want to display the 2 things(pdf&html) side by side. Any help on how to solve this?
Hi @Myntur, For future reference, @chris_klose has provided a solutione here: Are you using HTML in Markdown? Tell us why! Using Streamlit Hey @Myntur, I recommand to read this blogpost: New layout options for Streamlit Simply do: col1, col2 = st.beta_columns(2) Then you can put the contents into the cols. Something like: col1.image(pdf) col2.write(extraction) Something like (totally untested! Hope it can get you started ): c_left, c_right = st.beta_columns(2) with c_left: HtmlFile = open("test.html", 'r', encoding='utf-8') source_code = HtmlFile.read() print(source_code) components.html(source_code, height= 1600, width=1600) with c_right: with open("Datafile.pdf", "rb") as pdf_file: base64_pdf = base64.b64encode(pdf_file.read()).decode('utf-8') pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" width="700" height="1000" type="application/pdf">' st.markdown(pdf_display, unsafe_allow_html=True) Best, Fanilo
1
streamlit
Using Streamlit
“Failed to load resource” when using components.html
https://discuss.streamlit.io/t/failed-to-load-resource-when-using-components-html/20628
I’m trying to use components.html to load a local HTML file, but including CSS and JavaScript files in it throws an error “Failed to load resource: the server responded with a status of 404 (Not Found)” as it’s trying to access “http://localhost:8501/bootstrap.min.css” instead of the bootstrap.min.css in the local folder. Any idea how to solve this? On a side note, is there any way to use bi-directional components without React or TypeScript? Or is rewriting an HTML site to those formats the only way?
Hello @somedood , welcome to the community somedood: “Failed to load resource: the server responded with a status of 404 (Not Found)” as it’s trying to access “http://localhost:8501/bootstrap.min.css” instead of the bootstrap.min.css in the local folder. Any idea how to solve this? Can you put the code snippet you are using?I would rather refer to bootstrap not on your local machine but on a remote CDN like in the following. import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <div id="accordion"> <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Collapsible Group Item #1 </button> </h5> </div> <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #1 content </div> </div> </div> <div class="card"> <div class="card-header" id="headingTwo"> <h5 class="mb-0"> <button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Collapsible Group Item #2 </button> </h5> </div> <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordion"> <div class="card-body"> Collapsible Group Item #2 content </div> </div> </div> </div> """, height=600, ) somedood: On a side note, is there any way to use bi-directional components without React or TypeScript? Or is rewriting an HTML site to those formats the only way? Have a look at: Code snippet: create Components without any frontend tooling (no React, Babel, Webpack, etc) For the following you will need npm though to install JS packages: Reactless Component Template Streamlit quick & dirty Leaflet component that sends back coordinates on map click (github.com) Have a nice day, Fanilo
0
streamlit
Using Streamlit
How to show audio player when point on interactive plot is clicked?
https://discuss.streamlit.io/t/how-to-show-audio-player-when-point-on-interactive-plot-is-clicked/20664
click-and-show-player2955×1608 217 KB Hi! I’m trying to implement the above diagram in Streamlit. Each point on the graph represents an audio file and I would like to hear each audio file in order to do EDA. Any suggestions regarding how I can do this?
Hi @ssakhavi, This is not possible natively in Streamlit, but we have a couple of community members that made components that can (I believe): by @Bright: St_echarts_events, a new method to get the echarts-chart return value from the front-end event Show the Community! Hi, I just made a component that can easily access the echarts chart , receive the value returned from the front-end event., such as the x-axis and y-axis values returned in the click event. [Video_2021-12-06_163114] Source code in github Here is the doc. Streamlit Echarts Events a bi-directional streamlit components with pyecharts plots return event value from js-side to python-side。if no events designed, just display a chart. Installation pip install streamlit-ehcarts-events Usa… and another for vega, vega-light and Altair: GitHub GitHub - domoritz/streamlit-vega-lite: A Streamlit component to render... 1 A Streamlit component to render interactive Vega, Vega-Lite, and Altair visualizations and access the selected data from Python - GitHub - domoritz/streamlit-vega-lite: A Streamlit component to ren... Edit Looks like I missed a couple of components that do this for other libraries: (thanks to @andfanilo for pointing them out to me) @ash2shukla’s Brokeh: Component for bi-directional communication with bokeh Show the Community! I was working on a ML project with streamlit and I absolutely love it ! But one major drawback I found was that there’s literally no possible way/workaround to have bi-directional communication with bokeh graphs. It becomes really a bottleneck when you are dealing with geo-data and you want the user to draw a polygon or something and process the selected data. I came across this issue last night and have managed to put together a component that does just that, its far from optimal solution and j… @null-jones plotly one: Bi-directional Plotly Component Show the Community! Hey folks! I needed plot interactivity for a project, so I’ve put together a simple component that sends Plotly events back to Streamlit! Obviously this repo is pretty early-on, but I thought I’d make a post about it. Currently you can configure the component to send back click, select, and hover events for plotly. Some of the features I hope to implement are: Automatic layer generation to change the cursor to a pointer (to help indicate it’s clickable) (https://codepen.io/destrada/pen/p… @andfanilo’s echarts one does this as well: Streamlit-echarts Show the Community! Hello all ! EDIT : source repo https://github.com/andfanilo/streamlit-echarts Are there people familiar with echarts here ? I’m not very familiar with echarts myself and documentation can be daunting sometimes…so I’d like you to test the streamlit-echarts package. [demo] # you need to be in an environment with Streamlit custom components pip install streamlit-echarts streamlit run app.py with some sample files in the examples folder of the project https://github.com/andfanilo/streamlit-ech… Catch mouse events on ECharts plots in Streamlit | Introducing streamlit-echarts 0.4.0 Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Handling Session State with Streamlit_Option_Menu custom component
https://discuss.streamlit.io/t/handling-session-state-with-streamlit-option-menu-custom-component/20661
Hello, I have been banging my head against a wall trying to figure out how to keep a variable in session_state while using the streamlit_option_menu custom component (GitHub - victoryhb/streamlit-option-menu). Here is some sample code: import streamlit as st from streamlit_option_menu import option_menu with st.sidebar: selected = option_menu("Menu", ['Home', 'Text Analysis'], menu_icon="cast", default_index=0) if selected == 'Home': choice = st.radio('Choose an option:', ['A', 'B']) if choice == 'A': text = st.text_area('Enter Text:') submit1 = st.button('Submit Text') if submit1: if 'text' not in st.session_state: ## Here I am intializing the variable to '' st.session_state.text = '' st.session_state.text = text ## And here I am trying to assign the text from the text_area to the variable if selected == 'Text Analysis': submit2 = st.button('Test') if submit2: print(st.session_state.text) When the script is running, I enter text in the st.text_area and then hit the submit1 button things seem fine as long as I stay on the ‘Home’ menu option. If I go to “Text Analysis” menu option and click the submit2 button I get an error that “st.session_state.text is undefined”. I assume what is happening is that the st.session_state.text = text assignment is not carrying over from the “Home” tab to the “Text Analysis” tab, and Im not sure why that is. Any ideas or suggestions are greatly appreciated – thanks!!!
HI @Buckeyes2019, This is because you have nested the initialization of your variable inside the logic of your code. That is, your user has to select home before text_analysis for the script to initialize it in state. In practice, whenever I am initializing variables in state, I separate these away from the other code and logic in my app. That way I am sure that all the variables I want to use in the session_state of my app are initialized regardless of when and where I use them. import streamlit as st from streamlit_option_menu import option_menu # initialize ALL state variables: if 'text' not in st.session_state: st.session_state.text = "" with st.sidebar: selected = option_menu("Menu", ['Home', 'Text Analysis'], menu_icon="cast", default_index=0) if selected == 'Home': choice = st.radio('Choose an option:', ['A', 'B']) if choice == 'A': text = st.text_area('Enter Text:') submit1 = st.button('Submit Text') if submit1: st.session_state.text = text if selected == 'Text Analysis': submit2 = st.button('Test') if submit2: print(st.session_state.text) Give this a try and let me know! Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Update 3d scatter plot without resetting view
https://discuss.streamlit.io/t/update-3d-scatter-plot-without-resetting-view/20686
Hi I have a streamlit app where I’m displaying a bunch of points as a 3d scatter plot using plotly (plotly.express.scatter_3d). I have a couple of sliders that are used to as input to the function filters and colors certain points for plotting. All that works as expected. The problem is that every time I change the sliders the view of my 3D plot resets. I want to be able to first rotate/zoom my 3d plot to get the optimal view of my data and then change some arguments with my sliders to see how my data changes. Is there any way to achieve this? Dag
Maybe wrapping up your plot and your sliders into a form will solve your problem: docs.streamlit.io st.form - Streamlit Docs 3 st.form creates a form that batches elements together with a “Submit” button. then you can adjust your sliders and enter your new state by clicking the submit button. Hope this helps
0
streamlit
Using Streamlit
Refreshing page on st.number_input or chaning st.text_input
https://discuss.streamlit.io/t/refreshing-page-on-st-number-input-or-chaning-st-text-input/20607
Hello there. I use st.button that adds st.text_input, but everytime I write something into text_input and press enter, it refreshes the whole page. I saw the similar topics and advices to use session states, but I don’t quite understand how to use it.
Hi @Rockkley, As you point out, many people as they transition to the more advanced session state features have trouble wrapping their minds around the workflow of callbacks. I actually wrote a Knowledge base article in our documentation to help with this exact scenario! In the article, the button interacts with a slider, but the principle is the same. All you have to do is create and track a key:value pair when the button has been pressed, via the on_click parameter. Then in your script, you use the value stored in state to display your text_input and process the rest of the app. docs.streamlit.io Widget updating for every second input when using session state - Streamlit Docs 5 Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
pymongo.errors.ServerSelectionTimeoutError | Setting up MongoDB
https://discuss.streamlit.io/t/pymongo-errors-serverselectiontimeouterror-setting-up-mongodb/20676
Hi, I am trying to use MongoDB in my project . I have also mentioned the credentials in secret TOML of the app. However, it shoots me this error “pymongo.errors.ServerSelectionTimeoutError” App : https://share.streamlit.io/shubh2016shiv/bio-medicalqa/main/app.py GitHub Repo: GitHub - shubh2016shiv/Bio-MedicalQA So when I select the option “Search Bio-Topics & Questions” in navigation, it basically tries to create a new DB : BioASQ and populate the records in MongoDB after reading the data. This is where the issue seems to popping up. In local MongoDB, it is running correctly, however, on streamlit, something seems to be missing which I am not able to figure out. The function in app.py where MongoDB setup is being done is : “def setupMongoDB():” Kindly suggest the changes necessary for this. Thanks Shubham Singh
I think I saw this kind of Error for 2 different reasons so far. The database is not reachable from where you are deploying your app (however, I’m not sure if it was this exact Error or if it was a connection error directly) When I cached a database connection and it timed out at some point, I think on the database side. I solved this by giving my cached database setup function a timestamp as an input argument which changes every couple of minutes so that the connection would be re-established before it timed out. I think you are doing something similar to caching in your code by only initializing the client once. After some time the database will cut the connection due to a timeout at which point you would have to reconnect. Hope I could help you.
0
streamlit
Using Streamlit
Forms weird state behaviour
https://discuss.streamlit.io/t/forms-weird-state-behaviour/20126
I’m working on an app intended to be used to update a json file. I’ve read a json file initialized each json field as a state and create widgets with the same key and after submitting with the forms I would use the state to create a new json file with the newer field values. The structure is similar to this example import streamlit as st keys = ["a", "b", "c", "d", "e"] # We know that: # a -> 0 # b -> 1 # c -> 2 # d -> 3 # e -> 4 for idx, key in enumerate(keys): if key not in st.session_state: st.session_state[key] = idx st.write("# Some Header") with st.form("Form 1"): with st.expander("First Form"): st.slider("a", 0, 10, step=1, key= "a") st.slider("b", 0, 10, step=1, key='b') st.form_submit_button("Submit Here I") with st.form("Form 2"): with st.expander("Second Form"): st.slider("c", -1, 10, step=1, key= "c") st.slider("d", -1, 10, step=1, key='d') st.form_submit_button("Submit Here II") with st.expander("Other Thin outside form"): st.slider("e", 0, 10, step=1, key= "e") st.button("Do something") st.write([f"{key}: {st.session_state[key]}" for key in sorted(st.session_state.keys())]) Everything was okay until I’ve noticed that if I submit one of the forms without opening all the expanders the value that appears in the sliders would be the min_value instead of the state value. Any help would be very appreciated
Hi @Eduardo_Pacheco! So, what’s happening here is that by assigning a key to each slider of the same letter as the keys you already stored in the state. You have literally linked those values to whatever the slider value is. This means that the session state will always reflect the value that the slider is at the time that the user selects the form_submit_button. I think, if I understand your use case, you want the user to be able to choose to change the value, or not (ie. some values might change but some may stay the same). I think the easiest way to do this is by adding the parameter value to your sliders and assigning that value to be the initialized value for each key your are tracking. Check out the code snippet where I do that here: import streamlit as st keys = ["a", "b", "c", "d", "e"] # We know that: # a -> 0 # b -> 1 # c -> 2 # d -> 3 # e -> 4 for idx, key in enumerate(keys): if key not in st.session_state: st.session_state[key] = idx st.write("# Some Header") with st.form("Form 1"): with st.expander("First Form"): st.slider("a", 0, 10, step=1, value=st.session_state.a, key= "a") st.slider("b", 0, 10, step=1, value=st.session_state.b, key='b') st.form_submit_button("Submit Here I") with st.form("Form 2"): with st.expander("Second Form"): st.slider("c", -1, 10, step=1, value=st.session_state.c, key= "c") st.slider("d", -1, 10, step=1, value=st.session_state.d,key='d') st.form_submit_button("Submit Here II") with st.expander("Other Thin outside form"): st.slider("e", 0, 10, step=1,value=st.session_state.e, key= "e") st.button("Do something") st.write([f"{key}: {st.session_state[key]}" for key in sorted(st.session_state.keys())]) Now, when the slider renders in your browser, it will have the default value you assigned in the state, and if the user doesn’t update that value it will not change to the min_value for the slider. Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Error running app
https://discuss.streamlit.io/t/error-running-app/20680
Why I am getting this error, not sure… Can anyone help me to understand this? would be a great help… It is working completely fine locally using streamlit. Thanks you! error running app1911×903 106 KB
Hi @samachakole, Since this is an exact copy of the question you posted here 2. I’m going to close this topic and we can help you sort your app on the other thread. In future, you should only be opening one thread/forum post per question, so that it’s not confusing to those trying to help. Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
St.markdown tags
https://discuss.streamlit.io/t/st-markdown-tags/20687
I have been trying to use st.markdown to render some text strings. However, markdown is clobbering the newlines and displaying everything as continuous text. How can I display the newlines and paragraphs?
Hi @bhawmik, Can you paste your code here so I can see what it looks like? Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Error TypeError: ‘DataFrame’ object is not callable
https://discuss.streamlit.io/t/error-typeerror-dataframe-object-is-not-callable/20551
Hi, Building an app with this API GitHub - GeneralMills/pytrends: Pseudo API for Google Trends 1 I’ve made it to work in Jupyter, but for some reason can’t replicate using Streamlit. It’s breaking on this line of code : else: kw_list = removeRestrictedCharactersAndWhiteSpaces(linesList) pytrend.build_payload(kw_list, timeframe=selected_timeframe, geo=country_code[0], cat=category_ids[0]) historic_interest = pd.DataFrame( pytrend.get_historical_interest(kw_list,year_start=year_from, month_start=month_from, day_start=day_from, year_end=year_to, month_end=month_to, day_end=day_to) ) Error Traceback File "/Users/lazarinastoy/.local/lib/python3.8/site-packages/streamlit/script_runner.py", line 350, in _run_script exec(code, module.__dict__)File "/Users/lazarinastoy/Desktop/pytrendstest/streamlit_app.py", line 149, in <module> pytrend.get_historical_interest(kw_list,year_start=year_from, month_start=month_from, day_start=day_from, year_end=year_to, month_end=month_to, day_end=day_to)File "/Users/lazarinastoy/.local/lib/python3.8/site-packages/pytrends/request.py", line 490, in get_historical_interest df = pd.DataFrame() Any help with this will be appreciated.
Thanks, Charly! I actually found out the resolution to this query, so I’ve not graduated to another type of error (LOL), will update the resolution and close this topic down. Will keep you posted with my code, if any help is needed, I’m chipping away at it slowly but surely. Thanks Again. For those interested: The error was that the pytrends api returns a df object as a response to the get_hisotrical_interest() function (indicated by the last row in the error log). This needs to be wrapped up in a st.dataframe() when called in the web app. Like this: st.dataframe( pytrend.get_historical_interest(kw_list,year_start=year_from, month_start=month_from, day_start=day_from, year_end=year_to, month_end=month_to, day_end=day_to, sleep=0) ) Not like this: historic_interest = pd.DataFrame( pytrend.get_historical_interest(kw_list,year_start=year_from, month_start=month_from, day_start=day_from, year_end=year_to, month_end=month_to, day_end=day_to) )
1
streamlit
Using Streamlit
Creating multiple custom components in the same python package
https://discuss.streamlit.io/t/creating-multiple-custom-components-in-the-same-python-package/10906
Hello Streamlit Community! Is it possible to develop multiple streamlit custom components in same python package and expose them ? Something like material-ui react lib, where multiple UI components can be exported from.
Hello @Jacob_Lukose, welcome to the community Haven’t given it too much thought but 2 ideas coming to mind (sorry the following is going to be very rough pseudocode, I’ll try again later if that doesn’t help you): 1/ on Python side declare one URL per component then have react-router or Next.js on the React side check the route and send back the desired component. My guess is this is not the optimal solution but it may be a way to start and better understand the path to take. Roughly something like: _component_func_button = components.declare_component("http://localhost:3001/button") _component_func_slider = components.declare_component("http://localhost:3001/slider") def material_button(label: str): _component_func_button(label=label) def material_slider(min: int): _component_func_slider(min_value=min) and React side <Switch> <Route path="/button"> <Button label="args.label"/> </Route> <Route path="/slider"> <Slider min="args.min_value"/> </Route> </Switch> 2/ from Python to send the component to display as a prop, then in your React code check the prop and return the desired component. This may be better than 1/. Roughly something like: _component_func = components.declare_component("...") def material_button(): _component_func(component="button") def material_slider(): _component_func(component="slider") then on the React side <App> if(args.component == "button") {return Button(args.label)} if(args.component == "slider") {return Slider(args.min_value)} </App> @okld / @asehmi maybe you have more experience on this to share though ?
0
streamlit
Using Streamlit
Mito on Streamlit
https://discuss.streamlit.io/t/mito-on-streamlit/16344
Hi everyone, I discovered Mito recently, and users can only use it on JupyterLab. I wonder if anyone in the community has implemented Mito on Streamlit? Mito makes it super easy to manipulate data in the spreadsheet environment on GUI and encourages the non-programmer background client to use the tool to explore the data. Thanks, everyone!
Hey @C45513! Not scheduled yet but we’ll outreach to them to discuss the idea, as they seem interested! See the video from 22:33 morioh.com Developers of MITO Python Library | Data Science Podcast 28 Ever wanted to leverage your spreadsheet skills in Python? Now you can with Mito, the Python library that enables the use of a Spreadsheet directly in Jupyter. In this video, I sit down for a talk with the founders and developers of Mito Best, Charly
0
streamlit
Using Streamlit
Session state/ button interaction yields unexpected order
https://discuss.streamlit.io/t/session-state-button-interaction-yields-unexpected-order/18885
I want my button to toggle what it says depending on the session state, just like how a play button turns into pause after being clicked and back into play after being clicked again. Here is the bare reproduction code I wrote to do so. It’s easiest if you just try and run the code because the behaviour is hard to explain. import streamlit as st # initialize recording_data as true if "recording_data" not in st.session_state: st.session_state.recording_data = True toggle_text = "Stop" if st.session_state.recording_data else "Start" if st.sidebar.button(toggle_text): # flip recording_data st.session_state.recording_data = not st.session_state.recording_data st.write(st.session_state) Hitting the button switches recording_data, and hitting the button should also rerun the script, so I expect that since recording_data has been flipped, the text will also change. Instead, the text changes every second time the button is pressed. Printing out the session state is a bit revealing: I expect two states: Text is “Start”, st.session_state.recording_data = False Text is “Stop”, st.session_state.recording_data = True But there are actually 4 states, in this order: Text is “Start”, st.session_state.recording_data = False Text is “Start”, st.session_state.recording_data = True Text is “Stop”, st.session_state.recording_data = True Text is “Stop”, st.session_state.recording_data = False It seems to me like code in the button block is run after the site is reloaded, which is maybe a feature, not a bug, but is there a way to do what I want?
Seems like callback functions are what I need, as they execute when a button is pressed, and then the app is rerun, so if I put the change to session state in the callback all will be well, maybe
0
streamlit
Using Streamlit
Randomly generate a number and save this number and user input
https://discuss.streamlit.io/t/randomly-generate-a-number-and-save-this-number-and-user-input/20615
Hi, I think I found a problem with streamlit but I am not sure… I would like to build an app that samples a random number, let the user input some answer and save the number and the answer to a .csv file, from some reason, the input is saved with the next randomly generated number, below is an example: I expected this code to create two-line .csv files that look like the following: inputted_idx,idx 42,42 but instead, the number that will be saved under idx will be the next generated index (the one that will show after the refresh). for example: inputted_idx,idx 42,22 import random import streamlit as st import pandas as pd import datetime save_path = '~/' idx = random.randint(1,100) st.write(idx) with st.form('Form', clear_on_submit=True): inputted_idx = st.text_input('Input the number written above') submit = st.form_submit_button('Submit') if submit: pd.DataFrame({ 'inputted_idx':[inputted_idx], 'idx':[idx]}) \ .to_csv(save_path+str(datetime.datetime.now().time()), index=False)
Hey @per, AH! I see what you’re doing now! I have actually done something similar with an app I made about Monte Carlo modelling! So, instead of using random to generate a number every time the script runs, you can use state to store a random number until you want to generate a new one. # initializing with a random number if "rn" not in st.session_state: st.session_state["rn"] = random.randint(1,100) # callback function to change the random number stored in state def change_number(): st.session_state["rn"] = random.randint(1,100) return st.write(st.session_state.rn) ## button to generate a new random number st.button("New row?", on_click=change_number) with st.form('Form', clear_on_submit=True): inputted_idx = st.text_input('Input the number written above') submit = st.form_submit_button('Submit') if submit: data = pd.DataFrame({'inputted_idx':[inputted_idx], 'idx':[st.session_state.rn]}) st.dataframe(data) With this flow, the app generates a random number that is displayed on the screen, the person can then use the form to enter that number into the app and hit submit. I just displayed the data to the app so you can see that both are showing the correct number. Once the user is finished with that random number/row of the data, they can hit the button at the top called New row?, which triggers a callback function. The callback function simply updates the session state to have a. new random number to work with. Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
Datetimeindex format
https://discuss.streamlit.io/t/datetimeindex-format/12736
Hello there, community: I’m using Streamlit for my Python Data Science Web Projects. So far, so good. But, why I get this format on my DateTime index? error streamlit table1544×632 89.8 KB st.write(df) or st.dataframe(df) displays index as: 2020-01-01T00:15:00-05:00 I would like to display my table with this index format: 2020-01-01 00:15:00 Thanks in advance for your support. If you want you can see my web project on: https://renewables-peru.herokuapp.com/ 4
Welcome @KevinAQM to streamlit community . First, the column you are setting to the index have this variable T as being shown in this picture you available to us? maybe the index are auto formatting T as time, because at the blue box you circled he didn’t show this parameter…
0
streamlit
Using Streamlit
Read a csv file from Google cloud storage
https://discuss.streamlit.io/t/read-a-csv-file-from-google-cloud-storage/3821
Hello Team, I am new o Streamlit. I am trying to read a csv file from my google cloud storage (https://storage.cloud.google.com/timeseriesdata/devicedetails.csv 15). I have implemented the below code, but I am getting the tokenization error. DATA_URL = ( "https://storage.cloud.google.com/timeseriesdata/devicedetails.csv" ) @st.cache(persist=True) def load_data(nrows): data = pd.read_csv(DATA_URL, nrows=nrows) return data data = load_data(10) I would like to see the results in the form of a table. I have enclosed my error message as an attachment. Kindly suggest me on this. Thanks and Regards, S.ThilakTokenerror1920×1008 70.4 KB
Hey @randyzwitch Thanks for the information, I have checked the input file, looks like it requires data types to be mentioned for each column. I could able to figure it out. Thanks and Regards, S.Thilak
1
streamlit
Using Streamlit
json.decoder.JSONDecodeError
https://discuss.streamlit.io/t/json-decoder-jsondecodeerror/14830
My Streamlit App was working fine till the last week. But, when I tried to use it today, I see a weird error called “json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)”. Initially, I deployed in Heroku, and it was working without any issues, and just a few hours from now, I see this JSONDecodeError. I have tried many ways to resolve it, but no luck. So, I thought of testing it in my local, and the same error continues to persist. I even tried to deploy it on Streamlit share, and still, this error haunts me. Here, I provide URLs of my codebase and a complete error log. Heroku App URL: https://stock-data-app-streamlit.herokuapp.com/ 10 GitHub codebase repo: GitHub - msaf9/DataApp 3 Streamlit share error log: 2021-07-09 18:42:52.785 An update to the [server] config option section was detected. To have these changes be reflected, please restart streamlit. A new version of Streamlit is available. See what’s new at Official Announcements - Streamlit Enter the following command to upgrade: $ pip install streamlit --upgrade 2021-07-09 18:42:53.182 Uncaught app exception Traceback (most recent call last): File “/home/appuser/venv/lib/python3.7/site-packages/streamlit/script_runner.py”, line 337, in _run_script exec(code, module.dict) File “/app/dataapp/main.py”, line 44, in stockDf = stockData.history(period=‘1d’, start=From, end=To) File “/home/appuser/venv/lib/python3.7/site-packages/yfinance/base.py”, line 157, in history data = data.json() File “/home/appuser/.conda/lib/python3.7/site-packages/requests/models.py”, line 900, in json return complexjson.loads(self.text, **kwargs) 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 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File “/usr/local/lib/python3.7/json/decoder.py”, line 355, in raw_decode raise JSONDecodeError(“Expecting value”, s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Heroku deployment error log: JSONDecodeError: Expecting value: line 1 column 1 (char 0) Traceback: File “/app/.heroku/python/lib/python3.9/site-packages/streamlit/script_runner.py”, line 337, in _run_script exec(code, module.dict) File “/app/main.py”, line 43, in stockDf = stockData.history(period=‘1d’, start=From, end=To) File “/app/.heroku/python/lib/python3.9/site-packages/yfinance/base.py”, line 157, in history data = data.json() File “/app/.heroku/python/lib/python3.9/site-packages/requests/models.py”, line 900, in json return complexjson.loads(self.text, **kwargs) File “/app/.heroku/python/lib/python3.9/json/init.py”, line 346, in loads return _default_decoder.decode(s) File “/app/.heroku/python/lib/python3.9/json/decoder.py”, line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File “/app/.heroku/python/lib/python3.9/json/decoder.py”, line 355, in raw_decode raise JSONDecodeError(“Expecting value”, s, err.value) from None Can someone help me with this?
I had the same problem. It was working up to a point, then I got the same error message. Any help would be highly appreciated.
0
streamlit
Using Streamlit
File Upload Problem
https://discuss.streamlit.io/t/file-upload-problem/8365
Hello, Until very recently (yesterday night) everything was working extremely well. However, my results started to change without me making a single change in my own code. Basically, the problem is that the file uploader is not reading the files from my computer in the correct order. When I print out the names of the images that it read, this is what I got: IM00001.tif IM00002.tif IM00004.tif IM00003.tif IM00005.tif IM00006.tif IM00007.tif IM00009.tif IM00011.tif IM00008.tif IM00010.tif IM00014.tif IM00013.tif IM00012.tif IM00015.tif IM00016.tif IM00017.tif IM00018.tif IM00019.tif IM00021.tif The correct order is supposed to be the images with numbers in sequential order. Does anyone know what the problem might be?
I still don’t know what the problem is, but it may have something to do with the new streamlit update?
0
streamlit
Using Streamlit
Custom header right at the top of the page, styled with custom CSS
https://discuss.streamlit.io/t/custom-header-right-at-the-top-of-the-page-styled-with-custom-css/20612
I would like to have a Streamlit app, but with a custom header bar right at the very top, styled with custom CSS (and maybe even using a bit of Javascript) Is this possible? If so, how? I see lots of things about how to make custom components. But I’ve not found anything about bits that wrap the components. There is some information about themes, but I’ve not found out how to use them to control the HTML
Hi @michalc, welcome to the Streamlit community! Would Streamlit_navbar from Chanin suit your needs? GH: https://github.com/dataprofessor/streamlit_navbar 5 Demo is deployed here: https://share.streamlit.io/dataprofessor/streamlit_navbar/main/app_navbar.py 6 Chanin has also done a thorough tutorial, walking you through the navbar set-up: Is it Possible to Add a Navigation Bar to Streamlit Apps? | Streamlit #29 Best, Charly
0
streamlit
Using Streamlit
Integrating What-If-Tool Widget in Streamlit App
https://discuss.streamlit.io/t/integrating-what-if-tool-widget-in-streamlit-app/13859
Hi, I have been developing a Streamlit app for Machine Learning models and want to integrate the Widget provided by the What-If Tool (link: What-If Tool 13). For an example code of the Widget that I want to integrate please see the link: Example Code of Widget on Google Colab 7 Can anyone please help me on how to include the exact same widget in streamlit application with all the interactive functionalities maintained. Thanks in Advance!!
Same Issue with me also. Did anyone else has come across this requirement. Any solution would be helpful!!!
0
streamlit
Using Streamlit
Adding attributes to session state
https://discuss.streamlit.io/t/adding-attributes-to-session-state/20616
image3193×1397 219 KB What is wrong? I added the attribute ‘psyZ’ but it still shows the error like it’s not in there
Hi @Rockkley, Can you double-check that you have saved the file you made? Also, make sure your Streamlit version is up to date. From the small snippet, it looks correct to me, but there might be something else happening in other lines of code that I can’t see. If those two things don’t work, can you post a link to your code via GitHub or just a complete copy of your code would help so I can trace the error? Happy Streamlit-ing Marisa
0
streamlit
Using Streamlit
Charting Not Recognizing Datetime Objects within Dataframe
https://discuss.streamlit.io/t/charting-not-recognizing-datetime-objects-within-dataframe/20255
I’m having trouble creating a simple line chart from a data frame created with data from a SQL call. The df object looks like this: Screen Shot 2021-12-21 at 5.56.21 PM624×842 135 KB Index, Date, Images_Added. Date is type - datetime64[ns]. You can see that Streamlit renders the data frame object as such: Screen Shot 2021-12-21 at 5.55.52 PM644×728 36.7 KB However the chart that gets created with st.line_chart(df) is: Screen Shot 2021-12-21 at 5.56.11 PM2872×634 42.1 KB It seems that I should probably be using st.altair_chart and have tried to wrangle the data frame so that it will play nice with altair, but no luck so far. Any thoughts appreciated.
Hi @RickBL, welcome to the Streamlit community! I suspect you might get the chart you are looking for if you make the Date column an index instead, but you’re right, in the situation where st.line_chart doesn’t give you what you want, using st.altair_chart is the way to proceed. Best, Randy
1
streamlit
Using Streamlit
Server Error A10 Unable to Create App
https://discuss.streamlit.io/t/server-error-a10-unable-to-create-app/20591
Trying to deploy an app and am getting this error. SOS ! Thanks !
Hey @JamesWatkins, I believe it is a noob error actually! Can you try this and let me know if that fixes the problem for you? Your repo ad a folder COVID-19 in Ontario/ which has spaces in it. Spaces are actually (in general) a no-no when working with the terminal and coding, causing unforeseen errors. If you can change the folder name to remove the spaces I think that should allow you to deploy properly. Happy Streamlit-ing! Marisa
1
streamlit
Using Streamlit
‘sleep’ causes function to reload despite of cache
https://discuss.streamlit.io/t/sleep-causes-function-to-reload-despite-of-cache/20609
I’m trying to send a request to an external API, wait some time and get back the response. Here’s a minimal example of my code (I replaced the requests with just logs): import streamlit as st from time import sleep @st.cache def run(): print('Send some request and wait some time') sleep(5) print('Request the response') if __name__ == '__main__': run() When I run it (streamlit run app.py), the output is: Send some request and wait some time Send some request and wait some time Request the response Request the response In other words, it is executing the function twice, which shouldn’t happen. I notice the problem goes away when I remove the sleep (but of course I need it for my app to run properly).
Hi @rsilva, Can you try updating the version of Streamlit you’re using? Also what version do you have currently? I just tried your code snippet on my machine here and it seems to be working fine, only running one time and printing to the terminal (I attached a screenshot for you). I’ve got Streamlit 1.2.0 installed in this virtual environment. Screen Shot 2022-01-04 at 11.57.06 AM1796×1080 178 KB Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
Saving the Plotly Chart as .png or .jpeg file format locally
https://discuss.streamlit.io/t/saving-the-plotly-chart-as-png-or-jpeg-file-format-locally/20535
Dear Team, Wish you all a very Happy, Safe & Prosperous New Year!! Trust you all are doing well!! Recently, I was trying to add a PDF generator to one of my Streamlit App. I got stuck on the below part: I have created an app that read the datframe and plot charts (plotly express charts) as the result. Below is the snippet. image1707×593 26.4 KB Now, I want to store/save these charts as tempfile in the work folder to access for the next action that is PDF generator. So, I want to add these charts as Images inside HTML image-holders to create PDF report. The PDF report generator example follows here (developed by Streamlit): https://share.streamlit.io/streamlit/example-app-pdf-report/main 1 @AvratanuBiswas Thanks in Advance!!
Hi @amrit , Just found this from the community, Download Plotly plot as html Using Streamlit 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="da… Although, I haven’t tried it myself, but does this help in your case study ( for sure , you need to tweak the code further in your case ) ? Best Avra
0
streamlit
Using Streamlit
Error when running the python file
https://discuss.streamlit.io/t/error-when-running-the-python-file/20007
hi guys, anyone can help me with these errors? A new version of Streamlit is available. See what's new at https://discuss.streamlit.io/c/announcements Enter the following command to upgrade: $ pip install streamlit --upgrade You can now view your Streamlit app in your browser. Local URL: http://localhost:8501 Network URL: http://192.168.100.168:8501 2021-12-14 02:31:00.907 Uncaught exception GET /stream (::1) HTTPServerRequest(protocol='http', host='localhost:8501', method='GET', uri='/stream', version='HTTP/1.1', remote_ip='::1') Traceback (most recent call last): File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\web.py", line 1704, in _execute result = await result File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 278, in get await self.ws_connection.accept_connection(self) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 879, in accep t_connection await self._accept_connection(handler) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 962, in _acce pt_connection await self._receive_frame_loop() File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 1116, in _rec eive_frame_loop await self._receive_frame() File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 1205, in _rec eive_frame handled_future = self._handle_message(opcode, data) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 1217, in _han dle_message data = self._decompressor.decompress(data) File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\tornado\websocket.py", line 798, in decom press result = decompressor.decompress( TypeError: 'float' object cannot be interpreted as an integer C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\altair\utils\core.py:185: UserWarning: I don't kn ow how to infer vegalite type from 'empty'. Defaulting to nominal. warnings.warn(
my localhost become slower, cant rerun the localhost.
0
streamlit
Using Streamlit
Page keeps refreshing when typing in text input
https://discuss.streamlit.io/t/page-keeps-refreshing-when-typing-in-text-input/12199
The page keeps refreshing itself when typing in a text input, as shown in the GIF below: streamlit-CF_st-2021-04-25-01-04-341366×576 979 KB
Nevermind. Got it. Used SessionState.
1
streamlit
Using Streamlit
Use session state in debugger
https://discuss.streamlit.io/t/use-session-state-in-debugger/19800
Has anyone found that they can’t use the debugger in their streamlit code anymore once they use the native state management? Now whenever I use the debugger, it’s as if it can’t store any data in the st.session_state object. When I run the app, the code runs fine. However when I use my debugger in pycharm, I can’t get past the first line that accesses the st.session_state call because the “dictionary” is empty. See this example: print(st.session_state) {} st.session_state['foo'] = 'bar' st.session_state['foo'] Traceback (most recent call last): File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 381, in __getitem__ return self._getitem(widget_id, key) File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 424, in _getitem raise KeyError KeyError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3457, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-9404e5a9ae15>", line 1, in <module> st.session_state['foo'] File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 666, in __getitem__ return state[key] File "/opt/anaconda3/envs/yogen2/lib/python3.7/site-packages/streamlit/state/session_state.py", line 383, in __getitem__ raise KeyError(_missing_key_error_message(key)) KeyError: 'st.session_state has no key "foo". Did you forget to initialize it? More info: https://docs.streamlit.io/library/advanced-features/session-state#initialization' print(st.session_state) {} How are we supposed to develop applications if we can’t use the debugger mode in our IDEs?
anyone know the answer to this or have workarounds? surely I’m not the only one
0
streamlit
Using Streamlit
Multiselect and select boxes displaying the user selection on the screen
https://discuss.streamlit.io/t/multiselect-and-select-boxes-displaying-the-user-selection-on-the-screen/20563
Our application here is showing the user selection from the sidebar on to the screen which looks messy, is there a way we can change the way it looks(change colors and make it more presentable) or is there an alternative way to display this info.
Hi, you will have to include a screenshot or a link to your application, so that others can get an idea what you want help with. The application look can also be changed. Refer the following link: Streamlit – 18 Mar 21 Creating Custom Themes for Streamlit Apps 1 Try out the new dark mode and custom theming capabilities Cheers
0
streamlit
Using Streamlit
What is the difference between st.dataframe(df) vs st.write(df)
https://discuss.streamlit.io/t/what-is-the-difference-between-st-dataframe-df-vs-st-write-df/20338
Hello, The output looks the identical. But when would you use one over the other? TIA!
Hi Jeisma In my opinion st.write() is a combination of output function, it output based on what you put in, for example you can use st.write(df), st.write(error) or even st.write(altair_chart). For me the best thing about st.write() is it can output multiple item, such as st.write(df, df[‘col1’].dtype, fig1) in 1 line.
1
streamlit
Using Streamlit
Streamlit not loading dataframe. pandas,
https://discuss.streamlit.io/t/streamlit-not-loading-dataframe-pandas/20406
Not sure why the columns arent showing up on streamlit. image1709×633 39 KB image1215×430 26.3 KB I’m new to programming. Is this an issue with the pandas I pip installed?
Hi @dkrazey, welcome to the Streamlit community! I don’t know anything about the OpenSea API, but the first thing I would test is that you get a valid response back for r. I’d add something like if r.status == 200: to your code, to ensure that the parser is only run when you get a valid JSON response back. Best, Randy
0
streamlit
Using Streamlit
File_uploader woes - Pandas ‘read csv’ provides a consistent error with parser
https://discuss.streamlit.io/t/file-uploader-woes-pandas-read-csv-provides-a-consistent-error-with-parser/20315
After a very happy couple of days using streamlit - managed a couple of running apps and managed to package an offline app pretty cool and not bad for a biologist! first app here Streamlit 2 used as a test case for data viewing. The goal is an offline app for people to run on their own machines. It doesn’t like providing a path to files like local hosting for nativefier… not sure why… so trying to using file uploader. However, this isn’t working as expected - likely something I have missed…however the documents suggests that UploadFile ‘type’ is a online version of the csv file and should pass direct to pandas. So passing a single file or passing a loop set of files direct to pandas read_csv seems to work I get the normal error when reading these files. so calling a globbed path to files or URL of raw csv files works. arrays = ArayaManager(files) # this normally contains a globbed list of local file names and work if #passing st.text input and through pathlib. comp = arrays.concatenate_dataframes() # access the required files. passing… uploaded_files = st.file_uploader("Upload CSV", type='csv', accept_multiple_files=True) does not work - error concatenate_dataframes takes one argument got 2. Why is this? so try uploaded_files = st.file_uploader('Select files',type=['csv'],accept_multiple_files=True) file_lst = [uploaded_file.getbuffer for uploaded_file in uploaded_files] files = st.write(file_lst) and try passing to ArayaManger - get error - NoneType ‘object’ is not iterable so I am not passing anything and there is nothing for concatenate_dataframes to work on… image1141×817 43.4 KB The parser class class WellDataManager: """Parent class for importing data from any instrument""" def __init__(self, files, run_name_split_loc=1, group_name=""): super().__init__() # project attributes self.file_names = files self.group_name = group_name self.run_name = "" self.split_char_loc = run_name_split_loc self.run_df = pd.DataFrame() self.group_df = pd.DataFrame() # csv read attributes self.tables = 1 self.index_column = [0] self.header_row = [1] self.row_count = [8] self.column_names = ['Row_ID', 'Col_ID', 'Value'] def concatenate_dataframes(self): for each_file in self.file_names: self.get_run_name(each_file) self.build_dataframes(each_file) self.group_df = pd.concat([self.group_df, self.run_df], ignore_index=True) # print(self.group_df) return self.group_df def build_dataframes(self, each_file): self.read_file(each_file) self.coerce_numeric_values() self.run_df['Group_ID'] = self.group_name self.run_df['File_root'] = each_file self.run_df['Run_ID'] = self.run_name # print(self.run_df) def coerce_numeric_values(self): # may be used used to force values to numeric. Not applicable to all instruments pass def read_file(self, file_name): """Reads Initial Data from CSV file""" df = pd.read_csv(file_name, header=self.header_row, nrows=self.row_count, index_col=self.index_column) df = df.stack() self.run_df = df.reset_index() self.run_df.columns = self.column_names def get_run_name(self, file_name): """Splits string to get run name from file name.""" self.run_name = file_name[:self.split_char_loc] self.run_file_in = os.path.basename(csv) class ArtelVMSManager(WellDataManager): """Class that handles Well Data Data""" def __init__(self, files, run_name_split_loc=1, group_name=""): super().__init__(files, run_name_split_loc, group_name) # csv read attributes self.tables = 1 self.index_column = [0] self.header_row = [18] self.row_count = [8] self.column_names = ['Row_ID', 'Col_ID', 'Volume'] def coerce_numeric_values(self): """Coerce the 'volume' data to numeric. Otherwise mixture of strings and numeric values""" num_col = self.column_names[2] self.run_df[num_col] = pd.to_numeric(self.run_df[num_col], errors='coerce') class ArayaManager(WellDataManager): """Class that handles Well Data Data""" def __init__(self, files, run_name_split_loc=6, group_name="", dyes=None, separate_column=True): super().__init__(files, run_name_split_loc, group_name) if dyes is None: dyes = ['FAM', 'VIC', 'ROX'] # Ayara-specific items self.separate_column_per_dye = separate_column self.channel_df = pd.DataFrame() self.dyes = dyes self.channels = ['CH1', 'CH2', 'CH3'] # csv read attributes self.tables = 3 self.index_column = ["<>", "<>", "<>"] self.header_row = [5, 23, 41] self.row_count = [16, 16, 16] if self.separate_column_per_dye: # TODO: generalize for other dye names self.column_names = ['Row_ID', 'Col_ID', 'FAM_RFU', 'VIC_RFU', 'ROX_RFU'] else: self.column_names = ['Row_ID', 'Col_ID', 'RFU', 'Channel', 'Dye'] def read_each_channel(self, file_name, ch): """Reads Individual Channel Data from CSV file""" df = pd.read_csv(file_name, header=self.header_row[ch], nrows=self.row_count[ch], na_values="<>") # Need to shift to get rid of annoying '<>'. Otherwise won't parse correctly. df = df.shift(periods=1, axis='columns') #df.drop('<>', axis=1, inplace=True) # Stack df for various dyes and add additional columns df = df.stack() self.channel_df = df.reset_index() # For separate columns for each dye, rename RFU columns. pd.concat() method does the rest! if self.separate_column_per_dye: self.channel_df.columns = self.column_names[0:3] self.channel_df.rename(columns={'FAM_RFU': f'{self.dyes[ch]}_RFU'}, inplace=True) # case to stack all dyes into common RFU and Dye channels. else: self.channel_df['Channel'] = self.channels[ch] self.channel_df['Dye'] = self.dyes[ch] self.channel_df.columns = self.column_names def read_file(self, file_name): """Reads Each Channel Data from CSV file""" # loops through the 3 channel tables in the csv output files. self.run_df = pd.DataFrame() for ch in range(self.tables): self.read_each_channel(file_name, ch) # case to have separate columns for each dye if self.separate_column_per_dye: self.channel_df = self.channel_df[self.channel_df.columns.difference(self.run_df.columns)] self.run_df = pd.concat([self.run_df, self.channel_df], axis=1) # case to stack all dyes into common RFU and Dye channels. else: self.run_df = pd.concat([self.run_df, self.channel_df], ignore_index=True) # Force columns to correct order. Fixed bug with concat of separate dye columns. self.run_df = self.run_df[self.column_names] def get_run_name(self, file_name): """Splits string to get run name from file name.""" self.run_name = file_name[-(self.split_char_loc+4):-4]` Not sure why I cannot pass the UploadedFile type data directly to pandas - if I directly pass the file to pd.read_csv it will read single files. A for loop to read each does the same thing. Any help would be appreciated.
Hi @doc_curry, welcome to the Streamlit community! Is there a GitHub repo you can provide that shows the entirety of the code? Best, Randy
0
streamlit
Using Streamlit
Bootstrap Modal Element in Streamlit
https://discuss.streamlit.io/t/bootstrap-modal-element-in-streamlit/20302
Hello everyone! I am trying to use bootstrap modal for visualizing images in a modal (pop up). I followed this template code 3 but it is not working well with displaying of modals for some reason. I am able to incorporate other bootstrap components like accordians etc. but not modals… def custom_image_model(imgpth: str = "./img/1.jpg"): return components.html(f""" <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <img src="{imgpth}" alt="NotFound"> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> """, height=600) Can someone please guide me on where it is that I am going wrong… Thanks & Regards, Vinayak.
Hi @ElisonSherton, welcome back! I suspect the issue here is that modals are a pop-up, and Streamlit components run in their own iframe. So in this case, you are generating a popup in the wrong context (the iframe), where you want it in the outer container. There is no workaround for this currently through components.html, as we intentionally run that code in an iframe as a security design. Best, Randy
0
streamlit
Using Streamlit
How to put two buttons next to each other within a column?
https://discuss.streamlit.io/t/how-to-put-two-buttons-next-to-each-other-within-a-column/20417
I have a streamlit app with three columns, I want to add two buttons inside one of the columns, however it is impossible to nest columns into other columns. Are there any workarounds available?
Try using this component within your column and see if it solves your problem. New Component: `st_btn_select` - Selectbox alternative with buttons Show the Community! [Logo] [Homepage] [Demo] Streamlit Button Select Component Sometimes you want a user to make a selection, but you only have a few options. Using an st.selectbox component works, but wouldn’t it be easier to simply have a few buttons in a row ? Well, this custom component allows just that ! Installation pip install st_btn_select Usage Creating a Button Selection is really easy. from st_btn_select import st_btn_select selection = st_btn_select(('option 1', 'option 2', 'option 3')) st.… Cheers
1
streamlit
Using Streamlit
Seanborn Doesnt render faster-Is too slow on streamlit
https://discuss.streamlit.io/t/seanborn-doesnt-render-faster-is-too-slow-on-streamlit/20553
Dear Streamlit Community, Please which is the best chart to use with streamlit…I have tried seaborn and other charts but seaborn seems to be very slow with streamlit…orendously slow. Kindly help out
Hello @kareemrasheed89 There was a small benchmark done by @theimposingdwarf here: Plot Library Speed Trial 1 that suggests using Altair or Plotly rather than seaborn/matploblib. You could try those. If you are able to share a code snippet maybe we can see if there’s a way to optimize the seaborn part too. Have a nice day, Fanilo
0
streamlit
Using Streamlit
Streamlit interaction issues with Selenium
https://discuss.streamlit.io/t/streamlit-interaction-issues-with-selenium/4147
Hey! I’m trying to do a tiny app to make my webscraping script more useful. So I decided to use Streamlit. When I call the class which make the scrap, the Streamlit gets an error: " ModuleNotFoundError: No module named ‘selenium’ " I have no ideia whats going on, because i’m using the correct env to run the app (which already have Selenium) Specs: Streamlit Version: 0.61.0 Python Version: 3.8.3 Env: Conda OS: Windows Browser: Opera Some screenshots:
Hi Victor Did you make it work in the end?
0
streamlit
Using Streamlit
How to change st.sidebar.slider default color?
https://discuss.streamlit.io/t/how-to-change-st-sidebar-slider-default-color/3900
Hi, I tried to change the st.sidebar.slider default pink color to others with the below codes but getting error. Can anyone help me out in this… Code for default pink color: st.sidebar.slider('ABC',0,20,10) Tried with below code to change the color: st.sidebar.slider.markdown(f'<div style="font-size: medium;text-align: left;color: Blue;">'ABC',0,20,10</div>',unsafe_allow_html=True) OR st.sidebar.slider.markdown("<h1 style='text-align: left; color: Blue;'>'ABC',0,20,10</h1>", unsafe_allow_html=True)
I’m not sure you’re able to change the color of that element at this type, as it appears that it is dynamically created: .st-by { background: linear-gradient(to right, rgb(246, 51, 102) 0%, rgb(246, 51, 102) 75%, rgb(213, 218, 229) 75%, rgb(213, 218, 229) 100%); } If you open the developer panel of your browser and move the slider, you’ll notice that the percentage values change to indicate where on the slider you are. I’m not sure you can override that color scheme itself without changing the underlying slider code.
0
streamlit
Using Streamlit
Style Column Metrics like the Documentation
https://discuss.streamlit.io/t/style-column-metrics-like-the-documentation/20464
Working on nice Streamlit app with Columns and Metrics. I noticed the streamlit doc website appears to be a streamlit app with columns? If so, how can I format my metric in similar way? thank you Screen Shot 2021-12-29 at 9.11.56 PM879×158 14.6 KB Screen Shot 2021-12-29 at 8.57.44 PM949×280 27.1 KB
Well, you can achieve this effect in part with html & st.markdown, but you have to inspect elements, isolate them and then colour them. Refer the pix for the effect I tried to produce and the colours can be changed as required. tmp1295×336 13.4 KB
0
streamlit
Using Streamlit
Df.info() is not displaying any result in st.write()
https://discuss.streamlit.io/t/df-info-is-not-displaying-any-result-in-st-write/5100
Hi, I am trying to get information of pandas dataframe using the following code: st.write(df.info()) But instead of printing information of dataframe it is printing “None” and the result is printed in command prompt instead. Help me in resolving this issue.
Hi @anshul - This occurs because this pandas function doesn’t return anything back to Python (which is why you get a value of None), it only prints. The pandas documentation for df.info() 28 offers a similar type of solution: Pipe output of DataFrame.info to buffer instead of sys.stdout, get buffer content and writes to a text file: >>> import io >>> buffer = io.StringIO() >>> df.info(buf=buffer) >>> s = buffer.getvalue() >>> with open("df_info.txt", "w", ... encoding="utf-8") as f: ... f.write(s) In your case, you can probably do st.write(s) instead of writing to a file at the end.
1
streamlit
Using Streamlit
Change width of sidebar
https://discuss.streamlit.io/t/change-width-of-sidebar/5339
Hi there, I would like to show an image in the sidebar. Like this, the image can be viewed while scrolling through the app. Can the width of the sidebar be increased such that the complete image is visible in a reasonable size? It is possible to set the width of the image to make it smaller but this makes it difficult to read information from the image. Any help is very much appreciated! Cheers, Lili
Hi! I am having the same problem, but I want to print a small table (5 columns) onto the sidebar without scrolling right. @thiago How can we do it? Thanks!
0
streamlit
Using Streamlit
Select box width sizing along with text inputs
https://discuss.streamlit.io/t/select-box-width-sizing-along-with-text-inputs/20505
example_2304×638 35.5 KB Hello guys, I am newbie to Streamlit and maybe my question is too simple. I have 9 columns. The 1st column has “selectbox”, where feed ingredients are listed and the rest of them are text inputs. I would like to make “selectbox” wider so that an ingredient can be displayed easily upon selection and I would like to make the other “text_inputs” narrower (price, cost etc. do not need to be that wide). Is there are an easy workaround to this? Thanks
Refer st.columns in the documentation. You can change the width of a column relative to another column. The following example is for 2 columns; you can suitably modify it for 9 cols: col1, col2 = st.columns([3, 1]) Hope that helps
0
streamlit
Using Streamlit
Page title
https://discuss.streamlit.io/t/page-title/5770
AttributeError: module ‘streamlit’ has no attribute ‘beta_set_page_config’
Hi, which Streamlit Version are you using? The paramter ‘beta_set_page_config’ is only available since Version 0.65.0 Maybe you need to upgrade your version: pip install --upgrade streamlit Best, Alex
0
streamlit
Using Streamlit
User inputs gather on one database on deployment (sqlite)
https://discuss.streamlit.io/t/user-inputs-gather-on-one-database-on-deployment-sqlite/20471
So, I’m trying to make some kind of productivity web app where users can input their data which then stored to a file called data.db that I created beforehand. However, when I deploy it all the data from different users gather in one file (data.db). For example, user1 input their data. And the data will also appear on user2. How can I solve this problem, where each user have their own independent database. Kindly help me
Hi @Dylan_Mac , Welcome to the Streamlit community forum How about using Google Sheet as a Database? docs.streamlit.io Connect Streamlit to a private Google Sheet - Streamlit Docs Best, Avra
0
streamlit
Using Streamlit
Myapp.py not displaying in browser
https://discuss.streamlit.io/t/myapp-py-not-displaying-in-browser/20376
Hi all, I’m an absolute beginner at streamlit and quite new python/machine learning in general. I am trying to use streamlit to make a small app that takes inputs from a user and feeds them into an ML model and then displays a prediction. I have adapted code that I found in a tutorial here: Analytics Vidhya – 7 Dec 20 Model Deployment Using Streamlit | Deploy ML Models using Streamlit Streamlit is a popular open-source framework used for model deployment by machine learning and data science teams efficiently Est. reading time: 18 minutes My own code is as follows: %%writefile myapp.py import pickle import streamlit as st pickle_in = open(‘classifier.pkl’, ‘rb’) classifier = pickle.load(pickle_in) @st.cache() def prediction(d2, ex1, gx3, e1): if d2 == "Grade 0": d2 = 0 elif d2 == "Grade 1": d2 = 1 elif d2 == "Grade 2": d2 = 2 elif d2 == "Grade 3": d2 = 3 elif d2 == "Grade 4": d2 = 4 elif d2 == "Grade 5": d2 = 5 elif d2 == "Grade 6": d2 = 6 else: d2 = 0 if ex1 == "Grade 0": ex1 = 0 elif ex1 == "Grade 1": ex1 = 1 elif ex1 == "Grade 2": ex1 = 2 elif ex1 == "Grade 3": ex1 = 3 elif ex1 == "Grade 4": ex1 = 4 elif ex1 == "Grade 5": ex1 = 5 elif ex1 == "Grade 6": ex1 = 6 else: ex1 = 0 if gx3 == "Grade 0": gx3 = 0 elif gx3 == "Grade 1": gx3 = 1 elif gx3 == "Grade 2": gx3 = 2 elif gx3 == "Grade 3": gx3 = 3 elif gx3 == "Grade 4": gx3 = 4 elif gx3 == "Grade 5": gx3 = 5 elif gx3 == "Grade 6": gx3 = 6 else: gx3 = 0 ## mode value for gx3 if e1 == "Grade 0": e1 = 0 elif e1 == "Grade 1": e1 = 1 elif e1 == "Grade 2": e1 = 2 elif e1 == "Grade 3": e1 = 3 elif e1 == "Grade 4": e1 = 4 elif e1 == "Grade 5": e1 = 5 elif e1 == "Grade 6": e1 = 6 else: e1 = 0 ## mode value for e1 prediction = classifier.predict( [[d2, ex1, gx3, e1]]) if prediction == 0: pred = 'Grade 0' elif prediction == 1: pred = 'Grade 1' elif prediction == 2: pred = 'Grade 2' elif prediction == 3: pred = 'Grade 3' elif prediction == 4: pred = 'Grade 4' elif prediction == 5: pred = 'Grade 5' else: pred = 'Grade 6' return pred def main(): html_temp = """ <div style ="background-color:yellow;padding:13px"> <h1 style ="color:black;text-align:center;">Streamlit Loan Prediction ML App</h1> </div> """ st.markdown(html_temp, unsafe_allow_html = True) d2 = st.selectbox('d2 allergen result',("Grade 0","Grade 1","Grade 2","Grade 3","Grade 4","Grade 5","Grade 6", "Unknown")) ex1 = st.selectbox('ex1 allergen result',("Grade 0","Grade 1","Grade 2","Grade 3","Grade 4","Grade 5","Grade 6", "Unknown")) gx3 = st.selectbox('gx3 allergen result',("Grade 0","Grade 1","Grade 2","Grade 3","Grade 4","Grade 5","Grade 6", "Unknown")) e1 = st.selectbox('e1 allergen result',("Grade 0","Grade 1","Grade 2","Grade 3","Grade 4","Grade 5","Grade 6", "Unknown")) result ="" if st.button("Predict"): result = prediction(d2, ex1, gx3, e1) st.success('Predicted grade for d1: {}'.format(result)) print(pred) if __name__=='__main__': main() After running the command ‘streamlit run myapp.py’ in an anaconda environment my browser just displays an empty window. Can anybody help me here? Thanks Edit: Removed some formatting from my jupyter notebook
Hi all, just updating to say I see that my error was an incorrect indentation. Thanks!
1
streamlit
Using Streamlit
Getting an error “‘streamlit’ is not recognized as an internal or external command, operable program or batch file.”
https://discuss.streamlit.io/t/getting-an-error-streamlit-is-not-recognized-as-an-internal-or-external-command-operable-program-or-batch-file/361
Hi, I was trying to build a streamlit app. Performed the following steps: Activated my own environment using Ananconda prompt Installed streamlit using pip install streamlit Once installation is done, typed following command: streamlit hello Got the error “‘streamlit’ is not recognized as an internal or external command, operable program or batch file.” Please help, what exactly am I missing.
Hi @NitinKaushik, sorry to hear you’re having installation issues! I can’t reproduce your bug on my machine, so can you provide a bit more info so we can help debug? What operating system are you using? Also what OS version? What Conda version? What Python version? For steps (1) and (2) you posted above, can you provide the exact sequence of commands you used? For example: conda create --name myenv conda activate myenv pip install streamlit etc…
0
streamlit
Using Streamlit
Why does the variable ‘user_style’ not pass the if clause? Also, how do i make the program wait until the user enters a value in the text_input field?
https://discuss.streamlit.io/t/why-does-the-variable-user-style-not-pass-the-if-clause-also-how-do-i-make-the-program-wait-until-the-user-enters-a-value-in-the-text-input-field/20444
Here is the code snippet in question: st.write('The style for today will be ', style, '. If you would like to change this, enter it in the text box below.') user_style = st.text_input('Style','Casual') if(user_style != 'Casual' or user_style != 'Classy-casual' or user_style != 'Classy'): print('The value you entered is not an option. Style will remain ' + style) else: st.write('Style changed to ', user_style) style = user_style By debugging I find that user_style does get the default value of ‘Casual’, but the if statement evaluates true. How would I go about making the program wait until the user actually inputs a value in the text_input field? I ask this because some choices are made based on style and I want the user to be able to make their choice before the program continues.
Suggestion: You could replace your current if statement with the following line: if user_style in [ ‘Casual’, ‘Classy-casual’, ‘Classy’]: Solution: Add another if statement before your current if statement as below: If user_style != ‘’: and indent the rest of the lines as needed. Additional reading from Streamlit docs: st.stop() Also, remove ‘Casual’ from st.text_input line
1
streamlit
Using Streamlit
Editable Data Tables in Streamlit
https://discuss.streamlit.io/t/editable-data-tables-in-streamlit/529
Hello! Thank you to the dev team for making Streamlit, this is quite a brilliant, exiting and useful tool for data engineers who want to quickly and easily make front end app for data visualization. I am wondering if there is a way to insert editable data table, such as the one in Dash 313. It seems that editable datatable is a feature who does not exist in Plotly, so the plotly_chart() method won’t work. Thanks,
This would indeed be an incredible feature. It would be very useful to be able to read pandas dataframes into a Streamlit table and allow that table to be point and click editable and then read the values out of that table back into a dataframe.
0
streamlit
Using Streamlit
Clickable row in a dataframe
https://discuss.streamlit.io/t/clickable-row-in-a-dataframe/20399
Hello there! I have seen a few similar questions in the forum but this one is a little bit different. I am displaying a dataframe using streamlit and I would like the add the possibility of somehow clicking on a given row of the datafrane (irrespective of the column). When the use does so, a whole new dataframe is shown. In a sense, clicking on a row triggers the creation of a (row-dependent) new dataframe. Is this possible in streamlit? Thanks!
You can try third party component like Streamlit-Aggrid 13
0
streamlit
Using Streamlit
How can I download the file user have uploaded
https://discuss.streamlit.io/t/how-can-i-download-the-file-user-have-uploaded/20408
The user will upload .zip files how can i download them and unzip them also after he upload i want my app to make a signal for another .py file to run and the output of that will be in a folder that output i want to convert in zip ang give it to user after giving to the user i want the .zip files and the output files to be deleted the deleting part is option we can delete it mannually also because the site will be private but that part above means where we download zip extract it make another file run and give output that is in a folder to the user in zip format is must. Please Help!!
Check this blog, it may solve your problem https://blog.jcharistech.com/2021/01/21/how-to-save-uploaded-files-to-directory-in-streamlit-apps/ 3
0
streamlit
Using Streamlit
Show Images inside dataframes
https://discuss.streamlit.io/t/show-images-inside-dataframes/14219
Any updates on github.com/streamlit/streamlit Show Images inside dataframes 41 opened Aug 14, 2020 nthmost dataframe enhancement spec needed **User story:** - [I’m using the RDkit python packcage which allows to displa…y molecules.](https://discuss.streamlit.io/t/how-to-display-rdkit-molecules-within-the-dataframe/2980) I have them within my dataframe. I can see the molecules within jupyter notebooks withon pandas dataframe, but if I run that dataframe with Streamlit using st.write, all I get is html tags. - Jupyter notebook does this **The data looks like:** - _img_ tags within elements. (This is set by 3rd-party libraries, not by Streamlit users.) **Desired behavior:** - Display the image Current behavior: - Prints out the HTML as plaintext. **Questions:** - Does this imply we will have to process HTML? Maybe it doesn't. Maybe we just look for _img_ tags, which would absolve us of having to worry about code injection issues. - How will displaying images mess with display of the whole dataframe? From @treuille : Agreed that we can look for the _img_ tag rather than render arbitrary HTML. We will have to play around with the logic for how to size the image, but we could try to infer the width from the image (and an optional width attribute), while clamping it to a max width. Thanks/
Is there any way to show images inside dataframes? I have links of images as a column in the dataframe and I want to show them when I write dataframe. I know I can use “.to_html()” but I lost sort functionality in this case. Thanks
0
streamlit
Using Streamlit
Upload multiple images in bulk or as zip folder for app to loop over?
https://discuss.streamlit.io/t/upload-multiple-images-in-bulk-or-as-zip-folder-for-app-to-loop-over/20364
Hi all, I’d like to deploy a little streamlit app that loops over images I input and transforms them in a certain way. The amount of images Id like to loop over ranges from 10 to 10000 so I was wondering if there is a way to upload these in bulk or as zip folder so the script can unzip and process accordingly. So far I have tried to use the file_uploader function even with multi file upload set to true, but the single select at a time is not a workable solution so far. thanks in advance M
How about putting all the image filenames that you want to process, into a CSV file and then uploading that single CSV using the Streamlit file uploader? Your loop in the app processing the images can then be used to also read the images from disk before processing. You could repeat the above for multiple image file combinations in CSV files.
0
streamlit
Using Streamlit
Make component creation easier
https://discuss.streamlit.io/t/make-component-creation-easier/20366
Dear Streamlit Team I have a small request. Is there any way in the subsequent version of Streamlit, that you guys can make the creation of components easier and most importantly, possible, directly from Streamlit / python (without the inclusion of node / JS libs)? I guess all the guys currently creating components for Streamlit are veteran programmers, not budding ML / back office Excel enthusiasts. Can creating components be made as easy as creating Streamlit widgets? Just asking… (Thanks for Streamlit - it’s simply awesome)
@Shawn_Pereira - It’s pretty easy. Have a look at this static HTML component implementation - no fancy JS framework or external Node server required. GitHub - asehmi/streamlit-toggle-buttons-component: Pure static HTML/JS Streamlit component toggle button implementation 15
0
streamlit
Using Streamlit
Clear cache programmatically
https://discuss.streamlit.io/t/clear-cache-programmatically/19238
Is there a way to clear cache inside the python script? Tried the following but I assume the api is available no more: from streamlit import caching caching.clear_cache()
I’m curious about this also
0
streamlit
Using Streamlit
Is it possible to create a temporary folder with files?
https://discuss.streamlit.io/t/is-it-possible-to-create-a-temporary-folder-with-files/20370
Hello, I would like to know if it is possible to create a temporary folder with files, to zip them and after to export them as if the user was downloading the zip file. With the help of a button for example: def create(): .. st.button('Submit', on_click=create) Thank you very much.
Yes, you can create a temp folder using tempfile python module and either manually delete tempfolder using shutil or on exit tempfile module will delete the folder. [[ docs ]] https://docs.python.org/3/library/tempfile.html 2
0
streamlit
Using Streamlit
How to set log level to debug
https://discuss.streamlit.io/t/how-to-set-log-level-to-debug/4601
How can I set log_level to ‘debug’ via the command line when starting the server? Below is my failed attempt. Thanks. root@1ffe45d4b626:~/audbuild/2020_06_11_streamlit_audbuild# streamlit run audbuild.py --server.port=5001 --browser.serverAddress=0.0.0.0 --log_level=debug Usage: streamlit run [OPTIONS] TARGET [ARGS]… Try ‘streamlit run --help’ for help. Error: no such option: --log_level
Hi @dplutchok - It’s a mistake in the message (I’ll file an issue about it separately), the proper command is streamlit run pt.py --global.logLevel=debug github.com/streamlit/streamlit log_level parameter in CLI help is incorrect 49 opened Jul 30, 2020 randyzwitch streamlit help indicates that to set up logging, you use --log_level (embedcode) rzwitch@threadripper:~$ streamlit help Usage: streamlit [OPTIONS] COMMAND [ARGS]... Try out a... bug needs triage Best, Randy
1
streamlit
Using Streamlit
How to set the background color and text color of “st.header”,”st.write” etc. and let the text be showed at the left side of input and select box?
https://discuss.streamlit.io/t/how-to-set-the-background-color-and-text-color-of-st-header-st-write-etc-and-let-the-text-be-showed-at-the-left-side-of-input-and-select-box/11826
1.if we want the change the backgroud color or text color of st.header, st.write, st.info, st.success, st.warning and etc. how should we set in python program? 2.if we want to let the text be showed with the st.input and st.selectbox within same row(left side of input or select box), how should we set in python program? thank you.
I found a way to change the text background color, use different colors to replace st.header, st.write, st.success, st.warning code is like this: def header(url): st.markdown(f'<p style="background-color:#0066cc;color:#33ff33;font-size:24px;border-radius:2%;">{url}</p>', unsafe_allow_html=True) header(“notice”) and where you put ‘header(“notice”)’, the background color of text “notice” will change into “#0066cc” text color will be #33ff33 and font size will be 24px.
1
streamlit
Using Streamlit
AttributeError: ‘KMeans’ object has no attribute ‘_n_threads’
https://discuss.streamlit.io/t/attributeerror-kmeans-object-has-no-attribute-n-threads/12816
Hello, I created a KMeans model on some dataset, pickled it and then loaded it in the Streamlit app that I made. When I try to use this model in my app I get the following error: AttributeError: ‘KMeans’ object has no attribute ‘_n_threads’ When I searched this issue online I reached this stackoverflow question: python - 'KMeans' object has no attribute '_n_threads' - Stack Overflow 4, which made me realize this error might happen because of a difference between sklearn versions. The sklearn version on my machine is 0.22.1 whereas the sklearn that I added to the requirements.txt file for Streamlit isn’t pinned to a specific version. So I tried pinning it down to 0.22.1 but then I got this error: ERROR: Could not find a version that satisfies the requirement sklearn==0.22.1 (from versions: 0.0) ERROR: No matching distribution found for sklearn==0.22.1 [manager] installer returned a non-zero exit code I’ve also previously had ‘n_jobs=-1’ as a parameter in the pickled KMeans object and I know they mention in the documentation of sklearn.kmeans that this feature is deprecated in the newer version of sklearn. But since then I’ve tried to re-train my model without using n_jobs, pickled it, uploaded it to my Github, but I still get the same error above. How do I solve it? My Github where the app can be found: data_science/mushroom_project at main · idansul/data_science · GitHub My Streamlit app: https://share.streamlit.io/idansul/data_science/main/mushroom_project/web_app.py 1
Hi @Idan, welcome to the Streamlit community!! While you import sklearn in your scripts, the module’s name on PyPi 5 is actually scikit-learn. It’s really not obvious and a common mistake. You can fix it by replacing sklearn with scikit-learn or the specific version scikit-learn==0.22.1 in your requirements.txt file. Let us know if this helps! Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
Remove “Made with Streamlit” from bottom of app
https://discuss.streamlit.io/t/remove-made-with-streamlit-from-bottom-of-app/1370
Is there a way to remove or better yet, customize the " Made with Streamlit" comment at the bottom of the app pages? Thanks.
There is a github issue currently for removing the hamburger menu. Hamburger Menu: image716×770 22.9 KB The github issue. github.com/streamlit/streamlit Ability to hide the hamburger menu 200 opened Oct 14, 2019 tvst See: https://discuss.streamlit.io/t/how-do-i-hide-remove-the-menu-in-production/362 When developing a Streamlit app, the hamburger menu is quite useful. But afterwards, it has almost no use. Should we... enhancement spec needed I don’t see one for removing “made with streamlit”. I suggest making a github issue.
0
streamlit
Using Streamlit
How to not show the content of the unprocessed table?
https://discuss.streamlit.io/t/how-to-not-show-the-content-of-the-unprocessed-table/20348
Hello,my code contains a lot of table processing, but I just want to print the final result, why did these contents come out together? How can I remove them? ?898×906 24.2 KB
kxy09: [[macs] for macs in [macs]] Hi @kxy09, This line is interpreted as a magic command and implicitly wrapped with st.write(): [[macs] for macs in [macs]] You may want to comment it out. Any time Streamlit sees either a variable or literal value on its own line, it automatically writes that to your app using st.write . Best, Snehan
1
streamlit
Using Streamlit
Make Streamlit table results hyperlinks or add radio buttons to table?
https://discuss.streamlit.io/t/make-streamlit-table-results-hyperlinks-or-add-radio-buttons-to-table/7883
I have a large data set that I’m filtering through. After the user chooses the filters they want and clicks submit, I have a table that displays results (similar to the image below). image710×309 8.57 KB I want to make each entry in the “Link Number” column clickable. Is there a way to easily make the items in the list clickable with hyperlinks? Or does the hyperlink text need to just be included in the original dataframe? Or as another option, is there a way to show radio buttons for each line entry in a table? If so, is there a way to use that radio button to grab the text from the “Line Number” column then use that text in the URL?
Hey @srog, I dont think its easily doable with st.table but you sure can do it with bokeh. import streamlit as st import pandas as pd from bokeh.plotting import figure from bokeh.models import ColumnDataSource, CustomJS from bokeh.models import DataTable, TableColumn, HTMLTemplateFormatter df = pd.DataFrame({ "links": ["https://www.google.com", "https://streamlit.io", "https://outlook.com"], }) cds = ColumnDataSource(df) columns = [ TableColumn(field="links", title="links", formatter=HTMLTemplateFormatter(template='<a href="<%= value %>"target="_blank"><%= value %>')), ] p = DataTable(source=cds, columns=columns, css_classes=["my_table"]) st.bokeh_chart(p) Now if you want the text from the line number you need use a custom component, streamlit-bokeh-events something like this, import streamlit as st import pandas as pd from bokeh.plotting import figure from bokeh.models import ColumnDataSource, CustomJS from bokeh.models import DataTable, TableColumn, HTMLTemplateFormatter from streamlit_bokeh_events import streamlit_bokeh_events df = pd.DataFrame({ "links": ["https://www.google.com", "https://streamlit.io", "https://outlokk"], }) # create plot cds = ColumnDataSource(df) columns = [ TableColumn(field="links", title="links", formatter=HTMLTemplateFormatter(template='<a href="<%= value %>"target="_blank"><%= value %>')), ] # define events cds.selected.js_on_change( "indices", CustomJS( args=dict(source=cds), code=""" document.dispatchEvent( new CustomEvent("INDEX_SELECT", {detail: {data: source.selected.indices}}) ) """ ) ) p = DataTable(source=cds, columns=columns, css_classes=["my_table"]) result = streamlit_bokeh_events(bokeh_plot=p, events="INDEX_SELECT", key="foo", refresh_on_update=False, debounce_time=0, override_height=100) if result: if result.get("INDEX_SELECT"): st.write(df.iloc[result.get("INDEX_SELECT")["data"]]) This will work look like this, snippet949×897 530 KB Hope it helps !
0
streamlit
Using Streamlit
Take user inputs from Control Panel/Side Bar filters and save that info into a variable in the python script
https://discuss.streamlit.io/t/take-user-inputs-from-control-panel-side-bar-filters-and-save-that-info-into-a-variable-in-the-python-script/20342
Hi, I created a Streamlit page with several filters under the control panel/Side Bar. I need to store the selected data (in the filters) as a variable and use it in the actual python script to run other functions. Is there a way to do that? Right now I am getting empty returns. I am using a multi-select filter.
You’ll get your answers from this link: docs.streamlit.io Session State - Streamlit Docs 1 st.session_state is a way to share variables between reruns, for each user session.
0
streamlit
Using Streamlit
Upload Keras models or pickled files
https://discuss.streamlit.io/t/upload-keras-models-or-pickled-files/2246
Our current file_uplaoder is not able to upload machine learning models. Are you aware of any workaround? model_path = st.file_uploader("Choose a h5 file", type="h5") model = load_model(model_path) This gets me this error: unexpected type <class 'NoneType'> for filepath`` Any suggestions?
Hello @Abusnina, It’s a bit odd that the error refers to a filepath that looks like it’s None but the variable is not in the snippet you provided, so I guess it’s in the load_model method… Would you be able to provide a minimal reproducible example so we can dig into it ?
0
streamlit
Using Streamlit
St.dataframe header and index font color
https://discuss.streamlit.io/t/st-dataframe-header-and-index-font-color/19534
Hi community, How do I change the font size or color of the columns header in st.dataframe ? Right now the color is too bright. Any workaround? example: Blockquote import pandas as pd import streamlit as st data = { “calories”: [420, 380, 390], “duration”: [50, 40, 45] } df = pd.DataFrame(data) st.dataframe(df) Thanks in advance.
@ori a bit of css for these divs works just fine: div[class="ReactVirtualized__Grid table-bottom-left"] div, div[class="ReactVirtualized__Grid table-top-right"] div { color: red; }
0
streamlit
Using Streamlit
Fav Icon & Title Customization
https://discuss.streamlit.io/t/fav-icon-title-customization/10662
It would be nice to be able to change the FavIcon and Title for Streamlit apps
Bobby: I’ve tried that, but it still shows Streamlit in the title. It also temporarily shows “Streamlit” before loading custom title. Yeah it’s a known issue, there are some workarounds in this issue, it does involve tampering with the Streamlit install: github.com/streamlit/streamlit For beta_set_page_config, page_title still includes "Streamlit" 20 opened Aug 13, 2020 randyzwitch When running st.beta_set_page_config(page_title="streamlit-embedcode documentation",), the Streamlit app appends an extra · Streamlit value to the string: <title>streamlit-embedcode documentation · Streamlit</title> In letting the... enhancement product_review_needed Bobby: The favicon you can only set predefined icons. It accepts Twemoji icons but it should also accept types supported by st.image. EDIT: loading a favicon and displaying it works for me: from PIL import Image import streamlit as st im = Image.open("favicon.ico") st.set_page_config( page_title="Hello", page_icon=im, layout="wide", ) Fanilo
1
streamlit
Using Streamlit
Disable menu shortcuts (“r”,”c”)
https://discuss.streamlit.io/t/disable-menu-shortcuts-r-c/18458
First of all, I’m enjoying Streamlit a lot, so thanks I am looking for a way to disable the keyboard shortcuts assigned to “Rerun app” (shortcut: “r”) and “Clear cache” (shortcut: “c”) in the streamlit menu. Menu is hidden with the st.markdown “hack” but I want to disable the keyboard shortcuts too.
Hi again, Has anyone found a way to disable the “Rerun app” and "Clear cache keyboard shortcuts? Thanks in advance
0
streamlit
Using Streamlit
How to drop a column in dataframe
https://discuss.streamlit.io/t/how-to-drop-a-column-in-dataframe/20323
Hello, xx = {'tt': [{'a': '11', 'b': '22', 'c': '33'}, {'a':'44', 'b':'55', 'c':'66'}]} tt = xx['tt'] df = pd.DataFrame(tt) df.drop(columns=['b'], axis=1) st.write(df) Above code does still displays column ‘b’. How to remove it? TIA!
df.drop(columns=['b'], axis=1, inplace=True)
1
streamlit
Using Streamlit
Can I use Streamlit within a PyCharm development environment?
https://discuss.streamlit.io/t/can-i-use-streamlit-within-a-pycharm-development-environment/4837
I have successfully run Streamlit from the shell, eg: streamlit run mypythonscript.py Here Streamlit is the host application, getting the output from calls within the python script, eg: streamlit.dataframe() My question: Is it possible to run Streamlit where my python script is the host? Specifically, I would like to use Streamlit to allow me to browse through a dataframe that I have created within my python code. In essence similar to what one can do with matplotlib to plot data from within python. Thx.
Hi @miglto, welcome to the Streamlit community! Yes, you can run Streamlit from PyCharm in the same way you can run it from VSCode, Spyder, etc. In PyCharm, there is a terminal where you can run streamlit run app.py, and you can keep app.py open in PyCharm as a Python script. Every time you hit save on the script, the Streamlit app will change to reflect the results.
1
streamlit
Using Streamlit
Clear text_input
https://discuss.streamlit.io/t/clear-text-input/18884
Hello. Is there a way to clear a “text_input”? I created a “Question-Answering” App (this consists of loading a “context” and asking a question, an already trained HuggingFace model returns one or more answers). In my App the context (which is a document) is chosen with a “selectbox” and the question is defined in a “text_input”, after pressing “Enter” a “st.form” is executed showing several answers, each one accompanied of a “checkbox” so that the user can validate the result and update a dataset internally (which will help in the future to create a better model to our specific area). Validation is registered when clicking on “st.form_submit_button”. I would like that after clicking on “st.form_submit_button” the “text_input” can be cleared for a new query. I tried to achieve that with various approaches but was unsuccessful. I tried putting a “key” to the “text_input” so that its value is modified to empty ("") when the button “st.form_submit_button” was executed with a “callback”, this “callback” would modify the “key” of “text_input” to: “”, but it doesn’t work. I tried also using “st.empty” it also doesn’t work correctly, clean once and not clean the next and so on. I would appreciate any suggestions. Thank you.
This other question is related to the one I placed above: The example “Mirrored Widgets using Session State” (Session State for Streamlit. You can now store information across… | by abhi saini | Towards Data Science 9) is not working anymore as shown in the gift? I am not getting the same result on my PC, is there currently a way to reproduce the same result? Thank you!
0
streamlit
Using Streamlit
CSS Coding for Slider Bar
https://discuss.streamlit.io/t/css-coding-for-slider-bar/20256
I’m looking for help coding the design of a slider bar. Normally the end of the slider bar looks like this: When the option at the end of the slider is selected, it looks like this: On a mobile screen the label gets cut off like this: Instead of having the word run off the screen, I would prefer this: Does anyone know how to make this happen in streamlit? I should note that I only want the display:none for the left and right ends of the slider. The middle values should still show (if there are more than two values on the slider)
Hi @ryanlampkin, You can definitely make adjustments to the CSS via a “hack” by embedding CSS code (and also HTML codes) and unsafe_allow_html=True as input argument to the st.markdown() function. There’s a lively discussion about this here [1]. I’ve also used this approach to add a top navigation bar to Streamlit apps as shown in this video [2] this repo [3]. For your particular use case, I would recommend to inspect the names of the CSS elements in Google Chrome using View > Developer > Inspect Elements to figure out which elements needs to be altered. Links: Are you using HTML in Markdown? Tell us why! 4 Is it Possible to Add a Navigation Bar to Streamlit Apps? | Streamlit #29 - YouTube 1 GitHub - dataprofessor/streamlit_navbar 1 Hope this helps
1
streamlit
Using Streamlit
Styling only part of text in text_area
https://discuss.streamlit.io/t/styling-only-part-of-text-in-text-area/20260
Hello everyone, and thanks for the amazing work on Streamlit I have an application where I dynamically generate strings with the click of a button. I start from a user prompt in the text area, and then the generated string gets appended to it. I can do this multiple times. Is there a way to highlight in bold the generated part of the text only, in the text area?
You may not normally be able to do that in the text area widget, but if decide to write the text_area text to screen, you could probably repurpose this library. PyPI st-annotated-text 2 A simple component to display annotated text in Streamlit apps.
0
streamlit
Using Streamlit
Clear the text in text_input
https://discuss.streamlit.io/t/clear-the-text-in-text-input/2225
I can get the text entered by a user for streamlit.text_input. Is there a way to empty the text that was entered? It seems that I can only set the text in text_input when I first declared it like streamlit.text_input(‘Text’, ‘My Text’). Thanks.
Hi @demoacct, Looks like we still have an open documentation issue around this 1.1k! Thanks for the reminder. Check out the techniques discussed in the above issue thread and see if one of the ideas – e.g. using a button to reset the input – will work for you. Thanks!
0
streamlit
Using Streamlit
Unexpected session_state behaviour
https://discuss.streamlit.io/t/unexpected-session-state-behaviour/15216
I’m not sure if this is a bug or if I’m doing something wrong so I wanted to post here before raising an issue… import streamlit as st if 'text' not in st.session_state: st.session_state.text = 'text 1' st.session_state.number = 42 st.session_state.text = st.text_input('text', value=st.session_state.text) st.session_state.number = st.number_input('number', value=st.session_state.number) st.write(st.session_state.text) st.write(st.session_state.number) Steps to reproduce: Update the text - the two st.write calls at the bottom show the updated text & the original number as expected Update the number - the two st.write calls at the bottom show the update text & the updated number as expected Put the text back to its original value text 1 - the two st.write calls at the bottom show the original text & the updated number as expected Put the number back to its original value 42 - the two st.write calls at the bottom now show the updated text value (even though we just put it back to its original value in step 3) Can anybody see if this is a bug in the session_state or something wrong in my code? Here’s an animation if it helps show the behaviour I’m seeing… Thanks.
I had a similar issue, see here Callbacks - how to get current control value? - Using Streamlit - Streamlit 32 Setting the value by the value argument to number_input etc via session_state does not work.Rather define a key for the widget and set the intial value with some constant. If you use the key parameter, an entry for the widget is automatically created in the session_state dict. If you need to modify the value after the user has entered something, use a callback. I gues one problem in general is that while the streamlit code looks like normal python, the actual operation is determined by the streamlit engine and can be quite different to what the user expects.
1
streamlit
Using Streamlit
Fast real-time plot (100Hz)
https://discuss.streamlit.io/t/fast-real-time-plot-100hz/8155
Dear all, I am collecting data from a sensor with a sampling frequency of 100Hz. I would like to plot the data in real time as I receive them. I have tried: to animate matplotlib: How to animate a line chart 53, but this approach is too slow. to update altair chart with add_rows function: Appending to scatter chart sub-plots 26 , but I am not able to remove past data to keep visible in the chart only a certain amount of samples (e.g. 1000 samples) Would anybody be so kind to suggest me how to plot a stream of real-time data with streamlit? Thank you very much!!!
Hello, does anybody have any suggestion? Thank you again!
0
streamlit
Using Streamlit
Load_data is not executing, pls help. I need it asap
https://discuss.streamlit.io/t/load-data-is-not-executing-pls-help-i-need-it-asap/20236
image895×373 2.83 KB
Hi @Aquib_Aziz_Azizul_Ha, Looking at the code from the GitHub repo that you have provided, it seems from Lines 10-11 that the data range of the data being loaded by the load_data() function is spanning from Jan 1, 2015 to current date which would span 6 years, which may take some time to load. START = "2015-01-01" TODAY = date.today().strftime("%Y-%m-%d") You could try narrowing the time frame from time span of 6 years to something smaller such as 1 year and you’ll see that the app loads much quicker. Feel free to experiment with this. For example, you can adjust Line 10 to: START = "2021-01-01" Hope this helps
1
streamlit
Using Streamlit
Saving data from users into a CSV file
https://discuss.streamlit.io/t/saving-data-from-users-into-a-csv-file/20245
Hi, I want a web app which saves data from the user input and adds it into a CSV. The structure would be like this: import csv foo = "An" bar = None baz = "Example" fields = [foo, bar, baz] with open('Database.csv','a', newline='') as f: writer = csv.writer(f) writer.writerow(fields) How can I deploy this?
Hi @polgr98, Yes, you can easily spin up a Streamlit web app to do that. I would recommend to take a look at the Streamlit API Docs 1 which does a great job of showing what you can do with the various Streamlit functions with example codes. From what you described, you want to accept user input and write those to a CSV file. Building the Streamlit app Here’s what you can do to build the Streamlit app using 2 Streamlit functions (st.text_input and st.download_button): Use input widgets namely the st.text_input function to accept user text input. (Read more about st.text_input) Write user input to CSV file (what you already have) Encode the generated CSV file as a downloadable file via the st.download_button function (Read more about st.download_button 2) Deploying the Streamlit app You can easily deploy a Streamlit app using Streamlit Cloud 2 which has a free and team tier. More info on how to deploy a Streamlit app direct from the Streamlit Docs Further learning You can find some Streamlit tutorials on YouTube that you could follow, here are some: Playlist of 35 videos on Streamlit 1 from Data Professor 1 Playlist of 69 videos on Streamlit 1 from JCharisTech Playlist of 9 videos on Streamlit 1 from Avra 1 Playlist of 9 videos on Streamlit from Misra Turp Hope this helps!
0
streamlit
Using Streamlit
Session_state
https://discuss.streamlit.io/t/session-state/20104
May I know if there any way to prevent system to reset session state. The web page reset session_state to default state when I click button.
Can you provide some code? Or give more detail?
0
streamlit
Using Streamlit
Clear cache
https://discuss.streamlit.io/t/clear-cache/20244
I have been fighting with the cache function of Streamlit literally for days, and still am not able to achieve what I want. I want to achieve the following: On page load, load a dataset and cache it, so that next time when you load the page the dataset is retrieved from the cache Click on a button to update the dataset so that it is refreshed manually with the latest information How do I achieve this? This simple use case seems almost impossible to achieve. Help?
Hi @mmcnl - This forum post sounds like what you are trying to do: Clear cache with a time interval (at least once per hour)? Using Streamlit Here is a cached function, at_time is the timestamp used to control caching. @st.cache def get_phrase_data(start_date, end_date, phrases=None, at_time=None, **kwargs): """Wrapper for :func:`load_metadata_for_period` for Streamlit caching start_date and end_date should be ISO format strings in UTC for date """ #print('get_phrase_data', phrases) data = load_metadata_for_period(start_date, end_date, phrases=phrases, **… Ultimately, the cache function uses the function inputs to determine whether the data already exists in cache to be served. So you need to do something like pass a timestamp or other method of unique keys to your load data function, so that when you hit the button it passes a new value to your function. Best, Randy
0
streamlit
Using Streamlit
Bokeh 2.0 potentially broken in Streamlit
https://discuss.streamlit.io/t/bokeh-2-0-potentially-broken-in-streamlit/2025
There is a new Bokeh release that is coming up in the near future. It is a major number release. I tried the latest dev build and Streamlit did not render my bokeh plot, and gave no errors. This github issue 36 documents what I am referring to in a little more detail (bottom of thread). I just thought I would bring this to the attention of you all before its release. Thanks for the great tool!
Hello @likemo and welcome to the forums ! andfanilo: Oh, and a FR on Streamlit’s side : https://github.com/streamlit/streamlit/issues/1134 The Bokeh 2 upgrade has been merged into Streamlit 0.57. I think Streamlit before 0.57 only works with Bokeh 1.0 and Streamlit 0.57+ only works with Bokeh 2. Could you check your Bokeh/Streamlit versions ? And if it doesn’t work though the versions are ok, could you share a snippet of code so we can reproduce on our side many thanks !
1
streamlit
Using Streamlit
Bokeh chart doesn’t show
https://discuss.streamlit.io/t/bokeh-chart-doesnt-show/18132
Following the example in the docs 4 my app runs but no chart is displayed. There are no errors, but I do see a brief flash of blue on the screen which I think usually occurs before a plot is shown. I am confident the chart is created since I can save and download the html file if I try. I’ve tried chrome and safari. Any advice?
@robmarkcole am having same problem, have you been able to resolve
0
streamlit
Using Streamlit
Multiple Number Input Boxes
https://discuss.streamlit.io/t/multiple-number-input-boxes/20231
image1920×1007 48.1 KB image1920×1050 135 KB I am trying to change this tkinter page to Streamlit based on the picture that I have attached. My problem right now is I have a lot of multiple inputs. My intention is to develop a web app where the user needs to enter this multiple input boxes and once the user hit “Run/Submit”, it will generate a dataframe. Is there a way to do this in Streamlit? As you can see from the parameter on the sidebar, the user needs to fill in the inputs (all the parameters i.e. Gas Rate, CGR, WGR, PRES contains a similar input title. The only difference is the Reservoir Input). Once the user fill up all the input boxes (approximately 40 inputs), there will be a submit button and a dataframe will be generate. Hope someone can help me with this problem. Thank you.
Hi @Naqo, welcome to the Streamlit community! This sounds like a use-case for st.form: docs.streamlit.io st.form - Streamlit Docs 3 st.form creates a form that batches elements together with a “Submit” button. Best, Randy
0
streamlit
Using Streamlit
Cannot Mix List and non-list, non-null values
https://discuss.streamlit.io/t/cannot-mix-list-and-non-list-non-null-values/20219
I have a dataframe, total_df. It has a column called Assignee. It contains a list of dictionaries. I have written a function that iterates through the list, and pulls out my desired value, identified by the key “name” and adds it into a new list. I keep on getting the same error StreamlitAPIException : (‘cannot mix list and non-list, non-null values’, ‘Conversion failed for column Assignee with type object’) I haven’t been able to find any documentation regarding this error. Please advise.
Hi @Evan_Isenstein, welcome to the Streamlit forum! Without seeing the code and a data sample, it’s hard to say what the problem might be. Can you make a reproducible example and post it here? Best, Randy
0
streamlit
Using Streamlit
Changing color of a column
https://discuss.streamlit.io/t/changing-color-of-a-column/10175
Hi All, Is it possible to change the background color of a column? Example " left, right = st.beta_columns(2)" Is it possible to change the color of the “left” column here? Thanks in advance! A
I have an application for this too.
0
streamlit
Using Streamlit
Change backgroud
https://discuss.streamlit.io/t/change-backgroud/5653
Hi, I am new to streamlit and wanted to know that Is there any way to change the background of the streamlit app and add some custom colors or images to the background?
Hi @jeremy_ganem, welcome to the Streamlit community! This type of “hack” is pretty brittle, since it relies on the internal CSS selectors. Since this post was answered, we’ve been refactoring the Streamlit codebase, so it appears that the CSS selectors have changed. To fix this in the near-term, you would need to figure out what the new selectors would be. As a longer-term, more permanent solution, we’re working on releasing themeing in Streamlit, which will allow users to customize things in a safer way via Python. Best, Randy
1
streamlit
Using Streamlit
Interactively Cycling Through Data
https://discuss.streamlit.io/t/interactively-cycling-through-data/20165
I’m trying to use streamlit to build an app where the user can click through a series of datapoints and each will be plotted. To do this I have a doubly linked list of nodes, each indicating a data point the user can plot, and a next and previous button. I made two small callables to update the state of the current list node but that state doesn’t appear to change when the buttons are clicked. Is there a way to get the desired behavior with the out of the box widgets? I posted the code below in case someone can point me in the right direction, thanks! def move_next(data_node, node_name): data_node = data_node.next node_name.text(f"{data_node.val}") # define the file discovery variables args = _parse_args(sys.argv[1:]) coco_location = _find_coco(Path(args.root)) data_dirs = [Path(walk[0]) for walk in os.walk(coco_location.parent)][1:] data_node = _list_to_circular_linked_list(data_dirs) node_name = st.empty() next_button = st.button('next', on_click=lambda: move_next(data_node, node_name))
@isaak-willett I tried following your question, but it was difficult with the code snippet and description you gave. perhaps resubmit with a full working (or bugged) example with imports, functions, etc; or simplify the ask.
0
streamlit
Using Streamlit
Error installing
https://discuss.streamlit.io/t/error-installing/20074
“Im getting an error installing requirements” here’s the link to my app kindly assist https://share.streamlit.io/mimi-dotcom/fuel-guzzler-predictor-app/autopredictor.py 1
Hi @Mimi_SR, welcome to the Streamlit community!! You’re missing a dependency in your requirements.txt. The error is thrown because you’re importing a package (joblib) that hasn’t been installed. To fix the error, include joblib in your requirements file. Reference: ModuleNotFoundError No module named - Streamlit Docs Happy Streamlit-ing! Snehan
1
streamlit
Using Streamlit
How to dynamically create a number of columns and insert an element into each
https://discuss.streamlit.io/t/how-to-dynamically-create-a-number-of-columns-and-insert-an-element-into-each/8546
My app would involve allowing the user to choose the number of inputs he wishes to enter For example, at the top, there would be a select box asking the user for the number of inputs, say 1 to 5, I’ll call this n_input. And then, I would like there to be that number of select boxes to show up. So for example, the user selected “3” in the previous n_input select box, then 3 select boxes would show up which allow the user to input 3 items. This is not that difficult to accomplish: for i in range(n_input): input[i]=st.selectbox("Input # "+str(i),[1,2,3],key=i) However, I don’t know how to pack them into columns instead of just lining up vertically. The number of variables to unpack ranges from 1 to 7 so this requires some dynamic assignment. columns[1],columns[2],.....columns[n_words]=st.beta_columns(nwords) Surely, I could make a big if loop, if n_input==7: columns[1],columns[2],...,columns[7]=st.beta_columns(7) if n_input==6: columns[1],columns[2],...,columns[6]=st.beta_columns(6) if n_input==5: columns[1],columns[2],...,columns[5]=st.beta_columns(5) .... Is there a better way to do this?
Hi @terbiume65, welcome to the Streamlit community! You can accomplish what you are talking about using the following: import streamlit as st ncol = st.sidebar.number_input("Number of dynamic columns", 0, 20, 1) cols = st.beta_columns(ncol) for i, x in enumerate(cols): x.selectbox(f"Input # {i}",[1,2,3], key=i) Best, Randy
0
streamlit
Using Streamlit
Session_state initializing errors
https://discuss.streamlit.io/t/session-state-initializing-errors/20182
Hey I’ve been working on a website where you have to log in first before accessing the website. I’ve been using a checkbox to log in but I want to switch over to a button and using the session state function to get this to work. Only I’ve been getting this error “AttributeError: st.session_state has no attribute “load_state”. Did you forget to initialize it?” and I’ve no clue how to fix this. This is the code I’ve been using: import pyrebase import streamlit as st from matlab_integration_laptop import Matlab_Calc amount_of_peoples = 1 firebaseConfig = { "apiKey": "AIzaSyCxJfOQVBDT3cck7kMKJyCBgK8cdLCkeUI", "authDomain": "test-fireestore-streamlit.firebaseapp.com", "projectId": "test-fireestore-streamlit", "databaseURL": "https://test-fireestore-streamlit-default-rtdb.europe-west1.firebasedatabase.app/", "storageBucket": "test-fireestore-streamlit.appspot.com", "messagingSenderId": "110694863664", "appId": "1:110694863664:web:03f705aa4e180ff7762ef5", "measurementId": "G-2F25EY60QH" } firebase = pyrebase.initialize_app(firebaseConfig) auth = firebase.auth() db = firebase.database() storage = firebase.storage() st.sidebar.title("Our diabetes app") choice = st.sidebar.selectbox('login/signup',['Login','Sign up']) email = st.sidebar.text_input('Please enter your email address') password = st.sidebar.text_input('Please enter your password', type = 'password') if choice == 'Sign up': handle = st.sidebar.text_input('Please input your app username') submit = st.sidebar.button('Create my account') if submit: user = auth.create_user_with_email_and_password(email,password) st.success('Your account has been created successfully') st.balloons() user = auth.sign_in_with_email_and_password(email,password) db.child(user['localId']).child("Handle").set(handle) db.child(user['localId']).child("ID").set(user['localId']) st.title('Welcome '+handle) st.info('Login via login option') data_pd = {} weight_var = 0 if "load_state" not in st.session_state: st.session_state.load_state = False if choice == 'Login': login = st.sidebar.checkbox('Login') if login or st.session_state.load_state: st.session_state.load_state = True user = auth.sign_in_with_email_and_password(email,password) st.write('<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True) bio = st.radio('Choose an option:',['Home','Add food','Pick food','Base settings']) if bio == 'Base settings': if db.child(user['localId']).child("Weight").get().val() is not None: st.write("Your last weight input was "+str(db.child(user['localId']).child("Weight").get().val())+" kg") if db.child(user['localId']).child("Weight").get().val() is not None: weight_var = db.child(user['localId']).child("Weight").get().val() weight = st.number_input('Please enter your bodyweight (in kg)') weight_button = st.button('Submit!') if weight_button and weight != 0: if weight_var>weight: st.success("Great job!") db.child(user['localId']).child("Weight").set(weight) st.success('Your weight has been added successfully') elif bio == 'Home': st.write("Welcome to the Pentabetes diabetes tester!!") elif bio == 'Add food': Food_addition = st.text_input("Type the name of what food you want to add") Carb_addition = st.number_input("Amount of carbohydrates per 100 grams of chosen food") press_input = st.button("Add food") if press_input and Carb_addition != 0: data_pd[Food_addition] = Carb_addition db.child(user['localId']).child("Food").child(Food_addition).set(data_pd) st.success('Your food has been added successfully') elif bio == 'Pick food': if db.child(user['localId']).child("Food").get().val() is not None and db.child(user['localId']).child("Weight").get().val() is not None: data_pd_1 = db.child(user['localId']).child("Food").get().val() weight_1 = db.child(user['localId']).child("Weight").get().val() Chosen_food = st.selectbox("Select food you want to eat",data_pd_1) Amount_food = st.number_input("grams of "+Chosen_food+" you want to eat") time = st.number_input('Time until consumption (min)') Select_food = st.button("Calculate food") Add_food = st.checkbox("Add second food item") if Select_food and weight_1 != None: carb_100 = db.child(user['localId']).child("Food").child(Chosen_food).get().val() carbs = ((((carb_100[Chosen_food])/100)*1000)*Amount_food) Test_1 = Matlab_Calc(amount_of_peoples, weight_1, carbs, time) if Test_1 == 'YES GOOD YES EAT': st.success("You can eat "+str(Amount_food)+" grams of "+Chosen_food) else: st.error("You cannot eat "+str(Amount_food)+" grams of "+Chosen_food) if Add_food: Chosen_food_1 = st.selectbox("Select second food you want to eat",data_pd_1) Amount_food_1 = st.number_input("grams of "+Chosen_food_1+" you want to eat ") Select_food_1 = st.button("Calculate first and second food items") Add_food_1 = st.checkbox("Add third food item") if Select_food_1 and weight_1 != None: carb_100 = db.child(user['localId']).child("Food").child(Chosen_food).get().val() carb_100_1 = db.child(user['localId']).child("Food").child(Chosen_food_1).get().val() carbs_1 = (((((carb_100_1[Chosen_food_1])/100)*1000)*Amount_food_1)+((((carb_100[Chosen_food])/100)*1000)*Amount_food)) Test_1_1 = Matlab_Calc(amount_of_peoples, weight_1, carbs_1, time) if Test_1_1 == 'YES GOOD YES EAT': st.success("You can eat "+str(Amount_food)+" grams of "+Chosen_food+" and "+str(Amount_food_1)+" grams of "+Chosen_food_1) else: st.error("You cannot eat "+str(Amount_food)+" grams of "+Chosen_food+" and "+str(Amount_food_1)+" grams of "+Chosen_food_1) if Add_food_1: Chosen_food_2 = st.selectbox("Select third food you want to eat",data_pd_1) Amount_food_2 = st.number_input("grams of "+Chosen_food_2+" you want to eat ") Select_food_2 = st.button("Calculate all food items") if Select_food_2 and weight_1 != None: carb_100 = db.child(user['localId']).child("Food").child(Chosen_food).get().val() carb_100_1 = db.child(user['localId']).child("Food").child(Chosen_food_1).get().val() carb_100_2 = db.child(user['localId']).child("Food").child(Chosen_food_2).get().val() carbs_2 = (((((carb_100_1[Chosen_food_1])/100)*1000)*Amount_food_1)+((((carb_100[Chosen_food])/100)*1000)*Amount_food)+((((carb_100_2[Chosen_food_2])/100)*1000)*Amount_food_2)) Test_1_2 = Matlab_Calc(amount_of_peoples, weight_1, carbs_2, time) if Test_1_2 == 'YES GOOD YES EAT': st.success("You can eat "+str(Amount_food)+" grams of "+Chosen_food+" and "+str(Amount_food_1)+" grams of "+Chosen_food_1+" and "+str(Amount_food_2)+" grams of "+Chosen_food_2) else: st.error("You cannot eat "+str(Amount_food)+" grams of "+Chosen_food+" and "+str(Amount_food_1)+" grams of "+Chosen_food_1+" and "+str(Amount_food_2)+" grams of "+Chosen_food_2) elif db.child(user['localId']).child("Food").get().val() is None and db.child(user['localId']).child("Weight").get().val() is not None: st.info('Please add food') elif db.child(user['localId']).child("Weight").get().val() is None and db.child(user['localId']).child("Food").get().val() is not None : st.info('Please add your weight in the base settings') elif db.child(user['localId']).child("Weight").get().val() is None and db.child(user['localId']).child("Food").get().val() is None: st.info('Please add your weight in the base settings') st.info('Please add food') ```
Hi @Jeroen_Frieling , Welcome to the Streamlit community forum If I’m not wrong, we ( @andfanilo ) spoke about this error before . Thank you for the code snippet. I went through it quickly, I don’t see any issue with session state initializing (though I’ve not tried it!) I would like to request you to try session state code snippet from the Streamlit doc . Does that work for you? Best Avra
0
streamlit
Using Streamlit
Persitend and responsive input widgets
https://discuss.streamlit.io/t/persitend-and-responsive-input-widgets/20114
I think its easiest to understand the question if you test the code snippet below. You will notice that the first input widget behaves responsive, but restores to default vaule if you hide it and render again. The second input widget keeps it vaule if you, re-render it, but only changes the value every 2nd attempt to change it. But how do i get an input widget, which can keep it’s value but behaves responsive? import streamlit as st # Initialise Session Sate if "value_two" not in st.session_state: st.session_state["value_two"]=20 # for navigation select=st.radio(label="",options=["Setting responsive","Setting persistent"]) if select=="Setting responsive": st.warning(""" Good: Changing values behaves as expected Bad: If you switch to the other settings and back, all values will be restored to default""") st.session_state["value_one"]=st.number_input(label="Setting One",value=20,key="Key One") if select == "Setting persistent": st.info(""" Good: If you switch to the other Settings and back those values will stay the same Bad: Try changeing the same value multiple times in sucession. You will notice it changes only every other time""") st.session_state["value_two"]=st.number_input(label="Setting Two",value=st.session_state["value_two"],key= "Key Two") Related, but the proposed solution of @ksxx leads to the resoreing to default behaviour. Multiselect only updating for every second input Using Streamlit When choosing from the multiselectbox below, I find that I have to click the options twice in order for it to register in the streamlit application. By default the select shows the years 2017-2019. If I then click ‘2016’ it shows 2016-2019, correctly. If I then click ‘2015’ it show 2016-2019 once again. If I then click ‘2015’ once again, it shows 2015-2019, which is correct. I want the multiselect to default to the latest y1-input always, since the application has multiple pages, which the …
Hi @BenediktPrusas, I haven’t had a chance to test your code locally yet but I wanted to pop by and see if a recent Knowledge Base article from our docs might help. Widget updating for every second input when using session state 4 The key things to take away here: use a call-back function to update your app’s variable before the script re-runs make sure you’re using the values stored in your session state and not the return values of widgets specifically in your case: You’re assigning a key directly to a number input, creating the number input on a different line and adding it to session state with a key. Then in your call back set your value_one to the number inputs value. Hopefully, this helps! Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
How to activate my custom theme?
https://discuss.streamlit.io/t/how-to-activate-my-custom-theme/20171
Hi there, I’m trying to create a custom coloured theme for an app I’m making but for some reason it’s not working. Can someone help me? Here’s a link to my github with the config.toml file: streamlit_app_v1/config.toml at main · daniellambert95/streamlit_app_v1 · GitHub 2 Here’s a link to the app I created but the standard theme is activated… https://share.streamlit.io/daniellambert95/streamlit_app_v1/main/main.py 1 If anyone could help it would be highly appreciated!
I resolved it by rebooting the app in my Streamlit account
1
streamlit
Using Streamlit
Can’t display Holoviews Chord graph
https://discuss.streamlit.io/t/cant-display-holoviews-chord-graph/11614
Hi, I am trying to build a chord graph using holoviews, following this example https://holoviews.org/reference/elements/bokeh/Chord.html 7 this works just fine in a colab notebook, but I can not get it to work in streamlit I tried fig = hv.Chord(links) p = hv.render(fig, backend=‘bokeh’) st.bokeh_chart(p) but I get: ‘Figure’ object has no attribute ‘traverse’ If i output with st.write(type(p)) I get <class ‘bokeh.plotting.figure.Figure’> TIA for any help
@randyzwitch I’m having the same problem
0
streamlit
Using Streamlit
Turn vertical bar chart to horizontal?
https://discuss.streamlit.io/t/turn-vertical-bar-chart-to-horizontal/20107
Hi, Is it possible to turn vertical bar chart to horizontal? I use this example. Instead of 50 bars showing vertically, I want the whole chart to turn 90degree right. That is x-axis (y-axis) with 3 values, y-axis (vertical) with 50 values. docs.streamlit.io st.bar_chart - Streamlit Docs 2 st.bar_chart displays a bar chart. I tried the following 4 ways and does not work. Original: chart_data = pd.DataFrame( np.random.randn(50, 3), columns=["a", "b", "c"]) chart_data = pd.DataFrame( np.random.randn(50, 3), index=[“a”, “b”, “c”]) 2. ``` chart_data = pd.DataFrame( np.random.randn(50, 3), columns=["a", "b", "c"], rotation = 90) 3. chart_data = pd.DataFrame( np.random.randn(50, 3), columns=["a", "b", "c"], rotation = "vertical") 4. chart_data = pd.DataFrame( np.random.randn(50, 3), columns=["a", "b", "c"], rotation = "horizontal")
Hi @hahahazel, I adapted your original code to create a horizontal stacked bar chart with Altair and plot it with st.altair_chart(): Code import streamlit as st import pandas as pd import numpy as np import altair as alt chart_data = pd.DataFrame( np.random.rand(9, 4), index=["air","coffee","orange","whitebread","potato","wine","beer","wheatbread","carrot"], ) # Vertical stacked bar chart st.bar_chart(chart_data) # Convert wide-form data to long-form # See: https://altair-viz.github.io/user_guide/data.html#long-form-vs-wide-form-data data = pd.melt(chart_data.reset_index(), id_vars=["index"]) # Horizontal stacked bar chart chart = ( alt.Chart(data) .mark_bar() .encode( x=alt.X("value", type="quantitative", title=""), y=alt.Y("index", type="nominal", title=""), color=alt.Color("variable", type="nominal", title=""), order=alt.Order("variable", sort="descending"), ) ) st.altair_chart(chart, use_container_width=True) Ouput image844×637 21.4 KB Best, Snehan
1
streamlit
Using Streamlit
Is it possible to convert dataframe records into bootstrap card?
https://discuss.streamlit.io/t/is-it-possible-to-convert-dataframe-records-into-bootstrap-card/20134
i am building streamlit app that is connected to sql server database where it allow the user to perform some basic CRUD tasks. It also allow the use to search for the required data and fro now it display the data as dataframe table. What i am asking is’t possible to convert each returned record of this dataframe into a bootstrap card ? until now i a was able to embed bootstrap code using st.markdown() but this allow to add a one static card, what i want is to display bootstrap cards equal to the returned result of the dataframe.
Yep, so something like: for index, row in st.session_state.df.iterrows(): st.markdown(self.card_template.format(str(index + 1), paper_url, row['title'], row['authors'], row['published_year'], row['journal'], row['doi'], row['score'], row['abstract']), unsafe_allow_html=True) where the template might be: self.card_template = """ <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <div class="card bg-light mb-3" > <H5 class="card-header">{}. <a href={} style="display: inline-block" target="_blank">{}</h5> <div class="card-body"> <span class="card-text"><b>Author(s): </b>{}</span><br/> <span class="card-text"><b>Year: </b>{}</span><br/> <span class="card-text"><b>Journal: </b>{}</span><br/> <span class="card-text"><b>DOI: </b>{}</span><br/> <span class="card-text"><b>Score: </b>{}</span><br/><br/> <p class="card-text">{}</p> </div> </div> </div> """ For a variety of out-of-box cards, have a look here: getbootstrap.com Cards 5 Bootstrap’s cards provide a flexible and extensible content container with multiple variants and options.
1
streamlit
Using Streamlit
Is there a method for navigating to a particular anchor within the webapp?
https://discuss.streamlit.io/t/is-there-a-method-for-navigating-to-a-particular-anchor-within-the-webapp/20013
Is there any Streamlit method for navigating to a particular anchor within the webapp. If a title has an anchor for example is there any way to get the page to navigate to that particular section?
Hi @jamestaylor, Anchors are automatically added to header text. For example, if you define a header text using: st.header("Section 1") Then you can create a link to this header using: st.markdown("[Section 1](#section-1)", unsafe_allow_html=True) I’ve also created a demo app showing this in action (https://share.streamlit.io/dataprofessor/streamlit/main/anchor_app.py 4) And the corresponding code on GitHub is available here (streamlit/anchor_app.py at main · dataprofessor/streamlit · GitHub 3) Hope this helps
0
streamlit
Using Streamlit
Streamlit_app.py — “This file does not exist”
https://discuss.streamlit.io/t/streamlit-app-py-this-file-does-not-exist/20002
Hi, I am new to Streamlit. I set up the account and follow the instructions to link my Github. I have a school project in Github that I would like to deploy in Streamlit. When I try to deploy the app, under “Main file path” , “streamlit_app.py” is already by default but when I click “Deploy”. It said “This file does not exist”. See screenshot. Any advice is much appreciated! Screenshot 2021-12-13 at 18.04.251512×1118 105 KB
Hi @hahahazel, First, welcome to the Streamlit community! Can you link your GitHub repo that you’re deploying from? Happy Streamlit-ing! Marisa
0
streamlit
Using Streamlit
How to prevent the reloading of the whole page when I let the user to perform an action
https://discuss.streamlit.io/t/how-to-prevent-the-reloading-of-the-whole-page-when-i-let-the-user-to-perform-an-action/10800
Hello everyone, I am building a page which let the user to run a query against my database, once I have the data I would like to perform a simple exploratory data analysis of the data. The problem arise when, at button of the page, I let the user choose any column of the data set with a selectbox to make a countplot. When the user perform that action, every single element of my page is rendered again and it creates a really poor user experience with the page. When I load the data I use the decorator of cache with the allow_output_mutation option set true
Hi @Capi_hacendado - Re-running top-to-bottom is the core of the Streamlit execution model, and where you don’t want to re-run things you can use st.cache (which you’ve indicated you’re using). So it sounds like you are doing what you’re supposed to. Can you post a code snippet that demonstrates the problem? Best, Randy
0
streamlit
Using Streamlit
How can I add title in the centre of the page?
https://discuss.streamlit.io/t/how-can-i-add-title-in-the-centre-of-the-page/20105
how can I add title in the centre of the page? How can I adjust the text alignment?
Hi, you can see solution from this link: A way to build your own unique text and header Show the Community! you can choose the different colors to as your background, and you can define what information you want to tell. here is the code: # -*- coding: utf-8 -*- import streamlit as st col1, col2 ,col3= st.beta_columns(3) with col1: color1 = st.color_picker('选择渐变起始颜色', '#1aa3ff',key=1) st.write(f"你选择了{color1}") with col2: color2 = st.color_picker('选择渐变结尾颜色', '#00ff00',key=2) st.write(f"你选择了{color2}") with col3: color3 = st.color_picker('选择文字颜色', '#ffffff',key=3) st.writ…
0
streamlit
Using Streamlit
Image and text next to each other
https://discuss.streamlit.io/t/image-and-text-next-to-each-other/7627
Hi, I’m struggling to do some fairly rookie HTML stuff and searching for answers on this channel or trying to implement the answers I found on StackOverflow haven’t helped. I have two problems. First, I have a local image that I want to display (st.image works, but doesn’t work because I can’t find where the media directory is hosted! The more important problem is how do I render a text and image next to each other, like a logo and the name? This is for an open source tool. Thanks for providing an awesome tool to get started quickly. Best wishes, Dinesh
Hey @ddutt, Why not use our beloved markdown ? , I whipped up something for you it might do the job better for you. import streamlit as st import base64 LOGO_IMAGE = "logo.png" st.markdown( """ <style> .container { display: flex; } .logo-text { font-weight:700 !important; font-size:50px !important; color: #f9a01b !important; padding-top: 75px !important; } .logo-img { float:right; } </style> """, unsafe_allow_html=True ) st.markdown( f""" <div class="container"> <img class="logo-img" src="data:image/png;base64,{base64.b64encode(open(LOGO_IMAGE, "rb").read()).decode()}"> <p class="logo-text">Logo Much ?</p> </div> """, unsafe_allow_html=True ) It will look like this, snippet1725×829 690 KB Sorry for the abhorrent code though Hope it helps !
1
streamlit
Using Streamlit
Trying to make a graph slideshow using (altair, html, css, js)
https://discuss.streamlit.io/t/trying-to-make-a-graph-slideshow-using-altair-html-css-js/14253
Intent: Want to create a script that: Create altair charts Saves and embeds them into html slideshow skeleton Uses components.html to show html in streamlit I have found resources (below) for tackling some of the problems but still struggle to combined them. I suspect it is from my lack of knowledge about html/css/js and was wondering if anyone could fill int he gaps and combine them? Saving Altair Charts to HTML Multiple Charts in one HTML · Issue #1422 · altair-viz/altair · GitHub import altair as alt import pandas as pd two_charts_template = """ <!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/vega@{vega_version}"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@{vegalite_version}"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@{vegaembed_version}"></script> </head> <body> <div id="vis1"></div> <div id="vis2"></div> <script type="text/javascript"> vegaEmbed('#vis1', {spec1}).catch(console.error); vegaEmbed('#vis2', {spec2}).catch(console.error); </script> </body> </html> """ df = pd.DataFrame({'x': range(5), 'y': range(5)}) chart1 = alt.Chart(df).mark_point().encode(x='x', y='y') chart2 = alt.Chart(df).mark_line().encode(x='x', y='y') with open('charts.html', 'w') as f: f.write(two_charts_template.format( vega_version=alt.VEGA_VERSION, vegalite_version=alt.VEGALITE_VERSION, vegaembed_version=alt.VEGAEMBED_VERSION, spec1=chart1.to_json(indent=None), spec2=chart2.to_json(indent=None), )) Making a slide show using html, css, js How To Create a Slideshow 1 <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * {box-sizing: border-box} body {font-family: Verdana, sans-serif; margin:0} .mySlides {display: none} img {vertical-align: middle;} /* Slideshow container */ .slideshow-container { max-width: 1000px; position: relative; margin: auto; } /* Next & previous buttons */ .prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; user-select: none; } /* Position the "next button" to the right */ .next { right: 0; border-radius: 3px 0 0 3px; } /* On hover, add a black background color with a little bit see-through */ .prev:hover, .next:hover { background-color: rgba(0,0,0,0.8); } /* Caption text */ .text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center; } /* Number text (1/3 etc) */ .numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0; } /* The dots/bullets/indicators */ .dot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .active, .dot:hover { background-color: #717171; } /* Fading animation */ .fade { -webkit-animation-name: fade; -webkit-animation-duration: 1.5s; animation-name: fade; animation-duration: 1.5s; } @-webkit-keyframes fade { from {opacity: .4} to {opacity: 1} } @keyframes fade { from {opacity: .4} to {opacity: 1} } /* On smaller screens, decrease text size */ @media only screen and (max-width: 300px) { .prev, .next,.text {font-size: 11px} } </style> </head> <body> <div class="slideshow-container"> <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img src="img_nature_wide.jpg" style="width:100%"> <div class="text">Caption Text</div> </div> <div class="mySlides fade"> <div class="numbertext">2 / 3</div> <img src="img_snow_wide.jpg" style="width:100%"> <div class="text">Caption Two</div> </div> <div class="mySlides fade"> <div class="numbertext">3 / 3</div> <img src="img_mountains_wide.jpg" style="width:100%"> <div class="text">Caption Three</div> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> </div> <br> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> <script> var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; } </script> </body> </html>
Got the fix to my problem. I’m not a full-stack expert, so the solution may be rough but it works. My initial problems arise because the python replace method would have issues when javascript and CSS were in the same HTML file. So i seperated them into separate files, read them using open() into a python script where I eventually combined them. Python import streamlit as st import streamlit.components.v1 as components import altair as alt from vega_datasets import data cars = data.cars() st.title('Altair Slideshow') chart1 = alt.Chart(cars).mark_point().encode( x='Horsepower:Q', y='Miles_per_Gallon:Q', color='Origin:N' ) chart2 = alt.Chart(cars).mark_bar().encode( x=alt.X('Miles_per_Gallon', bin=alt.Bin(maxbins=30)), y='count()', color='Origin' ) chart3 = alt.Chart(cars).mark_area(opacity=0.3).encode( x=alt.X('Year', timeUnit='year'), y=alt.Y('ci0(Miles_per_Gallon)', axis=alt.Axis(title='Miles per Gallon')), y2='ci1(Miles_per_Gallon)', color='Origin' ).properties( width=800 ) html = open('slide.html', 'r').read() css = open('style.css', 'r').read() js = open('script.js', 'r').read() html = html.format( css_styler=css, slide_script=js, vega_version=alt.VEGA_VERSION, vegalite_version=alt.VEGALITE_VERSION, vegaembed_version=alt.VEGAEMBED_VERSION, spec1=chart1.to_json(indent=None), spec2=chart2.to_json(indent=None), spec3=chart3.to_json(indent=None) ) components.html(html, height=800,scrolling=True) HTML (slide.html) <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> {css_styler} </style> <script src="https://cdn.jsdelivr.net/npm/vega@{vega_version}"></script> <script src="https://cdn.jsdelivr.net/npm/vega-lite@{vegalite_version}"></script> <script src="https://cdn.jsdelivr.net/npm/vega-embed@{vegaembed_version}"></script> </head> <body> <div class="slideshow-container"> <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <div id="vis1"></div> <div class="text">Caption Text</div> </div> <div class="mySlides fade"> <div class="numbertext">2 / 3</div> <div id="vis2"></div> <div class="text">Caption Two</div> </div> <div class="mySlides fade"> <div class="numbertext">3 / 3</div> <div id="vis3"></div> <div class="text">Caption Three</div> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> </div> <br> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> <script> {slide_script} </script> <script type="text/javascript"> vegaEmbed('#vis1', {spec1}).catch(console.error); vegaEmbed('#vis2', {spec2}).catch(console.error); vegaEmbed('#vis3', {spec3}).catch(console.error); </script> </body> </html> CSS (style.css) * {box-sizing: border-box} body {font-family: Verdana, sans-serif; margin:0} .mySlides {display: none} img {vertical-align: middle;} /* Slideshow container */ .slideshow-container { max-width: 1000px; position: relative; margin: auto; } /* Next & previous buttons */ .prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; user-select: none; } /* Position the "next button" to the right */ .next { right: 0; border-radius: 3px 0 0 3px; } /* On hover, add a black background color with a little bit see-through */ .prev:hover, .next:hover { background-color: rgba(0,0,0,0.8); } /* Caption text */ .text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center; } /* Number text (1/3 etc) */ .numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0; } /* The dots/bullets/indicators */ .dot { cursor: pointer; height: 15px; width: 15px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .active, .dot:hover { background-color: #717171; } /* Fading animation */ .fade { -webkit-animation-name: fade; -webkit-animation-duration: 1.5s; animation-name: fade; animation-duration: 1.5s; } @-webkit-keyframes fade { from {opacity: .4} to {opacity: 1} } @keyframes fade { from {opacity: .4} to {opacity: 1} } /* On smaller screens, decrease text size */ @media only screen and (max-width: 300px) { .prev, .next,.text {font-size: 11px} } JS (script.js) var slideIndex = 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex-1].style.display = "block"; dots[slideIndex-1].className += " active"; } Next step: Need to edit python script., to be able to dynamically increase the number of graphs.
1
streamlit
Using Streamlit
Is it possible to get uploaded file file name?
https://discuss.streamlit.io/t/is-it-possible-to-get-uploaded-file-file-name/7586
using st.file_upload, you can see the file name on the GUI, but is there a way to retrieve that file name in python? I’m building an uploader that uploads file to S3, it would be nice to preserve the original file name after upload
As it returns a file io like object, try accessing the .name attribute on the file object that you receive.
0