def createlayout(): # st.sidebar.title("Menu") query_params = st.experimental_get_query_params() app_check = st.experimental_get_query_params() session_state = SessionState.get(first_query_params=query_params) first_query_params = session_state.first_query_params app_check = {k: v[0] if isinstance(v, list) else v for k, v in app_check.items()} st.sidebar.title("Menu") page_list = ["Homepage", "Gender Gap", "Popular YouTubers"] # default_selectbox = int(app_check["selectbox"]) if "selectbox" in app_check else 0 default_selectbox = int(app_check["selectbox"]) if "selectbox" in app_check else 0 app_mode = st.sidebar.selectbox("Please select a page", page_list,index = default_selectbox) if app_mode: # app_check["selectbox"] = page_list.index(app_mode) # st.experimental_set_query_params(**app_check) app_check["selectbox"] = page_list.index(app_mode) st.experimental_set_query_params(**app_check) # app_mode = st.sidebar.selectbox("Please select a page", ["Homepage", "Gender Gap", "Popular YouTubers"]) if app_mode == "Homepage": homepage() elif app_mode == "Gender Gap": gendergap.load_page() elif app_mode == "Popular YouTubers": youtube_earnings.load_page()
def get_and_set_active_app(self): query_params = st.experimental_get_query_params() maybe_default_view_id = self.get_maybe_active_view_id(query_params) logger.debug('url view id: %s', maybe_default_view_id) modules_by_id = self.list_modules() logger.debug('loaded mods: %s', modules_by_id) view = None if len(modules_by_id.keys()) == 0: pass else: if len(modules_by_id.keys()) == 1: view_id = list(modules_by_id.values())[0]['id'] view = modules_by_id[view_id] else: sorted_mods = sorted(modules_by_id.values(), key=lambda nfo: nfo['index']) view_id = st.sidebar.selectbox( '', [nfo['id'] for nfo in sorted_mods], index=0 if maybe_default_view_id is None else modules_by_id[maybe_default_view_id]['index'], format_func=(lambda id: modules_by_id[id]['name'].upper())) view = modules_by_id[view_id] query_params[self.VIEW_APP_ID_VAR] = view_id st.experimental_set_query_params(**query_params) return view
def get_set_multiselection(widget, name='ConfirmedDeath', label='Select Type', options=['Death_Rate', 'Confirmed', 'Death'], default_choices=['Death_Rate', 'Confirmed'], key=None): ''' can use as widget: st.multiselect st.sidebar.multiselect ''' params = st.experimental_get_query_params() if not isinstance(params, dict): params = {} default_choices = params[name] if name in params else default_choices # default_indices = get_indices(options, default_choices) selections = widget(label=label, options=options, default=default_choices, key=key) dict_selections = {name: selections} params = {**params, **dict_selections} st.experimental_set_query_params(**params) return selections
def get_set_selection(widget, name='visualisation', label='Select Maps or Timeseries', options=['Maps', 'Timeseries'], key=None): ''' can use as widget: st.selectbox st.sidebar.selectbox st.radio st.sidebar.radio ''' params = st.experimental_get_query_params() if not isinstance(params, dict): params = {} default_choice = params[name][0] if name in params else -1 default_index = get_index(options, default_choice) selection = widget(label=label, options=options, index=default_index, key=key) dict_selection = {name: selection} params = {**params, **dict_selection} st.experimental_set_query_params(**params) return selection
def ensure_src_data_loaded(): """ Get source data file location from URL and try to load/decrypt it. Returns parsed source data as an object, or None if there was an error. If data could not be loaded, an appropriate error message and prompt will be added to UI. """ # Source data location passed in as query param (https://.../?src=) qps = st.experimental_get_query_params() src_qp = qps.get('src', [None])[0] pwd_qp = qps.get('pwd', [None])[0] # Password in URL is base 64 encoded if pwd_qp: try: pwd_qp = base64.b64decode(pwd_qp).decode('ascii') except: pwd_qp = None # Error if no source data file specified if src_qp is None: st.write( '<font color="red">No source file specified. Please reload this page using the link that was provided.</font>', unsafe_allow_html=True) return None # Placeholder for error message and password prompt if needed pwd_field = None # st_error = st.empty() # with st_error.beta_container(): # pwd_err_field = st.empty() # pwd_field = st.text_input('Enter password:'******'', type='password') # pwd_submit = st.button('Submit') # Prefer user input to query param pwd = pwd_field or pwd_qp # Update URL to include current password if pwd: qps['pwd'] = base64.b64encode(pwd.encode('ascii')).decode('ascii') st.experimental_set_query_params(**qps) # Fetch/decrypt data data = None try: data = load_data(src_qp, pwd) except FileNotFoundError: st_error.write('<font color="red">Could not locate the data file ' + src_qp + '</font>', unsafe_allow_html=True) except ValueError as e: pwd_err_field.write( '<font color="red">Incorrect password for specified data file.</font>', unsafe_allow_html=True) # Remove error message/prompt on success # if data is not None: # st_error.empty() return data
def page_work(state_container, page_flip: bool): '''Main page workhorse''' if not state_container.helpSessionState: state_container.helpSessionState = HelpSessionState() state = state_container.helpSessionState url_params = st.experimental_get_query_params() help_on = url_params.get('help_on', [''])[0] if not help_on: st.info('Nothing to show help about') st.stop() helpdir = os.path.dirname( find_spec('suzieq.gui.pages').loader.path) + '/help' page_help_on = help_sidebar(state, helpdir) helptext = '' with open(f'{helpdir}/{help_on}.md', 'r') as f: helptext = f.read() if helptext: st.markdown(helptext) st.experimental_set_query_params( **{'page': '_Help_', 'help_on': help_on})
def run(): st.set_page_config(page_title="Data Engineering QAQC", page_icon="📊") st.sidebar.markdown( """ <div stule="margin-left: auto; margin-right: auto;"> <img style='width:40%; margin: 0 auto 2rem auto;display:block;' src="https://raw.githubusercontent.com/NYCPlanning/logo/master/dcp_logo_772.png"> </div> """, unsafe_allow_html=True, ) datasets_list = list(datasets.keys()) query_params = st.experimental_get_query_params() if query_params: name = query_params["page"][0] else: name = "Home" name = st.sidebar.selectbox("select a dataset for qaqc", datasets_list, index=datasets_list.index(name)) st.experimental_set_query_params( page=datasets_list[datasets_list.index(name)]) app = datasets[name] app()
def get_field(self, field: str, default=None): field = self.prefix + field query_params = st.experimental_get_query_params() maybe_v = json.loads(urllib.parse.unquote( query_params[field][0])) if field in query_params else None out = default if maybe_v is None else maybe_v logger.debug('resolved default for %s as %s :: %s', field, out, type(out)) return out
def apprun(): '''The main application routine''' st.set_page_config(layout="wide", page_title="Suzieq") state = get_session_state() # state = SessionState.get(pages=None, prev_page='', search_text='', # sqobjs={}) if not state.pages: state.pages = build_pages() state.sqobjs = build_sqobj_table() url_params = st.experimental_get_query_params() if url_params.get('page', ''): page = url_params['page'] if isinstance(page, list): page = page[0] old_session_state = get_session_state( url_params.get('session', [''])[0]) if page == "_Path_Debug_": state.pages[page](old_session_state, True) st.stop() elif page == "_Help_": state.pages[page](old_session_state, None) st.stop() if isinstance(page, list): page = page[0] else: page = None # Hardcoding the order of these three pagelist = ['Status', 'Xplore', 'Path', 'Search'] for pg in state.pages: if pg not in pagelist: pagelist.append(pg) page, search_text = display_title(state.prev_page, state.search_text, pagelist) if state.search_text is None: state.search_text = '' if search_text != state.search_text: state.search_text = search_text if state.prev_page != page: page_flip = True else: page_flip = False state.prev_page = page state.pages[page](state, page_flip) if page not in ['Search']: state.sync()
def get_query_params(state: SessionState) -> Dict: query_params = st.experimental_get_query_params() params = [ 'emb_id', 'time_from', 'time_to', 'debug', 'n_results', 'search_type', 'scope', 'query', 'query_cause', 'query_effect', 'doc_results', 'umique_docs', 'top_n_ranking' ] for p in params: if p not in query_params and state[p] is not None: query_params[p] = state[p] return query_params
def read_query_params(state: SessionState): """ retrieve url query parameters and update the state """ for k, v in st.experimental_get_query_params().items(): if v[0].isnumeric(): state[k] = int(v[0]) else: if len(v) > 1: state[k] = v else: state[k] = v[0] if not v[0] == 'None' else None
def _fetch_url_field(key: str) -> str: """Fetch a single field from the url query string. Args: key: parameter name Returns: the parameter value as a string (prior to any necessary conversion) Raises: KeyError: if the field does not exist """ # TODO: raise error if multiple values in the query_string exist return streamlit.experimental_get_query_params()[key][ 0] # always a list, get the first
def main(): params = st.experimental_get_query_params() set_page_config() df = fetch_data() conditions_by_user = set_conditions_by_user(df) main_page() conditions_for_df = side_page(conditions_by_user) fig = draw_graph(df, conditions_for_df) side_page_action(fig) if 'action' in params and 'send_to_slack' == params['action'][0]: send_to_slack(fig)
def main(): title = "Music Genre Classifier" st.title(title) image = Image.open('./presentation/turntable-2154823_1920.jpg') st.image(image, use_column_width=True) if st.button('Record'): with st.spinner('Recording...'): signal = sd.rec(int(6 * RECORD_SR), samplerate=RECORD_SR, channels=1, blocking=True, dtype='float64') #sd.wait() signal = signal.reshape(signal.shape[0]) #st.write(signal.shape) #st.write(signal) new_num_samples = round( len(signal) * float(DESIRED_SR) / RECORD_SR) signal = sps.resample(signal, new_num_samples) # st.write(signal.shape) # st.write(type(signal)) # st.write(signal) st.experimental_set_query_params(signal=signal) st.success("Recording completed") app_state = st.experimental_get_query_params() if st.button('Play'): try: signal = np.array(app_state["signal"], dtype='float') # st.write(type(signal)) # st.write(signal.shape) temp_file = io.BytesIO() write(temp_file, 22050, signal) st.audio(temp_file, format='audio/wav') except: st.write("Please record sound first") if st.button('Classify'): with st.spinner("Thinking..."): signal = np.array(app_state["signal"], dtype='float') # st.write(type(signal)) # st.write(signal.shape) # st.write(signal) pred = model.predict(get_harm_perc(signal)) st.success("Classification completed") labels[np.argmax(pred)]
def get_home_page(self): query_params = st.experimental_get_query_params() if len(query_params) > 0 and query_params.get("type")[0] == "detail": st.set_page_config(initial_sidebar_state="collapsed", page_title=query_params.get("sym")[0], layout="wide") else: st.set_page_config(layout="wide") self.hide_footer() self.left_menu() # self.testing_mess() self.action_router(query_params)
def set_field(self, field: str, val): field = self.prefix + field query_params = st.experimental_get_query_params() logger.debug('params at set: %s', query_params.items()) logger.debug('rewriting field %s val %s as %s', field, val, urllib.parse.quote(json.dumps(val), safe='')) query_params = st.experimental_set_query_params( **{ **{k: v[0] for k, v in query_params.items()}, **{ field: urllib.parse.quote(json.dumps(val), safe='') } })
def _get_state_from_url(self): url_params = st.experimental_get_query_params() page = url_params.pop('page', '') if self._title in page: if url_params and not all(not x for x in url_params.values()): for key, val in url_params.items(): if isinstance(val, list): val = val[0].strip() if not val: continue if hasattr(self._state, key): if isinstance(getattr(self._state, key), bool): val = val == 'True' setattr(self._state, key, val)
def get_set(widget, session_state, name, key=None, *args, **kwargs): if key == None: key = name kwargs['key'] = key params = st.experimental_get_query_params() if not isinstance(params, dict): params = {} selection = widget(**kwargs) dict_selection = {name: selection} params = {**params, **dict_selection} params = limit_2_allowed_keys(session_state, params) st.experimental_set_query_params(**params) return selection
def authenticate(header=None, stop_if_unauthenticated=True): query_params = st.experimental_get_query_params() authorization_code = query_params.get("code", [None])[0] if authorization_code is None: authorization_code = query_params.get("session", [None])[0] if authorization_code is None: login_header(header=header) if stop_if_unauthenticated: st.stop() return else: logout_header(header=header) strava_auth = exchange_authorization_code(authorization_code) logged_in_title(strava_auth, header) st.experimental_set_query_params(session=authorization_code) return strava_auth
def authenticate(url='http://heroku.com'): client = GoogleOAuth2(client_id, client_secret) authorization_url = asyncio.run( write_authorization_url(client=client, redirect_uri=redirect_uri)) session_state = get(token=None) if session_state.token is None: try: code = st.experimental_get_query_params()['code'] except: st.write(f''' <h1> Please login here: <a target="_self" href="{authorization_url}">Login</a></h1> ''', unsafe_allow_html=True) else: try: token = asyncio.run( write_access_token(client=client, redirect_uri=redirect_uri, code=code)) except: st.write(f''' <h1> This account is not allowed or page was refreshed. Please try again: <a target="_self" href="{authorization_url}">Login</a></h1> ''', unsafe_allow_html=True) else: if token.is_expired(): if token.is_expired(): st.write(f'''<h1> Login session has ended, please log in again: <a target="_self" href="{authorization_url}">Login</a></h1> ''') else: session_state.token = token initialize() else: initialize()
def page_work(state_container, page_flip: bool): '''Main page workhorse''' pathSession = state_container.pathSessionState if pathSession: pathobj = getattr(pathSession, 'pathobj', None) else: st.error('No saved path session found.') st.stop() if not pathobj: st.error('No saved path object found.') st.stop() path_debug_sidebar(pathSession) url_params = st.experimental_get_query_params() if url_params.get('lookupType', 'hop') == ['hop']: handle_hop_url(url_params, pathSession) else: handle_edge_url(url_params, pathSession)
def query_params(): st.write(""" # Introducing Query Params We have added to our experimental namespace the ability to get and set query parameters. With these query params, you can bookmark or share your app in various states. Thanks [@zhaoooyue](https://github.com/zhaoooyue) for the contribution! """) with st.echo("below"): radio_list = ['Eat', 'Sleep', 'Both'] query_params = st.experimental_get_query_params() # Query parameters are returned as a list to support multiselect. # Get the first item in the list if the query parameter exists. default = int( query_params["activity"][0]) if "activity" in query_params else 0 activity = st.radio("What are you doing at home during quarantine?", radio_list, index=default) if activity: st.experimental_set_query_params( activity=radio_list.index(activity))
def build_portfolio(): if portfolio_name == 'explore': base_investment = float( st.sidebar.slider('Investment CHF/asset: ', 100, 5000, 500, 100)) asset_list = fetch_asset_list() monitoring = ('BTC', 'DOGE', 'XRP', 'ETH', 'LTC', 'DOT', 'SOL') exploratory_assets = st.sidebar.multiselect('Select assets', asset_list, default=monitoring) portfolio_open_date = st.sidebar.date_input('Portfolio opening date:') portfolio = pd.DataFrame() if len(exploratory_assets) == 0: st.stop() for asset in exploratory_assets: instrument_name = f"{asset}-CHF" quote = fetch_historical_quote(instrument_name, portfolio_open_date) if float(quote[asset]['CHF']) == 0: st.text(f"No historical data available for {asset}") continue portfolio = portfolio.append( pd.DataFrame( { 'amount': base_investment / float(quote[asset]['CHF']), 'value': base_investment, 'direction': 'long' }, index=[instrument_name])) return portfolio else: url = st.experimental_get_query_params().get('portfolio_url')[0] s = requests.get(url).content return pd.read_csv(io.StringIO(s.decode('utf-8')), header=0, index_col=0)
def main(): st.set_page_config(page_title="DEAL OR NO DEAL", page_icon="🤑", initial_sidebar_state="expanded") st.sidebar.title('DEAL OR NO DEAL') selected_banker = st.sidebar.selectbox( 'Pick your Banker', ['Random Forest', 'LightGBM', 'XGBoost'], 0) if st.sidebar.button('New Game'): new_game() st.sidebar.markdown(""" This is a simulation of the Deal or No Deal Banker's offers. The code for this project can be found at [my Github](https://github.com/jstock29/dealnodeal) and the data that I painstakingly collected from over 100 episodes of the show is on [my Kaggle](https://www.kaggle.com/jaredstock/deal-or-no-deal-game-data). You can see what the RoboBanker will offer by simulating a board at various rounds. Each round you should pick the correct number of values from the board: 1. Pick 6 - 6 Total 2. Pick 5 - 11 Total 3. Pick 4 - 15 Total 4. Pick 3 - 18 Total 5. Pick 2 - 20 Total 6. Pick 1 - 21 Total 7. Pick 1 - 22 Total 8. Pick 1 - 23 Total 9. Pick 1 - 24 Total 10. Pick 1 -25 Total After each round you can see what my RoboBanker is offering you and decide if that's a deal you want to take or not. I will not give you that money though. FYI: Anonymous game data is sent to my database so I can maybe do stuff with it later. I don't know why that would sketch you out, this is all fake, but there you go. """) st.sidebar.caption('Jared Stock | NYC | 2021') app_state = st.experimental_get_query_params() game_id = app_state['game_id'][0] round_number = int(app_state['round_number'][0]) prev_offer = float(app_state['prev_offer'][0]) offer = 0. # st.write(app_state) st.header('Board') st.write('') col1, col2, col3 = st.beta_columns(3) l_cols = VALUES[:len(VALUES) // 2] r_cols = VALUES[len(VALUES) // 2:] model = joblib.load(f'bankers/{selected_banker}.pkl') with col1: values_1 = [ st.checkbox(str(val), key=session.run_id) for val in VALUES[:len(VALUES) // 2] ] left_sum = sum( [val for i, val in enumerate(l_cols) if not values_1[i]]) with col2: values_2 = [ st.checkbox(str(val), key=session.run_id) for val in VALUES[len(VALUES) // 2:] ] right_sum = sum( [val for i, val in enumerate(r_cols) if not values_2[i]]) values = values_1 + values_2 choices = [val for i, val in enumerate(VALUES) if values[i]] remaining = [val for i, val in enumerate(VALUES) if not values[i]] remaining_bigs = [_ for _ in remaining if _ in BIG_VALUES] average = np.average(remaining) _max = max(remaining) if right_sum == 0: balance = (left_sum / L_SUM) elif left_sum == 0: balance = (right_sum / R_SUM) else: balance = (right_sum / R_SUM) / (left_sum / L_SUM) ev = expected_value(remaining) with col3: st.subheader('Info') st.write(f'Round: {round_number}') st.write(f'Picked: {len(choices)}') st.write(f'Previous Offer: {prev_offer}') st.write(f'Expected Value: {round(ev, 0)}') st.write( f'Probability of having a big value: {round(len(remaining_bigs) / len(remaining) * 100, 1)}%' ) st.subheader('Banker Offer') if len(choices) > 5: X = pd.DataFrame({ 'Round': [round_number], 'Board Average': [ev], 'Previous Offer': [prev_offer] }) p = model.predict(X) offer = float(p[0]) st.write(f'Offer: ${round(float(offer), 2)}') if offer / ev <= 1: st.progress(offer / ev) else: st.progress(1) st.caption( f'Offer % of Expected Value: {round((offer / ev) * 100, 2)}%') else: st.info('Pick values to see offers') col14, col15 = st.beta_columns(2) if len(choices) == 6 or len(choices) == 11 or len(choices) == 15 or len( choices) == 18 or len(choices) >= 20: with col14: if st.button('Deal!'): round_data = { "Game ID": game_id, "Round": round_number, "Remaining Values": str(remaining), "Board Value": sum(remaining), "Board Average": round(average, 0), "Board Balance": round(balance, 3), "Probability of Big Value": round(len(remaining_bigs) / len(remaining), 3), "Previous Offer": prev_offer, "Offer": round(offer, 0), "Offer Percent of Average": round(offer / average, 4), "model": selected_banker, "datetime": datetime.datetime.now(), "Deal": True } df = pd.DataFrame(round_data, index=[0]) populate_round(df, 'player_games') with col15: if st.button('No Deal!'): round_data = { "Game ID": game_id, "Round": round_number, "Remaining Values": str(remaining), "Board Value": sum(remaining), "Board Average": round(average, 0), "Board Balance": round(balance, 3), "Probability of Big Value": round(len(remaining_bigs) / len(remaining), 3), "Previous Offer": prev_offer, "Offer": round(offer, 0), "Offer Percent of Average": round(offer / average, 4), "model": selected_banker, "datetime": datetime.datetime.now(), "Deal": False } round_number += 1 st.experimental_set_query_params(round_number=round_number, game_id=game_id, prev_offer=round(offer, 0)) df = pd.DataFrame(round_data, index=[0]) populate_round(df, 'player_games') data = get_data('player_games') data = data.loc[data['Game ID'] == game_id] if st.checkbox('Show data'): st.write(data) visualization.single_line(data, game_id, width=600, height=400)
'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 main(): st.set_page_config(page_title="DEAL OR NO DEAL", page_icon="🤑", initial_sidebar_state="expanded") st.sidebar.title('DEAL OR NO DEAL') selected_banker = st.sidebar.selectbox( 'Pick your Banker', ['Random Forest', 'LightGBM', 'XGBoost'], 0)
VORONOI = "Static Embed: Trader Joes Voronoi Map" WIKI = "Static Embed: Bar Chart Race of Wikipedia Views" FORM = "Bi-Directional Embed: HTML Form" DRAW = "Bi-Directional Embed: Drawing Canvas" COUNTIES = "Bi-Directional Embed: Selecting Counties" MATRIX = "Bi-Directional Embed: Matrix Input" def explain_btn(section): return st.checkbox("Explain this to me!", key=f"explain_{section}") sections = list(map(lambda d: d.value, Section)) section_i = 0 section_param = st.experimental_get_query_params().get("section") if section_param and section_param[0] in sections: section_i = sections.index(section_param[0]) section = st.sidebar.radio("Section", sections, index=section_i) st.sidebar.markdown(""" Made by [Alex Garcia](https://twitter.com/agarcia_me) 🦒 """) if section == Section.INTRO.value: st.experimental_set_query_params(section=Section.INTRO.value) st.write(""" # Introducing [`streamlit-observable`](https://github.com/asg017/streamlit-observable)!
def main(): st.title("COVID SCRIPTS of René Smit") # [n. name in menu, module name] options = [ ["0. welcome", "welcome"], ["1. covid dashboard", "covid dashboard rcsmit"], ["2. plot hosp ic per age", "plot hosp ic streamlit"], [ "3. false positive rate covid test", "calculate false positive rate covid test streamlit" ], ["4. number of cases interactive", "number of cases interactive"], ["5. ifr from prevalence", "calculate_ifr_from_prevalence_streamlit"], ["6. fit to data", "fit to data streamlit"], ["7. SEIR hobbeland", "SEIR hobbeland"], ["8. show contactmatrix", "show contactmatrix"], ["9. r getal per provincie", "r getal per provincie"], ["10. Cases from suspectibles", "cases_from_susp_streamlit"], ["11. Fit to data OWID", "fit_to_data_owid_streamlit_animated"], [ "12. Calculate R per country owid", "calculate_r_per_country_owid_streamlit" ], ["13. Covid dashboard OWID/Google or Waze", "covid dashboard owid"], [ "14. Dag verschillen per leeftijd", "dag_verschillen_casus_landelijk" ], ["15. Calculate spec./abs. humidity from rel. hum", "rh2q"], ["16. R getal per leeftijdscategorie", "r_number_by_age"], ["17. Show rioolwaardes", "show_rioolwater"], ["18. SIR model met leeftijdsgroepen", "SIR_age_structured_streamlit"], [ "19. grafiek pos testen per leeftijdscat", "grafiek pos testen per leeftijdscategorie streamlit" ], ["20. per provincie per leeftijd", "perprovincieperleeftijd"], ["21. kans om covid op te lopen", "kans_om_covid_op_te_lopen"], ["22. Data per gemeente", "vacc_inkomen_cases"], ["23. VE Israel", "israel_zijlstra"], ["24. Hosp/death NL", "cases_hospital_decased_NL"], ["25. VE Nederland", "VE_nederland_"], ["26. Scatterplots QoG OWID", "qog_owid"], ["27. VE & CI calculations", "VE_CI_calculations"], ["28. VE scenario calculator", "VE_scenario_calculator"], ["29. VE vs inv. odds", "VE_vs_inv_odds"], [ "30. Fit to data Levitt", "fit_to_data_owid_levitt_streamlit_animated" ], [ "31. Aerosol concentration in room by @hk_nien", "aerosol_in_room_streamlit" ], ["32. Compare two variants", "compare_two_variants"], ["33. Scatterplot OWID", "scatterplots_owid"], ["34. Playing with R0", "playing_with_R0"] ] query_params = st.experimental_get_query_params( ) # reading the choice from the URL.. choice = int( query_params["choice"][0] ) if "choice" in query_params else 0 # .. and make it the default value if choice == 99: #sandbox try: module = dynamic_import("various_test_and_sandbox") except Exception as e: st.error(f"Module not found or error in the script\n") st.warning(f"{e}") st.stop() try: module.main() except Exception as e: st.error( f"Function 'main()' in module '{module}' not found or error in the script" ) st.warning(f"{e}") st.warning(traceback.format_exc()) st.stop() st.stop() menuchoicelist = [options[n][0] for n, l in enumerate(options)] with st.sidebar.expander( 'MENU: Choose a script | scroll down for options/parameters', expanded=True): menu_choice = st.radio("", menuchoicelist, index=choice) st.sidebar.markdown("<h1>- - - - - - - - - - - - - - - - - </h1>", unsafe_allow_html=True) st.experimental_set_query_params(choice=menuchoicelist.index( menu_choice)) # setting the choice in the URL for n, l in enumerate(options): if menu_choice == options[n][0]: m = options[n][1].replace( " ", "_") # I was too lazy to change it in the list try: module = dynamic_import(m) except Exception as e: st.error(f"Module '{m}' not found or error in the script\n") st.warning(f"{e}") st.stop() try: module.main() except Exception as e: st.error( f"Function 'main()' in module '{m}' not found or error in the script" ) st.warning(f"{e}") st.warning(traceback.format_exc()) st.stop()
f.close() mname = 'facebook/blenderbot-90M' model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname) tokenizer = BlenderbotSmallTokenizer.from_pretrained(mname) return tokenizer, model @st.cache(allow_output_mutation=True) def Namer(name): a = name return a tokenizer, model = Loader() app_state = st.experimental_get_query_params() if app_state == {}: with st.form(key='columns_in_form'): cont0 = st.empty() cont0.beta_container() col03, col01, col02, col04 = cont0.beta_columns([0.15, 1, 0.20, 0.15]) nInputobj = col01.empty() nInput = nInputobj.text_input("Your name please:") contextobj = col02.empty() context = contextobj.selectbox("context", ('2', '3', '4', '5')) context = int(context) - 1 submitted = col02.form_submit_button('Submit') # f = open("animations/face-scan.json")
# this means that log messages from your code and log messages from the # libraries that you use will all show up on the terminal. #coloredlogs.install(level='DEBUG') # If you don't want to see log messages from libraries, you can pass a # specific logger object to the install() function. In this case only log # messages originating from that logger will show up on the terminal. #coloredlogs.install(level='DEBUG', logger=logger) st.set_page_config( page_title="Heya, world?", page_icon=":shark:", ) st.title('Test App 🕶!!!') log_text = st.text_input('Log text:') if st.button("send log"): logging.info(log_text) st.write(st.experimental_get_query_params()) query_param = st.text_input("query param:") if st.button('set query param'): st.experimental_set_query_params(test=query_param) st.write(st.beta_secrets) #st.header('Ysy') #st.video('https://www.youtube.com/watch?v=mLUZel-6p-g')
def get_url_app(): try: return st.experimental_get_query_params()["app"][0] except KeyError: return "index"