Spaces:
Sleeping
Sleeping
File size: 1,936 Bytes
2da18ee | 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 | from fastapi import FastAPI
from pydantic import BaseModel
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel
# -----------------------------
# Config
# -----------------------------
BASE_MODEL = "distilbert-base-uncased"
LORA_MODEL_PATH = "mjpsm/coca-cola-contact-classifier"
MAX_LENGTH = 128
id2label = {0: "not_relevant", 1: "relevant"}
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# -----------------------------
# Load model + tokenizer
# -----------------------------
tokenizer = AutoTokenizer.from_pretrained(LORA_MODEL_PATH)
base_model = AutoModelForSequenceClassification.from_pretrained(
BASE_MODEL,
num_labels=2
)
model = PeftModel.from_pretrained(base_model, LORA_MODEL_PATH)
model.to(device)
model.eval()
# -----------------------------
# FastAPI app
# -----------------------------
app = FastAPI(
title="Coca-Cola Contact Form Classifier",
description="LoRA-based text classification API",
version="1.0.0"
)
# -----------------------------
# Request schema
# -----------------------------
class PredictionRequest(BaseModel):
text: str
# -----------------------------
# Prediction endpoint
# -----------------------------
@app.post("/predict")
def predict(request: PredictionRequest):
inputs = tokenizer(
request.text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=MAX_LENGTH
).to(device)
with torch.no_grad():
outputs = model(**inputs)
probs = F.softmax(outputs.logits, dim=1)
confidence, pred_id = torch.max(probs, dim=1)
return {
"prediction": id2label[pred_id.item()],
"confidence": round(confidence.item(), 4)
}
# -----------------------------
# Health check
# -----------------------------
@app.get("/")
def health():
return {"status": "ok"}
|