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 = """ AI & News Detection

📰 Fake News Detection

{% if news_prediction %}

🧠 News Detection Result:

{{ news_prediction }}

Interpretation: This result indicates whether the submitted news text is likely real or fake. Higher confidence suggests stronger model certainty.

{% endif %}

🤖 What is ResNet50?

ResNet50 is a 50-layer deep convolutional neural network designed for image classification tasks. It can recognize thousands of objects from the ImageNet dataset.

""" @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