রোডম্যাপ
PHASE 8 · অধ্যায় 37

NLP API ডেভেলপমেন্ট

NLP API Development (FastAPI)

Model কে API আকারে expose করা।

ভূমিকা

আপনার NLP model GPU তে train হলো, Jupyter notebook এ test হলো — কিন্তু production এ কেউ ব্যবহার করতে পারছে না। কারণ model কে API আকারে expose না করলে frontend, mobile app, অন্য service — কেউ access করতে পারে না। FastAPI দিয়ে একটা ML model কে production-ready REST API বানানো যায় কয়েক ঘণ্টায়।

ধারণা

FastAPI একটি modern, fast (Starlette + Pydantic এর উপর built), async-first Python web framework। Type hint দিয়ে automatic request validation, OpenAPI/Swagger docs, dependency injection। ML/NLP context এ FastAPI standard — model load হয় startup এ, request এ inference, response JSON এ। CORS, auth, rate limit middleware সহজে যোগ করা যায়।

সহজ ব্যাখ্যা

ভাবুন আপনার model একটা restaurant এর chef — সে রান্না করতে পারে, কিন্তু waiter (API) ছাড়া customer (user) কীভাবে order দেবে? FastAPI ই সেই waiter — request নেয়, model কে দেয়, response সুন্দর করে customer এ ফেরত। Type hint hole menu — কী input দিতে হবে, কী output পাবে — সব documented।

বাস্তব ব্যবহার

  • HuggingFace Inference API — FastAPI পেছনে।
  • OpenAI API — সব major NLP service এই pattern এ।
  • Internal ML service — Uber, Netflix, Spotify।
  • Whisper, Stable Diffusion এর community deployment।
  • RAG application backend।

ধাপে ধাপে বিশ্লেষণ

1
Step 1 — Install
pip install fastapi uvicorn pydantic transformers।
2
Step 2 — Model load (startup)
Global scope এ একবার, প্রতি request এ না।
3
Step 3 — Request schema
Pydantic BaseModel দিয়ে input validation।
4
Step 4 — Endpoint define
@app.post('/predict') decorator।
5
Step 5 — Response model
Output ও Pydantic দিয়ে typed।
6
Step 6 — Run
uvicorn main:app --reload — auto docs /docs এ।

Python কোড

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from transformers import pipeline
from typing import List
import time

app = FastAPI(title="NLP Service", version="1.0.0")

classifier = pipeline("sentiment-analysis")

class PredictRequest(BaseModel):
    texts: List[str] = Field(..., min_length=1, max_length=32)

class Prediction(BaseModel):
    text: str
    label: str
    score: float

class PredictResponse(BaseModel):
    predictions: List[Prediction]
    latency_ms: float

@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/predict", response_model=PredictResponse)
def predict(req: PredictRequest):
    if any(len(t.strip()) == 0 for t in req.texts):
        raise HTTPException(status_code=400, detail="Empty text not allowed")

    start = time.time()
    raw = classifier(req.texts)
    elapsed = (time.time() - start) * 1000

    return PredictResponse(
        predictions=[
            Prediction(text=t, label=r["label"], score=r["score"])
            for t, r in zip(req.texts, raw)
        ],
        latency_ms=round(elapsed, 2),
    )

# Run: uvicorn main:app --reload --host 0.0.0.0 --port 8000
# Docs: http://localhost:8000/docs
ব্যাখ্যা

FastAPI app create, classifier global এ load (একবার, fast)। PredictRequest/Response Pydantic model — input/output validation + OpenAPI schema। /health endpoint Kubernetes/Docker এ readiness check। /predict batch text accept করে, latency সহ response।

সাধারণ ভুল

  • প্রতি request এ model load — extremely slow।
  • Pydantic validation skip — invalid input এ crash।
  • Sync endpoint এ heavy work — event loop block।
  • CORS middleware ভুলে যাওয়া — browser থেকে call fail।
  • Error handling নেই — internal exception 500 হয়ে যায়।

অনুশীলন

  1. Async endpoint বানান (async def) এবং compare।
  2. CORS middleware add করুন (CORSMiddleware)।
  3. API key auth middleware লিখুন।
  4. Multiple model endpoint (sentiment + NER + summary)।

ছোট প্রজেক্ট

Multi-Model NLP API

FastAPI দিয়ে 3টা endpoint: /sentiment, /ner, /summarize। প্রতিটার Pydantic input/output schema, /health endpoint, automatic Swagger docs। Postman বা curl দিয়ে test করুন।

সারাংশ

  • FastAPI = modern Python NLP API framework।
  • Type hint + Pydantic = auto validation + docs।
  • Model load startup এ (global), inference per-request।
  • Async, middleware, dependency injection — production-grade।
  • ML deployment এর de facto Python framework।