def main(): st.title("Streamlit Forms & Salary Calculator") menu = ["Home","About"] choice = st.sidebar.selectbox("Menu",menu) if choice == "Home": st.subheader("Forms Tutorial") # Salary Calculator # Combine forms + columns with st.form(key='salaryform'): col1,col2,col3 = st.beta_columns([3,2,1]) with col1: amount = st.number_input("Hourly Rate in $") with col2: hour_per_week = st.number_input("Hours Per Week",1,120) with col3: st.text("Salary") submit_salary = st.form_submit_button(label='Calculate') if submit_salary: with st.beta_expander("Results"): daily = [amount * 8] weekly = [amount * hour_per_week] df = pd.DataFrame({'hourly':amount,'daily':daily,'weekly':weekly}) st.dataframe(df.T) # Method 1: Context Manager Approach (with) with st.form(key='form1'): firstname = st.text_input("Firstname") lastname = st.text_input("lastname") dob = st.date_input("Date of Birth") # Important submit_button = st.form_submit_button(label='SignUp') # Results Can be either form or outside if submit_button: st.success("Hello {} you ve created an account".format(firstname)) # Method 2: form2 = st.form(key='form2') username = form2.text_input("Username") jobtype = form2.selectbox("Job",["Dev","Data Scientist","Doctor"]) submit_button2 = form2.form_submit_button("Login") if submit_button2: st.write(username.upper()) else: st.subheader("About")
def main(): st.title("Image to LaTeX") with st.form(key="imputs"): st.markdown("## Upload an Image") image = st.file_uploader("", type=["jpg", "png"]) st.form_submit_button(label="Upload") with st.form(key="outputs"): st.markdown("## Convert to LaTeX") st.text("Uploaded image:") if image is not None: st.image(image) inference_button = st.form_submit_button(label="Infer") if inference_button and image is not None: with st.spinner("Wait for it..."): b64_image = base64.b64encode(image.read()) response = requests.post( API_PREDICT_URL, json={"image": f"data:image/png;base64,{b64_image.decode()}"}) if response.status_code == 200: st.markdown("**Inferred LaTex:**") st.code(response.json()["pred"], language="latex") st.markdown("**Render Inferred LaTeX:**") st.latex(response.json()["pred"]) else: st.error("An error occurred in the model server.")
def test_submit_button_outside_form(self): """Test that a submit button is not allowed outside a form.""" with self.assertRaises(StreamlitAPIException) as ctx: st.form_submit_button() assert "`st.submit_button()` must be used inside an `st.form()`" in str( ctx.exception)
def test_submit_button_inside_form(self): """Test that a submit button is allowed inside a form.""" with st.form("foo"): st.form_submit_button() last_delta = self.get_delta_from_queue() self.assertEqual("foo", last_delta.new_element.button.form_id)
def main(): menu = ["Enter Details", "Search"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Enter Details": st.subheader("Enter Details") with st.form(key='my_form1'): col1, col2 = st.columns(2) dob = col1.date_input('Enter DOB') First_name = col1.text_input("First Name", ) Last_name = col1.text_input("Last Name", ) col1.write('Select Skill') option_1 = col1.checkbox('Java') option_2 = col1.checkbox('Shell script') option_3 = col1.checkbox('Python') option_4 = col1.checkbox('SQL') submit_button = st.form_submit_button(label='Submit') if submit_button: update_df['dob'] = [dob] update_df['First_name'] = [First_name.strip()] update_df['Last_name'] = [Last_name.strip()] update_df['Java'] = [option_1] update_df['Shell Script'] = [option_2] update_df['Python'] = [option_3] update_df['SQL'] = [option_4] sh = gc.open('prototype') wks = sh[0] df = wks.get_as_df() df = df.append(update_df) wks.set_dataframe(df, (1, 1)) elif choice == "Search": st.subheader("Search") with st.form(key='my_form2'): col1, col2 = st.columns(2) First_name = col1.text_input("First Name", ) Last_name = col1.text_input("Last Name", ) submit_button = st.form_submit_button(label='Submit') if submit_button: sh = gc.open('prototype') wks = sh[0] df = wks.get_as_df() if (First_name != "") and (Last_name != ""): filtered_df = df[ (df['First_name'].str.strip() == (First_name.strip())) & (df['Last_name'].str.strip() == Last_name.strip())] if (Last_name) == "": filtered_df = df[(df['First_name'].str.strip() == ( First_name.strip()))] if (First_name) == "": filtered_df = df[(df['Last_name'].str.strip() == ( Last_name.strip()))] st.write(filtered_df.reset_index(drop=True))
def continuar(msg, state): with st.form(key='continue'): st.text(msg) state.uploaded_files.pop(0) state.opened_file = False state.checked_file = False state.processed_file = False state.selected_option = False state.appended_file = False st.form_submit_button(label='Continuar') st.stop()
def main(): st.title("Lyrica") def searchlyrics(): song = lyrics(Artist_name, Song_name) for words in song: return (words) def parse_lyrics(): profane_words = "4r5e5h1t,f**k,bustin\',busting,f****d,5hit,a55,anal,anus,ar5e,arrse,arse,ass,ass-f****r,asses,assfucker,assfukka,asshole,assholes,asswhole,a_s_s,b!tch,b00bs,b17ch,b1tch,ballbag,balls,ballsack,bastard,beastial,beastiality,bellend,bestial,bestiality,bi+ch,biatch,bitch,bitcher,bitchers,bitches,bitchin,bitching,bloody,blow job,b*****b,blowjobs,boiolas,bollock,bollok,boner,boob,boobs,booobs,boooobs,booooobs,booooooobs,breasts,buceta,bugger,bum,bunny f****r,butt,butthole,buttmuch,b******g,c0ck,c0cksucker,carpet muncher,cawk,chinkcipa,cl1t,c**t,clitoris,clits,cnut,c**k,c**k-sucker,cockface,cockhead,cockmunch,cockmuncher,cocks,cocksuck, cocksucked, c********r,cocksucking,cocksucks,cocksuka,cocksukka,c*k,cokmuncher,coksucka,coon,cox,crap,cum,cummer,cumming,cums,cumshot,cunilingus,cunillingus,cunnilingus,c**t,cuntlick, cuntlicker, cuntlicking, cunts,cyalis,cyberfuc,cyberfuck, cyberfucked, cyberfucker,cyberfuckerscyberfucking,d1ck,damn,dick,dickhead,d***o,dildos,dink,dinks,dirsa,dlck,dog-f****r,doggin,dogging,donkeyribber,doosh,duche,dyke,e*******e,ejaculated,ejaculates,ejaculating, ejaculatings,e*********n,ejakulate,f u c k,f u c k e r,f4nny,f*g,fagging,faggitt,f****t,faggs,fagot,fagots,fags,fanny,fannyflaps,fannyfucker,fanyy,fatass,fcuk,fcuker,fcuking,feck,fecker,f******g,f*****e,f******o,fingerfuck, fingerfucked, fingerfucker,fingerfuckers,fingerfucking,fingerfucks,fistfuck,fistfucked, fistfucker,fistfuckers, fistfucking, fistfuckings, fistfucks, flangefook,fookefuck,f***a,f****d,f****r,fuckers,fuckhead,fuckheads,f****n,f*****g,f******s,fuckingshitmotherfucker,f****e, f***s,fuckwhit,f*****t,fudge packer,f*********r,fuk,fukerfukker,fukkin,fuks,fukwhit,fukwit,f*x,fux0r,f_u_c_k,g******g,gangbanged, gangbangs, gaylord,gaysex,g****e,God,god-dam,god-damned,goddamn,goddamned,hardcoresex, hell,heshe,hoar,hoare,hoer,h**o,hore,horniest,horny,hotsex,jack-off, jackoff,jap,jerk-off, jism,j*z,jizm, j**z,kawk,knob,knobeadknobed,k*****d,knobhead,knobjocky,knobjokey,kock,kondum,kondums,kum,kummer,kumming,kums,kunilingus,l3i+ch,l3itch,labia,lmfao,lust,lusting,m0f0,m0fo,m45terbate,ma5terb8,ma5terbate,m*******t,master-bate,masterb8,masterbat*,masterbat3,masterbate,masterbation,masterbations,m********e,mo-fo,mof0,mofo,mothafuck,m********a,mothafuckas,mothafuckaz,mothafucked, mothafucker,mothafuckers,mothafuckin,mothafucking, mothafuckings,mothafucks,mother f****r,motherfuck,motherfucked,m**********r,motherfuckers,motherfuckin,motherfucking,motherfuckings,motherfuckka,motherfucks,muff,mutha,muthafecker,muthafuckker,muther,mutherfucker,n1gga,n1gger,nazi,nigg3r,nigg4h,n***a,niggah,n****s,niggaz,nigger,niggers, nob,nob jokey,nobhead,nobjocky,nobjokey,numbnuts,nutsack,orgasim,orgasims, o****m,o*****s, p0rn,pawn,pecker,penis,penisfucker,phonesex,phuck,phuk,phuked,phuking,phukked,phukking,phuks,phuq,pigfucker,pimpis,piss,pissed,pisser,pissers,pisses,pissflaps,pissin, pissing,pissoff,poop,p**n,porno,pornography,pornos,prick,pricks, pron,pube,p***e,pussi,pussies,pussy,pussys, rectum,retard,rimjaw,rimming,s hit,s.o.b.,s****t,schlong,screwing,scroat,scrote,scrotum,s***n,sex,sh!+,sh!t,sh1tshag,shagger,shaggin,shagging,shemale,shi+,shit,shitdick,s***e,shited,shitey,shitfuck,shitfull,s******d,shiting,shitings,shits,s*****d,shitter,shitters, s******g,s*******s,shitty,skank,s**t,s***s,s****a,smut,snatch,son-of-a-bitch,spac,spunk,s_h_i_t,t1tt1e5,t1tties,teets,teez,testical,testicle,tit,titfuck,t**s,titt,tittie5,tittiefucker,titties,tittyfuck,tittywank,titwank,tosser,turd,tw4t,twat,twathead,twatty,twunt,twunter,v14gra,v1gra,v****a,viagra,vulva,w00se,wang,wank,wanker,wanky,whoar,w***e,willies,willy,xrated,xxx" profane = profane_words.replace(",", " ") profane = profane.split(" ") profane = unique.union(set(profane)) stpwrds = stopwords.words("english") tokens = word_tokenize(searchlyrics()) removing_stopwords = [ words for words in tokens if not words in stpwrds ] new_stopwords = stopwords.words("english") new_stopwords = new_stopwords.extend(profane) removing = [word for word in removing_stopwords if word in profane] return removing menu = ["Home", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Forms Tutorial") with st.form(key="searcher"): Artist_name = st.text_input("Artist") Song_name = st.text_input("Song") Fetch = st.form_submit_button("Fetch Lyrics") if Fetch: with st.beta_expander("Lyrics"): st.write(searchlyrics()) st.success("Lyrics fetched successfully") with st.form(key="form1"): # Lyrics = st.text_area("Lyrics", height=300) lyrica = st.empty() Analyze = st.form_submit_button("Analyze") if Analyze: with st.beta_expander("Keywords"): st.write(parse_lyrics()) else: st.subheader("About")
def main(): st.set_page_config(layout='wide') state = _get_state() placeholder = st.empty() if state.degiro is None: with placeholder.form('2FA'): username = st.text_input('Username', '') password = st.text_input('Password', '', type='password') totp = st.text_input('2FA - Leave empty if not needed', '') if st.form_submit_button('Submit'): state.degiro = degiroapi.DeGiro() try: state.degiro.login(username, password, totp) except Exception: st.warning('Wrong credentials') state.degiro = None st.stop() if state.degiro and state.products is None: placeholder.empty() process.get_data(state) if state.products is not None: show_page(state) state.sync()
def create_cross_validation_form(ui_params): col1, col2, col3 = st.columns(3) with col1: st_cv_initial_days = st.number_input("Initial days", value=730, min_value=1, step=1) with col2: st_cv_period_days = st.number_input("Period days", value=180, min_value=1, step=1) with col3: st_cv_horizon_days = st.number_input("Horizon days", value=365, min_value=1, step=1) st_validation_metric = st.selectbox("Validation Metric", options=VALIDATION_METRICS, index=3) show_cross_validation = st.form_submit_button(label='Cross-Validate') # show_cross_validation = st.checkbox("Show Cross-Validation", value=False) st.caption("This can take some time.") dic_return = DotDict(initial_days=st_cv_initial_days, period_days=st_cv_period_days, horizon_days=st_cv_horizon_days, validation_metric=st_validation_metric, cross_validation=show_cross_validation) return dic_return
def form(): with st.form("my_form"): st.write("Envie os seguintes dados abaixo") with col1: st.write(""" ## João da silva (aposentado/funcionario publico)""") with col2: date = st.date_input('Data de nascimento', datetime.date.today()) st.write("## Foto") uploaded_file_foto = st.file_uploader("Choose a file", key=1) st.write("## Audio") uploaded_file_audio = st.file_uploader("Choose a file", key=2) st.write("## Video") uploaded_file_video = st.file_uploader("Choose a file", key=3) # Every form must have a submit button. submitted = st.form_submit_button("Submit") if submitted: st.write("data", date) st.write(date) st.balloons() ## enviar para api de autenticação ## enciar para s3 e rodar sagemaker para validação ## usar ec2 para hosting st.write(" ")
def predict_page(self): st.write('## Simulator') st.write("""Predict the outcome or probability of survival by customizing the input data of individuals""") st.write('') model_list = os.listdir('../output') avail_algo = [re.search('(?<=model_).+(?=\.pkl)', m).group(0) for m in model_list] with st.form(key="predict_form"): # New Data col1, col2, col3 = st.columns(3) pclass = col1.radio("Passage Class", (1, 2, 3), format_func=lambda x: CLASS_NAME[x]) sex = col2.selectbox("Sex", ('male', 'female'), format_func=lambda x: x.title()) age = col3.number_input("Age", step = 5) new_data = pd.DataFrame({ 'Pclass': [pclass], 'Sex': [sex], 'Age': [age] }) # Prediction Options col4, col5 = st.columns([2, 1]) algorithm = col4.selectbox('Algorithm', avail_algo, format_func=lambda x: ALGO_NAME[x]) probs = col5.radio('Predict Probability?', (True, False), format_func=lambda x: 'Yes' if x else 'No') predict = st.form_submit_button(label = 'Predict') if predict: pred = self.predict(new_data, algorithm, probs) if probs: velocimeter_chart(pred[0]) else: outcome = 'SURVIVED' if pred == 1 else 'DIED' st.write(f""" The model predicted that this individual would have ### {outcome} in the Titanic tragic accident """)
def main(): st.title("Titanic: Machine Learning from Disaster") df = load_data() target = "Survived" features = [c for c in df.columns.values if c != target] with st.beta_expander("About Titanic"): c1, c2 = st.beta_columns(2) description = read_markdown_file("pages/titanic.md") c1.markdown(f"{description}", unsafe_allow_html=True) c2.image("images/titanic.jpg") st.header("Data preview") st.caption(f"Shape of dataset : {df.shape[0]} rows, {df.shape[1]} columns") st.dataframe(df.describe()) cols_to_style = st.multiselect("Choose columns to apply BG gradient", features) st.dataframe( df.style.background_gradient(subset=cols_to_style, cmap="BuGn")) st.markdown("---") st.header("Plot distribution") col = st.selectbox("Choose a column to display", features) with_target = st.checkbox("Separate per target ?") chart = (alt.Chart(df).mark_bar().encode( alt.X(f"{col}:Q", bin=alt.Bin(maxbins=10)), alt.Y("count()"), tooltip=[col, "count()"], ).interactive()) if with_target: chart = chart.encode(color=f"{target}:N") st.altair_chart(chart, use_container_width=True) st.markdown("---") st.header("Correlation") fig, ax = plt.subplots() sns.heatmap(df.corr(), ax=ax) st.pyplot(fig) st.markdown("---") st.header("Classification") with st.form(key="classify"): c1, c2 = st.beta_columns(2) n_estimators = c1.number_input("Choose number of trees:", 1, 1000, 100) max_depth = c2.number_input("Max depth:", 1, 100, 5) button_pressed = st.form_submit_button(label="Train model") if button_pressed: with st.spinner("Training..."): clf, confusion_matrix, importance_plot, force_plot = train_rf( df, n_estimators, max_depth) st.balloons() st.pyplot(confusion_matrix) st.pyplot(importance_plot) st_shap(force_plot, 400)
def login(state): with st.sidebar.form(key='my_form'): user = st.text_input('Utilizador', '') password = st.text_input('Password', '', type='password') submit_button = st.form_submit_button(label='Entrar') if submit_button: if user == st.secrets['user'] and password == st.secrets['password']: state.login = True else: st.sidebar.warning('Utilizador / Password errados') st.stop()
def web_visualisation(): submitted = False while not submitted: with st.form("my_form"): st.title("Are you likely to have heart disease?") age = st.slider("How old are you?", 0, 100) sex = st.radio("What is your gender?", ["Male", "Female"]) cp = st.radio("What is your chest pain type", [0, 1, 2, 3]) trtbps = st.slider("What is your resting blood pressure (Hg)?", 0, 200) chol = st.slider("What is your cholestrol level (mg /dl)?", 0, 700) fbs = st.radio("What is your fasting blood sugar (mg) ?", [0, 1]) restecg = st.slider( "What is resting electrocardiographic results?", 0, 2) thalachh = st.slider("What is your maximmum heart rate?", 0, 200) exng = st.radio("Does your exercise induce anigma?", ["No", "Yes"]) oldpeak = st.slider( "What is ST depression induced by exercise relative to rest?", 0.00, 7.00, step=0.05) slp = st.slider( "What is the slope of the peak exercise ST segment?", 0, 2) caa = st.slider( "What is number of major vessels (0-3) colored by flourosopy?", 0, 3) thall = st.radio( "3 = normal; 6 = fixed defect; 7 = reversable defect", [3, 6, 7]) submitted = st.form_submit_button("Submit") if sex == 'Female': sex = 0 sex = 1 if thall == 3: thall = 1 elif thall == 6: thall = 2 else: thall = 3 if exng == "No": exng = 0 else: exng = 1 heart_param = np.array([ age, sex, cp, trtbps, chol, fbs, restecg, thalachh, exng, oldpeak, slp, caa, thall ]) submitted = True return heart_param
def login(state): with st.sidebar.form(key='login'): user = st.text_input('Utilizador', '') password = st.text_input('Password', '', type='password') submit_button = st.form_submit_button(label='Entrar') if submit_button: if not state.user_credentials.loc[ (state.user_credentials.user == user) & (state.user_credentials.password == password)].empty: state.user = user else: st.sidebar.warning('Utilizador / Password errados')
def _create_sidebar(self) -> None: state = self._state devdf = gui_get_df('device', columns=['namespace']) if devdf.empty: st.error('Unable to retrieve any namespace info') st.stop() namespaces = [''] + sorted(devdf.namespace.unique().tolist()) if self._state.namespace: nsidx = namespaces.index(self._state.namespace) else: nsidx = 0 url = '&'.join([ f'{get_base_url()}?page=Help&session={get_session_id()}', 'help=yes', 'help_on=Path', ]) display_help_icon(url) with st.sidebar: with st.form(key='trace'): state.namespace = st.selectbox('Namespace', namespaces, key='path_namespace', index=nsidx) state.source = st.text_input('Source IP', key='path_source', value=state.source) state.dest = st.text_input('Dest IP', value=state.dest, key='path_dest') state.vrf = st.text_input('VRF', value=state.vrf, key='path_vrf') state.start_time = st.text_input('Start Time', value=state.start_time, key='path_start_time') state.end_time = st.text_input('End Time', value=state.end_time, key='path_end_time') _ = st.form_submit_button('Trace', on_click=self._sync_state) state.show_ifnames = st.checkbox('Show in/out interface names', value=state.show_ifnames, key='path_show_ifnames', on_change=self._sync_state) _ = st.button('Source <-> Dest', key='path_swap', on_click=self._sync_state)
def main(): st.title("Emotion Classifier App") menu = ["Home", "Monitor", "About"] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Home-Emotion In Text") with st.form(key='emotion_clf_form'): raw_text = st.text_area("Type Here") submit_text = st.form_submit_button(label='Submit') if submit_text: col1, col2 = st.beta_columns(2) # Apply Fxn Here prediction = predict_emotions(raw_text) probability = get_prediction_proba(raw_text) #add_prediction_details(raw_text,prediction,np.max(probability)) with col1: st.success("Original Text") st.write(raw_text) st.success("Prediction") emoji_icon = emotions_emoji_dict[prediction] st.write("{}:{}".format(prediction, emoji_icon)) st.write("Confidence:{}".format(np.max(probability))) with col2: st.success("Prediction Probability") # st.write(probability) proba_df = pd.DataFrame(probability, columns=pipe_lr.classes_) # st.write(proba_df.T) proba_df_clean = proba_df.T.reset_index() proba_df_clean.columns = ["emotions", "probability"] fig = alt.Chart(proba_df_clean).mark_bar().encode( x='emotions', y='probability', color='emotions') st.altair_chart(fig, use_container_width=True) elif choice == "Monitor": st.subheader("Monitor App") else: st.subheader("About")
def delete(st_obj): with st_obj: with st.form(key='delete_review'): st.subheader('Delete review from database') st.markdown('Copy and paste the ID of the review to be deleted') update_id = st.text_input('Enter review ID', key='delete') update_table = st.selectbox('Enter table to be deleted from',['movie-reviews', 'short-film-reviews']) st.info('This action is non-reversible. Once deleted, review cannot be recovered.') submit_delete = st.form_submit_button('Confirm deletion of selected review') if submit_delete: Database.deleteReview(update_table, update_id)
def editIG(st_obj): with st_obj: with st.form(key='update_ig'): st.subheader('Update Instagram Status') st.markdown('Copy and paste the ID of the review that you want its IG status to be updated') update_id = st.text_input('Enter review ID') update_val = st.selectbox('Uploaded on Instagram?', [True, False]) update_table = st.selectbox('Enter table to be updated',['movie-reviews', 'short-film-reviews']) submit_ig = st.form_submit_button('Confirm instagram update status') if submit_ig: Database.updateIG(update_table, update_id, update_val)
def main(): st.title("Emotion Classifier") menu = ['Home', 'Monitor', 'About'] choice = st.sidebar.selectbox("Menu", menu) if choice == "Home": st.subheader("Home - Emotion in Text") with st.form(key='emotion_clf_form'): raw_text = st.text_area("Enter Your Text Here") submit_text = st.form_submit_button(label='Submit') if submit_text: col1, col2 = st.beta_columns(2) # Apply functions here prediction = predict_emotions(raw_text) probability = get_prediction_proba(raw_text) with col1: st.success("Original Text") st.write(raw_text) st.success("Prediction") st.write(emotion_emoji_dict[prediction]) st.write(f"Confidence Level: {np.max(probability):.3%}") with col2: st.success("Prediction Probability") # st.write(probability) df_proba = pd.DataFrame(probability, columns=pipe_lr.classes_) # Print out a probability table df_proba_trans = df_proba.T df_proba_trans.columns = ["Probability"] st.write(df_proba_trans) # Transpose it so it is a vertical column df_proba_clean = df_proba.T.reset_index() df_proba_clean.columns = ["Emotion", "Probability"] fig = alt.Chart(df_proba_clean).mark_bar().encode(x="Emotion", y="Probability", color='Emotion') st.altair_chart(fig, use_container_width=True) elif choice == "Monitor": st.subheader("Monitor App") else: st.subheader("About")
def login(auth): with st.beta_expander('Sign in and Logout panel'): with st.form('login_panel'): email = st.text_input('Enter email') password = st.text_input('Enter password') submit_login = st.form_submit_button('Login to the dashboard') if submit_login: login = auth.sign_in_with_email_and_password(email, password) if (login): Page.state = True st.success('Signed in! Logging you in') if st.button('Log out from current session'): Page.state = False
def model_page(self): st.write('## Model Fitting') st.write("""#### Train the developed machine learning algorithm""") with st.form(key="model_form"): algo_options = ['All'] + list(self.algos.keys()) chosen_algo = st.selectbox('Choose algorithm', algo_options, format_func=lambda x: x if x == 'All' else ALGO_NAME[x]) if chosen_algo == 'All': model_algo = self.algos else: model_algo = {key: value for key, value in self.algos.items() if key == chosen_algo} st.write('Execute model?') fit = st.form_submit_button('Fit') if fit: with st.spinner("Running algorithm ..."): df_model = self.preprocess() self.fit_model(df_model, model_algo) st.write('### Success! Models fitted!')
def main(): if config.ISLAND_URL == None: st.error("未设置小岛链接") return db = InitDB() st.header("敏感词检测") with st.form("敏感词检测"): limit_time = st.date_input("时间限制", help="只会对时间在此之后的帖子进行敏感词检测") enable_ban_word_match = st.form_submit_button("开始检测") if enable_ban_word_match: flag = st.warning("正在获取数据,请稍后......") GetData(config.ISLAND_URL, db, "all_post_data", limit_time) flag = st.success("获取数据成功!") BanWordMatch(db)
def page(kiara: Kiara): with st.form(key="onboard_corpus"): st.markdown("## Onboard text corpus") st.markdown("Select sample data from one publication folder located in kiara_modules.playground/examples/newspaper_corpora/CI_newspaper_subcorpora") st.markdown("Once you're ready, go to the next step via select box on the left") alias = st.text_input("Corpus name") uploaded_files = st.file_uploader("Add files", type = 'txt', accept_multiple_files=True) alias_valid = check_alias_valid(kiara, alias) onboard_button = st.form_submit_button(label="Onboard") if onboard_button and alias_valid and uploaded_files: onboard_file_bundle(kiara=kiara, uploaded_files=uploaded_files, aliases=[alias]) st.markdown(f"Onboarded corpus: {alias}") else: if onboard_button: if not alias_valid: st.markdown("Corpus name not valid or already exists. Not onboarding any files...") else: st.markdown("Corpus name valid, but no files selected.") available_tables = [] for item in kiara.data_store.aliases: md = kiara.data_store.get_metadata_for_id(item) if md.value_type == "table": column_names = md.metadata["table"]["metadata_item"]["column_names"] if "content" in column_names and "file_name" in column_names: available_tables.append(item) st.markdown("## Select text corpus") st.markdown("Select the corpus you want to work.") selected = st.selectbox("Corpus alias", available_tables) if selected: table_value = kiara.data_store.load_value(selected) table: pa.Table = table_value.get_value_data() st.dataframe(table.to_pandas()) st.session_state.selected_corpus_name = selected
def page_third(): st.title("Retrieve Reports") with st.form(key='retrieve'): topic = st.text_input(label='Enter Topic') username = st.text_input("Enter username") password = st.text_input("Enter password", type="password") submitted3 = st.form_submit_button('Retrieve') if submitted3: usrPass = username + ":" + password b64Val = base64.b64encode(usrPass.encode()).decode() headers = {"Authorization": "Basic %s" % b64Val} res = requests.get(f"http://web:8000/summaries/getReports?topic=" + str(topic), headers=headers) processed_reports = res.json() for reportId in processed_reports.keys(): report_name = processed_reports[reportId] st.markdown(get_report_download_link(reportId, report_name), unsafe_allow_html=True)
def forms_demo(): st.image( "https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/240/apple/271/crystal-ball_1f52e.png", width=100, ) st.write(""" # Try out `st.form`! We built a super-secret algorithm to recommend a Streamlit app or component based on your personality. The problem: It takes a long time to run. That's why we use a form to bundle all the input widgets 👇 """) st.write("") with st.form(key="recommender"): st.write("Click **Submit** to get your recommendation!") st.selectbox( "Your favorite streamlit call", ["st.form", "st.balloons 🎈 ", "st.form_submit_button", "st.write"], ) st.text_input("Your favorite thing to build streamlit apps for") st.slider("How excited you are about forms", 0, 11, 10) submitted = st.form_submit_button() st.write("") if submitted: with st.spinner("🤓 Crunching numbers..."): time.sleep(2) use_component = random.choice([True, False]) if use_component: desc = "a component" name, author, url = random.choice(components) else: desc = "an app" name, author, url = random.choice(apps) st.success( f"☘️ The algorithm recommended {desc} to you: **[{name}]({url}) by {author}** (find more cool apps & components in [our gallery](https://streamlit.io/gallery)!)" ) st.info( "💡 With `st.form`, this app (and our complex algorithm!) only reruns when you hit the submit button, not at each widget interaction. [Check out the blog post to learn how it works!](https://blog.streamlit.io/introducing-submit-button-and-forms/)" )
def email(): with st.form(key='my_form'): st.header("Want to be notified of new features?") col1, col2 = st.beta_columns([5, 1]) regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$' with col1: text_input = st.text_input( 'Subscribe to get the latest news and updates.', 'Email Address') with col2: st.header('') submit_button = st.form_submit_button(label="Subscribe") if submit_button and re.search(regex, text_input): st.info("You've been subscribed successfully!") st.balloons() sendmail(text_input) elif submit_button: st.error("Invalid Email")
def create_account(dbx, state): with st.sidebar.form(key='create_account'): user = st.text_input('Novo Utilizador', '') password = st.text_input('Password', '', type='password') submit_button = st.form_submit_button(label='Criar Conta') if submit_button: if not password: st.sidebar.warning('Por favor escolha uma password') st.stop() if any(state.user_credentials.user == user): st.sidebar.warning('Utilizador já registado') st.stop() else: st.sidebar.warning('Criando Conta...') state.user_credentials = state.user_credentials.append( {'user': user, 'password': password}, ignore_index=True).sort_values(by='user', axis=0) db.upload_dataframe( dbx, APP, state.user_credentials, CREDS) state.user = user
def get_sp_data(form_key, data_model, st_asset, submit_label = 'Submit', do_cache = False, **kwargs): ''' Create a form in ST using streamlit_pydantic and return the resulting data object in dictionary form ''' if do_cache: cache_key = f'{form_key}_cache' with st_asset.form(key = form_key): st.markdown(f'#### {form_key} params') input_data = sp.pydantic_input(key = form_key, model = data_model, **kwargs) submitted = st.form_submit_button(label = submit_label if submit_label else 'Submit') if submitted: data = input_data st.session_state[cache_key] = data else: data = st.session_state[cache_key] if cache_key in st.session_state else None else: with st_asset: data = sp.pydantic_form(key = form_key, model = data_model, submit_label = submit_label, **kwargs) return data
def api_poc(): st.subheader("POC for connecting catalog and API") with st.form(key="catalog_search"): query = st.text_input(label="Search the catalog", value="data") submit_button = st.form_submit_button(label="Submit catalog search") catalog_data = get_catalog_results(query) st.subheader("Results from the catalog are:") st.write(catalog_data) st.subheader("Results from the API") api_keyword_data = requests.get( f"http://localhost:8000/keyword?q={query}").json() api_keyword_data_df = pd.DataFrame(api_keyword_data) st.write(api_keyword_data_df) st.subheader("Results from title similiarity") title_query = " ".join(catalog_data["title"]) api_similarity_data = requests.get( f"http://localhost:8000/titlesimilarity?q={title_query}").json() st.write(api_similarity_data)