Spaces:
Sleeping
Sleeping
Eric Dyke commited on
Commit ·
f77de7e
1
Parent(s): a92cf10
Initialize ML API Frontend project with Streamlit
Browse filesAdd main Streamlit app in streamlit_app.py
Include requirements.txt for dependencies
Add Dockerfile for containerization
Provide README.md with usage instructions and project structure
Change:
Update Docker container port to 7860 for Hugging Face Spaces compatibility
Files changed (5)
- .gitignoreAdded+90
- Dockerfile+6-3
- README.md+40-10
- requirements.txt+2-2
- src/streamlit_app.py+87-34
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# pipenv
Pipfile.lock
# poetry
poetry.lock
# mypy
.mypy_cache/
.dmypy.json
# Pyre type checker
.pyre/
# pyright
.pyright/
# VS Code
.vscode/
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Streamlit
# .streamlit/
# Local files
*.local
# MacOS
.DS_Store
# Windows
Thumbs.db
# Documentation
docs/12 unmodified lines131415161718192012 unmodified linesRUN pip3 install -r requirements.txtEXPOSE 8501HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/healthENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]12 unmodified lines131415161718192021222312 unmodified linesRUN pip3 install -r requirements.txt# IMPORTANT: Hugging Face uses port 7860EXPOSE 7860# Updated healthcheck for the new portHEALTHCHECK CMD curl --fail http://localhost:7860/_stcore/health# Updated ENTRYPOINT with port 7860 and XSRF/CORS flagsENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false", "--server.enableCORS=false"]
3 unmodified lines45678910111213141516171819203 unmodified linescolorFrom: redcolorTo: redsdk: dockerapp_port: 8501tags:- streamlitpinned: falseshort_description: Streamlit frontend for ML-APIlicense: apache-2.0---# Welcome to Streamlit!Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).3 unmodified lines45678910111213141516171819202122232425262728293031323334353637383940414243444546474849503 unmodified linescolorFrom: redcolorTo: redsdk: dockerapp_port: 7860---# ML API FrontendThis repository contains a Streamlit application that serves as the frontend interface for interacting with a machine learning API.## Features- User-friendly web interface built with Streamlit- Connects to a backend ML API for predictions or data processing- Easy to deploy and extend for various ML use cases## Getting Started1. Clone the repository:```bashgit clone https://huggingface.co/spaces/HighFive52/ML-API-Frontend```2. Install dependencies:```bashpip install -r requirements.txt```3. Run the app:```bashstreamlit run app.py```## Project Structure- `src/streamlit_app.py` — Main Streamlit application## Available APIsThis Streamlit app can interact with the following APIs:- **Spaceship Titanic API:**- `SPACESHIP_API_URL = "https://HighFive52-ml-api.hf.space/spaceship-titanic/predict"`- **Digit Recognizer API:**- `DIGITS_API_URL = "https://HighFive52-ml-api.hf.space/digit-recognizer/predict"`## Requirements- Python 3.7+- Streamlit- Other dependencies as listed in `requirements.txt`## LicenseThis project is licensed under the MIT License.
123altairpandasstreamlit123streamlitaltairpandas
12345678910111213141516171819202122232425262728293031323334353637383940import altair as altimport numpy as npimport pandas as pdimport streamlit as st"""# Welcome to Streamlit!Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [communityforums](https://discuss.streamlit.io).In the meantime, below is an example of what you can do with just a few lines of code:"""num_points = st.slider("Number of points in spiral", 1, 10000, 1100)num_turns = st.slider("Number of turns in spiral", 1, 300, 31)indices = np.linspace(0, 1, num_points)theta = 2 * np.pi * num_turns * indicesradius = indicesx = radius * np.cos(theta)y = radius * np.sin(theta)df = pd.DataFrame({"x": x,"y": y,"idx": indices,"rand": np.random.randn(num_points),})st.altair_chart(alt.Chart(df, height=700, width=700).mark_point(filled=True).encode(x=alt.X("x", axis=None),y=alt.Y("y", axis=None),color=alt.Color("idx", legend=None, scale=alt.Scale()),size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import streamlit as stimport requestsimport pandas as pdimport osst.title("ML Model Prediction Interface")# App descriptionst.write("""This Streamlit app demonstrates how to build an interactive interface that communicates with a machine learning prediction API. The primary goal is to provide an example of integrating a UI with an API for ML predictions—not to serve as a tool for quickly generating Kaggle competition submission files.""")st.write("Upload a CSV file to get predictions from the API.")# Use environment variables if present, otherwise default to local URLsSPACESHIP_API_URL = os.environ.get("SPACESHIP_API_URL", "http://127.0.0.1:8000/spaceship-titanic/predict")DIGITS_API_URL = os.environ.get("DIGITS_API_URL", "http://127.0.0.1:8000/digit-recognizer/predict")model_options = {"Spaceship Titanic": SPACESHIP_API_URL,"Digit Recognizer": DIGITS_API_URL,}# Track selected model in session stateif "selected_model" not in st.session_state:st.session_state.selected_model = list(model_options.keys())[0]def on_model_change():st.session_state.uploaded_file_key += 1# Track file_uploader key in session stateif "uploaded_file_key" not in st.session_state:st.session_state.uploaded_file_key = 0selected_model = st.selectbox("Select Prediction Model",options=list(model_options.keys()),index=list(model_options.keys()).index(st.session_state.selected_model),on_change=on_model_change,key="selected_model",)API_URL = model_options[selected_model]uploaded_file = st.file_uploader("Choose a CSV file",type=["csv"],key=f"file_uploader_{st.session_state.uploaded_file_key}",)if uploaded_file is not None:# Show preview of uploaded CSV fileuploaded_file.seek(0)df = pd.read_csv(uploaded_file)st.write("Preview of uploaded file:")st.dataframe(df.head())# Reset file pointer and send to APIuploaded_file.seek(0)files = {"file": (uploaded_file.name, uploaded_file, "text/csv")}with st.spinner("Getting predictions from API..."):headers = {"User-Agent": "streamlit-hf-space/1.0"}try:response = requests.post(API_URL, files=files, headers=headers)except Exception as e:st.error(f"Request failed: {e}")st.stop()if response.status_code == 200:result = response.json()result_df = pd.DataFrame(result)st.success("Predictions received!")st.dataframe(result_df)if set(["PassengerId", "blend_pred"]).issubset(result_df.columns):download_df = result_df[["PassengerId", "blend_pred"]].rename(columns={"PassengerId": "PassengerId", "blend_pred": "Transported"})else:download_df = result_dfcsv = download_df.to_csv(index=False).encode("utf-8")st.download_button("Download Predictions as CSV", csv, "predictions.csv", "text/csv")else:st.warning("The uploaded file likely did not match the expected format for the selected model, or the API is blocking the request. Please check your file, model selection, and API configuration.")
.gitignoreAdded+90
Dockerfile+6-3
README.md+40-10
requirements.txt+2-2
src/streamlit_app.py+87-34