Streamlit UploadFile

Hello. i need help with streamlit upload files. I’ve been building a project and while deploying it didn’t work as it did locally. here’s the problem.

I’m building an app to explain ml models. I need users to upload files as well as their models so my system can explain. but the problem is how this ML model can be uploaded and used directly without saving it first to a directory.

Summary: after uploading with file_uploader. how i can open this model file and use directly without saving it first to a directory.

been working on this for a few months now. so sad I got stuck here. it’s an abandoned project till I get help here. thanks

Hi @nelsonchristof
I understand your concern about uploading machine learning models directly in Streamlit without saving them to a directory first. To achieve this, you can use Python’s io.BytesIO to read the uploaded model file as bytes and then load it into memory using a machine learning library such as Scikit-learn or TensorFlow.

import streamlit as st
import io
import pickle  # If you're using Scikit-learn models
import tensorflow as tf  # If you're using TensorFlow models

Create a Streamlit file uploader to allow users to upload their model files:

uploaded_file = st.file_uploader("Upload your machine learning model file", type=["pkl", "h5"])

Check if a file has been uploaded:

if uploaded_file is not None:
    model_bytes = uploaded_file.read()

If you’re using Scikit-learn models (saved with pickle), you can load the model like this:

    model = pickle.load(io.BytesIO(model_bytes))
    # Now you can use the 'model' variable for predictions or explanations

If you’re using TensorFlow models, you can load the model like this:

    model = tf.keras.models.load_model(io.BytesIO(model_bytes))
    # Now you can use the 'model' variable for predictions or explanations

I hope this will solve your problem. Thank you