A demonstration of how a model can be built into an API and deployed on a cloud service, for beginners.
This repository demonstrates how to build a machine learning model into an API and deploy it on various cloud services. The project uses a Hugging Face opinion mining model, Flask for API creation, and Docker for containerization.
Dockerfile
: Contains instructions for building the Docker image.app.py
: Contains Flask APIs that interacts with the machine learning model.model.py
: Contains the Hugging Face model.requirements.txt
: Contains the necessary Python dependencies.Install the necessary dependencies:
pip install -r requirements.txt
Build the Docker image:
docker build -t model-api .
Run the Docker container:
docker run -p 5000:5000 model-api
The API should now be accessible at http://localhost:5000
.
The API endpoint is /feedback
and it accepts POST requests. The request body should be a JSON object with a text
field containing the text to analyze.
You can use the requests
library in Python to send a POST request:
import requests
import json
url = "http://localhost:5000/feedback"
data = {"text": "Your text here"}
response = requests.post(url, data=json.dumps(data))
print(response.json())
Alternatively, you can use cURL to send a POST request from the command line:
curl -X POST -H "Content-Type: application/json" -d '{"text":"Your text here"}' http://localhost:5000/feedback
Build the Docker image and push it to Google Container Registry (GCR):
gcloud builds submit --tag gcr.io/PROJECT-ID/model-api
Deploy the image to Cloud Run:
gcloud run deploy --image gcr.io/PROJECT-ID/model-api --platform managed
Create a Docker run configuration file named Dockerrun.aws.json
.
Initialize your Elastic Beanstalk environment:
eb init -p docker your-app-name
Create an environment and deploy your application:
eb create your-env-name
Create a Docker image and push it to Docker Hub or Azure Container Registry (ACR).
Create a new App Service on Azure portal.
In the Deployment Center, choose Docker Container for the source and select the Docker image you pushed.
Click on Run API and your API should be live.
Please refer to the official documentation of each cloud service for more detailed instructions and troubleshooting. Each service has ways to attach domains.
To secure your API, you can implement API key authentication. This involves modifying your Flask application to require an API key with each request.
Here's a simple example of how you can do this:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/feedback', methods=['POST'])
def feedback():
api_key = request.headers.get('X-API-KEY')
if not api_key or api_key != 'YOUR_API_KEY':
return jsonify({'message': 'Invalid API Key'}), 403
# Your existing code here...
if __name__ == '__main__':
app.run(debug=True)
Again, each cloud service has functionalities for managing API keys.