'Dash' object has no attribute 'html' - python

I am new to Dash, trying to create a page where user can upload three csv files. I am getting an error 'Dash' object has no attribute 'html'. Below is the code I'm trying.
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
app = dash.Dash()
app.layout=app.html.Div([
html.H1('Training Data Set'),
dcc.Upload(id='upload-training-data', children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
])),
html.H1('Meta Data'),
dcc.Upload(id='upload-meta-data', children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
])),
html.H1('Validation Data Set'),
dcc.Upload(id='upload-validation-data', children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]))
])
I tried installing and uninstalling dash and other components but still not able to resolve

Related

Stream file into python-pptx with Dash

I would like a Dash dashboard to extract data from powerpoint .pptx files, a deployment constraint is that we can't read or write files to a directory so I would like to stream the input file straight into python-pptx's Presentation function.
here is a small reprex:
from flask import Flask, send_from_directory
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from pptx import Presentation
server = Flask(__name__)
app = dash.Dash(server=server)
app.layout = html.Div(
[
html.H1("File Browser"),
html.H2("Upload"),
dcc.Upload(
id="upload-data",
children=html.Div(
["Drag and drop or click to select a file to upload."]
),
multiple=True,
),
html.H2("Shape List"),
html.Ul(id="shape-list"),
],
style={"max-width": "500px"},
)
#app.callback(
Output("shape-list", "children"),
[Input("upload-data", "filename"), Input("upload-data", "contents")],
)
def update_output(uploaded_filenames, uploaded_file_contents):
shape_text = []
if uploaded_filenames is not None and uploaded_file_contents is not None:
for name, data in zip(uploaded_filenames, uploaded_file_contents):
prs = Presentation(data)
shape_text += [shape.text for shape in prs.slides[0].shapes]
return [html.Li(txt) for txt in shape_text]
if __name__ == "__main__":
app.run_server(debug=True, port=8888)
which gives error:
pptx.exc.PackageNotFoundError: Package not found at 'data:application/vnd.openxmlformats-officedocument.presentationml.presentation;base64...
I tried a few different attempts at encoding/decoding the input with StringIO and BytesIO but couldn't get it into a working format.
The data property contains also content type, which should be separated before doing the base64 decoding. Hence the parsing code should be along the lines of,
content_type, content_string = data.split(',')
prs = Presentation(BytesIO(base64.b64decode(content_string)))
Replacing
prs = Presentation(data)
in you example with that parsing code, I am able to parse a pptx file as intended.

Python Dash TypeError: cannot convert 'NoneType' object to bytes

I am trying to build a dashboard using Dash. I keep getting this error when I go to the default website http://127.0.0.1:8050/ and I get TypeError: cannot convert 'NoneType' object. Check the image for the error. My code does not have any mistakes and I was able to run it before and the dashboard would work perfectly. Can someone please help me? Here is the code:
import dash # (version 1.12.0) pip install dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import datetime
from datetime import date
app = dash.Dash(__name__)
# App layout
app.layout = html.Div([
html.H1("Snodas SWE/SD For January", style={'text-align': 'center'}),
dcc.DatePickerSingle(
id='my-date-picker-single',
min_date_allowed=date(2020, 1, 1),
max_date_allowed=date(2020, 12, 30),
initial_visible_month=date(2020, 1, 1),
date=date(2020, 1, 1)
),
html.Div(id='output-container-date-picker-single'),
dcc.Checklist(
options=[
{'label': 'SWE', 'value': 'SWE'},
{'label': 'SD', 'value': 'SD'}
],
labelStyle={'display': 'inline-block'}
),
html.Iframe(id='map', srcDoc=open('map1.html', 'r').read(), width='100%', height='1000')
])
#app.callback(
Output('map', 'srcDoc'),
Input('my-date-picker-single', 'date'))
def update_output(date):
return open('map_swe_sd_{}.html'.format(str(date)), 'r').read()
if __name__ == "__main__":
app.run_server(debug = True)
Error Message
Try this:
#app.callback(
Output('map', 'srcDoc'),
Input('my-date-picker-single', 'date'))
def update_output(date):
if not date:
raise dash.exceptions.PreventUpdate
return open('map_swe_sd_{}.html'.format(str(date)), 'r').read()
I am new to all of this, so I hope I do this right and according to the conventional rules:
I had the same problem when I simply tried to do the dash tutorial on the dash website.
There was something wrong with my installation of dash or with my python environment (I know that "something wrong is not really an identification of the problem). It seems like this is similar in your case since the tracebacks point to packages, right? After creating and activating a new python environment, and installing dash there, everything worked.
I hope this might help you as well.

Import of Dash module alters .csv files

I've run into a strange behaviour when using the Dash library and I apologies in advance as I don't think I can't make an example which is easy to reproduce, so instead I will include all the information I think is relevant.
I was trying to create a small dashboard which loaded some data and then plotted it in a bar chart. The code I used for this is below (it is adapted from the Docs):
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import os.path as path
def find_unique_id(data, first_name, second_name, season):
name = first_name + '_' + second_name
data_filt = data[data['season'] == season]
data_filt = data_filt[data_filt['name'] == name]
print(data_filt['unique_id'])
return data_filt['unique_id'].iloc[0]
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
path_data = path.join(path.dirname(path.dirname(path.abspath(__file__))), 'Processed', 'player_database.csv')
data = pd.read_csv(path_data)
unique_id = []
unique_id.append(find_unique_id(data, 'Harry', 'Kane', 2020))
unique_id.append(find_unique_id(data, 'Mohamed', 'Salah', 2020))
unique_id.append(find_unique_id(data, 'Heung-Min', 'Son', 2020))
fig = px.bar(data[data['unique_id'].isin(unique_id)], x="round", y="points_mean3", color="name", barmode="group")
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure=fig
)
])
if __name__ == '__main__':
app.run_server(debug=True)
The player_database.csv is loaded and detailed in the picture (notice the file sizes):
However now whenever I import any Dash related module even in a different file, it changes all the files in this folder, and appears to role them back to an earlier state. For example when I run the following code, you can see the change in file size happening:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
This alters all the files in this directory (again as shown by the file size):
Does anyone know why this might be happening, has Dash got some kind of cache somewhere which loads the files it was working with from some previous state? I've tried googling and can't find anything on this.
Thanks

Send Alert Message For Invalid File Type Upload (Python)

I'm making a dashboard application, and I want to use dash_bootstrap_components to show an alert message when a user attempts to upload a file which isn't a CSV.
This is what I have right now.
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output
app.layout = html.Div(
[
html.H1(children=''),
# uploader
dcc.Upload(
id='upload-data',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files'),
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px'
},
# Allow multiple files to be uploaded
multiple=True
),
html.Div([
dbc.Alert(
"Unsuccessful Upload. Please make sure to upload a CSV file.",
id='alert_message',
color="warning",
dismissable=True,
is_open=False,
),
]),
]
)
#app.callback(Output('alert_message', 'is_open'),
[
Input('upload-data', 'filename'),
]
)
def is_valid(filename, is_open):
if 'csv' not in filename:
return not is_open
return is_open
When I run this, I get this error...
TypeError: is_valid() missing 1 required positional argument: 'is_open'
...and when I try to upload a file that is not a csv, no message is shown. How can I tweak this so that a user will see the alert message when they upload an inappropriate file?
Incidentally, I'm most likely going about checking the uploaded file type the wrong way. I looked up other methods for doing so, but they didn't seem to be compatible with using dbc alerts. If you know a better way of checking the file type, I'd love help with that too. But my main concern is getting the alert to show up.
Thanks in advance!

Unable to load DataTable with Dash 0.41

Since the version 0.41.0 of dash, the following code is on error :
import dash
from dash_table_experiments import DataTable
app = dash.Dash() app.layout = DataTable( id='datatable', rows=[{'V'+dash.__version__: i} for i in range(5)] )
app.run_server(debug=True)
whereas version 0.40.0 displays the table properly.
Would any one know what has changed ?
Thanks for your help ;
From the README file on the dash-table-experiements github page:
dash-table-experiments
DEPRECATED
If you are looking for a first class data table component for Dash head on over to https://github.com/plotly/dash-table and check out the documentation https://dash.plot.ly/datatable.
The component is no longer supported. The dash-table component works really well, though. Here is a basic example:
import dash
import numpy as np
import pandas
from dash_table import DataTable
app = dash.Dash()
df = pandas.DataFrame(np.arange(30).reshape(5, 6))
app.layout = DataTable(id='datatable',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict(orient='records'))
if __name__ == '__main__':
app.run_server(debug=True)

Categories