Esempio n. 1
0
async def serve(q: Q):
    if not q.client.initialized:
        q.page['meta'] = ui.meta_card(box='')
        q.page['example'] = ui.form_card(box='1 1 11 10', items=[
            ui.button(name='show_side_panel', label='Order donuts', primary=True)
        ])
        q.client.initialized = True
    else:
        if q.args.show_side_panel:
            q.page['meta'].side_panel = ui.side_panel(title='Welcome to store', items=[
                ui.text('Donuts cost $1.99. Proceed?'),
                ui.buttons([ui.button(name='next_step', label='Next', primary=True)])
            ])
        elif q.args.next_step:
            q.page['meta'].side_panel.items = [
                ui.text('You will be charged $1.99. Proceed?'),
                ui.buttons([
                    ui.button(name='cancel', label='Back to safety'),
                    ui.button(name='submit', label='Place order', primary=True),
                ])
            ]
        elif q.args.submit:
            q.page['example'].items = [ui.message_bar('success', 'Order placed!')]
            q.page['meta'].side_panel = None

        elif q.args.cancel:
            q.page['example'].items = [ui.message_bar('info', 'Order canceled!')]
            q.page['meta'].side_panel = None

    await q.page.save()
Esempio n. 2
0
async def render_customer_selector(q: Q):

    clear_page(q)

    columns = [
        ui.table_column(name=column,
                        label=column,
                        sortable=True,
                        searchable=True)
        for column in q.app.customer_df.columns
    ]
    rows = [
        ui.table_row(name=str(index), cells=row.tolist())
        for index, row in q.app.customer_df.applymap(str).iterrows()
    ]
    q.client.cards.add('customer_table')
    q.page['customer_table'] = ui.form_card(
        box='customer_table',
        items=[
            ui.message_bar(text='Click "Status" to review a customer',
                           type='info'),
            ui.table(
                name='customer_table',
                columns=columns,
                rows=rows,
                groupable=True,
                multiple=False,
            )
        ])
Esempio n. 3
0
async def serve(q: Q):
    if q.args.start:
        q.page['form'] = ui.form_card(box='1 1 12 10',
                                      items=[ui.progress('Running...')])
        await q.page.save()

        seconds = random.randint(1, 6)

        # DON'T DO THIS!
        # This will make your app unresponsive for some time:
        # message = blocking_function(seconds)

        # Do this instead:
        with concurrent.futures.ThreadPoolExecutor() as pool:
            message = await q.exec(pool, blocking_function, seconds)

        # You can also pass a ProcessPoolExecutor, like this:
        # with concurrent.futures.ProcessPoolExecutor() as pool:
        #    message = await q.exec(pool, blocking_function, seconds)

        q.page['form'] = ui.form_card(box='1 1 12 10',
                                      items=[ui.message_bar('info', message)])
        await q.page.save()
    else:
        q.page['form'] = ui.form_card(
            box='1 1 12 10', items=[ui.button(name='start', label='Start')])
        await q.page.save()
Esempio n. 4
0
def get_contrast(color1: str, color2: str, q: Q, min_contrast=4.5):
    rgb1 = hex_to_rgb(q.client[color1].lstrip('#'))
    rgb2 = hex_to_rgb(q.client[color2].lstrip('#'))
    lum1 = get_luminance(rgb1[0], rgb1[1], rgb1[2])
    lum2 = get_luminance(rgb2[0], rgb2[1], rgb2[2])
    brightest = max(lum1, lum2)
    darkest = min(lum1, lum2)
    contrast = (brightest + 0.05) / (darkest + 0.05)
    if contrast < min_contrast:
        return ui.message_bar(
            type='error',
            text=f'Improve contrast between **{color1}** and **{color2}**.')
    else:
        return ui.message_bar(
            type='success',
            text=f'Contrast between **{color1}** and **{color2}** is great!')
Esempio n. 5
0
async def serve(q: Q):
    if q.args.train:
        # train WaveML Model using H2O-3 AutoML
        copy_expando(q.args, q.client)
        q.client.wave_model = build_model(
            train_df=q.client.train_df,
            target_column='target',
            model_type=ModelType.H2O3,
            _h2o3_max_runtime_secs=30,
            _h2o3_nfolds=2,
            _h2o3_include_algos=[q.client.algo]
        )
        model_id = q.client.wave_model.model.model_id
        accuracy = round(100 - q.client.wave_model.model.mean_per_class_error() * 100, 2)

        # show training details and prediction option
        q.page['example'].items[1].choice_group.value = q.client.algo
        q.page['example'].items[2].buttons.items[1].button.disabled = False
        q.page['example'].items[3].message_bar.type = 'success'
        q.page['example'].items[3].message_bar.text = 'Training successfully completed!'
        q.page['example'].items[4].text.content = f'''**H2O AutoML model id:** {model_id} <br />
            **Accuracy:** {accuracy}%'''
        q.page['example'].items[5].text.content = ''
    elif q.args.predict:
        # predict on test data
        preds = q.client.wave_model.predict(test_df=q.client.test_df)

        # show predictions
        q.page['example'].items[3].message_bar.text = 'Prediction successfully completed!'
        q.page['example'].items[5].text.content = f'''**Example predictions:** <br />
            {preds[0]} <br /> {preds[1]} <br /> {preds[2]}'''
    else:
        # prepare sample train and test dataframes
        data = load_wine(as_frame=True)['frame']
        q.client.train_df, q.client.test_df = train_test_split(data, train_size=0.8)

        # algos
        algo_choices = [ui.choice(x, x) for x in ['DRF', 'GLM', 'XGBoost', 'GBM', 'DeepLearning']]

        # display ui
        q.page['example'] = ui.form_card(
            box='1 1 -1 -1',
            items=[
                ui.text(content='''The sample dataset used is the
                    <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_wine.html" target="_blank">wine dataset</a>.'''),
                ui.choice_group(name='algo', label='Select Algo', choices=algo_choices, value='DRF'),
                ui.buttons(items=[
                    ui.button(name='train', label='Train', primary=True),
                    ui.button(name='predict', label='Predict', primary=True, disabled=True),
                ]),
                ui.message_bar(type='warning', text='Training will take a few seconds'),
                ui.text(content=''),
                ui.text(content='')
            ]
        )

    await q.page.save()
Esempio n. 6
0
def render_plot_view(q: Q):
    """Sets up the view a file as ui.table card"""

    items = [ui.separator(label='Step 3: Visualize the Dataset')]

    if q.client.working_file_path is None:
        items.append(ui.message_bar(type='warning', text='Please upload a dataset!'))
    else:
        items.append(make_ui_plot(file_path=q.client.working_file_path))

    q.page['plot'] = ui.form_card(box='4 6 8 -1', items=items)
Esempio n. 7
0
def render_table_view(q: Q):
    """Sets up the view a file as ui.table card"""

    items = [ui.separator(label='Step 2: View the Dataset')]

    if q.client.working_file_path is None:
        items.append(ui.message_bar(type='warning', text='Please upload a dataset!'))
    else:
        items.append(ui.text_xl(os.path.basename(q.client.working_file_path)))
        items.append(make_ui_table(file_path=q.client.working_file_path, n_rows=10, name='head_of_table'))

    q.page['table'] = ui.form_card(box='4 2 8 4', items=items)
Esempio n. 8
0
def render_upload_view(q: Q):
    """Sets up the upload-dataset card"""
    q.page['upload'] = ui.form_card(
        box='1 2 3 -1',
        items=[
            ui.separator(label='Step 1: Choose a Dataset'),
            ui.message_bar(
                type='info',
                text='This application requires a .csv file with any type of data within it',
            ),
            ui.file_upload(name='file_upload', label='Upload Data', multiple=False, file_extensions=['csv']),
        ]
    )
Esempio n. 9
0
async def list_tweets_for_hashtag(q):
    values, text = search_tweets(q)

    for tweet_count, tweet in enumerate(text):
        popularity_score = values[tweet]
        q.page[f'twitter_card_{tweet_count}'].items = [
            ui.message_bar(type=f"{derive_sentiment_message_type(popularity_score['compound'])}",
                           text=f"Sentiment - {derive_sentiment_status(popularity_score['compound'])}"),
            ui.text(content=tweet[:150].strip()),
            ui.frame(content=convert_plot_to_html(
                generate_figure_pie_of_target_percent(map_popularity_score_keys(popularity_score)), "cdn", False),
                    width='300px', height='250px')
        ]
Esempio n. 10
0
def form_training_completed(q: Q):
    # display when model training is completed
    return [
        ui.text(content=DATASET_TEXT),
        ui.dropdown(name='dai_instance_id', label='Select Driverless AI instance', value=q.client.dai_instance_id,
                    choices=q.client.choices_dai_instances, required=True),
        ui.buttons(items=[
            ui.button(name='train', label='Train', primary=True),
            ui.button(name='predict', label='Predict', primary=True)
        ]),
        ui.message_bar(type='success', text='Training successfully completed!'),
        ui.text(content=q.client.model_details)
    ]
Esempio n. 11
0
def form_prediction_completed(q: Q):
    # display when model prediction is completed
    return [
        ui.text(content=DATASET_TEXT),
        ui.dropdown(name='dai_instance_id', label='Select Driverless AI instance', value=q.client.dai_instance_id,
                    choices=q.client.choices_dai_instances, required=True),
        ui.dropdown(name='categorical_columns', label='Select categorical columns',
                    choices=q.client.column_choices, values=q.client.categorical_columns),
        ui.buttons(items=[
            ui.button(name='train', label='Train', primary=True),
            ui.button(name='predict', label='Predict', primary=True)
        ]),
        ui.message_bar(type='success', text='Prediction successfully completed!'),
        ui.text(content=q.client.model_details),
        ui.text(content=f'''**Example predictions:** <br />
            {q.client.preds[0]} <br /> {q.client.preds[1]} <br /> {q.client.preds[2]}''')
    ]
Esempio n. 12
0
def form_prediction_completed(q: Q):
    # display when model prediction is completed
    return [
        ui.text(content=DATASET_TEXT),
        ui.dropdown(name='dai_instance_id', label='Select Driverless AI instance', value=q.client.dai_instance_id,
                    choices=q.client.choices_dai_instances, required=True),
        ui.slider(name='dai_interpretability', label='Interpretability', min=1, max=10, step=1,
                  value=q.client.dai_interpretability),
        ui.toggle(name='dai_reproducible', label='Reproducible', value=q.client.dai_reproducible),
        ui.buttons(items=[
            ui.button(name='train', label='Train', primary=True),
            ui.button(name='predict', label='Predict', primary=True)
        ]),
        ui.message_bar(type='success', text='Prediction successfully completed!'),
        ui.text(content=q.client.model_details),
        ui.text(content=f'''**Example predictions:** <br />
            {q.client.preds[0]} <br /> {q.client.preds[1]} <br /> {q.client.preds[2]}''')
    ]
Esempio n. 13
0
def render_compare_word_cloud(q: Q):
    df = filter_data_frame(config.dataset, q.client.filters)

    if len(df):
        image = plot_word_cloud(merge_to_single_text(df[q.client.review]))

        q.page['compare'] = ui.image_card(
            box=config.boxes['right_panel'],
            title='Word Cloud based on the selected filters',
            type='png',
            image=image,
        )
    else:
        q.page['compare'] = ui.form_card(
            box=config.boxes['right_panel'],
            items=[
                ui.message_bar(type='warning',
                               text='No reviews matching filter criteria!')
            ])
Esempio n. 14
0
async def serve(q: Q):
    if q.args.start:
        q.page['form'] = ui.form_card(box='1 1 -1 -1', items=[ui.progress('Running...')])
        await q.page.save()

        seconds = random.randint(1, 6)

        # DON'T DO THIS!
        # This will make your app unresponsive for some time:
        # message = blocking_function(seconds)

        # Do this instead:
        message = await q.run(blocking_function, seconds)

        q.page['form'] = ui.form_card(box='1 1 -1 -1', items=[ui.message_bar('info', message)])
        await q.page.save()
    else:
        q.page['form'] = ui.form_card(box='1 1 -1 -1', items=[ui.button(name='start', label='Start')])
        await q.page.save()
Esempio n. 15
0
def form_training_completed(q: Q):
    # display when model training is completed
    return [
        ui.text(content=DATASET_TEXT),
        ui.dropdown(name='dai_instance_id',
                    label='Select Driverless AI instance',
                    value=q.client.dai_instance_id,
                    choices=q.client.choices_dai_instances,
                    required=True),
        ui.button(name='train',
                  label='Train',
                  primary=True,
                  disabled=q.client.disable_training),
        ui.message_bar(type='success',
                       text='Training successfully completed!'),
        ui.text(content=q.client.model_details),
        ui.text(content=
                f'**Download:** <a href="{q.client.path_autodoc}">AutoDoc</a>')
    ]
Esempio n. 16
0
def render_diff_word_cloud(q: Q):
    df = config.dataset

    for key, value in q.client.filters.items():
        df = df[df[key] == value]

    if len(df):
        q.page['diff'] = ui.image_card(box='content',
                                       title='Diff',
                                       type='png',
                                       image=plot_word_cloud(
                                           df[q.client.review], q))
    else:
        # TODO: Move into sidebar when https://github.com/h2oai/wave/pull/507 merged.
        q.page['diff'] = ui.form_card(
            box='content',
            items=[
                ui.message_bar(type='warning',
                               text='No reviews matching filter criteria!')
            ])
Esempio n. 17
0
def render_home(q: Q):
    init(q)

    df = predictor.get_testing_data_as_pd_frame()
    predicted_df = predictor.get_predict_data_as_pd_frame()
    drop_column_from_df(df, 'default.payment.next.month')
    add_column_to_df(df, predicted_df, 'Default Prediction Rate', 'predict')
    df = round_df_column(df, 'Default Prediction Rate', 4)

    q.page["risk_table"] = ui.form_card(
        box='risk_table',
        items=[
            ui.message_bar(text='Double click to review a customer',
                           type='info'),
            ui.table(name='risk_table',
                     columns=get_column_headers_for_df(df, True),
                     rows=get_rows(q, df),
                     groupable=True,
                     multiple=False,
                     height="800px")
        ])
Esempio n. 18
0
async def serve(q: Q):
    if q.args.start:  # The button named 'start' was clicked
        seconds = 5

        # Grab a reference to the form
        form = q.page['form']

        # Start incrementing the progress bar in the background
        future = asyncio.ensure_future(display_progress_bar(q, form, seconds))

        # Execute our long-running function in the background
        with concurrent.futures.ThreadPoolExecutor() as pool:
            message = await q.exec(pool, blocking_function, seconds)

        # Stop the progress bar (optional unless we used a infinite while loop in display_progress_bar()).
        future.cancel()

        # At this point, we're done with the long-running function; so display a completion message
        form.items = [ui.message_bar('info', message)]
        await q.page.save()
    else:
        q.page['form'] = ui.form_card(
            box='1 1 -1 -1', items=[ui.button(name='start', label='Start')])
        await q.page.save()
Esempio n. 19
0
async def showProducts(q: Q):
    global filter_product
    global filter_manufacturer
    global filter_supplier
    global unit_measure
    global gqty

    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]

    print('---------------------------')
    print('== PRODUCT TAB == ')
    print('q.args.show_tables: ' + str(q.args.show_tables) +
          ', q.args.show_inputs: ' + str(q.args.show_inputs))

    ## the user have clicked 'Add' button but haven't clicked 'Submit' button yet
    if (q.args.show_tables == None or q.args.show_tables == False) and (
            q.args.show_inputs or q.args.product or q.args.manufacturer
            or q.args.supplier or q.args.qty):

        ## need to get manufacturer data first (later used for the dropdown when adding new supplier)
        df_m = pd.DataFrame(l_manufacturers,
                            columns=['manufacturer', 'product'])
        df_s = pd.DataFrame(l_suppliers,
                            columns=['supplier', 'manufacturer', 'product'])

        ## if there is no manufacturer data
        if len(df_m) == 0:
            items.extend([
                ui.message_bar(type='info',
                               text='Try adding manufacturer first'),
                ui.button(name='goto_manufacturer',
                          label='Close',
                          primary=True)
            ])

        ## if there is no supplier data
        elif len(df_s) == 0:
            items.extend([
                ui.message_bar(type='info', text='Try adding supplier first'),
                ui.button(name='goto_supplier', label='Close', primary=True)
            ])

        ## if there is data on manufacturer and supplier, when the user click 'Add Product' button
        else:
            items.append(ui.text_xl(content='Add Product'))
            print('q.args.product: ' + str(q.args.product) +
                  ', q.args.manufacturer: ' + str(q.args.manufacturer) +
                  ', q.args.supplier: ' + str(q.args.supplier))

            if q.args.product and (filter_product == None
                                   or q.args.product != filter_product):
                filter_product = q.args.product
                filter_manufacturer = None
                filter_supplier = None
                unit_measure = None
                # selling_price = None
                gqty = None
            elif q.args.manufacturer and (
                    filter_manufacturer == None
                    or q.args.manufacturer != filter_manufacturer):
                filter_manufacturer = q.args.manufacturer
                filter_supplier = None
                unit_measure = None
                # selling_price = None
                gqty = None
            elif q.args.supplier and (filter_supplier == None
                                      or q.args.supplier != filter_supplier):
                filter_supplier = q.args.supplier
                unit_measure = None
                # selling_price = None
                gqty = None
            if q.args.qty:
                gqty = q.args.qty

            print(filter_product, filter_manufacturer, filter_supplier)

            ## PRODUCT
            if filter_product != None:
                items.append(
                    ui.dropdown(name='product',
                                label='Product',
                                choices=[
                                    ui.choice(name=x, label=x)
                                    for x in df_m['product'].unique()
                                ],
                                trigger=True,
                                value=filter_product))
                tmp_m = df_m[df_m['product'] ==
                             q.args.product]['manufacturer'].unique()

            else:
                items.append(
                    ui.dropdown(name='product',
                                label='Product',
                                choices=[
                                    ui.choice(name=x, label=x)
                                    for x in df_m['product'].unique()
                                ],
                                trigger=True))
                tmp_m = df_m['manufacturer'].unique()

            ## MANUFACTURER
            if filter_manufacturer != None:
                items.append(
                    ui.dropdown(
                        name='manufacturer',
                        label='Manufacturer',
                        choices=[ui.choice(name=x, label=x) for x in tmp_m],
                        trigger=True,
                        value=filter_manufacturer))
                tmp_s = df_s[(df_s['product'] == filter_product)
                             & (df_s['manufacturer'] == filter_manufacturer
                                )]['supplier'].unique()

            else:
                items.append(
                    ui.dropdown(
                        name='manufacturer',
                        label='Manufacturer',
                        choices=[ui.choice(name=x, label=x) for x in tmp_m],
                        trigger=True))
                tmp_s = df_s['supplier'].unique()

            ## SUPPLIER
            if filter_supplier != None:
                items.append(
                    ui.dropdown(
                        name='supplier',
                        label='Supplier',
                        choices=[ui.choice(name=x, label=x) for x in tmp_s],
                        trigger=True,
                        value=filter_supplier))
                # selling_price = df_s[(df_s['product']==filter_product)&(df_s['manufacturer']==filter_manufacturer)
                #                   &(df_s['supplier']==filter_supplier)]['selling_price'].values[0]
                # unit_measure = df_s[(df_s['product']==filter_product)&(df_s['manufacturer']==filter_manufacturer)
                #                   &(df_s['supplier']==filter_supplier)]['uom'].values[0]

            else:
                items.append(
                    ui.dropdown(
                        name='supplier',
                        label='Supplier',
                        choices=[ui.choice(name=x, label=x) for x in tmp_s],
                        trigger=True))
                # selling_price = None

            # items.append(ui.date_picker(name='purchase_date', label='Purchase Date'))
            # items.append(ui.textbox(name='qty', label='Qty'))

            # ## SELLING PRICE
            # if selling_price!=None:
            #   items.append(ui.textbox(name='selling_price', label='Selling Price', value = str(selling_price)))
            # else:
            #   items.append(ui.textbox(name='selling_price', label='Selling Price'))

            # ## UOM
            # if unit_measure!=None:
            #   items.append(ui.textbox(name='uom', label='Unit of Measurement', value = unit_measure, readonly = True))
            # else:
            #   items.append(ui.dropdown(name='uom', label='Unit of Measurement', choices=[
            #       ui.choice(name=x, label=x) for x in uom
            #   ]))

            # items.extend([
            #   # ui.date_picker(name='mfg_date', label='Mfg Date'),
            #   # ui.date_picker(name='exp_date', label='Exp Date'),
            #   ui.textbox(name='selling_price', label='Selling Price'),
            #   # ui.textbox(name='operational_cost', label='Operational Cost'),
            #   # ui.textbox(name='lvl', label='Order Point by level(%)'),
            #   # ui.textbox(name='schedule', label='Order Point Schedule (days)'),
            #   # ui.textbox(name='schedule_qty', label='Scheduled Qty'),
            #   # ui.textbox(name='rate', label='Avg. Consumption'),
            #   # ui.dropdown(name='freq', label='Consumption Frequency', choices=[
            #   #     ui.choice(name=x, label=x, value='daily', readonly=True) for x in consumption
            #   # ]),
            #   ui.button(name='show_tables', label='Submit', primary=True)])

            items.extend([
                # ui.textbox(name='selling_price', label='Selling Price'),
                ui.button(name='show_tables', label='Submit', primary=True)
            ])

    else:  ## first iteration goes here
        filter_product = None
        filter_manufacturer = None
        filter_supplier = None
        unit_measure = None
        selling_price = None
        gqty = None

        ## if q.args.show_tables == True
        if q.args.show_tables:
            # l_products.append([q.args.product, q.args.manufacturer, q.args.supplier, q.args.purchase_date, q.args.qty,
            #             q.args.uom, q.args.selling_price, q.args.mfg_date, q.args.exp_date, q.args.selling_price,
            #             q.args.operational_cost, q.args.lvl, q.args.schedule, q.args.schedule_qty, q.args.rate])
            # p = Products(q.args.product, q.args.manufacturer, q.args.supplier, q.args.purchase_date, q.args.qty,
            #             q.args.uom, q.args.selling_price, q.args.mfg_date, q.args.exp_date, q.args.selling_price,
            #             q.args.operational_cost, q.args.lvl, q.args.schedule, q.args.schedule_qty, q.args.rate)

            # l_products.append([q.args.product, q.args.manufacturer, q.args.supplier,
            #             q.args.uom])
            l_products.append(
                [q.args.product, q.args.manufacturer, q.args.supplier])
            # p = Products(q.args.product, q.args.manufacturer, q.args.supplier,
            #             q.args.uom)
            p = Products(q.args.product, q.args.manufacturer, q.args.supplier)
            products.append(p)
            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a product'))

        ## if there is a product data
        if len(products) > 0:
            items.append(
                ui.table(
                    name='products',
                    columns=column_product_table,
                    rows=[
                        ui.table_row(
                            name=product.id,
                            # cells=[product.product, product.manufacturer, product.supplier, product.selling_price,
                            #     product.uom]
                            cells=[
                                product.product, product.manufacturer,
                                product.supplier
                            ]) for product in products
                    ],
                    groupable=True,
                    downloadable=True,
                    resettable=True,
                    height='500px'))
        else:  ## if there is no product data
            items.append(ui.text_l(content='No Product found'))

        # items.append(ui.button(name='show_inputs', label='Add Product', primary=True))

        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Product',
                          primary=True),
                ui.button(name='delete_button', label='Delete Product'),
                ui.button(name='edit_button', label='Edit Product'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
Esempio n. 20
0
async def showManufacturers(q: Q):
    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]

    print('---------------------------')
    print('== MANUFACTURER TAB == ')

    ## when user is adding new manufacturer
    if q.args.show_inputs:
        items.extend([
            ui.text_xl(content='Add Manufacturer'),
            ui.textbox(name='manufacturer', label='Manufacturer'),
            ui.textbox(name='product', label='Product'),
            # ui.dropdown(name='uom', label='Unit of Measurement', choices=[
            #     ui.choice(name=x, label=x) for x in uom
            # ]),
            ui.button(name='show_tables', label='Submit', primary=True)
        ])

    # ## when user is editing existing manufacturer
    # elif q.args.edit_button:
    #   items.extend([ui.text_xl(content='Edit Manufacturer'),
    #   ui.textbox(name='manufacturer', label='Manufacturer'),
    #   # ui.textbox(name='product', label='Product'),
    #   # ui.dropdown(name='uom', label='Unit of Measurement', choices=[
    #   #     ui.choice(name=x, label=x) for x in uom
    #   # ]),
    #   ui.button(name='show_tables', label='Submit', primary=True)])

    ## default goes here
    else:

        ## user have click has clicked 'Submit' button after adding supplier
        if q.args.show_tables:
            l_manufacturers.append([q.args.manufacturer, q.args.product])
            m = Manufacturers(q.args.manufacturer, q.args.product)
            manufacturers.append(m)

            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a product'))

            ## GET ALL MANUFACTURERS DATA

        ## default view (if there's a manufacturer data)
        if len(manufacturers) > 0:
            items.append(
                ui.table(name='manufacturers',
                         columns=column_manufacturer_table,
                         rows=[
                             ui.table_row(name=manufacturer.id,
                                          cells=[
                                              manufacturer.manufacturer,
                                              manufacturer.product
                                          ]) for manufacturer in manufacturers
                         ],
                         groupable=True,
                         downloadable=True,
                         resettable=True,
                         height='500px'))

        ## GET ALL MANUFACTURERS DATA

        ## default view (if there's no manufacturer data)
        else:
            items.append(ui.text_l(content='No Manufacturer found'))

        # items.append(ui.button(name='show_inputs', label='Add Manufacturer', primary=True))
        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Manufacturer',
                          primary=True),
                ui.button(name='delete_button', label='Delete Manufacturer'),
                ui.button(name='edit_button', label='Edit Manufacturer'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
Esempio n. 21
0
async def showSuppliers(q: Q):
    items = [ui.tabs(name='menu', value=q.args.menu, items=tabs)]
    print('items in supplier: ' + str(items))

    ## if user clicks 'Add Supplier'
    if q.args.show_inputs:
        ## need to get manufacturer data first (later used for the dropdown when addiing new supplier)
        df_m = pd.DataFrame(l_manufacturers,
                            columns=['manufacturer', 'product'])

        ## if there is no Manufacter data, then the user should add manufacturer data first
        if len(df_m) == 0:
            items.extend([
                ui.message_bar(type='info',
                               text='Try adding manufacturer first'),
                ui.button(name='goto_manufacturer',
                          label='Close',
                          primary=True)
            ])

        ## there's a manufacturer data, then go here
        else:
            items.extend([
                ui.text_xl(content='Add Supplier'),
                ui.textbox(name='supplier', label='Supplier'),
                ui.dropdown(
                    name='manufacturer',
                    label='Manufacturer',
                    choices=[  ## dropdown existing manufacturers
                        ui.choice(name=x, label=x)
                        for x in df_m['manufacturer'].unique()
                    ]),
                ui.dropdown(
                    name='product',
                    label='Product',
                    choices=[  ## dropdown existing items
                        ui.choice(name=x, label=x)
                        for x in df_m['product'].unique()
                    ]),  ## product should based on the what manufacturer have
                # ui.dropdown(name='uom', label='Unit of Measurement', choices=[ ## dropdown unit of measurement based on UOM variable above
                #     ui.choice(name=x, label=x) for x in uom
                # ]),
                # ui.textbox(name='selling_price', label='Price'),
                # ui.textbox(name='lead_time', label='Lead Time(days)'),
                # ui.textbox(name='delivery_time', label='Delivery Time(days)'),
                ui.button(name='show_tables', label='Submit',
                          primary=True)  ## submit button
            ])

    ## user hasn't clicked 'Add suppliers' button
    else:
        ## user have click has clicked 'Submit' button after adding supplier
        if q.args.show_tables:
            l_suppliers.append(
                [q.args.supplier, q.args.manufacturer, q.args.product])  ## !!!
            s = Suppliers(q.args.supplier, q.args.manufacturer, q.args.product)
            suppliers.append(s)
            items.append(
                ui.message_bar(type='success',
                               text='You have successfully added a supplier'))

        ## default view (if there's suppliers data)
        if len(suppliers) > 0:
            items.append(
                ui.table(name='suppliers',
                         columns=column_supplier_table,
                         rows=[
                             ui.table_row(name=supplier.id,
                                          cells=[
                                              supplier.supplier,
                                              supplier.manufacturer,
                                              supplier.product
                                          ]) for supplier in suppliers
                         ],
                         groupable=True,
                         downloadable=True,
                         resettable=True,
                         height='500px'))

        ## default view (if there's a supplier data)
        else:
            items.append(ui.text_l(content='No Supplier found'))

        # items.append(ui.button(name='show_inputs', label='Add Supplier', primary=True))

        items.append(
            ui.buttons([
                ui.button(name='show_inputs',
                          label='Add Supplier',
                          primary=True),
                ui.button(name='delete_button', label='Delete Supplier'),
                ui.button(name='edit_button', label='Edit Supplier'),
            ]))

    q.page['example'] = ui.form_card(box='1 2 -1 -1', items=items)
    await q.page.save()
Esempio n. 22
0
async def serve(q: Q):
    q.page['example'] = ui.form_card(box='1 1 4 10', items=[
        ui.text_xl(content='Extra-large text, for headings.'),
        ui.text_l(content='Large text, for sub-headings.'),
        ui.text_m(content='Body text, for paragraphs and other content.'),
        ui.text_s(content='Small text, for small print.'),
        ui.text_xs(content='Extra-small text, for really small print.'),
        ui.separator(label='A separator sections forms'),
        ui.progress(label='A progress bar'),
        ui.progress(label='A progress bar'),
        ui.message_bar(type='success', text='Message bar'),
        ui.textbox(name='textbox', label='Textbox'),
        ui.label(label='Checkboxes'),
        ui.checkbox(name='checkbox1', label='A checkbox'),
        ui.checkbox(name='checkbox1', label='Another checkbox'),
        ui.checkbox(name='checkbox1', label='Yet another checkbox'),
        ui.toggle(name='toggle', label='Toggle'),
        ui.choice_group(name='choice_group', label='Choice group', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.checklist(name='checklist', label='Checklist', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.dropdown(name='dropdown', label='Dropdown', choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.dropdown(name='dropdown', label='Multi-valued Dropdown', values=[], choices=[
            ui.choice(name=x, label=x) for x in ['Egg', 'Bacon', 'Spam']
        ]),
        ui.combobox(name='combobox', label='Combobox', choices=['Choice 1', 'Choice 2', 'Choice 3']),
        ui.slider(name='slider', label='Slider'),
        ui.range_slider(name='range_slider', label='Range slider', max=99),
        ui.spinbox(name='spinbox', label='Spinbox'),
        ui.date_picker(name='date_picker', label='Date picker'),
        ui.color_picker(name='color_picker', label='Color picker'),
        ui.buttons([
            ui.button(name='primary_button', label='Primary', primary=True),
            ui.button(name='standard_button', label='Standard'),
            ui.button(name='standard_disabled_button', label='Standard', disabled=True),
        ]),
        ui.file_upload(name='file_upload', label='File upload'),
        ui.table(name='table', columns=[
            ui.table_column(name='col1', label='Column 1'),
            ui.table_column(name='col2', label='Column 2'),
        ], rows=[
            ui.table_row(name='row1', cells=['Text A', 'Text B']),
            ui.table_row(name='row2', cells=['Text C', 'Text D']),
            ui.table_row(name='row3', cells=['Text E', 'Text F']),
        ]),
        ui.link(label='Link'),
        ui.tabs(name='tabs', items=[
            ui.tab(name='email', label='Mail', icon='Mail'),
            ui.tab(name='events', label='Events', icon='Calendar'),
            ui.tab(name='spam', label='Spam'),
        ]),
        ui.expander(name='expander', label='Expander'),
        ui.frame(path='https://example.com'),
        ui.markup(content=html),
        ui.template(
            content=menu,
            data=pack(dict(dishes=[
                dict(name='Spam', price='$2.00'),
                dict(name='Ham', price='$3.45'),
                dict(name='Eggs', price='$1.75'),
            ]))
        ),
        ui.picker(name='picker', label='Picker', choices=[
            ui.choice('choice1', label='Choice 1'),
            ui.choice('choice2', label='Choice 2'),
            ui.choice('choice3', label='Choice 3'),
        ]),
        ui.stepper(name='stepper', items=[
            ui.step(label='Step 1', icon='MailLowImportance'),
            ui.step(label='Step 2', icon='TaskManagerMirrored'),
            ui.step(label='Step 3', icon='Cafe'),
        ]),
        ui.visualization(
            plot=ui.plot([ui.mark(type='interval', x='=product', y='=price', y_min=0)]),
            data=data(fields='product price', rows=[(c, x) for c, x, _ in [f.next() for _ in range(n)]], pack=True),
        ),
        ui.vega_visualization(
            specification=spec,
            data=data(fields=["a", "b"], rows=[
                ["A", rnd()], ["B", rnd()], ["C", rnd()],
                ["D", rnd()], ["E", rnd()], ["F", rnd()],
                ["G", rnd()], ["H", rnd()], ["I", rnd()]
            ], pack=True),
        ),
        ui.button(name='show_inputs', label='Submit', primary=True),
    ])
    await q.page.save()
Esempio n. 23
0
# Form / Message Bar
# Use message bars to indicate relevant status information.
# #form #message_bar
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 4 10',
    items=[
        ui.message_bar(type='blocked', text='This action is blocked.'),
        ui.message_bar(type='error', text='This is an error message'),
        ui.message_bar(type='warning', text='This is a warning message.'),
        ui.message_bar(type='info', text='This is an information message.'),
        ui.message_bar(type='success', text='This is an success message.'),
        ui.message_bar(type='danger', text='This is a danger message.'),
    ])
page.save()
Esempio n. 24
0
# Form / Message Bar
# Use message bars to indicate relevant status information.
# #form #message_bar
# ---
from h2o_wave import site, ui

page = site['/demo']

page['example'] = ui.form_card(
    box='1 1 4 10',
    items=[
        ui.message_bar(type='blocked', text='This action is blocked.'),
        ui.message_bar(type='error', text='This is an error message'),
        ui.message_bar(type='warning', text='This is a warning message.'),
        ui.message_bar(type='info', text='This is an information message.'),
        ui.message_bar(type='success', text='This is an success message.'),
        ui.message_bar(type='danger', text='This is a danger message.'),
        ui.message_bar(type='success',
                       text='This is a **MARKDOWN** _message_.'),
        ui.message_bar(type='success',
                       text='This is an <b>HTML</b> <i>message</i>.'),
    ])
page.save()
Esempio n. 25
0
async def serve(q: Q):
    if q.args.train:
        # train WaveML Model using H2O-3 AutoML
        q.client.wave_model = build_model(
            train_df=q.client.train_df,
            target_column='target',
            model_type=ModelType.H2O3,
            _h2o3_max_runtime_secs=5,
            _h2o3_nfolds=2,
            _h2o3_include_algos=['DRF', 'XGBoost', 'GBM'])
        model_id = q.client.wave_model.model.model_id
        accuracy = round(q.client.wave_model.model.accuracy()[0][1] * 100, 2)

        # show training details and prediction option
        q.page['example'].items[1].buttons.items[1].button.disabled = False
        q.page['example'].items[2].message_bar.type = 'success'
        q.page['example'].items[
            2].message_bar.text = 'Training successfully completed!'
        q.page['example'].items[
            3].text.content = f'''**H2O AutoML model id:** {model_id} <br />
            **Accuracy:** {accuracy}%'''
        q.page['example'].items[4].text.content = ''
        q.page['example'].items[5].text.content = ''
    elif q.args.predict:
        # predict on test data
        preds = q.client.wave_model.predict(test_df=q.client.test_df)
        shaps = q.client.wave_model.model.predict_contributions(
            H2OFrame(q.client.test_df)).as_data_frame()

        # show predictions
        q.page['example'].items[
            2].message_bar.text = 'Prediction successfully completed!'
        q.page['example'].items[
            4].text.content = f'''**Example predictions:** <br />
            {preds[0]} <br /> {preds[1]} <br /> {preds[2]}'''
        q.page['example'].items[
            5].text.content = f'''**Example SHAP contributions:** <br />
            {shaps.head(3).to_html()}'''
    else:
        # prepare sample train and test dataframes
        data = load_breast_cancer(as_frame=True)['frame']
        q.client.train_df, q.client.test_df = train_test_split(data,
                                                               train_size=0.8)

        # display ui
        q.page['example'] = ui.form_card(
            box='1 1 -1 -1',
            items=[
                ui.text(content='''The sample dataset used is the
                    <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_breast_cancer.html#sklearn.datasets.load_breast_cancer" target="_blank">breast cancer dataset</a>.'''
                        ),
                ui.buttons(items=[
                    ui.button(name='train', label='Train', primary=True),
                    ui.button(name='predict',
                              label='Predict',
                              primary=True,
                              disabled=True),
                ]),
                ui.message_bar(type='warning',
                               text='Training will take a few seconds'),
                ui.text(content=''),
                ui.text(content=''),
                ui.text(content='')
            ])

    await q.page.save()
Esempio n. 26
0
async def serve(q: Q):
    if q.args.train:
        # train WaveML Model using H2O-3 AutoML
        wave_model = build_model(train_df=q.client.train_df,
                                 target_column='target',
                                 model_type=ModelType.H2O3,
                                 _h2o3_max_runtime_secs=5,
                                 _h2o3_nfolds=2)
        model_id = wave_model.model.model_id
        accuracy = round(100 - wave_model.model.mean_per_class_error() * 100,
                         2)

        # save model to local folder
        q.client.path_model = save_model(model=wave_model,
                                         output_dir_path='./mymodelfolder')

        # show training details and prediction option
        q.page['example'].items[1].buttons.items[1].button.disabled = False
        q.page['example'].items[2].message_bar.type = 'success'
        q.page['example'].items[
            2].message_bar.text = 'Training successfully completed!'
        q.page['example'].items[
            3].text.content = f'''**H2O AutoML model id:** {model_id} <br />
            **Accuracy:** {accuracy}%'''
        q.page['example'].items[4].text.content = ''
    elif q.args.predict:
        # load model from local path
        wave_model = load_model(file_path=q.client.path_model)

        # predict on test data
        preds = wave_model.predict(test_df=q.client.test_df)

        # show predictions
        q.page['example'].items[
            2].message_bar.text = 'Prediction successfully completed!'
        q.page['example'].items[
            4].text.content = f'''**Example predictions:** <br />
            {preds[0]} <br /> {preds[1]} <br /> {preds[2]}'''
    else:
        # prepare sample train and test dataframes
        data = load_wine(as_frame=True)['frame']
        q.client.train_df, q.client.test_df = train_test_split(data,
                                                               train_size=0.8)

        # display ui
        q.page['example'] = ui.form_card(
            box='1 1 -1 -1',
            items=[
                ui.text(content='''The sample dataset used is the
                    <a href="https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_wine.html" target="_blank">wine dataset</a>.'''
                        ),
                ui.buttons(items=[
                    ui.button(name='train', label='Train', primary=True),
                    ui.button(name='predict',
                              label='Predict',
                              primary=True,
                              disabled=True),
                ]),
                ui.message_bar(type='warning',
                               text='Training will take a few seconds'),
                ui.text(content=''),
                ui.text(content='')
            ])

    await q.page.save()
Esempio n. 27
0
def add_error_message(q, type, message):
    q.page['error_message'] = ui.form_card(box='1 5 2 2',
                                           items=[
                                               ui.message_bar(type=type,
                                                              text=message),
                                           ])