from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse from pydantic import BaseModel from transformers import AutoTokenizer, AutoModelForSequenceClassification import torch import torch.nn.functional as F import os # Load model and tokenizer from local files MODEL_DIR = "./" tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR) model = AutoModelForSequenceClassification.from_pretrained(MODEL_DIR) model.eval() # FastAPI app app = FastAPI() # Serve index.html when visiting root @app.get("/", response_class=HTMLResponse) def serve_index(): with open("index.html", "r") as f: return f.read() # Request body model class TextRequest(BaseModel): text: str # Predict endpoint @app.post("/predict") def predict(request: TextRequest): inputs = tokenizer(request.text, return_tensors="pt", truncation=True, padding=True, max_length=512) with torch.no_grad(): logits = model(**inputs).logits probs = F.softmax(logits, dim=-1).squeeze() topk = torch.topk(probs, k=5) indices = topk.indices.tolist() scores = topk.values.tolist() # Use id2label mapping if available id2label = model.config.id2label if hasattr(model.config, "id2label") else {i: f"Label {i}" for i in range(len(probs))} results = [{"label": id2label[idx], "score": f"{score:.4f}"} for idx, score in zip(indices, scores)] return {"predictions": results}