How to output results in dash bootstrap Toast component?

I am trying to output my machine learning model results which are in list to Toast component (dash bootstrap) and below is the code.
Here is how my dashboard currently look and I want to show the results below the text box and submit button area.

app = dash.Dash(
    __name__, title="Multi Tag Prediction", external_stylesheets=[dbc.themes.BOOTSTRAP]
)
server = app.server
app.layout = html.Div(
    [
        html.H2(
            ["Multi Tag Prediction"],
            style={
                "text-align": "left",
                "margin-left": "4.5%",
                "margin-right": "2%",
                "margin-bottom": "2%",
            },
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.Div(
                        [
                            dbc.FormGroup(
                                [
                                    dbc.Label(
                                        "Filter by Preprocessing Functions to Apply:"
                                    ),
                                    dbc.RadioItems(
                                        options=[
                                            {"label": "All", "value": "all"},
                                            {"label": "Customized", "value": "custom"},
                                        ],
                                        value="all",
                                        id="radio-button",
                                        inline=True,
                                        style={"padding": "10px"},
                                    ),
                                ]
                            ),
                            html.Div(
                                [
                                    dcc.Dropdown(
                                        id="drop-down",
                                        options=[
                                            {
                                                "label": "remove_digits",
                                                "value": "remove_digits",
                                            },
                                            {
                                                "label": "remove_stopwords",
                                                "value": "stop_words",
                                            },
                                            {
                                                "label": "text_lemmatization",
                                                "value": "text_lemmatization",
                                            },
                                        ],
                                        value=[
                                            "remove_digits",
                                            "remove_stopwords",
                                            "text_lemmatization",
                                        ],
                                        multi=True,
                                        placeholder="Select the preprocessing functions",
                                        searchable=True,
                                    )
                                ],
                                style={"padding": "5px", "margin-bottom": "10px",},
                            ),
                            html.Div(
                                [
                                    html.H6(
                                        "Filter by threshold (probabilty of labels to include):"
                                    ),
                                    dcc.Slider(
                                        id="slider",
                                        min=0.1,
                                        max=0.9,
                                        step=0.1,
                                        value=0.5,
                                        marks={
                                            0.1: "0.1",
                                            0.2: "0.2",
                                            0.3: "0.3",
                                            0.4: "0.4",
                                            0.5: "0.5",
                                            0.6: "0.6",
                                            0.7: "0.7",
                                            0.8: "0.8",
                                            0.9: "0.9",
                                        },
                                        tooltip={"placement": "top"},
                                        included=False,
                                    ),
                                ],
                                style={"margin-bottom": "10px"},
                            ),
                            html.Div(
                                [
                                    html.H6(
                                        "Filter by label count (how many labels to include if there are more):"
                                    ),
                                    dcc.Slider(
                                        id="slider-2",
                                        min=5,
                                        max=10,
                                        step=1,
                                        value=5,
                                        marks={
                                            5: "5",
                                            6: "6",
                                            7: "7",
                                            8: "8",
                                            9: "9",
                                            10: "10",
                                        },
                                        tooltip={"placement": "top"},
                                        included=False,
                                    ),
                                ],
                                style={"margin-top": "10px"},
                            ),
                        ],
                        style={
                            "width": "100%",
                            "box-shadow": "5px 5px 5px  #cacfd2",
                            "padding": "35px",
                            "background-color": "#f9f9f9",
                        },
                    ),
                    width={"size": 4, "order": "first", "offset": 0},
                ),
                dbc.Col(
                    html.Div(
                        [
                            dbc.Textarea(
                                id="input_text",
                                value="",
                                style={
                                    "height": 300,
                                    "width": "100%",
                                    "box-shadow": "5px 5px 5px  #cacfd2",
                                    # "margin-left": "-20px",
                                    "background-color": "#f9f9f9",
                                },
                                maxLength=10000,
                                placeholder="Type the text or copy-paste from somewhere else",
                            ),
                            dbc.Button(
                                "Submit",
                                id="submit-button",
                                n_clicks=0,
                                style={"margin-left": "532px", "margin-top": "15px",},
                                outline=True,
                                color="primary",
                            ),
                            html.Div(
                                [
                                    dbc.Spinner(
                                        [
                                            dbc.Toast(
                                                id="output-state",
                                                header="Predicted Labels:",
                                                icon="info",
                                                duration=10,
                                            )
                                        ],
                                        type="grow",
                                        color="info",
                                        fullscreen=True,
                                    ),
                                ]
                            ),
                        ]
                    ),
                    width={"size": 6, "order": "second"},
                    # align="end",
                ),
            ],
            justify="around",
        ),
    ],
    # style={
    #     "background-color": "#f2f2f2",
    #     "margin-left": "-15px",
    #     "margin-right": "-15px",
    #     "margin-bottom": "-15px",
    # },
)

Callbacks:


@app.callback(Output("drop-down", "value"), [Input("radio-button", "value")])
def display_status(selector):
    if selector == "all":
        return ["remove_digits", "text_lemmatization", "remove_stopwords"]
    else:
        return []


@app.callback(
    Output("output-state", "children"),
    [Input("submit-button", "n_clicks")],
    [
        State("input_text", "value"),
        State("slider", "value"),
        State("drop-down", "value"),
        State("slider-2", "value"),
    ],
    prevent_initial_call=True,
)
def label_prediction(num_clicks, text, threshold_value, preprocess_func, label_value):
    if text is None or num_clicks is None:
        raise PreventUpdate

    else:
        params = ["remove_digits", "remove_stopwords", "text_lemmatization"]
        dict_params = [param in preprocess_func for param in params]
        preprocess_text = preprocess(text, *dict_params)
        transformed_text = tfidf.fit_transform([preprocess_text])
        prediction = classifier.predict_proba(transformed_text)
        return f"Predicted labels:{get_tags(prediction[0],threshold_value,label_value)}"


if __name__ == "__main__":
    app.run_server(debug=True)

Moreover, I tried to raise PreventUpdate from loading the page in label_prediction function but it still loads the page in empty text area.
Any Help would be really appreciated in debugging the issue.

@adamschroeder @chriddyp @Emmanuelle @empet …sorry for tagging you guys individually but looks like this community is dead and no one here to help with the issues (either beginner or otherwise). Can you guys make some moderator which can give some of their time to this Dash and Plotly community and help it grow? There are many unanswered questions lying dormant.

Hi @matsujju ,

This is a user Forum, if you enjoy using a free software and receiving free advice, you need also to colaborate with us before making any complain.

You didn’t answer any of the “many unanswered questions” that you mentioned.

This community can grow if all of us take a litle of our time to answer at least the same number of answer we receive. :thinking:

True but being beginner if I don’t clear my doubts then how will I help others?

Well, Your code says that you can answer a lot of other beginners questions. :smiley:

1 Like

You really think I can write better than beginner code?

Can you help me with the above issue in my code? I will surely help the other beginner questions.

You can write better than me, and I answered a lot of questions since june 2020 (when I started learning how to code). :smiley:

Usually I do not give advise about code, I just help others where to find a solution.

And in the process I learned a lot answering other questions.

PD: I don’t understand your formulas in the callback and I not sure what you want to acomplish.

please specify a litle bit what you want to show and what is your callback return given (is showing something?)

What I am trying to achieve is that if user enters text and select the given options in left sidebar, it will return some results based on machine learning model as shown in label_prediction func but if text box is empty or button hasn’t been clicked it should return anything…and I want to return the result in dash bootstrap Toast component. In the callbacks, the input values from user is being kept in State until button is clicked.

Ok. But in your return f"Predicted labels:{get_tags(prediction[0],threshold_value,label_value)}"

is giving you something, as I can’t reproduce your code, it is imposible to know what problem are you facing.

here I am returning the get_tags function which looks like this

def get_tags(predicted_list, threshold, labels):
    mlb = [(i1, c1) for i1, c1 in enumerate(multilabel.classes_)]
    temp_list = sorted(
        [(i, c) for i, c in enumerate(list(predicted_list))],
        key=lambda x: x[1],
        reverse=True,
    )
    tag_list = [item1 for item1 in temp_list if item1[1] >= threshold]
    tags = [
        item[1] for item2 in tag_list[:labels] for item in mlb if item2[0] == item[0]
    ]
    return tags

Yes it gives list of tags like this [‘python’,‘dash’,‘plotly’]

Please answer my questions:

  1. Are you getting some result from your callback?
  2. What is the problem you are facing?
  1. Yes as answered above.
  2. I am not able to show the results in webapp after clicking button as shown in screenshot

if I print instead of return in callback like this

@app.callback(
    Output("output-state", "children"),
    [Input("submit-button", "n_clicks")],
    [
        State("input_text", "value"),
        State("slider", "value"),
        State("drop-down", "value"),
        State("slider-2", "value"),
    ],
    # prevent_initial_call=True,
)
def label_prediction(num_clicks, text, threshold_value, preprocess_func, label_value):
    if text is None:
        raise PreventUpdate

    if num_clicks > 0:
        params = ["remove_digits", "remove_stopwords", "text_lemmatization"]
        dict_params = [param in preprocess_func for param in params]
        preprocess_text = preprocess(text, *dict_params)
        transformed_text = tfidf.fit_transform([preprocess_text])
        prediction = classifier.predict_proba(transformed_text)
        print(f"Predicted labels:{get_tags(prediction[0],threshold_value,label_value)}")

it prints in console after I entered some text in webapp

(streamlit) C:\Users\Sujju\Downloads\Projects\Multi_Tag_Prediction>python streamlit_app.py
Dash is running on http://127.0.0.1:8050/

 * Serving Flask app "streamlit_app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
Predicted labels:[]

Well if Predicted labels:[]

The correct answer is:

1) No, it is giving me nothing. :joy:

Well I was not looking for correct labels as I entered some random text in text box…that is not the issue…the issue is, it is not returning in dash web app not even empty list as shown in console.

you are printing the return and the console shows [ ]

If you send this to the output why you pretend to see something :thinking:

Sorry but I don’t understand.

Look, the output-id in Toast component has children object which takes list, so I leave the children in Toast component as seen in layout and I return the results which happens to be in list and I don’t care what it has inside. I use the print instead of return to just show you that is printing in console (not printing the return).
To make it easily understandable to you, I just need to show user the result below submit button area in my webapp (attached the screenshot of my webapp above) and I am trying to do that in Toast component of dash bootstrap that’s it.
I hope you get it.

As I said: I’m a beginner too.
As far as I know, the Toast will show whatever you send as children in your callback, not only list (perhaps I’m wrong).

Try first sending something to your tost like: return "This is the result to show"

see if the Toast shows you that.

If it works, try to print in the console that what you want to show in the Toast.