shanti commited on
Commit
c6e7c13
Β·
verified Β·
1 Parent(s): b870322

Create app.py

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