Spaces:
Sleeping
Sleeping
Eric Dyke commited on
Commit ·
0de3c15
1
Parent(s): 16a46a6
FastAPI ML API for Spaceship Titanic and Digit Recognition
Browse files- FastAPI app with modular routers for spaceship survival prediction and digit recognition
- Model loading for PyTorch and scikit-learn/xgboost/lightgbm models
- In-memory and file-based API testing with pytest and TestClient
- Pre-commit hook for Black formatting
- GitHub Actions workflow for linting
- Documentation and example test data include
Files changed (18)
- .github/workflows/python-lint.ymlAdded+31
- .gitignoreAdded+131
- .pre-commit-config.yamlAdded+8
- DockerfileAdded+17
- app.pyAdded+44
- docs/documentation.mdAdded+167
- ml/common/model_loader.pyAdded+37
- ml/digits/mnist_model.pyAdded+45
- ml/spaceship/spaceship_transformers.pyAdded+158
- models/digit_recognizer/mnist_checkpoint.pthAdded+3
- models/spaceship/hgb_tuned.pklAdded+3
- models/spaceship/lgbm_tuned.pklAdded+3
- models/spaceship/xgb_tuned.pklAdded+3
- requirements.txtAdded+13
- routers/digits.pyAdded+38
- routers/spaceship.pyAdded+40
- static/favicon.icoAdded
- tests/test_api_pytest.pyAdded+42
12345678910111213141516171819202122232425262728293031name: Python Lint
on:
push:
branches:
- "**"
pull_request:
branches:
- "**"
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.12'
- name: Upgrade pip
run: python -m pip install --upgrade pip
- name: Install Black
run: python -m pip install black==26.1.0
- name: Run Black
run: black --check .123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# 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
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# 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/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
/docs/_build/
# PyBuilder
.target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
Pipfile.lock
# poetry
poetry.lock
# PDM
pdm.lock
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# VS Code
.vscode/12345678# .pre-commit-config.yaml
repos:
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
language_version: python3.12
files: '\.py$'1234567891011121314151617# Read the doc: https://huggingface.co/docs/hub/spaces-sdks-docker
# you will also find guides on how best to write your Dockerfile
FROM python:3.12
RUN useradd -m -u 1000 user
USER user
ENV PATH="/home/user/.local/bin:$PATH"
WORKDIR /app
COPY --chown=user ./requirements.txt requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
COPY --chown=user ./app.py app.py
COPY --chown=user ./requirements.txt requirements.txt
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]1234567891011121314151617181920212223242526272829303132333435363738394041424344from fastapi import FastAPI
from pathlib import Path
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from routers import spaceship, digits
from ml.common.model_loader import load_spaceship_models, load_digit_model
import joblib
app = FastAPI()
BASE_DIR = Path(__file__).resolve().parent
print(f"Base directory: {BASE_DIR}")
models_dir = BASE_DIR / "models"
print(f"Models directory: {models_dir}")
joblib.load("models/spaceship/xgb_tuned.pkl")
# Load models
tuned_models = load_spaceship_models(models_dir)
digit_model = load_digit_model(models_dir)
# Inject into routers
spaceship.set_models(tuned_models)
digits.set_digit_model(digit_model)
# Register routers
app.include_router(spaceship.router)
app.include_router(digits.router)
# Mount static directory for favicon
app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
# Serve favicon.ico at root
@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
return FileResponse(BASE_DIR / "static" / "favicon.ico")
@app.get("/health")
def health():
return {"status": "ok"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167## Pre-commit Hooks
This project uses [pre-commit](https://pre-commit.com/) to automatically check and format code before each commit.
### Setup
1. Install pre-commit if you haven't already:
```powershell
pip install pre-commit
```
2. Install the git hook scripts:
```powershell
pre-commit install
```
3. Now, every time you run `git commit`, pre-commit will automatically run Black (and any other configured hooks) on your code.
### Configuration
The configuration is in `.pre-commit-config.yaml`. Example for Black:
```yaml
repos:
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
language_version: python3.12
files: '\.py$'
```
### Manually Run All Hooks
You can manually run all pre-commit hooks on all files with:
```powershell
pre-commit run --all-files
```
# ML API Project Documentation
## Project Structure
```
ml-api/
│
├── app.py # Main FastAPI application entry point
├── Dockerfile # Docker configuration
├── requirements.txt # Python dependencies
├── README.md # Project overview
├── .gitignore # Git ignore rules
│
├── ml/ # Machine learning code
│ ├── common/
│ │ └── model_loader.py
│ ├── digits/
│ │ └── mnist_model.py
│ └── spaceship/
│ └── spaceship_transformers.py
│
├── models/ # Saved model files
│ ├── digit_recognizer/
│ │ └── mnist_checkpoint.pth
│ └── spaceship/
│ ├── hgb_tuned.pkl
│ ├── lgbm_tuned.pkl
│ └── xgb_tuned.pkl
│
├── routers/ # FastAPI routers
│ ├── digits.py
│ └── spaceship.py
│
├── tests/ # Tests and test data
│ ├── test_api.py
│ └── data/
│ ├── test_digits.csv
│ └── test_spaceship.csv
│
└── docs/
└── documentation.md # This file
```
## How to Start the API Locally
1. **Activate your virtual environment**
```powershell
.venv\Scripts\Activate.ps1
```
2. **Install dependencies**
```powershell
pip install -r requirements.txt
```
3. **Start the API server**
```powershell
uvicorn app:app --reload
```
The server will start at [http://127.0.0.1:8000](http://127.0.0.1:8000)
4. **Test the API**
- Swagger UI: [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)
- Redoc: [http://127.0.0.1:8000/redoc](http://127.0.0.1:8000/redoc)
## API Endpoints
- `/digit-recognizer/predict` (POST): Upload a CSV of digit images (flattened 28x28) to get predictions.
- `/spaceship-titanic/predict` (POST): Upload a CSV of spaceship passenger data to get survival predictions.
- `/health` (GET): Health check endpoint.
## Model and Transformer Notes
- Custom transformers for Spaceship Titanic are in `ml/spaceship/spaceship_transformers.py`.
- The digit recognizer model is defined in `ml/digits/mnist_model.py`.
- Model loading logic is in `ml/common/model_loader.py`.
- Saved models are in the `models/` directory.
## Testing
- Test scripts and sample data are in the `tests/` folder.
### How to Run Tests
1. Make sure you have all dependencies installed:
```powershell
pip install -r requirements.txt
pip install pytest httpx
```
2. Run the tests from the project root with the correct Python path:
```powershell
$env:PYTHONPATH="."; pytest
```
This ensures that your app and modules are correctly imported during testing.
3. All tests in the `tests/` folder will be discovered and executed automatically.
## Updating Models or Transformers
If you change or add custom transformers or functions:
- Update both your training code and API code to import them from the same file (e.g., `ml/spaceship/spaceship_transformers.py`).
- Retrain and re-save your models so the references are correct.
## Docker
To build and run the API with Docker:
```powershell
docker build -t ml-api .
docker run -p 8000:8000 ml-api
```
---
For more details, see the README.md.12345678910111213141516171819202122232425262728293031323334353637import joblib
import os
import torch
from ml.spaceship.spaceship_transformers import (
LogicalImputeTransformer,
FeatureEngineer,
Log1pTransformer,
to_str,
)
from ml.digits.mnist_model import MNISTModel
def load_spaceship_models(models_dir):
tuned_models = {}
model_names = ["xgb_tuned", "lgbm_tuned", "hgb_tuned"]
for name in model_names:
path = os.path.join(models_dir, "spaceship", f"{name}.pkl")
tuned_models[name] = joblib.load(path)
return tuned_models
def load_digit_model(models_dir):
checkpoint = torch.load(
os.path.join(models_dir, "digit_recognizer", "mnist_checkpoint.pth"),
map_location="cpu",
)
model = MNISTModel(dropout_rate=checkpoint["dropout"])
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
return model123456789101112131415161718192021222324252627282930313233343536373839404142434445import torch
import torch.nn as nn
class MNISTModel(nn.Module):
def __init__(self, dropout_rate=0.3):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
self.bn2 = nn.BatchNorm2d(64)
self.pool = nn.MaxPool2d(2, 2)
self.relu = nn.ReLU()
self.dropout = nn.Dropout(dropout_rate)
self.fc1 = nn.Linear(64 * 7 * 7, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
# Block 1
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.pool(x)
# Block 2
x = self.conv2(x)
x = self.bn2(x)
x = self.relu(x)
x = self.pool(x)
# Flatten
x = torch.flatten(x, 1)
# Fully connected
x = self.fc1(x)
x = self.relu(x)
x = self.dropout(x)
x = self.fc2(x)
return x123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
def to_str(X):
return X.astype(str)
class LogicalImputeTransformer(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
X = pd.DataFrame(X)
self.columns_ = X.columns
return self
def transform(self, X):
X = pd.DataFrame(X).copy()
# Impute missing values for Cabin and Name with logical defaults
X["Cabin"] = X["Cabin"].fillna("Unknown/0/U")
X["Name"] = X["Name"].fillna("Unknown Unknown")
spend_cols = ["RoomService", "FoodCourt", "ShoppingMall", "Spa", "VRDeck"]
# Rule 1: CryoSleep NaN + zero spending → CryoSleep = 1
cond_null = X["CryoSleep"].isnull()
cond_zero_spend = X[spend_cols].sum(axis=1) == 0
rule1 = cond_null & cond_zero_spend
X.loc[rule1, "CryoSleep"] = 1
# Rule 2: CryoSleep NaN + any spending > 0 → CryoSleep = 0
cond_null = X["CryoSleep"].isnull()
cond_spend = X[spend_cols].sum(axis=1) > 0
rule2 = cond_null & cond_spend
X.loc[rule2, "CryoSleep"] = 0
# Rule 3: CryoSleep = 1 + spending NaN → spending = 0
cond_cryo_true = X["CryoSleep"] == 1
for col in spend_cols:
X.loc[cond_cryo_true, col] = X.loc[cond_cryo_true, col].fillna(0)
return X
def get_feature_names_out(self, input_features=None):
return np.array(self.columns_)
class FeatureEngineer(BaseEstimator, TransformerMixin):
NUMERIC_FEATURES = [
"Age",
"GroupSize",
"IsAlone",
"TotalSpend",
"LuxurySpend",
"BasicSpend",
"SpendVariance",
"IsAwakeZeroSpender",
]
ORDINAL_FEATURES = ["Cabin_Num_Binned", "AgeBin"]
CATEGORICAL_FEATURES = [
"Deck",
"Side",
"CryoSleep",
"VIP",
"HomePlanet",
"Destination",
]
OUTPUT_FEATURES = NUMERIC_FEATURES + ORDINAL_FEATURES + CATEGORICAL_FEATURES
def fit(self, X, y=None):
cabin_split = X["Cabin"].str.split("/", expand=True)
cabin_num = pd.to_numeric(cabin_split[1], errors="coerce")
# store bin edges
self.cabin_bins_ = pd.qcut(cabin_num, q=3, retbins=True, duplicates="drop")[1]
return self
def transform(self, X):
X = X.copy().reset_index(drop=True)
# 2.1 PassengerId features
# Extract GroupId and IndividualId from PassengerId and calculate GroupSize
X["GroupId"] = X["PassengerId"].str[:4]
X["IndividualId"] = X["PassengerId"].str[5:].astype(int)
X["GroupSize"] = (
X.groupby("GroupId")["IndividualId"].transform("max").to_numpy()
)
# 2.1 Cabin features
# Create IsAlone feature based on GroupSize
X["IsAlone"] = (X["GroupSize"] == 1).astype(int).to_numpy()
# Split Cabin into Deck and Side
cabin_split = X["Cabin"].str.split("/", expand=True)
X["Deck"] = cabin_split[0].to_numpy()
X["Cabin_Num"] = pd.to_numeric(cabin_split[1], errors="coerce")
X["Side"] = cabin_split[2].to_numpy()
X["Cabin_Num_Binned"] = pd.cut(
X["Cabin_Num"],
bins=self.cabin_bins_,
labels=["Low", "Mid", "High"][: len(self.cabin_bins_) - 1],
include_lowest=True,
)
# 2.3 Name features
X["LastName"] = X["Name"].str.split(" ").str[1]
X["FamilySize"] = X.groupby("LastName")["LastName"].transform("count")
# 2.4 Age features
# Age bins
X["AgeBin"] = pd.cut(
X["Age"],
bins=[0, 12, 17, 25, 65, 200],
labels=["Child", "Teen", "YoungAdult", "Adult", "Senior"],
include_lowest=True,
)
# 2.5 Spend features
# Create CombinedServices as the sum of RoomService, FoodCourt, ShoppingMall, Spa, and VRDeck
spend_cols = ["RoomService", "FoodCourt", "ShoppingMall", "Spa", "VRDeck"]
X["TotalSpend"] = X[spend_cols].sum(axis=1)
X["BasicSpend"] = X[["FoodCourt", "ShoppingMall"]].sum(axis=1)
X["LuxurySpend"] = X[["RoomService", "Spa", "VRDeck"]].sum(axis=1)
X["SpendVariance"] = X[spend_cols].var(axis=1)
X["IsAwakeZeroSpender"] = (
(X["CryoSleep"] == False) & (X["TotalSpend"] == 0)
).astype(int)
return X[self.OUTPUT_FEATURES]
class Log1pTransformer(BaseEstimator, TransformerMixin):
def fit(self, X, y=None):
X = pd.DataFrame(X)
self.columns_ = X.columns
skew_vals = X.skew().abs()
self.skewed_cols_ = skew_vals[skew_vals > 2.0].index.tolist()
return self
def transform(self, X):
X = pd.DataFrame(X).copy()
for col in self.skewed_cols_:
X[col] = np.log1p(np.clip(X[col], 0, None))
return X.to_numpy()
def get_feature_names_out(self, input_features=None):
return np.array(self.columns_)123version https://git-lfs.github.com/spec/v1oid sha256:b517a1a4edc9f83062903a64903f947eb22b2ccfec9d26e915898a6e259ac344size 1694597123version https://git-lfs.github.com/spec/v1oid sha256:7f2d146cb7b0b4297c2229c127c0c3d9ffa7ab4b98b69699b47bafb2160d23c7size 936594123version https://git-lfs.github.com/spec/v1oid sha256:76bf96f18173902d3073c60c1008ea9bdd7ad5e0989897cb7b4aa78b0cbd66e1size 900449123version https://git-lfs.github.com/spec/v1oid sha256:faaa91e438282a3ee57d2d3540343f9cb216d2d1274c2136421b04f4874a5f21size 231024712345678910111213fastapi==0.136.1
torch==2.11.0
numpy==2.4.4
pandas==3.0.2
requests==2.33.1
joblib==1.5.3
scikit-learn==1.8.0
python-multipart==0.0.27
xgboost==3.2.0
lightgbm==4.6.0
pytest==9.0.3
httpx==0.28.1
black==26.3.11234567891011121314151617181920212223242526272829303132333435363738from fastapi import APIRouter, HTTPException, UploadFile, File
import io
import pandas as pd
import numpy as np
import torch
from typing import List
router = APIRouter(prefix="/digit-recognizer", tags=["Digit Recognizer"])
def set_digit_model(model):
router.model = model
@router.post("/predict")
async def predict_digits_csv(file: UploadFile = File(...)):
try:
contents = await file.read()
# Read CSV into DataFrame
df = pd.read_csv(io.StringIO(contents.decode("utf-8")))
# Each row is a flattened 28x28 image
images = df.values.astype(np.float32).reshape(-1, 1, 28, 28)
tensor = torch.tensor(images)
model = router.model
with torch.no_grad():
outputs = model(tensor)
preds = outputs.argmax(dim=1).tolist()
# Add ImageID (row number starting from 1) and Label (predicted digit)
result_df = pd.DataFrame(
{"ImageID": list(range(1, len(preds) + 1)), "Label": preds}
)
return result_df.to_dict(orient="list")
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))12345678910111213141516171819202122232425262728293031323334353637383940from fastapi import APIRouter, UploadFile, File, HTTPException
import pandas as pd
from io import StringIO
router = APIRouter(prefix="/spaceship-titanic", tags=["Spaceship Titanic"])
def set_models(models):
router.models = models
@router.post("/predict")
async def predict(file: UploadFile = File(...)):
try:
contents = await file.read()
df = pd.read_csv(StringIO(contents.decode("utf-8")))
models = router.models
xgb_proba = models["xgb_tuned"].predict_proba(df)[:, 1]
lgbm_proba = models["lgbm_tuned"].predict_proba(df)[:, 1]
hgb_proba = models["hgb_tuned"].predict_proba(df)[:, 1]
blend_proba = (xgb_proba + lgbm_proba + hgb_proba) / 3
blend_pred = (blend_proba >= 0.5).astype(bool)
passenger_ids = (
df["PassengerId"].tolist()
if "PassengerId" in df.columns
else list(range(len(blend_pred)))
)
return {
"PassengerId": passenger_ids,
"blend_proba": blend_proba.tolist(),
"blend_pred": blend_pred.tolist(),
}
except Exception as e:
raise HTTPException(status_code=400, detail=str(e))123456789101112131415161718192021222324252627282930313233343536373839404142import pytest
from fastapi.testclient import TestClient
from app import app
import io
client = TestClient(app)
@pytest.mark.parametrize(
"endpoint,csv_content,filename",
[
(
"/spaceship-titanic/predict",
# Minimal valid spaceship CSV (adjust columns as needed for your model)
"PassengerId,Cabin,Name,Age,RoomService,FoodCourt,ShoppingMall,Spa,VRDeck,CryoSleep,VIP,HomePlanet,Destination\n"
"0001_01,B/0/S,John Doe,30,0,0,0,0,0,0,0,Earth,Mars\n",
"test_spaceship.csv",
),
(
"/digit-recognizer/predict",
# Minimal valid digit recognizer CSV (flattened 28x28 = 784 columns)
",".join([f"pixel{i+1}" for i in range(784)])
+ "\n"
+ ",".join(["0"] * 784)
+ "\n",
"test_digits.csv",
),
],
)
def test_api_endpoints(endpoint, csv_content, filename):
file = io.BytesIO(csv_content.encode("utf-8"))
response = client.post(endpoint, files={"file": (filename, file, "text/csv")})
assert response.status_code == 200
result = response.json()
assert isinstance(result, dict)
assert len(result) > 0
def test_health():
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}.github/workflows/python-lint.ymlAdded+31
.gitignoreAdded+131
.pre-commit-config.yamlAdded+8
DockerfileAdded+17
app.pyAdded+44
docs/documentation.mdAdded+167
ml/common/model_loader.pyAdded+37
ml/digits/mnist_model.pyAdded+45
ml/spaceship/spaceship_transformers.pyAdded+158
models/digit_recognizer/mnist_checkpoint.pthAdded+3
models/spaceship/hgb_tuned.pklAdded+3
models/spaceship/lgbm_tuned.pklAdded+3
models/spaceship/xgb_tuned.pklAdded+3
requirements.txtAdded+13
routers/digits.pyAdded+38
routers/spaceship.pyAdded+40
static/favicon.icoAdded
tests/test_api_pytest.pyAdded+42