swathi6016 commited on
Commit
d88501a
·
verified ·
1 Parent(s): dd8f7cc

Upload 2 files

Browse files
Files changed (2) hide show
  1. main.py +138 -0
  2. requirements.txt +5 -0
main.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import httpx
5
+ import os
6
+
7
+ app = FastAPI(title="Phishing Detection API")
8
+
9
+ # CORS
10
+ app.add_middleware(
11
+ CORSMiddleware,
12
+ allow_origins=["https://phishing-detector-frontend-eight.vercel.app"], # Allow all origins for now
13
+ allow_credentials=True,
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ # Configuration
19
+ HF_TOKEN = os.getenv("HF_TOKEN")
20
+ HF_MODEL_ID = os.getenv("HF_MODEL_ID", "swathi6016/phishing-detector1")
21
+ HF_API_URL = f"https://api-inference.huggingface.co/models/{HF_MODEL_ID}"
22
+
23
+ # Pydantic model for request validation
24
+ class URLRequest(BaseModel):
25
+ url: str
26
+
27
+ @app.get("/")
28
+ async def root():
29
+ """Root endpoint"""
30
+ return {
31
+ "message": "Phishing Detection API",
32
+ "status": "running",
33
+ "model": "DistilBERT via HuggingFace",
34
+ "endpoints": {
35
+ "check": "POST /check",
36
+ "health": "GET /health",
37
+ "docs": "GET /docs"
38
+ }
39
+ }
40
+
41
+ @app.get("/health")
42
+ async def health():
43
+ """Health check"""
44
+ return {
45
+ "status": "healthy",
46
+ "model": HF_MODEL_ID,
47
+ "hf_token_set": bool(HF_TOKEN)
48
+ }
49
+
50
+ @app.post("/check")
51
+ async def check_url(request: URLRequest):
52
+ """Check if URL is phishing"""
53
+
54
+ if not HF_TOKEN:
55
+ raise HTTPException(
56
+ status_code=500,
57
+ detail="HF_TOKEN not configured"
58
+ )
59
+
60
+ url = request.url.strip()
61
+ if not url:
62
+ raise HTTPException(status_code=400, detail="URL is required")
63
+
64
+ try:
65
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
66
+ payload = {"inputs": url}
67
+
68
+ async with httpx.AsyncClient(timeout=30.0) as client:
69
+ response = await client.post(HF_API_URL, headers=headers, json=payload)
70
+
71
+ if response.status_code == 503:
72
+ raise HTTPException(
73
+ status_code=503,
74
+ detail="Model is loading. Please try again in 20 seconds."
75
+ )
76
+
77
+ if response.status_code != 200:
78
+ raise HTTPException(
79
+ status_code=response.status_code,
80
+ detail=f"HuggingFace API error: {response.text}"
81
+ )
82
+
83
+ result = response.json()
84
+
85
+ # Parse response
86
+ if isinstance(result, list) and len(result) > 0:
87
+ predictions = result[0] if isinstance(result[0], list) else result
88
+
89
+ phishing_score = 0.0
90
+ legitimate_score = 0.0
91
+
92
+ for pred in predictions:
93
+ label = str(pred.get("label", "")).lower()
94
+ score = float(pred.get("score", 0.0))
95
+
96
+ if "1" in label or "phishing" in label:
97
+ phishing_score = score
98
+ elif "0" in label or "legitimate" in label or "legit" in label:
99
+ legitimate_score = score
100
+
101
+ is_phishing = phishing_score > legitimate_score
102
+ confidence = max(phishing_score, legitimate_score)
103
+
104
+ if phishing_score > 0.8:
105
+ risk_level = "HIGH RISK"
106
+ elif phishing_score > 0.5:
107
+ risk_level = "MEDIUM RISK"
108
+ else:
109
+ risk_level = "LOW RISK"
110
+
111
+ return {
112
+ "url": url,
113
+ "is_phishing": is_phishing,
114
+ "phishing_probability": phishing_score,
115
+ "legitimate_probability": legitimate_score,
116
+ "confidence": confidence,
117
+ "prediction": "PHISHING" if is_phishing else "LEGITIMATE",
118
+ "risk_level": risk_level
119
+ }
120
+ else:
121
+ raise HTTPException(
122
+ status_code=500,
123
+ detail="Unexpected response format from model"
124
+ )
125
+
126
+ except httpx.TimeoutException:
127
+ raise HTTPException(status_code=504, detail="Request timeout")
128
+ except httpx.RequestError as e:
129
+ raise HTTPException(status_code=500, detail=f"Connection error: {str(e)}")
130
+ except HTTPException:
131
+ raise
132
+ except Exception as e:
133
+ raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
134
+
135
+ if __name__ == "__main__":
136
+ import uvicorn
137
+ port = int(os.environ.get("PORT", 8000))
138
+ uvicorn.run(app, host="0.0.0.0", port=port)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi==0.104.1
2
+ uvicorn[standard]==0.24.0
3
+ httpx==0.25.1
4
+ pydantic==2.5.0
5
+ python-dotenv==1.0.0