fake-real / app.py
TruthLens's picture
Update app.py
d9d507c verified
raw
history blame
3.89 kB
import os
from flask import Flask, request, render_template_string
from PIL import Image
import torch
from torchvision import models, transforms
import requests
from transformers import pipeline
app = Flask(__name__)
# Create the 'static/uploads' folder if it doesn't exist
upload_folder = os.path.join('static', 'uploads')
os.makedirs(upload_folder, exist_ok=True)
# Download ImageNet class labels
imagenet_class_labels_url = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
response = requests.get(imagenet_class_labels_url)
imagenet_class_labels = response.json()
# Load pre-trained ResNet50 for object classification
resnet50_model = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
resnet50_model.eval()
# Load ResNet18 for AI vs. Human detection
resnet18_model = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)
resnet18_model.eval()
# Load fake news detection model from Hugging Face
news_classifier = pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection")
# Image transformation pipeline
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# HTML Template with improved UI
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AI & News Detection</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f5f5f5; padding: 20px; }
.container { background: white; padding: 30px; border-radius: 12px; max-width: 750px; margin: auto; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
h1, h2 { color: #333; }
textarea { width: 100%; padding: 12px; margin-top: 10px; border-radius: 8px; border: 1px solid #ccc; }
button { background-color: #4CAF50; color: white; border: none; padding: 12px 20px; border-radius: 8px; cursor: pointer; font-size: 16px; }
button:hover { background-color: #45a049; }
.result { background: #e7f3fe; padding: 15px; border-radius: 10px; margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
<h1>πŸ“° Fake News Detection</h1>
<form method="POST" action="/detect">
<textarea name="text" placeholder="Enter news text..." required></textarea>
<button type="submit">Detect News Authenticity</button>
</form>
{% if news_prediction %}
<div class="result">
<h2>🧠 News Detection Result:</h2>
<p>{{ news_prediction }}</p>
<p><strong>Interpretation:</strong> This result indicates whether the submitted news text is likely real or fake. Higher confidence suggests stronger model certainty.</p>
</div>
{% endif %}
<div style="margin-top: 30px;">
<h2>πŸ€– What is ResNet50?</h2>
<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>
</div>
</div>
</body>
</html>
"""
@app.route("/", methods=["GET"])
def home():
return render_template_string(HTML_TEMPLATE)
@app.route("/detect", methods=["POST"])
def detect():
text = request.form.get("text")
if not text:
return render_template_string(HTML_TEMPLATE, news_prediction="No text provided.")
# Use the model for prediction
result = news_classifier(text)[0]
label = "REAL" if result['label'] == "LABEL_1" else "FAKE"
confidence = result['score'] * 100
return render_template_string(
HTML_TEMPLATE,
news_prediction=f"News is {label} (Confidence: {confidence:.2f}%)"
)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) # Suitable for Hugging Face Spaces