Spaces:
Build error
Build error
| import streamlit as st | |
| import tensorflow as tf | |
| import tensorflow_hub as hub | |
| from PIL import Image | |
| import numpy as np | |
| import cv2 | |
| import io | |
| import os | |
| # Load the MobileNet model from TensorFlow Hub | |
| mobilenet_url = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4" | |
| mobilenet_model = hub.load(mobilenet_url) | |
| # Create a function to perform image classification | |
| def classify_image(image): | |
| # Preprocess the image | |
| image = image.resize((224, 224)) | |
| image = np.array(image) / 255.0 # Normalize the pixel values | |
| image = tf.image.convert_image_dtype(image, tf.float32) | |
| image = tf.image.resize_with_pad(image, 224, 224) | |
| image = tf.expand_dims(image, axis=0) | |
| # Perform classification | |
| predictions = mobilenet_model(image) | |
| return predictions | |
| # Function to perform basic deepfake detection (for educational purposes) | |
| def detect_deepfake(image_path): | |
| image = cv2.imread(image_path) | |
| gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
| faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5) | |
| if len(faces) > 0: | |
| return 0.3 # A face was detected, indicating it may be a real image | |
| else: | |
| return 0.9 # No face detected; it may be a deepfake | |
| # Streamlit UI | |
| st.title("Truecaptions - AI-Generated Image Detection") | |
| uploaded_image = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"]) | |
| if uploaded_image is not None: | |
| image = Image.open(uploaded_image) | |
| st.image(image, caption="Uploaded Image", use_column_width=True) | |
| if st.button("Classify"): | |
| st.write("Classifying...") | |
| predictions = classify_image(image) | |
| st.write("Image Classification Results:") | |
| top_classes = np.argsort(predictions)[0, ::-1][:5] # Top 5 classes | |
| for i, class_idx in enumerate(top_classes): | |
| st.write(f"Class {class_idx}: {predictions[0, class_idx]:.4f}") | |
| st.write("Detecting deepfake...") | |
| # Save the uploaded image to a temporary file and get its path | |
| temp_image_path = "temp_image.jpg" | |
| image.save(temp_image_path) | |
| deepfake_score = detect_deepfake(temp_image_path) | |
| # Remove the temporary image file | |
| os.remove(temp_image_path) | |
| if deepfake_score > 0.5: | |
| st.write("This image is likely AI-generated (deepfake).") | |
| else: | |
| st.write("This image appears to be real.") | |
| st.text("Upload an image and click the 'Classify' button to see image classification and deepfake detection results.") | |