Skip to content
All articles

Article

Globalizing Your Machine: Testing and Deploying AI Apps from Your Local Computer

My ML API grew to 2 GB and no free host could run it, so I served it from my own machine with FastAPI and ngrok, so teammates could test it from anywhere.

April 7, 2024 4 min read Originally on Medium
DeploymentFastAPIMachine learning

Introduction

Today, we aim to address a problem I recently encountered. The other day, I developed a Machine Learning (ML) model and integrated it into FastAPI for use in our system. I successfully built the API and included the model. However, I faced a significant issue — the API size ballooned to about 2GB!

Despite scouring the internet for free trial options, I found nothing suitable. Platforms like Render, Vercel, and Fly.io offer very limited resources, typically not exceeding 512MB RAM and less than 1GB CPU. Unfortunately, this wouldn’t suffice for my needs. All I wanted was to test the API and share it with other developers working on the application we’re building.

This led me to ponder: what if I could run this API on my localhost and share it with my colleagues while it’s running on my own device? Fortunately, I discovered a fantastic tool that takes your local domain and converts it to a global one. This means anyone can try your API, application, service, etc., until you decide to use a deploying service like AWS, Azure, Google Cloud, or any other platform.

Strategy

First, we’ll build an ML model for classification using the iris dataset from scikit-learn. We’ll train the model and save it. Then, we’ll integrate it into a FastAPI. This API will accept inputs for the model and return the classification result. After testing the model, we’ll utilize ngrok to make our local API accessible globally.

It’s important to note that when using ngrok, your device essentially functions as a cloud hosting instance for the API. As long as the API is running on your device, it will be accessible. However, each request consumes your device’s resources. Once you shut down your device, the API endpoint disappears. Therefore, your device needs to be powered on continuously while you’re publishing the API.

Of course, it’s not advisable to use this tool on your regular laptop or device for deployment. It’s primarily for testing purposes and to make it easier for non-developers to test your service without needing to download and run applications on their own machines. If you have a server, it’s preferable to deploy your service on it for stability and scalability.

Model Building

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
import joblib

# Load Iris dataset
iris = load_iris()
X = iris.data
y = iris.target

# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Feature scaling
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

# Create SVC classifier
classifier = SVC(kernel='linear', C=1, probability=True, random_state=42)

# Train the classifier
classifier.fit(X_train_scaled, y_train)

# Evaluate the classifier
accuracy = classifier.score(X_test_scaled, y_test)
print("Accuracy:", accuracy)

# Save the trained model
joblib.dump(classifier, 'iris_classifier.pkl')
Accuracy: 0.9666666666666667

After saving the weights of the model now it’s time for building the API!

API

This FastAPI application provides an interface for users to send input data related to Iris flowers, including features such as sepal length, sepal width, petal length, and petal width, and receive predictions of the corresponding flower’s class label based on a pre-trained classification model.

from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import numpy as np

# Load the saved model
classifier = joblib.load('iris_classifier.pkl')

# Create FastAPI app
app = FastAPI()

# Define input request body
class InputData(BaseModel):
    sepal_length: float
    sepal_width: float
    petal_length: float
    petal_width: float

# Define prediction endpoint
@app.post("/predict")
def predict(data: InputData):
    # Prepare input features for prediction
    input_features = np.array([[data.sepal_length, data.sepal_width, data.petal_length, data.petal_width]])
    
    # Make prediction
    prediction = classifier.predict(input_features)
    
    # Map prediction index to class label
    class_label = iris.target_names[prediction[0]]
    
    return {"prediction": class_label}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Let’s try an example

import requests

# Define input data
input_data = {
    "sepal_length": 5.1,
    "sepal_width": 3.5,
    "petal_length": 1.4,
    "petal_width": 0.2
}

# Send POST request to prediction endpoint
response = requests.post("http://127.0.0.1:8000/predict", json=input_data)

# Print the predicted class label
print("Predicted class label:", response.json()["prediction"])
Predicted class label: versicolor

Make the API Global

To install ngrok on your machine, please refer to their documentation, which provides excellent guidance.

We’re just one step away from our global API!

After installing the API and running it locally, navigate to the terminal or command line and enter the following command. Please ensure to use the correct port number; I used 8080 as it matches the port number of my API, but if you’re using a different port, make sure to update it accordingly.

ngrok http http://localhost:8080

You will see something similar to the following console UI in your terminal.

ngrok                                                                   (Ctrl+C to quit)

Session Status                online
Account                       inconshreveable (Plan: Free)
Version                       3.0.0
Region                        United States (us)
Latency                       78ms
Web Interface                 http://127.0.0.1:4040
Forwarding                    https://84c5df474.ngrok-free.dev -> http://localhost:8080

Connections                   ttl     opn     rt1     rt5     p50     p90
                              0       0       0.00    0.00    0.00    0.00

You can access the API by clicking on the domain name displayed next to “Forwarding.” Keep in mind that ngrok offers both free and premium subscriptions. If you wish to customize your domain and unlock additional benefits, you will need to subscribe to their premium plan.

And that’s it! You now have your own application or API accessible by anyone in the world.

If you found this article helpful, please consider liking it and following me for more interesting tutorials in the future.