def main():
    """Hep Mortality Prediction App"""
    # st.title("Hepatitis Mortality Prediction App")
    st.markdown(html_temp.format('royalblue'), unsafe_allow_html=True)

    menu = ["Home", "Login", "SignUp"]
    sub_menu = ["Plot", "Prediction"]

    choice = st.sidebar.selectbox("Menu", menu)
    if choice == "Home":
        st.subheader("Home")
        # st.text("What is Hepatitis?")
        st.markdown(descriptive_message_temp, unsafe_allow_html=True)
        st.image(load_image('images/hepimage.png'))

    elif choice == "Login":
        username = st.sidebar.text_input("Username")
        password = st.sidebar.text_input("Password", type='password')
        if st.sidebar.checkbox("Login"):
            create_usertable()
            hashed_pswd = generate_hashes(password)
            result = login_user(username, verify_hashes(password, hashed_pswd))
            # if password == "12345":
            if result:
                st.success("Welcome {}!".format(username))

                activity = st.selectbox("Activity", sub_menu)
                if activity == "Plot":
                    st.subheader("Data Visualization Plot")
                    df = pd.read_csv("data/clean_hepatitis_dataset.csv")
                    st.dataframe(df)

                    df['class'].value_counts().plot(kind='bar')
                    st.pyplot()

                    # Freq Dist Plot
                    freq_df = pd.read_csv("data/freq_df_hepatitis_dataset.csv")
                    st.bar_chart(freq_df['count'])

                    if st.checkbox("Area Chart"):
                        all_columns = df.columns.to_list()
                        feat_choices = st.multiselect("Choose a Feature",
                                                      all_columns)
                        new_df = df[feat_choices]
                        st.area_chart(new_df)

                elif activity == "Prediction":
                    st.subheader("Predictive Analytics")

                    age = st.number_input("Age", 7, 80)
                    sex = st.radio("Sex", tuple(gender_dict.keys()))
                    steroid = st.radio("Do You Take Steroids?",
                                       tuple(feature_dict.keys()))
                    antivirals = st.radio("Do You Take Antivirals?",
                                          tuple(feature_dict.keys()))
                    fatigue = st.radio("Do You Have Fatigue",
                                       tuple(feature_dict.keys()))
                    spiders = st.radio("Presence of Spider Naeve",
                                       tuple(feature_dict.keys()))
                    ascites = st.selectbox("Ascities",
                                           tuple(feature_dict.keys()))
                    varices = st.selectbox("Presence of Varices",
                                           tuple(feature_dict.keys()))
                    bilirubin = st.number_input("bilirubin Content", 0.0, 8.0)
                    alk_phosphate = st.number_input(
                        "Alkaline Phosphate Content", 0.0, 296.0)
                    sgot = st.number_input("Sgot", 0.0, 648.0)
                    albumin = st.number_input("Albumin", 0.0, 6.4)
                    protime = st.number_input("Prothrombin Time", 0.0, 100.0)
                    histology = st.selectbox("Histology",
                                             tuple(feature_dict.keys()))
                    feature_list = [
                        age,
                        get_value(sex, gender_dict),
                        get_fvalue(steroid),
                        get_fvalue(antivirals),
                        get_fvalue(fatigue),
                        get_fvalue(spiders),
                        get_fvalue(ascites),
                        get_fvalue(varices), bilirubin, alk_phosphate, sgot,
                        albumin,
                        int(protime),
                        get_fvalue(histology)
                    ]
                    st.write(len(feature_list))
                    st.write(feature_list)
                    pretty_result = {
                        "age": age,
                        "sex": sex,
                        "steroid": steroid,
                        "antivirals": antivirals,
                        "fatigue": fatigue,
                        "spiders": spiders,
                        "ascites": ascites,
                        "varices": varices,
                        "bilirubin": bilirubin,
                        "alk_phosphate": alk_phosphate,
                        "sgot": sgot,
                        "albumin": albumin,
                        "protime": protime,
                        "histolog": histology
                    }
                    st.json(pretty_result)
                    single_sample = np.array(feature_list).reshape(1, -1)

                    # ML
                    model_choice = st.selectbox("Select Model",
                                                ["LR", "KNN", "DecisionTree"])
                    if st.button("Predict"):
                        if model_choice == "KNN":
                            loaded_model = load_model(
                                "models/knn_hepB_model.pkl")
                            prediction = loaded_model.predict(single_sample)
                            pred_prob = loaded_model.predict_proba(
                                single_sample)
                        elif model_choice == "DecisionTree":
                            loaded_model = load_model(
                                "models/decision_tree_clf_hepB_model.pkl")
                            prediction = loaded_model.predict(single_sample)
                            pred_prob = loaded_model.predict_proba(
                                single_sample)
                        else:
                            loaded_model = load_model(
                                "models/logistic_regression_hepB_model.pkl")
                            prediction = loaded_model.predict(single_sample)
                            pred_prob = loaded_model.predict_proba(
                                single_sample)

                        # st.write(prediction)
                        # prediction_label = {"Die":1,"Live":2}
                        # final_result = get_key(prediction,prediction_label)
                        if prediction == 1:
                            st.warning("Patient Dies")
                            pred_probability_score = {
                                "Die": pred_prob[0][0] * 100,
                                "Live": pred_prob[0][1] * 100
                            }
                            st.subheader(
                                "Prediction Probability Score using {}".format(
                                    model_choice))
                            st.json(pred_probability_score)
                            st.subheader("Prescriptive Analytics")
                            st.markdown(prescriptive_message_temp,
                                        unsafe_allow_html=True)

                        else:
                            st.success("Patient Lives")
                            pred_probability_score = {
                                "Die": pred_prob[0][0] * 100,
                                "Live": pred_prob[0][1] * 100
                            }
                            st.subheader(
                                "Prediction Probability Score using {}".format(
                                    model_choice))
                            st.json(pred_probability_score)

                    if st.checkbox("Interpret"):
                        if model_choice == "KNN":
                            loaded_model = load_model(
                                "models/knn_hepB_model.pkl")

                        elif model_choice == "DecisionTree":
                            loaded_model = load_model(
                                "models/decision_tree_clf_hepB_model.pkl")

                        else:
                            loaded_model = load_model(
                                "models/logistic_regression_hepB_model.pkl")

                            # loaded_model = load_model("models/logistic_regression_model.pkl")
                            # 1 Die and 2 Live
                            df = pd.read_csv(
                                "data/clean_hepatitis_dataset.csv")
                            x = df[[
                                'age', 'sex', 'steroid', 'antivirals',
                                'fatigue', 'spiders', 'ascites', 'varices',
                                'bilirubin', 'alk_phosphate', 'sgot',
                                'albumin', 'protime', 'histology'
                            ]]
                            feature_names = [
                                'age', 'sex', 'steroid', 'antivirals',
                                'fatigue', 'spiders', 'ascites', 'varices',
                                'bilirubin', 'alk_phosphate', 'sgot',
                                'albumin', 'protime', 'histology'
                            ]
                            class_names = ['Die(1)', 'Live(2)']
                            explainer = lime.lime_tabular.LimeTabularExplainer(
                                x.values,
                                feature_names=feature_names,
                                class_names=class_names,
                                discretize_continuous=True)
                            # The Explainer Instance
                            exp = explainer.explain_instance(
                                np.array(feature_list),
                                loaded_model.predict_proba,
                                num_features=13,
                                top_labels=1)
                            exp.show_in_notebook(show_table=True,
                                                 show_all=False)
                            # exp.save_to_file('lime_oi.html')
                            st.write(exp.as_list())
                            new_exp = exp.as_list()
                            label_limits = [i[0] for i in new_exp]
                            # st.write(label_limits)
                            label_scores = [i[1] for i in new_exp]
                            plt.barh(label_limits, label_scores)
                            st.pyplot()
                            plt.figure(figsize=(20, 10))
                            fig = exp.as_pyplot_figure()
                            st.pyplot()

            else:
                st.warning("Incorrect Username/Password")

    elif choice == "SignUp":
        new_username = st.text_input("Username")
        new_password = st.text_input("Password", type='password')

        confirm_password = st.text_input("Confirm Password", type='password')
        if new_password == confirm_password and new_password != "":
            st.success("Password Confirmed")
        elif new_password != confirm_password:
            st.warning("Password does not match")

        if st.button("Submit"):
            create_usertable()
            hashed_new_password = generate_hashes(new_password)
            add_userdata(new_username, hashed_new_password)
            st.success("You have successfully created a New Account")
            st.info("Login to Get Started")
# number of clusters
nb_clusters = st.slider(
    "How many categories do you think we can cluster your images",
    min_value=2,
    max_value=8,
    value=3,
    step=1)

# CLASSIFICATION ROUTINE
if st.button("Classify!"):
    model_output = flatten_output(model, images)
    st.success("Convolution Layers applied.")
    model_pca = create_fit_PCA(model_output)
    model_output_pca = model_pca.transform(model_output)
    st.success("Dimensionality reduction performed")
    if algo == "KMeans":
        K_fitted = create_train_kmeans(model_output_pca)
        clusters = K_fitted.predict(model_output_pca)
    elif algo == "Gaussian Mixture":
        GM_fitted = create_train_gmm(model_output_pca)
        clusters = GM_fitted.predict(model_output_pca)

    dictionnary, figs = group_and_plot(folder,
                                       clusters,
                                       nb_clusters,
                                       size=(56, 56),
                                       plot=True)

    for i, fig in enumerate(figs):
        st.warning(f"Group {i}")
        st.pyplot(fig)
Beispiel #3
0
def style_transfer(image=None):
    #image = None
    got_style_image = False

    #----------------- Uploading User Tree image from URL or File -------------------

    # Image from upload

    st.title(
        'Please provide an image which will be the content image for Neural Style Transfer.'
    )

    st.title("Upload Options")
    input_method = st.radio("Options", ('File Upload', 'URL'))

    flag = 0
    if input_method == 'File Upload':
        user_upload_image = st.file_uploader("Upload an image",
                                             type=['png', 'jpeg', 'jpg'])
        if user_upload_image is not None:
            file_details = {
                "FileName": user_upload_image.name,
                "FileType": user_upload_image.type,
                "FileSize": user_upload_image.size
            }
            # st.write(file_details)
            flag = 1
        if flag == 1:
            #		from PIL import Image
            image_source = user_upload_image.name
            image = Image.open(user_upload_image)
            st.image(
                image,
                caption=user_upload_image.name + '  ' +
                user_upload_image.type + '  ' + str(user_upload_image.size) +
                ' bytes',
                width=300,
                use_column_width=True,
            )

    # Image from URL
    if input_method == 'URL':
        image_url = st.text_area("Enter the complete Url",
                                 key="user_url_choice")
        image_url_status = st.button('Upload')

        if image_url_status:
            image_source = image_url
            image = Image.open(urllib.request.urlopen(image_url))
            st.image(
                image,
                caption=str(image),
                width=300,
                use_column_width=True,
            )
        else:
            st.warning('click on upload')

    st.title(
        'Neural Style Transfer - See the style choices below, select from menu.'
    )
    # Google drawing saved as jpg file of the five style images
    five_artists = Image.open(r'Five_Artists.jpg')
    st.image(five_artists, use_column_width=True)

    st.title("Neural Style Transformation")

    style_selection = st.radio(
        "Style Options",
        ('No Transformation', 'Artist 1: Raja Ravi Varma',
         'Artist 2: Jackson Pollack', 'Artist 3: Katsushika Hokusai',
         'Artist 4: Cheri Samba', 'Artist 5: Frida Kahlo',
         'Upload Your Own Style Image'), 0)

    got_style_image = False

    if style_selection != 'No Transformation':

        if style_selection == 'Artist 1: Raja Ravi Varma':
            style_image = Image.open('raja-ravi_woman-in-garden.jpeg')
            style_source = "Artist Raja Ravi Varma"
            got_style_image = True
        elif style_selection == 'Artist 2: Jackson Pollack':
            style_image = Image.open('jackson-pollack_style.png')
            style_source = "Artist Jackson Pollack"
            got_style_image = True
        elif style_selection == 'Artist 3: Katsushika Hokusai':
            style_image = Image.open('Katsushika-Hokusai_Great-Wave.jpeg')
            style_source = "Artist Katsushika Hokusai"
            got_style_image = True
        elif style_selection == 'Artist 4: Cheri Samba':
            style_image = Image.open('Cheri-Samba_J-aime-la-couleur.jpeg')
            style_source = "Artist Cheri Samba"
            got_style_image = True
        elif style_selection == 'Artist 5: Frida Kahlo':
            style_image = Image.open('frida-kahlo_style.png')
            style_source = "Artist Frida Kahlo"
            got_style_image = True
        elif style_selection == 'Upload Your Own Style Image':
            st.title("Style Upload Options")
            style_input_method = st.radio("Choose One",
                                          ('Style File Upload', 'Style URL'))

            got_style_image = False
            got_image = False

            # Style image from upload

            if style_input_method == 'Style File Upload':
                # first clear any previous uploaded style file
                got_style_image = False
                style_upload_image = None
                flag2 = 0
                style_upload_image = st.file_uploader(
                    "Upload an image for style", type=['png', 'jpeg', 'jpg'])
                if style_upload_image is not None:
                    file_details = {
                        "FileName": style_upload_image.name,
                        "FileType": style_upload_image.type,
                        "FileSize": style_upload_image.size
                    }
                    flag2 = 1
                if flag2 == 1:
                    #		from PIL import Image
                    style_image = Image.open(style_upload_image)
                    style_source = style_upload_image.name
                    got_style_image = True
                    # st.write('For debugging: got uploaded image')

            # Image from URL
            elif style_input_method == 'Style URL':
                # first clear any previous URL style file
                got_style_image = False
                style_image_url = None

                style_image_url = st.text_area("Enter the complete Url",
                                               key="style_url_choice")
                style_image_url_status = st.button('Enter Style URL')

                if style_image_url_status:
                    style_image = Image.open(
                        urllib.request.urlopen(style_image_url))
                    style_source = str(style_image_url)
                    got_style_image = True
                    #st.image(image, caption= str(image), width = 300, use_column_width=True, )
                    # st.write('For debugging: got URL image')
                else:
                    st.warning('click on Enter Style URL')

        # if type(style_image) == 'NoneType':
        # 	got_style_image = False

        ready_to_run_style = (style_selection !=
                              'No Transformation') and got_style_image

        if ready_to_run_style:
            st.title('***Neural Style Transfer is beginning***')

            st.write(
                'Please be patient, the transformation takes four or five minutes.'
            )
            #st.write('For debugging: got_style_image is ', got_style_image)
            #st.write('For debugging: style_image type is ', type(style_image))
            content_image = image

            image_w_style = run_vgg19_style_transfer(image, style_image)

            # Captions for the input photo, style photo, and resulting output photo.
            # content_image_caption = 'Your photo: ' + user_upload_image.name # breaks for URL image
            content_image_caption = 'Your photo: ' + image_source
            style_image_caption = 'Art image by ' + style_source
            output_image_caption = 'Image with style applied from ' + style_source

            st.image(content_image, caption=content_image_caption, width=200)
            st.image(style_image, caption=style_image_caption, width=200)

            st.image(image_w_style, caption=output_image_caption, width=400)
            st.write(
                'Right click on or touch output image and choose "Save Image As" to save a copy.'
            )

            # Clear image settings before style transfer runs again
            style_image = None
            got_image = False
            got_style_image = False
            style_upload_image = None
Beispiel #4
0
st.subheader("Choose an ML Model:")
model = st.radio('',['XGBoost Classifier', 
                     'Decision Tree Classifier', 'KNN Classifier'])


# Button
if st.button("Submit"):
    import time
    with st.spinner("ML Model is loading..."):
        my_bar=st.progress(0)
        for p in range(0,101,10):
            my_bar.progress(p)
            time.sleep(0.1)

        if model=='Decision Tree Classifier':
            churn_probability = dec_model.predict_proba(df)
            is_churn= dec_model.predict(df)
        elif model=='XGBoost Classifier':
            churn_probability= xgb_model.predict_proba(df)
            is_churn= xgb_model.predict(df)           
        elif model=='KNN Classifier':
            churn_probability= knn_model.predict_proba(df)
            is_churn= knn_model.predict(df)
    
    
        st.success(f'The Probability of the Employee Churn is %{round(churn_probability[0][1]*100,1)}')
        
        if is_churn[0]:
            st.warning("The Employee is CHURN")
        else:
            st.success("The Employee is NOT CHURN")
# Datasets
st.subheader("Choose the source for dataset")
dataset = st.selectbox("Select a proper gnomAD data set:", [
    "gnomad_r2_1", "gnomad_r3", "gnomad_r2_1_controls",
    "gnomad_r2_1_non_neuro", "gnomad_r2_1_non_cancer",
    "gnomad_r2_1_non_topmed", "exac"
])

# Reference Genome
st.subheader("Choose the reference genome")
reference_genome = st.selectbox("Select a proper reference genome build:",
                                ["GRCh37", "GRCh38"])

if reference_genome == "GRCh38":
    st.warning(
        "gnomAD structural variant (SV) data might not available on reference genome `GRCh38`."
    )

# SV Dataset
if filter_by in ["gene_id", "gene_name"]:
    st.subheader("Choose the source for structural variant (SV) dataset")
    sv_dataset = st.selectbox("Select a proper SV gnomAD data set:", [
        "gnomad_sv_r2_1", "gnomad_sv_r2_1_controls", "gnomad_sv_r2_1_non_neuro"
    ])


# Main Function for Getting Data and Saving them
def get_variants_by(filter_by, search_term, dataset, mode, timeout=None):

    query_for_transcripts = """
    {
Beispiel #6
0
    def download(self, path=LOCAL_DATA):
        # mostly taken from https://github.com/streamlit/demo-face-gan/
        #   blob/master/streamlit_app.py
        root = Path(path).resolve()
        path = root / self.filename

        # Don't download the file twice. (If possible, verify the
        # download using the file length.)
        if os.path.exists(path):
            if not self.size or os.path.getsize(path) == self.size:
                return path

        mkdir_p(path.parent)

        # These are handles to two visual elements to animate.
        status, progress_bar = None, None
        try:
            status = st.warning("Downloading %s..." % path)

            # handle cases where files hosted on gdrive sometimes fail
            # to download
            if "google.com" in self.url:
                _ = gdown.cached_download(self.url, path=path)
            else:
                progress_bar = st.progress(0)
                # with open(path, "wb") as output_file:
                with urllib.request.urlopen(
                    self.url, cafile=certifi.where()
                ) as response:
                    if response.info()["Content-Length"] is not None:
                        with open(path, "wb") as output_file:
                            length = int(response.info()["Content-Length"])
                            counter = 0.0
                            MEGABYTES = 2.0 ** 20.0
                            while True:
                                data = response.read(8192)
                                if not data:
                                    break
                                counter += len(data)
                                output_file.write(data)

                                # We perform animation by overwriting the elements.
                                status.warning(
                                    "Downloading %s... (%6.2f/%6.2f MB)"
                                    % (path, counter / MEGABYTES, length / MEGABYTES)
                                )
                                progress_bar.progress(min(counter / length, 1.0))

        except urllib.error.URLError as e:
            logger.exception(f"Invalid URL: {self.url}", exc_info=e)
        # Finally, we remove these visual elements by calling .empty().
        finally:
            if status is not None:
                status.empty()
            if progress_bar is not None:
                progress_bar.empty()

        if not path.exists():
            raise FileNotFoundError(str(path))

        elif os.path.getsize(path) == 0:
            os.remove(path)
            raise ValueError(f"Invalid URL: {self.url}")

        return path
Beispiel #7
0
def run_rank():
    st.title('当月排名进度')
    category = st.selectbox('品类名称:',catelist['category_name'])
    catid=catelist[catelist['category_name']==category]['category_id'].values[0]
    st.markdown(f'#### 已选中 **{category}** ,  品类ID: **{catid}**')
    data = None
    while data is None:
        data_load_state=st.text('正在加载数据')
        data=load_data(catid)
    table=data.groupby(['asin','date'])['ranking'].agg('median').apply(lambda x:int(x))
    t1=table.unstack(level=1)
    st.write(t1)
    data_load_state.success('✔️ 数据加载完成')
    time.sleep(1)
    data_load_state.text('')
    chosed_asin = st.selectbox('Asin',data.asin.unique())
    a1=pd.DataFrame(t1.loc[f'{chosed_asin}',:].dropna()).transpose()
    a1_rank=a1.apply(lambda x: int(np.median(x)),axis=1)[0]
    #画图模块   
    t2=pd.DataFrame(t1.loc[f'{chosed_asin}'])
    t2['date']=t2.index.get_level_values(0)
    t2.reset_index(drop=True)
    fig = px.line(t2, x=t2['date'], y=t2[f'{chosed_asin}'], title=f'{chosed_asin}的当月排名情况(红线为当月排名)')
    fig.add_shape(type='line',
                    x0=t2['date'].iloc[0],
                    y0=a1_rank,
                    x1=t2['date'].iloc[-1],
                    y1=a1_rank,
                    line=dict(color='Red'),
                    xref='x',
                    yref='y')
    st.plotly_chart(fig, use_container_width=True)
    #画图模块    
    st.info(f'ASIN {chosed_asin}的当月排名为:    {int(a1_rank)}')
    a2=t1.apply(lambda x: np.median(x),axis=1).sort_values()
    if int(a2[0])==1:
        st.success(f'当前品类下月排名最高的Asin为{a2.index[0]},  月排名为: {int(a2[0])}')
    elif int(a2[0])<=8:
        st.info(f'当前品类下月排名最高的Asin为{a2.index[0]},  月排名为: {int(a2[0])}')
    else:
        st.warning(f'当前品类下月排名最高的Asin为{a2.index[0]},  月排名为: {int(a2[0])}')
    d1,d2=st.beta_columns(2)
    with d1:
        start_time = st.date_input("根据日期查看",t2['date'].iloc[0])
    with d2:
        end_time = st.date_input("结束日期",t2['date'].iloc[-1])
    if str(start_time) in t1.columns:
        st.write(t1.loc[:,start_time:end_time])
        t2=t1[f'{start_time}'].sort_values()
        top1=t2[0]
        topn=t2.where(t2<=8).count()
        if top1==1:
            st.success(f'{start_time}日 {t2.index[0]} 的日排名为第一!')
        elif topn>=4:
            st.success('有四个个以上asin进入前八!')
        else:
            st.warning('没有排名靠前的Asin')

    else:
        st.write('数据缺失')

    with st.beta_expander('原始数据详情',expanded=False):
        i=st.number_input('输入你想要看到的条数',min_value=1,value=50,step=50)
        detail=data.iloc[:i,:]
        st.write(detail)
Beispiel #8
0
##############################################################################
# 実行コントロール定義
##############################################################################
buttonState = st.sidebar.button('検索')

st.sidebar.write('※検索には約10秒かかります')

if buttonState:
    with st.spinner('実行中です。しばらくお待ちください。'):
        # 選択項目から読み込み対象のURLを取得
        urlList = utl.CreateUrlList(urlResult)

        # スクレイピング
        df = utl.ScrapingSuumo(urlList)
        if df is None:
            st.warning('物件がありません')
        else:
            # 前処理
            df = utl.ModifyFormat(df)

            # 予測
            df_disp = Prediction(df, include)
            #df_disps = df_disp.to_html(escape=False) URLをリンクで飛べるようにしたかったがあきらめる

            ##############################################################################
            # 予測結果コントロール定義
            ##############################################################################
            if df_disp is None:
                st.warning('物件がありません')
            else:
                st.success('成功しました')
Beispiel #9
0
    }
    </style>
    ''' % bin_str
    
    st.markdown(page_bg_img, unsafe_allow_html=True)
    return

set_png_as_page_bg('background.png')





message = st.text_area("Please Give Us Your Hotel Experience")
if st.button("Analyze"):
    with st.spinner('Analyzing the text …'):
         prediction=predict(message)
         if prediction > 0.6:
              st.error("Negative review with {:.2f} confidence".format(prediction))
              
        
         elif prediction <0.4:
            st.success("Positive review with {:.2f} confidence".format(1-prediction))
            st.balloons()
        
         else:
             
             st.warning("Not sure! Try to add some more words")


 
Beispiel #10
0
import streamlit as st
## Widget
## Checkbox
if st.checkbox("Show/Hide"):
    st.text("체크박스가 선택되었습니다.")
    st.success("체크박스 선택 완료")

st.markdown("* * *")

## Radio button
status = st.radio("Select status.", ("Active", "Inactive"))
if status == "Active":
    st.success("활성화 되었습니다.")
else:
    st.warning("비활성화 되었습니다.")

st.markdown("* * *")

# Select Box (ex)
occupation = st.selectbox("직군을 선택하세요.", [
    "Backend Developer", "Frontend Developer", "ML Engineer", "Data Engineer",
    "Database Administrator", "Data Scientist", "Data Analyst",
    "Security Engineer"
])
st.write("당신의 직군은 ", occupation, " 입니다.")

st.markdown("* * *")

## MultiSelect
location = st.multiselect("선호하는 유투브 채널을 선택하세요.",
                          ("운동", "IT기기", "브이로그", "먹방", "반려동물", "맛집 리뷰"))
Beispiel #11
0
st.markdown('#### header-4')
st.markdown('###### header-6')

# list
st.header('markdown: List')
st.markdown('- list1')
st.markdown('- list2')
st.markdown('- list3\n'
            '   * inner list1\n'
            '   * inner list2\n'
            '       - inner-inner list\n')

## Latex, raw
st.header('latex')
st.latex(r"\alpha_n, \beta, \gamma, \cdots, \omega")
st.latex(r"Y = \alpha + \beta X_i")  # raw text
## Latex-inline
st.markdown(r"회귀분석에서 오차는 다음과 같습니다 $e_i = y_i - \hat{y}_i$")
## Mean squared error
st.subheader("Mean squared error")
st.markdown(r"## $MSE = \frac{1}{N-1} \sum_{i=1}^{N-1} (y_i - \hat{y}_i)^2$")

## Message
st.info("End of first note: **text, markdown, latex**!")  #blue

## streamlit messages
st.success("Successful")  #green
st.info("Information!")  #blue
st.warning("This is a warning")  #yellow
st.error("This is an error!")  #red
st.exception("NameError('Error name is not defined')")  #red
Beispiel #12
0
def main():
    """A Simple FCH Blog App"""
    html_temp = """
		<div style="background-color:{};padding:10px;border-radius:10px">
		<img src="http://fch.world/images/logo.png" style="vertical-align: middle;float:left;width: 80px;height: 80px;border-radius: 50%;">
		<h1 style="color:{};text-align:center;">FreeCash Community Blog </h1>
		</div>
		"""
    st.markdown(html_temp.format('royalblue', 'white'), unsafe_allow_html=True)

    # Display a picture
    image = Image.open('sunrise.png')
    st.image(image,
             caption='Freecash:A Free-Evolved Electronic Currency System!',
             use_column_width=True)

    # Display audio
    # video_file = open('satoshi.mp4','rb')
    # video_bytes = video_file.read()
    # st.video(video_bytes,format='video/mp4',start_time=0)

    menu2 = ["Home", "View Post", "Add Post", "Search", "Manage Blog"]
    choice2 = st.sidebar.selectbox("Main Menu", menu2)

    if choice2 == "Home":
        st.subheader("Home")
        result = view_all_notes()
        for i in result:
            # short_article = str(i[2])[0:int(len(i[2])/2)]
            short_article = str(i[2])[0:100]
            st.write(title_temp.format(i[1], i[0], short_article),
                     unsafe_allow_html=True)

    elif choice2 == "View Post":
        st.subheader("View Post")

        all_titles = [i[0] for i in view_all_titles()]
        postlist = st.sidebar.selectbox("All Posts", all_titles)
        post_result = get_blog_by_title(postlist)
        for i in post_result:
            st.text("Reading Time:{} minutes".format(readingTime(str(i[2]))))
            st.markdown(head_message_temp.format(i[1], i[0], i[3]),
                        unsafe_allow_html=True)
            # st.markdown(full_message_temp.format(i[2]), unsafe_allow_html=True)
            st.markdown(i[2])

            reward_number = st.slider("Select a reward number(satoshi)", 0,
                                      10000000)
            st.write("You will reward:", reward_number)

            # Reward blog_author(CID),
            # CID from the Li Ming API(http://39.104.79.176:8989/fc/info/cid/cid/pageSize/1/pageNum/1),
            # Generate QR code of the FCH address

            blog_author = str(i[0])
            r = requests.get(
                'http://39.104.79.176:8989/fc/info/cid/{}/pageSize/0/pageNum/0'
                .format(blog_author))
            blog_author_address = r.json()['data']['address']
            if st.button("Reward(satoshi)"):
                myqr.run(
                    words=blog_author_address,
                    version=5,  # 设置容错率
                    level='H',  # 控制纠错水平,范围是L、M、Q、H,从左到右依次升高
                    picture='myqr1.png',
                    colorized=True,
                    contrast=2.0,  # 调节图片的对比度,1.0 表示原始图片,默认为1.0。
                    brightness=1.0,  # 调节图片的亮度,1.0 表示原始图片,默认为1.0。
                    save_name='myqr2.png')
                qr_image = Image.open('myqr2.png')
                st.image(qr_image,
                         caption='Reward FreeCash Address:{}'.format(
                             blog_author_address),
                         use_column_width=True)
                st.success('Thank you very much for your reward!')

    elif choice2 == "Add Post":
        st.subheader("Add Your Article")
        create_table()
        blog_title = st.text_input('Enter Post Title')
        blog_author = st.text_input("Enter Author Name(FCH_CID)", max_chars=30)
        blog_article = st.text_area("Enter Your Message", height=300)
        blog_post_date = st.date_input("Post Date")
        if st.button("Add"):
            add_data(blog_author, blog_title, blog_article, blog_post_date)
            st.success("Post::'{}' Saved".format(blog_title))

    elif choice2 == "Search":
        st.subheader("Search Articles")
        search_term = st.text_input("Enter Term")
        search_choice = st.radio("Field to Search", ("title", "author"))
        if st.button('Search'):
            if search_choice == "title":
                article_result = get_blog_by_title(search_term)
            elif search_choice == "author":
                article_result = get_blog_by_author(search_term)

        # Preview Articles
        for i in article_result:
            st.text("Reading Time:{} minutes".format(readingTime(str(i[2]))))
            st.write(head_message_temp.format(i[1], i[0], i[3]),
                     unsafe_allow_html=True)
            # st.write(full_message_temp.format(i[2]), unsafe_allow_html=True)

    elif choice2 == "Manage Blog":
        st.subheader("Manage Blog")
        result = view_all_notes()
        clean_db = pd.DataFrame(
            result, columns=["Author", "Title", "Article", "Date", "Index"])
        st.table(clean_db)

        unique_list = [i[0] for i in view_all_titles()]
        delete_by_title = st.selectbox("Select Title", unique_list)
        if st.button("Delete"):
            delete_data(delete_by_title)
            st.warning("Deleted: '{}'".format(delete_by_title))

        if st.checkbox("Metrics"):
            new_df = clean_db
            new_df['Length'] = new_df['Article'].str.len()

            st.table(new_df['Author'].value_counts())
            st.subheader("Author Stats")
            new_df['Author'].value_counts().plot(kind='bar', figsize=(10, 5))
            st.pyplot()

            new_df['Author'].value_counts().plot.pie(autopct="%1.1f%%",
                                                     figsize=(10, 10))
            st.pyplot()

        if st.checkbox("WordCloud"):
            text = ','.join(clean_db['Article'])
            # Create and generate a word cloud image
            wordcloud = WordCloud().generate(text)

            # Display the generated image
            plt.imshow(wordcloud, interpolation='bilinear')
            plt.axis("off")
            st.pyplot()

        if st.checkbox("BarH Plot"):
            st.subheader("Length of Articles")
            new_df = clean_db
            new_df['Length'] = new_df['Article'].str.len()
            barh_plot = new_df.plot.barh(x='Author',
                                         y='Length',
                                         figsize=(8, 5))
            st.pyplot()
Beispiel #13
0
import streamlit as st

st.title("Streamlit Crash course")
st.header("Simple Header")
st.sidebar.header("Example de Side Bar")
st.sidebar.text("Hello")
st.text("For a simple text")
st.markdown("#### A Markdown ")
st.success("Successful")
st.info("This is an info alert ")
st.warning("This is a warning ")
st.error("This shows an error ")
# st.help(range())
# st.write("Text with write")
# st.write("Python Range with write",range(10))
# st.text("Display JSON")
# dico={'name':'hello','age':34}
# st.json(dico)
st.button("Simple Button")
st.text("Une check box")

if st.checkbox("Show/Hide"):
    #do some action
    st.text("Some actions")

status = st.radio("Ton statut", ('Active', 'Inactive'))
if status == 'Active':
    st.text("OK t'es Actif(ve)")
else:
    st.warning("Et un petit warning")
Beispiel #14
0
qa = init()

st.title("To BERT or not to BERT")

question = st.text_input("What is your question?")
max_answers = st.selectbox("How much answers do you want?", options=[5, 10, 15], index=0)

if question != "":
    try:
        df = search(question=question, max_answers=max_answers)
        answer_found = True
    except:
        answer_found = False

    if answer_found:
        st.warning("Note: the **bold text** is the answer of the question, and the \
                    surrounding text is the context where the answer was found!")

        for _id in range(df.__len__()):
            context = str(df.loc[_id, "Context"]) \
                .replace("<font color='red'>", "<strong>") \
                .replace("</font>", "</strong>")
            st.markdown(context, unsafe_allow_html=True)

            confidence = "{:.10f}".format(df.loc[_id, "Confidence"])
            st.markdown("Confidence: " + confidence, unsafe_allow_html=True)

            st.markdown("<hr/>", unsafe_allow_html=True)
    else:
        st.error("Sorry, no answer on your question found.")
Beispiel #15
0
import streamlit as st
st.write('Hello, world!!')
x = st.slider('x')
st.write(x, 'squared is', x * x)

if st.checkbox('test'):
    st.success('Passed')
else:
    st.warning('Failed')

st.latex(r'''
    a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
     \sum_{k=0}^{n-1} ar^k =
     a \left(\frac{1-r^{n}}{1-r}\right)
     ''')

import plotly.figure_factory as ff
import numpy as np


@st.cache
def plotMe():
    # Add histogram data
    x1 = np.random.randn(200) - 2
    x2 = np.random.randn(200)
    x3 = np.random.randn(200) + 2

    # Group data together
    hist_data = [x1, x2, x3]

    group_labels = ['Group 1', 'Group 2', 'Group 3']
Beispiel #16
0
def make_scatterplot(df_temp, what_to_show_l, what_to_show_r, categoryfield,
                     hover_name, hover_data):
    """Makes a scatterplot with trendline and statistics

    Args:
        df_temp ([type]): [description]
        what_to_show_l ([type]): [description]
        what_to_show_r ([type]): [description]
        show_cat ([type]): [description]
        categoryfield ([type]): [description]
        hovername
        hoverdata
    """
    df_temp = df_temp[df_temp[what_to_show_l] != None]
    df_temp = df_temp[df_temp[what_to_show_r] != None]
    #df_temp = df_temp[df_temp["continent"] != None]
    #df_temp = df_temp[df_temp["location"] != None]
    #st.write(df_temp)
    if len(df_temp) == 0:
        st.warning("Geen data")
    else:
        correlation_sp = round(df_temp[what_to_show_l].corr(
            df_temp[what_to_show_r], method='spearman'),
                               3)  #gebruikt door HJ Westeneng, rangcorrelatie
        correlation_p = round(
            df_temp[what_to_show_l].corr(df_temp[what_to_show_r],
                                         method='pearson'), 3)

        with _lock:
            fig1xy, ax = plt.subplots()
            try:

                x_ = np.array(df_temp[what_to_show_l])
                y_ = np.array(df_temp[what_to_show_r])
                #obtain m (slope) and b(intercept) of linear regression line
                idx = np.isfinite(x_) & np.isfinite(y_)
                m, b = np.polyfit(x_[idx], y_[idx], 1)
                model = np.polyfit(x_[idx], y_[idx], 1)

                predict = np.poly1d(model)
                r2 = r2_score(y_[idx], predict(x_[idx]))
                fig1xy = px.scatter(df_temp,
                                    x=what_to_show_l,
                                    y=what_to_show_r,
                                    color=categoryfield,
                                    hover_name=hover_name,
                                    hover_data=hover_data,
                                    trendline="ols",
                                    trendline_scope='overall',
                                    trendline_color_override='black')
                title_scatter = (
                    f"{what_to_show_l} -  {what_to_show_r}<br>Correlation spearman = {correlation_sp} - Correlation pearson = {correlation_p}<br>y = {round(m,2)}*x + {round(b,2)} | r2 = {round(r2,4)}"
                )

            except:

                fig1xy = px.scatter(df_temp,
                                    x=what_to_show_l,
                                    y=what_to_show_r,
                                    color=categoryfield,
                                    hover_name=hover_name,
                                    hover_data=hover_data)
                title_scatter = (f"{what_to_show_l} -  {what_to_show_r}")

            #fig1xy = px.scatter(df_temp, x=what_to_show_l, y=what_to_show_r,  hover_name=hover_name, color=categoryfield)

            #
            fig1xy.update_layout(title=dict(text=title_scatter,
                                            x=0.5,
                                            y=0.95,
                                            font=dict(family="Arial",
                                                      size=14,
                                                      color='#000000')),
                                 xaxis_title=what_to_show_l,
                                 yaxis_title=what_to_show_r,
                                 font=dict(family="Courier New, Monospace",
                                           size=12,
                                           color='#000000'))

            ax.text(
                1,
                1.3,
                "Created by Rene Smit — @rcsmit",
                transform=ax.transAxes,
                fontsize="xx-small",
                va="top",
                ha="right",
            )

            st.plotly_chart(fig1xy, use_container_width=True)
Beispiel #17
0
def obj_detection(my_img):
    st.set_option('deprecation.showPyplotGlobalUse', False)

    column1, column2 = st.beta_columns(2)

    column1.subheader("Input image")
    st.text("")
    # plt.figure(figsize=(16, 16))
    # plt.imshow(my_img)
    # original = Image.open(image)
    #col1.header("Original")
    if my_img.mode != 'RGB':
        my_img = my_img.convert('RGB')
    column1.image(my_img, use_column_width=True)
    # column1.pyplot(use_column_width=True)

    # YOLO model : # load the YOLO network
    # net = cv2.dnn.readNet("yolov3_training_last.weights","yolov3_testing.cfg")
    # net = cv2.dnn.readNetFromDarknet("yolov4-custom.cfg","yolov4-custom_best.weights" )
    net = cv2.dnn.readNet('yolov4-custom_best.weights', 'yolov4-custom.cfg')

    # labels = []
    # with open("classes.txt", "r") as f:
    #     labels = [line.strip() for line in f.readlines()]

    # loading all the class labels (objects)

    classes = []
    with open("classes.txt", "r") as f:
        classes = f.read().splitlines()

    # names_of_layer = net.getLayerNames()
    # output_layers = [names_of_layer[i[0] - 1] for i in net.getUnconnectedOutLayers()]

    # generating colors for each object for later plotting
    font = cv2.FONT_HERSHEY_PLAIN
    colors = np.random.uniform(0, 255, size=(100, 3))

    # colors = np.random.uniform(0, 255, size=(len(classes), 3))
    print("Colors:", colors)

    # Image loading
    newImage = np.array(my_img.convert('RGB'))
    img = cv2.cvtColor(newImage, 1)
    height, width, channels = img.shape

    # Objects detection (Converting into blobs)
    # (image, scalefactor, size, mean(mean subtraction from each layer), swapRB(Blue to red), crop)
    # blob = cv2.dnn.blobFromImage(img, 0.00392, (inpWidth, inpHeight), (0, 0, 0), True,
    # crop=False)
    blob = cv2.dnn.blobFromImage(img,
                                 1 / 255, (416, 416), (0, 0, 0),
                                 swapRB=True,
                                 crop=False)

    # sets the blob as the input of the network
    net.setInput(blob)
    # outputs = net.forward(output_layers)
    output_layers_names = net.getUnconnectedOutLayersNames()
    # layerOutputs = net.forward(output_layers_names)

    # get all the layer names
    # ln = net.getLayerNames()
    # ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    # names_of_layer = net.getLayerNames()
    # output_layers = [names_of_layer[i[0] - 1] for i in net.getUnconnectedOutLayers()]
    # feed forward (inference) and get the network output
    # measure how much it took in seconds
    # start = time.perf_counter()
    # outputs = net.forward(output_layers)
    outputs = net.forward(output_layers_names)
    # time_took = time.perf_counter() - start
    # print(f"Time took: {time_took:.2f}s")

    # The function getPerfProfile returns the overall time for inference(t) and the timings for each of the layers(in layersTimes)
    t, _ = net.getPerfProfile()
    infLabel = 'Inference time: %.2f ms' % (t * 1000.0 /
                                            cv2.getTickFrequency())
    #  cv2.putText(frame, label, (0, 15), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255))

    classID = []
    confidences = []
    boxes = []

    # SHOWING INFORMATION CONTAINED IN 'outputs' VARIABLE ON THE SCREEN
    # loop over each of the layer outputs
    for op in outputs:
        for detection in op:
            scores = detection[5:]
            class_id = np.argmax(scores)
            confidence = scores[class_id]
            if confidence > 0.2:
                # OBJECT DETECTED
                # Get the coordinates of object: center,width,height
                center_x = int(detection[0] * width)
                center_y = int(detection[1] * height)
                w = int(detection[2] *
                        width)  # width is the original width of image
                h = int(detection[3] *
                        height)  # height is the original height of the image

                # use the center (x, y)-coordinates to derive the top and
                # and left corner of the bounding box
                # RECTANGLE COORDINATES
                x = int(center_x - w / 2)  # Top-Left x
                y = int(center_y - h / 2)  # Top-left y

                # To organize the objects in array so that we can extract them later
                boxes.append([x, y, w, h])
                confidences.append(float(confidence))
                classID.append(class_id)

    # score_threshold = st.sidebar.slider("Confidence_threshold", 0.00, 1.00, 0.5, 0.01)
    # nms_threshold = st.sidebar.slider("NMS_threshold", 0.00, 1.00, 0.4, 0.01)
    score_threshold = 0.2
    st.sidebar.info(f"Confidence_threshold:{ score_threshold }")
    nms_threshold = 0.4
    st.sidebar.info(f"NMS_threshold :{nms_threshold} ")
    st.sidebar.success(infLabel)

    indexes = cv2.dnn.NMSBoxes(boxes, confidences, score_threshold,
                               nms_threshold)
    print("DNN Index:", indexes)

    font = cv2.FONT_HERSHEY_SIMPLEX
    items = []
    for i in range(len(boxes)):
        if i in indexes.flatten():
            x, y, w, h = boxes[i]
            # To get the name of object
            label = str.upper((classes[classID[i]]))
            # label = str(classes[class_ids[i]])
            confidence = str(round(confidences[i], 2))
            print("value of i:", i)
            color = colors[i]
            cv2.rectangle(img, (x, y), (x + w, y + h), color, 3)
            cv2.putText(img, label + " " + confidence, (x, y + 10), font, 0.25,
                        (0, 0, 255), 1)
            items.append(label)

    st.text("")
    st.spinner('Model working....')
    column2.subheader("Output image")
    st.text("")
    #  plt.figure(figsize=(15, 15))
    # plt.imshow(img)
    # column2.pyplot(use_column_width=True)
    column2.image(img, use_column_width=True)

    if len(indexes) > 1:
        st.success("Found {} Objects - {}".format(
            len(indexes), [item for item in set(items)]))
        st.balloons()
    elif len(indexes) == 1:
        st.success("Found {} Object - {}".format(len(indexes),
                                                 [item
                                                  for item in set(items)]))
        st.balloons()
    else:
        st.warning("Found {} Object - {}".format(len(indexes),
                                                 [item
                                                  for item in set(items)]))
Beispiel #18
0
st.title("Distance Violation Detection for Social Distancing")
st.info('This project is used to provide data for Social Distancing. ')
if st.checkbox("Videos"):
        video=st.file_uploader('Upload a video',type=['mp4','3gp'])
        if video and st.button("UPLOAD"):
          path=os.path.join('uploads',f'{video.name}')
          with open(path,'wb') as f:
            f.write(video.getbuffer())
            save_file(path)
            st.info('Upload Succesfully') 
if st.checkbox("Detect Video File"):
  db = opendb()
  videos=db.query(Video).all()
  db.close()
  vid = st.selectbox('Select a Video to Play',videos)
  if vid and os.path.exists(vid.path) and st.button('Start Detection')and st.warning('press esc to exit'):
      use_video(vid.path,"output/out.mp4")
      st.success('Detection Successful')

if st.checkbox("Webcam"):
   if st.button('open webcam')and st.warning('press esc to exit'):
       use_webcam()
       st.success('Detection Successful')
       
    
if st.checkbox("About Project"):
    st.image('gif2.gif')
    st.info('Social distancing is important in times of epidemics and pandemics to prevent the spread of disease. Can we build a social distancing detector with OpenCV. ')
    st.image('gif1.gif')
    st.info(' Social distancing is crucial to preventing the spread of disease. Using computer vision technology based on OpenCV and YOLO-based deep learning, we are able to estimate the social distance of people in video streams. ')
    st.image('flow chart.png')
Beispiel #19
0
elif bowling_team == 'Kolkata Knight Riders':
    result_array = result_array + [0, 0, 0, 1, 0, 0, 0, 0]
elif bowling_team == 'Mumbai Indians':
    result_array = result_array + [0, 0, 0, 0, 1, 0, 0, 0]
elif bowling_team == 'Rajasthan Royals':
    result_array = result_array + [0, 0, 0, 0, 0, 1, 0, 0]
elif bowling_team == 'Royal Challengers Bangalore':
    result_array = result_array + [0, 0, 0, 0, 0, 0, 1, 0]
elif bowling_team == 'Sunrisers Hyderabad':
    result_array = result_array + [0, 0, 0, 0, 0, 0, 0, 1]
else:
    pass
if batting_team == bowling_team:
    sl.error("Please Select Two Different Teams For Prediction")
sl.title("Lets Start Our Score Prediction")
sl.warning('please choice the overs correctly')
overs = sl.number_input('Enter Number Of Overs Compeleted',
                        min_value=5.0,
                        max_value=20.0)
runs = sl.number_input('Enter Number Of Runs Scored')
wickets = sl.slider('Select numbetr of wickets down?', 0, 10, 1)
wickets_in_prev_5 = sl.number_input(
    'Enter Number Of wickwts Down In Previous 5 Overs')
runs_in_prev_5 = sl.number_input(
    'Enter Number Of Runs Scored In Previous 5 Overs')
result_array = result_array + [
    overs, runs, wickets, runs_in_prev_5, wickets_in_prev_5
]
data = np.array([result_array])
lower_limit = int(rr.predict(data)) - 5
upper_limit = int(rr.predict(data)) + 10
Beispiel #20
0
def run():
    st.write("""
    Any process in data science starts with data.

    You can think of data as a collection of facts, each one can be as simple or as complicated as you want.
    The smallest unit of data that's useful is probably a single number:

    ```python
    31
    ```

    But this number is useless unless we assign some meaning to it.
    Is it someone's age? Is it a price? Is it the number of days since something happened?

    The easiest way to assign it some meaning is by giving this number *a name* that *means something to us*.

    ```python
    my_age = 31
    ```

    > (This is my real age, though, at least when I started writing this... ­ЪўЮ)

    In Python, we give names to things by using **variables**. A variable is just a name that *refers* to something.
    And that name can be *anything* that you want. It's your responsibility to give things names that are meaningful for you,
    or anyone else, that comes back later to read your code.

    The way we say, in Python, that a variable refers to something (like a number) is how you just saw, by simply writing `variable = something`.

    So, let's try that. Tell my what's your age, in Python code, the way I just did before.
    """)

    your_age_expression = st.text_input("Tell me your age in Python code")

    if not your_age_expression:
        return

    global_vars = {}

    try:
        exec(your_age_expression, global_vars)
        your_age = global_vars['my_age']
        assert isinstance(your_age, int)
        assert your_age > 0
    except SyntaxError:
        st.error(
            "­ЪЎЃ That code doesn't seem right. Make sure you typed everything as I taught you."
        )
        return
    except KeyError:
        st.error(
            "­ЪЎЃ That code doesn't tell me your age. Make sure your variable is called `my_age`, the way I did before."
        )
        return
    except AssertionError:
        st.error(
            "­ЪЎЃ That code doesn't seem right. Your age should be a whole number, greater than 0."
        )
        return

    if your_age == 31:
        st.warning(
            "­Ъцћ Are you sure that's your real age? You didn't copied and pasted *my* code, right? Ok, I'll believe you..."
        )

    if your_age < 10 or your_age > 90:
        st.warning(
            "­Ъцћ Are you sure that's your real age? It seems a bit... extreme. Ok, I'll believe you..."
        )

    st.success(
        "­ЪЦ│ There you go! You just wrote your first program in Python!")

    st.write("""
    > ### ­ЪЈє You have discovered a Fundamental Concept: **naming things**.

    > In a computer program, we always give names to everything: values, operations, even specific fragments of code.
    By naming things conveniently, we make sure *everyone* knows what our program is *meant* to do.
    We'll be seeing this concept over a over as we learn more.
    """)

    st.write(f"""
        ## What about "real" numbers?

        In order to express most of the interesting facts precisely, we need more that whole numbers.
        For example, your very own age almost surely is not exactly {your_age}, but something between
        {your_age} and {your_age + 1}, right?

        In math, we have the *integer numbers*, which are just whole numbers, and the *real numbers*, which are 
        those with decimal values (you might know there are more sets of numbers, but let's stick to the basics).
        Maybe you'll remember the mathematical symbols that represent all the integer and real numbers: $\mathcal{{N}}$
        and $\mathcal{{R}}$ respectively.

        In a computer, we cannot really represent *whatever* real number we want, for a very simple reason: your RAM memory is finite.
        So, for example, $\pi = 3.14159265...$ is a number with an infinite non-periodic decimal expansion (that's just a fancy
        way of saying it goes on an on after the dot).
        So instead we have the next best thing, an approximation of the real numbers that has a significant number
        of limitations. We will talk about many of those limitations as they become relevant but, for now, just keep
        in mind that there are some numbers (actually, a lot of them) that you cannot represent precisely in a computer program,
        because your RAM memory is limited.

        As you might (or not) expect, numbers with decimal values are written with a dot (`.`) separating the whole
        part from the decimal part:

        ```python
        pi = 3.14159265 # (not really, only approximately)
        ```

        > By the way, that piece of gray text starting with `#` is what we call a *comment*. You can put these
        anywhere in your program and they are completely ignored by the computer. There are useful to leave, well, comments
        to other programmers (or yourself).
    """)

    st.write("""
        ## What about letters?

        Numbers are far from the only type of data we need to express facts.
        The second most basic type of is probably text, which is funny, because it's both super simple and
        also capable of expressing the most complex concepts, right?

        In Python, we denote a piece of literal text between pairs of `"`, like this.
        They can be as long as you want, and have any letter, including spaces, smileys, 
        and anything you can write on a text message, basically.

        ```python
        my_name = "Alejandro Piad"
        ```

        Go on, give it a try:
    """)

    your_name_expression = st.text_input("Tell me your name in Python code")

    if not your_name_expression:
        return

    global_vars = {}

    try:
        exec(your_name_expression, global_vars)
        your_name = global_vars['my_name']
        assert isinstance(your_name, str)
    except SyntaxError:
        st.error(
            "­ЪЎЃ That code doesn't seem right. Make sure you typed everything as I taught you."
        )
        return
    except KeyError:
        st.error(
            "­ЪЎЃ That code doesn't tell me your age. Make sure your variable is called `my_name`, the way I did before."
        )
        return
    except NameError:
        st.error(
            "­ЪЎЃ That code doesn't seem right. Make sure your enclosing your name in a pair of `\"` like I did before."
        )
        return
    except AssertionError:
        st.error(
            "­ЪЎЃ That code doesn't seem right. Your name should be a non-empty literal text, between pairs of `\"`."
        )
        return

    if your_name == "Alejandro Piad":
        st.warning(
            "­Ъцћ Are you sure that's your real name? You didn't copied and pasted *my* code, right? Ok, I'll believe you..."
        )

    st.success(
        f"­ЪЦ│ Congrats, **{your_name}**, with age **{your_age}**. Now you know three types of data!"
    )

    st.write("""
        You can go a long way with just text and numbers. Actually, we could argue that everything, in the end,
        is just a *composition* of numbers and text.
    """)

    st.info("""
        ­ЪЊЮ Technically speaking, whole numbers in Python (and most programming languages) are called `integers`
        (just like their mathematical name), while decimal numbers are called `floats` 
        (which stands for *floating-point*, something we'll explain later),
        and fragments of text are called `strings`, for historical purposes (they are strings of letters ­Ъци).
        So now you know, when others mention these funny names, they're just talking about numbers and text. 
        
        ­ЪЉЅ We'll stick to their technical name from now on,
        just to be fancy ­ЪўЅ.
    """)

    st.write("""
        ## Рџа№ИЈ The type of the data matters!

        Now that you know two, well, techincally three, different types of data, it's important to get rid
        of a common source of mistakes. You can represent apparently the same datum with all three, 
        but they are actually different, and that difference matters.

        If you say `a = 25` as opposed to `a = 25.0`, *mathematically* you're saying
        the same things, but *computationally* these are two different values.
        The reason is because these are values of two different *types* (integers and floats) and
        you should *always* be clear of the exact type you're dealing with.
    """)
Beispiel #21
0
st.markdown("## **②  Paste keywords/internal search terms ✨**")

linesDeduped2 = []
MAX_LINES = 200
text = st.text_area("One keyword per line (200 max)", height=200, key=1)
lines = text.split("\n")  # A list of lines
linesList = []
for x in lines:
    linesList.append(x)
linesList = list(dict.fromkeys(linesList))  # Remove dupes
linesList = list(filter(None, linesList))  # Remove empty

if len(linesList) > MAX_LINES:
    st.warning(
        f"⚠️ Only the 200 first keywords will be reviewed. Increased allowance  is coming - Stay tuned! 😊)"
    )
    linesList = linesList[:MAX_LINES]

########################

c = st.beta_container()
c30 = st.beta_container()
c29, c30, c31 = st.beta_columns(3)

with c29:
    start_execution = st.button(" Run model! ✨ ")
    c50 = st.beta_container()

c29, c30, c31 = st.beta_columns([1, 6, 1])
Beispiel #22
0
                latest_iteration.text(
                    f'Progress: {n_sample}/{i}. Accuracy: {round(n_right / n_sample, 2) * 100}%'
                )
                bar.progress(i / n_sample)
                time.sleep(0.05)
            time_end = time.time()
            if n_right == n_sample:
                text = "tests" if n_sample > 1 else "test"
                st.success(
                    f"{n_sample} {text} passed in {round((time_end - time_start) * 1000 - n_sample * 50, 2)} ms."
                )
            else:
                if n_right == 0:
                    st.error("All tests failed.")
                else:
                    st.warning(f"{n_right} passed. {n_wrong} failed.")
                for sample in wrong_samples:
                    st.error(
                        f"Test #{sample[2]}: {sample[3]}" +
                        f" - Output \'{sample[1]} ({triangle.type_of_triangle[sample[1]]})\'"
                        +
                        f" is expected to be \'{int(sample[0])} ({triangle.type_of_triangle[sample[0]]})\'"
                    )

            st.header("Analysis")
            labels = 'pass', 'fail'
            sizes = [n_right, n_wrong]
            plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
            plt.axis('equal')
            st.pyplot()
Beispiel #23
0
    submit = st.button(label="Submit")

    if submit:
        for file in file_n:
            x = os.path.join("C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/Proforma Template/",file)
            try:
                doc = DocxTemplate(os.path.join("/Proforma Template/",x))
                x = requests.get('http://151.80.237.86:1251/ords/zkt/pi_doc/doc?pi_no={}'.format(usr_input))
                data = x.json()
                for x in data['items']:
                    doc.render(x)
                    doc.save(f"C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/Proforma/{usr_input}_{file}.docx")
                    pythoncom.CoInitialize()
                    convert(f"C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/Proforma/{usr_input}_{file}.docx",f"C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/Proforma/{usr_input}_{file}.pdf")
            except Exception as e:
                st.warning(e)
        if file_name is not None:
            for file in file_name:
                doc = DocxTemplate(file)
                doc.save(f"{file.name}")
                for x in os.listdir("C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/"):
                    # st.write(x)
                    if x.endswith(".docx"):
                        doc = DocxTemplate(x)
                        x = requests.get('http://151.80.237.86:1251/ords/zkt/pi_doc/doc?pi_no={}'.format(usr_input))
                        data = x.json()
                        for x in data['items']:
                            doc.render(x)
                            doc.save(
                                f"C:/Users/SoftChan.Arshad/Desktop/Garibsons Setup/Version 2.0/Proforma/{usr_input}_{file.name}.docx")
                            pythoncom.CoInitialize()
Beispiel #24
0
def write():
    # Load dataframes from excel sheets
    df = MTX.MTX_pandas_main_file(Destination_main_file)
    # Pandas dataframe witch value equals the row in the dataframe witch represent the selected treatment
    df_st = MTX.MTX_pandas_st_file(Destination_st_file)

    # in case of KeyError for [df_st["selected_treatment"][0], exception is rasied an user is referred to startpage
    try:
        # Get variabels from dataframe
        Vægt = df["Vægt"][df_st["selected_treatment"][0]]
        Overflade = df["Overflade"][df_st["selected_treatment"][0]]
        Treatment_time_t0 = df["Treatment_time_t0"][df_st["selected_treatment"]
                                                    [0]]
        Plasma_kreatinin_før_start = df["Plasma_kreatinin_før_start"][
            df_st["selected_treatment"][0]]
        Udskillelsesskema = df["Udskillelsesskema"][df_st["selected_treatment"]
                                                    [0]]
        Time_t23 = MTX.Treatment_time_t0_validering(23, df, df_st)
        Time_t36 = MTX.Treatment_time_t0_validering(36, df, df_st)
        Time_t42 = MTX.Treatment_time_t0_validering(42, df, df_st)
        Time_t48 = MTX.Treatment_time_t0_validering(48, df, df_st)
        Time_t54 = MTX.Treatment_time_t0_validering(54, df, df_st)
        Time_t60 = MTX.Treatment_time_t0_validering(60, df, df_st)
        Time_t66 = MTX.Treatment_time_t0_validering(66, df, df_st)
        Diurese_600ml_6timer = df["Diurese_600ml_6timer"][
            df_st["selected_treatment"][0]]
        Dosis_natriumcarbonat_ved_lav_pH = df[
            "Dosis_natriumcarbonat_ved_lav_pH"][df_st["selected_treatment"][0]]

        # Selected patient info
        MTX.patient_information_box(df, df_st)

        # Oversigt over blodprøver og deres værdier
        MTX.Blood_sample_overview(Udskillelsesskema, df, df_st)

        if Dosis_natriumcarbonat_ved_lav_pH != 0.0 and Diurese_600ml_6timer != 0.0:
            st.info(
                "Diuresen skal være over 600 ml/m²/ 6 timer svt. " +
                str(Diurese_600ml_6timer) + " ml/6 timer.  \n\n"
                "Ved urin pH<7.0 skal der gives ekstra bicarbonat:  \n"
                "Na-bicarbonat 20 mmol/m² blandes i 40 ml af hydreringsvæsken og gives over over 30 min. samtidig med forhydreringen. "
                "Svarende til: **" + str(Dosis_natriumcarbonat_ved_lav_pH) +
                "** mmol Na-bicarbonat.  \n\n"
                "Ved urin pH > 8 skiftes til KNaG uden bicarbonat i 3 time.  \n"
                "Når pH er under 8 skiftes til bicarbonatholdig hydrering.")

        #### Time 23 ####
        st.subheader("Time 23: " + str(Time_t23))
        # Text area for notes
        MTX.Fritekst_indtastningsfelt("Time 23", df, df_st)

        # Input for Se_MTX_t23
        Se_MTX_t23 = MTX.Blood_sample_input(23, "Se-MTX", df, df_st)

        # Input for P_kreatinin_t23
        P_kreatinin_t23 = MTX.Blood_sample_input(23, "P-kreatinin", df, df_st)

        st.write("Pt. køres på OP til MTX is.")

        #### Time 36 ####
        st.subheader("Time 36: " + str(Time_t36))
        # Text area for notes
        MTX.Fritekst_indtastningsfelt("Time 36", df, df_st)
        st.write("MTX konc t36 analyseres sammen med t23 til time 42 ")

        # Input for Se_MTX_t36
        Se_MTX_t36 = MTX.Blood_sample_input(36, "Se-MTX", df, df_st)
        MTX.MTX_input_check(Se_MTX_t23, Se_MTX_t36)

        # Input for P_kreatinin_t36
        P_kreatinin_t36 = MTX.Blood_sample_input(36, "P-kreatinin", df, df_st)

        try:
            if P_kreatinin_t23 > Plasma_kreatinin_før_start * 1.5 or P_kreatinin_t36 > Plasma_kreatinin_før_start * 1.5 or Se_MTX_t36 > 3.0:
                Hydreing_ved_høj_P_kreatinin_t36 = int(
                    round(Overflade * 4500 / 24))
                Diurese_ved_høj_P_kreatinin_t36 = int(round(Overflade * 900))
                st.error(
                    "OPMÆRKSOM: Patienten er i høj-risiko for at have forsinket MTX udskillelse.  \n"
                    "Hydreringen øges til 4500 ml/m²/døgn svt. **" +
                    str(Hydreing_ved_høj_P_kreatinin_t36) + " ml/t.**  \n"
                    "Duriresen skal være over 900 ml/m²/ 6 timer svt. **" +
                    str(Diurese_ved_høj_P_kreatinin_t36) + " ml/6t.**")
            elif P_kreatinin_t36 != 0:
                Hydreing_ved_normal_P_kreatinin_t36 = int(
                    round(Overflade * 300 / 24))
                Diurese_ved_normal_P_kreatinin_t36 = int(round(Overflade *
                                                               600))
                st.warning(
                    "Hydreringen fortsættes med 3000 ml/m²/døgn svarende til **"
                    + str(Hydreing_ved_normal_P_kreatinin_t36) + " ml/t.**  \n"
                    "Duriresen skal være over 600 ml/m²/ 6 timer svt. **" +
                    str(Diurese_ved_normal_P_kreatinin_t36) + " ml/t.**")
        except TypeError as error:
            if str(error
                   ) == "can't multiply sequence by non-int of type 'float'":
                st.error(
                    "!!!  \n"
                    "Forhydreringen er ikke registreret. Gå til forhydrering og indtast data for forhydrering."
                    "  \n!!!")

        #### Time 42 ####
        st.subheader("Time 42: " + str(Time_t42))
        # Text area for notes
        MTX.Fritekst_indtastningsfelt("Time 42", df, df_st)

        st.write("MTX konc t42 analyseres sammen med t23 til time 36.")
        st.warning(
            "OBS: Hvis Se-MTX t42 > 1 µmol/l skal der straks gives ekstra calciumfolinat."
        )

        # Input for Se_MTX_t42
        Se_MTX_t42 = MTX.Blood_sample_input(42, "Se-MTX", df, df_st)
        MTX.MTX_input_check(Se_MTX_t36, Se_MTX_t42)

        try:
            if (Se_MTX_t42 < 0.5 or Se_MTX_t42 > 3.0) and Se_MTX_t42 != 0.0:
                st.error(
                    "OPMÆRMSOM: Du har indtastet en Se-MTX værdi som ikke ligger intervallet 0.5-3.0 µmol/l hvilket er uden for normalen ved time 42."
                )
        except TypeError as error:
            if error == "'<' not supported between instances of 'str' and 'float'":
                pass

        try:
            # Determine witch hydration scheme the patient shall follow
            if Udskillelsesskema == "":
                if Se_MTX_t42 > 1:
                    Udskillelsesskema = "Sen udskillelse"
                elif 0.6 <= Se_MTX_t42 <= 1:
                    Udskillelsesskema = "Normal udskillelse"
                elif Se_MTX_t42 < 0.6 and Se_MTX_t42 != 0.0:
                    Udskillelsesskema = "Hurtig udskillelse"
                df.loc[df_st["selected_treatment"][0],
                       "Udskillelsesskema"] = Udskillelsesskema
        except TypeError as error:
            if error == "'>' not supported between instances of 'str' and 'int'":
                pass

        # Makes it possible to change hydration scheme if Se-MTX t42 is changed
        if Udskillelsesskema != "":
            if Se_MTX_t42 > 1 and Udskillelsesskema != "Sen udskillelse":
                Udskillelsesskema_ny = "Sen udskillelse"

            elif 0.6 <= Se_MTX_t42 <= 1 and Udskillelsesskema != "Normal udskillelse":
                Udskillelsesskema_ny = "Normal udskillelse"

            elif Se_MTX_t42 < 0.6 and Se_MTX_t42 != 0.0 and Udskillelsesskema != "Hurtig udskillelse":
                Udskillelsesskema_ny = "Hurtig udskillelse"

            try:
                if Udskillelsesskema_ny != Udskillelsesskema:
                    st.warning(
                        "Du har ændret i værdien for Se-MTX t42. "
                        "Den gamle værdi angav at patienten skal følge skema for _"
                        + str.lower(Udskillelsesskema) +
                        "_, hvorimod den nye værdi angiver at patienten skal følge skema for _"
                        + str.lower(Udskillelsesskema_ny) + "_  \n"
                        "Vil du bekræfte at patienten skal skifte til skema for _"
                        + str.lower(Udskillelsesskema_ny) + "_?")
                    if st.button("Ja, overgå til skema for " +
                                 str.lower(Udskillelsesskema_ny)):
                        df.loc[df_st["selected_treatment"][0],
                               "Udskillelsesskema"] = Udskillelsesskema_ny
                        df.to_excel(Destination_main_file)
            except UnboundLocalError:
                pass

        # Calculate dosis calciumfolinat and display to user
        MTX.Dosis_calciumfolinat_function(42, False, df, df_st)

        # Input function for validation of administration of dosis
        MTX.Sygeplejerske_navn_tid_validering(
            "Sygeplejerske_navn_dosis_calciumfolinat_t42",
            "Sygeplejerske_tid_dosis_calciumfolinat_t42",
            "Dosis calciumfoliat af Se-MTX t42 er givet", df, df_st)

        # If the hydration scheme is determined if statement will show next treatment procedure
        if Udskillelsesskema in {
                "Hurtig udskillelse", "Normal udskillelse", "Sen udskillelse"
        }:
            if Udskillelsesskema == "Sen udskillelse":
                Ekstra_dosis_calciumfolinat_t42 = MTX.Ekstra_dosis_calciumfolinat_function(
                    42, Se_MTX_t42, df, df_st)
                st.error("Grundet Se-MTX t42 > 1 µmol/l:  \n"
                         "Giv straks 1. ekstra calciumfolinatdosis af **" +
                         str(int(round(Ekstra_dosis_calciumfolinat_t42))) +
                         " mg iv.**")

                # Input function for validation of administration of dosis
                MTX.Sygeplejerske_navn_tid_validering(
                    "Sygeplejerske_navn_Ekstra_dosis_calciumfolinat_t42",
                    "Sygeplejerske_tid_Ekstra_dosis_calciumfolinat_t42",
                    "Ekstra dosis calciumfoliat af Se-MTX t42 er givet", df,
                    df_st)

                Hydreing_ved_sen_udskillelse = int(round(Overflade * 4500 /
                                                         24))
                Diurese_ved_sen_udskillelse = int(round(Overflade * 900))
                st.error(
                    "OPMÆRKSOM: Patienten overgår til skema for sen udskillelse!  \n\n"
                    "Hydreringen øges til 4500 ml/m²/døgn svt. **" +
                    str(Hydreing_ved_sen_udskillelse) + " ml/t.**  \n"
                    "Duriresen skal være over 900 ml/m²/ 6 timer svt. **" +
                    str(Diurese_ved_sen_udskillelse) + " ml/6t.**  \n"
                    "Fortsættes indtil se-MTX er < 0,2 µmol/l.")

            #### Time 48 ####
            st.subheader("Time 48: " + str(Time_t48) + " - (" +
                         str(Udskillelsesskema) + ")")
            # Text area for notes
            MTX.Fritekst_indtastningsfelt("Time 48", df, df_st)

            if Udskillelsesskema == "Hurtig udskillelse":
                st.write("MTX konc t48 analyseres sammen med t54 næste dag")
            if Udskillelsesskema == "Normal udskillelse":
                st.write(
                    "MTX konc t48 analyseres sammen med t54 og t66 næste dag")
            if Udskillelsesskema == "Sen udskillelse":
                st.write(
                    "Tag Se-MTX t48: Analyseres akut. Afvent svar før calciumfolinat."
                )

            # Input for Se_MTX_t48
            Se_MTX_t48 = MTX.Blood_sample_input(48, "Se-MTX", df, df_st)
            MTX.MTX_input_check(Se_MTX_t42, Se_MTX_t48)

            # Calculate dosis calciumfolinat and display to user
            if Udskillelsesskema in {
                    "Hurtig udskillelse", "Normal udskillelse"
            }:
                MTX.Dosis_calciumfolinat_function(48, False, df, df_st)
            if Udskillelsesskema == "Sen udskillelse":
                MTX.Dosis_calciumfolinat_function(48, True, df, df_st)

            # Input function for validation of administration of dosis
            MTX.Sygeplejerske_navn_tid_validering(
                "Sygeplejerske_navn_dosis_calciumfolinat_t48",
                "Sygeplejerske_tid_dosis_calciumfolinat_t48",
                "Dosis calciumfoliat af Se-MTX t48 er givet", df, df_st)

            #### Time 54 ####
            st.subheader("Time 54: " + str(Time_t54) + " - (" +
                         str(Udskillelsesskema) + ")")
            # Text area for notes
            MTX.Fritekst_indtastningsfelt("Time 54", df, df_st)

            if Udskillelsesskema == "Hurtig udskillelse":
                st.write(
                    "MTX konc t54 analyseres sammen med t48 fra forrige dag")
            if Udskillelsesskema == "Normal udskillelse":
                st.write(
                    "MTX konc t54 analyseres sammen med t48 og t66 næste dag")
            if Udskillelsesskema == "Sen udskillelse":
                if Se_MTX_t48 > 1:
                    st.write(
                        "Tag Se-MTX t54: Analyseres akut. Afvent svar før calciumfolinat."
                    )
                if Se_MTX_t48 <= 1:
                    st.write(
                        "Tag Se-MTX t54: Akut analyse er ikke nødvendig. Analyse kan vente til næste dag."
                    )

            # Input for Se_MTX_t54
            Se_MTX_t54 = MTX.Blood_sample_input(54, "Se-MTX", df, df_st)
            MTX.MTX_input_check(Se_MTX_t48, Se_MTX_t54)

            # Calculate dosis calciumfolinat and display to user
            if Udskillelsesskema in {
                    "Hurtig udskillelse", "Normal udskillelse"
            }:
                MTX.Dosis_calciumfolinat_function(54, False, df, df_st)
            if Udskillelsesskema == "Sen udskillelse":
                MTX.Dosis_calciumfolinat_function(54, True, df, df_st)

            # Input function for validation of administration of dosis
            MTX.Sygeplejerske_navn_tid_validering(
                "Sygeplejerske_navn_dosis_calciumfolinat_t54",
                "Sygeplejerske_tid_dosis_calciumfolinat_t54",
                "Dosis calciumfoliat af Se-MTX t54 er givet", df, df_st)

            if Udskillelsesskema == "Hurtig udskillelse":
                MTX.Tjek_for_udskrivelse_af_patient(54, Se_MTX_t54, True, df,
                                                    df_st)

            if Udskillelsesskema == "Normal udskillelse":
                MTX.Tjek_for_udskrivelse_af_patient(54, Se_MTX_t54, False, df,
                                                    df_st)

                #### Time 66 ####
                st.subheader("Time 66: " + str(Time_t66) + " - (" +
                             str(Udskillelsesskema) + ")")
                # Text area for notes
                MTX.Fritekst_indtastningsfelt("Time 66", df, df_st)
                st.write(
                    "MTX konc t66 analyseres sammen med t48 og t54. Afvent svar før evt. t66 dosis calciumfolinat"
                )

                # Input for Se_MTX_t66
                Se_MTX_t66 = MTX.Blood_sample_input(66, "Se-MTX", df, df_st)
                MTX.MTX_input_check(Se_MTX_t54, Se_MTX_t66)

                # Input for P_kreatinin_t66
                P_kreatinin_t66 = MTX.Blood_sample_input(
                    66, "P-kreatinin", df, df_st)

                if Se_MTX_t66 >= 0.2:
                    # Calculate dosis calciumfolinat and display to user
                    MTX.Dosis_calciumfolinat_function(66, False, df, df_st)

                    # Input function for validation of administration of dosis
                    MTX.Sygeplejerske_navn_tid_validering(
                        "Sygeplejerske_navn_dosis_calciumfolinat_t66",
                        "Sygeplejerske_tid_dosis_calciumfolinat_t66",
                        "Dosis calciumfoliat af Se-MTX t66 er givet", df,
                        df_st)

                MTX.Tjek_for_udskrivelse_af_patient(66, Se_MTX_t66, True, df,
                                                    df_st)

            if Udskillelsesskema == "Sen udskillelse":

                #### Time 60 ####
                st.subheader("Time 60: " + str(Time_t60) + " - (" +
                             str(Udskillelsesskema) + ")")
                # Text area for notes
                MTX.Fritekst_indtastningsfelt("Time 60", df, df_st)
                st.write(
                    "Giv t60 dosis calciumfolinat-dosis, i samme dosis som ved t54."
                )

                # Calciumfolinat dosis t60
                if df["Se_MTX_t54"][df_st["selected_treatment"][0]] == "":
                    st.warning(
                        "Indtast Se-MTX t54 for at beregne calciumfolinat-dosis."
                    )

                if df["Se_MTX_t54"][df_st["selected_treatment"][0]] != "":
                    Dosis_calciumfolinat_t60 = MTX.Ekstra_dosis_calciumfolinat_function(
                        60, Se_MTX_t54, df, df_st)
                    st.write(
                        "Giv t60 calciumfolinat-dosis " +
                        str(int(round(Dosis_calciumfolinat_t60 / Overflade))) +
                        " mg/m² svt. **" +
                        str(round(Dosis_calciumfolinat_t60)) + " mg iv.**")

                # Input function for validation of administration of dosis
                MTX.Sygeplejerske_navn_tid_validering(
                    "Sygeplejerske_navn_dosis_calciumfolinat_t60",
                    "Sygeplejerske_tid_dosis_calciumfolinat_t60",
                    "Dosis calciumfoliat af Se-MTX t60 er givet", df, df_st)

                # While-loop for delayed excretion that continues until the treatment ends.
                # Get value to dertermine of patient is still Hospitalized
                Udskrevet = df["Udskrevet"][df_st["selected_treatment"][0]]
                Fortsæt_behandling = True

                Tid_while_loop_str = df["Tid_while_loop"][
                    df_st["selected_treatment"][0]]
                if Tid_while_loop_str != "start-66":
                    #st.success(")")
                    Tid_while_loop_list = list(Tid_while_loop_str.split("-"))
                    #st.write(Tid_while_loop_list)
                if Tid_while_loop_str == "start-66":
                    #st.success("")
                    Tid_while_loop_list = list(Tid_while_loop_str.split("-"))
                    #st.write(Tid_while_loop_list)

                for i in range(1, len(Tid_while_loop_list)):
                    tid0 = str(Tid_while_loop_list[i])
                    Time_t_start = Treatment_time_t0 + dt.timedelta(
                        hours=int(tid0))
                    tid12 = str(int(tid0) + 12)
                    Time_t_12 = Treatment_time_t0 + dt.timedelta(
                        hours=int(tid0) + 12)

                    # Get values for blood sample check
                    Se_MTX_T_start_minus_12 = df[
                        "Se_MTX_t" +
                        str(int(tid0) - 12)][df_st["selected_treatment"][0]]
                    Se_MTX_T_start_minus_24 = df[
                        "Se_MTX_t" +
                        str(int(tid0) - 24)][df_st["selected_treatment"][0]]

                    try:
                        keyerror_check = df["Fritekst_Time " + tid0][
                            df_st["selected_treatment"][0]]
                    except KeyError as error:
                        MTX.Forlæng_behandling_indsæt_nye_kolonner(
                            tid0, tid12, df)

                    #### Time start ####
                    st.subheader("Time " + tid0 + ": " + str(Time_t_start) +
                                 " - (Sen udskillelse)")
                    # Text area for notes
                    MTX.Fritekst_indtastningsfelt("Time " + tid0, df, df_st)

                    st.write(
                        "Tag Se-MTX t" + tid0 +
                        ": Analyseres akut. Afvent svar før yderligere calciumfolinat."
                    )

                    # Input for Se_MTX_t_start
                    Se_MTX_t_start = MTX.Blood_sample_input(
                        int(tid0), "Se-MTX", df, df_st)
                    # Input check for Se-MTX
                    if Se_MTX_T_start_minus_12 != "":
                        MTX.MTX_input_check(Se_MTX_T_start_minus_12,
                                            Se_MTX_t_start)
                    elif Se_MTX_T_start_minus_24 != "":
                        MTX.MTX_input_check(Se_MTX_T_start_minus_24,
                                            Se_MTX_t_start)

                    # Input for P_kreatinin_t_start
                    P_kreatinin_t_start = MTX.Blood_sample_input(
                        int(tid0), "P-kreatinin", df, df_st)

                    # Need Se-MTX t_start input:
                    if df["Se_MTX_t" +
                          tid0][df_st["selected_treatment"][0]] == "":
                        st.warning("Indtast Se-MTX t" + tid0 +
                                   " for at beregne calciumfolinat-dosis.")

                    if df["Se_MTX_t" +
                          tid0][df_st["selected_treatment"][0]] != "":
                        if Se_MTX_t_start >= 0.2:
                            Dosis_calciumfolinat_t_start = MTX.Ekstra_dosis_calciumfolinat_function(
                                tid0, Se_MTX_t_start, df, df_st)
                            st.info(
                                "Giv t" + tid0 +
                                " dosis calciumfolinat-dosis " + str(
                                    int(
                                        round(Dosis_calciumfolinat_t_start /
                                              Overflade))) + " mg/m² svt. **" +
                                str((Dosis_calciumfolinat_t_start)) +
                                " mg iv. **")

                            # Input function for validation of administration of dosis
                            MTX.Sygeplejerske_navn_tid_validering(
                                "Sygeplejerske_navn_dosis_calciumfolinat_t" +
                                tid0,
                                "Sygeplejerske_tid_dosis_calciumfolinat_t" +
                                tid0, "Dosis calciumfoliat af Se-MTX t" +
                                tid0 + " er givet", df, df_st)

                        MTX.Tjek_for_udskrivelse_af_patient(
                            tid0, Se_MTX_t_start, False, df, df_st)

                        if Se_MTX_t_start >= 0.5:
                            # Make calculation of ekstra calciumfolinat dosis and input fields for four ekstra doses
                            MTX.Fire_ekstra_dosis_calciumfolinat(
                                int(tid0), Se_MTX_t_start, df, df_st)

                            if Se_MTX_t_start > 2.0 or (
                                    Se_MTX_t_start > 1.0
                                    and Se_MTX_T_start_minus_24 != ""):
                                st.warning(
                                    "Grundet Se-MTX t" + tid0 +
                                    " > 2,0 µmol/l: Giv calciumfolinat og mål Se-MTX 2 gange i døgnet til Se-MTX er < 1,0 µmol/l."
                                )

                                #### Time t start + 12 timer ####
                                st.subheader("Time " + tid12 + ": " +
                                             str(Time_t_12) +
                                             " - (Sen udskillelse)")
                                # Text area for notes
                                MTX.Fritekst_indtastningsfelt(
                                    "Time " + tid12, df, df_st)

                                st.write("Tag Se-MTX t" + tid12)

                                # Input for Se_MTX_t_start_plus_12
                                Se_MTX_t_start_plus_12 = MTX.Blood_sample_input(
                                    int(tid12), "Se-MTX", df, df_st)
                                MTX.MTX_input_check(Se_MTX_t_start,
                                                    Se_MTX_t_start_plus_12)
                                MTX.Tjek_for_udskrivelse_af_patient(
                                    tid12, Se_MTX_t_start_plus_12, False, df,
                                    df_st)

                    # Treatment stops as default and wait for user to prolong
                    Fortsæt_behandling = False

                    # If blood sample values is present, the user can prolong treatment
                    if Se_MTX_t_start != 0 and Udskrevet == False and int(
                            Tid_while_loop_list[i]) == int(
                                Tid_while_loop_list[-1]):
                        Fortsæt_behandling = st.button(
                            "Patienten er endnu ikke udskrevet. Tryk for at fortsætte behandlingen.",
                            key=tid0)

                        if Fortsæt_behandling:
                            # update time variable so treatment can continue for 24 hours
                            Tid_while_loop_str += "-" + str(int(tid0) + 24)
                            df.loc[df_st["selected_treatment"][0],
                                   "Tid_while_loop"] = Tid_while_loop_str
                            df.to_excel(Destination_main_file)

        # Tells use to input Se-MTX t42 so further treatment can be chosen
        elif Se_MTX_t42 == 0.0:
            st.error("Indtast Se-MTX t42 før behandling fortsættes.")

            Ingen_Se_MTX_t42 = st.checkbox("Fortsæt uden Se-MTX t42 værdi.")
            if Ingen_Se_MTX_t42:
                st.error(
                    "ADVARSEL: Værdien af Se-MTX t42 afgør om patienten har normal, hurtig eller sen udskillelse.  \n"
                    "Du er i gang med at gå videre uden denne værdi, hvilket ikke anbefales.  \n"
                )
                Udskillelsesskema = st.radio(
                    "Vælg hvilket udskillelsesskema patienten skal behandles ved:",
                    options=[
                        "Hurtig udskillelse", "Normal udskillelse",
                        "Sen udskillelse"
                    ],
                    index=1)
                if st.button("Bekræft at du har valgt " +
                             str.lower(Udskillelsesskema)):
                    df.loc[df_st["selected_treatment"][0],
                           "Udskillelsesskema"] = Udskillelsesskema
                    df.to_excel(Destination_main_file)

    except IndexError:
        st.info(
            "Der er ingen tidligere patienter. Gå til startside og opret ny patient."
        )
    except KeyError:
        st.warning(
            "Der er ikke valg en patient.  \n"
            "Gå til 'Startside', vælg patient og behandling og tryk på knappen 'Vælg patient'."
        )
def generate_plot(search_by, filter_by, mode):
    st.subheader("Plots \n ")
    try:
        if filter_by in ["gene_name", "gene_id", "transcript_id"]:
            variant_file = "./outputs/" + search_by + "/variants.tsv"

            if os.path.isfile(variant_file):
                ## gnomad
                variants_df = pd.read_csv(variant_file, sep="\t")
                fig1 = make_grouping_freq_plot(
                    variants_df, "consequence",
                    'Consequence of gnomAD Variants')
                fig2 = make_grouping_freq_plot(variants_df, "lof",
                                               'LoF of gnomAD Variants')
                fig3 = make_grouping_freq_plot(
                    variants_df, "lof_filter", 'LoF Filtes of gnomAD Variants')

                ## clinvar
                clivar_df = pd.read_csv("./outputs/" + search_by +
                                        "/clinvar_variants.tsv",
                                        sep="\t")
                clivar_df["clinical_significance"] = clivar_df[
                    "clinical_significance"].apply(lambda x: x.split("'")[1])
                fig4 = make_grouping_freq_plot(
                    clivar_df, "clinical_significance",
                    'Clinical Significance of ClinVar Variants')
                fig5 = make_grouping_freq_plot(
                    clivar_df, "major_consequence",
                    'Major Consequence of ClinVar Variants')

                # Show in the app
                if mode == "single":
                    st.plotly_chart(fig1)
                    st.plotly_chart(fig2)
                    st.plotly_chart(fig3)
                    st.plotly_chart(fig4)
                    st.plotly_chart(fig5)

                # Export as HTML
                fig1.write_html("./outputs/" + search_by +
                                "/gnomAD_variants_by_consequence.html")
                fig2.write_html("./outputs/" + search_by +
                                "/gnomAD_variants_by_lof.html")
                fig3.write_html("./outputs/" + search_by +
                                "/gnomAD_variants_by_lof_filter.html")
                fig4.write_html(
                    "./outputs/" + search_by +
                    "/clinvar_variants_by_clinical_significance.html")
                fig5.write_html("./outputs/" + search_by +
                                "/clinvar_variants_by_major_consequence.html")
            else:
                st.warning(
                    "Plots were not generated since `variants.tsv` could not be created. It may happens if the data is not available for your dataset"
                )

        if filter_by in ["gene_name", "gene_id"]:
            structural_variants_file = "./outputs/" + search_by + "/structural_variants.tsv"
            if os.path.isfile(variant_file):
                ## structural_variants
                sv_df = pd.read_csv(structural_variants_file, sep="\t")
                fig6 = make_grouping_freq_plot(
                    sv_df, "consequence",
                    'Major Consequence of Structural Variants')

                # Show in the app
                if mode == "single":
                    st.plotly_chart(fig6)

                # Export as HTML
                fig6.write_html("./outputs/" + search_by +
                                "/structural_variants_by_consequence.html")
            else:
                st.warning(
                    "Plots were not generated since `structural_variants.tsv` could not be created. It may happens if the data is not available for your dataset"
                )

    except Exception as plotError:
        # st.text(plotError)
        pass
def main():
    st.title('Perform EDA with ease...')

    def file_select(folder='./datasets'):
        filelist=os.listdir(folder)
        selectedfile=st.selectbox('select a default file',filelist)
        return os.path.join(folder,selectedfile)


    if st.checkbox('Select dataset from local machine'):
        data=st.file_uploader('Upload Dataset in .CSV',type=['CSV'])
        if data is not None:
            df=pd.read_csv(data)
    else:
        filename=file_select()
        st.info('You selected {}'.format(filename))
        if filename is not None:
            df=pd.read_csv(filename)
    #show data
    if st.checkbox('Show Dataset'):
        num=st.number_input('No. of Rows',5,10)
        head=st.radio('Select Head/Tail',('Head','Tail'))
        if head=='Head':
            st.dataframe(df.head(num))
        else:
            st.dataframe(df.tail(num))
        
    #show columns
    if st.checkbox('Columns'):
        st.write(df.columns)
    #show shape
    if st.checkbox('Shape'):
        st.text('(Rows,Columns)')
        st.write(df.shape)
    
    #select columns
    if st.checkbox('Select Columns to show'):
        collist=df.columns.tolist()
        selcols=st.multiselect("Select",collist)
        newdf=df[selcols]
        st.dataframe(newdf)
    #unique values
    if st.checkbox('Unique Values'):
        st.dataframe(df.nunique())
        selectedcol=st.selectbox('Select column to see unique values',df.columns.tolist())
        st.write(df[selectedcol].unique())
    #data type
    if st.checkbox('Data Types'):
        st.dataframe(df.dtypes)
    #chech for nul values
    if st.checkbox('Null values'):
        st.dataframe(df.isnull().sum()) 
        st.write(sns.heatmap(df.isnull(),yticklabels=False,cbar=False,cmap='viridis'))
        st.pyplot()
    #show summary
    if st.checkbox('Summary/Describe'):
        st.write(df.describe())

    #plot and viz.
    st.header('Data Visualization with Seaborn')
    #seaborn correlation plot
    if st.checkbox('Correlation plot'):
        st.write(sns.heatmap(df.corr(),annot=True))
        st.pyplot()
    #univariate distribution
    if st.checkbox('Univariate Distribution'):
        cols=df.columns.tolist()
        plottype=st.selectbox('Select plot type',['dist','hist'])
        selectedcol=st.selectbox('Select columns to plot',cols)
        binnum=st.number_input('No. of bins',10,50)
        st.write(sns.distplot(df[selectedcol],bins=binnum))
        st.pyplot()
    #bivariate distribution
    if st.checkbox('Bivariate Distribution'):
        cols=df.columns.tolist()
        plottype=st.selectbox('Select plot type',['scatterplot','jointplot'])
        st.text('Select two columns')
        x=st.selectbox('Select X-axis column to plot',cols)
        y=st.selectbox('Select Y-axis column to plot',cols)
        kindtype=st.selectbox('Select plot kind',['none','reg','resid','hex','kde'])
        if kindtype!='none':
            st.write(sns.jointplot(df[x],df[y],kind=kindtype))
            st.pyplot()
        else:
            st.write(sns.jointplot(df[x],df[y]))
            st.pyplot()
    #pair wise plot
    if st.checkbox('Pair Plot'):
        cols=df.columns.tolist()
        cols.insert(0,'none')
        selectedcollist=st.multiselect('Select columns to plot',cols)
        hueval=st.selectbox('Select a hue column',cols)
        if hueval!='none':
            st.write(sns.pairplot(df[selectedcollist],hue=df[hueval]))
            st.pyplot()
        else:
            st.write(sns.pairplot(df[selectedcollist]))
            st.pyplot()
    
    #categorical plots
    if st.checkbox('Categorical Scatterplots'):
        cols=df.columns.tolist()
        cols.insert(0,'none')
        plottype=st.selectbox('Select plot type',['stripplot','swarmplot'])
        x=st.selectbox('Select X-axis(categorical) column to plot',cols)
        y=st.selectbox('Select Y-axis(numericall) column to plot',cols)
        hueval=st.selectbox('Select a hue column(categorical)',cols)
        if plottype=='stripplot':
            if x!='none' and hueval!='none':
                st.write(sns.stripplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            elif x!='none' and hueval=='none':
                st.write(sns.stripplot(df[x],df[y]))
                st.pyplot()
        else:
            if x!='none' and hueval!='none':
                st.write(sns.swarmplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            elif x!='none' and hueval=='none':
                st.write(sns.swarmplot(df[x],df[y]))
                st.pyplot()
    #categorical distributions
    if st.checkbox('Categorical Distributions'):
        cols=df.columns.tolist()
        cols.insert(0,'none')
        plottype=st.selectbox('Select plot type',['box','bar','violin','count','point','factor'])
        x=st.selectbox('Select X-axis(catrogrical) column to plot',cols)
        y=st.selectbox('Select Y-axis(numerical) column to plot',cols)
        hueval=st.selectbox('Select a hue column',cols)
        #box plot
        if plottype=='box':
            if hueval!='none':
                st.write(sns.boxplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            else:
                st.write(sns.boxplot(df[x],df[y]))
                st.pyplot()
        #bar plot
        if plottype=='bar':
            if hueval!='none':
                st.write(sns.barplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            else:
                st.write(sns.barplot(df[x],df[y]))
                st.pyplot()
        
        #violin plot
        if plottype=='violin':
            if hueval!='none':
                st.write(sns.violinplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            else:
                st.write(sns.violinplot(df[x],df[y]))
                st.pyplot()
        #count plot
        if plottype=='count':
            st.text('Plotting countplot for selected X column')
            if hueval!='none':
                st.write(sns.countplot(df[x],hue=df[hueval]))
                st.pyplot()
            else:
                st.write(sns.countplot(df[x]))
                st.pyplot()
        
        #point plot
        if plottype=='point':
            if hueval!='none':
                st.write(sns.pointplot(df[x],df[y],hue=df[hueval]))
                st.pyplot()
            else:
                st.write(sns.pointplot(df[x],df[y]))
                st.pyplot()

        #factor plot
        if plottype=='factor':
            typekind=st.selectbox('Select plottype for factor for plot',['point','bar','box','violin','strip','swarm'])
            colm=st.selectbox('Select column(col) parameter',cols)
            rows=st.selectbox('Select(only if col is selected) column(row) parameter',cols)
            if hueval!='none':
                if colm!='none' and rows!='none':
                    st.write(sns.factorplot(x=x,y=y,hue=hueval,col=colm,row=rows,data=df,kind=typekind))
                    st.pyplot()
                elif colm!='none' and rows=='none':
                    st.write(sns.factorplot(x=x,y=y,hue=hueval,col=colm,data=df,kind=typekind))
                    st.pyplot()
            else:
                if colm!='none' and rows!='none':
                    st.write(sns.factorplot(x=x,y=y,col=colm,row=rows,data=df,kind=typekind))
                    st.pyplot()
                elif colm!='none' and rows=='none':
                    st.write(sns.factorplot(x=x,y=y,col=colm,data=df,kind=typekind))
                    st.pyplot()


    #linear relationship
    if st.checkbox('Linear Relationship'):
        cols=df.columns.tolist()
        cols.insert(0,'none')
        xval=st.selectbox('Select X-axis',cols)
        yval=st.selectbox('Select Y-axis',cols)
        hueval=st.selectbox('Select hue column',cols)
        if hueval!='none':
            st.write(sns.lmplot(x=xval,y=yval,hue=hueval,data=df))
            st.pyplot()
        else:
            st.write(sns.lmplot(x=xval,y=yval,data=df))
            st.pyplot()

###########

    st.subheader('Customizable plots')
    cols=df.columns.tolist()
    plottype=st.selectbox('Select plot type',['bar','hist','box','area','line','kde'])
    selectedcollist=st.multiselect('Select columns to plot',cols)

    if st.button('Generate plot'):
        st.success('Generating customizable {} plot for {}'.format(plottype,selectedcollist))
        #plot using streamlit
        if plottype=='area' :
            cusdata=df[selectedcollist]
            st.area_chart(cusdata)
        elif plottype=='bar' :
            cusdata=df[selectedcollist]
            st.bar_chart(cusdata)
        elif plottype=='line' :
            cusdata=df[selectedcollist]
            st.line_chart(cusdata)
        elif plottype :
            cusplot=df[selectedcollist].plot(kind=plottype)
            st.write(cusplot)
            st.pyplot()

    if st.button('See who created this!'):
        st.subheader('Project developed by:')
        st.info('Name: K Vikas Reddy')
        st.info('College: SASTRA Deemed to be University')
        st.info('Gmail:  [email protected]')

    if st.button('Thanks'):
        st.balloons()
    st.text('')
    st.text('')
    st.warning('Please report bugs if any and suggest any new features')
    if st.checkbox('About this project'):
        st.write('Exploratory Data Analysis is the first step every Data Scientist does in every project.') 
        st.write('I saw many people groan to perform EDA. It is because of the same scripts written over and over for every project.')
        st.write('If you also felt the same, then this project is for you. This project helps you perform EDA with ease.')
        st.write('You dont need to write any scripts. EDA can be performed with just few clicks. It is also very time efficient.')
        st.write('As Data Science is becoming very popular, Data Science aspirants should also become smart and productive.')
        st.write('Hope this project helps you to some extent.')
Beispiel #27
0
def classify():
    image = None

    #----------------- Uploading User Tree image from URL or File -------------------

    st.title(
        'Please provide an image - will be identified as pepper tree, willow tree, or neither.'
    )

    #----------------- Side Bar Options for User Image ------------------------------
    st.title("Upload Options")
    input_method = st.radio("Options", ('File Upload', 'URL'))

    flag = 0
    if input_method == 'File Upload':
        user_upload_image = st.file_uploader("Upload a picture of Tree",
                                             type=['png', 'jpeg', 'jpg'])
        if user_upload_image is not None:
            file_details = {
                "FileName": user_upload_image.name,
                "FileType": user_upload_image.type,
                "FileSize": user_upload_image.size
            }
            # st.write(file_details)
            flag = 1
        if flag == 1:
            image_source = user_upload_image.name
            image = Image.open(user_upload_image)
            st.image(
                image,
                caption=user_upload_image.name + '  ' +
                user_upload_image.type + '  ' + str(user_upload_image.size) +
                ' bytes',
                width=300,
                use_column_width=True,
            )

# Image from URL
    if input_method == 'URL':
        image_url = st.text_area("Enter the complete Url",
                                 key="user_url_choice")
        image_url_status = st.button('Upload')

        if image_url_status:
            image_source = image_url
            image = Image.open(urllib.request.urlopen(image_url))
            st.image(
                image,
                caption=str(image),
                width=300,
                use_column_width=True,
            )
        else:
            st.warning('click on upload')

    #----------------------  Choosing Classification Method ---------------------------
    st.title('Choose the model for Analysis')
    model_selected = st.radio("Options", ['Pre Trained Model'])

    # model_selected = st.sidebar.radio(
    # 	"Options",
    # 	('Pre Trained Model', 'CNN Model', 'FFN Model', 'Random Forest', 'Logistic Regression', 'Ensemble'),0)

    if model_selected == 'Pre Trained Model':
        model_selected2 = st.selectbox("Choose the Pretrained Model",
                                       ['VGG16'])

        # model_selected2 = st.sidebar.selectbox("Choose the Pretrained Model",
        # 	['VGG16','PTM2','PTM2','PTM2','PTM2','PTM2','PTM2','PTM2'])

    if model_selected2 == 'VGG16' and image != None:
        # note that the predict function returns top_probabilities, top_classes
        model = load_checkpoint(
            '/home/kate/data_and_models/ai_models/vgg16-tree-3class-model.pth')
        probs, classes = predict(image, model)

        st.title('Tree Classification Results')

        with open('tree_to_name.json', 'r') as f:
            tree_to_name = json.load(f)
        tree_names = [tree_to_name[i] for i in classes]
        chart_data = pd.DataFrame(data=[probs], columns=tree_names)

        # st.write("chart_data type ", type(chart_data))

        if (chart_data["willow tree"][0]) > 0.5:
            tree_detected = "Willow Tree"
        elif (chart_data["pepper tree"][0]) > 0.5:
            tree_detected = "Pepper Tree"
        else:
            tree_detected = "Not a Pepper Tree or a Willow Tree"

        st.write('The image is: ', tree_detected)
        st.write('Percentage confidence in the image identification ',
                 chart_data)

        st.bar_chart(chart_data)
Beispiel #28
0
                                db[key]['distance'] / 100)
        else:
            totElevGain = round(db[key]['total_elevation_gain'])
        st.write('Total elevation gain: ', totElevGain, ' m = ',
                 round(totElevGain * 3.281), 'ft')

        st.write('Average grade: ', db[key]['average_grade'], '%')

        # Display segment on map
        st.plotly_chart(segmentMap(db, key), use_container_width=True)

        # Display time to finish plot
        if (db[key]['total_elevation_gain'] == 0):
            G = db[key]['average_grade'] / 100
            st.warning(
                'The total elevation gain for this segment is missing in Strava\'s database so it has been calculated using the provided average grade. The resulting power calculation will be less accurate than for segments where the total elevation gain is a measured quantity.'
            )
        else:
            # This should be more accurate
            G = db[key]['total_elevation_gain'] / db[key]['distance']
        st.plotly_chart(timeToFinishPlot(w=w_total, G=G,
                                         d=db[key]['distance']),
                        use_container_width=True)

    ### Elevation profile
    # https://docs.mapbox.com/api/maps/#tilequery
    # https://docs.mapbox.com/help/tutorials/find-elevations-with-tilequery-api/
    # "Because the elevation data you want is included in the contour layer, you will need to parse the returned GeoJSON to isolate the features from the contour layer and find the highest elevation value."
    # mapbox API GET:/v4/{tileset_id}/tilequery/{lon},{lat}.json
    # payload = {'layers': 'contour', 'radius': '0', 'limit': '50', 'access_token': mapbox_token}
    # tileset_id = 'mapbox.mapbox-terrain-v2'
Beispiel #29
0
def main():
    session = SessionState.get(run_id=0)

    if st.sidebar.button("Reset"):
        session.run_id += 1

    # Init params
    random_noise = st.sidebar.checkbox('init_with_random_noise', value=False, key=session.run_id)
    if random_noise:
        rng_noise_amount_plh = st.sidebar.empty()
        rng_seed_plh = st.sidebar.empty()
    draw_square = st.sidebar.checkbox('init_with_square', value=True, key=session.run_id)
    if draw_square:
        square_ratio_plh = st.sidebar.empty()
    if (not random_noise) and (not draw_square):
        st.warning('Please initialize with random noise or square')
    iters = st.sidebar.slider('iterations', min_value=10, max_value=10000, step=10, value=6000, key=session.run_id)
    f = st.sidebar.slider('feed_rate', min_value=0.03, max_value=0.1, step=0.0001, value=0.055, key=session.run_id)  # 0.055
    k = st.sidebar.slider('kill_rate', min_value=0.03, max_value=0.1, step=0.0001, value=0.062, key=session.run_id)  # 0.062
    d_A = st.sidebar.slider('d_A', min_value=0.5, max_value=1.3, step=0.1, value=1.0, key=session.run_id)
    d_B = st.sidebar.slider('d_B', min_value=0.3, max_value=1.0, step=0.1, value=0.5, key=session.run_id)
    img_size = st.sidebar.slider('img_size', min_value=10, max_value=1000, step=1, value=200, key=session.run_id)
    cmap = st.sidebar.selectbox('plot_colormap', ['binary', 'PiYG', 'PRGn', 'BrBG', 'PuOr', 'RdGy', 'RdBu',
            'RdYlBu', 'RdYlGn', 'Spectral', 'coolwarm', 'bwr', 'seismic'], index=0,  key=session.run_id)
    dt = 1.0

    h = img_size
    w = img_size
    size = (h, w)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    kernel = torch.tensor([
        [.05, .2, .05],
        [ .2, -1, .2 ],
        [.05, .2, .05]
    ], device=device)

    A = torch.ones(size, device=device)
    B = torch.zeros(size, device=device)

    # Add randomness to the pattern
    if random_noise:
        rng_seed = rng_seed_plh.slider('rng_seed', min_value=0, max_value=1000, step=10, value=40, key=session.run_id)
        rng_noise_amount = rng_noise_amount_plh.slider('rng_noise_amount', min_value=0.0, max_value=0.5, step=0.005, value=0.005, key=session.run_id)
        np.random.seed(rng_seed)

        B_ones_frac = rng_noise_amount  # fraction of B == 1
        B_ones_n = int(h + w * B_ones_frac)
        mask = (np.random.randint(0, h, B_ones_n), np.random.randint(0, w, B_ones_n))
        B[mask] = 1.0

    # Add a square in the center of the image
    if draw_square:
        square_ratio = square_ratio_plh.slider('square_ratio', min_value=0.05, max_value=1.0, step=0.05, value=0.1, key=session.run_id)
        h2 = h // 2
        w2 = w // 2
        _h = max(1, int(h * square_ratio))
        _w = max(1, int(w * square_ratio))
        B[h2-_h:h2+_h, w2-_w:w2+_w] = 1
        B[h2-_h + 1:h2+_h - 1, w2-_w + 1:w2+_w - 1] = 0  # fill the inner area with 0

    t0 = time.perf_counter()
    fig1 = plt.figure(figsize=(4,4))
    gs = fig1.add_gridspec(2, 5, wspace=0, hspace=0, top=0.5)

    # Simulate pattern
    with st.spinner('Processing...'):
        A, B, interim_b = simulate_torch(A, B, kernel, d_A, d_B, f, k, dt, iters)

    # Visualize interim results
    for i, b in enumerate(interim_b):
        plt.subplot(gs[i])
        plt.axis('off')
        plt.imshow(b, cmap=cmap)


    # Visualize the final result heatmap
    fig2 = plt.figure()
    plt.axis('off')
    plt.imshow(B, cmap=cmap)
    # plt.colorbar()
    st.pyplot(fig2, clear_figure=True)

    # Visualize interm results
    st.pyplot(fig1, clear_figure=True)

    st.write(f'Elapsed: {time.perf_counter() - t0:.2f} sec')
    st.write(f'Current parameters:', pd.DataFrame(dict(iters=iters, d_A=d_A, d_B=d_B, feed=f, kill=k, dt=dt), index=[0]))
concavity_worst = right_column.number_input('concavity_worst')
symmentry = right_column.number_input('symmetry')
concavity_mean = right_column.number_input('concavity_mean')
concave_points_mean = right_column.number_input('concave_points_mean')
perimeter_worse = right_column.number_input('perimeter_worse')

compactness_worst = left_column.number_input('compactness_worst')
concave_points = left_column.number_input('concave_point')
compactness_mean = left_column.number_input('compactness_mean')
texture = left_column.number_input('texture')
area = left_column.number_input('area', step=10, min_value=20, max_value=300)

features_list = [
    concavity_worst, symmentry, concavity_mean, concave_points_mean,
    perimeter_worse, compactness_worst, concave_points, compactness_mean,
    texture, area
]

model_name = "breast_cancer_ML_model.pkl"
model = pickle.load(open(model_name, 'rb'))

prediction = int(model.predict([features_list]))
prediction_proba = model.predict_proba([features_list])[:, 0]
if prediction == 0: prediction = 'Benign'
else: prediction = "Malignant"
diagnosis = st.button('Get Diagnosis')
if diagnosis:
    st.info(prediction)
    st.info(prediction_proba)
    st.warning(prediction)
    st.success(prediction)