TruthLens commited on
Commit
e064416
·
verified ·
1 Parent(s): 3a9179e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -65
app.py CHANGED
@@ -3,7 +3,7 @@ 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
 
@@ -11,18 +11,19 @@ app = Flask(__name__)
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([
@@ -31,60 +32,52 @@ transform = transforms.Compose([
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>
@@ -99,41 +92,39 @@ def home():
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)
 
 
3
  from PIL import Image
4
  import torch
5
  from torchvision import models, transforms
6
+ from transformers import pipeline, CLIPProcessor, CLIPModel
7
 
8
  app = Flask(__name__)
9
 
 
11
  upload_folder = os.path.join('static', 'uploads')
12
  os.makedirs(upload_folder, exist_ok=True)
13
 
14
+ # Load Updated Fake News Detection Pipelines
15
+ news_models = {
16
+ "newsverify": pipeline("text-classification", model="newsverify/roberta-fake-news"),
17
+ "fakenewsdetector": pipeline("text-classification", model="fakenewsdetector/bert-fake-news")
18
+ }
19
 
20
+ # Load Image Models for AI vs. Human Detection
21
+ clip_model = CLIPModel.from_pretrained("openai/clip-vit-large-patch14")
22
+ clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-large-patch14")
23
 
24
+ ai_image_models = {
25
+ "openai": clip_model
26
+ }
27
 
28
  # Image transformation pipeline
29
  transform = transforms.Compose([
 
32
  transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
33
  ])
34
 
35
+ # HTML Template with Model Selection
36
  HTML_TEMPLATE = """
37
  <!DOCTYPE html>
38
  <html lang="en">
39
  <head>
40
  <meta charset="UTF-8">
41
+ <title>AI & News Detection</title>
42
  <style>
43
  body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5; padding: 20px; }
44
+ .container { background: white; padding: 30px; border-radius: 12px; max-width: 800px; margin: auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
45
+ textarea, select { 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; margin-top: 10px; }
 
47
  button:hover { background-color: #45a049; }
48
  .result { background: #e7f3fe; padding: 15px; border-radius: 10px; margin-top: 20px; }
 
49
  </style>
50
  </head>
51
  <body>
52
  <div class="container">
53
+ <h1>📰 Fake News Detection</h1>
54
  <form method="POST" action="/detect">
55
  <textarea name="text" placeholder="Enter news text..." required></textarea>
56
+ <label for="model">Select Fake News Model:</label>
57
+ <select name="model" required>
58
+ <option value="newsverify">NewsVerify (RoBERTa)</option>
59
+ <option value="fakenewsdetector">FakeNewsDetector (BERT)</option>
60
+ </select>
61
  <button type="submit">Detect News Authenticity</button>
62
  </form>
63
 
64
+ {% if news_prediction %}
 
 
 
 
 
 
 
 
 
 
 
65
  <div class="result">
66
+ <h2>🧠 News Detection Result:</h2>
67
+ <p>{{ news_prediction }}</p>
 
68
  </div>
69
  {% endif %}
70
 
71
+ <h1>🖼️ AI vs. Human Image Detection</h1>
72
+ <form method="POST" action="/detect_image" enctype="multipart/form-data">
73
+ <input type="file" name="image" required>
74
+ <button type="submit">Upload and Detect</button>
75
+ </form>
76
+
77
+ {% if image_prediction %}
78
  <div class="result">
79
+ <h2>📷 Image Detection Result:</h2>
80
+ <p>{{ image_prediction }}</p>
 
 
 
 
 
81
  </div>
82
  {% endif %}
83
  </div>
 
92
  @app.route("/detect", methods=["POST"])
93
  def detect():
94
  text = request.form.get("text")
95
+ model_key = request.form.get("model")
96
+
97
+ if not text or model_key not in news_models:
98
+ return render_template_string(HTML_TEMPLATE, news_prediction="Invalid input or model selection.")
99
+
100
+ result = news_models[model_key](text)[0]
101
+ label = "REAL" if result['label'].lower() in ["real", "label_1"] else "FAKE"
102
+ confidence = result['score'] * 100
103
+
104
+ return render_template_string(
105
+ HTML_TEMPLATE,
106
+ news_prediction=f"News is {label} (Confidence: {confidence:.2f}%)"
107
+ )
108
 
109
  @app.route("/detect_image", methods=["POST"])
110
  def detect_image():
111
  if "image" not in request.files:
112
+ return render_template_string(HTML_TEMPLATE, image_prediction="No image uploaded.")
113
 
114
  file = request.files["image"]
115
+ img = Image.open(file).convert("RGB")
116
+ inputs = clip_processor(images=img, return_tensors="pt")
 
 
 
117
 
 
118
  with torch.no_grad():
119
+ image_features = ai_image_models["openai"].get_image_features(**inputs)
 
 
120
 
121
+ prediction = "AI-Generated" if torch.mean(image_features).item() > 0 else "Human-Created"
 
 
 
 
 
 
 
122
 
123
  return render_template_string(
124
  HTML_TEMPLATE,
125
+ image_prediction=f"Prediction: {prediction}"
 
126
  )
127
 
128
  if __name__ == "__main__":
129
+ app.run(host="0.0.0.0", port=7860) # Suitable for Hugging Face Spaces
130
+