|
|
from fastapi import FastAPI, Form |
|
|
from fastapi.responses import Response |
|
|
from twilio.rest import Client |
|
|
from twilio.twiml.messaging_response import MessagingResponse |
|
|
import requests |
|
|
import os |
|
|
|
|
|
app = FastAPI(title="WhatsApp → Public HuggingFace → Forward Bot") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
HF_API_URL = "https://api-inference.huggingface.co/models/ST-THOMAS-OF-AQUINAS/SCAM" |
|
|
|
|
|
|
|
|
TWILIO_SID = os.environ.get("TWILIO_SID") |
|
|
TWILIO_AUTH = os.environ.get("TWILIO_AUTH") |
|
|
TWILIO_WHATSAPP = os.environ.get("TWILIO_WHATSAPP") |
|
|
MY_WHATSAPP = os.environ.get("MY_WHATSAPP") |
|
|
|
|
|
twilio_client = Client(TWILIO_SID, TWILIO_AUTH) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.post("/whatsapp") |
|
|
async def whatsapp_forward(From: str = Form(...), Body: str = Form(...)): |
|
|
if not Body.strip(): |
|
|
return Response(content="", media_type="application/xml") |
|
|
|
|
|
|
|
|
try: |
|
|
payload = {"inputs": Body} |
|
|
hf_response = requests.post(HF_API_URL, json=payload, timeout=30) |
|
|
hf_response.raise_for_status() |
|
|
result = hf_response.json() |
|
|
|
|
|
prediction = result[0]["label"] |
|
|
confidence = result[0]["score"] * 100 |
|
|
|
|
|
|
|
|
forward_text = ( |
|
|
f"📩 New message from {From}\n\n" |
|
|
f"Message: {Body}\n" |
|
|
f"Prediction: {prediction}\n" |
|
|
f"Confidence: {confidence:.2f}%" |
|
|
) |
|
|
except Exception as e: |
|
|
forward_text = f"❌ Error calling model: {str(e)}" |
|
|
|
|
|
|
|
|
twilio_client.messages.create( |
|
|
from_=TWILIO_WHATSAPP, |
|
|
to=MY_WHATSAPP, |
|
|
body=forward_text |
|
|
) |
|
|
|
|
|
|
|
|
resp = MessagingResponse() |
|
|
resp.message("✅ Message received and processed.") |
|
|
return Response(content=str(resp), media_type="application/xml") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/") |
|
|
async def health_check(): |
|
|
return {"status": "✅ API is running"} |
|
|
|