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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding:UTF-8 -*-
|
| 2 |
+
#!/usr/bin/env python
|
| 3 |
+
import numpy as np
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import roop.globals
|
| 6 |
+
from roop.core import (
|
| 7 |
+
start,
|
| 8 |
+
decode_execution_providers,
|
| 9 |
+
suggest_max_memory,
|
| 10 |
+
suggest_execution_threads,
|
| 11 |
+
)
|
| 12 |
+
from roop.processors.frame.core import get_frame_processors_modules
|
| 13 |
+
from roop.utilities import normalize_output_path
|
| 14 |
+
import os
|
| 15 |
+
from PIL import Image
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from huggingface_hub import HfApi, login
|
| 18 |
+
from datasets import load_dataset, Dataset
|
| 19 |
+
import json
|
| 20 |
+
import shutil
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
|
| 23 |
+
# Load environment variables
|
| 24 |
+
load_dotenv()
|
| 25 |
+
|
| 26 |
+
class FaceIntegrDataset:
|
| 27 |
+
def __init__(self, repo_id="Arrcttacsrks/face_integrData"):
|
| 28 |
+
# Get token from environment variable
|
| 29 |
+
self.token = os.getenv('hf_token')
|
| 30 |
+
if not self.token:
|
| 31 |
+
raise ValueError("HF_TOKEN environment variable is not set")
|
| 32 |
+
|
| 33 |
+
self.repo_id = repo_id
|
| 34 |
+
self.api = HfApi()
|
| 35 |
+
|
| 36 |
+
# Login to Hugging Face
|
| 37 |
+
login(self.token)
|
| 38 |
+
|
| 39 |
+
# Create local temp directory for organizing files
|
| 40 |
+
self.temp_dir = "temp_dataset"
|
| 41 |
+
os.makedirs(self.temp_dir, exist_ok=True)
|
| 42 |
+
|
| 43 |
+
def create_date_folder(self):
|
| 44 |
+
"""Create folder structure based on current date"""
|
| 45 |
+
current_date = datetime.now().strftime("%Y-%m-%d")
|
| 46 |
+
folder_path = os.path.join(self.temp_dir, current_date)
|
| 47 |
+
os.makedirs(folder_path, exist_ok=True)
|
| 48 |
+
return folder_path, current_date
|
| 49 |
+
|
| 50 |
+
def save_metadata(self, source_path, target_path, output_path, timestamp):
|
| 51 |
+
"""Save metadata for the face swap operation"""
|
| 52 |
+
metadata = {
|
| 53 |
+
"timestamp": timestamp,
|
| 54 |
+
"source_image": source_path,
|
| 55 |
+
"target_image": target_path,
|
| 56 |
+
"output_image": output_path,
|
| 57 |
+
"date_created": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 58 |
+
}
|
| 59 |
+
return metadata
|
| 60 |
+
|
| 61 |
+
def upload_to_hf(self, local_folder, date_folder):
|
| 62 |
+
"""Upload files to Hugging Face dataset"""
|
| 63 |
+
try:
|
| 64 |
+
# Upload the files
|
| 65 |
+
self.api.upload_folder(
|
| 66 |
+
folder_path=local_folder,
|
| 67 |
+
repo_id=self.repo_id,
|
| 68 |
+
repo_type="dataset",
|
| 69 |
+
path_in_repo=date_folder
|
| 70 |
+
)
|
| 71 |
+
return True
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"Error uploading to Hugging Face: {str(e)}")
|
| 74 |
+
return False
|
| 75 |
+
|
| 76 |
+
def swap_face(source_file, target_file, doFaceEnhancer):
|
| 77 |
+
folder_path = None
|
| 78 |
+
try:
|
| 79 |
+
# Initialize dataset handler
|
| 80 |
+
dataset_handler = FaceIntegrDataset()
|
| 81 |
+
|
| 82 |
+
# Create date-based folder
|
| 83 |
+
folder_path, date_folder = dataset_handler.create_date_folder()
|
| 84 |
+
|
| 85 |
+
# Generate timestamp for unique identification
|
| 86 |
+
timestamp = datetime.now().strftime("%S-%M-%H-%d-%m-%Y")
|
| 87 |
+
|
| 88 |
+
# Save input images with timestamp in folder
|
| 89 |
+
source_path = os.path.join(folder_path, f"source_{timestamp}.jpg")
|
| 90 |
+
target_path = os.path.join(folder_path, f"target_{timestamp}.jpg")
|
| 91 |
+
output_path = os.path.join(folder_path, f"OutputImage{timestamp}.jpg")
|
| 92 |
+
|
| 93 |
+
# Save the input images
|
| 94 |
+
if source_file is None or target_file is None:
|
| 95 |
+
raise ValueError("Source and target images are required")
|
| 96 |
+
|
| 97 |
+
source_image = Image.fromarray(source_file)
|
| 98 |
+
source_image.save(source_path)
|
| 99 |
+
target_image = Image.fromarray(target_file)
|
| 100 |
+
target_image.save(target_path)
|
| 101 |
+
|
| 102 |
+
print("source_path: ", source_path)
|
| 103 |
+
print("target_path: ", target_path)
|
| 104 |
+
|
| 105 |
+
# Set global paths
|
| 106 |
+
roop.globals.source_path = source_path
|
| 107 |
+
roop.globals.target_path = target_path
|
| 108 |
+
roop.globals.output_path = normalize_output_path(
|
| 109 |
+
roop.globals.source_path,
|
| 110 |
+
roop.globals.target_path,
|
| 111 |
+
output_path
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
# Configure face processing options
|
| 115 |
+
if doFaceEnhancer:
|
| 116 |
+
roop.globals.frame_processors = ["face_swapper", "face_enhancer"]
|
| 117 |
+
else:
|
| 118 |
+
roop.globals.frame_processors = ["face_swapper"]
|
| 119 |
+
|
| 120 |
+
# Set global parameters
|
| 121 |
+
roop.globals.headless = True
|
| 122 |
+
roop.globals.keep_fps = True
|
| 123 |
+
roop.globals.keep_audio = True
|
| 124 |
+
roop.globals.keep_frames = False
|
| 125 |
+
roop.globals.many_faces = False
|
| 126 |
+
roop.globals.video_encoder = "libx264"
|
| 127 |
+
roop.globals.video_quality = 18
|
| 128 |
+
roop.globals.max_memory = suggest_max_memory()
|
| 129 |
+
roop.globals.execution_providers = decode_execution_providers(["cuda"])
|
| 130 |
+
roop.globals.execution_threads = suggest_execution_threads()
|
| 131 |
+
|
| 132 |
+
print(
|
| 133 |
+
"start process",
|
| 134 |
+
roop.globals.source_path,
|
| 135 |
+
roop.globals.target_path,
|
| 136 |
+
roop.globals.output_path,
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# Check frame processors
|
| 140 |
+
for frame_processor in get_frame_processors_modules(roop.globals.frame_processors):
|
| 141 |
+
if not frame_processor.pre_check():
|
| 142 |
+
return None
|
| 143 |
+
|
| 144 |
+
# Process the face swap
|
| 145 |
+
start()
|
| 146 |
+
|
| 147 |
+
# Save metadata
|
| 148 |
+
metadata = dataset_handler.save_metadata(
|
| 149 |
+
f"source_{timestamp}.jpg",
|
| 150 |
+
f"target_{timestamp}.jpg",
|
| 151 |
+
f"OutputImage{timestamp}.jpg",
|
| 152 |
+
timestamp
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# Save metadata to JSON file in the same folder
|
| 156 |
+
metadata_path = os.path.join(folder_path, f"metadata_{timestamp}.json")
|
| 157 |
+
with open(metadata_path, 'w') as f:
|
| 158 |
+
json.dump(metadata, f, indent=4)
|
| 159 |
+
|
| 160 |
+
# Upload to Hugging Face
|
| 161 |
+
upload_success = dataset_handler.upload_to_hf(folder_path, date_folder)
|
| 162 |
+
|
| 163 |
+
if upload_success:
|
| 164 |
+
print(f"Successfully uploaded files to dataset {dataset_handler.repo_id}")
|
| 165 |
+
else:
|
| 166 |
+
print("Failed to upload files to Hugging Face dataset")
|
| 167 |
+
|
| 168 |
+
# Read the output image before cleaning up
|
| 169 |
+
if os.path.exists(output_path):
|
| 170 |
+
output_image = Image.open(output_path)
|
| 171 |
+
output_array = np.array(output_image)
|
| 172 |
+
# Clean up temp folder after reading the image
|
| 173 |
+
shutil.rmtree(folder_path)
|
| 174 |
+
return output_array
|
| 175 |
+
else:
|
| 176 |
+
print("Output image not found")
|
| 177 |
+
if folder_path and os.path.exists(folder_path):
|
| 178 |
+
shutil.rmtree(folder_path)
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
except Exception as e:
|
| 182 |
+
print(f"Error in face swap process: {str(e)}")
|
| 183 |
+
if folder_path and os.path.exists(folder_path):
|
| 184 |
+
shutil.rmtree(folder_path)
|
| 185 |
+
raise gr.Error(f"Face swap failed: {str(e)}")
|
| 186 |
+
|
| 187 |
+
def create_interface():
|
| 188 |
+
# Create custom style
|
| 189 |
+
custom_css = """
|
| 190 |
+
.container {
|
| 191 |
+
max-width: 1200px;
|
| 192 |
+
margin: auto;
|
| 193 |
+
padding: 20px;
|
| 194 |
+
}
|
| 195 |
+
.output-image {
|
| 196 |
+
min-height: 400px;
|
| 197 |
+
border: 1px solid #ccc;
|
| 198 |
+
border-radius: 8px;
|
| 199 |
+
padding: 10px;
|
| 200 |
+
}
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
# Gradio interface setup
|
| 204 |
+
title = "Face - Integrator"
|
| 205 |
+
description = r"""
|
| 206 |
+
Please upload source and target images to begin the face swap process.
|
| 207 |
+
"""
|
| 208 |
+
article = r"""
|
| 209 |
+
<div style="text-align: center; max-width: 650px; margin: 40px auto;">
|
| 210 |
+
<p>
|
| 211 |
+
This tool performs face swapping with optional enhancement.
|
| 212 |
+
</p>
|
| 213 |
+
</div>
|
| 214 |
+
"""
|
| 215 |
+
|
| 216 |
+
# Create Gradio interface with improved layout
|
| 217 |
+
with gr.Blocks(title=title, css=custom_css) as app:
|
| 218 |
+
gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
|
| 219 |
+
gr.Markdown(description)
|
| 220 |
+
|
| 221 |
+
with gr.Row():
|
| 222 |
+
with gr.Column(scale=1):
|
| 223 |
+
source_image = gr.Image(
|
| 224 |
+
label="Source Image",
|
| 225 |
+
type="numpy",
|
| 226 |
+
sources=["upload"]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
with gr.Column(scale=1):
|
| 230 |
+
target_image = gr.Image(
|
| 231 |
+
label="Target Image",
|
| 232 |
+
type="numpy",
|
| 233 |
+
sources=["upload"]
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
with gr.Column(scale=1):
|
| 237 |
+
output_image = gr.Image(
|
| 238 |
+
label="Output Image",
|
| 239 |
+
type="numpy",
|
| 240 |
+
interactive=False,
|
| 241 |
+
elem_classes="output-image"
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
with gr.Row():
|
| 245 |
+
enhance_checkbox = gr.Checkbox(
|
| 246 |
+
label="Apply the algorithm?",
|
| 247 |
+
info="Image Quality Improvement",
|
| 248 |
+
value=False
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
with gr.Row():
|
| 252 |
+
process_btn = gr.Button(
|
| 253 |
+
"Process Face Swap",
|
| 254 |
+
variant="primary",
|
| 255 |
+
size="lg"
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
# Set up the processing event
|
| 259 |
+
process_btn.click(
|
| 260 |
+
fn=swap_face,
|
| 261 |
+
inputs=[source_image, target_image, enhance_checkbox],
|
| 262 |
+
outputs=output_image,
|
| 263 |
+
api_name="swap_face"
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
gr.Markdown(article)
|
| 267 |
+
|
| 268 |
+
return app
|
| 269 |
+
|
| 270 |
+
def main():
|
| 271 |
+
# Create and launch the interface
|
| 272 |
+
app = create_interface()
|
| 273 |
+
app.launch(share=False)
|
| 274 |
+
|
| 275 |
+
if __name__ == "__main__":
|
| 276 |
+
main()
|