KingNish commited on
Commit
ff98b47
1 Parent(s): f1cdcfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -57
app.py CHANGED
@@ -26,102 +26,93 @@ transform_image = transforms.Compose(
26
  ]
27
  )
28
 
29
-
30
  @spaces.GPU
31
- def fn(vid, fps, color):
32
  # Load the video using moviepy
33
  video = mp.VideoFileClip(vid)
34
-
35
- # Extract audio from the video
36
  audio = video.audio
37
-
38
- # Extract frames at the specified FPS
39
- frames = video.iter_frames(fps=fps)
40
-
41
- # Process each frame for background removal
42
  processed_frames_no_bg = []
43
  processed_frames_changed_bg = []
44
- for frame in frames:
 
 
 
 
 
45
  pil_image = Image.fromarray(frame)
46
- processed_image, mask = process(pil_image, color) # Get both processed image and mask
47
- processed_frames_no_bg.append(np.array(processed_image)) # Save no-background frame
 
48
 
49
- # Compose with background for changed background video
50
  background = Image.new("RGBA", pil_image.size, color + (255,))
51
  composed_image = Image.composite(pil_image, background, mask)
52
  processed_frames_changed_bg.append(np.array(composed_image))
53
-
54
- # Create a new video from the processed frames
55
- processed_video = mp.ImageSequenceClip(processed_frames_changed_bg, fps=fps)
56
-
57
- # Add the original audio back to the processed video
58
- processed_video = processed_video.set_audio(audio)
59
-
60
- # Save the processed video to a temporary file
61
  temp_dir = "temp"
62
  os.makedirs(temp_dir, exist_ok=True)
63
- unique_filename = str(uuid.uuid4()) + ".mp4"
64
- temp_filepath = os.path.join(temp_dir, unique_filename)
 
 
65
  processed_video.write_videofile(temp_filepath, codec="libx264")
66
-
67
- # Create and save no-background video
68
  processed_video_no_bg = mp.ImageSequenceClip(processed_frames_no_bg, fps=fps)
69
  processed_video_no_bg = processed_video_no_bg.set_audio(audio)
70
- temp_filepath_no_bg = os.path.join(temp_dir, str(uuid.uuid4()) + ".webm")
71
  processed_video_no_bg.write_videofile(temp_filepath_no_bg, codec="libvpx")
72
-
73
- return temp_filepath_no_bg, temp_filepath
74
-
75
 
76
  def process(image, color_hex):
77
  image_size = image.size
78
  input_images = transform_image(image).unsqueeze(0).to("cuda")
79
- # Prediction
80
  with torch.no_grad():
81
  preds = birefnet(input_images)[-1].sigmoid().cpu()
82
  pred = preds[0].squeeze()
83
  pred_pil = transforms.ToPILImage()(pred)
84
  mask = pred_pil.resize(image_size)
85
-
86
- # Convert hex color to RGB tuple
87
  color_rgb = tuple(int(color_hex[i:i + 2], 16) for i in (1, 3, 5))
88
-
89
- # Create a background image with the chosen color
90
  background = Image.new("RGBA", image_size, color_rgb + (255,))
91
-
92
- # Composite the image onto the background using the mask
93
  image = Image.composite(image, background, mask)
94
-
95
- return image, mask # Return both the processed image and the mask
96
-
97
-
98
- def process_file(f, color="#00FF00"):
99
- name_path = f.rsplit(".", 1)[0] + ".png"
100
- im = load_img(f, output_type="pil")
101
- im = im.convert("RGB")
102
- transparent = process(im, color)
103
- transparent.save(name_path)
104
- return name_path
105
-
106
 
107
  def change_color(in_video, fps_slider, color_picker):
108
- no_bg_video_path, changed_bg_video_path = fn(in_video, fps_slider, color_picker)
109
- return no_bg_video_path, changed_bg_video_path
110
-
111
 
112
  with gr.Blocks() as demo:
113
  with gr.Row():
114
  in_video = gr.Video(label="Input Video")
115
- no_bg_video = gr.Video(label="No BG Video") # Added for no-background video
116
- out_video = gr.Video(label="Output Video") # This will be the changed-background video
117
- submit_button = gr.Button("Change Background")
 
 
 
 
118
  with gr.Row():
119
  fps_slider = gr.Slider(minimum=1, maximum=60, step=1, value=12, label="Output FPS")
120
  color_picker = gr.ColorPicker(label="Background Color", value="#00FF00")
121
-
122
-
 
 
123
  submit_button.click(
124
- change_color, inputs=[in_video, fps_slider, color_picker], outputs=[no_bg_video, out_video]
 
 
125
  )
126
 
127
  if __name__ == "__main__":
 
26
  ]
27
  )
28
 
 
29
  @spaces.GPU
30
+ def fn(vid, fps, color, progress=gr.Progress()):
31
  # Load the video using moviepy
32
  video = mp.VideoFileClip(vid)
 
 
33
  audio = video.audio
34
+ frames = list(video.iter_frames(fps=fps))
35
+ total_frames = len(frames)
36
+
 
 
37
  processed_frames_no_bg = []
38
  processed_frames_changed_bg = []
39
+
40
+ # Create a live preview state
41
+ preview_no_bg = None
42
+ preview_with_bg = None
43
+
44
+ for idx, frame in enumerate(progress.tqdm(frames)):
45
  pil_image = Image.fromarray(frame)
46
+ processed_image, mask = process(pil_image, color)
47
+
48
+ processed_frames_no_bg.append(np.array(processed_image))
49
 
 
50
  background = Image.new("RGBA", pil_image.size, color + (255,))
51
  composed_image = Image.composite(pil_image, background, mask)
52
  processed_frames_changed_bg.append(np.array(composed_image))
53
+
54
+ # Update preview every 10 frames or on the last frame
55
+ if idx % 10 == 0 or idx == total_frames - 1:
56
+ preview_no_bg = np.array(processed_image)
57
+ preview_with_bg = np.array(composed_image)
58
+ yield preview_no_bg, preview_with_bg, None, None
59
+
60
+ # Create videos from processed frames
61
  temp_dir = "temp"
62
  os.makedirs(temp_dir, exist_ok=True)
63
+
64
+ processed_video = mp.ImageSequenceClip(processed_frames_changed_bg, fps=fps)
65
+ processed_video = processed_video.set_audio(audio)
66
+ temp_filepath = os.path.join(temp_dir, f"{uuid.uuid4()}.mp4")
67
  processed_video.write_videofile(temp_filepath, codec="libx264")
68
+
 
69
  processed_video_no_bg = mp.ImageSequenceClip(processed_frames_no_bg, fps=fps)
70
  processed_video_no_bg = processed_video_no_bg.set_audio(audio)
71
+ temp_filepath_no_bg = os.path.join(temp_dir, f"{uuid.uuid4()}.webm")
72
  processed_video_no_bg.write_videofile(temp_filepath_no_bg, codec="libvpx")
73
+
74
+ # Final yield with completed videos
75
+ yield None, None, temp_filepath_no_bg, temp_filepath
76
 
77
  def process(image, color_hex):
78
  image_size = image.size
79
  input_images = transform_image(image).unsqueeze(0).to("cuda")
 
80
  with torch.no_grad():
81
  preds = birefnet(input_images)[-1].sigmoid().cpu()
82
  pred = preds[0].squeeze()
83
  pred_pil = transforms.ToPILImage()(pred)
84
  mask = pred_pil.resize(image_size)
85
+
 
86
  color_rgb = tuple(int(color_hex[i:i + 2], 16) for i in (1, 3, 5))
 
 
87
  background = Image.new("RGBA", image_size, color_rgb + (255,))
 
 
88
  image = Image.composite(image, background, mask)
89
+
90
+ return image, mask
 
 
 
 
 
 
 
 
 
 
91
 
92
  def change_color(in_video, fps_slider, color_picker):
93
+ return gr.update(visible=True), gr.update(visible=True), gr.update(visible=False), gr.update(visible=False)
 
 
94
 
95
  with gr.Blocks() as demo:
96
  with gr.Row():
97
  in_video = gr.Video(label="Input Video")
98
+ no_bg_video = gr.Video(label="No BG Video", visible=True)
99
+ out_video = gr.Video(label="Output Video", visible=True)
100
+
101
+ with gr.Row(visible=False) as preview_row:
102
+ preview_no_bg = gr.Image(label="Live Preview (No Background)", visible=True)
103
+ preview_with_bg = gr.Image(label="Live Preview (With Background)", visible=True)
104
+
105
  with gr.Row():
106
  fps_slider = gr.Slider(minimum=1, maximum=60, step=1, value=12, label="Output FPS")
107
  color_picker = gr.ColorPicker(label="Background Color", value="#00FF00")
108
+
109
+ submit_button = gr.Button("Change Background")
110
+
111
+ # Handle visibility changes and processing
112
  submit_button.click(
113
+ fn=fn,
114
+ inputs=[in_video, fps_slider, color_picker],
115
+ outputs=[preview_no_bg, preview_with_bg, no_bg_video, out_video]
116
  )
117
 
118
  if __name__ == "__main__":