import os
from flask import Flask, request, render_template_string
from PIL import Image
import torch
from torchvision import models, transforms
from transformers import pipeline, CLIPProcessor, CLIPModel
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)
# Updated Fake News Detection Models
news_models = {
"mrm8488": pipeline("text-classification", model="mrm8488/bert-tiny-finetuned-fake-news-detection"),
"liam168": pipeline("text-classification", model="liam168/fake-news-bert-base-uncased"),
"distilbert": pipeline("text-classification", model="distilbert-base-uncased-finetuned-sst-2-english")
}
# Updated Image Models for AI vs. Human Detection
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
ai_image_models = {
"clip-vit-base-patch32": clip_model
}
# 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 Model Selection
HTML_TEMPLATE = """
AI & News Detection
📰 Fake News Detection
{% if news_prediction %}
🧠 News Detection Result:
{{ news_prediction }}
{% endif %}
🖼️ AI vs. Human Image Detection
{% if image_prediction %}
📷 Image Detection Result:
{{ image_prediction }}
{% endif %}
"""
@app.route("/", methods=["GET"])
def home():
return render_template_string(HTML_TEMPLATE)
@app.route("/detect", methods=["POST"])
def detect():
text = request.form.get("text")
model_key = request.form.get("model")
if not text or model_key not in news_models:
return render_template_string(HTML_TEMPLATE, news_prediction="Invalid input or model selection.")
result = news_models[model_key](text)[0]
label = "REAL" if result['label'].lower() in ["real", "label_1"] else "FAKE"
confidence = result['score'] * 100
return render_template_string(
HTML_TEMPLATE,
news_prediction=f"News is {label} (Confidence: {confidence:.2f}%)"
)
@app.route("/detect_image", methods=["POST"])
def detect_image():
if "image" not in request.files:
return render_template_string(HTML_TEMPLATE, image_prediction="No image uploaded.")
file = request.files["image"]
img = Image.open(file).convert("RGB")
inputs = clip_processor(images=img, return_tensors="pt")
with torch.no_grad():
image_features = ai_image_models["clip-vit-base-patch32"].get_image_features(**inputs)
prediction = "AI-Generated" if torch.mean(image_features).item() > 0 else "Human-Created"
return render_template_string(
HTML_TEMPLATE,
image_prediction=f"Prediction: {prediction}"
)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=7860) # Suitable for Hugging Face Spaces