Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,26 +1,56 @@
|
|
1 |
-
import
|
2 |
-
from transformers import ViTForImageClassification, ViTImageProcessor
|
3 |
from PIL import Image
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
model_name = "google/vit-base-patch16-224"
|
7 |
-
processor = ViTImageProcessor.from_pretrained(model_name)
|
8 |
-
model = ViTForImageClassification.from_pretrained(model_name)
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
return "REAL" if outputs.logits.argmax() == 0 else "FAKE (Deepfake!)"
|
15 |
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
|
26 |
-
app.
|
|
|
1 |
+
from flask import Flask, request, jsonify
|
|
|
2 |
from PIL import Image
|
3 |
+
import requests
|
4 |
+
from io import BytesIO
|
5 |
+
import torch
|
6 |
+
from transformers import AutoImageProcessor, AutoModelForImageClassification
|
7 |
|
8 |
+
app = Flask(__name__)
|
|
|
|
|
|
|
9 |
|
10 |
+
# Load model and processor (cache them for better performance)
|
11 |
+
MODEL_NAME = "dima806/deepfake_vs_real_image_detection"
|
12 |
+
processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
|
13 |
+
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
|
|
|
14 |
|
15 |
+
@app.route('/detect', methods=['POST'])
|
16 |
+
def detect_deepfake():
|
17 |
+
try:
|
18 |
+
# Get image from request
|
19 |
+
if 'file' not in request.files:
|
20 |
+
return jsonify({"error": "No file uploaded"}), 400
|
21 |
+
|
22 |
+
file = request.files['file']
|
23 |
+
if file.filename == '':
|
24 |
+
return jsonify({"error": "No selected file"}), 400
|
25 |
+
|
26 |
+
# Open and process image
|
27 |
+
image = Image.open(file.stream).convert("RGB")
|
28 |
+
|
29 |
+
# Preprocess image
|
30 |
+
inputs = processor(images=image, return_tensors="pt")
|
31 |
+
|
32 |
+
# Run inference
|
33 |
+
with torch.no_grad():
|
34 |
+
outputs = model(**inputs)
|
35 |
+
|
36 |
+
# Get probabilities
|
37 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
38 |
+
real_prob = round(probabilities[0][0].item() * 100, 2)
|
39 |
+
fake_prob = round(probabilities[0][1].item() * 100, 2)
|
40 |
+
|
41 |
+
# Determine result
|
42 |
+
result = "Real" if real_prob > fake_prob else "Fake"
|
43 |
+
confidence = real_prob if result == "Real" else fake_prob
|
44 |
+
|
45 |
+
return jsonify({
|
46 |
+
"result": result,
|
47 |
+
"confidence": confidence,
|
48 |
+
"real_probability": real_prob,
|
49 |
+
"fake_probability": fake_prob
|
50 |
+
})
|
51 |
+
|
52 |
+
except Exception as e:
|
53 |
+
return jsonify({"error": str(e)}), 500
|
54 |
|
55 |
+
if __name__ == '__main__':
|
56 |
+
app.run(host='0.0.0.0', port=5000)
|