Data And Beyond

Selected stories around Data Science, Machine Learning, Artificial Intelligence, Programming, and Technology topics. Writing guide: https://medium.com/data-and-beyond/how-to-write-for-data-and-beyond-b83ff0f3813e

Follow publication

From Idea to Prototype in Minutes: Building Fast Web Apps with Dash

CheeKean
Data And Beyond
Published in
13 min readJan 9, 2023

--

Snapshot of a Production Dashboard for Risk Detection
Demo Dashboard from Official Dash Gallery https://dash.gallery/Portal/
Page 1 of the Dash App (Graph Output with Variable Selection)
Page 2 of the Dash App (Sentiment Analyzer)

2. Dash Overview

3. Code Structure


+---assets
| general.css
|
+---components
| | __init__.py
| |
| +---callbacks
| | | callback_1.py
| | | callback_2.py
| | | main_callback.py
| | | __init__.py
| | |
| +---templates
| | | main_layout.py
| | | page_1.py
| | | page_2.py
| | | __init__.py
| app.py
| app.yaml
| index.py
| requirements.txt
!pip install dash pandas dash_bootstrap_components torch transformers

app.py file

import dash
import dash_bootstrap_components as dbc

external_stylesheets = [dbc.themes.BOOTSTRAP]
app = dash.Dash(
__name__,
external_stylesheets=external_stylesheets)

app.config['suppress_callback_exceptions'] = True

index.py file

from app import app
from components.templates.main_layout import layout
app.layout = layout

if __name__ == '__main__':
app.run_server(debug=False, host='0.0.0.0', port=8050)

components folder

import pandas as pd
import numpy as np
from app import app
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
from components.callbacks import main_callback

### tabs for page selection ###
tabs = dbc.Tabs([
dbc.Tab(label="Page A", tab_id='main_tab_a'),
dbc.Tab(label="Page B", tab_id='main_tab_b')],
id='main_tab',
active_tab="main_tab_a",
)

### content to be display ###
content = html.Div(id='page_content', className='content')

### final layout ###
layout = html.Div([
dcc.Location(id="url"),
tabs,
content
])
from dash.dependencies import Input, Output
from datetime import datetime
from app import app
from components.templates import page_1
from components.templates import page_2

### update page content with selected tab ###
@app.callback(
Output("page_content", "children"),
Input("main_tab", "active_tab")
)
def render_tab_content(tab):
if tab == 'main_tab_a':
return page_1.layout
elif tab == 'main_tab_b':
return page_2.layout
else:
return None

from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px
from components.callbacks import callback_1

### dropdown
dropdown_1 = dcc.Dropdown(
id='xaxis-column',
style={'width': '48%', 'display': 'inline-block'})

dropdown_2 = dcc.Dropdown(
id='yaxis-column',
style={'width': '48%', 'display': 'inline-block'})

### scatter plot
scatter_plot = dcc.Graph(id='indicator-graphic')

### final layout ###
layout = html.Div(
children=[
dropdown_1,
dropdown_2,
scatter_plot
]
)
from app import app
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')

### update options list in the dropdown
@app.callback(
[
Output('xaxis-column', 'options'),
Output('xaxis-column', 'value'),
Output('yaxis-column', 'options'),
Output('yaxis-column', 'value'),
],
Input('main_tab', 'value')
)

def update_dropdown_options(_):
option_list = df['Indicator Name'].unique()
return option_list, option_list[0], option_list, option_list[-1]


### update plot based on dropdown selection
@app.callback(
Output('indicator-graphic', 'figure'),
Input('xaxis-column', 'value'),
Input('yaxis-column', 'value'),
)

def update_graph(x_axis, y_axis):
dff = df.copy()

fig = px.scatter(x=dff[dff['Indicator Name'] == x_axis]['Value'],
y=dff[dff['Indicator Name'] == y_axis]['Value'],
hover_name=dff[dff['Indicator Name'] == y_axis]['Country Name'])

# update plot layout
fig.update_layout(
margin={'l': 40, 'b': 40, 't': 10, 'r': 0},
hovermode='closest')

fig.update_xaxes(title=x_axis)
fig.update_yaxes(title=y_axis)

return fig
Page 2 of the Dash App (Sentiment Analyzer)
from dash import dcc
from dash import html
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.express as px
from components.callbacks import callback_2

### text input and output ###
text_container = html.Div(
dbc.Container(
[
html.H1("Sentiment Analyser", className="fw-bolder"),
html.P("Enter Text to get the Sentiment in return"),
html.Hr(className="my-3"),

# text input area
dbc.Textarea(id="input", placeholder="Type something..."),
dbc.Button("Compute", id="submit-button", className="my-2"),
html.Br(),

# text ouput
dbc.Alert(
id="output",
children=["This is a primary alert"], style={"visibility" : 'hidden'}),

],
fluid=True,
className="py-3",
),
className="p-3 bg-light rounded-3",
)

### final layout ###
layout = html.Div(
children=[
text_container,
]
)
from app import app
from dash.dependencies import Input, Output, State
from transformers import pipeline

model = pipeline("text-classification",
model="nlptown/bert-base-multilingual-uncased-sentiment")

@app.callback(
[Output('output', 'children'),
Output('output', 'color'),
Output('output', 'style')],
[Input('submit-button', 'n_clicks'),
State('input', 'value')]
)

def analyse_sentiment(click, text):

if (text is not None) | (len(text) > 0):
visible = 'visible'
output = model(text)[0]['label']

if (output == "1 star") | (output == "2 stars"):
text_output = f"☹️ {output} review"
color = 'danger'

elif output == "3 stars":
text_output = f"😐 {output} review"
color = 'secondary'

else:
text_output = f"😃 {output} review"
color = 'success'

# if textarea box is empty
else:
visible = 'hidden'

return text_output, color, {"visibility" : visible}

assets folder

A favicon is the icon located on the top of a webpage
body { 
margin: 10px;
}

.content {
margin: 20px;
}

4. Test Run

python3 index.py

5. Deployment

6. Scaling this to production

7. Conclusion

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Data And Beyond
Data And Beyond

Published in Data And Beyond

Selected stories around Data Science, Machine Learning, Artificial Intelligence, Programming, and Technology topics. Writing guide: https://medium.com/data-and-beyond/how-to-write-for-data-and-beyond-b83ff0f3813e

CheeKean
CheeKean

Written by CheeKean

Senior Data Scientist | 🔍 Explaining Complex Concepts | 💻 Python Enthusiast

No responses yet