-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathss.py
186 lines (164 loc) · 7.21 KB
/
ss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import os
import sys
import shutil
import subprocess
import platform
import random
import requests
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
def handle_error(message, exception):
print(f"\033[31m{message}: {exception}\033[0m")
sys.exit(1)
def check_program_installed(program):
return shutil.which(program) is not None
def download_file(url, output_path):
try:
print(f"正在下载 {url}...")
urllib.request.urlretrieve(url, output_path)
print("下载完成")
except Exception as e:
handle_error("下载失败", e)
def get_video_duration(video_file):
try:
result = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", video_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
return float(result.stdout)
except Exception as e:
handle_error("无法获取视频时长", e)
def generate_random_timestamps(duration, num_screenshots):
if duration > 30 * 60:
start_time = 300
end_time = max(start_time, duration - 900)
else:
start_time = 0
end_time = duration
return [f"{int(rand_time // 3600):02}:{int((rand_time % 3600) // 60):02}:{int(rand_time % 60):02}.{int((rand_time % 1) * 1000):03}"
for rand_time in [random.uniform(start_time, end_time) for _ in range(num_screenshots)]]
def get_file_size(file_path):
return os.path.getsize(file_path) / 1024
def clear_directory(directory):
if os.path.exists(directory):
shutil.rmtree(directory)
os.makedirs(directory)
def capture_screenshots(video_file, timestamps, output_dir):
""" 使用 ffmpeg 截取截图。 """
for i, timestamp in enumerate(timestamps, 1):
output_file = os.path.join(output_dir, f"screenshot_{i:03}.png")
result = subprocess.run(
["ffmpeg", "-ss", timestamp, "-i", video_file,
"-frames:v", "1", "-qscale:v", "0", "-vsync", "vfr", output_file],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
if result.returncode == 0:
file_size = get_file_size(output_file)
print(f"\033[1;32m生成无损截图:\033[0m {output_file},\033[1;32m时间戳:\033[0m {timestamp},\033[1;32m图片大小:\033[0m {file_size:.2f} KB")
else:
print(f"\033[31m生成截图失败: {result.stderr.decode().strip()}\033[0m")
def process_images_and_upload(output_dir):
url = "https://api.pixhost.to/images"
headers = {}
image_urls = []
bbcode_list = []
for file_name in os.listdir(output_dir):
file_path = os.path.join(output_dir, file_name)
if os.path.isfile(file_path):
with open(file_path, 'rb') as image_file:
files = {'img': (file_name, image_file)}
data = {'content_type': '0', 'max_th_size': '420'}
try:
response = requests.post(url, data=data, files=files, headers=headers)
if response.status_code == 200:
response_data = response.json()
# 获取 th_url
th_url = response_data.get('th_url', '')
if th_url:
# 提取服务器编号
server_number = th_url.split('.')[0].split('t')[-1]
# 构建直接链接
direct_image_url = th_url.replace(f't{server_number}', f'img{server_number}').replace('thumbs', 'images')
bbcode = f"[img]{direct_image_url}[/img]"
image_urls.append(direct_image_url)
bbcode_list.append(bbcode)
else:
print(f"\033[31m图片 {file_name} 上传失败,HTTP状态码: {response.status_code}\033[0m")
except Exception as e:
print(f"\033[31m上传图片 {file_name} 时出错: {e}\033[0m")
if image_urls:
print("\n\033[1;32m直接链接\033[0m:")
for url in image_urls:
print(url)
if bbcode_list:
print("\n\033[1;32mBBCode\033[0m:")
for bbcode in bbcode_list:
print(bbcode)
def install_ffmpeg():
system = platform.system().lower()
try:
if system == "linux":
distro = platform.linux_distribution()[0].lower()
if "ubuntu" in distro or "debian" in distro:
subprocess.run(["sudo", "apt", "update"], check=True)
subprocess.run(["sudo", "apt", "install", "-y", "ffmpeg"], check=True)
elif "centos" in distro:
subprocess.run(["sudo", "yum", "install", "-y", "epel-release"], check=True)
subprocess.run(["sudo", "yum", "install", "-y", "ffmpeg"], check=True)
else:
print("\033[31m暂不支持此 Linux 发行版的自动安装。\033[0m")
else:
print("\033[31m自动安装仅支持 Linux 系统。\033[0m")
except Exception as e:
handle_error("安装 ffmpeg 时出错", e)
print("\033[1;32mffmpeg 安装完成。\033[0m")
def display_menu():
print("\n\033[1;36m欢迎使用盒子截图脚本\033[0m")
print("----------------------")
print("\033[1;36m1.\033[0m 无损截图")
print("\033[1;36m2.\033[0m 安装 ffmpeg")
print("\033[1;36m0.\033[0m 退出")
def main_menu():
while True:
display_menu()
choice = input("请选择功能: ").strip()
if choice == "1":
lossless_screenshot()
elif choice == "2":
install_ffmpeg()
elif choice == "0":
print("退出程序。")
break
else:
print("\033[31m无效选项,请重试。\033[0m")
def lossless_screenshot():
if not check_program_installed('ffmpeg'):
print("\033[31m错误: ffmpeg 未安装,请先安装。\033[0m")
return
while True:
user_input = input("请输入'视频文件路径 截图数量'。如/root/1.mp4 5。输入0返回菜单: ").strip()
if user_input == "0":
break
try:
video_path, screenshot_count = user_input.rsplit(" ", 1)
screenshot_count = int(screenshot_count)
if screenshot_count <= 0:
print("\033[31m截图数量必须为正整数。\033[0m")
continue
except ValueError:
print("\033[31m输入格式错误,请重新输入。\033[0m")
continue
if not os.path.exists(video_path):
print("\033[31m视频文件路径无效,请重新输入。\033[0m")
continue
output_dir = "screenshots"
clear_directory(output_dir)
duration = get_video_duration(video_path)
timestamps = generate_random_timestamps(duration, screenshot_count)
capture_screenshots(video_path, timestamps, output_dir)
process_images_and_upload(output_dir)
if __name__ == "__main__":
main_menu()