Upload Keras models or pickled files

Our current file_uplaoder is not able to upload machine learning models. Are you aware of any workaround?

model_path = st.file_uploader("Choose a h5 file", type="h5")
model = load_model(model_path)

This gets me this error:

unexpected type <class 'NoneType'> for filepath``

Any suggestions?

Hello @Abusnina,

It’s a bit odd that the error refers to a filepath that looks like it’s None but the variable is not in the snippet you provided, so I guess it’s in the load_model method…

Would you be able to provide a minimal reproducible example so we can dig into it ?

For those wondering how to upload a pre-trained keras model to a streamlit app, this might save you an afternoon of googling: :slight_smile:

import zipfile
import tempfile

stream = st.file_uploader('TF.Keras model file (.h5py.zip)', type='zip')
if stream is not None:
  myzipfile = zipfile.ZipFile(stream)
  with tempfile.TemporaryDirectory() as tmp_dir:
    myzipfile.extractall(tmp_dir)
    root_folder = myzipfile.namelist()[0] # e.g. "model.h5py"
    model_dir = os.path.join(tmp_dir, root_folder)
    #st.info(f'trying to load model from tmp dir {model_dir}...')
    model = tf.keras.models.load_model(model_dir)
6 Likes

Thanks a lot. You saved so much time. I owe you one.

Thanks, I owe you one too.