Spaces:
Sleeping
Sleeping
Update video_processing.py
Browse files- video_processing.py +111 -89
video_processing.py
CHANGED
|
@@ -7,117 +7,139 @@ from transformers import CLIPProcessor, CLIPModel
|
|
| 7 |
import torch
|
| 8 |
import yt_dlp
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
# Segment video into scenes
|
| 15 |
-
scenes = find_scenes(video_path)
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
if os.path.exists(final_clip_path):
|
| 31 |
-
os.remove(final_clip_path)
|
| 32 |
-
final_clip.write_videofile(final_clip_path, codec='libx264', audio_codec='aac')
|
| 33 |
-
except Exception as e:
|
| 34 |
-
return str(e)
|
| 35 |
|
| 36 |
-
|
|
|
|
| 37 |
|
| 38 |
def find_scenes(video_path):
|
| 39 |
-
# Create a video manager object for the video
|
| 40 |
video_manager = VideoManager([video_path])
|
| 41 |
scene_manager = SceneManager()
|
| 42 |
-
|
| 43 |
-
# Add ContentDetector algorithm with a threshold. Adjust threshold as needed.
|
| 44 |
scene_manager.add_detector(ContentDetector(threshold=30))
|
| 45 |
-
|
| 46 |
-
# Start the video manager and perform scene detection
|
| 47 |
video_manager.set_downscale_factor()
|
| 48 |
video_manager.start()
|
| 49 |
scene_manager.detect_scenes(frame_source=video_manager)
|
| 50 |
-
|
| 51 |
-
# Obtain list of detected scenes as timecodes
|
| 52 |
scene_list = scene_manager.get_scene_list()
|
| 53 |
video_manager.release()
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
def convert_timestamp_to_seconds(timestamp):
|
| 60 |
-
"""Convert a timestamp in HH:MM:SS format to seconds."""
|
| 61 |
h, m, s = map(float, timestamp.split(':'))
|
| 62 |
return int(h) * 3600 + int(m) * 60 + s
|
| 63 |
|
| 64 |
-
def
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
end_seconds = convert_timestamp_to_seconds(end_time)
|
| 68 |
-
video_clip = VideoFileClip(video_path).subclip(start_seconds, end_seconds)
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
frames.append(frame)
|
| 73 |
|
| 74 |
-
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
highest_prob = 0.0
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
frames = extract_frames(video_path, start_time, end_time)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
for frame in frames:
|
| 90 |
-
inputs = processor(text=description, images=frame, return_tensors="pt", padding=True)
|
| 91 |
-
outputs = model(**inputs)
|
| 92 |
-
logits_per_image = outputs.logits_per_image
|
| 93 |
-
probs = logits_per_image.softmax(dim=1)
|
| 94 |
-
|
| 95 |
-
max_prob = max(probs[0]).item()
|
| 96 |
-
if max_prob > highest_prob:
|
| 97 |
-
highest_prob = max_prob
|
| 98 |
-
best_scene = (start_time, end_time)
|
| 99 |
-
|
| 100 |
-
return best_scene
|
| 101 |
-
|
| 102 |
-
def extract_best_scene(video_path, scene):
|
| 103 |
-
if scene is None:
|
| 104 |
-
return VideoFileClip(video_path) # Return the entire video if no scene is found
|
| 105 |
-
|
| 106 |
-
start_time, end_time = scene
|
| 107 |
-
start_seconds = convert_timestamp_to_seconds(start_time)
|
| 108 |
-
end_seconds = convert_timestamp_to_seconds(end_time)
|
| 109 |
-
video_clip = VideoFileClip(video_path).subclip(start_seconds, end_seconds)
|
| 110 |
-
return video_clip
|
| 111 |
|
| 112 |
-
def
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
-
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 120 |
-
info_dict = ydl.extract_info(video_url, download=True)
|
| 121 |
-
video_file = ydl.prepare_filename(info_dict)
|
| 122 |
-
|
| 123 |
-
return video_file
|
|
|
|
| 7 |
import torch
|
| 8 |
import yt_dlp
|
| 9 |
|
| 10 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 11 |
+
model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device)
|
| 12 |
+
processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
def download_video(url):
|
| 15 |
+
ydl_opts = {
|
| 16 |
+
'format': 'bestvideo[height<=1440]+bestaudio/best[height<=1440]',
|
| 17 |
+
'outtmpl': 'downloaded_video.%(ext)s',
|
| 18 |
+
'merge_output_format': 'mp4',
|
| 19 |
+
}
|
| 20 |
+
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
| 21 |
+
result = ydl.extract_info(url, download=True)
|
| 22 |
+
video_filename = ydl.prepare_filename(result)
|
| 23 |
+
safe_filename = sanitize_filename(video_filename)
|
| 24 |
+
if os.path.exists(video_filename) and video_filename != safe_filename:
|
| 25 |
+
os.rename(video_filename, safe_filename)
|
| 26 |
+
return safe_filename
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
def sanitize_filename(filename):
|
| 29 |
+
return "".join([c if c.isalnum() or c in " .-_()" else "_" for c in filename])
|
| 30 |
|
| 31 |
def find_scenes(video_path):
|
|
|
|
| 32 |
video_manager = VideoManager([video_path])
|
| 33 |
scene_manager = SceneManager()
|
|
|
|
|
|
|
| 34 |
scene_manager.add_detector(ContentDetector(threshold=30))
|
|
|
|
|
|
|
| 35 |
video_manager.set_downscale_factor()
|
| 36 |
video_manager.start()
|
| 37 |
scene_manager.detect_scenes(frame_source=video_manager)
|
|
|
|
|
|
|
| 38 |
scene_list = scene_manager.get_scene_list()
|
| 39 |
video_manager.release()
|
| 40 |
+
return scene_list
|
| 41 |
+
|
| 42 |
+
def extract_frames(video_path, scene_list):
|
| 43 |
+
scene_frames = {}
|
| 44 |
+
cap = cv2.VideoCapture(video_path)
|
| 45 |
+
for i, (start_time, end_time) in enumerate(scene_list):
|
| 46 |
+
frames = []
|
| 47 |
+
first_frame = None
|
| 48 |
+
start_frame = start_time.get_frames()
|
| 49 |
+
end_frame = end_time.get_frames()
|
| 50 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
|
| 51 |
+
while cap.get(cv2.CAP_PROP_POS_FRAMES) < end_frame:
|
| 52 |
+
ret, frame = cap.read()
|
| 53 |
+
if ret:
|
| 54 |
+
if first_frame is None:
|
| 55 |
+
first_frame = frame
|
| 56 |
+
if int(cap.get(cv2.CAP_PROP_POS_FRAMES)) % 5 == 0:
|
| 57 |
+
frames.append(frame)
|
| 58 |
+
scene_frames[i] = (start_time, end_time, frames, first_frame)
|
| 59 |
+
cap.release()
|
| 60 |
+
return scene_frames
|
| 61 |
|
| 62 |
def convert_timestamp_to_seconds(timestamp):
|
|
|
|
| 63 |
h, m, s = map(float, timestamp.split(':'))
|
| 64 |
return int(h) * 3600 + int(m) * 60 + s
|
| 65 |
|
| 66 |
+
def classify_and_categorize_scenes(scene_frames, description_phrases):
|
| 67 |
+
scene_categories = {}
|
| 68 |
+
description_texts = description_phrases
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
action_indices = [0]
|
| 71 |
+
context_indices = list(set(range(len(description_texts))) - set(action_indices))
|
|
|
|
| 72 |
|
| 73 |
+
for scene_id, (start_time, end_time, frames, first_frame) in scene_frames.items():
|
| 74 |
+
scene_scores = [0] * len(description_texts)
|
| 75 |
+
valid_frames = 0
|
| 76 |
|
| 77 |
+
for frame in frames:
|
| 78 |
+
image = Image.fromarray(frame[..., ::-1])
|
| 79 |
+
image_input = processor(images=image, return_tensors="pt").to(device)
|
| 80 |
+
with torch.no_grad():
|
| 81 |
+
text_inputs = processor(text=description_texts, return_tensors="pt", padding=True).to(device)
|
| 82 |
+
text_features = model.get_text_features(**text_inputs)
|
| 83 |
+
image_features = model.get_image_features(**image_input)
|
| 84 |
+
logits = (image_features @ text_features.T).squeeze()
|
| 85 |
+
probs = logits.softmax(dim=0)
|
| 86 |
+
scene_scores = [sum(x) for x in zip(scene_scores, probs.tolist())]
|
| 87 |
+
valid_frames += 1
|
| 88 |
+
|
| 89 |
+
if valid_frames > 0:
|
| 90 |
+
scene_scores = [score / valid_frames for score in scene_scores]
|
| 91 |
+
action_confidence = sum(scene_scores[i] for i in action_indices) / len(action_indices)
|
| 92 |
+
context_confidence = sum(scene_scores[i] for i in context_indices) / len(context_indices)
|
| 93 |
+
|
| 94 |
+
best_description_index = scene_scores.index(max(scene_scores))
|
| 95 |
+
best_description = description_texts[best_description_index]
|
| 96 |
+
|
| 97 |
+
if action_confidence > context_confidence:
|
| 98 |
+
category = "Action Scene"
|
| 99 |
+
confidence = action_confidence
|
| 100 |
+
else:
|
| 101 |
+
category = "Context Scene"
|
| 102 |
+
confidence = context_confidence
|
| 103 |
+
|
| 104 |
+
duration = end_time.get_seconds() - start_time.get_seconds()
|
| 105 |
+
scene_categories[scene_id] = {
|
| 106 |
+
"category": category,
|
| 107 |
+
"confidence": confidence,
|
| 108 |
+
"start_time": str(start_time),
|
| 109 |
+
"end_time": str(end_time),
|
| 110 |
+
"duration": duration,
|
| 111 |
+
"first_frame": first_frame,
|
| 112 |
+
"best_description": best_description
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
return scene_categories
|
| 116 |
+
|
| 117 |
+
def save_clip(video_path, scene_info, output_directory, scene_id):
|
| 118 |
+
output_filename = f"scene_{scene_id+1}_{scene_info['category'].replace(' ', '_')}.mp4"
|
| 119 |
+
output_filepath = os.path.join(output_directory, output_filename)
|
| 120 |
+
|
| 121 |
+
start_seconds = convert_timestamp_to_seconds(scene_info['start_time'])
|
| 122 |
+
end_seconds = convert_timestamp_to_seconds(scene_info['end_time'])
|
| 123 |
|
| 124 |
+
video_clip = VideoFileClip(video_path).subclip(start_seconds, end_seconds)
|
|
|
|
| 125 |
|
| 126 |
+
video_clip.write_videofile(output_filepath, codec='libx264', audio_codec='aac')
|
| 127 |
+
video_clip.close()
|
|
|
|
| 128 |
|
| 129 |
+
return output_filepath, scene_info['first_frame']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
def process_video(video_url, description):
|
| 132 |
+
output_directory = "output"
|
| 133 |
+
os.makedirs(output_directory, exist_ok=True)
|
| 134 |
+
|
| 135 |
+
video_path = download_video(video_url)
|
| 136 |
+
scenes = find_scenes(video_path)
|
| 137 |
+
scene_frames = extract_frames(video_path, scenes)
|
| 138 |
+
description_phrases = [description] # Modify if multiple descriptions are needed
|
| 139 |
+
scene_categories = classify_and_categorize_scenes(scene_frames, description_phrases)
|
| 140 |
+
|
| 141 |
+
best_scene = max(scene_categories.items(), key=lambda x: x[1]['confidence'])[1]
|
| 142 |
+
clip_path, first_frame = save_clip(video_path, best_scene, output_directory, 0)
|
| 143 |
+
|
| 144 |
+
return clip_path
|
| 145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|