File size: 5,553 Bytes
4899c48 9c845ff 4899c48 9c845ff e753508 f6a86a1 e753508 f6a86a1 e753508 bfc8332 4899c48 9c845ff 4899c48 9c845ff 4899c48 bfc8332 e00265c db62218 e00265c 4d4bca8 e00265c 65f367a bfc8332 4899c48 4d4bca8 9c845ff 4d4bca8 e00265c 4899c48 6e0cae9 b05c0a7 4899c48 9c845ff 6e0cae9 4899c48 c3cd6c8 b05c0a7 6e0cae9 86f532d 65f367a 6e0cae9 b05c0a7 36a1c8b b05c0a7 6e0cae9 e753508 9c845ff e753508 9c845ff e753508 6e0cae9 65f367a 36a1c8b 9c845ff 0f2cda2 65f367a c3cd6c8 6e0cae9 e4b4786 6e0cae9 bfc8332 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | import numpy as np
import cv2
import streamlit as st
import insightface
from insightface.app import FaceAnalysis
from PIL import Image
from nudenet import NudeDetector
# Initialize the FaceAnalysis model
app = FaceAnalysis(name='buffalo_l')
app.prepare(ctx_id=0, det_size=(640, 640)) # Ensure the model runs on the CPU if there's limited GPU
# Load the face swapping model (downloading on-demand)
swapper = insightface.model_zoo.get_model('insightface/inswapper_128.onnx', download=True)
# Initialize the NudeDetector model for nudity detection
detector = NudeDetector()
# Function to detect adult content in images
def check_for_adult_content(image):
# Convert PIL image to a numpy array
img = np.array(image)
# Use NudeDetector to predict nudity
results = detector.detect(img) # Returns a list of dictionaries
# Check if any of the results contain explicit labels
explicit_labels = [
'EXPOSED_ANUS',
'EXPOSED_BREAST_F',
'EXPOSED_GENITALIA_F',
'EXPOSED_GENITALIA_M'
]
# Iterate through results and check for explicit content
for item in results:
if 'label' in item and item['label'] in explicit_labels:
return True # Detected explicit content
return False # No explicit content detected
# Face swapping function with added sharpening
def swap_faces(destination_image, source_image):
# Load the destination and source images from Streamlit inputs
img = cv2.cvtColor(np.array(destination_image), cv2.COLOR_RGB2BGR)
test = cv2.cvtColor(np.array(source_image), cv2.COLOR_RGB2BGR)
# Detect faces in the destination and source images
faces = app.get(img)
test_faces = app.get(test)
if not faces or not test_faces:
return "No faces detected in one or both images."
test_face = test_faces[0]
# Perform face swapping with error handling
res = img.copy()
try:
for face in faces:
res = swapper.get(res, face, test_face, paste_back=True)
except MemoryError:
return "Memory error: Face swapping operation failed due to memory overload."
# Apply sharpening for a clearer image
kernel = np.array([[0, -1, 0],
[-1, 5, -1],
[0, -1, 0]])
sharpened_res = cv2.filter2D(res, -1, kernel)
# Commented smoothing (blurring) for testing purposes
smoothed_res = cv2.GaussianBlur(res, (5, 5), 0)
# Convert the result to RGB for display in Streamlit
sharpened_res_rgb = cv2.cvtColor(sharpened_res, cv2.COLOR_BGR2RGB)
return sharpened_res_rgb
# Streamlit app layout
def main():
st.set_page_config(page_title="SnapSwap", page_icon=":camera:")
# CSS for styling
st.markdown("""
<style>
.header {
font-size: 2em;
font-weight: bold;
color: #4e73df;
}
.subtitle {
font-size: 1.2em;
color: #4e73df;
}
.content {
font-size: 1em;
}
</style>
""", unsafe_allow_html=True)
# Page Header (outside sidebar)
st.header("SnapSwap :camera:")
st.write("Welcome to the face swapping app! Upload two images and watch the magic happen!")
# Sidebar for file uploads and instructions
with st.sidebar:
st.subheader("Upload Images for Face Swapping and hit Swap Faces button")
source_image = st.file_uploader("Upload Source Image", type=["jpg", "png", "jpeg"])
destination_image = st.file_uploader("Upload Destination Image", type=["jpg", "png", "jpeg"])
if destination_image and source_image:
# Check if destination image contains adult content
destination_img = Image.open(destination_image)
if check_for_adult_content(destination_img):
st.error("The destination image does not fall within ethical guidelines.")
else:
st.write("Both images uploaded! Click below to swap faces.")
if st.button("Swap Faces"):
with st.spinner("Processing..."):
# Read images with PIL (Streamlit works with PIL images)
source_img = Image.open(source_image)
# Call the face swapping function
result = swap_faces(destination_img, source_img)
if isinstance(result, str):
st.error(result) # Display error message if no faces detected or memory error
else:
st.session_state.result = result # Save the result in session state
st.success("Face swapping complete!")
# Instructions on how to use the app (below upload buttons and swap button)
st.subheader("How to Use the App:")
st.markdown("""
1. **Upload the destination and source images**: Select the images you want to use for face swapping.
2. **Click on the \"Swap Faces\" button**: The app will process the images and swap the faces.
3. **View the output**: The swapped face image will appear after processing.
""")
# Main content area for displaying the swapped face image
if 'result' in st.session_state:
st.image(st.session_state.result, caption="Swapped Face", use_container_width=True)
# Footer with credits
st.markdown("Developed with ❤ by Aklavya")
# Run the app
if __name__ == '__main__':
main() |