ishworrsubedii commited on
Commit
8c8893b
·
verified ·
1 Parent(s): fd8a60f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -130
app.py CHANGED
@@ -1,5 +1,5 @@
1
  # -*- coding:UTF-8 -*-
2
- #!/usr/bin/env python
3
  import spaces
4
  import numpy as np
5
  import gradio as gr
@@ -18,87 +18,37 @@ import onnxruntime as ort
18
  import cv2
19
  from roop.face_analyser import get_one_face
20
 
21
- # Set up the application theme and styling
22
- custom_css = """
23
- .gradio-container {
24
- font-family: 'Arial', sans-serif;
25
- }
26
- .disclaimer {
27
- background-color: #f8d7da;
28
- border: 1px solid #f5c6cb;
29
- color: #721c24;
30
- padding: 10px;
31
- margin-bottom: 20px;
32
- border-radius: 5px;
33
- }
34
- .instructions {
35
- background-color: #e2f0d9;
36
- border: 1px solid #c5e0b4;
37
- padding: 10px;
38
- margin-bottom: 20px;
39
- border-radius: 5px;
40
- }
41
- """
42
-
43
  @spaces.GPU
44
  def swap_face(source_file, target_file, doFaceEnhancer):
45
- """
46
- Swap faces between source and target images.
47
-
48
- Args:
49
- source_file: Image containing the face to be used
50
- target_file: Image where the face will be swapped onto
51
- doFaceEnhancer: Whether to enhance the resulting face
52
-
53
- Returns:
54
- Path to the output image with the swapped face
55
- """
56
- # Create a temporary directory for processing
57
- session_dir = "temp"
58
  os.makedirs(session_dir, exist_ok=True)
59
-
60
- # Generate random filenames to avoid conflicts
61
  source_filename = f"source_{random.randint(1000, 9999)}.jpg"
62
  target_filename = f"target_{random.randint(1000, 9999)}.jpg"
63
  output_filename = f"output_{random.randint(1000, 9999)}.jpg"
64
-
65
- # Save uploaded images to the temporary directory
66
  source_path = os.path.join(session_dir, source_filename)
67
  target_path = os.path.join(session_dir, target_filename)
68
-
69
  source_image = Image.fromarray(source_file)
70
  source_image.save(source_path)
71
-
72
  target_image = Image.fromarray(target_file)
73
  target_image.save(target_path)
74
-
75
- print("Processing source image:", source_path)
76
- print("Processing target image:", target_path)
77
-
78
  # Check if a face is detected in the source image
79
  source_face = get_one_face(cv2.imread(source_path))
80
  if source_face is None:
81
- raise gradio.exceptions.Error("No face detected in the source image. Please upload a clear photo with a face.")
82
-
83
  # Check if a face is detected in the target image
84
  target_face = get_one_face(cv2.imread(target_path))
85
  if target_face is None:
86
- raise gradio.exceptions.Error("No face detected in the target image. Please upload a clear photo with a face.")
87
-
88
- # Set up output path
89
  output_path = os.path.join(session_dir, output_filename)
90
  normalized_output_path = normalize_output_path(source_path, target_path, output_path)
91
-
92
- # Determine which processors to use
93
  frame_processors = ["face_swapper", "face_enhancer"] if doFaceEnhancer else ["face_swapper"]
94
-
95
- # Validate processors
96
  for frame_processor in get_frame_processors_modules(frame_processors):
97
  if not frame_processor.pre_check():
98
  print(f"Pre-check failed for {frame_processor}")
99
- raise gradio.exceptions.Error(f"The {frame_processor} module failed to initialize. Please try again.")
100
-
101
- # Configure roop settings
102
  roop.globals.source_path = source_path
103
  roop.globals.target_path = target_path
104
  roop.globals.output_path = normalized_output_path
@@ -115,80 +65,52 @@ def swap_face(source_file, target_file, doFaceEnhancer):
115
  roop.globals.similar_face_distance = 0.6
116
  roop.globals.max_memory = 60
117
  roop.globals.execution_threads = 8
118
-
119
- # Start the face swapping process
120
  start()
121
-
122
  return normalized_output_path
123
 
124
- # Create the Gradio interface with improved descriptions and layout
125
- with gr.Blocks(css=custom_css) as app:
126
- gr.Markdown("# AI Face Swap Tool")
127
-
128
- with gr.Row():
129
- with gr.Column():
130
- gr.Markdown("""
131
- <div class="disclaimer">
132
- <h3>⚠️ Ethical Usage Guidelines</h3>
133
- <p>This tool is provided for educational and creative purposes only. Please use responsibly:</p>
134
- <ul>
135
- <li>Do not use to create misleading or deceptive content</li>
136
- <li>Do not use for harassment or to misrepresent individuals</li>
137
- <li>Always get consent when using someone's likeness</li>
138
- <li>Be aware that creating deepfakes may violate laws in some jurisdictions</li>
139
- </ul>
140
- </div>
141
- """)
142
-
143
- gr.Markdown("""
144
- <div class="instructions">
145
- <h3>📝 How to Use This Tool</h3>
146
- <ol>
147
- <li><b>Source Image:</b> Upload a clear photo of the face you want to use</li>
148
- <li><b>Target Image:</b> Upload the photo where you want to place the face</li>
149
- <li><b>Face Enhancer:</b> Toggle this option to improve the quality of the swapped face</li>
150
- <li>Click the "Swap Face" button and wait for processing to complete</li>
151
- </ol>
152
- <p><b>Tips for best results:</b></p>
153
- <ul>
154
- <li>Use high-resolution images with clear, front-facing faces</li>
155
- <li>Ensure good lighting in both photos</li>
156
- <li>Similar face angles work best</li>
157
- <li>Processing may take 10-30 seconds depending on image size</li>
158
- </ul>
159
- </div>
160
- """)
161
-
162
- with gr.Row():
163
- with gr.Column():
164
- source_image = gr.Image(label="Source Face", info="Upload a photo with the face you want to use")
165
- with gr.Column():
166
- target_image = gr.Image(label="Target Image", info="Upload the photo where you want to place the face")
167
-
168
- with gr.Row():
169
- face_enhancer = gr.Checkbox(
170
- label="Apply Face Enhancement",
171
- info="Enable this to improve the quality and realism of the result",
172
- value=True
173
- )
174
-
175
- with gr.Row():
176
- swap_button = gr.Button("Swap Face", variant="primary")
177
-
178
- output_image = gr.Image(label="Result")
179
-
180
- swap_button.click(
181
- fn=swap_face,
182
- inputs=[source_image, target_image, face_enhancer],
183
- outputs=output_image
184
- )
185
-
186
- gr.Markdown("""
187
- ### How It Works
188
- This application uses AI to detect faces in both images, then carefully transplants the face from
189
- the source image onto the target image while preserving natural appearance. The optional face
190
- enhancement feature uses additional AI processing to improve skin texture and details.
191
- """)
192
 
193
- # Launch the application
194
  app.launch()
 
1
  # -*- coding:UTF-8 -*-
2
+ # !/usr/bin/env python
3
  import spaces
4
  import numpy as np
5
  import gradio as gr
 
18
  import cv2
19
  from roop.face_analyser import get_one_face
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  @spaces.GPU
22
  def swap_face(source_file, target_file, doFaceEnhancer):
23
+ session_dir = "temp" # Sử dụng thư mục cố định
 
 
 
 
 
 
 
 
 
 
 
 
24
  os.makedirs(session_dir, exist_ok=True)
25
+ # Tạo tên file ngẫu nhiên
 
26
  source_filename = f"source_{random.randint(1000, 9999)}.jpg"
27
  target_filename = f"target_{random.randint(1000, 9999)}.jpg"
28
  output_filename = f"output_{random.randint(1000, 9999)}.jpg"
 
 
29
  source_path = os.path.join(session_dir, source_filename)
30
  target_path = os.path.join(session_dir, target_filename)
 
31
  source_image = Image.fromarray(source_file)
32
  source_image.save(source_path)
 
33
  target_image = Image.fromarray(target_file)
34
  target_image.save(target_path)
35
+ print("source_path: ", source_path)
36
+ print("target_path: ", target_path)
 
 
37
  # Check if a face is detected in the source image
38
  source_face = get_one_face(cv2.imread(source_path))
39
  if source_face is None:
40
+ raise gradio.exceptions.Error("No face in source path detected.")
 
41
  # Check if a face is detected in the target image
42
  target_face = get_one_face(cv2.imread(target_path))
43
  if target_face is None:
44
+ raise gradio.exceptions.Error("No face in target path detected.")
 
 
45
  output_path = os.path.join(session_dir, output_filename)
46
  normalized_output_path = normalize_output_path(source_path, target_path, output_path)
 
 
47
  frame_processors = ["face_swapper", "face_enhancer"] if doFaceEnhancer else ["face_swapper"]
 
 
48
  for frame_processor in get_frame_processors_modules(frame_processors):
49
  if not frame_processor.pre_check():
50
  print(f"Pre-check failed for {frame_processor}")
51
+ raise gradio.exceptions.Error(f"Pre-check failed for {frame_processor}")
 
 
52
  roop.globals.source_path = source_path
53
  roop.globals.target_path = target_path
54
  roop.globals.output_path = normalized_output_path
 
65
  roop.globals.similar_face_distance = 0.6
66
  roop.globals.max_memory = 60
67
  roop.globals.execution_threads = 8
 
 
68
  start()
 
69
  return normalized_output_path
70
 
71
+ app = gr.Interface(
72
+ fn=swap_face,
73
+ inputs=[
74
+ gr.Image(label="Source Face Image", info="Upload a photo containing the face you want to use. Make sure the face is clearly visible."),
75
+ gr.Image(label="Target Image", info="Upload the photo where you want to place the new face. This image should also contain a clearly visible face."),
76
+ gr.Checkbox(label="Apply Face Enhancement", info="Check this to improve the quality and realism of the swapped face. Recommended for better results.")
77
+ ],
78
+ outputs="image",
79
+ title="AI Face Swap Tool",
80
+ description="""
81
+ ## Welcome to the AI Face Swap Tool
82
+
83
+ This tool allows you to swap a face from one image onto another. It's easy to use, even if you're not tech-savvy!
84
+
85
+ ### How to Use:
86
+ 1. Upload a **Source Image** containing the face you want to use
87
+ 2. Upload a **Target Image** where you want to place the face
88
+ 3. Choose whether to enable **Face Enhancement** for better quality
89
+ 4. Click **Submit** and wait for the result
90
+
91
+ ### Tips for Best Results:
92
+ - Use high-quality images with clear, well-lit faces
93
+ - Front-facing photos work best
94
+ - Similar face angles between source and target give more natural results
95
+ - Processing may take a few seconds depending on image size
96
+
97
+ ### Ethical Usage Guidelines:
98
+ Please use this tool responsibly. Do not create misleading content or use someone's likeness without permission. This tool is provided for creative and educational purposes only.
99
+ """,
100
+ article="""
101
+ ### About This Technology
102
+
103
+ This face swap tool uses artificial intelligence to detect faces in both images and carefully blend them together. The process works by:
104
+
105
+ 1. Detecting facial features in both images
106
+ 2. Aligning the source face to match the target face's position
107
+ 3. Blending the images naturally while preserving lighting and skin tones
108
+ 4. Optional enhancement to improve details and realism
109
+
110
+ For technical support or questions, please contact the administrator.
111
+
112
+ *Remember: Use this tool ethically and responsibly.*
113
+ """
114
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
 
116
  app.launch()