प्री-ट्रेंड मॉडल के साथ FastAPI प्रेडिक्शन

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Matt Eckerle

Software and Data Engineering Leader

पर्यावरण सेटअप

जरूरी लाइब्रेरी:  

  • FastAPI: Python से API बनाने का फ्रेमवर्क
  • uvicorn: तेज ASGI सर्वर जो Python वेब ऐप चलाता है
  • joblib: मॉडल लोड करने के लिए

 

from fastapi import FastAPI
import uvicorn
import joblib
# Create the FastAPI app instance
app = FastAPI()
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

प्री-ट्रेंड पेंगुइन क्लासिफायर लोड करना

  • Palmer Penguins डेटासेट पर ट्रेन किया गया
  • 4 फीचर के आधार पर पेंगुइन प्रजाति प्रेडिक्ट करता है: culmen length, culmen depth, flipper length, और body mass
  • आउटपुट: Adelie, Chinstrap, या Gentoo
import joblib

# Load the pre-trained model
model = joblib.load('penguin_classifier.pkl')
# Check data type of model to verify model loading
print(type(model))
<class 'sklearn.pipeline.Pipeline'>
1 https://huggingface.co/SIH/penguin-classifier-sklearn
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Uvicorn

  • ASGI (Asynchronous Server Gateway Interface) सर्वर
  • Python द्वारा और Python के लिए बनाया गया
uvicorn main:app \
        --host 0.0.0.0 \
        --port 8080
import uvicorn
uvicorn.run(app, 
            host="0.0.0.0", 
            port=8080)

Uvicorn लोगो

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

प्रेडिक्शन एंडपॉइंट बनाना

# FastAPI prediction endpoint
@app.post("/predict")
def predict(culmen_length_mm, culmen_depth_mm, 
            flipper_length_mm, body_mass_g):

    features = [[culmen_length_mm, culmen_depth_mm,
                 flipper_length_mm, body_mass_g]]

    prediction = model.predict(features)[0]
    return {"predicted_species": prediction}
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

एप्लिकेशन चलाना

if __name__ == "__main__":
    uvicorn.run(
      app, 
      host="0.0.0.0", 
      port=8080)

सारा कोड एक Python फाइल में सेव करें - your_api_script.py

$ python3 your_api_script.py

Uvicorn स्टार्टअप लॉग

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

API का परीक्षण

curl \

-X POST "http://localhost:8080/predict" \
-H "Content-Type: application/json" \
-d '{"culmen_length_mm": 39.1, "culmen_depth_mm": 18.7, "flipper_length_mm": 181, "body_mass_g": 3750}'
{
    "prediction": "Adelie",
    "confidence": 0.87
}
FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

अभ्यास करते हैं!

FastAPI के साथ प्रोडक्शन में AI डिप्लॉय करना

Preparing Video For Download...