Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Form
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
| 4 |
+
import torch
|
| 5 |
+
from twilio.twiml.messaging_response import MessagingResponse
|
| 6 |
+
|
| 7 |
+
# --- Load model ---
|
| 8 |
+
model_id = "ST-THOMAS-OF-AQUINAS/SCAM"
|
| 9 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 10 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id)
|
| 11 |
+
model.eval()
|
| 12 |
+
|
| 13 |
+
label_map = {0: "author1", 1: "author2"}
|
| 14 |
+
|
| 15 |
+
# --- FastAPI app ---
|
| 16 |
+
app = FastAPI(title="Scam Detector API with Twilio")
|
| 17 |
+
|
| 18 |
+
# --- Helper prediction function ---
|
| 19 |
+
def predict_author(text: str):
|
| 20 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
| 21 |
+
with torch.no_grad():
|
| 22 |
+
outputs = model(**inputs)
|
| 23 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
| 24 |
+
pred = torch.argmax(probs, dim=1).item()
|
| 25 |
+
confidence = probs[0][pred].item()
|
| 26 |
+
predicted_author = label_map[pred]
|
| 27 |
+
return predicted_author, round(confidence * 100, 2)
|
| 28 |
+
|
| 29 |
+
# --- Twilio WhatsApp webhook ---
|
| 30 |
+
@app.post("/whatsapp")
|
| 31 |
+
async def whatsapp_reply(Body: str = Form(...)):
|
| 32 |
+
resp = MessagingResponse()
|
| 33 |
+
|
| 34 |
+
if Body.strip():
|
| 35 |
+
author, confidence = predict_author(Body)
|
| 36 |
+
reply = f"Prediction: {author}\nConfidence: {confidence}%"
|
| 37 |
+
else:
|
| 38 |
+
reply = "⚠️ No text detected."
|
| 39 |
+
|
| 40 |
+
resp.message(reply)
|
| 41 |
+
return str(resp)
|
| 42 |
+
|
| 43 |
+
# --- Simple test endpoint ---
|
| 44 |
+
@app.get("/predict")
|
| 45 |
+
async def predict(text: str):
|
| 46 |
+
author, confidence = predict_author(text)
|
| 47 |
+
return {"prediction": author, "confidence": confidence}
|
| 48 |
+
|