Upload app (1).py
Browse files- app (1).py +139 -0
app (1).py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from flask import Flask, request, render_template_string
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import torch
|
| 5 |
+
from torchvision import models, transforms
|
| 6 |
+
import requests
|
| 7 |
+
|
| 8 |
+
app = Flask(__name__)
|
| 9 |
+
|
| 10 |
+
# Create the 'static/uploads' folder if it doesn't exist
|
| 11 |
+
upload_folder = os.path.join('static', 'uploads')
|
| 12 |
+
os.makedirs(upload_folder, exist_ok=True)
|
| 13 |
+
|
| 14 |
+
# Download ImageNet class labels
|
| 15 |
+
imagenet_class_labels_url = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
|
| 16 |
+
response = requests.get(imagenet_class_labels_url)
|
| 17 |
+
imagenet_class_labels = response.json()
|
| 18 |
+
|
| 19 |
+
# Load pre-trained ResNet50 for object classification
|
| 20 |
+
resnet50_model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
|
| 21 |
+
resnet50_model.eval()
|
| 22 |
+
|
| 23 |
+
# Load ResNet18 for AI vs. Human detection (Use custom-trained weights if available)
|
| 24 |
+
resnet18_model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
|
| 25 |
+
resnet18_model.eval()
|
| 26 |
+
|
| 27 |
+
# Image transformation pipeline
|
| 28 |
+
transform = transforms.Compose([
|
| 29 |
+
transforms.Resize((224, 224)),
|
| 30 |
+
transforms.ToTensor(),
|
| 31 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
| 32 |
+
])
|
| 33 |
+
|
| 34 |
+
# HTML Template with improved UI and interpretation
|
| 35 |
+
HTML_TEMPLATE = """
|
| 36 |
+
<!DOCTYPE html>
|
| 37 |
+
<html lang="en">
|
| 38 |
+
<head>
|
| 39 |
+
<meta charset="UTF-8">
|
| 40 |
+
<title>AI & Image Detection</title>
|
| 41 |
+
<style>
|
| 42 |
+
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5; padding: 20px; }
|
| 43 |
+
.container { background: white; padding: 30px; border-radius: 12px; max-width: 750px; margin: auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
|
| 44 |
+
h1, h2 { color: #333; }
|
| 45 |
+
textarea, input[type="file"] { width: 100%; padding: 12px; margin-top: 10px; border-radius: 8px; border: 1px solid #ccc; }
|
| 46 |
+
button { background-color: #4CAF50; color: white; border: none; padding: 12px 20px; border-radius: 8px; cursor: pointer; font-size: 16px; }
|
| 47 |
+
button:hover { background-color: #45a049; }
|
| 48 |
+
.result { background: #e7f3fe; padding: 15px; border-radius: 10px; margin-top: 20px; }
|
| 49 |
+
ul { text-align: left; }
|
| 50 |
+
</style>
|
| 51 |
+
</head>
|
| 52 |
+
<body>
|
| 53 |
+
<div class="container">
|
| 54 |
+
<h1>📰 Fake News & Image Detection</h1>
|
| 55 |
+
<form method="POST" action="/detect">
|
| 56 |
+
<textarea name="text" placeholder="Enter news text..." required></textarea>
|
| 57 |
+
<button type="submit">Detect News Authenticity</button>
|
| 58 |
+
</form>
|
| 59 |
+
|
| 60 |
+
<h1>🖼️ Upload Image for Detection</h1>
|
| 61 |
+
<form method="POST" action="/detect_image" enctype="multipart/form-data">
|
| 62 |
+
<input type="file" name="image" required>
|
| 63 |
+
<button type="submit">Upload and Analyze</button>
|
| 64 |
+
</form>
|
| 65 |
+
|
| 66 |
+
<div style="margin-top: 30px;">
|
| 67 |
+
<h2>🤖 What is ResNet50?</h2>
|
| 68 |
+
<p>ResNet50 is a 50-layer deep convolutional neural network designed for image classification tasks. It can recognize thousands of objects from the ImageNet dataset.</p>
|
| 69 |
+
</div>
|
| 70 |
+
|
| 71 |
+
{% if ai_prediction %}
|
| 72 |
+
<div class="result">
|
| 73 |
+
<h2>🧠 AI vs. Human Detection Result:</h2>
|
| 74 |
+
<p>{{ ai_prediction }}</p>
|
| 75 |
+
<p><strong>Interpretation:</strong> This result indicates whether the uploaded image was likely created by AI or a human. Higher confidence suggests stronger model certainty.</p>
|
| 76 |
+
</div>
|
| 77 |
+
{% endif %}
|
| 78 |
+
|
| 79 |
+
{% if classification_results %}
|
| 80 |
+
<div class="result">
|
| 81 |
+
<h2>📦 Object Classification Results (ResNet50):</h2>
|
| 82 |
+
<ul>
|
| 83 |
+
{% for result in classification_results %}
|
| 84 |
+
<li>• {{ result.label }} ({{ (result.score * 100) | round(2) }}%) - Detected object category.</li>
|
| 85 |
+
{% endfor %}
|
| 86 |
+
</ul>
|
| 87 |
+
<p><strong>Interpretation:</strong> The model predicts the most probable object categories in the uploaded image along with confidence scores. Higher percentages indicate stronger matches.</p>
|
| 88 |
+
</div>
|
| 89 |
+
{% endif %}
|
| 90 |
+
</div>
|
| 91 |
+
</body>
|
| 92 |
+
</html>
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
@app.route("/", methods=["GET"])
|
| 96 |
+
def home():
|
| 97 |
+
return render_template_string(HTML_TEMPLATE)
|
| 98 |
+
|
| 99 |
+
@app.route("/detect", methods=["POST"])
|
| 100 |
+
def detect():
|
| 101 |
+
text = request.form.get("text")
|
| 102 |
+
final_label = "REAL" if "trusted" in text.lower() else "FAKE" # Placeholder logic
|
| 103 |
+
return render_template_string(HTML_TEMPLATE, ai_prediction=f"News is {final_label}.", classification_results=None)
|
| 104 |
+
|
| 105 |
+
@app.route("/detect_image", methods=["POST"])
|
| 106 |
+
def detect_image():
|
| 107 |
+
if "image" not in request.files:
|
| 108 |
+
return "No image uploaded.", 400
|
| 109 |
+
|
| 110 |
+
file = request.files["image"]
|
| 111 |
+
img_path = os.path.join(upload_folder, file.filename)
|
| 112 |
+
file.save(img_path)
|
| 113 |
+
|
| 114 |
+
img = Image.open(img_path).convert("RGB")
|
| 115 |
+
img_tensor = transform(img).unsqueeze(0)
|
| 116 |
+
|
| 117 |
+
# AI vs. Human detection
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
ai_output = resnet18_model(img_tensor)
|
| 120 |
+
ai_confidence = torch.softmax(ai_output, dim=1).max().item()
|
| 121 |
+
ai_label = "AI-Generated" if ai_confidence > 0.55 else "Human-Created"
|
| 122 |
+
|
| 123 |
+
# Object classification with ResNet50
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
outputs = resnet50_model(img_tensor)
|
| 126 |
+
probs = torch.softmax(outputs, dim=1)[0]
|
| 127 |
+
top5_probs, top5_indices = torch.topk(probs, 5)
|
| 128 |
+
classification_results = [
|
| 129 |
+
{"label": imagenet_class_labels[idx], "score": prob.item()} for idx, prob in zip(top5_indices, top5_probs)
|
| 130 |
+
]
|
| 131 |
+
|
| 132 |
+
return render_template_string(
|
| 133 |
+
HTML_TEMPLATE,
|
| 134 |
+
ai_prediction=f"{ai_label} (Confidence: {(ai_confidence * 100):.2f}%)",
|
| 135 |
+
classification_results=classification_results
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
if __name__ == "__main__":
|
| 139 |
+
app.run(host="0.0.0.0", port=7860) # Updated for Hugging Face Spaces (no ngrok required)
|