def get_tweets(user_name, tweet_count): tweets_list = [] img_url = "" name = "" try: for tweet in api.user_timeline(id=user_name, count=tweet_count, tweet_mode="extended"): tweets_dict = {} tweets_dict["date_created"] = tweet.created_at tweets_dict["tweet_id"] = tweet.id tweets_dict["tweet"] = tweet.full_text tweets_list.append(tweets_dict) img_url = tweet.user.profile_image_url name = tweet.user.name screen_name = tweet.user.screen_name desc = tweet.user.description except BaseException as e: st.exception( "Failed to retrieve the Tweets. Please check if the twitter handle is correct." ) sys.exit(1) return tweets_list, img_url, name, screen_name, desc
def handle_uncaught_app_exception(e: BaseException) -> None: """Handle an exception that originated from a user app. By default, we show exceptions directly in the browser. However, if the user has disabled client error details, we display a generic warning in the frontend instead. """ error_logged = False if config.get_option("logger.enableRich"): try: # Print exception via rich # Rich is only a soft dependency # -> if not installed, we will use the default traceback formatting _print_rich_exception(e) error_logged = True except Exception: # Rich is not installed or not compatible to our config # -> Use normal traceback formatting as fallback # Catching all exceptions because we don't want to leave any possiblity of breaking here. error_logged = False if config.get_option("client.showErrorDetails"): if not error_logged: # TODO: Clean up the stack trace, so it doesn't include ScriptRunner. LOGGER.warning("Uncaught app exception", exc_info=e) st.exception(e) else: if not error_logged: # Use LOGGER.error, rather than LOGGER.debug, since we don't # show debug logs by default. LOGGER.error("Uncaught app exception", exc_info=e) st.exception(UncaughtAppException(e))
def ttest_power_ui(): '''The Power Analysis for Two-sample Student's t-test section. ''' # Render the header. with st.beta_container(): st.title('Two-sample Student\'s t-test') st.header('Power analysis') # Render input boxes and plots with st.beta_container(): param_list = ['Standardized effect size', 'alpha (1 - Significance level)', 'Power (1 - beta)', 'Group A sample size'] param_name = {'Standardized effect size': 'effect_size', 'alpha (1 - Significance level)': 'alpha', 'Power (1 - beta)': 'power', 'Group A sample size': 'n1'} param_default = { 'Standardized effect size': {'min_value': 0.0, 'value': 0.2}, 'alpha (1 - Significance level)': {'min_value': 0.01, 'max_value': 0.5, 'value': 0.05}, 'Power (1 - beta)': {'min_value': 0.01, 'max_value': 0.99, 'value': 0.8}, 'Group A sample size': {'min_value': 10, 'value': 1000}} kwargs = {} unknown_param = st.selectbox('Solve for: ', param_list) param_list.remove(unknown_param) for param in param_list: kwargs[param] = st.number_input(param, **param_default[param]) kwargs = {param_name[param]: kwargs[param] for param in param_list} kwargs['ratio'] = st.number_input('Sample size Ratio (Group B : Group A)', min_value=0.01, value=1.0) try: value, fig = sm_tt_ind_solve_power(**kwargs) except: st.exception('The solution is out of bound. Please adjust the input parameters. ') st.stop() st.success('{}: `{:.4f}`'.format(unknown_param, value)) st.write(fig, width=200)
def testStatus(): import time # 进度条 my_bar = st.progress(0) for percent_complete in range(5): time.sleep(0.1) my_bar.progress((percent_complete + 1) * 20) # 代码段运行时显示的信息 with st.spinner('Wait for it...'): time.sleep(2) st.success('Done!') selected1 = st.selectbox("选择测试消息类型:", ("庆祝气球", "错误", "警告", "提示", "成功", "异常")) if selected1 == "庆祝气球": st.balloons() elif selected1 == "错误": st.error('This is an error') elif selected1 == "警告": st.warning('This is a warning') elif selected1 == "提示": st.info('This is a purely informational message') elif selected1 == "成功": st.success('This is a success message!') elif selected1 == "异常": e = RuntimeError('This is an exception of type RuntimeError') st.exception(e)
def _read_from_cache(mem_cache, key, persist, allow_output_mutation, func_or_code, hash_funcs=None): """Read a value from the cache. Our goal is to read from memory if possible. If the data was mutated (hash changed), we show a warning. If reading from memory fails, we either read from disk or rerun the code. """ try: return _read_from_mem_cache(mem_cache, key, allow_output_mutation, func_or_code, hash_funcs) except CachedObjectMutationError as e: st.exception(CachedObjectMutationWarning(e)) return e.cached_value except CacheKeyNotFoundError as e: if persist: value = _read_from_disk_cache(key) _write_to_mem_cache(mem_cache, key, value, allow_output_mutation, func_or_code, hash_funcs) return value raise e
def read_file_from_url(url): try: return requests.get(url).content except requests.exceptions.RequestException: st.error("Unable to load file from %s. " "Is the internet connected?" % url) except Exception as e: st.exception(e) return None
def read_file_from_url(url): try: return urllib.request.urlopen(url).read() except urllib.error.URLError: st.error('Unable to load file from %s. ' 'Is the internet connected?' % url) except Exception as e: st.exception(e) return None
def load_csv(file_selected_path, nrows): try: if nrows == -1: df = pd.read_csv(file_selected_path) else: df = pd.read_csv(file_selected_path, nrows=nrows) except Exception as ex: df = pd.DataFrame([]) st.exception(ex) return df
def test_st_exception(self): """Test st.exception.""" e = RuntimeError("Test Exception") st.exception(e) el = self.get_delta_from_queue().new_element self.assertEqual(el.exception.type, "RuntimeError") self.assertEqual(el.exception.message, "Test Exception") # We will test stack_trace when testing # streamlit.elements.exception_element self.assertEqual(el.exception.stack_trace, [])
def render_ui(self) -> None: try: if isinstance(self._output_data, BaseModel): self._render_single_output(st, self._output_data) return if type(self._output_data) == list: self._render_list_output(st, self._output_data) return except Exception as ex: st.exception(ex) # Fallback to st.json(jsonable_encoder(self._output_data))
def app(): st.markdown(""" *Получение предсказаний модели* """) df = get_dataframe_from_query( Query([ db.Model.name.label('Модель'), db.Model.description.label('Описание'), db.Model.params.label('Параметры модели'), db.Model.metrics.label('Метрики'), db.Dataset.name.label('Датасет'), case([(db.Model.pretrained, 'Да'), (~db.Model.pretrained, 'Нет')]).label('Предобученная'), db.Model.training_time.label('Время обучения, с'), db.Model.created_at.label('Дата обучения'), ]).join(db.Project).join(db.Dataset).order_by(desc( db.Model.created_at))) st.dataframe(df) selected_model = st.selectbox('Выбор модели', df['Модель'].unique()) photo = st.file_uploader('Фотография', type=['png', 'jpg', 'jpeg']) if photo: st.image(photo) predict_button = st.button('Предсказать') if predict_button: if not photo: st.error('Необходимо загрузить фото') else: with create_session() as session: model_path = (session.query(db.Model.path).filter( db.Model.name == selected_model).first()[0]) with open('temp.png', 'wb') as f: f.write(photo.read()) try: kwargs = { 'path': 'temp.png', 'n_crops': 228, 'path_out': 'res.png', 'top_k': 3, 'type': 'window', # or 'random' 'canny_crop': False, 'model_path': str(model_path), } main(**kwargs) st.image('res.png') except Exception as e: st.exception(e)
def show_messages() -> None: st.header("Message types") with st.echo(): st.info("This is just some information") with st.echo(): st.success("This is a **success** message") with st.echo(): st.warning("This is a _warning_ message") with st.echo(): st.error("This is an __error__ message") with st.echo(): st.exception("This is an error message") st.exception(RuntimeError("This is a runtime error"))
def run_app(tp, fp, missing_df, extra_df): dfname = get_dfname() col1, _ = st.beta_columns([4, 1]) # container = st.beta_container() # container = st.empty() if dfname == "True Positive": col1.subheader("True Positive Data") df, image_name = get_tp_df(tp) elif dfname == "False Positive": col1.subheader("False Positive Data") df, image_name = get_fp_df(fp) elif dfname == "Missing Detections": col1.subheader("Missing Predictions") df, image_name = get_missing_df(missing_df) else: col1.subheader("Extra Predictions") df, image_name = get_extra_df(extra_df) col1.write(df) show_image = st.sidebar.checkbox("Check to display image", False) if show_image: img_resize = st.sidebar.slider("Resize Image", min_value=1, max_value=10, value=9, step=1) if img_resize > 5: img_resize = (10 % img_resize) + 1 elif img_resize == 5: img_resize = 6 elif img_resize == 4: img_resize = 7 elif img_resize == 3: img_resize = 8 elif img_resize == 2: img_resize = 9 elif img_resize == 1: img_resize = 10 if image_name == "all_images": st.exception(RuntimeError("cannot show all_images")) else: try: image = Image.open(os.path.join("images", image_name)) width, height = image.size image = image.resize( (width // img_resize, height // img_resize)) st.image(image, caption=image_name, use_column_width=False) # container.empty() except: st.error("Image %s not found " % image_name)
def main(): st.title("NLP-ify with streamlit") st.subheader("Natural Language Processing on a go") # Tokenization if st.checkbox("Show Tokens and Lemmatization"): st.subheader("Tokenize your text") message = st.text_area("Enter Your Text", "Type Here") if st.button("Analyze"): nlp_result = text_analyzer(message) st.json(nlp_result) # Sentiment Analysis if st.checkbox("Show Sentiment Analysis"): st.subheader("Sentiment of Your Text") message = st.text_area("Enter Your Text", "Type Here") if st.button("Analyze"): blob = TextBlob(message) result_sentiment = blob.sentiment st.success(result_sentiment) # Text Summarization if st.checkbox("Show Text Summarization"): st.subheader("Summarize Your Text") message = st.text_area("Enter Your Text", "Type Here") summary = st.selectbox("Choose your summarizer", ('gensim', 'sumy')) if st.button("Summarize"): if summary == 'gensim': try: st.text("Using Gensim...") summary_result = summarize(message) st.success(summary_result) except: st.exception("Input must have more than one sentence.") elif summary == 'sumy': try: st.text("Using Sumy...") summary_result = sumy_sumarizer(message) st.success(summary_result) except: st.exception("Input correct things.") st.sidebar.subheader('About the App') st.sidebar.markdown('## NLP-ify App with Streamlit') st.sidebar.info("#### Get the Tokens of your text") st.sidebar.info("#### Get the Named-Entities of your text") st.sidebar.info("#### Get the Sentiment Analysis of your text") st.sidebar.info("#### Get the Summary of your text")
def main(): data = pd.read_csv("research-and-development-survey-2019-csv.csv") data_1 = pd.read_csv( "greenhouse-gas-emissions-by-region-industry-and-household-year-ended-2018-csv.csv" ) st.dataframe(data) st.table(data.iloc[0:10]) st.dataframe(data_1) st.table(data_1.iloc[0:10]) st.line_chart(data_1) st.json({'foo': 'bar', 'fu': 'ba'}) st.beta_container() st.beta_columns(4) col1, col2 = st.beta_columns(2) col1.subheader('Columnisation') st.beta_expander('Expander') with st.beta_expander('Expand'): st.write('Juicy deets') st.sidebar.write("# Noniot") a = st.sidebar.radio('R:', [1, 2]) st.button('Hit me') st.checkbox('Check me out') st.radio('Radio', [1, 2, 3]) st.selectbox('Select', [1, 2, 3]) st.multiselect('Multiselect', [1, 2, 3]) st.slider('Slide me', min_value=0, max_value=10) st.select_slider('Slide to select', options=[1, '2']) st.text_input('Enter some text') st.number_input('Enter a number') st.text_area('Area for textual entry') st.date_input('Date input') st.time_input('Time entry') st.file_uploader('File uploader') st.color_picker('Pick a color') st.progress(90) st.spinner() with st.spinner(text='In progress'): time.sleep(5) st.success('Done') st.balloons() st.error('Error message') st.warning('Warning message') st.info('Info message') st.success('Success message') st.exception("e")
def handle_uncaught_app_exception(e: BaseException) -> None: """Handle an exception that originated from a user app. By default, we show exceptions directly in the browser. However, if the user has disabled client error details, we display a generic warning in the frontend instead. """ if config.get_option("client.showErrorDetails"): LOGGER.warning(traceback.format_exc()) st.exception(e) # TODO: Clean up the stack trace, so it doesn't include ScriptRunner. else: # Use LOGGER.error, rather than LOGGER.debug, since we don't # show debug logs by default. LOGGER.error("Uncaught app exception", exc_info=e) st.exception(UncaughtAppException(e))
def FrameCapture(path, buffer): vidObj = cv2.VideoCapture(path) count = 0 success = 1 while success: success, image = vidObj.read() try: cv2.imwrite("frame%d.jpg" % count, image) except: pass st.exception( "Either loop has reached last frame or one frame is errored out" ) count += buffer st.success("Finished with " + count + " images")
def menu_graph_generator(): """ Side menu configurations for graph generator Used into menu.py file """ st.sidebar.markdown("--------------") st.sidebar.markdown("**Generate a new Graph**") dataset_path = st.sidebar.text_input("Dataset Path", value="./data/conte_followers.csv") follower_number = st.sidebar.number_input("Number of users in the graph", min_value=1, max_value=2000, value=500) level2_path = st.sidebar.text_input("Level 2 followers path", value="./data/conte_followers") graph_name_list = ["500-users", "1000-users", "1500-users", "2000-users"] graph_name = st.sidebar.selectbox("Graph name", graph_name_list) graph_direct = st.sidebar.checkbox( "Check the box if you want to generate a direct graph", True) button_graph_generator = st.sidebar.button("Launch the Graph generator", key="b2") if button_graph_generator: try: # load the dataframe with st.spinner("Start creating the graph...please be patient.."): df = pd.read_csv(dataset_path) # create the graph result = create_graph(df, follower_number, level2_path, graph_name, graph_direct) st.success( f"Graph: **{graph_name}** created succesfully with: **{result}** number of nodes" ) print("\nSimulation completed") return True except Exception as message: st.error( f"Impossible to read the csv file, please check the path or the code and retry.. {message}" ) st.exception( "WARNING: Impossible to read the csv file, check the path") print("\nImpossible to complete the simulation") return False
def test_st_exception(self, show_tracebacks: bool): """Test st.exception.""" # client.showTracebacks has no effect on code that calls # st.exception directly. This test should have the same result # regardless fo the config option. with testutil.patch_config_options( {"client.showTracebacks": show_tracebacks}): e = RuntimeError("Test Exception") st.exception(e) el = self.get_delta_from_queue().new_element self.assertEqual(el.exception.type, "RuntimeError") self.assertEqual(el.exception.message, "Test Exception") # We will test stack_trace when testing # streamlit.elements.exception_element self.assertEqual(el.exception.stack_trace, [])
def run_filters(num_nodes, num_edges): try: import cudf except Exception as e: st.exception(RuntimeError('Failed importing cudf')) raise e nodes_df = cudf.DataFrame({ 'n': [x for x in range(0, num_nodes)] }) edges_df = cudf.DataFrame({ 's': [x % num_nodes for x in range(0, num_edges)], 'd': [(x+1) % num_nodes for x in range(0, num_edges)], }) graph_url = graphistry.nodes(nodes_df).edges(edges_df) \ .bind(source='s', destination='d', node='n')\ .plot(render=False) return { 'nodes_df': nodes_df.to_pandas(), 'edges_df': edges_df.to_pandas(), 'graph_url': graph_url }
def main( ) : st.title( "hello streamlit project!" ) name = '김나나' st.text("안녕하세요 저는 {}입니다.".format(name)) st.header("안녕하세요") st.header('안녕하세요') # 큰따옴표, 작은 따옴표 상관 없이 결과는 같음 st.markdown("# 큰글자") # 글자 굵게 st.markdown("## 중간글자") # 일반 #st 더 작은 글자?? st.success('성공했을때~') st.warning('경고를 하고 싶을때') st.info('인포를 주고 싶을때') st.error('에러가 발생했음을 알리고 싶을때') st.exception('예외 상황이 발생했을때')
def test_st_exception(self): """Test st.exception.""" e = RuntimeError("Test Exception") st.exception(e) el = self.get_delta_from_queue().new_element self.assertEqual(el.exception.type, "RuntimeError") self.assertEqual(el.exception.message, "Test Exception") # We will test stack_trace when testing # streamlit.elements.exception_element if sys.version_info >= (3, 0): self.assertEqual(el.exception.stack_trace, []) else: self.assertEqual( el.exception.stack_trace, [ u"Cannot extract the stack trace for this exception. Try " u"calling exception() within the `catch` block." ], )
def _save_dataset(name, description, dataset): if not name: st.error('Необходимо задать название датасету') return False if not dataset: st.error('Необходимо загрузить данные с метками или без меток') return False with create_session() as session: record = db.Dataset(name=name, description=description) # noqa session.add(record) session.flush() try: uploaded_file = dataset path = Path(f'data/{record.id}/temp.tar.xz') path.parent.mkdir(exist_ok=True) with open(path, 'wb') as f: f.write(uploaded_file.read()) with tarfile.open(path) as f: f.extractall(path=f'data/{record.id}/') record.train_count = len( list((path.parent / DatasetType.TRAIN.value).glob('*.png')) ) record.test_count = len( list((path.parent / DatasetType.TEST.value).glob('*.png')) ) record.unlabelled_count = len( list((path.parent / DatasetType.UNLABELLED.value).glob('*.png')) ) except Exception as e: st.exception(e) return False return True
def init_config(): # Read the config.yaml try: with open(os.path.join('..', 'Config.yaml'), 'r') as f: config = yaml.safe_load(f) except Exception as e: st.exception(e) config['DataDirectory'] = st.text_input( 'Data directory for storing large files (e.g. HEASARC database.):', config['DataDirectory']) # Finally save the yaml back to disk in case the user made changes. with open(os.path.join('..', 'Config.yaml'), 'w') as f: yaml.dump(config, f) # Make sure the data directory exists if not os.path.exists(config['DataDirectory']): os.mkdir(config['DataDirectory']) # Make sure the data directory for Fluxed RGS spectra exists if not os.path.exists( os.path.join(config['DataDirectory'], 'XMMNewtonFluxed')): os.mkdir(os.path.join(config['DataDirectory'], 'XMMNewtonFluxed')) return config
# Tutorial de Streamlit no youtube # https://www.youtube.com/watch?v=_9WiB2PDO7k&list=PLJ39kWiJXSixyRMcn3lrbv8xI8ZZoYNZU import streamlit as st # Text;Title st.title("Streamlit Tutorials") # Header/Subheader st.header("This is a header") st.subheader("This is a subheader") # Text st.text("Hello Streamlit") # Markdown st.markdown("### This is a Markdown") # Error/Colorful Text st.success("Sucessful") st.info("Information!") st.warning("This is a warning") st.error("This is an error Danger") st.exception("NameError('name three not defined')")
import numpy as np import os, sys, shutil import pandas as pd import plotly.express as px import plotly.graph_objects as go import re import streamlit as st import yaml import WhiteLineMethods as wlm # Read the config.yaml try: with open(os.path.join('..', 'Config.yaml'), 'r') as f: config = yaml.safe_load(f) except Exception as e: st.exception(e) config['DataDirectory'] = st.text_input( 'Data directory for storing large files (e.g. dust maps):', config['DataDirectory']) # Finally save the yaml back to disk in case the user made changes. with open(os.path.join('..', 'Config.yaml'), 'w') as f: yaml.dump(config, f) @st.cache def InitializeDustmap(config): # Fetch the planck data if we don't have it yet. if not os.path.exists(os.path.join(config['DataDirectory'], 'planck')): print('downloading planck data') from dustmaps.config import config as dustconfig dustconfig['data_dir'] = config['DataDirectory']
st.text( "Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, " ) st.markdown("## This is a Markdown") st.success("This is a Success message") st.info("This is a information message") st.warning("This is a warning message") st.error("This is a error message") st.exception("Is is a EXCEPTION") st.help(range) from PIL import Image img = Image.open("example.JPG") st.image(img, width=300, caption="Simple Image") vid_file = open("example.mp4", "rb").read() st.video(vid_file) if st.checkbox("Show/Hide"): st.text("Show something")
def main(): st.sidebar.title("WasteNot") menu = ["Home","Forecast","Backcast"] choice = st.sidebar.selectbox("Navigation",menu) access_token = st.sidebar.text_input('Access Token', '', help='Get your token from [https://www.bluedotthinking.com/subscriptions](https://www.bluedotthinking.com/subscriptions)') if choice == "Home": st.title("Home - About This Tool") st.write('Welcome to the web application for WasteNot - an example of how to perform forecast and backcasts for perishable food items to reduce waste and increase profits') st.write('Before starting, please ensure you have signed up for an account at [https://www.bluedotthinking.com](https://www.bluedotthinking.com) and retrieved your access token from the Subscription tab') st.write('There are 2 key functionalities:') st.write("- Forecast: Generate an optimised forecast, based on the historical demand, and the item's attributes. This requires subscription to a paid plan - a 30 day free trial is available.") st.write("- Backcast: Calculate the business benefits WasteNot could have brought, based on the historical demand, and the item's attributes. This does not require subscription to a paid plan.") st.write('In both cases, the user can choose to:') st.write('- Use an example file containing daily demand, for a 12-month period') st.write('- Upload their own data file containing historical daily demand') st.write('Uploaded data is not saved, and does not persist beyond your session') elif choice == "Forecast": st.title("Forecast") input_data_expander = st.beta_expander("Historical Demand Data", expanded=True) with input_data_expander: file_upload_selector = ["Use Example File","Upload A File"] col1, col2 = st.beta_columns(2) with col1: upload_file_choice = st.selectbox("Time Series Data", file_upload_selector) if upload_file_choice == "Use Example File": data_file = 'https://raw.githubusercontent.com/bluedotthinking/wastenot-documentation/master/example_data/bdt_example_input.csv' input_df = pd.read_csv(data_file) st.write('The example file contains historical demand data with 2 columns:') st.write('- "date", containing dates in the format YYYY-MM-DD') st.write('- "demand_units", containing only integers (whole numbers)') if upload_file_choice == "Upload A File": data_file = None data_file = st.file_uploader("Upload CSV",type=['csv']) st.write('The file you upload with historical demand data must have 2 columns:') st.write('- "date", containing dates in the format YYYY-MM-DD') st.write('- "demand_units", containing only integers (whole numbers)') with col2: if data_file is not None: # file_details = {"Filename":data_file.name,"FileType":data_file.type,"FileSize":data_file.size} input_df = pd.read_csv(data_file) fig_input = go.Figure() fig_input.update_layout(title="Historical Demand Data") fig_input.add_trace( go.Bar(x=input_df['date'].values, y=input_df['demand_units'].values, name="Training Data")) st.plotly_chart(fig_input, use_container_width=True) # st.dataframe(input_df) else: st.write('Please upload some data') st.markdown('#') simulation_params_expander = st.beta_expander("Simulation Parameters", expanded=False) with simulation_params_expander: opt_param, unit_cost, unit_sell_price, currency_symbol, forecast_ahead_periods, shelf_life_days, shelf_life_seconds, fraction_wasted, replenishment_daysofweek, n_forecasts_simulated, n_training_periods = set_simulation_params(choice) st.markdown('#') col3, col4 = st.beta_columns((1,3)) with col4: if access_token == '': st.write('Get your Access Token at https://www.bluedotthinking.com/subscriptions/') else: st.write('Perform a forecast with the provided data and access token, with a unit cost of',currency_symbol,unit_cost, ', unit sell-price of',currency_symbol,unit_sell_price, ', for the next',forecast_ahead_periods,'periods (days)') with col3: run_triggered = False if st.button("Run Forecast"): input_data_expander.expand=False run_triggered = True payload_dict = {'timestamp':list(input_df['date'].values), 'demand':[int(dd) for dd in input_df['demand_units'].values], "cost": float(unit_cost), "sale_price": float(unit_sell_price), "shelf_life_seconds": int(shelf_life_seconds), "opt_param": opt_param, "forecast_periods_ahead":int(forecast_ahead_periods), "replenishment_dayofweek": replenishment_daysofweek, "fraction_wasted": float(fraction_wasted)} payload_json = json.dumps(payload_dict) url = "https://api.bluedotthinking.com/forecast" headers = { 'access_token': access_token, 'Content-Type': 'application/json' } response = requests.request("POST", url, headers=headers, data=payload_json) result_expander = st.beta_expander("Results", expanded=True) with result_expander: col4, col5 = st.beta_columns((3,2)) if run_triggered and response.status_code == 200: json_data = json.loads(response.text) st.success('Forecast Successful, Response code:'+str(response.status_code)) delivery_df = pd.DataFrame(data={'timestamp':json_data['delivery_timestamp'], 'delivered_units':json_data['delivery_units'] }) delivery_df['timestamp'] = pd.to_datetime(delivery_df['timestamp']) forecast_df = pd.DataFrame(data={'timestamp': json_data['forecast_timestamp'], 'predicted_demand_units': json_data['predicted_demand_units'], 'optimised_demand_units': json_data['optimised_demand_units'], }) forecast_df['timestamp'] = pd.to_datetime(forecast_df['timestamp']) fig_output = go.Figure() fig_output.update_layout(title="Forecast Demand") fig_output.add_trace( go.Bar(x=forecast_df['timestamp'], y=forecast_df['predicted_demand_units'], name="Forecasted Demand")) fig_output.add_trace( go.Bar(x=delivery_df['timestamp'], y=delivery_df['delivered_units'], name="Optimised Replenishments")) fig_output.update_layout(legend=dict( orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1 )) st.plotly_chart(fig_output, use_container_width=True) merged_df = pd.merge(delivery_df, forecast_df, on = 'timestamp', how='outer').fillna(0).sort_values('timestamp', ascending=True) st.dataframe(merged_df) csv = merged_df.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() # some strings <-> bytes conversions necessary here href = f'<a href="data:file/csv;base64,{b64}" download="replenishment.csv">Download Results in CSV format</a>' st.markdown(href, unsafe_allow_html=True) elif run_triggered and response.status_code != 200: error = 'Backcast Failed, Response code:'+str(response.status_code)+', Error message:'+response.text st.exception(error) else: st.write('Forecast has not yet been run') elif choice == "Backcast": st.title("Backcast") input_data_expander = st.beta_expander("Historical Demand Data", expanded=True) with input_data_expander: file_upload_selector = ["Use Example File","Upload A File"] # upload_file_choice = st.sidebar.selectbox("Time Series Data", file_upload_selector) col1, col2 = st.beta_columns(2) with col1: upload_file_choice = st.selectbox("Time Series Data", file_upload_selector) if upload_file_choice == "Use Example File": data_file = 'https://raw.githubusercontent.com/bluedotthinking/wastenot-documentation/master/example_data/bdt_example_input.csv' input_df = pd.read_csv(data_file) st.write('The example file contains historical demand data with 2 columns:') st.write('- "date", containing dates in the format YYYY-MM-DD') st.write('- "demand_units", containing only integers (whole numbers)') # fig_input = go.Figure() # fig_input.update_layout(title="Historical Demand Data") # fig_input.add_trace( # go.Bar(x=input_df['date'].values, y=input_df['demand_units'].values, # name="Training Data")) # st.plotly_chart(fig_input, use_container_width=True) # st.dataframe(input_df) if upload_file_choice == "Upload A File": # data_file = st.sidebar.file_uploader("Upload CSV",type=['csv']) data_file = None data_file = st.file_uploader("Upload CSV",type=['csv']) st.write('The file you upload with historical demand data must have 2 columns:') st.write('- "date", containing dates in the format YYYY-MM-DD') st.write('- "demand_units", containing only integers (whole numbers)') with col2: if data_file is not None: # file_details = {"Filename":data_file.name,"FileType":data_file.type,"FileSize":data_file.size} input_df = pd.read_csv(data_file) fig_input = go.Figure() fig_input.update_layout() fig_input.add_trace( go.Bar(x=input_df['date'].values, y=input_df['demand_units'].values, name="Training Data")) st.plotly_chart(fig_input, use_container_width=True) # st.dataframe(input_df) else: st.write('Please upload some data') st.markdown('#') simulation_params_expander = st.beta_expander("Simulation Parameters", expanded=False) with simulation_params_expander: opt_param, unit_cost, unit_sell_price, currency_symbol, forecast_ahead_periods, shelf_life_days, shelf_life_seconds, fraction_wasted, replenishment_daysofweek, n_forecasts_simulated, n_training_periods= set_simulation_params(choice) st.markdown('#') n_periods_simulated = int(forecast_ahead_periods*n_forecasts_simulated) run_triggered = False col3, col4 = st.beta_columns((1,3)) with col4: if access_token == '': st.write('Get your Access Token at https://www.bluedotthinking.com/subscriptions/') else: st.write('Perform a backcast with the provided file, with a unit cost of', currency_symbol,unit_cost,', unit sell-price of',currency_symbol,unit_sell_price,', and a shelf-life of',shelf_life_days,'days. Carrying out,',n_forecasts_simulated,'forecasts, forecasting',forecast_ahead_periods,'periods (days) ahead each time') st.write('The first',n_training_periods,'periods (days) will be used as the training data, and the following', n_periods_simulated,'periods will be simulated') with col3: if st.button("Run Backcast"): response = backcast_request(access_token, input_df, unit_sell_price, unit_cost, shelf_life_seconds, opt_param, forecast_ahead_periods, replenishment_daysofweek, n_training_periods, n_forecasts_simulated, fraction_wasted) json_data = json.loads(response.text) run_triggered = True if run_triggered and response.status_code == 200: # if response: st.header('Results') st.write('Backcast Successful, Response code:',response.status_code) results_df = pd.DataFrame(data={'timestamp_start':json_data['timestamp_start'], 'timestamp_end':json_data['timestamp_end'], 'simulation_satisfied_units':json_data['simulation_satisfied_units'], 'simulation_delivered_units':json_data['simulation_delivered_units'], 'simulation_unmet_units':json_data['simulation_unmet_units'], 'simulation_wasted_units':json_data['simulation_wasted_units'], 'actual_demand_units_unconstrained':json_data['actual_demand_units_unconstrained'] }) results_df['timestamp_start'] = pd.to_datetime(results_df['timestamp_start']) results_df['timestamp_end'] = pd.to_datetime(results_df['timestamp_end']) results_df['fraction_of_demand_satisfied'] = results_df['simulation_satisfied_units'] / results_df['actual_demand_units_unconstrained'] calculate_benefits(results_df, json_data, fraction_wasted, unit_sell_price, unit_cost, currency_symbol) elif run_triggered and response.status_code != 200: error = 'Backcast Failed, Response code:'+str(response.status_code)+', Error message:'+response.text st.exception(error)
def main(): """ A simple Analytics App """ st.header('Sample Analytical App - Guru.K') #image = Image.open('guru.png') #st.image(image, use_column_width=True) st.subheader('Charts And Insights') st.sidebar.header('Want to know more about data?') st.sidebar.text('Yeah, Lets go!') st.sidebar.subheader('Overview') st.sidebar.markdown(''' Insights about the given data ''') df = pd.read_csv('sitel_csv.csv') st.dataframe(df) #Trainers Vs Process Complexity (Avg AHT): p1 = pd.pivot_table(df, values='AHT', columns='Process Complexity', index='Trainer') option1 = st.radio("Type Of Chart", ('Bar', 'Line', 'Scatter')) if option1 == 'Bar': ax = px.bar(p1, x=p1.index, y=['L1', 'L2']) ax.update_layout(barmode='group') st.plotly_chart(ax) elif option1 == 'Line': ax = px.line(p1, x=p1.index, y=['L1', 'L2']) st.plotly_chart(ax) elif option1 == 'Scatter': ax = px.scatter(p1, x=p1.index, y=['L1', 'L2']) st.plotly_chart(ax) #Team Leaders vs Avg AHT: p2 = pd.pivot_table(df, values='AHT', index='Team Leader') option1 = st.radio("Type Of Chart", ('Box', 'Line', 'Treemap')) if option1 == 'Box': ax = px.box(p2, x=p2.index, y='AHT') st.plotly_chart(ax) elif option1 == 'Line': ax = px.line(p2, x=p2.index, y='AHT') st.plotly_chart(ax) elif option1 == 'Treemap': ax = px.treemap(p2, path=[p2.index], values='AHT') st.plotly_chart(ax) df1 = px.data.tips() fig = px.box(df1, x="day", y="total_bill", color="smoker", title="guru's boxplot", height=600, width=900) fig.update_traces( quartilemethod="exclusive") # or "inclusive", or "linear" by default st.plotly_chart(fig) rate = st.slider('Please feel free to rate this app', 1, 5, 1) if st.button('Submit'): st.write( 'Feedback Recieved at 8667722919 & [email protected].\n Thank you for the feedback.' ) #image2 = Image.open('guru_image.jpg') #st.image(image2, use_column_width=False) df2 = pd.DataFrame({'col1': [1, 2, 3]}) st.dataframe(df2) st.table(df2) #st.dataframe(df.style.highlight_max(axis=0)) st.text('This is some text.') st.markdown('Streamlit is **_really_ cool**.') st.write('Hello, *World!* :sunglasses:') st.title('This is a title') st.header('This is a header') st.subheader('This is a subheader') code = '''def hello(): print("Hello, Streamlit!")''' st.code(code, language='python') chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c']) st.line_chart(chart_data) st.area_chart(chart_data) st.bar_chart(chart_data) df = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']) st.map(df) from PIL import Image image = Image.open('guru_image.jpg') st.image(image, caption='Image', use_column_width=False) agree = st.checkbox('I agree') if agree: st.write('Great!') genre = st.radio("What's your favorite movie genre", ('Comedy', 'Drama', 'Documentary')) if genre == 'Comedy': st.write('You selected comedy.') else: st.write("You didn't select comedy.") option = st.selectbox('How would you like to be contacted?', ('Email', 'Home phone', 'Mobile phone')) st.write('You selected:', option) options = st.multiselect('What are your favorite colors', ['Green', 'Yellow', 'Red', 'Blue'], ['Yellow', 'Red']) age = st.slider('How old are you?', 0, 130, 25) st.write("I'm ", age, 'years old') values = st.slider('Select a range of values', 0.0, 100.0, (25.0, 75.0)) st.write('Values:', values) title = st.text_input('Movie title', 'Life of Brian') st.write('The current movie title is', title) number = st.number_input('Insert a number') st.write('The current number is ', number) txt = st.text_area( 'Text to analyze', ''' It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, ( ) ''') #st.write('Sentiment:', run_sentiment_analysis(txt)) uploaded_file = st.file_uploader("Choose a CSV file", type="csv") if uploaded_file is not None: data = pd.read_csv(uploaded_file) st.write(data) #color = st.beta_color_picker('Pick A Color', '#00f900') #st.write('The current color is', color) add_selectbox = st.sidebar.selectbox( "How would you like to be contacted??", ("Email", "Home phone", "Mobile phone")) with st.echo(): st.write('This code will be printed') st.write('Progress bar') import time my_bar = st.progress(0) for percent_complete in range(3): time.sleep(0.1) my_bar.progress(percent_complete + 1) st.write('Spinner') with st.spinner('Wait for it'): time.sleep(1) st.success('Done!') st.balloons() st.error('This is an error') st.warning('This is a warning') st.info('This is a purely informational message') st.success('This is a success message!') e = RuntimeError('This is an exception of type RuntimeError') st.exception(e) st.help(pd.DataFrame) st.write('Append Option') df1 = pd.DataFrame(np.random.randn(5, 5), columns=('col %d' % i for i in range(5))) my_table = st.table(df1) df2 = pd.DataFrame(np.random.randn(5, 5), columns=('col %d' % i for i in range(5))) my_table.add_rows(df2) my_chart = st.line_chart(df1) my_chart.add_rows(df2)
#Titulo st.title("Streamlit Titulo") # Header/subHeader st.header('Streamlit Header') st.subheader('Streamlit Header') #Texto st.text('Sctreamlit texto') #Markdown st.markdown('### Streamlit *** Markdown ***') # Error/colorfull texto st.success('Sucesso') st.info('Informação') st.error('Erro') st.warning('Atenção - warning') st.exception("Nome do erro('Variavel especifica nao definida')") #Help sobre comandos do python st.help(range) #Escreva texto com write st.write('Texto ecrito usando write') st.write(range(10)) # imagem from PIL import Image img = Image.open('arquivos/bot2.jpg') st.image(img, width=200, caption='Imagem simples') #Video vid = open('arquivos/sample.mp4', 'rb').read() st.video(vid) #Arquivo de audio audio1 = open('arquivos/Folia.mp3', 'rb').read() st.audio(audio1, format='audio/mp3')