Ii commited on
Commit
c0b1bd9
·
verified ·
1 Parent(s): 04dd9f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -41
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import gradio as gr
2
- from refacer import Refacer
3
- import argparse
4
  import os
5
  import requests
 
6
 
7
  # Hugging Face URL to download the model
8
  model_url = "https://huggingface.co/ofter/4x-UltraSharp/resolve/main/inswapper_128.onnx"
@@ -25,42 +26,67 @@ def download_model():
25
  # Download the model when the script runs
26
  download_model()
27
 
28
- # Argument parser
29
- parser = argparse.ArgumentParser(description='Refacer')
30
- parser.add_argument("--max_num_faces", type=int, help="Max number of faces on UI", default=5)
31
- parser.add_argument("--force_cpu", help="Force CPU mode", default=False, action="store_true")
32
- parser.add_argument("--share_gradio", help="Share Gradio", default=False, action="store_true")
33
- parser.add_argument("--server_name", type=str, help="Server IP address", default="127.0.0.1")
34
- parser.add_argument("--server_port", type=int, help="Server port", default=7860)
35
- parser.add_argument("--colab_performance", help="Use in colab for better performance", default=False, action="store_true")
36
- args = parser.parse_args()
37
-
38
- # Initialize the Refacer class
39
- refacer = Refacer(force_cpu=args.force_cpu, colab_performance=args.colab_performance)
40
-
41
- num_faces = args.max_num_faces
42
-
43
- # Run function for refacing video
44
- def run(*vars):
45
- video_path = vars[0]
46
- origins = vars[1:(num_faces+1)]
47
- destinations = vars[(num_faces+1):(num_faces*2)+1]
48
- thresholds = vars[(num_faces*2)+1:]
49
-
50
- faces = []
51
- for k in range(0, num_faces):
52
- if origins[k] is not None and destinations[k] is not None:
53
- faces.append({
54
- 'origin': origins[k],
55
- 'destination': destinations[k],
56
- 'threshold': thresholds[k]
57
- })
58
-
59
- # Call refacer to process video and get file path
60
- refaced_video_path = refacer.reface(video_path, faces) # refaced video path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  print(f"Refaced video can be found at {refaced_video_path}")
62
 
63
- return refaced_video_path # Return the file path to show in Gradio output
64
 
65
  # Prepare Gradio components
66
  origin = []
@@ -71,10 +97,10 @@ with gr.Blocks() as demo:
71
  with gr.Row():
72
  gr.Markdown("# Refacer")
73
  with gr.Row():
74
- video = gr.Video(label="Original video", format="mp4")
75
- video2 = gr.Video(label="Refaced video", interactive=False, format="mp4")
76
 
77
- for i in range(0, num_faces):
78
  with gr.Tab(f"Face #{i+1}"):
79
  with gr.Row():
80
  origin.append(gr.Image(label="Face to replace"))
@@ -85,7 +111,7 @@ with gr.Blocks() as demo:
85
  with gr.Row():
86
  button = gr.Button("Reface", variant="primary")
87
 
88
- button.click(fn=run, inputs=[video] + origin + destination + thresholds, outputs=[video2])
89
 
90
  # Launch the Gradio app
91
- demo.queue().launch(show_error=True, share=args.share_gradio, server_name="0.0.0.0", server_port=args.server_port)
 
1
  import gradio as gr
2
+ import cv2
3
+ import multiprocessing
4
  import os
5
  import requests
6
+ from refacer import Refacer
7
 
8
  # Hugging Face URL to download the model
9
  model_url = "https://huggingface.co/ofter/4x-UltraSharp/resolve/main/inswapper_128.onnx"
 
26
  # Download the model when the script runs
27
  download_model()
28
 
29
+ # Initialize Refacer class (force CPU mode)
30
+ refacer = Refacer(force_cpu=True)
31
+
32
+ # Dummy function to simulate frame-level processing
33
+ def process_frame(frame, origin_face, destination_face, threshold):
34
+ # Simulate face swapping or any processing needed
35
+ result_frame = refacer.reface(frame, [{
36
+ 'origin': origin_face,
37
+ 'destination': destination_face,
38
+ 'threshold': threshold
39
+ }])
40
+ return result_frame
41
+
42
+ # Function to process the video in parallel using multiprocessing
43
+ def process_video(video_path, origins, destinations, thresholds, max_processes=2):
44
+ cap = cv2.VideoCapture(video_path)
45
+ frames = []
46
+
47
+ # Read all frames from the video
48
+ while cap.isOpened():
49
+ ret, frame = cap.read()
50
+ if not ret:
51
+ break
52
+ frames.append(frame)
53
+
54
+ cap.release()
55
+
56
+ # Parallel processing of frames with limited processes (for CPU optimization)
57
+ with multiprocessing.Pool(processes=max_processes) as pool:
58
+ processed_frames = pool.starmap(process_frame, [
59
+ (frame, origins[min(i, len(origins) - 1)], destinations[min(i, len(destinations) - 1)], thresholds[min(i, len(thresholds) - 1)])
60
+ for i, frame in enumerate(frames)
61
+ ])
62
+
63
+ # Saving the processed frames back into a video
64
+ output_video_path = "processed_video.mp4"
65
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Compression using mp4 codec
66
+ out = cv2.VideoWriter(output_video_path, fourcc, 30.0, (640, 360)) # Reduce resolution to speed up processing
67
+
68
+ for frame in processed_frames:
69
+ out.write(frame)
70
+
71
+ out.release()
72
+ return output_video_path
73
+
74
+ # Gradio Interface function
75
+ def run(video_path, *vars):
76
+ # Split the inputs into origins, destinations, and thresholds based on num_faces
77
+ num_faces = 5 # You can adjust this based on your UI
78
+ origins = vars[:num_faces]
79
+ destinations = vars[num_faces:2*num_faces]
80
+ thresholds = vars[2*num_faces:]
81
+
82
+ # Ensure there are no index errors by limiting the number of inputs
83
+ if len(origins) != num_faces or len(destinations) != num_faces or len(thresholds) != num_faces:
84
+ return "Please provide input for all faces."
85
+
86
+ refaced_video_path = process_video(video_path, origins, destinations, thresholds)
87
  print(f"Refaced video can be found at {refaced_video_path}")
88
 
89
+ return refaced_video_path
90
 
91
  # Prepare Gradio components
92
  origin = []
 
97
  with gr.Row():
98
  gr.Markdown("# Refacer")
99
  with gr.Row():
100
+ video_input = gr.Video(label="Original video", format="mp4")
101
+ video_output = gr.Video(label="Refaced video", interactive=False, format="mp4")
102
 
103
+ for i in range(5): # Set max faces to 5
104
  with gr.Tab(f"Face #{i+1}"):
105
  with gr.Row():
106
  origin.append(gr.Image(label="Face to replace"))
 
111
  with gr.Row():
112
  button = gr.Button("Reface", variant="primary")
113
 
114
+ button.click(fn=run, inputs=[video_input] + origin + destination + thresholds, outputs=[video_output])
115
 
116
  # Launch the Gradio app
117
+ demo.launch(show_error=True, server_name="0.0.0.0", server_port=7860)