KingNish commited on
Commit
a2b9299
1 Parent(s): 6785fcb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -62
app.py CHANGED
@@ -5,19 +5,19 @@ from transformers import AutoModelForImageSegmentation
5
  import torch
6
  from torchvision import transforms
7
  import moviepy.editor as mp
 
8
  from PIL import Image
9
  import numpy as np
10
  import os
11
  import tempfile
12
  import uuid
13
- from concurrent.futures import ThreadPoolExecutor
14
 
15
  torch.set_float32_matmul_precision("highest")
16
 
17
  birefnet = AutoModelForImageSegmentation.from_pretrained(
18
  "ZhengPeng7/BiRefNet", trust_remote_code=True
19
- ).to("cuda")
20
-
21
  transform_image = transforms.Compose(
22
  [
23
  transforms.Resize((1024, 1024)),
@@ -26,85 +26,79 @@ transform_image = transforms.Compose(
26
  ]
27
  )
28
 
29
- BATCH_SIZE = 3
30
- executor = ThreadPoolExecutor(max_workers=4) # Adjust as needed
31
-
32
- def get_background_image(bg_type, bg_image, background_frames, current_frame_index, video_handling, slow_down_factor):
33
- if bg_type == "Video":
34
- if video_handling == "slow_down":
35
- frame_index = int(current_frame_index / slow_down_factor)
36
- else:
37
- frame_index = current_frame_index
38
- return Image.fromarray(background_frames[frame_index % len(background_frames)])
39
- elif bg_type == "Image":
40
- return bg_image # Directly returns the image path
41
- else: # bg_type == "Color"
42
- return bg_image # bg_image here is the color string
43
 
44
  @spaces.GPU
45
  def fn(vid, bg_type="Color", bg_image=None, bg_video=None, color="#00FF00", fps=0, video_handling="slow_down"):
46
  try:
 
47
  video = mp.VideoFileClip(vid)
48
- try:
49
- audio = video.audio
50
- except AttributeError:
51
- audio = None
52
 
 
53
  if fps == 0:
54
  fps = video.fps
 
 
 
 
 
55
  frames = video.iter_frames(fps=fps)
 
 
56
  processed_frames = []
57
- yield gr.update(visible=True), gr.update(visible=False) # Update Gradio display
58
 
59
  if bg_type == "Video":
60
  background_video = mp.VideoFileClip(bg_video)
61
- if background_video.duration < video.duration and video_handling == "slow_down":
62
- slow_down_factor = video.duration / background_video.duration
63
- else:
64
- slow_down_factor = 1
65
- background_frames = list(background_video.iter_frames(fps=fps))
 
66
  else:
67
  background_frames = None
68
- slow_down_factor = None # Not needed for image or color backgrounds
69
 
70
- bg_frame_index = 0
71
- frame_batch = []
72
 
73
  for i, frame in enumerate(frames):
74
- frame_batch.append(frame)
75
- if len(frame_batch) == BATCH_SIZE or i == int(video.fps * video.duration) - 1:
76
- pil_images = [Image.fromarray(f) for f in frame_batch]
77
-
78
- if bg_type == "Video":
79
- processed_images = list(executor.map(process, pil_images, [get_background_image(bg_type, bg_image, background_frames, bg_frame_index + j, video_handling, slow_down_factor) for j in range(len(pil_images))]))
80
- bg_frame_index += len(frame_batch)
81
- elif bg_type == "Color":
82
- processed_images = list(executor.map(process, pil_images, [color] * len(pil_images))) # Use color directly
83
- elif bg_type == "Image":
84
- processed_images = list(executor.map(process, pil_images, [bg_image] * len(pil_images))) # Use image path directly
85
- else:
86
- processed_images = pil_images # No processing needed
87
-
88
- for processed_image in processed_images:
89
- processed_frames.append(np.array(processed_image))
90
- yield processed_image, None # Update Gradio with processed images
91
- frame_batch = []
92
 
 
 
93
 
 
94
  processed_video = mp.ImageSequenceClip(processed_frames, fps=fps)
95
- if audio:
96
- processed_video = processed_video.set_audio(audio)
97
 
98
- # Save processed video to a temporary file
 
 
 
99
  temp_dir = "temp"
100
  os.makedirs(temp_dir, exist_ok=True)
101
  unique_filename = str(uuid.uuid4()) + ".mp4"
102
  temp_filepath = os.path.join(temp_dir, unique_filename)
103
- processed_video.write_videofile(temp_filepath, codec="libx264", logger=None)
104
 
105
-
106
- yield gr.update(visible=False), gr.update(visible=True) # Update Gradio display
107
- yield processed_image, temp_filepath # Return final output
108
 
109
  except Exception as e:
110
  print(f"Error: {e}")
@@ -113,27 +107,28 @@ def fn(vid, bg_type="Color", bg_image=None, bg_video=None, color="#00FF00", fps=
113
 
114
 
115
 
116
-
117
  def process(image, bg):
118
  image_size = image.size
119
  input_images = transform_image(image).unsqueeze(0).to("cuda")
 
120
  with torch.no_grad():
121
  preds = birefnet(input_images)[-1].sigmoid().cpu()
122
  pred = preds[0].squeeze()
123
  pred_pil = transforms.ToPILImage()(pred)
124
  mask = pred_pil.resize(image_size)
125
 
126
- if isinstance(bg, str) and bg.startswith("#"): # If bg is a color
127
  color_rgb = tuple(int(bg[i:i+2], 16) for i in (1, 3, 5))
128
- background = Image.new("RGBA", image_size, color_rgb + (255,)) # Create image with color
129
  elif isinstance(bg, Image.Image):
130
- background = bg.convert("RGBA").resize(image_size) #Resize if bg is an image
131
- else: #If bg is an image path
132
- background = Image.open(bg).convert("RGBA").resize(image_size) # Open and resize image
133
 
 
134
  image = Image.composite(image, background, mask)
135
- return image
136
 
 
137
 
138
 
139
  with gr.Blocks(theme=gr.themes.Ocean()) as demo:
 
5
  import torch
6
  from torchvision import transforms
7
  import moviepy.editor as mp
8
+ from pydub import AudioSegment
9
  from PIL import Image
10
  import numpy as np
11
  import os
12
  import tempfile
13
  import uuid
 
14
 
15
  torch.set_float32_matmul_precision("highest")
16
 
17
  birefnet = AutoModelForImageSegmentation.from_pretrained(
18
  "ZhengPeng7/BiRefNet", trust_remote_code=True
19
+ )
20
+ birefnet.to("cuda")
21
  transform_image = transforms.Compose(
22
  [
23
  transforms.Resize((1024, 1024)),
 
26
  ]
27
  )
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 = list(background_video.iter_frames(fps=fps)) # Convert to list
58
  else:
59
  background_frames = None
 
60
 
61
+ bg_frame_index = 0 # Initialize background frame index
 
62
 
63
  for i, frame in enumerate(frames):
64
+ pil_image = Image.fromarray(frame)
65
+ if bg_type == "Color":
66
+ processed_image = process(pil_image, color)
67
+ elif bg_type == "Image":
68
+ processed_image = process(pil_image, bg_image)
69
+ elif bg_type == "Video":
70
+ if video_handling == "slow_down":
71
+ background_frame = background_frames[bg_frame_index % len(background_frames)]
72
+ bg_frame_index += 1
73
+ background_image = Image.fromarray(background_frame)
74
+ processed_image = process(pil_image, background_image)
75
+ else: # video_handling == "loop"
76
+ background_frame = background_frames[bg_frame_index % len(background_frames)]
77
+ bg_frame_index += 1
78
+ background_image = Image.fromarray(background_frame)
79
+ processed_image = process(pil_image, background_image)
80
+ else:
81
+ processed_image = pil_image # Default to original image if no background is selected
82
 
83
+ processed_frames.append(np.array(processed_image))
84
+ yield processed_image, None
85
 
86
+ # Create a new video from the processed frames
87
  processed_video = mp.ImageSequenceClip(processed_frames, fps=fps)
 
 
88
 
89
+ # Add the original audio back to the processed video
90
+ processed_video = processed_video.set_audio(audio)
91
+
92
+ # Save the processed video to a temporary file
93
  temp_dir = "temp"
94
  os.makedirs(temp_dir, exist_ok=True)
95
  unique_filename = str(uuid.uuid4()) + ".mp4"
96
  temp_filepath = os.path.join(temp_dir, unique_filename)
97
+ processed_video.write_videofile(temp_filepath, codec="libx264")
98
 
99
+ yield gr.update(visible=False), gr.update(visible=True)
100
+ # Return the path to the temporary file
101
+ yield processed_image, temp_filepath
102
 
103
  except Exception as e:
104
  print(f"Error: {e}")
 
107
 
108
 
109
 
 
110
  def process(image, bg):
111
  image_size = image.size
112
  input_images = transform_image(image).unsqueeze(0).to("cuda")
113
+ # Prediction
114
  with torch.no_grad():
115
  preds = birefnet(input_images)[-1].sigmoid().cpu()
116
  pred = preds[0].squeeze()
117
  pred_pil = transforms.ToPILImage()(pred)
118
  mask = pred_pil.resize(image_size)
119
 
120
+ if isinstance(bg, str) and bg.startswith("#"):
121
  color_rgb = tuple(int(bg[i:i+2], 16) for i in (1, 3, 5))
122
+ background = Image.new("RGBA", image_size, color_rgb + (255,))
123
  elif isinstance(bg, Image.Image):
124
+ background = bg.convert("RGBA").resize(image_size)
125
+ else:
126
+ background = Image.open(bg).convert("RGBA").resize(image_size)
127
 
128
+ # Composite the image onto the background using the mask
129
  image = Image.composite(image, background, mask)
 
130
 
131
+ return image
132
 
133
 
134
  with gr.Blocks(theme=gr.themes.Ocean()) as demo: