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") # ------------------------------- # Hugging Face public model URL # ------------------------------- HF_API_URL = "https://api-inference.huggingface.co/models/ST-THOMAS-OF-AQUINAS/SCAM" # Twilio credentials (set in Space Secrets) TWILIO_SID = os.environ.get("TWILIO_SID") TWILIO_AUTH = os.environ.get("TWILIO_AUTH") TWILIO_WHATSAPP = os.environ.get("TWILIO_WHATSAPP") # e.g., whatsapp:+14155238886 MY_WHATSAPP = os.environ.get("MY_WHATSAPP") # Your personal WhatsApp twilio_client = Client(TWILIO_SID, TWILIO_AUTH) # ------------------------------- # Incoming message webhook # ------------------------------- @app.post("/whatsapp") async def whatsapp_forward(From: str = Form(...), Body: str = Form(...)): if not Body.strip(): return Response(content="", media_type="application/xml") # 1️⃣ Send message to Hugging Face model 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 # 2️⃣ Build the forward message 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)}" # 3️⃣ Send the message to YOUR WhatsApp twilio_client.messages.create( from_=TWILIO_WHATSAPP, to=MY_WHATSAPP, body=forward_text ) # 4️⃣ Reply to sender optionally resp = MessagingResponse() resp.message("✅ Message received and processed.") return Response(content=str(resp), media_type="application/xml") # ------------------------------- # Health check # ------------------------------- @app.get("/") async def health_check(): return {"status": "✅ API is running"}