def main(): df = read_jarchive() state = SessionState.get(question_number=1, num_correct=0, score=0) st.title("Streamlit Jeopardy!") category, question, answer, value = get_one_question( state.question_number, df) answered = False st.write(f"Question from category {category} for ${value}:") st.write(f" {question}") response = st.text_input("What is: ", key=str(state.question_number)) if (response != ''): sresponse = sanitize(response) sanswer = sanitize(answer) if (compare_strings(sresponse, sanswer) >= 0.5): answered = True st.write(f"Correct! The reference answer is {answer}.") else: answered = False st.write( f"Sorry! Your response was {response}. The correct answer is {answer}." ) if (answered): state.num_correct += 1 state.score += value else: state.score -= value st.write( f"Your score is {state.num_correct}/{state.question_number} and winnings are ${state.score}" ) st.write("") if st.button('Next question'): state.question_number += 1 raise RerunException(RerunData(widget_states=None)) if st.button('Reset score'): state.question_number = 0 state.num_correct = 0 state.score = 0 raise RerunException(RerunData(widget_states=None))
def run_labeler(): state = SessionState.get(captcha_number=0) captcha_image_list = get_captcha_list() captcha = get_random_captcha(captcha_image_list, state.captcha_number) st.image(captcha) col_1, col_2 = st.beta_columns(2) if col_1.button('Break it!'): model, lb = import_model('output') image, text = predict_captcha_image(captcha, model, lb) st.image(image) st.write(text) if col_2.button('Next captcha'): state.captcha_number += 1 raise RerunException(RerunData(widget_states=None))
def get_session_state(rando): session_state = SessionState.get(sessionstep=0, random_number=random.random(), chatinput='', personality='', personalityhistory=[], bot_input_ids='', chat_history_ids='', chathistory=[], bothistory=[], emojitranslate='', length_gen='', temperature='', topk='', topp='', no_repeat_ngram_size='') return session_state
def main(): with open('credentials.json','r') as f: credentials = json.load(f) auth = tweepy.OAuthHandler(credentials.get('api_key'), credentials.get('api_secret')) api = tweepy.API(auth) st.title('Huggingtweets!') st.header('Tweet like you favorite account! Use this app to compose a tweet in the stylings of your twitter personality.') session_state = SessionState.get(handle="", button_handle_submit=False) session_state.handle = st.text_input('Type in the twitter handle of your choice') button_handle_submit = st.button("Submit") if button_handle_submit: session_state.button_handle_submit = True # handle = st.text_input('Type in the twitter handle of your choice') if session_state.button_handle_submit: huggingtweets(api,session_state.handle,session_state)
def add_well_logs_app(): st.subheader('Visualizing well logs') st.write( "This simple app allows you to visualize any LAS file you upload below. This is part of the open" " source initiative by Pro Well Plan AS.") st.markdown( '[About our Open Source initiative]' '(https://prowellplan.com/modern-drilling-organization/open-source-boosting-the-digital-transformation)' ) session_state = SessionState.get( name="", logs_list=None, df=None) # record log_list and df when it is created uploaded_file = st.file_uploader('Load a LAS file', type=["las"]) if uploaded_file: string = uploaded_file.read().decode() number = len(string) if number > 0: df_file = lasio.read(string).df() df_file.index.name = 'DEPT' df_file['MD ' + '(ref)'] = df_file.index.values session_state.df = df_file session_state.logs_list = list(session_state.df.columns) logs = st.multiselect('Select the logs to be included', session_state.logs_list, default=session_state.logs_list[:4]) if len(logs) == 1: st.warning('Please select at least two logs') else: df_final = session_state.df[logs] fig = ags.plot_log(df_final) st.plotly_chart(fig) st.dataframe(df_final) csv = df_final.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() # some strings link = f'<a href="data:file/csv;base64,{b64}" download="well_logs_data.csv">Download dataset</a>' st.markdown(link, unsafe_allow_html=True)
def display_next(img_ids_cat): prev, _, next = st.beta_columns([1, 10, 1]) session_state = SessionState.get(page_number=0) last_page = img_ids_cat.shape[0] - 1 if next.button("Next"): if session_state.page_number + 1 > last_page: session_state.page_number = 0 else: session_state.page_number += 1 if prev.button("Previous"): if session_state.page_number - 1 < 0: session_state.page_number = last_page else: session_state.page_number -= 1 val = session_state.page_number st.image(img_ids_cat[val])
def main(): st.subheader("new") session_state = SessionState.get(name="", button_sent=False) session_state.password = test_auth.confirm_button_example() button_sent = st.button("Send") if button_sent: session_state.button_sent = True if session_state.button_sent: st.write(session_state.name) session_state.bye = st.checkbox("bye") session_state.welcome = st.checkbox("welcome") if session_state.bye: st.write("I see") if session_state.welcome: st.write("you see")
def main(): # Render the readme as markdown using st.markdown. session_state = SessionState._get_state() if session_state.page_number is None: session_state.page_number = 0 if session_state.object_type is None: session_state.object_type = 0 if session_state.label_col is None: session_state.label_col = [0.0, 0.0, 0.0] if session_state.part_disp is None: session_state.part_disp = False if session_state.bbox_disp is None: session_state.bbox_disp = False if session_state.graph is None: session_state.graph = False if session_state.set is None: session_state.set = 0 st.write( '<style>div.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True) f = open(os.path.join(path, 'instructions.md'), "r") image_list = pd.read_csv( os.path.join(path, 'src', 'visualization', 'dataset.csv')) readme_text = st.markdown(f.read()) # Once we have the dependencies, add a selector for the app mode on the sidebar. st.sidebar.title("What to do") app_mode = st.sidebar.selectbox( "Choose the app mode", ["Show instructions", "Run the app", "Show the source code"]) if app_mode == "Show instructions": st.sidebar.success('To continue select "Run the app".') elif app_mode == "Show the source code": readme_text.empty() f = open(path + 'src/visualization/' + "graph_viz.py", "r") st.code(f.read()) elif app_mode == "Run the app": readme_text.empty() run_the_app(session_state, image_list)
def app(): st.write(""" # Aplicación de informe de ArcGIS Online BMCR """ ) option = st.selectbox("Use", ['File','Login']) if option == 'File': file_data = st.file_uploader('Select file in csv:',type=['csv']) if file_data: data = pd.read_csv(file_data,sep=';',encoding='utf8') EDA(data) else: portal = st.text_input("Enter a portal link", "https://www.arcgis.com/") st.write(""" ## Admin acount is required""") user = st.text_input("Enter the user",'rmartin_esri_colombia') password = st.text_input("Enter the password", type="password") session_state = SessionState.get(name="", button_sent=False) button_login = st.button("Login") if button_login: session_state.button_sent = True if session_state.button_sent: st.write(session_state.name) try: gis = GIS(portal,user,password) st.write("Authentication succesfull") try: EDA(arcgis_use(gis)) except: st.write('noshe que pasa') except: st.write("Authentication failed")
def config() -> List[str]: """ The selection which elements to validate and fix. """ col1, col2 = st.beta_columns([6, 1]) col2.write("") col2.write("") session = SessionState.get(run_id=0) if col2.button("Reset"): session.run_id += 1 validation_criteria = col1.multiselect( "", VALIDATION_CRITERIA + ADDITIONAL_VALIDATION_CRITERIA, default=VALIDATION_CRITERIA, key=session.run_id, ) if not validation_criteria: st.error("Please select at least one option to validate!") st.stop() return validation_criteria
def main(): #_max_width_() df = load_data() track_df = load_track_data() state = SessionState.get(option='', a=[]) state.a = get_select_options(df, track_df) st.sidebar.markdown( 'Welcome to Bovada Scrape!!! Select an option below and see a visualization to the right!' ) #option=st.sidebar.selectbox('Select a bet -', a) state.option state.option = st.sidebar.selectbox('Select a bet -', state.a) st.sidebar.markdown('you selected ' + state.option) if len(state.option) > 0: try: draw_main(df, state.option, track_df) except: st.sidebar.markdown('Select an option above')
from PIL import Image import classify import tensorflow as tf import numpy as np import keras import cv2 from keras.models import model_from_json import pandas as pd import SessionState import os.path import os import streamlit as st session = SessionState.get(loged=False) # a = st.radio("Edit or show", ['Edit', 'Show'], 0) # if a == 'Edit': # session.code = st.text_input('Edit code', session.code) # else: # st.write(session.code) abbreviation_dict = {12: 'Neutrophil (segmented)', 11: 'Neutrophil (band)', 2: 'Eosinophil', 0: 'Basophil', 8: 'Monocyte', 5: 'Lymphocyte (typical)',
BIG_VALUES = [val for val in VALUES if val >= 100_000] L_SUM = sum([val for val in VALUES[:len(VALUES) // 2]]) R_SUM = sum([val for val in VALUES[len(VALUES) // 2:]]) engine = create_engine( 'postgresql://{user}:{pw}@{host}:{port}/{dbname}'.format( user=st.secrets['username'], pw=st.secrets['password'], host=st.secrets['host'], port=5432, dbname=st.secrets['dbname'])) session = SessionState.get(run_id=0) def generate(random_chars=12, alphabet="0123456789abcdef"): r = random.SystemRandom() return ''.join([r.choice(alphabet) for i in range(random_chars)]) query_params = st.experimental_get_query_params() if not hasattr(st, 'game_id') or not query_params: st.game_id = generate(8) session.game_id = st.game_id st.experimental_set_query_params(round_number=1, game_id=st.game_id, prev_offer=0)
def app(): state = SessionState._get_state() @st.cache(allow_output_mutation=True) def get_json_data(): with open('../ToolJson/train.json', 'r') as f: test_data = json.load(f) with open('../ToolJson/train.json', 'r') as f: train_data = json.load(f) with open('../ToolJson/val.json', 'r') as f: train_val_data = json.load(f) return test_data, train_data, train_val_data test_data, train_data, train_val_data = get_json_data() if state.bookmarks is None: state.bookmarks = [] if state.counter is None: state.counter = 0 if state.counter is None: state.region = "Character Line Segment" # Filters data based on user selection (Test, Train, Validation,Bookmarks) def filter_json(value): if (value == 'Train'): data = train_data elif (value == 'Test'): data = test_data elif (value == 'Validation'): data = train_val_data elif (value == 'Bookmarks'): data = state.bookmarks # else: # return 'null' return data # Filters data based on user selection (CLS,CC,Page Boundary, etc) def filter_component(value, data): new_data = [] for i in range(len(data)): if data[i]['label'][0] == value: new_data.append(data[i]) return new_data # Returns image based on current counter value (which stores the current index of image being viewed) def update_image_info(data): if (state.counter >= 0 and len(data) > state.counter): info = data[state.counter] image_directory = data[state.counter]['image_url'][0][14:] image_directory = image_directory.replace("%20", " ") image_path = '../new_jpg_data' + image_directory else: return 'null', 'null' return info, image_path # Sorts data by iou or hd, showing worst results first def sort_data(data, inp): if inp == 'iou': data = sorted(data, key=lambda k: k['iou'], reverse=False) elif inp == 'hd': data = sorted(data, key=lambda k: k['hd'], reverse=True) return data # Saves current image path, along with IOU and HD values in filenames.txt for later reference def save_path(image_path, iou, hd, ttv, index): with open("saved_paths.txt", "a") as f: f.write(image_path + "\tiou: " + str(iou) + "\thd: " + str(hd) + "\t" + ttv + "\tindex: " + str(index) + "\n\n") # MAIN APP LAYOUT st.title('Layer Visualizer') dataset = ['Train', 'Test', 'Validation'] if len(state.bookmarks) > 0: dataset.append('Bookmarks') image_selector = st.radio('Image Type', dataset) state.region = st.selectbox( 'Select component type ', ('Character Line Segment', 'Character Component', 'Page Boundary', 'Boundary Line', 'Physical Degradation', 'Library Marker', 'Picture / Decorator')) json_selected = filter_json(image_selector) sort_by = st.selectbox('Sort by (iou, hd)', ('iou', 'hd')) json_selected = filter_component(state.region, json_selected) json_selected = sort_data(json_selected, sort_by) # Index selection sl = st.empty() if (state.counter > len(json_selected) - 1): state.counter = 0 if len(json_selected) - 1 > 0: state.counter = sl.slider("Select image", 0, len(json_selected) - 1, state.counter) else: state.counter = 0 c1, c2 = st.beta_columns(2) p = c1.button('Prev') n = c2.button('Next') if p: state.counter -= 1 if n: state.counter += 1 ind = int(st.text_input("Enter index value here: ", state.counter)) if ind and ind in range(0, len(json_selected)): state.counter = ind # Display image and relevant data based on index selected info, image_path = update_image_info(json_selected) if (info != 'null'): img = PlotImage.BNetImage(image_path, info) fig, label, iou, hd = img.RenderImage() st.plotly_chart(fig) st.write("IOU: " + str(iou)) st.write("HD: " + str(hd)) else: st.title('Image not found') if st.button("Save for later"): save_path(image_path, iou, hd, image_selector, state.counter) if st.button("Bookmark current image"): state.bookmarks.append(json_selected[state.counter]) state.sync()
def main(): """bioinformatics_web_app""" st.title('Sequence Analysis') #st.header('This is a header') #st.subheader('This is a subheader') st.set_option('deprecation.showfileUploaderEncoding', False) file = st.file_uploader("Upload FASTA file of DNA", type=["fasta", "txt"]) session_state = SessionState.get(status='off') if st.button("submit"): if file is not None: session_state.status = 'on' else: st.error('Need to upload file') if session_state.status == 'on': radio = st.radio("Select option to view", ('DNA analysis', 'RNA analysis', 'Protein analysis')) seq_record = SeqIO.read(file, "fasta") sequence = str(seq_record.seq) seq_ob = Seq(sequence).upper() transcribed = seq_ob.transcribe() translated = seq_ob.translate() if radio == 'DNA analysis': st.write('DNA sequence: ', seq_ob) lenght = str(len(seq_ob)) section = '### Sequence length: ' + "**" + str(len(seq_ob)) + "**" st.markdown(section) st.write("") G = [seq_ob.count('G')] A = [seq_ob.count('A')] T = [seq_ob.count('T')] C = [seq_ob.count('C')] GC_content = round((G[0] + C[0]) / len(seq_ob) * 100, 2) AT_content = round((A[0] + T[0]) / len(seq_ob) * 100, 2) st.write('GC content: ', GC_content, '%') st.write('AT content: ', AT_content, '%') rows = ['G', 'A', 'T', 'C'] df = pd.DataFrame(np.array([G, A, T, C]), columns=['Count'], index=rows) st.markdown("### Nucleotide count:") st.dataframe(data=df, width=1000, height=1000) #hide auto-error message with matplotlib st.set_option('deprecation.showPyplotGlobalUse', False) #plot bar graph of nucleotide frequencies plt.bar(rows, [G[0], A[0], T[0], C[0]]) plt.title('Nucleotide frequencies') st.pyplot() elif radio == 'RNA analysis': st.write('RNA sequence: ', transcribed) lenght = str(len(transcribed)) section = '### Sequence length: ' + "**" + str( len(transcribed)) + "**" st.markdown(section) st.write("") G = [transcribed.count('G')] A = [transcribed.count('A')] U = [transcribed.count('U')] C = [transcribed.count('C')] GC_content = round((G[0] + C[0]) / len(seq_ob) * 100, 2) AU_content = round((A[0] + U[0]) / len(seq_ob) * 100, 2) st.write('GC content: ', GC_content, '%') st.write('AU content: ', AU_content, '%') rows = ['G', 'A', 'U', 'C'] df = pd.DataFrame(np.array([G, A, U, C]), columns=['Count'], index=rows) st.markdown("### Nucleotide count:") st.dataframe(data=df, width=1000, height=1000) #hide auto-error message with matplotlib st.set_option('deprecation.showPyplotGlobalUse', False) #plot bar graph of nucleotide frequencies plt.bar(rows, [G[0], A[0], U[0], C[0]]) plt.title('Nucleotide frequencies') st.pyplot() elif radio == 'Protein analysis': st.write('Protein sequence: ', translated) lenght = str(len(translated)) section = '### Sequence length: ' + "**" + str( len(translated)) + "**" st.markdown(section) st.write("") aa_count = {} for letter in translated: if letter in aa_count.keys(): aa_count[letter] += 1 else: aa_count[letter] = 1 display_dict = {} for key, value in aa_count.items(): display_dict[aa_dict[key]] = value reverse_aa_dict = {value: key for key, value in aa_dict.items()} display_names = [key for key in display_dict.keys()] display_counts = [value for value in display_dict.values()] temp_zip = list(zip(display_names, display_counts)) temp_zip.sort(key=lambda x: x[1], reverse=True) names = [tup[0] for tup in temp_zip] names2 = [(name + "(" + str(reverse_aa_dict[name]) + ")") for name in names] counts = [tup[1] for tup in temp_zip] aa_df = pd.DataFrame(counts, columns=['Count'], index=names2) st.markdown("### Amino Acid count:") st.dataframe(aa_df, width=1000, height=1000) st.set_option('deprecation.showPyplotGlobalUse', False) #plot bar graph of amino acid frequencies ordered_abbreviations = [reverse_aa_dict[name] for name in names] plt.bar(ordered_abbreviations, counts) plt.title('Amio Acid frequencies') st.pyplot()
CLASSES = classes_and_models["model"]["classes"] MODEL = classes_and_models["model"]["model_name"] # Display info about and classes if st.checkbox("Show classes"): st.write(f"These are the classes of food it can identify:\n", CLASSES) # File uploader allows user to add their own image uploaded_file = st.file_uploader(label="Upload an image of food", type=["png", "jpeg", "jpg"]) # Setup session state to remember state of app so refresh isn't always needed # See: https://discuss.streamlit.io/t/the-button-inside-a-button-seems-to-reset-the-whole-app-why/1051/11 session_state = SessionState.get(pred_button=False) # Create logic for app flow if not uploaded_file: st.warning("Please upload an image.") st.stop() else: session_state.uploaded_image = uploaded_file.read() st.image(session_state.uploaded_image, use_column_width=True) pred_button = st.button("Detect") # Did the user press the predict button? if pred_button: session_state.pred_button = True # And if they did...
import streamlit as st from Class import method as mt import ptvsd import SessionState from PIL import Image from st_aggrid import GridOptionsBuilder, AgGrid, GridUpdateMode, DataReturnMode, JsCode session_state = SessionState.get(Session=False) st.set_page_config(layout='wide', page_title='oList SR') #-------------------------------- # Side Bar #-------------------------------- Side = st.sidebar Side.header('Autenticación de usuario') Side.subheader('Inicio de sesión') userName = Side.text_input('Usuario') passUser = Side.text_input('Contraseña', type='password') LogIn, LogOut = Side.beta_columns(2) if LogIn.button('LogIn'): if len(userName) > 0 and len(passUser) > 0: sucess = mt.LogIn(userName, passUser) if sucess: Side.success('Datos Correctos!') session_state.Session = True else: Side.error('Datos incorrectos...') else:
import time import streamlit as st import SessionState import numpy as np from predictor import Predictor from dataset.add_noise import SynthesizeData state = SessionState.get(text_correct="", input="", noise="") import nltk def main(): model, synther = load_model() st.title("Chương trình sửa lỗi chính tả tiếng Việt") # Load model state.input = "" state.noise = "" text_input = st.text_area("Nhập đầu vào:", value=state.input) text_input = text_input.strip() if st.button("Correct"): state.noise = text_input state.text_correct = model.spelling_correct(state.noise) st.text("Câu nhiễu: ") st.success(state.noise) st.text("Kết quả:") st.success(state.text_correct) if st.button("Add noise and Correct"): state.noise = synther.add_noise(text_input, percent_err=0.3) # state.output = noise_text state.text_correct = model.spelling_correct(state.noise)
def main(): df_Movies = load_data() df_Users = load_data_User() total=pd.merge(df_Users,df_Movies[['tconst','runtimeMinutes']], on='tconst',how='inner') total_time=total.groupby('userId')['runtimeMinutes'].sum() total_actors=pd.merge(df_Users,df_Movies[['tconst','actorsName']], on='tconst',how='inner') total_actors['actorsName']=total_actors['actorsName'].apply(lambda x : ','+x+',') session_state = SessionState.get(name="", button_selected=False) st.image("https://raw.githubusercontent.com/roussetcedric/StreamLitMovies_Project/master/logo.png", width=700) my_bar = st.progress(0) for percent_complete in range(100): time.sleep(0.01) my_bar.progress(percent_complete + 1) AdminitrationPage = st.sidebar.radio("Interface",["Utilisateur","Administrateur"]) if AdminitrationPage == "Administrateur" : st.title('Interface Administrateur') st.write('Analysez les habitudes de vos clients') Analyse = st.sidebar.radio("Analyse",["Par Utilisateur","Global"]) if Analyse == "Global" : df_Analysis = df_Movies elif Analyse == "Par Utilisateur" : UserSelected = st.sidebar.selectbox('', df_Users["userId"].unique()) liste_film_user = df_Users[df_Users['userId'] == UserSelected]['tconst'].to_list() df_Analysis = df_Movies.loc[df_Movies['tconst'].isin(liste_film_user)] df_Genres = pd.concat([df_Analysis[['isAdult']], df_Analysis['genres'].str.get_dummies(sep=','), df_Analysis['averageRating']], axis=1) for col in df_Genres.columns : df_Genres[col] = df_Genres[col]*df_Genres["averageRating"] df_GenrePie = pd.melt(df_Genres,value_vars=df_Genres.columns[1:-1],var_name='Genre',value_name='Nombre').groupby('Genre').sum() df_Genres = df_Genres.replace(0, np.NaN) df_GenreBar = pd.melt(df_Genres,value_vars=df_Genres.columns[1:-1],var_name='Genre',value_name='Nombre').groupby('Genre').mean() st.write("* **Nombre de Films** :" + str(df_Analysis.shape[0])) figPie = px.pie(df_GenrePie, values='Nombre', names=df_GenrePie.index) figPie.update_layout( title="REPARTITION DES FILMS PAR GENRES", font=dict( family="Courier New, monospace", size=18, color="#7f7f7f" )) st.plotly_chart(figPie) figBar = px.bar(df_GenreBar, x=df_GenreBar.index, y='Nombre') figBar.update_layout( title="NOTE MOYENNE PAR GENRES", xaxis_title="GENRE", yaxis_title="NOTE", font=dict( family="Courier New, monospace", size=18, color="#7f7f7f" )) st.plotly_chart(figBar) if Analyse == "Par Utilisateur" : st.write("* **Temps passé en salle obscure** : " + str(total_time.loc[UserSelected]) + " minutes") df_Analysis['actorsName']=df_Analysis['actorsName'].apply(lambda x : ','+x+',') top = df_Analysis['actorsName'].str.extractall(pat=",(.*?),")[0].value_counts() st.write("* **Acteur préféré** : " + str(top.index[0]) + " dans " + str(top[0]) + " films vus") picList = [] captionList = [] st.write("* **5 Derniers films vus** :") df_Analysis = df_Analysis.reset_index(drop=True) for loop in range(1,6) : picList.append(get_poster_from_api(df_Analysis.iloc[df_Analysis.shape[0]-loop]["tconst"])) captionList.append(df_Analysis.iloc[df_Analysis.shape[0]-loop]["originalTitle"]) st.image(picList, width=120, caption=captionList) elif AdminitrationPage == "Utilisateur" : #Select Movie st.title('Predictus Filmus !!') st.write('Rentrez le titre de votre Film') title = st.text_input('', '') if title != '' : df_SelectedNameAndYear = GetNameAndYear(df_Movies, title) if df_SelectedNameAndYear.shape[0] == df_Movies.shape[0]: st.write("Il n'y a pas de Film correspondant à votre recherche") else : st.write('Choisissez votre Film :') MovieSelectedTitle = st.selectbox('', df_SelectedNameAndYear["titleYear"].to_list()) IndiceFilm = df_SelectedNameAndYear[df_SelectedNameAndYear["titleYear"] == MovieSelectedTitle]["tconst"] df_MovieSelectedOne = df_Movies[df_Movies["tconst"] == IndiceFilm.iloc[0]] DisplayPoster(get_poster_from_api(df_MovieSelectedOne.iloc[0]["tconst"])) if get_poster_from_api(df_MovieSelectedOne.iloc[0]["tconst"]) != "" : BackGround_string = "<style>" \ "body { "\ "background: url('" + str(get_poster_from_api(df_MovieSelectedOne.iloc[0]["tconst"])) + "') center center no-repeat;" \ "background-size: 70%;" \ "background-attachment: fixed;" \ "background-color: black;" \ "color: black;" \ "height: 20%;" \ "width: 20%;" \ "}" \ ".block-container{" \ "background: hsla(0,0%,100%,.8);" \ "}" \ "</style>" st.markdown(BackGround_string, unsafe_allow_html=True) else : st.markdown(""" <style> body { background: url('https://images.unsplash.com/photo-1489599849927-2ee91cede3ba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80') center center no-repeat; background-size: cover; background-attachment: fixed; color: white; height: 100%; width: 100%; } </style> """, unsafe_allow_html=True) st.write('* **Titre** : ' + str(df_MovieSelectedOne.iloc[0]["originalTitle"])) st.write('* **Résumé** : ' + str(get_overview_from_api(IndiceFilm.iloc[0]))) st.write('* **Année de sortie** : ' + str(df_MovieSelectedOne.iloc[0]["startYear"])) st.write('* **Durée** : ' + str(df_MovieSelectedOne.iloc[0]["runtimeMinutes"]) + ' min') st.write('* **Note** : ' + str(df_MovieSelectedOne.iloc[0]["averageRating"])) st.write('* **Genre** : ' + str(df_MovieSelectedOne.iloc[0]["genres"])) get_actor_pic_from_api(df_MovieSelectedOne.iloc[0]["tconst"],df_MovieSelectedOne.iloc[0]["actorsName"]) get_director_pic_from_api(df_MovieSelectedOne.iloc[0]["tconst"],df_MovieSelectedOne.iloc[0]["directorsName"]) get_writer_pic_from_api(df_MovieSelectedOne.iloc[0]["tconst"], df_MovieSelectedOne.iloc[0]["writersName"]) get_composer_pic_from_api(df_MovieSelectedOne.iloc[0]["tconst"], df_MovieSelectedOne.iloc[0]["composersName"]) preview_url = get_preview_from_api(IndiceFilm.iloc[0]) if preview_url != '': st.write("<iframe width='420' height='315' src="+ str(preview_url)+"> /iframe>", unsafe_allow_html=True) # Define Side Menu ---------------------------------------------- GenreList_list = st.sidebar.multiselect("Filtre par Genre", df_MovieSelectedOne.iloc[0]["genres"].split(",")) ActorList_list = st.sidebar.multiselect("Filtre par Acteur", df_MovieSelectedOne.iloc[0]["actorsName"].split(",")) DirectorList_list = st.sidebar.multiselect("Filtre apr Directeur", df_MovieSelectedOne.iloc[0]["directorsName"].split(",")) WriterList_list = st.sidebar.multiselect("Filtre par Scénariste", df_MovieSelectedOne.iloc[0]["writersName"].split(",")) if pd.notna(df_MovieSelectedOne.iloc[0]["composersName"]) : ComposerList_list = st.sidebar.multiselect("Filtre par Compositeur", df_MovieSelectedOne.iloc[0]["composersName"].split(",")) else : ComposerList_list = [] if st.button('Recommandez moi des Films !') : session_state.button_selected = True else : ActorList_list = [] DirectorList_list = [] GenreList_list = [] WriterList_list = [] ComposerList_list = [] if session_state.button_selected: Model = st.sidebar.radio("Type de recommandation",["Recommandation par Film","Recommandantion par Cinéphiles"]) df_Filtered = DisplayDataFrame(df_Movies,GenreList_list, DirectorList_list, ActorList_list, WriterList_list, ComposerList_list) if Model == "Recommandation par Film" : df_Display = KnnPrediction(df_Filtered,IndiceFilm) elif Model == "Recommandantion par Cinéphiles" : clust=df_Users[df_Users['tconst']==IndiceFilm.iloc[0]]['clusterId'].to_list() liste_film_user = df_Users[df_Users['clusterId'].isin(clust)] ModelScore = st.sidebar.radio("Prediction par ",["Popularité","Avis"]) if ModelScore == "Popularité" : df_Popularity=list(liste_film_user['tconst'].value_counts().nlargest(5).index) df_Display = df_Movies.loc[df_Movies['tconst'].isin(df_Popularity)] elif ModelScore == "Avis" : df_Avis=list(liste_film_user.groupby('tconst')['rating'].mean().nlargest(5).index) df_Display = df_Movies.loc[df_Movies['tconst'].isin(df_Avis)] if df_Display.shape[0] > 5 : df_Display = df_Display[0:5] x = st.slider('x', 1, df_Display.shape[0]) if x <= df_Display.shape[0]: DisplayPoster(get_poster_from_api(df_Display.iloc[x-1]["tconst"])) score = random.randint(67, 99) st.write('* **Recommandation** : ' + str(score) + '%') my_bar = st.progress(score) if pd.notna(df_Display.iloc[x-1]["originalTitle"]) : st.write('* **Titre** : ' + str(df_Display.iloc[x-1]["originalTitle"])) st.write('* **Résumé** : ' + str(get_overview_from_api(df_Display.iloc[x-1]["tconst"]))) if pd.notna(df_Display.iloc[x-1]["startYear"]) : st.write('* **Année de sortie** : ' + str(df_Display.iloc[x-1]["startYear"])) if pd.notna(df_Display.iloc[x-1]["runtimeMinutes"]) : st.write('* **Durée** : ' + str(df_Display.iloc[x-1]["runtimeMinutes"]) + ' min') if pd.notna(df_Display.iloc[x-1]["averageRating"]) : st.write('* **Note** : ' + str(df_Display.iloc[x-1]["averageRating"])) get_actor_pic_from_api(df_Display.iloc[x-1]["tconst"], df_Display.iloc[x-1]["actorsName"]) get_director_pic_from_api(df_Display.iloc[x-1]["tconst"],df_Display.iloc[x-1]["directorsName"]) get_writer_pic_from_api(df_Display.iloc[x-1]["tconst"], df_Display.iloc[x-1]["writersName"]) get_composer_pic_from_api(df_Display.iloc[x-1]["tconst"], df_Display.iloc[x-1]["composersName"]) preview_url = get_preview_from_api(df_Display.iloc[x-1]["tconst"]) if preview_url != '': st.write("<iframe width='420' height='315' src="+ str(preview_url)+"> /iframe>", unsafe_allow_html=True)
def getSessionState(): print ("Creating new session") return SessionState.get(logout=False, show_movie_count=0, show_reco_count=0, rec_dict={}, options=[], api_call=False)
import Cities import functions import time import mapbox from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.wsd import lesk import SessionState random.seed(123) search_terms = terms.total_terms st.title('Predicting Technology Trends') session_state = SessionState.get(a='Data Scientist', b=0, c=0) option = st.sidebar.text_input('Enter position title: ', value=session_state.a, key=9) dtotal = pd.read_csv('cleaned_df.csv') submit = st.sidebar.button('Search', key=1) if submit: session_state.a = option try: dtotal = dtotal[dtotal['title'].astype(str).str.contains(option)] except: pass total_length = len(dtotal) dtotal2 = dtotal['description']
except FileNotFoundError: exit() def get_file_content_as_string(file): return open('../dataset/' + file, 'r', encoding='utf-8').read() # def processContextWithNewParams(docs, param1, param2, param3, param4): # for i in docs: # docs[name]['contextobj'] = PC(docs[name]['data']) # return docs possible_db_name = os.listdir('../dataset') session_state = SessionState.get(user_name='qnabot', selectedfile=possible_db_name[0], rerun=False) docs = loadData(possible_db_name) instead_use_lemmanization = False placeholder = "Enter your Query here ..." stemmer = "No Stemmer" lemm_stemm_flag = "No" specific = False ut = UT() yesnoDict = {"Yes": True, "No": False} st.sidebar.title("Configure Your Bot") lemm_or_stemm = st.sidebar.selectbox("Stemming or Lemmanization of the word", ["None", "Stemming", "Lemmanization"]) if lemm_or_stemm == "Lemmanization":
import streamlit as st import time import SessionState import base64 import spacy from window_align import get_scoring_matrix_from_lines, make_alignment_dataframe from matchscoring import * session = SessionState.get(src_lines=[], tgt_lines=[], df=None) st.title("Windowed LASER Aligner") st.text("By Tarun") # current segmenter is one for english can customize later nlp = spacy.load('en_core_web_sm') def get_table_download_link(df): """Generates a link allowing the data in a given panda dataframe to be downloaded in: dataframe out: href string """ csv = df.to_csv(index=False) # some strings <-> bytes conversions necessary here b64 = base64.b64encode(csv.encode()).decode() href = f'<a href="data:file/csv;base64,{b64}">Right click and download csv file</a>' return href def get_alignment_df(src_lines, tgt_lines, src_lang="en", tgt_lang="en", window_size=5):
import streamlit as st import numpy as np import SessionState from streamlit.ScriptRunner import RerunException from streamlit.ScriptRequestQueue import RerunData state = SessionState.get(question_number=0, num_correct=0) @st.cache def get_question(question_number): arr = np.random.randint(0, 100, 2) q = f"{arr[0]} * {arr[1]}" ans = arr[0] * arr[1] choices = ["Please select an answer", ans, ans - 1, ans + 1, ans + 2] return arr, q, ans, choices arr, q, ans, choices = get_question(state.question_number) answered = False st.write(f"Your score is {state.num_correct}/{state.question_number}") st.write("") st.text(f"Solve: {q}") a = st.selectbox('Answer:', choices) if a != "Please select an answer": st.write(f"You chose {a}") if (ans == a): answered = True st.write(f"Correct!") else:
from serial.tools import list_ports from time import sleep import SessionState st.write("""# Hello""") port_name = st.selectbox("Select PORT", [port.device for port in list_ports.comports()]) speed = st.selectbox("Select speed", [115200]) connect_button = st.empty() disconnect_button = st.empty() start_button = st.empty() dataframe = [] state = SessionState.get(port=None, started=False, data=[]) if connect_button.button("Connect", key='connect'): state.port = serial.Serial(port=port_name, baudrate=115200, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE) connect_button.empty() if disconnect_button.button("Disconnect", key="disconnect"): state.port.close() state.port = None disconnect_button.empty() if state.port:
for chord, num in natural: note_map[chord] = num note_map[chord + 'm'] = num + 12 if chord not in ['E', 'B']: note_map[chord + '#'] = (num + 1) % 12 note_map[chord + '#' + 'm'] = note_map[chord + '#'] + 12 note_map['N'] = 24 # Reversing the mapping - map chord ids to chords, while sorting by chord id values first chords = {k: v for k, v in sorted(note_map.items(), key=lambda item: item[1])} st.title('ReChord') st.header('Create chord annotations of your favourite songs!') session_state = SessionState.get(name="", annotate_clicked=False) song = st.text_input('Enter Spotify link of the song to annotate', '') if st.button('Annotate'): session_state.annotate_clicked = True session_state.predictions = False session_state.interval = False session_state.wav_song = None session_state.song_name = None if session_state.annotate_clicked: if not session_state.predictions: session_state.predictions, session_state.wav_song, session_state.song_name = make_preds( song)
import streamlit as st import SessionState st.info("## Instructions\n" + "1. Type '2' into text input.\n" + "2. Press Enter.\n" + "3. Text changes as expected.\n" + "4. Type '3' into text input.\n" + "5. Press Enter.\n" + "6. Text instantly goes back to '2'.\n") session = SessionState.get(text="1") session.text = st.text_input("Text", session.text) st.write(session.text)
def main(): """Main function (loop for StreamLit).""" st.title('Closed-Form Factorization of Latent Semantics in GANs') st.sidebar.title('Options') reset = st.sidebar.button('Reset') model_name = st.sidebar.selectbox( 'Model to Interpret', ['stylegan_animeface512', 'stylegan_car512', 'stylegan_cat256', 'pggan_celebahq1024']) model = get_model(model_name) gan_type = parse_gan_type(model) layer_idx = st.sidebar.selectbox( 'Layers to Interpret', ['all', '0-1', '2-5', '6-13']) layers, boundaries, eigen_values = factorize_model(model, layer_idx) num_semantics = st.sidebar.number_input( 'Number of semantics', value=10, min_value=0, max_value=None, step=1) steps = {sem_idx: 0 for sem_idx in range(num_semantics)} if gan_type == 'pggan': max_step = 5.0 elif gan_type == 'stylegan': max_step = 2.0 elif gan_type == 'stylegan2': max_step = 15.0 for sem_idx in steps: eigen_value = eigen_values[sem_idx] steps[sem_idx] = st.sidebar.slider( f'Semantic {sem_idx:03d} (eigen value: {eigen_value:.3f})', value=0.0, min_value=-max_step, max_value=max_step, step=0.04 * max_step if not reset else 0.0) image_placeholder = st.empty() button_placeholder = st.empty() try: base_codes = np.load(f'latent_codes/{model_name}_latents.npy') except FileNotFoundError: base_codes = sample(model, gan_type) state = SessionState.get(model_name=model_name, code_idx=0, codes=base_codes[0:1]) if state.model_name != model_name: state.model_name = model_name state.code_idx = 0 state.codes = base_codes[0:1] if button_placeholder.button('Random', key=0): state.code_idx += 1 if state.code_idx < base_codes.shape[0]: state.codes = base_codes[state.code_idx][np.newaxis] else: state.codes = sample(model, gan_type) code = state.codes.copy() for sem_idx, step in steps.items(): if gan_type == 'pggan': code += boundaries[sem_idx:sem_idx + 1] * step elif gan_type in ['stylegan', 'stylegan2']: code[:, layers, :] += boundaries[sem_idx:sem_idx + 1] * step image = synthesize(model, gan_type, code) image_placeholder.image(image / 255.0)
import pandas as pd import streamlit as st import SessionState session = SessionState.get(columns=None) st.info("## Instructions:\n" + "1. Upload simple csv (like `data.csv` from this repo)\n" + "2. Check the box to choose column names\n" + "3. Deselect one of the column names\n" + "4. Try to add that column name back, note that it takes two tries\n") csv_file = st.file_uploader("File", type="csv") if csv_file is not None: dataframe = pd.read_csv(csv_file) all_columns = list(dataframe.columns) if session.columns is None: session.columns = all_columns.copy() if st.checkbox("Select Columns", False): session.columns = st.multiselect("Columns", all_columns, session.columns) st.write(dataframe.filter(list(session.columns)))
#result_files_paths = [os.path.join(RESULT_FILE_PATH, fname.split('.')[0]+'.json') for fname in input_files] #title_text_mapping_dict={} #title_json_mapping_dict={} #for index, file_path in enumerate(input_files_paths): # lines = open(file_path, 'r', encoding='utf-8').readlines() # title = lines[0] # text = ''.join(lines[1:]) # title_text_mapping_dict[title] = text # title_json_mapping_dict[title] = result_files_paths[index] #### Displaying Available examples import SessionState ss = SessionState.get(x=1) selected_title = list(zip(test_data.index, test_data.Insight))[ss.x] c1, c2 = st.columns(2) with c1: if st.button("Previous Insight"): ss.x = ss.x - 1 selected_title = list(zip(test_data.index, test_data.Insight))[ss.x] with c2: if st.button("Next Insight"): ss.x = ss.x + 1 selected_title = list(zip(test_data.index, test_data.Insight))[ss.x]