NumHDonors_cutoff = st.sidebar.slider( label="NumHDonors", min_value=0, max_value=15, value=5, step=10, ) NumHAcceptors_cutoff = st.sidebar.slider( label="NumHAcceptors", min_value=0, max_value=20, value=10, step=1, ) df_result = df[df["MW"] < weight_cutoff] df_result2 = df_result[df_result["LogP"] < logp_cutoff] df_result3 = df_result2[df_result2["NumHDonors"] < NumHDonors_cutoff] df_result4 = df_result3[df_result3["NumHAcceptors"] < NumHAcceptors_cutoff] st.write(df_result4.shape) st.write(df_result4) raw_html = mols2grid.display( df_result4, subset=["Name", "img", "MW", "LogP", "NumHDonors", "NumHacceptors"], mapping={ "smiles": "SMILES", "generic_name": "Name" })._repr_html() components.html(raw_html, width=900, height=1100, scrolling=False)
def write(text, c='black', height=50): html = f""" {bs()} <p style='color:{c}'>{text}</p>""" return components.html(html, height=height)
train_int_col.image(train_inp_example, caption="INPUT EXAMPLE", width=250) train_inp_example = torch.tensor(train_inp_example) train_out_example = preprocess(uploaded_out_example, image_size=TRAINING_IMAGE_SIZE[0:2], gray_scale=False) train_out_col.image(train_out_example, caption="OUTPUT EXAMPLE", width=250) train_out_example = torch.tensor(train_out_example) # image = preprocess(uploaded_file, image_size=IMAGE_SIZE[0:2], gray_scale=False) image = preprocess(uploaded_file, image_size=OUTPUT_IMAGE_SIZE[0:2], gray_scale=False) input_col.image(image, width=250, caption='input image') net.add(train_inp_example, train_out_example) output = net(torch.tensor(image)).numpy() output_col.image(output, width=250, caption='output image') # st.write(net.graph) net.graph.write_html('graph.html') # components.html(net.graph.html, height) components.html(net.graph.html, height=600) # st.write(html) # # image = torch.rand(IMAGE_SIZE) # rand_input_col.image(image.numpy(), width=250, caption='random input image') # output = net(torch.tensor(image)).numpy() # rand_output_col.image(output, width=250, caption='output image')
ql.update(best_models) #n_iter = 2 #for i in range(n_iter): # qg.fit(train, threads=8, show=None) # model_graph_holder.markdown(render_svg(qg[0]._repr_svg_()),unsafe_allow_html=True) # model_iter_holder.write(f"Iteration:{i+1}/{n_iter}") # ql.update(qg.best()) # my_bar.progress(i/n_iter + 1/n_iter) model_iter_holder.write("Done") with st.beta_expander("Model Validation on the Training Data"): # Plot Summary components.html(models[0].plot(train)._repr_html_(), height=600, width=800) #col1, col2 = st.beta_columns(2) #fig_roc, ax = plt.subplots() #models[0].plot_roc_curve(train) #col1.pyplot(fig_roc) #fig_confusion, ax = plt.subplots() #models[0].plot_confusion_matrix(train) #col2.pyplot(fig_confusion) with st.beta_expander("Model Validation on the Test Data"): # Plot Summary components.html(models[0].plot(test)._repr_html_(), height=600, width=800)
def display(text, c='black', s=1, height=70): html = f""" {bs()} <h1 class='display-{s}' style='color:{c}'>{text}</h1>""" return components.html(html, height=height)
st.markdown(hide_streamlit_style, unsafe_allow_html=True) if page == 'Home': # Additional sidebar st.sidebar.markdown('### FAQ') if st.sidebar.button('Not sure how to pronounce my name?'): st.sidebar.audio('media/sound-name.mp3') # Main page avatar = "<img src='data:image/png;base64,{}' class='img-fluid rounded-circle mx-auto d-block' style='max-width:25%'>".format( img_to_bytes("media/avatar.png")) st.write(avatar, unsafe_allow_html=True) st.write(read_markdown_file("content/intro.md"), unsafe_allow_html=True) components.html(socia_media_links, height=40) elif page == 'Projects': # Additional sidebar st.sidebar.markdown('### Tech Demo') sentiment_test = TextBlob( st.sidebar.text_input('Sentiment Polarity & Subjectivity')) if sentiment_test: st.sidebar.markdown(f""" Polarity: {round(sentiment_test.sentiment.polarity,2)} Subjectivity: {round(sentiment_test.sentiment.subjectivity,2)} """) st.sidebar.markdown('---') feedback = st.sidebar.text_input('Feedback')
def render_entities(raw_text): docx = nlp(raw_text) html = displacy.render(docx, style='ent') html = html.replace("\n\n", "\n") result = HTML_WRAPPER.format(html) stc.html(result, height=1000)
from jinja2 import Environment, FileSystemLoader import streamlit.components.v1 as components import streamlit as st st.title("Hello Lottie-web !") loop = st.checkbox("Loop animation", True) with open('data.json') as json_file: lottie_data = json_file.read() env = Environment(loader=FileSystemLoader('./'), trim_blocks=True, lstrip_blocks=True) template = env.get_template('template.html.jinja') html_data = template.render(data=lottie_data, loop=str(loop).lower()) components.html(html_data, height=800)
def main(): """A Simple Summarization NLP App""" st.title("NLP App with Streamlit") menu = ["Home", "NLP(files)", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Home: Analyse Text") raw_text = st.text_area("Enter Text Here") num_of_most_common = st.sidebar.number_input("Most Common Tokens", 5, 15) if st.button("Analyze"): with st.beta_expander("Original Text"): st.write(raw_text) with st.beta_expander("Text Analysis"): token_result_df = text_analyzer(raw_text) st.dataframe(token_result_df) with st.beta_expander("Entities"): # entity_result = get_entities(raw_text) # st.write(entity_result) entity_result = render_entities(raw_text) # st.write(entity_result) stc.html(entity_result, height=1000, scrolling=True) # Layouts col1, col2 = st.beta_columns(2) with col1: with st.beta_expander("Word Stats"): st.info("Word Statistics") docx = nt.TextFrame(raw_text) st.write(docx.word_stats()) with st.beta_expander("Top Keywords"): st.info("Top Keywords/Tokens") processed_text = nfx.remove_stopwords(raw_text) keywords = get_most_common_tokens( processed_text, num_of_most_common ) st.write(keywords) with st.beta_expander("Sentiment"): sent_result = get_sentiment(raw_text) st.write(sent_result) with col2: with st.beta_expander("Plot Word Freq"): fig = plt.figure() # sns.countplot(token_result_df['Token']) top_keywords = get_most_common_tokens( processed_text, num_of_most_common ) plt.bar(keywords.keys(), top_keywords.values()) plt.xticks(rotation=45) st.pyplot(fig) with st.beta_expander("Plot Part of Speech"): try: fig = plt.figure() sns.countplot(token_result_df["PoS"]) plt.xticks(rotation=45) st.pyplot(fig) except: st.warning("Insufficient Data: Must be more than 2") with st.beta_expander("Plot Wordcloud"): try: plot_wordcloud(raw_text) except: st.warning("Insufficient Data: Must be more than 2") with st.beta_expander("Download Text Analysis Result"): make_downloadable(token_result_df) elif choice == "NLP(files)": st.subheader("NLP Task") text_file = st.file_uploader("Upload Files", type=["pdf", "docx", "txt"]) num_of_most_common = st.sidebar.number_input("Most Common Tokens", 5, 15) if text_file is not None: if text_file.type == "application/pdf": raw_text = read_pdf(text_file) # st.write(raw_text) elif text_file.type == "text/plain": # st.write(text_file.read()) # read as bytes raw_text = str(text_file.read(), "utf-8") # st.write(raw_text) else: raw_text = docx2txt.process(text_file) # st.write(raw_text) with st.beta_expander("Original Text"): st.write(raw_text) with st.beta_expander("Text Analysis"): token_result_df = text_analyzer(raw_text) st.dataframe(token_result_df) with st.beta_expander("Entities"): # entity_result = get_entities(raw_text) # st.write(entity_result) entity_result = render_entities(raw_text) # st.write(entity_result) stc.html(entity_result, height=1000, scrolling=True) # Layouts col1, col2 = st.beta_columns(2) with col1: with st.beta_expander("Word Stats"): st.info("Word Statistics") docx = nt.TextFrame(raw_text) st.write(docx.word_stats()) with st.beta_expander("Top Keywords"): st.info("Top Keywords/Tokens") processed_text = nfx.remove_stopwords(raw_text) keywords = get_most_common_tokens( processed_text, num_of_most_common ) st.write(keywords) with st.beta_expander("Sentiment"): sent_result = get_sentiment(raw_text) st.write(sent_result) with col2: with st.beta_expander("Plot Word Freq"): fig = plt.figure() # sns.countplot(token_result_df['Token']) top_keywords = get_most_common_tokens( processed_text, num_of_most_common ) plt.bar(keywords.keys(), top_keywords.values()) plt.xticks(rotation=45) st.pyplot(fig) with st.beta_expander("Plot Part of Speech"): try: fig = plt.figure() sns.countplot(token_result_df["PoS"]) plt.xticks(rotation=45) st.pyplot(fig) except: st.warning("Insufficient Data") with st.beta_expander("Plot Wordcloud"): try: plot_wordcloud(raw_text) except: st.warning("Insufficient Data") with st.beta_expander("Download Text Analysis Result"): make_downloadable(token_result_df) else: st.subheader("About")
background-image: none; color: #ffffff }</style>""", unsafe_allow_html=True) #st.title("Record and Analyze Blast Operation Data") menu = ["Home","Login","SignUp"] choice = st.sidebar.selectbox("Menu",menu) if choice == "Home": components.html(""" <style> .city { background-color: rgb(159, 177, 188); color: white; border: 1px solid black; margin: 5px; padding: 5px; text-align: center; font-size:35px !important; font-family:"B mitra", serif; } </style> <body> <div class="city"><h2>واحد آموزش و نیروی انسانی</h2></div> """,width=750, height=200, scrolling=False) pic = Image.open('LOGO.jpg') st.image(pic,width=500) #pi = Image.open('p.jpg') #st.image(pi, use_column_width=True) st.markdown(""" <style>
def displayData(split_data): # Function to display data which has been split global html_text process_data = True processing_info = st.empty() progress_bar = st.empty() cancel_button = st.empty() bar = progress_bar.progress(0) cancel = cancel_button.button('Cancel Processing') if cancel: process_data = False html_text = """<!DOCTYPE html> <html> <head> <style> .pass { color:black } .fail { color:red } .text-left { text-align: left; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: center; padding: 5px; } /*table thead tr{ display:block; } table tbody{ display:block; height:380px; overflow:auto;//set tbody to auto } */ .headers { background-color: #dddddd; } </style> </head> <body> <table width="100%"> <thead> <tr> <th width="64%">Clause</th> <th width="11%">Acceptance Probability (%)</th> <th width="12%">Acceptable(0), Unacceptable(1)</th> <th width="11%">Disagree?</th> </tr></thead> <tbody>""" index_for_display = 0 for data in split_data: index_for_display = index_for_display + 1 if len(data) <= 0: continue if not process_data: break if data.find("Title:") >= 0: html_text = html_text + """ <tr class="headers"> <td colspan="4" class="text-left"> """ + data[ 6:] + """</td> </tr>""" else: processing_info.text("Processing " + str(index_for_display) + " of " + str(len(split_data)) + " clauses") bar.progress(index_for_display / len(split_data)) bar.progress(index_for_display / len(split_data)) prediction_result = predictor.predict(data) df2 = prediction_result.iloc[[-1]] row_class = "pass" if df2['prediction'].values[0] == 1: row_class = "fail" html_text = html_text + """ <tr class=""" + row_class + """> <td width="65%" class="text-left"> """ + html.escape( data) + """</td> <td width="11%"> """ + str(df2['acceptable_probability'].values[0]) + """</td> <td width="12%">""" + str(df2['prediction'].values[0]) + """</td> <td><span id='recording_""" + str( index_for_display ) + """' style='display:none'>Recorded</span><button type="button" class="btn btn-warning" onclick="this.style.display = 'none';document.getElementById( 'recording_""" + str( index_for_display ) + """').style.display = 'block'">Disagree</button></td> </tr>""" html_text = html_text + """ </tbody> </table> </body> </html> """ processing_info.empty() progress_bar.empty() cancel_button.empty() st.subheader('Assessment Result') components.html(html_text, width=None, height=700, scrolling=True)
import streamlit.components.v1 as components import qrcode from PIL import Image from PIL import Image img = Image.open("qrcode.jpg") st.image(img, width=700) html_code = """ <div style="background-color: #3cba54 ; padding: 10px; border-radius: 10px"> <h1 style="color:white; text-align: center">QR Code Generator</h1> </div> """ components.html(html_code) # Add the data to QR data = st.text_input("Enter the data you want to embed") data_title = data.title() # Number Inputs box_size = st.number_input("Enter the box size") border = st.number_input("Enter the border spacing value") # Select Box Inputs from matplotlib import colors as mcolors colors = mcolors.CSS4_COLORS
def st_dtree(plot, height=None): dtree_html = f'<body>{viz.svg()}</body>' components.html(dtree_html, height=height)
import streamlit as st import streamlit.components.v1 as components # bootstrap 4 collapse example components.html( """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Тег SCRIPT</title> </head> <body> <script type="text/javascript"> document.write ('<table width="100%" border="1">'); for (i=1; i<6; i++) { document.writeln("<tr>"); for (j=1; j<6; j++) document.write("<td>" + i + j + "<\/td>"); document.writeln("<\/tr>"); } document.write ("<\/table> "); </script> </body> </html> """, height=100, ) #components.iframe("https://docs.streamlit.io/en/latest") st.markdown('Streamlit is **_really_ cool**.')
def main(): menu = ["Home", "Pandas Profile", "Sweetviz", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Pandas Profile": st.subheader("Automated EDA with Pandas Profile") data_file = st.file_uploader("Upload CSV", type=['csv']) st.set_option('deprecation.showfileUploaderEncoding', False) if data_file is not None: df = pd.read_csv(data_file) st.dataframe(df.head()) profile = ProfileReport(df) st_profile_report(profile) elif choice == "Sweetviz": st.subheader("Automated EDA with Sweetviz") data_file = st.file_uploader("Upload CSV", type=['csv']) st.set_option('deprecation.showfileUploaderEncoding', False) if data_file is not None: df = pd.read_csv(data_file) st.dataframe(df.head()) if st.button("Generate Sweetviz Report"): st_display_sweetviz("SWEETVIZ_REPORT.html") #Normal Workflow (save .html) #report = sv.analyze(df) #report.show_html() elif choice == "About": st.subheader("Onur Erdogan tarafından yapılmıstır") #components.iframe('https://www.google.com) else: st.subheader("Home") components.html(""" <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="https://www.w3schools.com/howto/img_snow_wide.jpg" style="width:100%"> <div class="text">Caption Text</div> </div> <div class="mySlides fade"> <div class="numbertext">2 / 3</div> <img src="https://www.w3schools.com/howto/img_nature_wide.jpg" style="width:100%"> <div class="text">Caption Two</div> </div> <div class="mySlides fade"> <div class="numbertext">3 / 3</div> <img src="https://www.w3schools.com/howto/img_mountains_wide.jpg" style="width:100%"> <div class="text">Caption Three</div> </div> <a class="prev" onclick="plusSlides(-1)">❮</a> <a class="next" onclick="plusSlides(1)">❯</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> """)
import streamlit.components.v1 as components from pyecharts import options as opts from pyecharts.charts import Bar c = ( Bar().add_xaxis( ["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"]).add_yaxis( '2017-2018 Revenue in (billion $)', [21.2, 20.4, 10.3, 6.08, 4, 2.2]).set_global_opts( title_opts=opts.TitleOpts(title="Top cloud providers 2018", subtitle="2017-2018 Revenue"), toolbox_opts=opts.ToolboxOpts()).render_embed( ) # generate a local HTML file ) components.html(c, width=1000, height=1000)
def st_display_sweetviz(report_html, width=1000, height=500): report_file = codecs.open(report_html, 'r') page = report_file.read() components.html(page, width=width, height=height, scrolling=True)
return img if fn == "Clifford": st.markdown("""## Clifford Attractor""") st.latex("x_{n +1} = \sin(%2.1f y_{n}) + %2.1f \cos(%2.1f x_{n})" % (a, c, a)) st.latex("y_{n +1} = \sin(%2.1f x_{n}) + %2.1f \cos(%2.1f y_{n})" % (b, d, b)) g = dsplot(Clifford, (0, 0, a, b, c, d), plotsize, cmap=palette[cmap][::-1]) components.html(g._repr_html_(), height=plotsize + 10, width=plotsize + 10) elif fn == "De Jong": st.markdown("""## De Jong Attractor""") st.latex("x_{n +1} = \sin(%2.1f y_{n}) - \cos(%2.1f x_{n})" % (a, b)) st.latex("y_{n +1} = \sin(%2.1f x_{n}) - \cos(%2.1f y_{n})" % (c, d)) dg = dsplot(De_Jong, (0, 0, a, b, c, d), plotsize, cmap=palette[cmap][::-1]) components.html(dg._repr_html_(), height=plotsize + 10, width=plotsize + 10)
def st_shap(plot, height=None): shap_html = f"<head>{shap.getjs()}</head><body>{plot.html()}</body>" components.html(shap_html, height=height)
def write(): st.subheader("Data Cleaning") df = pd.read_csv('data/ljubljana_categories.csv', sep=',') # Drop location duplicates st.success( 'If multiple rows have the same GPS coordinates, only the last one is kept.' ) # Renaming id column df.columns = df.columns.str.lower() df = df.drop_duplicates(subset=['latitude', 'longitude'], keep='last') df = df.reset_index(drop=True) # Adding a distance df_d = df.assign(distance=0) for i in range(len(df_d) - 1): j = i + 1 df_d.loc[j, 'distance'] = round( distance((df_d.latitude[i], df_d.longitude[i]), (df_d.latitude[j], df_d.longitude[j])) * 1000, 2) # Filtering for min. and max. distances st.subheader('Plausibility tests') data_points = len(df_d) slide_max = int(df_d['distance'].max()) + 10 dist = st.slider( 'Select a range of plausible distances beween observations to be included: ', 0, slide_max, (0, 200)) df_d = df_d[(df_d['distance'] >= dist[0]) & (df_d['distance'] <= dist[1])] filtered_points = len(df_d) message = 'Minimum distance is ' + str(dist[0]) + ' meters and maximum distance is ' + str(dist[1]) + ' meters. Your data are reduced by: ' + \ str(round(100 * (1 - filtered_points / data_points), 2)) + \ ' %. Using the slider, you can change these values and see the effect in the table below. There are ' + \ str(filtered_points) + ' data rows now.' st.success(message) # Display DataFrame df_d = df_d.reset_index(drop=True) st.dataframe(df_d[[ 'time', 'latitude', 'longitude', 'distance', 'sats', 'precision', 'category' ]].style.background_gradient(subset=['distance', 'precision'], cmap='Blues')) # Safe new data frame st.markdown(get_table_download_link(df_d), unsafe_allow_html=True) # Pairwise Viz st.subheader("Pairwise comparison of mapping data") fig2 = plt.subplots() fig2 = sns.pairplot( df_d[['latitude', 'longitude', 'rawtime', 'category', 'distance']], markers=["o", "s", "D", "*"]) # hue='Category' st.pyplot(fig2) # Use of categories col1, col2 = st.beta_columns(2) col1.info('This bar chart shows the usage frequency per category.') cat = df_d[['category']].groupby(['category']).size() catSeries = pd.Series([0, 0, 0, 0, 0, 0]) catSeries = catSeries[1:6] for x in cat.index: catSeries[x] = cat[x] fig, ax = plt.subplots() ax = sns.barplot(x=catSeries.index, y=catSeries) col1.pyplot(fig) # GPS quality col2.info( 'This bar chart indicates the quality of your GPS coordinates. 5+ is good.' ) satDistribution = df_d.groupby( df_d['sats']).size().sort_values(ascending=False) satNum = list(satDistribution.keys()) satFreq = list(satDistribution) fig2, ax2 = plt.subplots() ax2 = sns.barplot(x=satNum, y=satFreq) col2.pyplot(fig2) # category coloring # tracks_d = categories.assign(Distance=0) df_d['color'] = "" df_d['color'] = df_d['color'].astype('object') cat_color = { 1: [0, 0, 255, 250], # Blue 2: [255, 0, 0, 250], # Red 3: [0, 255, 0, 250], # Green 4: [255, 106, 0, 250], # Orange 5: [0, 88, 0, 250] # Dark Green } for i in range(len(df_d)): df_d.at[i, 'color'] = cat_color[df_d.at[i, 'category']] st.subheader("Data Map") st.info( "... let's draw maps! You can choose the size of markers (4-12 is recommended) and the map's background." ) marker = st.number_input('Marker Size: ', min_value=2, value=8) MapColor = { "Dark": 'mapbox://styles/innodesign/ckl128luk027z17mwftpdxyg1', "Light": 'mapbox://styles/mapbox/streets-v8', } map_col = st.radio("Map Background: ", list(MapColor.keys())) data = df_d[['latitude', 'longitude', 'color']] midpoint = (np.average(data['latitude']), np.average(data['longitude'])) st.info('Centre coordinates of the map: ' + str(round(midpoint[0], 4)) + ' and ' + str(round(midpoint[1], 4))) components.html(""" <h4 style="font-family: Verdana, sans-serif">Color coding of categories:</h4> <ul style="font-family: Verdana, sans-serif; background-color: rgb(219, 213, 213)"> <li style="color: rgb(0, 0, 255); list-style: none; background-color: rgb(219, 213, 213)"> Category 1: Blue</li> <li style="color: rgb(255, 0, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 2: Red</li> <li style="color: rgb(0, 255, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 3: Green</li> <li style="color: rgb(255, 106, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 4: Orange</li> <li style="color: rgb(0, 88, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 5: Dark Green</li> <li style="color: rgb(219, 213, 213); list-style: none; background-color: rgb(219, 213, 213)"..<li> </ul> """, height=180) st.pydeck_chart( pdk.Deck( # map_style='mapbox://styles/mapbox/dark-v9', # map_style='mapbox://styles/mapbox/streets-v8', map_style=MapColor[map_col], initial_view_state=pdk.ViewState( latitude=midpoint[0], longitude=midpoint[1], zoom=13, pitch=0, ), layers=pdk.Layer( "ScatterplotLayer", # type='HexagonLayer' / ScatterplotLayer / PointCloudLayer, data=data, get_position='[longitude, latitude]', elevation_scale=4, get_fill_color='color', get_radius=marker, opacity=0.5, filled=True))) st.info( 'The heatmap below gives an impression of those areas, where most observations have been mapped. The more you zoom in, the more fine grained the aggregation becomes.' ) st.pydeck_chart( pdk.Deck(map_style=MapColor[map_col], initial_view_state=pdk.ViewState( latitude=midpoint[0], longitude=midpoint[1], zoom=13, pitch=0, ), layers=pdk.Layer( "HeatmapLayer", data=data, get_position='[longitude, latitude]', get_fill_color='color', opacity=0.9, aggregation='MEAN', )))
return y_pred.pooler_output.tolist() def rgb_to_hex(rgb): r, g, b = int(min(rgb[0], 1) * 255), int(min(rgb[1], 1) * 255), int( min(rgb[2], 1) * 255) return '#{:02x}{:02x}{:02x}'.format(r, g, b) def code_to_rgb(code): return [int(code[1:3], 16), int(code[3:5], 16), int(code[5:7], 16)] def render_color_markdown(texts, colors): span_tags = [ f'<span style="font-weight: bold; color: {rgb_to_hex(color)}">{text}</span>' for text, color in zip(texts, colors) ] return ' '.join(span_tags) tokenizer, model = tokenizer(), load_model() text = st.text_input('text', 'apple cherry peach grape orange watermelon strawberry') if len(text) != 0: texts = text.split(' ') rgbs = texts_to_words(texts, model) components.html(render_color_markdown(texts, rgbs))
def st_shap(plot, height=200,width=870): shap_html = f"<head>{shap.getjs()}</head><body>{plot.html()}</body>" components.html(shap_html, height=height,width=width)
def header(text, c='black', s=1, height=50): html = f""" {bs()} <h{s} style='color:{c}'>{text}</h{s}>""" return components.html(html, height=height)
#Adding the data kepler_map.add_data(data=gdf_city_edge, name='city lockdown') kepler_map.add_data(data=gdf.drop(['loc'], axis = 1), name='location') kepler_map.add_data(data=gdf_lockdown.drop(['loc'], axis = 1), name = 'lockdown') #Adding the config kepler_map.config = config #Transform to a html file kepler_map_html = kepler_map._repr_html_() return(kepler_map_html) except : st.text('location not found ! 😲') #Header st.title('Interactive lockdown map from your location') #Subheader st.subheader('Made with ❤️ by Basile Goussard') #User input user_input = st.text_input("Your location", 'Planches, Trouville') #Building the map components.html(main(user_input), width=700, height=700)
def lead(text, c='black', height=50): html = f""" {bs()} <p class='lead' style='color:{c}'>{text}</p>""" return components.html(html, height=height)
import streamlit.components.v1 as components # type: ignore from jinja2 import Template with open("src/apps/components/action_button.html") as fo: button_template = Template(fo.read()) components.html(button_template.render(state=None), height=64)
df = pd.read_csv(url) #df = df.set_index(pd.Datetimeindex('Date') #df.set_index(pd.DatetimeIndex('Date'), inplace=True) return df #-------------------------------------------------# # Title HTML_BANNER = """ <div style="background-color:#8B0000;padding:10px;border-radius:10px"> <h1 style="color:white;text-align:center;">Crypto Currency Analysis</h1> <p style="color:white;text-align:center;">Built with: [email protected]</p> </div> """ stc.html(HTML_BANNER) st.markdown(''' **Description:** This is web app `Crypto Coins` currency Analysis ''') #-----------------------------------------------------------------# #main df = load_dataset() df['Date'] = pd.to_datetime(df['Date']) df.set_index('Date', inplace=True) menu = ['Analysis', 'Visualizations'] choice = st.sidebar.selectbox('Menu', menu) analysis_menu = ['Show Data Structure', 'Daily Analysis']
components.html( """ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script> </head> <body> <div class="p-3 mb-2 bg-light text-dark"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-caret-right-fill" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path d="M12.14 8.753l-5.482 4.796c-.646.566-1.658.106-1.658-.753V3.204a1 1 0 0 1 1.659-.753l5.48 4.796a1 1 0 0 1 0 1.506z"/> </svg> <a class="navbar-brand" href="#">My Portfolio</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#academicdetails">Education</a> </li> <li class="nav-item"> <a class="nav-link" href="#skills">Skill Set</a> </li> <li class="nav-item"> <a class="nav-link" href="#certs">Workshops</a> </li> <li class="nav-item"> <a class="nav-link" href="#project">Hobbies</a> </li> <li class="nav-item"> <a class="nav-link" href="#project">contact Me</a> </li> </ul> </nav> <hr> <h6 class="mt-0">Sravani Bommireddy</h6> <button type="button" class="btn btn-dark">BSC-MSCs</button> </div> <hr> <h6>Career Objective </h6> <p>Looking for a challenging career to show the best of my professional ability, skills and techniques to enhance my knowledge and growth in Electronics and communication industry.</p> <hr> <div id = "academicdetails"> <u> <h6>Academic Details </h6> </u> <table class="table table-hover table-white"> <thead> <tr> <th scope="col">Qualification</th> <th scope="col">College/School</th> <th scope="col">GPA/Percentage</th> <th scope="col">Passing Year</th> </tr> </thead> <tbody> <tr> <th scope="row">BSC-MSCs</th> <td>St.Ann's College for Women.</td> <td>6.7</td> <td>2020</td> </tr> <tr> <th scope="row">InterMediate</th> <td>Sri Gayatri </td> <td>80%</td> <td>2017</td> </tr> <tr> <th scope="row">SSC</th> <td>St Anns High School</td> <td>8.3</td> <td>2015</td> </tr> </tbody> </table> </div> <hr> <div id = "skills"> <u> <h6> Skill Set (on scale of 5)</h6> </u> <ul class="list-group"> <li class="list-group-item d-flex justify-content-between align-items-center"> C-programming <span class="badge badge-primary badge-pill">4</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> Java <span class="badge badge-primary badge-pill">3</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> Python <span class="badge badge-primary badge-pill">4.5</span> </li> <li class="list-group-item d-flex justify-content-between align-items-center"> HTML <span class="badge badge-primary badge-pill">4</span> </li> </ul> </ul> </div> <hr> <div id= "worsh"> <u> <h6> Workshops </h6> </u> <p> <ul> <li> Presented a project titled Advance Cyber Attacks and its threats 2017.</li> <li> Participated in a workshop on Appreciation and Applications of Data Science, Hyderabad in 2018.</li> <li> Participated in a workshop Buisness Data Analysis Management and Innovation, Hyderabad in 2019.</li> <li> Participated in a National Colloquium on works of a Giant Statistician Prof.C.R.Rao AIMSCS, UoH campus, Hyderabad in 2019. </li> </ul> </div> <hr> <div id="hob"> <u> <h6>Hobbies</h6> </u> <p> <ul> <li> Listening to music </li> <li> Watching movies </li> <li> Reading books </li> </ul> </p> </div> <hr> </nav> </div> <div class="card"> <button type="button" class="btn btn-light">Contact Me</button> <div class="card-body"> <span style="padding-left:200px"> <p>Email : [email protected] </p> <span style="padding-left:200px"> <p> Mobile no :+91 7287035697 </p> <span style="padding-left:200px"> <p> LinkedIn Profile :sravanibommireddy </p> </div> </div> </body> """, height=2200, )
def app(): st.write(""" # S&P 500 Stock Analyzer Shown below are the **Fundamentals**, **News Sentiment**, **Bollinger Bands** and **Comprehensive Report (Compared with SPY as a whole as benchmark)** of your selected stock! """) st.markdown("***") st.sidebar.header('User Input Parameters') symbol, start, end = user_input_features() start = pd.to_datetime(start) end = pd.to_datetime(end) #symbol1 = get_symbol(symbol.upper()) #st.subheader(symbol1) stock = finvizfinance(symbol.lower()) stock_chart = stock.ticker_charts() st.image(stock_chart) # Read data data = yf.download(symbol, start, end, threads=False) # ## SMA and EMA #Simple Moving Average data['SMA'] = talib.SMA(data['Adj Close'], timeperiod=20) # Exponential Moving Average data['EMA'] = talib.EMA(data['Adj Close'], timeperiod=20) # Plot st.subheader(f""" Simple Moving Average vs. Exponential Moving Average\n {symbol} """) st.line_chart(data[['Adj Close', 'SMA', 'EMA']]) # Bollinger Bands data['upper_band'], data['middle_band'], data['lower_band'] = talib.BBANDS( data['Adj Close'], timeperiod=20) # Plot st.subheader(f""" Bollinger Bands\n {symbol} """) st.line_chart( data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']]) # ## MACD (Moving Average Convergence Divergence) # MACD data['macd'], data['macdsignal'], data['macdhist'] = talib.MACD( data['Adj Close'], fastperiod=12, slowperiod=26, signalperiod=9) # Plot st.subheader(f""" Moving Average Convergence Divergence\n {symbol} """) st.line_chart(data[['macd', 'macdsignal']]) # ## RSI (Relative Strength Index) # RSI data['RSI'] = talib.RSI(data['Adj Close'], timeperiod=14) # Plot st.subheader(f""" Relative Strength Index\n {symbol} """) st.line_chart(data['RSI']) st.markdown("***") st.subheader("Fundamentals: ") st.dataframe(get_fundamentals(symbol)) st.markdown("***") # ## Latest News st.subheader("Latest News: ") st.table(get_news(symbol).head(5)) st.markdown("***") # ## Recent Insider Trades st.subheader("Recent Insider Trades: ") st.table(get_insider(symbol).head(5)) st.markdown("***") st.write("Generating comprehensive stock report...") st.write("**please wait for some time... **") st.write( "This section will compare the historical performance of your selected stock with SPDR S&P 500 Trust ETF (Ticker: SPY) as benchmark." ) stock_report(symbol) # ## Stock report st.subheader(f"""**{symbol} Stock Report**""") #st.header(symbol + " Stock Report") HtmlFile = open("report.html", 'r', encoding='utf-8') source_code = HtmlFile.read() #print(source_code) components.html(source_code, height=9000) st.write( "Disclaimer: The data are collected from Google, Yahoo Finance and Finviz" )
#PIL or pillow will be used to perform different image transformation operations from PIL import Image #streamlit is the latest webapp framework for data driven apps import streamlit as st #Drawable canvas will be used to get the data/image from the canvas from streamlit_drawable_canvas import st_canvas #components will be used to render html import streamlit.components.v1 as components # Render the h1 block, contained in a frame of size 200xY. #st.markdown method will be used to get settings from style.css file st.markdown('<style>' + open('style.css').read() + '</style>', unsafe_allow_html=True) components.html(f""" <html><meta name="viewport" content="width=device-width, initial-scale=1"><body style ="font-size:30px;color:green;" ><center>Mindreader</center><center>Personal Art Therapist</center></body></html>""", height=111) #""" ignore below imports used for different experiments """ #import base64 #from io import BytesIO #from pydrive.auth import GoogleAuth #from pydrive.drive import GoogleDrive from google.cloud import storage from google.oauth2 import service_account import tempfile #import os #import shutil dirpath = tempfile.mkdtemp() # ... do stuff with dirpath