File size: 7,317 Bytes
9207866
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"""

FastAPI application for intent classification using fine-tuned Falcon AI model.

"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
from typing import List, Dict
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="Intent Classification API",
    description="API for classifying user intents using fine-tuned Falcon AI model",
    version="1.0.0"
)

# Global model and tokenizer
model = None
tokenizer = None
MODEL_PATH = "./finetuned_intent_falconsai"


class PredictionRequest(BaseModel):
    """Request model for intent prediction."""
    text: str = Field(..., description="Text to classify", min_length=1, max_length=512)
    return_all_scores: bool = Field(False, description="Return scores for all labels")


class PredictionResponse(BaseModel):
    """Response model for intent prediction."""
    text: str
    intent: str
    confidence: float
    all_scores: List[Dict[str, float]] = None


class BatchPredictionRequest(BaseModel):
    """Request model for batch predictions."""
    texts: List[str] = Field(..., description="List of texts to classify", max_items=100)
    return_all_scores: bool = Field(False, description="Return scores for all labels")


class HealthResponse(BaseModel):
    """Health check response."""
    model_config = {"protected_namespaces": ()}
    
    status: str
    model_loaded: bool


@app.on_event("startup")
async def load_model():
    """Load model and tokenizer on startup."""
    global model, tokenizer
    try:
        logger.info(f"Loading model from {MODEL_PATH}...")
        tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
        model = AutoModelForSequenceClassification.from_pretrained(MODEL_PATH)
        model.eval()  # Set to evaluation mode
        logger.info("Model loaded successfully!")
    except Exception as e:
        logger.error(f"Failed to load model: {str(e)}")
        raise


@app.get("/", response_model=HealthResponse)
async def root():
    """Root endpoint with basic health check."""
    return {
        "status": "online",
        "model_loaded": model is not None and tokenizer is not None
    }


@app.get("/health", response_model=HealthResponse)
async def health_check():
    """Health check endpoint."""
    return {
        "status": "healthy" if model is not None else "unhealthy",
        "model_loaded": model is not None and tokenizer is not None
    }


@app.post("/predict", response_model=PredictionResponse)
async def predict_intent(request: PredictionRequest):
    """

    Predict intent for a single text input.

    

    Args:

        request: PredictionRequest containing text and options

        

    Returns:

        PredictionResponse with predicted intent and confidence

    """
    if model is None or tokenizer is None:
        raise HTTPException(status_code=503, detail="Model not loaded")
    
    try:
        # Tokenize input
        inputs = tokenizer(
            request.text,
            return_tensors="pt",
            truncation=True,
            max_length=128,
            padding=True
        )
        
        # Get prediction
        with torch.no_grad():
            outputs = model(**inputs)
            logits = outputs.logits
            probabilities = torch.softmax(logits, dim=-1)[0]
            predicted_class = torch.argmax(logits, dim=-1).item()
        
        # Get predicted label and confidence
        predicted_label = model.config.id2label[predicted_class]
        confidence = probabilities[predicted_class].item()
        
        # Prepare response
        response = {
            "text": request.text,
            "intent": predicted_label,
            "confidence": confidence
        }
        
        # Add all scores if requested
        if request.return_all_scores:
            all_scores = [
                {
                    "label": model.config.id2label[i],
                    "score": probabilities[i].item()
                }
                for i in range(len(probabilities))
            ]
            all_scores.sort(key=lambda x: x["score"], reverse=True)
            response["all_scores"] = all_scores
        
        return response
        
    except Exception as e:
        logger.error(f"Prediction error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Prediction failed: {str(e)}")


@app.post("/predict/batch")
async def predict_batch(request: BatchPredictionRequest):
    """

    Predict intents for multiple texts in batch.

    

    Args:

        request: BatchPredictionRequest containing list of texts

        

    Returns:

        List of predictions

    """
    if model is None or tokenizer is None:
        raise HTTPException(status_code=503, detail="Model not loaded")
    
    if len(request.texts) == 0:
        raise HTTPException(status_code=400, detail="No texts provided")
    
    try:
        results = []
        
        # Process in batch
        inputs = tokenizer(
            request.texts,
            return_tensors="pt",
            truncation=True,
            max_length=128,
            padding=True
        )
        
        with torch.no_grad():
            outputs = model(**inputs)
            logits = outputs.logits
            probabilities = torch.softmax(logits, dim=-1)
            predicted_classes = torch.argmax(logits, dim=-1)
        
        # Build results
        for i, text in enumerate(request.texts):
            predicted_class = predicted_classes[i].item()
            predicted_label = model.config.id2label[predicted_class]
            confidence = probabilities[i][predicted_class].item()
            
            result = {
                "text": text,
                "intent": predicted_label,
                "confidence": confidence
            }
            
            if request.return_all_scores:
                all_scores = [
                    {
                        "label": model.config.id2label[j],
                        "score": probabilities[i][j].item()
                    }
                    for j in range(len(probabilities[i]))
                ]
                all_scores.sort(key=lambda x: x["score"], reverse=True)
                result["all_scores"] = all_scores
            
            results.append(result)
        
        return {"predictions": results}
        
    except Exception as e:
        logger.error(f"Batch prediction error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Batch prediction failed: {str(e)}")


@app.get("/labels")
async def get_labels():
    """Get all available intent labels."""
    if model is None:
        raise HTTPException(status_code=503, detail="Model not loaded")
    
    return {
        "labels": list(model.config.id2label.values()),
        "num_labels": len(model.config.id2label)
    }


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