KingNish commited on
Commit
55e1949
1 Parent(s): 5d2dafa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -50
app.py CHANGED
@@ -28,48 +28,78 @@ transform_image = transforms.Compose(
28
 
29
 
30
  @spaces.GPU
31
- def fn(vid, bg_type="Color", bg_image=None, color="#00FF00", fps=0):
32
- # Load the video using moviepy
33
- video = mp.VideoFileClip(vid)
34
-
35
- # Load original fps if fps value is equal to 0
36
- if fps == 0:
37
- fps = video.fps
38
-
39
- # Extract audio from the video
40
- audio = video.audio
41
-
42
- # Extract frames at the specified FPS
43
- frames = video.iter_frames(fps=fps)
44
-
45
- # Process each frame for background removal
46
- processed_frames = []
47
- yield gr.update(visible=True), gr.update(visible=False)
48
- for frame in frames:
49
- pil_image = Image.fromarray(frame)
50
- if bg_type == "Color":
51
- processed_image = process(pil_image, color)
 
 
 
 
 
 
52
  else:
53
- processed_image = process(pil_image, bg_image)
54
- processed_frames.append(np.array(processed_image))
55
- yield processed_image, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- # Create a new video from the processed frames
58
- processed_video = mp.ImageSequenceClip(processed_frames, fps=fps)
59
-
60
- # Add the original audio back to the processed video
61
- processed_video = processed_video.set_audio(audio)
62
-
63
- # Save the processed video to a temporary file
64
- temp_dir = "temp"
65
- os.makedirs(temp_dir, exist_ok=True)
66
- unique_filename = str(uuid.uuid4()) + ".mp4"
67
- temp_filepath = os.path.join(temp_dir, unique_filename)
68
- processed_video.write_videofile(temp_filepath, codec="libx264")
69
-
70
- yield gr.update(visible=False), gr.update(visible=True)
71
- # Return the path to the temporary file
72
- yield processed_image, temp_filepath
73
 
74
 
75
  def process(image, bg):
@@ -82,11 +112,13 @@ def process(image, bg):
82
  pred_pil = transforms.ToPILImage()(pred)
83
  mask = pred_pil.resize(image_size)
84
 
85
- if bg.startswith("#"):
86
- color_rgb = tuple(int(bg[i : i + 2], 16) for i in (1, 3, 5))
87
  background = Image.new("RGBA", image_size, color_rgb + (255,))
 
 
88
  else:
89
- background = Image.open(bg).convert("RGBA").resize(image_size)
90
 
91
  # Composite the image onto the background using the mask
92
  image = Image.composite(image, background, mask)
@@ -108,22 +140,34 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
108
  value=0,
109
  label="Output FPS (0 will inherit the original fps value)",
110
  )
111
- bg_type = gr.Radio(["Color", "Image"], label="Background Type", value="Color")
112
  color_picker = gr.ColorPicker(label="Background Color", value="#00FF00", visible=True)
113
  bg_image = gr.Image(label="Background Image", type="filepath", visible=False)
 
 
 
114
 
115
  def update_visibility(bg_type):
116
  if bg_type == "Color":
117
- return gr.update(visible=True), gr.update(visible=False)
 
 
 
 
118
  else:
119
- return gr.update(visible=False), gr.update(visible=True)
 
120
 
121
- bg_type.change(update_visibility, inputs=bg_type, outputs=[color_picker, bg_image])
122
 
123
 
124
  examples = gr.Examples(
125
- [["rickroll-2sec.mp4", "Image", "images.webp"], ["rickroll-2sec.mp4", "Color", None]],
126
- inputs=[in_video, bg_type, bg_image],
 
 
 
 
127
  outputs=[stream_image, out_video],
128
  fn=fn,
129
  cache_examples=True,
@@ -133,7 +177,7 @@ with gr.Blocks(theme=gr.themes.Ocean()) as demo:
133
 
134
  submit_button.click(
135
  fn,
136
- inputs=[in_video, bg_type, bg_image, color_picker, fps_slider],
137
  outputs=[stream_image, out_video],
138
  )
139
 
 
28
 
29
 
30
  @spaces.GPU
31
+ def fn(vid, bg_type="Color", bg_image=None, bg_video=None, color="#00FF00", fps=0, video_handling="slow_down"):
32
+ try:
33
+ # Load the video using moviepy
34
+ video = mp.VideoFileClip(vid)
35
+
36
+ # Load original fps if fps value is equal to 0
37
+ if fps == 0:
38
+ fps = video.fps
39
+
40
+ # Extract audio from the video
41
+ audio = video.audio
42
+
43
+ # Extract frames at the specified FPS
44
+ frames = video.iter_frames(fps=fps)
45
+
46
+ # Process each frame for background removal
47
+ processed_frames = []
48
+ yield gr.update(visible=True), gr.update(visible=False)
49
+
50
+ if bg_type == "Video":
51
+ background_video = mp.VideoFileClip(bg_video)
52
+ if background_video.duration < video.duration:
53
+ if video_handling == "slow_down":
54
+ background_video = background_video.fx(mp.vfx.speedx, factor=video.duration / background_video.duration)
55
+ else: # video_handling == "loop"
56
+ background_video = mp.concatenate_videoclips([background_video] * int(video.duration / background_video.duration + 1))
57
+ background_frames = background_video.iter_frames(fps=fps)
58
  else:
59
+ background_frames = None
60
+
61
+ for i, frame in enumerate(frames):
62
+ pil_image = Image.fromarray(frame)
63
+ if bg_type == "Color":
64
+ processed_image = process(pil_image, color)
65
+ elif bg_type == "Image":
66
+ processed_image = process(pil_image, bg_image)
67
+ elif bg_type == "Video":
68
+ try:
69
+ background_frame = next(background_frames)
70
+ background_image = Image.fromarray(background_frame)
71
+ processed_image = process(pil_image, background_image)
72
+ except StopIteration:
73
+ # Handle case where background video is shorter than input video
74
+ processed_image = process(pil_image, "#000000") # Default to black background
75
+ else:
76
+ processed_image = pil_image # Default to original image if no background is selected
77
+
78
+ processed_frames.append(np.array(processed_image))
79
+ yield processed_image, None
80
+
81
+ # Create a new video from the processed frames
82
+ processed_video = mp.ImageSequenceClip(processed_frames, fps=fps)
83
+
84
+ # Add the original audio back to the processed video
85
+ processed_video = processed_video.set_audio(audio)
86
+
87
+ # Save the processed video to a temporary file
88
+ temp_dir = "temp"
89
+ os.makedirs(temp_dir, exist_ok=True)
90
+ unique_filename = str(uuid.uuid4()) + ".mp4"
91
+ temp_filepath = os.path.join(temp_dir, unique_filename)
92
+ processed_video.write_videofile(temp_filepath, codec="libx264")
93
+
94
+ yield gr.update(visible=False), gr.update(visible=True)
95
+ # Return the path to the temporary file
96
+ yield processed_image, temp_filepath
97
+
98
+ except Exception as e:
99
+ print(f"Error: {e}")
100
+ yield gr.update(visible=False), gr.update(visible=True)
101
+ yield None, f"Error processing video: {e}"
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
 
105
  def process(image, bg):
 
112
  pred_pil = transforms.ToPILImage()(pred)
113
  mask = pred_pil.resize(image_size)
114
 
115
+ if isinstance(bg, str) and bg.startswith("#"):
116
+ color_rgb = tuple(int(bg[i:i+2], 16) for i in (1, 3, 5))
117
  background = Image.new("RGBA", image_size, color_rgb + (255,))
118
+ elif isinstance(bg, Image.Image):
119
+ background = bg.convert("RGBA").resize(image_size)
120
  else:
121
+ background = Image.new("RGBA", image_size, (0, 0, 0, 255)) # Default to black background
122
 
123
  # Composite the image onto the background using the mask
124
  image = Image.composite(image, background, mask)
 
140
  value=0,
141
  label="Output FPS (0 will inherit the original fps value)",
142
  )
143
+ bg_type = gr.Radio(["Color", "Image", "Video"], label="Background Type", value="Color")
144
  color_picker = gr.ColorPicker(label="Background Color", value="#00FF00", visible=True)
145
  bg_image = gr.Image(label="Background Image", type="filepath", visible=False)
146
+ bg_video = gr.Video(label="Background Video", visible=False)
147
+ with gr.Column(visible=False) as video_handling_options:
148
+ video_handling_radio = gr.Radio(["slow_down", "loop"], label="Video Handling", value="slow_down")
149
 
150
  def update_visibility(bg_type):
151
  if bg_type == "Color":
152
+ return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
153
+ elif bg_type == "Image":
154
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
155
+ elif bg_type == "Video":
156
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), gr.update(visible=True)
157
  else:
158
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
159
+
160
 
161
+ bg_type.change(update_visibility, inputs=bg_type, outputs=[color_picker, bg_image, bg_video, video_handling_options])
162
 
163
 
164
  examples = gr.Examples(
165
+ [
166
+ ["rickroll-2sec.mp4", "Image", "images.webp", None],
167
+ ["rickroll-2sec.mp4", "Color", None, None],
168
+ ["rickroll-2sec.mp4", "Video", None, "background.mp4"]
169
+ ],
170
+ inputs=[in_video, bg_type, bg_image, bg_video],
171
  outputs=[stream_image, out_video],
172
  fn=fn,
173
  cache_examples=True,
 
177
 
178
  submit_button.click(
179
  fn,
180
+ inputs=[in_video, bg_type, bg_image, bg_video, color_picker, fps_slider, video_handling_radio],
181
  outputs=[stream_image, out_video],
182
  )
183