AIcoder35235 commited on
Commit
a850497
·
verified ·
1 Parent(s): 5415465

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +81 -0
app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from transformers import pipeline
5
+ from PIL import Image
6
+ import base64
7
+ import io
8
+ import requests
9
+
10
+ app = FastAPI(title="STOA Deepfake Detector API")
11
+
12
+ # --- CORS ---
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_credentials=True,
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ # --- MODEL LOADING ---
22
+ print("Booting Security Node. Loading Deepfake ViT model into memory...")
23
+ pipe = pipeline("image-classification", model="dima806/deepfake_vs_real_image_detection")
24
+ print("Agent Ready!")
25
+
26
+ # --- REQUEST SCHEMA ---
27
+ class PredictRequest(BaseModel):
28
+ image: str | None = None
29
+ image_url: str | None = None
30
+
31
+ # --- ENDPOINTS ---
32
+ @app.get("/health")
33
+ def health_check():
34
+ return {"status": "ok"}
35
+
36
+ @app.post("/predict")
37
+ def predict(req: PredictRequest):
38
+ try:
39
+ img = None
40
+
41
+ # 1. Handle URL Input (with the Wikipedia bypass fix from Task 24!)
42
+ if req.image_url:
43
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
44
+ response = requests.get(req.image_url, stream=True, headers=headers)
45
+ if response.status_code != 200:
46
+ raise Exception(f"Could not download image. Server returned: {response.status_code}")
47
+ img = Image.open(response.raw).convert("RGB")
48
+
49
+ # 2. Handle Base64 Input
50
+ elif req.image:
51
+ b64_data = req.image
52
+ if "," in b64_data:
53
+ b64_data = b64_data.split(",")[1]
54
+ image_bytes = base64.b64decode(b64_data)
55
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
56
+
57
+ # 3. Handle Empty Request
58
+ else:
59
+ raise HTTPException(status_code=400, detail="Must provide 'image' (base64) or 'image_url'.")
60
+
61
+ # 4. Execute AI Math
62
+ results = pipe(img)
63
+
64
+ # 5. Format to exact Task 25 specifications
65
+ scores_dict = {}
66
+ for res in results:
67
+ raw_label = res['label'].upper()
68
+ # Map standard model output to strict spec requirements
69
+ final_label = "DEEPFAKE" if "FAKE" in raw_label else "REAL"
70
+ scores_dict[final_label] = round(res['score'], 4)
71
+
72
+ top_pred = max(scores_dict, key=scores_dict.get)
73
+
74
+ return {
75
+ "prediction": top_pred,
76
+ "confidence": scores_dict[top_pred],
77
+ "scores": scores_dict
78
+ }
79
+
80
+ except Exception as e:
81
+ raise HTTPException(status_code=400, detail=f"Failed to process face: {str(e)}")