Python streamlit.markdown() Examples

The following are 6 code examples of streamlit.markdown(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module streamlit , or try the search function .
Example #1
Source File: app.py    From demo-self-driving with Apache License 2.0 6 votes vote down vote up
def main():
    # Render the readme as markdown using st.markdown.
    readme_text = st.markdown(get_file_content_as_string("instructions.md"))

    # Download external dependencies.
    for filename in EXTERNAL_DEPENDENCIES.keys():
        download_file(filename)

    # 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()
        st.code(get_file_content_as_string("app.py"))
    elif app_mode == "Run the app":
        readme_text.empty()
        run_the_app()

# This file downloader demonstrates Streamlit animation. 
Example #2
Source File: app.py    From demo-self-driving with Apache License 2.0 6 votes vote down vote up
def draw_image_with_boxes(image, boxes, header, description):
    # Superpose the semi-transparent object detection boxes.    # Colors for the boxes
    LABEL_COLORS = {
        "car": [255, 0, 0],
        "pedestrian": [0, 255, 0],
        "truck": [0, 0, 255],
        "trafficLight": [255, 255, 0],
        "biker": [255, 0, 255],
    }
    image_with_boxes = image.astype(np.float64)
    for _, (xmin, ymin, xmax, ymax, label) in boxes.iterrows():
        image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] += LABEL_COLORS[label]
        image_with_boxes[int(ymin):int(ymax),int(xmin):int(xmax),:] /= 2

    # Draw the header and image.
    st.subheader(header)
    st.markdown(description)
    st.image(image_with_boxes.astype(np.uint8), use_column_width=True)

# Download a single file and make its content available as a string. 
Example #3
Source File: app.py    From demo-self-driving with Apache License 2.0 5 votes vote down vote up
def frame_selector_ui(summary):
    st.sidebar.markdown("# Frame")

    # The user can pick which type of object to search for.
    object_type = st.sidebar.selectbox("Search for which objects?", summary.columns, 2)

    # The user can select a range for how many of the selected objecgt should be present.
    min_elts, max_elts = st.sidebar.slider("How many %ss (select a range)?" % object_type, 0, 25, [10, 20])
    selected_frames = get_selected_frames(summary, object_type, min_elts, max_elts)
    if len(selected_frames) < 1:
        return None, None

    # Choose a frame out of the selected frames.
    selected_frame_index = st.sidebar.slider("Choose a frame (index)", 0, len(selected_frames) - 1, 0)

    # Draw an altair chart in the sidebar with information on the frame.
    objects_per_frame = summary.loc[selected_frames, object_type].reset_index(drop=True).reset_index()
    chart = alt.Chart(objects_per_frame, height=120).mark_area().encode(
        alt.X("index:Q", scale=alt.Scale(nice=False)),
        alt.Y("%s:Q" % object_type))
    selected_frame_df = pd.DataFrame({"selected_frame": [selected_frame_index]})
    vline = alt.Chart(selected_frame_df).mark_rule(color="red").encode(
        alt.X("selected_frame:Q", axis=None)
    )
    st.sidebar.altair_chart(alt.layer(chart, vline))

    selected_frame = selected_frames[selected_frame_index]
    return selected_frame_index, selected_frame

# Select frames based on the selection in the sidebar 
Example #4
Source File: app.py    From demo-self-driving with Apache License 2.0 5 votes vote down vote up
def object_detector_ui():
    st.sidebar.markdown("# Model")
    confidence_threshold = st.sidebar.slider("Confidence threshold", 0.0, 1.0, 0.5, 0.01)
    overlap_threshold = st.sidebar.slider("Overlap threshold", 0.0, 1.0, 0.3, 0.01)
    return confidence_threshold, overlap_threshold

# Draws an image with boxes overlayed to indicate the presence of cars, pedestrians etc. 
Example #5
Source File: evaluate.py    From gobbli with Apache License 2.0 5 votes vote down vote up
def show_metrics(metrics: Dict[str, Any]):
    st.header("Metrics")
    md = ""
    for name, value in metrics.items():
        md += f"- **{name}:** {value:.4f}\n"
    st.markdown(md) 
Example #6
Source File: predict_set.py    From arauto with Apache License 2.0 4 votes vote down vote up
def predict_set(timeseries, y, seasonality, transformation_function, model, exog_variables=None,forecast=False, show_train_prediction=None, show_test_prediction=None):
    '''
    Predicts the in-sample train observations

    Args.
        timeseries (Pandas Series): a time series that was used to fit a model
        y (str): the target column
        seasonality (int): the seasonality frequency
        transformation_function (func): a function used to transform the target values
        model (Statsmodel object): a fitted model
        exog_variables (Pandas DataFrame): exogenous (independent) variables of your model
        forecast (bool): wether or not forecast the test set
        show_train_prediction (bool): wether or not to plot the train set predictions
        show_test_prediction (bool): wether or not to plot the test set predictions
    '''
    timeseries = timeseries.to_frame()
    timeseries[y] = transformation_function(timeseries[y])

    if forecast:
        timeseries['ŷ'] = transformation_function(model.forecast(len(timeseries), exog=exog_variables))
    else:
        timeseries['ŷ'] = transformation_function(model.predict())
    
    if show_train_prediction and forecast == False:
        timeseries[[y, 'ŷ']].iloc[-(seasonality*3):].plot(color=['green', 'red'])

        plt.ylabel(y)
        plt.xlabel('')
        plt.title('Train set predictions')
        st.pyplot()
    elif show_test_prediction and forecast:
        timeseries[[y, 'ŷ']].iloc[-(seasonality*3):].plot(color=['green', 'red'])

        plt.ylabel(y)
        plt.xlabel('')
        plt.title('Test set predictions')
        st.pyplot()

    try:
        rmse = sqrt(mean_squared_error(timeseries[y].iloc[-(seasonality*3):], timeseries['ŷ'].iloc[-(seasonality*3):]))
        aic = model.aic
        bic = model.bic
        hqic = model.hqic
        mape = np.round(mean_abs_pct_error(timeseries[y].iloc[-(seasonality*3):], timeseries['ŷ'].iloc[-(seasonality*3):]), 2)
        mae = np.round(mean_absolute_error(timeseries[y].iloc[-(seasonality*3):], timeseries['ŷ'].iloc[-(seasonality*3):]), 2)
    except ValueError:
        error_message = '''
                        There was a problem while we calculated the model metrics. 
                        Usually this is due a problem with the format of the DATE column. 
                        Be sure it is in a valid format for Pandas to_datetime function
                        '''
        raise ValueError(error_message)
    
    metrics_df = pd.DataFrame(data=[rmse, aic, bic, hqic, mape, mae], columns = ['{} SET METRICS'.format('TEST' if forecast else 'TRAIN')], index = ['RMSE', 'AIC', 'BIC', 'HQIC', 'MAPE', 'MAE'])
    st.markdown('### **Metrics**')
    st.dataframe(metrics_df)