supersolar commited on
Commit
054c36d
·
verified ·
1 Parent(s): 49df7c6

Upload 3 files

Browse files
Files changed (3) hide show
  1. all_in_one.py +31 -14
  2. all_in_one_filespaths.py +100 -0
  3. split_videos.py +89 -0
all_in_one.py CHANGED
@@ -1,5 +1,23 @@
1
  # @title #设置提示词,获取坐标
2
  import subprocess
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import pickle
4
  import cv2
5
  import os
@@ -7,20 +25,19 @@ import re
7
  import pickle
8
  from moviepy.editor import VideoFileClip, ImageSequenceClip
9
  import subprocess
10
- out_dir = "/workspace/tem"
11
- os.makedirs(out_dir, exist_ok=True)
12
  def set_prompt_and_get_coordinates(output_video, texts=['men', 'the table']):
13
  if isinstance(texts, str):
14
  texts = texts.split(',') # Assuming prompts are separated by commas
15
  texts = [text.strip() for text in texts]
16
  print(texts)
17
  # 保存提示词到文件
18
- with open('/workspace/tem/texts.pkl', 'wb') as file:
19
  pickle.dump(texts, file)
20
- with open('/workspace/tem/output_video.pkl', 'wb') as file:
21
  pickle.dump(output_video, file)
22
  # 构建命令
23
- command = ['python', '/workspace/florence-sam-tencent/1.py']
24
 
25
  # 执行命令并捕获输出
26
  all_ok_bboxes = subprocess.run(command, capture_output=True, text=True)
@@ -28,18 +45,18 @@ def set_prompt_and_get_coordinates(output_video, texts=['men', 'the table']):
28
  return all_ok_bboxes
29
 
30
  # 示例调用
31
- output_video = '/workspace/transvnet/o_videos/2.mp4'
32
  texts="men, the table"
33
  result = set_prompt_and_get_coordinates(output_video,texts)
34
- print(result.stdout)
35
- #result
36
  # @title #sam2处理
37
 
38
 
39
  def run_sam2(output_video):
40
 
41
  # 定义脚本路径
42
- script_path = '/workspace/florence-sam-tencent/2.py'
43
 
44
  # 构建命令
45
  command = ['python3', script_path]
@@ -52,8 +69,7 @@ def run_sam2(output_video):
52
  # 示例调用
53
  #output_video = 'path/to/output_video.mp4'
54
  result = run_sam2(output_video)
55
- #print(result.stdout)
56
- #result
57
 
58
 
59
  def create_video_with_audio(image_folder, input_video_path):
@@ -94,7 +110,7 @@ def create_video_with_audio(image_folder, input_video_path):
94
 
95
  # 生成与输入视频同名的输出文件
96
  #output_video_path = os.path.join('/tmp/gradio/', os.path.basename(input_video_path))
97
- output_video_path = os.path.join('/workspace/tem/sam2_videos/', os.path.basename(input_video_path))
98
  # 确保输出目录存在
99
  os.makedirs(os.path.dirname(output_video_path), exist_ok=True)
100
 
@@ -104,9 +120,10 @@ def create_video_with_audio(image_folder, input_video_path):
104
  print(f"Video created successfully: {output_video_path}")
105
  return output_video_path
106
 
 
107
  # 示例调用
108
- image_folder = '/workspace/tem/output'
109
- with open('/workspace/tem/output_video.pkl', 'rb') as file:
110
  output_video = pickle.load(file)
111
  print(output_video)
112
  input_video_path = output_video
 
1
  # @title #设置提示词,获取坐标
2
  import subprocess
3
+ import subprocess
4
+
5
+ def uninstall_tensorflow():
6
+ try:
7
+ # 使用 subprocess.run 执行 pip uninstall 命令
8
+ result = subprocess.run(['pip', 'uninstall', '-y', 'tensorflow'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
9
+ print("卸载成功")
10
+ print("输出:", result.stdout.decode('utf-8'))
11
+ except subprocess.CalledProcessError as e:
12
+ print("卸载失败")
13
+ print("错误:", e.stderr.decode('utf-8'))
14
+
15
+ # 调用函数
16
+ uninstall_tensorflow()
17
+ import os
18
+
19
+ # 设置环境变量
20
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
21
  import pickle
22
  import cv2
23
  import os
 
25
  import pickle
26
  from moviepy.editor import VideoFileClip, ImageSequenceClip
27
  import subprocess
28
+
 
29
  def set_prompt_and_get_coordinates(output_video, texts=['men', 'the table']):
30
  if isinstance(texts, str):
31
  texts = texts.split(',') # Assuming prompts are separated by commas
32
  texts = [text.strip() for text in texts]
33
  print(texts)
34
  # 保存提示词到文件
35
+ with open('/workspace/florence-sam/texts.pkl', 'wb') as file:
36
  pickle.dump(texts, file)
37
+ with open('/workspace/florence-sam/output_video.pkl', 'wb') as file:
38
  pickle.dump(output_video, file)
39
  # 构建命令
40
+ command = ['python', '/workspace/florence-sam/1.py']
41
 
42
  # 执行命令并捕获输出
43
  all_ok_bboxes = subprocess.run(command, capture_output=True, text=True)
 
45
  return all_ok_bboxes
46
 
47
  # 示例调用
48
+ output_video = '/workspace/transvnet/o_videos/3.mp4'
49
  texts="men, the table"
50
  result = set_prompt_and_get_coordinates(output_video,texts)
51
+ print(result)
52
+
53
  # @title #sam2处理
54
 
55
 
56
  def run_sam2(output_video):
57
 
58
  # 定义脚本路径
59
+ script_path = '/workspace/florence-sam/2.py'
60
 
61
  # 构建命令
62
  command = ['python3', script_path]
 
69
  # 示例调用
70
  #output_video = 'path/to/output_video.mp4'
71
  result = run_sam2(output_video)
72
+ print(result)
 
73
 
74
 
75
  def create_video_with_audio(image_folder, input_video_path):
 
110
 
111
  # 生成与输入视频同名的输出文件
112
  #output_video_path = os.path.join('/tmp/gradio/', os.path.basename(input_video_path))
113
+ output_video_path = os.path.join('/workspace/sam2_videos', os.path.basename(input_video_path))
114
  # 确保输出目录存在
115
  os.makedirs(os.path.dirname(output_video_path), exist_ok=True)
116
 
 
120
  print(f"Video created successfully: {output_video_path}")
121
  return output_video_path
122
 
123
+
124
  # 示例调用
125
+ image_folder = '/workspace/output'
126
+ with open('/workspace/florence-sam/output_video.pkl', 'rb') as file:
127
  output_video = pickle.load(file)
128
  print(output_video)
129
  input_video_path = output_video
all_in_one_filespaths.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import pickle
4
+ import cv2
5
+ from moviepy.editor import VideoFileClip, ImageSequenceClip
6
+ import shutil
7
+
8
+ # 设置环境变量
9
+ os.environ['CUDA_VISIBLE_DEVICES'] = '0'
10
+
11
+ def uninstall_tensorflow():
12
+ try:
13
+ result = subprocess.run(['pip', 'uninstall', '-y', 'tensorflow'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
14
+ print("卸载成功")
15
+ print("输出:", result.stdout.decode('utf-8'))
16
+ except subprocess.CalledProcessError as e:
17
+ print("卸载失败")
18
+ print("错误:", e.stderr.decode('utf-8'))
19
+
20
+ # 调用函数
21
+ uninstall_tensorflow()
22
+
23
+ def set_prompt_and_get_coordinates(output_video, texts=['men', 'the table']):
24
+ if isinstance(texts, str):
25
+ texts = texts.split(',')
26
+ texts = [text.strip() for text in texts]
27
+ print(texts)
28
+ with open('/workspace/florence-sam/texts.pkl', 'wb') as file:
29
+ pickle.dump(texts, file)
30
+ with open('/workspace/florence-sam/output_video.pkl', 'wb') as file:
31
+ pickle.dump(output_video, file)
32
+ command = ['python', '/workspace/florence-sam/1.py']
33
+ all_ok_bboxes = subprocess.run(command, capture_output=True, text=True)
34
+ return all_ok_bboxes
35
+
36
+ def run_sam2(output_video):
37
+ script_path = '/workspace/florence-sam/2.py'
38
+ command = ['python3', script_path]
39
+ sam2_output = subprocess.run(command, capture_output=True, text=True)
40
+ return sam2_output
41
+
42
+ def create_video_with_audio(image_folder, input_video_path):
43
+ image_files = [f for f in os.listdir(image_folder) if f.endswith(('.png', '.jpg', '.jpeg'))]
44
+
45
+ def natural_sort_key(s, _nsre=re.compile('([0-9]+)')):
46
+ return [int(text) if text.isdigit() else text.lower() for text in re.split(_nsre, s)]
47
+
48
+ image_files.sort(key=natural_sort_key)
49
+
50
+ if image_files:
51
+ first_image = cv2.imread(os.path.join(image_folder, image_files[0]))
52
+ height, width, layers = first_image.shape
53
+ else:
54
+ raise ValueError("No valid images found in the folder after skipping the first one.")
55
+
56
+ cap = cv2.VideoCapture(input_video_path)
57
+ fps = cap.get(cv2.CAP_PROP_FPS)
58
+ cap.release()
59
+
60
+ image_paths = [os.path.join(image_folder, img) for img in image_files]
61
+ clip = ImageSequenceClip(image_paths, fps=fps)
62
+
63
+ audio_clip = VideoFileClip(input_video_path).audio
64
+ final_clip = clip.set_audio(audio_clip)
65
+
66
+ output_video_path = os.path.join('/workspace/sam2_videos', os.path.basename(input_video_path))
67
+ os.makedirs(os.path.dirname(output_video_path), exist_ok=True)
68
+
69
+ final_clip.write_videofile(output_video_path, codec='libx264')
70
+
71
+ print(f"Video created successfully: {output_video_path}")
72
+ return output_video_path
73
+
74
+ def process_videos(source_dir, target_dir, texts="men, the table"):
75
+ os.makedirs(target_dir, exist_ok=True)
76
+
77
+ for video_file in os.listdir(source_dir):
78
+ if video_file.endswith(('.mp4', '.avi', '.mov')):
79
+ video_path = os.path.join(source_dir, video_file)
80
+ print(f"Processing video: {video_path}")
81
+
82
+ result = set_prompt_and_get_coordinates(video_path, texts)
83
+ print(result)
84
+
85
+ result = run_sam2(video_path)
86
+ print(result)
87
+
88
+ with open('/workspace/florence-sam/output_video.pkl', 'rb') as file:
89
+ output_video = pickle.load(file)
90
+
91
+ create_video_with_audio('/workspace/output', output_video)
92
+
93
+ # 移动原视频到目标目录
94
+ shutil.move(video_path, os.path.join(target_dir, video_file))
95
+
96
+ if __name__ == "__main__":
97
+ source_dir = '/workspace/transvnet/o_videos'
98
+ target_dir = '/workspace/alreayvideos'
99
+ texts = "men, the table"
100
+ process_videos(source_dir, target_dir, texts)
split_videos.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from moviepy.editor import VideoFileClip, concatenate_audioclips
3
+ import os
4
+
5
+ # 设置环境变量
6
+ os.environ['CUDA_VISIBLE_DEVICES'] = '1'
7
+ import subprocess
8
+
9
+ def install_tensorflow():
10
+ try:
11
+ # 使用 subprocess.run 执行 pip install 命令
12
+ result = subprocess.run(['pip', 'install', 'tensorflow'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
13
+ print("安装成功")
14
+ print("输出:", result.stdout.decode('utf-8'))
15
+ except subprocess.CalledProcessError as e:
16
+ print("安装失败")
17
+ print("错误:", e.stderr.decode('utf-8'))
18
+
19
+ # 调用函数
20
+ install_tensorflow()
21
+ import shutil
22
+ import os
23
+ import sys
24
+ from moviepy.editor import *
25
+ from transnetv2 import TransNetV2
26
+ import shutil
27
+ import pickle
28
+ import json
29
+ import pickle
30
+ os.chdir("/workspace/transvnet")
31
+ sys.path.append('/workspace/transvnet')
32
+
33
+ import os
34
+ from moviepy.editor import VideoFileClip
35
+ import pickle
36
+ import time
37
+ os.makedirs('/workspace/transvnet/o_videos', exist_ok=True)
38
+ # @title 分割剪辑视频的代码
39
+
40
+ def check_scenes(video_name):
41
+ scenes_dir = '/workspace/transvnet/scenes'
42
+ if not os.path.exists(scenes_dir):
43
+ os.makedirs(scenes_dir)
44
+ print("创建目录 %s 成功" % scenes_dir)
45
+ else:
46
+ print("目录 %s 已存在" % scenes_dir)
47
+ if os.path.exists(os.path.join(scenes_dir, video_name)):
48
+ print("文件scenes %s 已存在直接使用" % video_name)
49
+ with open(os.path.join(scenes_dir, video_name), 'rb') as f:
50
+ scenes = pickle.load(f)
51
+ return scenes
52
+ else:
53
+ return False
54
+
55
+ def change_video_speed(video_path, output_folder):
56
+ video_name = os.path.basename(video_path)
57
+ video_folder = os.path.dirname(video_path)
58
+ scenes = check_scenes(video_name)
59
+
60
+ if scenes is not False:
61
+ print("场景检测之前已完成")
62
+ else:
63
+ print("场景检测开始")
64
+ model = TransNetV2()
65
+ video_frames, single_frame_predictions, all_frame_predictions = model.predict_video_2(video_path)
66
+ scenes = model.predictions_to_scenes(single_frame_predictions)
67
+ scenes_dir = '/workspace/transvnet/scenes'
68
+ with open(os.path.join(scenes_dir, video_name), 'wb') as f:
69
+ pickle.dump(scenes, f)
70
+
71
+ print(scenes)
72
+ video_clip2 = VideoFileClip(video_path)
73
+ split_time = scenes
74
+ n = 1
75
+ for i in split_time:
76
+ #time.sleep(1)
77
+ start = i[0]
78
+ end = i[1]
79
+ start_time = start / video_clip2.fps
80
+ end_time = end / video_clip2.fps
81
+ segment_clip = video_clip2.subclip(start_time, end_time)
82
+ #output_video_name = f"{os.path.splitext(video_name)[0]}_{n}{os.path.splitext(video_name)[1]}"
83
+ output_video_name = f"{n}{os.path.splitext(video_name)[1]}"
84
+ output_video_path = os.path.join(output_folder, output_video_name)
85
+ #segment_clip.write_videofile(output_video_path, fps=video_clip2.fps)
86
+ segment_clip.write_videofile(output_video_path, fps=int(video_clip2.fps), codec='libx264', audio_codec='aac')
87
+ n += 1
88
+
89
+ change_video_speed('/workspace/马龙VS林诗栋,仿佛看到了2017年的大战.mp4', '/workspace/transvnet/o_videos')