Spaces:
Running
Running
Upload 4 files
Browse files
README.md
CHANGED
@@ -1,14 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
license: mit
|
11 |
-
short_description: Image and Video Face Swaping App
|
12 |
---
|
13 |
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
# Face Swapping App by Adil Khan
|
3 |
+
|
4 |
+
Welcome to the **Face Swapping App** repository! This application leverages **Streamlit** and **OpenCV**, powered by **InsightFace**, to perform seamless face swapping on images and videos. Whether you want to swap faces in pictures or videos, this app provides a simple and efficient solution.
|
5 |
+
|
6 |
+
---
|
7 |
+
|
8 |
+
## Features
|
9 |
+
|
10 |
+
- **Image Face Swap**: Effortlessly swap faces between a source and target image.
|
11 |
+
- **Video Face Swap**: Apply face swapping across all frames of a target video using a source face image.
|
12 |
+
- **High Precision**: Built on **InsightFace** deep learning models for accurate face detection and swapping.
|
13 |
+
- **User-Friendly Interface**: Interact with the app through a sleek and intuitive **Streamlit** interface.
|
14 |
+
|
15 |
+
---
|
16 |
+
|
17 |
+
## How It Works
|
18 |
+
|
19 |
+
1. **Image Face Swapping**:
|
20 |
+
- Detects faces in both the source and target images.
|
21 |
+
- Replaces the target face with the source face using the `inswapper_128.onnx` model.
|
22 |
+
|
23 |
+
2. **Video Face Swapping**:
|
24 |
+
- Processes each frame of the video to detect and swap faces to match the source face.
|
25 |
+
|
26 |
+
---
|
27 |
+
|
28 |
+
## Installation
|
29 |
+
|
30 |
+
Follow these steps to get started:
|
31 |
+
|
32 |
+
1. **Clone the repository**:
|
33 |
+
```bash
|
34 |
+
git clone https://github.com/AdiKhanOfficial/face-swap-app.git
|
35 |
+
cd face-swap-app
|
36 |
+
```
|
37 |
+
|
38 |
+
2. **Install dependencies**:
|
39 |
+
```bash
|
40 |
+
pip install -r requirements.txt
|
41 |
+
```
|
42 |
+
|
43 |
+
3. **Run the app**:
|
44 |
+
- For the Streamlit interface:
|
45 |
+
```bash
|
46 |
+
streamlit run app.py
|
47 |
+
```
|
48 |
+
- Or, simply run:
|
49 |
+
```bash
|
50 |
+
python run.py
|
51 |
+
```
|
52 |
+
|
53 |
+
---
|
54 |
+
|
55 |
+
## Requirements
|
56 |
+
|
57 |
+
- **Python 3.9**
|
58 |
+
- **Streamlit**
|
59 |
+
- **OpenCV**
|
60 |
+
- **InsightFace**
|
61 |
+
|
62 |
+
**Download Links**:
|
63 |
+
- [Python 3.9](https://www.python.org/downloads/release/python-390/)
|
64 |
+
- [InSwapper Model (`inswapper_128.onnx`)](https://cdn.adikhanofficial.com/python/insightface/models/inswapper_128.onnx)
|
65 |
+
|
66 |
---
|
67 |
+
|
68 |
+
## Usage
|
69 |
+
|
70 |
+
1. Open the application using Streamlit or `run.py`.
|
71 |
+
2. Upload your **source face image** and the **target image/video**.
|
72 |
+
3. Click the process button and let the magic happen!
|
73 |
+
4. Once processing is complete, download the swapped images or videos directly from the app.
|
74 |
+
|
|
|
|
|
75 |
---
|
76 |
|
77 |
+
## Results
|
78 |
+
<img src='https://raw.githubusercontent.com/AdiKhanOfficial/face_swapping/refs/heads/main/Results/Result.jpg' style='width:100%'/>
|
79 |
+
|
80 |
+
---
|
81 |
+
|
82 |
+
## Contributing
|
83 |
+
|
84 |
+
Contributions are welcome! If you’d like to improve the app or add new features, feel free to fork the repository, make your changes, and submit a pull request.
|
85 |
+
|
86 |
+
---
|
87 |
+
|
88 |
+
## License
|
89 |
+
|
90 |
+
This project is licensed under the [MIT License](LICENSE).
|
91 |
+
|
92 |
+
---
|
93 |
+
|
94 |
+
## About
|
95 |
+
|
96 |
+
Developed by **Adil Khan**.
|
97 |
+
For more projects and updates, visit my [GitHub Profile](https://github.com/AdiKhanOfficial) or follow me on social media.
|
98 |
+
|
99 |
+
---
|
100 |
+
|
101 |
+
Feel free to reach out with any questions or feedback! 😊
|
102 |
+
|
app.py
ADDED
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from tempfile import NamedTemporaryFile
|
3 |
+
import streamlit as st
|
4 |
+
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()
|
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])
|