def GNB():
    st.title("Модель прогнозирования - Naive Bayes")
    if st.checkbox("Показать код"):
        st.code("""clf2 = GaussianNB().fit(X_train, y_train)
    y_pred2 = clf2.predict(X_test)
    acc_nb=roc_auc_score(y_test, y_pred2)
    st.text(acc_nb)""")

    if st.checkbox("Использовать несбалансированные данные"):

        clf2 = GaussianNB().fit(X_train, y_train)
        y_pred2 = clf2.predict(X_test)

        acc_nb = roc_auc_score(y_test, y_pred2)
        st.text(acc_nb)
    else:
        clf2 = GaussianNB().fit(X_train_res, y_train_res)
        y_pred2 = clf2.predict(X_test0)
        acc_nb = roc_auc_score(y_test0, y_pred2)
        st.text(acc_nb)
Exemplo n.º 2
0
def show_progress() -> None:
    st.header("Show progress of longer operations")

    st.write("Source code of time consuming task:")
    st.code(inspect.getsource(do_stuff))

    st.subheader("Spinner")
    with st.echo():
        if st.button("Start Spinner"):
            with st.spinner("Waiting for it to be done"):
                do_stuff()

    st.markdown('-' * 6)

    st.subheader("Progress bar")

    with st.echo():
        my_bar = st.progress(0)
        if st.button("Start Progress"):
            do_stuff(my_bar.progress)
Exemplo n.º 3
0
def main():
    readme_text = st.markdown(get_file_content_as_string("readme.md"))
    st.sidebar.title("What to do")

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

    unzipData("dicom-jpg.zip")
    app_mode = st.sidebar.selectbox(
        "Choose the app mode",
        ["Show instructions", "Run the app", "Show the source code"])
    if app_mode == "Show instructions":
        st.sidebar.success('To continue select "Run the app".')
    elif app_mode == "Run the app":
        readme_text.empty()
        run_the_app()
    elif app_mode == "Show the source code":
        readme_text.empty()
        st.code(get_file_content_as_string("pneumo_app.py"))
Exemplo n.º 4
0
def import_file(name):
    st.write("run file name: " + str(name))
    file = st.file_uploader("Upload file", type=FILE_TYPES,key=name)
    show_file = st.empty()
    if not file:
        show_file.info("Please upload a file of type: " + ", ".join(FILE_TYPES))
        return

    file_type = get_file_type(file)
    if file_type == FileType.IMAGE:
        show_file.image(file)
    elif file_type == FileType.PYTHON:
        st.code(file.getvalue())
    else:
        data = pd.read_csv(file)
        st.dataframe(data.head(5))
        st.markdown('*** số lượng dòng của file *** ')
        st.dataframe(data.count())
    file.close()
    return data
Exemplo n.º 5
0
def main():
    # Render the readme as markdown using st.markdown.
    readme_text = st.markdown(get_file_content_as_string("instructions.md"))

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

    # Once we have the dependencies, add a selector for the app mode on the sidebar.
    st.sidebar.title("What to do")
    app_mode = st.sidebar.selectbox("Choose the app mode",
        ["Show instructions", "Run the app", "Show the source code"])
    if app_mode == "Show instructions":
        st.sidebar.success('To continue select "Run the app".')
    elif app_mode == "Show the source code":
        readme_text.empty()
        st.code(get_file_content_as_string("streamlit_app.py"))
    elif app_mode == "Run the app":
        readme_text.empty()
        run_the_app()
def st_get_apt_packages() -> str:
    st.markdown("---")
    st.header("🐧 Apt Packages")
    st.markdown(
        "List all installed **`apt`** packages of the runtime - acquired with **`dpkg-query --show --showformat`**"
    )
    exitcode, output = get_subprocess_apt_list()
    stringblock = str()
    if exitcode:
        st.warning('FAILED: dpkg-query --show --showformat')
        st.code(output, language='logging')
    else:
        headers = ['Package', 'Version', 'Description']
        cells = get_apt_package_list(output)
        st.markdown(tabulate_table_factory(headers, cells, showindex=True))
        stringblock = tabulate_table_factory(headers,
                                             cells,
                                             showindex=True,
                                             tablefmt="fancy_grid")
    return stringblock
Exemplo n.º 7
0
def recommendation_engine():
    caching.clear_cache()
    st.write('')
    st.header('Recommendation Engine')
    st.write('-----------------------------------------------------------------------') 
    st.write('')

    st.subheader("Tracks Most Similar to 'Pwede Ba' (Pinoy Indie)")
    if st.checkbox('Show code', value=False, key="1"):
        st.code("""
        #get top 10 nearest to seed_track_data
        recommendation_df = tracks_df[tracks_df['predicted_genre']=='pinoy indie']\
                                            [tracks_df['track_id']!=seed_track_data['track_id']]\
                                            .sort_values('cosine_dist')[:10]
        recommendation_df[['track_name','artist_name','cosine_dist','predicted_genre']+feature_cols]
        recommendation_df.to_csv('../data/recommended_pinoy_indie.csv')
        """, language="python")
    df_indie = pd.read_csv('data/recommended_pinoy_indie.csv')
    st.write(df_indie.set_index('track_id').drop(columns=['Unnamed: 0']))
    st.write('')
    st.subheader('Top Artists with a Similar "Pinoy Indie" Sound:')
    st.write('Markki Stroem, Brisom, Gabe Bondoc, TALA, Jensen & The Flips')
    st.write('-----------------------------------------------------------------------') 
    st.write('')
    

    st.subheader("Tracks Most Similar to 'Pwede Ba' (Pinoy Rock)")
    if st.checkbox('Show code', value=False, key="2"):
        st.code("""
        #get top 10 nearest to seed_track_data
        recommendation_df = tracks_df[tracks_df['predicted_genre']=='pinoy rock']\
                                            [tracks_df['track_id']!=seed_track_data['track_id']]\
                                            .sort_values('cosine_dist')[:10]
        recommendation_df[['track_name','artist_name','cosine_dist','predicted_genre']+feature_cols]
        recommendation_df.to_csv('../data/recommended_pinoy_indie.csv')
        """, language="python")
    df_indie = pd.read_csv('data/recommended_pinoy_rock.csv')
    st.write(df_indie.set_index('track_id').drop(columns=['Unnamed: 0']))
    st.write('')
    st.subheader('Top Artists with a Similar "Pinoy Rock" Sound:')
    st.write('6cyclemind, Bamboo, Shamrock, Cinderell, Fred Engay')
Exemplo n.º 8
0
def main():
    """Run this function to display the Streamlit app"""
    #st.info(__doc__)
    st.markdown(STYLE, unsafe_allow_html=True)

    file = st.file_uploader("Upload file", type=FILE_TYPES)
    show_file = st.empty()
    if not file:
        show_file.info("Please install the files that have these extensions: " + ", ".join(FILE_TYPES))
        return

    file_type = get_file_type(file)
    if file_type == FileType.IMAGE:
        show_file.image(file)
    elif file_type == FileType.PYTHON:
        st.code(file.getvalue())
    else:
        if file_type ==  FileType.CSV:
            try:
                data = pd.read_csv(file)
            except:
                data = pd.read_csv(file,error_bad_lines = False)


            data = translate_data(data)
            return data

            

        else: 
            try:
                data = pd.read_excel(file)
            except:
                try:
                    data = pd.read_excel(file,index_col=None, header=None)
                except:
                    data = pd.read_html(file)

          
            data = translate_data(data)
            return data
Exemplo n.º 9
0
def main():
    with open(
            os.path.join(
                os.path.abspath(os.path.join(__file__, *3 * [os.path.pardir])),
                "README.md"), "r") as _f:
        readme_text = st.markdown(_f.read())

    st.sidebar.title("What to visualize?")
    dataset_path = st.sidebar.text_input("Enter the dataset root directory",
                                         "/mnt/fsx/dgp/")
    dataset_split = "train"

    dataset_json_list = glob.glob(os.path.join(dataset_path, "*.json"))
    if dataset_json_list:
        dataset_version = st.sidebar.selectbox(
            "Choose a version (dataset.json)",
            [os.path.basename(_x) for _x in dataset_json_list])
        dataset_path = os.path.join(dataset_path, dataset_version)
        splits = get_dataset_split(dataset_path)
        dataset_split = st.sidebar.selectbox("Choose a dataset split to read",
                                             splits)

    app_mode = st.sidebar.selectbox("Choose the mode", [
        "Show instructions", "Show the visualizer source code",
        "Run Parallel Domain Visualizer", "Run Synchronized Visualizer"
    ])

    # TODO: automatically detect type of the dataset and display a list of available visualization methods.
    if app_mode == "Show instructions":
        st.sidebar.success(
            'To continue enter the "dataset path" and suitable "visualizer"')
    elif app_mode == "Show the visualizer source code":
        readme_text.empty()
        with open(os.path.abspath(__file__), "r") as _f:
            st.code(_f.read())
    elif app_mode == "Run Synchronized Visualizer":
        readme_text.empty()
        run_synchronized_visualizer(dataset_path, dataset_split)
    elif app_mode == "Run Parallel Domain Visualizer":
        readme_text.empty()
        run_parallel_domain_visualizer(dataset_path, dataset_split)
Exemplo n.º 10
0
def parser_LL1():
    """
    LL(1) Subsection
    """
    st.title('Parser LL(1)')

    result = gp.load_grammar()
    if result[0]:
        st.error('No se ha definido una gramatica\
            o la gramatica definida no es correcta')
        return

    G = result[1]

    options = ['Tabla de Parsing', 'Parsear Cadena']

    M = build_parsing_table(G)

    if not isLL1(G, M):
        st.error('La gramática definida no es LL(1)')
        options.remove('Parsear Cadena')

        # Get conflicts
        pair = get_ll1_conflict(M)
        c1, c2 = M[pair[0], pair[1]][:2]
        st.subheader('Producciones de conflicto:')
        st.code(f'{c1}\n{c2}')

        s1, s2 = generate_ll1_conflict_string(G, M, pair)
        st.subheader('Cadenas de conflicto')
        st.code(f'{s1}\n{s2}')

    selected = st.multiselect('', options)

    if options[0] in selected:
        st.title('Tabla LL(1)')
        frame = LL1_to_dataframe(G)
        st.write(frame)
    if len(options) > 1 and options[1] in selected:
        parser = metodo_predictivo_no_recursivo(G)
        render_parser(G, 'método predictivo no recursivo', parser, is_ll1=True)
Exemplo n.º 11
0
def testAPI(show_code):
    import streamlit as st
    import inspect, textwrap
    itemDict = OrderedDict([
        ("魔法命令", (testMgic, "魔法命令(Magic Commands)",
                  """**Magic Commands 只能工作在Python3环境**  
            Steamlit会自动将每行的`变量`或`文本`自动使用`st.write()`方式显示到程序中,其中文本支持MarkDown。同时它会自动忽略文件、函数开头的说明文本."""
                  )),
        ("文本",
         (testText, "文本(text)",
          """`st.title()`可以设置APP的标题,此外还有两个标题级别可以使用`st.header`和`st.subheader`.  
            其他文本函数:  
            `st.write`: 被称为瑞士军刀,可以自动显示多种数据类型,文本,变量,甚至图表等。`st.text()`: 纯文本  
            `st.markdown()`: Markdown(Github-flavored Markdow)  
            `st.code()`, `st.latex()`...""")),
        ("数据", (testDat, "数据(data)", "格式化显示原始数据表格等信息")),
        ("图表",
         (testChart, "图表(chart)",
          """Streamlit支持Matplotlib、交互式图表[Vega Lite](https://vega.github.io/vega-lite/) (2D charts)和[deck.gl](https://github.com/uber/deck.gl) (maps and 3D charts)等图表库,同时Streamlit有一些“原生”绘图方式"""
          )), ("多媒体", (testMedia, "多媒体(Media)", "嵌入图片、音频、视频文件")),
        ("控件", (testWidget, "交互控件(interactive widgets)", None)),
        ("边框", (testSide, "边框(Sidebar)", "左边就是sidebar,里面嵌套了两个selectbox")),
        ("代码", (testCode, "代码(code)", "`st.echo()`用于显示代码")),
        ("状态及进度", (testStatus, "进度条及状态提示信息", None)),
        ("占位符、帮助和选项", (testPlh, "占位符、帮助和选项(Placeholders, help, and options)",
                       None)),
        ("追加数据", (testMdat, "追加数据(Mutate data)",
                  "Streamlit可以修改已有元素(chart、table、DataFrame)的数据")),
        ("优化性能", (testCache, "性能优化(Caching)", None))
    ])
    testType = st.sidebar.selectbox("测试内容", list(itemDict.keys()))
    testFun = itemDict[testType][0]
    st.subheader(itemDict[testType][1])
    if itemDict[testType][2] != None:
        st.markdown(itemDict[testType][2])
    testFun()
    if show_code:
        st.write("## 代码")
        source_code, _ = inspect.getsourcelines(testFun)
        fsource = textwrap.dedent("".join(source_code[1:]))
        st.code(fsource)
Exemplo n.º 12
0
def cs_body(report, project, framework, nn_type):

    pdf_url = 'https://github.com/r0han99/Deep-Learning-Anatomy/raw/main/' + report[
        'ipynb'][2:]

    cols = list(report.keys())[3:-3]
    # report.fillna('None',inplace=True)
    st.markdown(
        "<h3 style='font-family: sora; font-weight:bold; font-size:25px;'>Project Artefacts</h3>",
        unsafe_allow_html=True)
    st.markdown('***')

    with open('./assets/prompt-list.txt', 'rb') as f:
        data = f.read()
    d = pickle.loads(data)

    # st.write(report.keys())
    # st.write(d)

    for i, col in enumerate(cols):
        st.markdown(d[i])
        st.code(report[col])

    st.markdown('***')

    st.markdown('***Synopsis: ***')
    st.markdown('_' + report['summary'] + '_')

    st.markdown('***')

    expander = st.beta_expander('Source-Code')
    expander.markdown('_Ipynb_ translated into _PDF_ using _LaTeX_')
    expander.markdown(
        '''[<img src='data:image/png;base64,{}' class='img-fluid' width=64 height=64>]({}) <small style='color:blue;'><i>Download</i></small>'''
        .format(img_to_bytes('./pngs/ipynb.png'), pdf_url),
        unsafe_allow_html=True)
    expander.markdown('***')
    if expander.checkbox('Note'):
        expander.markdown(
            '_"This link is a dynamically generated link, if this is a non-existent url, it is possible to traceback a 404 error, please visit the main repository for more info."_'
        )
Exemplo n.º 13
0
def main():
    readme_text = st.markdown(get_file_content_as_string("instructions.md"))

    st.sidebar.title("What do you want to do ?")
    modes = st.sidebar.selectbox("Choose the app mode", [
        "Show instructions", "Run the app", "Show the source code",
        "See train data"
    ])

    if modes == "Show instructions":
        st.sidebar.success('To continue select "Run the app".')
    elif modes == "Show the source code":
        readme_text.empty()
        st.code(get_file_content_as_string("main.py"))
    elif modes == "See train data":
        readme_text.empty()
        data = show_data()
        st.write(data)
    elif modes == "Run the app":
        readme_text.empty()
        run()
Exemplo n.º 14
0
def source_code():
    soruce_code = get_file_content_as_string()
    code_display = st.code(soruce_code)
    link = st.markdown(
        "[View on GitHub](https://github.com/alanwong626/market-monitoring)",
        unsafe_allow_html=True)
    st.write(
        "__Disclaimer__: Data collected from Yahoo Finance and Investing.com. This dashboard is for demonstration purposes only."
    )
    st.write("__Contact__: [email protected]")

    return code_display, link
Exemplo n.º 15
0
    def print(self, message: str, mode: str = ''):
        if mode == 'code':
            st.code(message)

        elif mode == 'success':
            st.success(message)

        elif mode == 'title':
            st.title(message)

        elif mode == 'header':
            st.header(message)

        elif mode == 'info':
            st.info(message)

        elif mode == 'warning':
            st.warning(message)

        else:
            st.write(message)
Exemplo n.º 16
0
def run():

    st.write(
        'ЁЯЪз Page configuration is a beta feature and should evolve soon ЁЯЪз'
    )

    st.write(
        'Page configuration allows to configure the favicon and title of the page in the browser tab, as well as the initial state of the sidebar and the general layout of the page'
    )

    st.write(
        'тЪая╕П `beta_set_page_config` should be the first streamlit statement of the app тЪая╕П'
    )

    st.code('''
        st.beta_set_page_config(
            page_title="Quick reference", # => Quick reference - Streamlit
            page_icon="ЁЯРН",
            layout="centered", # wide
            initial_sidebar_state="auto") # collapsed
        ''')
Exemplo n.º 17
0
    def test_st_code(self):
        """Test st.code."""
        dg = st.code('print(\'My string = %d\' % my_value)', language='python')
        expected = textwrap.dedent('''
            ```python
            print('My string = %d' % my_value)
            ```
        ''')

        el = self.get_delta_from_queue().new_element
        self.assertEqual(el.text.body, expected.strip())
        self.assertEqual(el.text.format, Text.MARKDOWN)
def KNN(neig, leaf_s, P):
    st.title("Модель прогнозирования - KNN")
    if st.checkbox("Показать код"):
        st.code(
            """knn = KNeighborsClassifier(n_neighbors=neig, leaf_size=leaf_s, p=P)
    clf = knn.fit(X_train, y_train)
    y_pred = clf.predict(X_test)
    acc_knb_model=roc_auc_score(y_test, y_pred)
    st.text(acc_knb_model)""")
    if st.checkbox("Использовать несбалансированные данные"):
        knn = KNeighborsClassifier(n_neighbors=neig, leaf_size=leaf_s, p=P)
        clf = knn.fit(X_train, y_train)
        y_pred = clf.predict(X_test)
        acc_knb_model = roc_auc_score(y_test, y_pred)
        st.text(acc_knb_model)
    else:
        knn = KNeighborsClassifier(n_neighbors=neig, leaf_size=leaf_s, p=P)
        clf = knn.fit(X_train_res, y_train_res)
        y_pred = clf.predict(X_test0)
        acc_knb_model = roc_auc_score(y_test0, y_pred)
        st.text(acc_knb_model)
def LR():
    st.title("Модель прогнозирования - LinearRegression")
    if st.checkbox("Показать код"):
        st.code("""regr = linear_model.LinearRegression()
    regr.fit(X_train,y_train)
    regr_pred=regr.predict(X_test)
    acc_regr=round(regr.score(X_train,y_train),10)
    st.text(acc_regr)""")

    if st.checkbox("Использовать несбалансированные данные"):
        regr = linear_model.LinearRegression()
        regr.fit(X_train, y_train)
        regr_pred = regr.predict(X_test)
        acc_log_reg = roc_auc_score(y_test, regr_pred)
        st.text(acc_log_reg)
    else:
        regr = linear_model.LinearRegression()
        regr.fit(X_train_res, y_train_res)
        regr_pred = regr.predict(X_test0)
        acc_log_reg = roc_auc_score(y_test0, regr_pred)
        st.text(acc_log_reg)
Exemplo n.º 20
0
def main():	
	st.title('Arabic Sentiment Analysis: Service Reviews') # title
	st.subheader("By Abed Khooli - Twitter: @akhooli, LinkedIn: /in/akhooli")
	display_image('sent_pn.png')	
	# Render the readme as markdown using st.markdown.
	readme_text = st.markdown(get_file_content_as_string("README.md"))

	# Once we have the dependencies, add a selector for the app mode on the sidebar.
	st.sidebar.title("Main Menu")
	app_mode = st.sidebar.selectbox("Select an option",
				["Show background info", "Run the app", "Show the source code"])
	if app_mode == "Show background info":
		st.sidebar.success('To run this app select "Run the app" from the drop down list.')
	elif app_mode == "Show the source code":
		readme_text.empty()
		st.code(get_file_content_as_string("app.py"))
	elif app_mode == "Run the app":
		readme_text.empty()
		st.sidebar.info("Note: the app ignores non-Arabic text as well as diacritics. You may try (copy/paste) one of the random (real) reviews displayed below or enter your own.")
		st.sidebar.write(f"Random text (one of ten of real reviews):\n {RNADOM_REVIEW}")
		run_the_app()
Exemplo n.º 21
0
Arquivo: app.py Projeto: kuss/examples
def main(args):
    st.title('Inference Detectron2')

    st.sidebar.title("What to do")
    app_mode = st.sidebar.selectbox(
        "Choose the app mode", ["Instruction", "Inference", "Source code"])
    if app_mode == "Instruction":
        st.write('## A simple app to inference Detectron2\n'
                 '### To inference with trained model:\n'
                 '1. Click **Inference** app mode on the side bar\n'
                 '2. Select the image\n'
                 '3. Choose the threshold on the slider\n'
                 '4. Click the **Inference** button\n'
                 '5. The inference result will show up\n'
                 '### To show the source code:\n'
                 '1. Click **Source code** app mode on the side bar\n'
                 '2. The source code will show up')
    elif app_mode == "Inference":
        inference(args.test_path, args.model_path)
    elif app_mode == "Source code":
        st.code(read_file(args.app_path))
Exemplo n.º 22
0
def page_2__view_run_lists(state):
    import streamlit as st

    st.markdown("# Run Lists 🎈")
    # 1: Iterate through all the requests in the state.
    for i, r in enumerate(state.requests):
        i = str(i)
        # 2: Display information such as request, logs, work state, model score.
        work = state._state["structures"]["ws"]["works"][f"w_{i}"]
        with st.expander(f"Expand to view Run {i}", expanded=False):
            if st.checkbox("Expand to view your configuration", key=i):
                st.json(r)
            if st.checkbox("Expand to view logs", key=i):
                st.code(body=work["vars"]["logs"])
            if st.checkbox("Expand to view your work state", key=i):
                work["vars"].pop("logs")
                st.json(work)
            best_model_score = r.get("best_model_score", None)
            if best_model_score:
                if st.checkbox("Expand to view your run performance", key=i):
                    st.json({"best_model_score": best_model_score, "best_model_path": r.get("best_model_path")})
Exemplo n.º 23
0
def samples_display(text):
    if nb_samples < 4:
        cols_f = st.beta_columns(3)
        for i in range(nb_samples):
            with cols_f[i].beta_expander(f"Sample {i + 1} "):
                st.code(text)
    else:
        cols_f = st.beta_columns(3)
        for i in range(3):
            with cols_f[i].beta_expander(f"Sample {i + 1} "):
                st.code(text)
        st.subheader(
            ""
        )
        st.subheader(
            ""
        )
        st.subheader(
            ""
        )
        st.subheader(
            ""
        )
        cols_f = st.beta_columns(2)
        for i in range(3, nb_samples):
            with cols_f[i - 3].beta_expander(f"Sample {i + 1} "):
                st.code("Your Text will appear here ...")
Exemplo n.º 24
0
def rerun():
    st.write("""
        # Programatically rerun your app

        Thanks to a contribution from [SimonBiggs](https://github.com/SimonBiggs),
        you can now re-execute your script from the top to bottom. Please note,
        this is an
        [experimental feature](https://docs.streamlit.io/en/stable/api.html#experimental),
        and subject to change.

        Thanks again [SimonBiggs](https://github.com/SimonBiggs)!

        -----
        """)

    st.code("""
placeholder = st.empty()
stop = st.button("Stop rerunning")
if stop:
    st.stop()

for i in range(10):
    with placeholder:
        st.write(f"Getting ready to rerun in {10-i}")
        time.sleep(1)

st.experimental_rerun()
    """)

    placeholder = st.empty()
    stop = st.button("Stop rerunning")
    if stop:
        st.stop()

    for i in range(10):
        with placeholder:
            st.write(f"Getting ready to rerun in {10-i}")
            time.sleep(1)

    st.experimental_rerun()
Exemplo n.º 25
0
def write():
    """This method writes the Gallery index page which is used to navigate between gallery apps"""

    ast.shared.components.title_awesome("Gallery")
    apps = get_resources()
    authors = get_authors(apps)
    index_default_author = authors.index(
        ast.database.resources.DEFAULT_RESOURCE.author)
    author = st.selectbox("Select Author", authors, index=index_default_author)
    apps_by_author = get_resources_by_author(apps, author)
    if author == ast.database.resources.DEFAULT_RESOURCE.author:
        app_index = apps_by_author.index(
            ast.database.resources.DEFAULT_RESOURCE)
    else:
        app_index = 0
    run_app = st.selectbox("Select the App", apps_by_author, index=app_index)
    app_credits = st.empty()

    app_credits.markdown(
        f"""Resources: [Author]({run_app.author.url}), [App Code]({run_app.url})"""
    )
    st.sidebar.title("Gallery")
    show_source_code = st.sidebar.checkbox("Show Source Code", True)

    # Fetch the content
    python_code = get_file_content_as_string(run_app.url)

    # Run the child app
    if python_code is not None:
        try:
            with st.spinner(f"Loading {run_app.name} ..."):
                exec(python_code, globals())  # pylint: disable=exec-used
        except Exception as exception:  # pylint: disable=broad-except
            st.write("Error occurred when executing [{0}]".format(run_app))
            st.error(str(exception))
            logging.error(exception)

        if show_source_code:
            st.header("Source code")
            st.code(python_code)
Exemplo n.º 26
0
def edge():
    st.header(" Morphological Transformations of image")
    uploaded_file = st.file_uploader("Choose any jpg file to detect corner", type="jpg")
    if uploaded_file is not None:
        # Convert the file to an opencv image.
        file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
        opencv_image = cv2.imdecode(file_bytes, 1)
        
        if st.button('See Original Image'):
        
            st.image(opencv_image, use_column_width=True)
        # Now do something with the image! For example, let's display it:
        # st.image(opencv_image, channels="BGR")
        image = opencv_image
        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

        R = st.slider('R: Red', min_value=0, max_value=255)
        G = st.slider('G: Green', min_value=0, max_value=255)
        B = st.slider('B: Blue', min_value=0, max_value=255)

        blue_min = np.array([R, G, B])   
        blue_max = np.array([255, 255, 255])

        mask = cv2.inRange(hsv, blue_min, blue_max)
        res = cv2.bitwise_and(image, image, mask=mask)

        Laplacian = cv2.Laplacian(image, cv2.CV_8U)
        Sobelx = cv2.Sobel(image, cv2.CV_8U, 1, 0, ksize=3)
        Sobely = cv2.Sobel(image, cv2.CV_8U, 0, 1, ksize=3)

        st.image(image)
        st.code('a. orignal image')
        st.image( mask)
        st.code('b. mask image', )
        st.image(Laplacian)
        st.code('c. Laplacian image' )
        st.image( Sobelx)
        st.code('d. sobelX image' )
        st.image( Sobely)
        st.code('e. SobelY image' )
Exemplo n.º 27
0
def main():
    # Render the readme as markdown using st.markdown.
    session_state = SessionState._get_state()
    if session_state.page_number is None:
        session_state.page_number = 0
    if session_state.object_type is None:
        session_state.object_type = 0
    if session_state.label_col is None:
        session_state.label_col = [0.0, 0.0, 0.0]
    if session_state.part_disp is None:
        session_state.part_disp = False
    if session_state.bbox_disp is None:
        session_state.bbox_disp = False
    if session_state.graph is None:
        session_state.graph = False
    if session_state.set is None:
        session_state.set = 0

    st.write(
        '<style>div.row-widget.stRadio > div{flex-direction:row;}</style>',
        unsafe_allow_html=True)
    f = open(os.path.join(path, 'instructions.md'), "r")
    image_list = pd.read_csv(
        os.path.join(path, 'src', 'visualization', 'dataset.csv'))
    readme_text = st.markdown(f.read())

    # Once we have the dependencies, add a selector for the app mode on the sidebar.
    st.sidebar.title("What to do")
    app_mode = st.sidebar.selectbox(
        "Choose the app mode",
        ["Show instructions", "Run the app", "Show the source code"])
    if app_mode == "Show instructions":
        st.sidebar.success('To continue select "Run the app".')
    elif app_mode == "Show the source code":
        readme_text.empty()
        f = open(path + 'src/visualization/' + "graph_viz.py", "r")
        st.code(f.read())
    elif app_mode == "Run the app":
        readme_text.empty()
        run_the_app(session_state, image_list)
Exemplo n.º 28
0
def start_process():
    """Strt camera container

    :return:
    """

    cam_id = st.text_input(label='Camera ID')
    if cam_id:
        response = spawner_api.camera_info(session.api_key, cam_id)
        st.write("## Camera Info")
        st.json(response)

        st.write('## Select process stack')
        process_stack = []
        if st.checkbox(label='Entry/Exit'):
            process_stack.append('person_counter')

        if st.checkbox(label='Socail Distancing'):
            process_stack.append('social_distance')

        if st.checkbox(label='Config override'):
            # config = st.text_input(label='Enter configuration')
            st.write(
                "##### Configuration to override default, *follow this format*"
            )
            st.write(
                ''' > `{ "nms_threshold": 0.5, "confidence_thresh": 0.4}` ''')

        st.write("## Current Selection")
        st.write(process_stack)
        if st.button("Start Process"):
            process_stack = '#'.join(process_stack)
            response = spawner_api.container_start(session.api_key,
                                                   cam_id,
                                                   process_stack,
                                                   stable=True)
            st.code(response)

    else:
        st.error('Please enter camera-id')
Exemplo n.º 29
0
def show_file(label: st, file_name: str, code: bool = False):
    """
    Utility to show contents of a file

    Args:
        label: str
        file_name: str
        code:

    Return: None

    """
    st.markdown("&nbsp ")
    st.markdown(f"### {label}")
    st.write(f"{file_name}")
    with open(f"{file_name}", "r") as file:
        file_lines = file.readlines()

    if code:
        st.code(textwrap.dedent("".join(file_lines[1:])))
    else:
        st.markdown(textwrap.dedent("".join(file_lines[1:])))
Exemplo n.º 30
0
def main():
    """Run this function to display the Streamlit app"""
    st.info(__doc__)
    st.markdown(STYLE, unsafe_allow_html=True)

    file = st.file_uploader("Upload file", type=FILE_TYPES)
    show_file = st.empty()
    if not file:
        show_file.info("Please upload a file of type: " +
                       ", ".join(FILE_TYPES))
        return

    file_type = get_file_type(file)
    if file_type == FileType.IMAGE:
        show_file.image(file)
    elif file_type == FileType.PYTHON:
        st.code(file.getvalue())
    else:
        data = pd.read_csv(file)
        st.dataframe(data.head(10))

    file.close()