Download app.py from jackgaletti/propaganda-classifier-web-app: direct link, hf CLI and curl.
- Browser
- Download file 1.41 kB
-
https://huggingface.co/spaces/jackgaletti/propaganda-classifier-web-app/resolve/main/app.py
- Command line
-
hf download hf://spaces/jackgaletti/propaganda-classifier-web-app/app.py
-
curl -L -o app.py https://huggingface.co/spaces/jackgaletti/propaganda-classifier-web-app/resolve/main/app.py
1.41 kB
| 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 | |
| def serve_index(): | |
| with open("index.html", "r") as f: | |
| return f.read() | |
| # Request body model | |
| class TextRequest(BaseModel): | |
| text: str | |
| # Predict endpoint | |
| 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} | |