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|
+
import cv2
|
| 5 |
+
import numpy as np
|
| 6 |
+
import insightface
|
| 7 |
+
from insightface.app import FaceAnalysis
|
| 8 |
+
import time
|
| 9 |
+
import requests
|
| 10 |
+
|
| 11 |
+
app = ''
|
| 12 |
+
swapper = ''
|
| 13 |
+
st.set_page_config(page_title="FaceSwap App by Adil Khan")
|
| 14 |
+
|
| 15 |
+
def download_model():
|
| 16 |
+
url = "https://cdn.adikhanofficial.com/python/insightface/models/inswapper_128.onnx"
|
| 17 |
+
filename = url.split('/')[-1]
|
| 18 |
+
filepath = os.path.join(os.path.dirname(__file__),filename)
|
| 19 |
+
|
| 20 |
+
if not os.path.exists(filepath):
|
| 21 |
+
print(f"Downloading {filename}...")
|
| 22 |
+
response = requests.get(url)
|
| 23 |
+
with open(filepath, 'wb') as file:
|
| 24 |
+
file.write(response.content)
|
| 25 |
+
print(f"{filename} downloaded successfully.")
|
| 26 |
+
else:
|
| 27 |
+
print(f"{filename} already exists in the directory.")
|
| 28 |
+
|
| 29 |
+
def swap_faces(target_image, target_face, source_face):
|
| 30 |
+
try:
|
| 31 |
+
return swapper.get(target_image, target_face, source_face, paste_back=True)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
st.error(f"Error during swaping: {e}")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def image_faceswap_app():
|
| 37 |
+
st.title("Face Swapper for Image")
|
| 38 |
+
source_image = st.file_uploader("Upload Source Image", type=["jpg", "jpeg", "png"])
|
| 39 |
+
target_image = st.file_uploader("Upload Target Image", type=["jpg", "jpeg", "png"])
|
| 40 |
+
if source_image and target_image:
|
| 41 |
+
with st.spinner("Swapping... Please wait."):
|
| 42 |
+
try:
|
| 43 |
+
source_image = cv2.imdecode(np.frombuffer(source_image.read(), np.uint8), -1)
|
| 44 |
+
target_image = cv2.imdecode(np.frombuffer(target_image.read(), np.uint8), -1)
|
| 45 |
+
source_image = cv2.cvtColor(source_image, cv2.COLOR_BGR2RGB)
|
| 46 |
+
target_image = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB)
|
| 47 |
+
source_faces = app.get(source_image)
|
| 48 |
+
source_faces = sorted(source_faces, key=lambda x: x.bbox[0])
|
| 49 |
+
if len(source_faces) == 0:
|
| 50 |
+
raise ValueError("No faces found in the source image.")
|
| 51 |
+
source_face = source_faces[0]
|
| 52 |
+
target_faces = app.get(target_image)
|
| 53 |
+
target_faces = sorted(target_faces, key=lambda x: x.bbox[0])
|
| 54 |
+
if len(target_faces) == 0:
|
| 55 |
+
raise ValueError("No faces found in the target image.")
|
| 56 |
+
target_face = target_faces[0]
|
| 57 |
+
swapped_image = swap_faces(target_image, target_face, source_face)
|
| 58 |
+
message_placeholder = st.empty()
|
| 59 |
+
message_placeholder.success("Swapped Successfully!")
|
| 60 |
+
col1, col2, col3 = st.columns([1, 1, 1])
|
| 61 |
+
with col1:
|
| 62 |
+
st.image(source_image, caption="Source Image", use_column_width=True)
|
| 63 |
+
with col2:
|
| 64 |
+
st.image(target_image, caption="Target Image", use_column_width=True)
|
| 65 |
+
with col3:
|
| 66 |
+
st.image(swapped_image, caption="Swapped Image", use_column_width=True)
|
| 67 |
+
except Exception as e:
|
| 68 |
+
st.error(f"Error during image processing: {e}")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def process_video(source_img, video_path, output_video_path):
|
| 72 |
+
try:
|
| 73 |
+
cap = cv2.VideoCapture(video_path)
|
| 74 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
| 75 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 76 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
| 77 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
| 78 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 79 |
+
out = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))
|
| 80 |
+
source_faces = app.get(source_img)
|
| 81 |
+
source_faces = sorted(source_faces, key=lambda x: x.bbox[0])
|
| 82 |
+
if len(source_faces) == 0:
|
| 83 |
+
raise ValueError("No faces found in the source image.")
|
| 84 |
+
source_face = source_faces[0]
|
| 85 |
+
progress_placeholder = st.empty()
|
| 86 |
+
frame_count = 0
|
| 87 |
+
start_time = time.time()
|
| 88 |
+
while True:
|
| 89 |
+
ret, frame = cap.read()
|
| 90 |
+
if not ret:
|
| 91 |
+
break
|
| 92 |
+
target_faces = app.get(frame)
|
| 93 |
+
target_faces = sorted(target_faces, key=lambda x: x.bbox[0])
|
| 94 |
+
if len(target_faces) > 0:
|
| 95 |
+
frame = swap_faces(frame, target_faces[0], source_face)
|
| 96 |
+
out.write(frame)
|
| 97 |
+
elapsed_time = time.time() - start_time
|
| 98 |
+
frames_per_second = frame_count / elapsed_time if elapsed_time > 0 else 0
|
| 99 |
+
remaining_time_seconds = max(0, (total_frames - frame_count) / frames_per_second) if frames_per_second > 0 else 0
|
| 100 |
+
remaining_minutes, remaining_seconds = divmod(remaining_time_seconds, 60)
|
| 101 |
+
elapsed_minutes, elapsed_seconds = divmod(elapsed_time, 60)
|
| 102 |
+
progress_placeholder.text(
|
| 103 |
+
f"Processed Frames: {frame_count}/{total_frames} | Elapsed Time: {int(elapsed_minutes)}m {int(elapsed_seconds)}s | Remaining Time: {int(remaining_minutes)}m {int(remaining_seconds)}s")
|
| 104 |
+
frame_count += 1
|
| 105 |
+
cap.release()
|
| 106 |
+
out.release()
|
| 107 |
+
except Exception as e:
|
| 108 |
+
st.error(f"Error during video processing: {e}")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def video_faceswap_app():
|
| 112 |
+
st.title("Face Swapper for Video")
|
| 113 |
+
source_image = st.file_uploader("Upload Source Face Image", type=["jpg", "jpeg", "png"])
|
| 114 |
+
if source_image is not None:
|
| 115 |
+
source_image = cv2.imdecode(np.frombuffer(source_image.read(), np.uint8), -1)
|
| 116 |
+
target_video = st.file_uploader("Upload Target Video", type=["mp4"])
|
| 117 |
+
if target_video is not None:
|
| 118 |
+
temp_video = NamedTemporaryFile(delete=False, suffix=".mp4")
|
| 119 |
+
temp_video.write(target_video.read())
|
| 120 |
+
output_video_path = os.path.splitext(temp_video.name)[0] + '_output.mp4'
|
| 121 |
+
status_placeholder = st.empty()
|
| 122 |
+
try:
|
| 123 |
+
with st.spinner("Processing... This may take a while."):
|
| 124 |
+
process_video(source_image, temp_video.name, output_video_path)
|
| 125 |
+
status_placeholder.success("Processing complete!")
|
| 126 |
+
st.subheader("Your video is ready:")
|
| 127 |
+
st.video(output_video_path)
|
| 128 |
+
except Exception as e:
|
| 129 |
+
st.error(f"Error during video processing: {e}")
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def main():
|
| 133 |
+
app_selection = st.sidebar.radio("Select App", ("Image Face Swapping", "Video Face Swapping"))
|
| 134 |
+
if app_selection == "Image Face Swapping":
|
| 135 |
+
image_faceswap_app()
|
| 136 |
+
elif app_selection == "Video Face Swapping":
|
| 137 |
+
video_faceswap_app()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
app = FaceAnalysis(name='buffalo_l')
|
| 142 |
+
app.prepare(ctx_id=0, det_size=(640, 640))
|
| 143 |
+
download_model() #download model if not available
|
| 144 |
+
swapper = insightface.model_zoo.get_model('inswapper_128.onnx', root=os.path.dirname(__file__))
|
| 145 |
+
main()
|
gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
opencv-python
|
| 2 |
+
numpy
|
| 3 |
+
insightface
|
| 4 |
+
onnx
|
| 5 |
+
onnxruntime
|
| 6 |
+
streamlit
|
run.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import subprocess
|
| 4 |
+
|
| 5 |
+
# Define the path to the Streamlit app
|
| 6 |
+
script_path = os.path.join(os.path.dirname(__file__), 'app.py')
|
| 7 |
+
|
| 8 |
+
# Run the Streamlit app
|
| 9 |
+
if __name__ == "__main__":
|
| 10 |
+
subprocess.run([sys.executable, "-m", "streamlit", "run", script_path])
|